From 238e754cc57dc395008b4e2e034fe2951f1db412 Mon Sep 17 00:00:00 2001 From: Fernando Santoro <44955673+santorofer@users.noreply.github.com> Date: Mon, 12 Apr 2021 22:31:21 -0400 Subject: [PATCH 01/27] Feature: Changes to acq2106 435st.py so that a trigger source can be manually chosen. (#2268) * Fix: add selection of trigger source * Improved a comment/explanation * Change resampling init() parameter to be a False/True boolean --- pydevices/HtsDevices/acq2106_435sc.py | 4 +-- pydevices/HtsDevices/acq2106_435st.py | 37 +++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/pydevices/HtsDevices/acq2106_435sc.py b/pydevices/HtsDevices/acq2106_435sc.py index a58fe30853..98dde1d938 100644 --- a/pydevices/HtsDevices/acq2106_435sc.py +++ b/pydevices/HtsDevices/acq2106_435sc.py @@ -92,9 +92,9 @@ def init(self): self.slots[card].SC32_GAIN_COMMIT = 1 print("GAINs Committed for site {}".format(card)) # Here, the argument to the init of the superclass: - # - init(1) => use resampling function: + # - init(True) => use resampling function: # makeSegmentResampled(begin, end, dim, b, resampled, res_factor) - super(_ACQ2106_435SC, self).init(1) + super(_ACQ2106_435SC, self).init(resampling = True) INIT=init diff --git a/pydevices/HtsDevices/acq2106_435st.py b/pydevices/HtsDevices/acq2106_435st.py index 63c8f8671c..6e225e0f45 100755 --- a/pydevices/HtsDevices/acq2106_435st.py +++ b/pydevices/HtsDevices/acq2106_435st.py @@ -178,6 +178,14 @@ class _ACQ2106_435ST(MDSplus.Device): 'valueExpr': "Action(Dispatch('CAMAC_SERVER','STORE',50,None),Method(None,'STOP',head))", 'options': ('no_write_shot',) }, + + #Trigger sources + { + 'path':':TRIG_SRC', + 'type':'text', + 'value': 'NONE', + 'options':('no_write_shot',) + }, ] data_socket = -1 @@ -381,7 +389,7 @@ def run(self): else: self.full_buffers.put(buf) - def init(self, resampling=0): + def init(self, resampling = False): import acq400_hapi MIN_FREQUENCY = 10000 @@ -391,6 +399,12 @@ def init(self, resampling=0): if self.ext_clock.length > 0: raise Exception('External Clock is not supported') + # Initializing Sources to NONE: + # D0 signal: + uut.s0.SIG_SRC_TRG_0 = 'NONE' + # D1 signal: + uut.s0.SIG_SRC_TRG_1 = 'NONE' + freq = int(self.freq.data()) # D-Tacq Recommendation: the minimum sample rate is 10kHz. if freq < MIN_FREQUENCY: @@ -406,7 +420,7 @@ def init(self, resampling=0): trg = 'soft' else: role = mode.split(":")[0] - trg = mode.split(":")[1] + trg = mode.split(":")[1] print("Role is {} and {} trigger".format(role, trg)) @@ -423,6 +437,25 @@ def init(self, resampling=0): # modifiers [CLKDIV=div] uut.s0.sync_role = '%s %s TRG:DX=%s' % (role, self.freq.data(), trg_dx) + # The following allows for any source to be chosen, among other things the WR source. + # Signal highway d0: + srcs_0 = ['EXT', 'HDMI', 'HOSTB', 'GPG0', 'DSP0', 'nc', 'WRTT0', 'NONE'] + # Signal highway d1: + srcs_1 = ['STRIG', 'HOSTA', 'HDMI_GPIO', 'GPG1', 'DSP1', 'FP_SYNC', 'WRTT1', 'NONE'] + + if trg_dx == 'd0': + if str(self.trig_src.data()) in srcs_0: + uut.s0.SIG_SRC_TRG_0 = str(self.trig_src.data()) + else: + sys.exit("TRIG_SRC should be one of {}".format(srcs_0)) + + elif trg_dx == 'd1': + if str(self.trig_src.data()) in srcs_1: + uut.s0.SIG_SRC_TRG_1 = str(self.trig_src.data()) + else: + sys.exit("TRIG_SRC should be one of {}".format(srcs_1)) + + # Fetching all calibration information from every channel. uut.fetch_all_calibration() coeffs = uut.cal_eslo[1:] From 8b4cdee07a71172b137a1f47aec82c8dadb2ec41 Mon Sep 17 00:00:00 2001 From: Fernando Santoro <44955673+santorofer@users.noreply.github.com> Date: Wed, 14 Apr 2021 14:32:09 -0400 Subject: [PATCH 02/27] Fix: Rework acq435 `TRIG_SRC` (#2284) Remove new `TRIG_SRC` node Move functionality into existing `TRIG_MODE` node `TRIG_MODE` can now be * hard, soft * master:hard, solo:soft, etc * master:ext, solo:wrtt0, fpmaster:fp_sync, etc. Refactor .format() to % format Move `getUUT()` to parent 435st class (overridden in 435sc) Removed legacy `trig_types` Moved constants to class scope * MIN_FREQUENCY * TRIG_SRC_OPTS_0 * TRIG_SRC_OPTS_1 Removed initializing trigger sources to 'NONE' Should be set automatically by sync_role Wrap debug statements in `if self.debug` Co-authored-by: Stephen Lane-Walsh --- pydevices/HtsDevices/acq2106_435sc.py | 35 ++++--- pydevices/HtsDevices/acq2106_435st.py | 137 ++++++++++++++------------ 2 files changed, 94 insertions(+), 78 deletions(-) diff --git a/pydevices/HtsDevices/acq2106_435sc.py b/pydevices/HtsDevices/acq2106_435sc.py index 98dde1d938..5bf5669a04 100644 --- a/pydevices/HtsDevices/acq2106_435sc.py +++ b/pydevices/HtsDevices/acq2106_435sc.py @@ -72,29 +72,37 @@ class _ACQ2106_435SC(acq2106_435st._ACQ2106_435ST): ] def init(self): - uut = self.getUUT() self.slots = super(_ACQ2106_435SC, self).getSlots() for card in self.slots: if self.is_global.data() == 1: # Global controls for GAINS and OFFSETS self.slots[card].SC32_OFFSET_ALL = self.def_offset.data() - print("Site {} OFFSET ALL {}".format(card, self.def_offset.data())) + + if self.debug: + print("Site %s OFFSET ALL %d" % (card, int(self.def_offset.data()))) self.slots[card].SC32_G1_ALL = self.def_gain1.data() - print("Site {} GAIN 1 ALL {}".format(card, self.def_gain1.data())) + + if self.debug: + print("Site %s GAIN 1 ALL %d" % (card, int(self.def_gain1.data()))) self.slots[card].SC32_G2_ALL = self.def_gain2.data() - print("Site {} GAIN 2 ALL {}".format(card, self.def_gain2.data())) + + if self.debug: + print("Site %s GAIN 2 ALL %d" % (card, int(self.def_gain2.data()))) else: self.setGainsOffsets(card) self.slots[card].SC32_GAIN_COMMIT = 1 - print("GAINs Committed for site {}".format(card)) + + if self.debug: + print("GAINs Committed for site %s" % (card,)) + # Here, the argument to the init of the superclass: # - init(True) => use resampling function: # makeSegmentResampled(begin, end, dim, b, resampled, res_factor) - super(_ACQ2106_435SC, self).init(resampling = True) + super(_ACQ2106_435SC, self).init(resampling=True) INIT=init @@ -104,7 +112,6 @@ def getUUT(self): return uut def setGainsOffsets(self, card): - uut = self.getUUT() for ic in range(1,32+1): if card == 1: setattr(self.slots[card], 'SC32_OFFSET_%2.2d' % (ic,), getattr(self, 'INPUT_%3.3d:SC_OFFSET' % (ic,)).data()) @@ -141,46 +148,46 @@ def assemble(cls): 'options': ('no_write_model', 'write_once',) }, { - 'path': ':INPUT_%3.3d:DECIMATE'%(i+1,), + 'path': ':INPUT_%3.3d:DECIMATE' % (i+1,), 'type':'NUMERIC', 'valueExpr':'head.def_dcim', 'options':('no_write_shot',) }, { - 'path': ':INPUT_%3.3d:COEFFICIENT'%(i+1,), + 'path': ':INPUT_%3.3d:COEFFICIENT' % (i+1,), 'type':'NUMERIC', 'options':('no_write_model', 'write_once',) }, { - 'path': ':INPUT_%3.3d:OFFSET'%(i+1,), + 'path': ':INPUT_%3.3d:OFFSET' % (i+1,), 'type':'NUMERIC', 'options':('no_write_model', 'write_once',) }, { # Local (per channel) SC gains - 'path': ':INPUT_%3.3d:SC_GAIN1'%(i+1,), + 'path': ':INPUT_%3.3d:SC_GAIN1' % (i+1,), 'type':'NUMERIC', 'valueExpr':'head.def_gain1', 'options':('no_write_shot',) }, { # Local (per channel) SC gains - 'path': ':INPUT_%3.3d:SC_GAIN2'%(i+1,), + 'path': ':INPUT_%3.3d:SC_GAIN2' % (i+1,), 'type':'NUMERIC', 'valueExpr':'head.def_gain2', 'options':('no_write_shot',) }, { # Local (per channel) SC offsets - 'path': ':INPUT_%3.3d:SC_OFFSET'%(i+1,), + 'path': ':INPUT_%3.3d:SC_OFFSET' % (i+1,), 'type':'NUMERIC', 'valueExpr':'head.def_offset', 'options':('no_write_shot',) }, { # Conditioned signal goes here: - 'path': ':INPUT_%3.3d:SC_INPUT'%(i+1,), + 'path': ':INPUT_%3.3d:SC_INPUT' % (i+1,), 'type': 'SIGNAL', 'valueExpr': 'ADD(MULTIPLY(head.INPUT_%3.3d, MULTIPLY(head.INPUT_%3.3d.SC_GAIN1, head.INPUT_%3.3d.SC_GAIN2)), head.INPUT_%3.3d.SC_OFFSET)' diff --git a/pydevices/HtsDevices/acq2106_435st.py b/pydevices/HtsDevices/acq2106_435st.py index 6e225e0f45..3ab868bde7 100755 --- a/pydevices/HtsDevices/acq2106_435st.py +++ b/pydevices/HtsDevices/acq2106_435st.py @@ -178,20 +178,10 @@ class _ACQ2106_435ST(MDSplus.Device): 'valueExpr': "Action(Dispatch('CAMAC_SERVER','STORE',50,None),Method(None,'STOP',head))", 'options': ('no_write_shot',) }, - - #Trigger sources - { - 'path':':TRIG_SRC', - 'type':'text', - 'value': 'NONE', - 'options':('no_write_shot',) - }, ] data_socket = -1 - trig_types = ['hard', 'soft', 'automatic'] - class MDSWorker(threading.Thread): NUM_BUFFERS = 20 @@ -222,10 +212,8 @@ def __init__(self, dev): self.device_thread = self.DeviceWorker(self) def run(self): - import acq400_hapi import ast import re - uut = acq400_hapi.Acq400(self.dev.node.data(), monitor=False) def lcm(a, b): from fractions import gcd @@ -389,29 +377,43 @@ def run(self): else: self.full_buffers.put(buf) - def init(self, resampling = False): - import acq400_hapi - MIN_FREQUENCY = 10000 + # The minimum frequency we can operate at + MIN_FREQUENCY = 10000 - uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + # These are partial lists of the options we support. + # For a complete list, consult D-Tacq + + # Trigger Source Options for Signal Highway d0 + TRIG_SRC_OPTS_0 = [ + 'ext', # External Trigger + 'hdmi', # HDMI Trigger + 'gpg0', # Gateway Pulse Generator Trigger + 'wrtt0' # White Rabbit Trigger + ] + + # Trigger Source Options for Signal Highway d1 + TRIG_SRC_OPTS_1 = [ + 'strig', # Software Trigger + 'hdmi_gpio', # HDMI General Purpose I/O Trigger + 'gpg1', # Gateway Pulse Generator Trigger + 'fp_sync', # Front Panel SYNC + 'wrtt1' # White Rabbit Trigger + ] + + def init(self, resampling=False): + uut = self.getUUT() uut.s0.set_knob('set_abort', '1') if self.ext_clock.length > 0: raise Exception('External Clock is not supported') - # Initializing Sources to NONE: - # D0 signal: - uut.s0.SIG_SRC_TRG_0 = 'NONE' - # D1 signal: - uut.s0.SIG_SRC_TRG_1 = 'NONE' - freq = int(self.freq.data()) # D-Tacq Recommendation: the minimum sample rate is 10kHz. - if freq < MIN_FREQUENCY: + if freq < self.MIN_FREQUENCY: raise MDSplus.DevBAD_PARAMETER( "Sample rate should be greater or equal than 10kHz") - mode = self.trig_mode.data() + mode = str(self.trig_mode.data()).lower() if mode == 'hard': role = 'master' trg = 'hard' @@ -422,14 +424,27 @@ def init(self, resampling = False): role = mode.split(":")[0] trg = mode.split(":")[1] - print("Role is {} and {} trigger".format(role, trg)) + if self.debug: + print("Role is %s and %s trigger" % (role, trg)) + + + src_trg_0 = None + src_trg_1 = None if trg == 'hard': trg_dx = 'd0' - elif trg == 'automatic': + src_trg_0 = 'EXT' # External Trigger + elif trg == 'soft' or trg == 'automatic': trg_dx = 'd1' - elif trg == 'soft': + src_trg_1 = 'STRIG' # Soft Trigger + elif trg in self.TRIG_SRC_OPTS_0: + trg_dx = 'd0' + src_trg_0 = trg + elif trg in self.TRIG_SRC_OPTS_1: trg_dx = 'd1' + src_trg_1 = trg + elif trg != 'none': + raise MDSplus.DevBAD_PARAMETER("TRIG_MODE does not contain a valid trigger source") # USAGE sync_role {fpmaster|rpmaster|master|slave|solo} [CLKHZ] [FIN] # modifiers [CLK|TRG:SENSE=falling|rising] [CLK|TRG:DX=d0|d1] @@ -437,24 +452,13 @@ def init(self, resampling = False): # modifiers [CLKDIV=div] uut.s0.sync_role = '%s %s TRG:DX=%s' % (role, self.freq.data(), trg_dx) - # The following allows for any source to be chosen, among other things the WR source. - # Signal highway d0: - srcs_0 = ['EXT', 'HDMI', 'HOSTB', 'GPG0', 'DSP0', 'nc', 'WRTT0', 'NONE'] - # Signal highway d1: - srcs_1 = ['STRIG', 'HOSTA', 'HDMI_GPIO', 'GPG1', 'DSP1', 'FP_SYNC', 'WRTT1', 'NONE'] - - if trg_dx == 'd0': - if str(self.trig_src.data()) in srcs_0: - uut.s0.SIG_SRC_TRG_0 = str(self.trig_src.data()) - else: - sys.exit("TRIG_SRC should be one of {}".format(srcs_0)) - - elif trg_dx == 'd1': - if str(self.trig_src.data()) in srcs_1: - uut.s0.SIG_SRC_TRG_1 = str(self.trig_src.data()) - else: - sys.exit("TRIG_SRC should be one of {}".format(srcs_1)) + # snyc_role will set a default trigger source, we need to override it to the selected trigger source + # These must be uppercase + if src_trg_0: + uut.s0.SIG_SRC_TRG_0 = src_trg_0.upper() + if src_trg_1: + uut.s0.SIG_SRC_TRG_1 = src_trg_1.upper() # Fetching all calibration information from every channel. uut.fetch_all_calibration() @@ -473,26 +477,27 @@ def init(self, resampling = False): # Hardware decimation: if self.debug: - print("Hardware Filter (NACC) from tree node is {}".format( + print("Hardware Filter (NACC) from tree node is %d" % ( int(self.hw_filter.data()))) # Hardware Filter: Accumulate/Decimate filter. Accumulate nacc_samp samples, then output one value. nacc_samp = int(self.hw_filter.data()) - print("Number of sites in use {}".format(self.sites)) + + if self.debug: + print("Number of sites in use %d" % (self.sites,)) # Get the slots (aka sites, or cards) that are physically active in the chassis of the ACQ self.slots = self.getSlots() - for card in self.slots: - if 1 <= nacc_samp <= 32: + if nacc_samp >= 1 and nacc_samp <= 32: + for card in self.slots: self.slots[card].nacc = ('%d' % nacc_samp).strip() - else: - print( - "WARNING: Hardware Filter samples must be in the range [0,32]. 0 => Disabled == 1") - self.slots[card].nacc = '1' + else: + print("WARNING: Hardware Filter samples must be in the range [0,32]. 0 => Disabled == 1") + self.slots[card].nacc = '1' self.running.on = True - # If resampling=1, then resampling is used during streaming: + # If resampling == 1, then resampling is used during streaming: self.resampling = resampling thread = self.MDSWorker(self) @@ -500,24 +505,24 @@ def init(self, resampling = False): INIT = init def getSlots(self): - import acq400_hapi - uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + uut = self.getUUT() + # Ask UUT what are the sites that are actually being populatee with a 435ELF slot_list = {} - for (site, module) in sorted(uut.modules.items()): + for (site, _) in sorted(uut.modules.items()): site_number = int(site) if site_number == 1: - slot_list[site_number]=uut.s1 + slot_list[site_number] = uut.s1 elif site_number == 2: - slot_list[site_number]=uut.s2 + slot_list[site_number] = uut.s2 elif site_number == 3: - slot_list[site_number]=uut.s3 + slot_list[site_number] = uut.s3 elif site_number == 4: - slot_list[site_number]=uut.s4 + slot_list[site_number] = uut.s4 elif site_number == 5: - slot_list[site_number]=uut.s5 + slot_list[site_number] = uut.s5 elif site_number == 6: - slot_list[site_number]=uut.s6 + slot_list[site_number] = uut.s6 return slot_list def stop(self): @@ -525,11 +530,15 @@ def stop(self): STOP = stop def trig(self): - import acq400_hapi - uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + uut = self.getUUT() uut.s0.set_knob('soft_trigger', '1') TRIG = trig + def getUUT(self): + import acq400_hapi + uut = acq400_hapi.Acq400(self.node.data(), monitor=False, has_wr=True) + return uut + def setChanScale(self, num): chan = self.__getattr__('INPUT_%3.3d' % num) chan.setSegmentScale(MDSplus.ADD(MDSplus.MULTIPLY( From 2a9a97a60baf3ad584c0dc97c7f133aab70a4362 Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Tue, 20 Apr 2021 15:19:18 +0200 Subject: [PATCH 03/27] Fix:remove useless time consuming opoeration in MDSUdpEvent (#2282) * Fix:remove useless time consuming opoeration in MDSUdpEvent * Feature:allow assigning core mask to thread listening to events Extended MDS Event API with an additional MdsEventAstMask routine. MdsEventAstMask behaves exactly as MdsEventAst but ensures that the created thread is assigned to a core as specified by the core mask. In Event cpp interface a new Event constructor has been added to handle the additional mask argument. * MOVE include * MOVE include * MOVE include * Check if CPU_SET defined * add attribute unused to mask Co-authored-by: mdsplus --- include/mdsobjects.h | 8 +++++- include/mdsshr.h | 3 ++ mdsobjects/cpp/mdseventobjects.cpp | 9 ++++-- mdsshr/MdsEvents.c | 20 +++++++++++++ mdsshr/UdpEvents.c | 46 +++++++++++++++++++++++++----- mdsshr/mdsshrp.h | 3 ++ 6 files changed, 79 insertions(+), 10 deletions(-) diff --git a/include/mdsobjects.h b/include/mdsobjects.h index 76b83d8a9d..be024ece7c 100644 --- a/include/mdsobjects.h +++ b/include/mdsobjects.h @@ -3974,6 +3974,7 @@ class EXPORT Tree { class EXPORT Event { public: Event(const char *name); + Event(const char *name, unsigned int cpuMask); virtual ~Event(); @@ -4025,10 +4026,10 @@ class EXPORT Event { Event() {} Event(const Event &) {} friend void eventAst(void *arg, int len, char *buf); - std::string eventName; std::string eventBuf; int eventId; + unsigned int cpuMask; int64_t eventTime; ConditionVar condition; }; @@ -4200,6 +4201,11 @@ class EXPORT EventStream : public Event { names.clear(); name = streamName; } + EventStream(const char *streamName, unsigned int cpuMask) : Event(streamName, cpuMask) { + listeners.clear(); + names.clear(); + name = streamName; + } static void send(int shot, const char *name, bool isAbsTime, int nTimes, void *times, int nDims, int *dims, float *samples); static void send(int shot, const char *name, float time, float sample); diff --git a/include/mdsshr.h b/include/mdsshr.h index 89e6cc85d7..886cefc3c3 100644 --- a/include/mdsshr.h +++ b/include/mdsshr.h @@ -113,6 +113,9 @@ extern int MDSEvent(const char *eventName, int num_bytes, char *data); extern int MDSEventAst(const char *eventName, void (*astadr)(void *, int, char *), void *astprm, int *eventid); +extern int MDSEventAstMask(const char *eventName, + void (*astadr)(void *, int, char *), void *astprm, + int *eventid, unsigned int cpuMask); extern int MDSEventCan(const int eventid); extern int MDSWfevent(const char *const evname, const int buflen, char *const data, int *const datlen); diff --git a/mdsobjects/cpp/mdseventobjects.cpp b/mdsobjects/cpp/mdseventobjects.cpp index 2bec1ff61a..20571d93ba 100644 --- a/mdsobjects/cpp/mdseventobjects.cpp +++ b/mdsobjects/cpp/mdseventobjects.cpp @@ -44,6 +44,8 @@ extern "C" { int64_t convertAsciiToTime(const char *ascTime); int MDSEventAst(const char *eventNameIn, void (*astadr)(void *, int, char *), void *astprm, int *eventid); +int MDSEventAstMask(const char *eventNameIn, void (*astadr)(void *, int, char *), + void *astprm, int *eventid, unsigned int cpuMask); int MDSEventCan(int id); int MDSEvent(const char *eventNameIn, int bufLen, char *buf); void *MdsEventAddListener(char *name, @@ -91,7 +93,7 @@ void Event::connectToEvents() { InitializeCriticalSection(&critSect); } #endif - if (!MDSEventAst(this->getName(), MDSplus::eventAst, this, &eventId)) + if (!MDSEventAstMask(this->getName(), MDSplus::eventAst, this, &eventId, cpuMask)) throw MdsException("failed to connect to event listener"); } @@ -102,8 +104,11 @@ void Event::disconnectFromEvents() { void Event::run() {} +Event::Event(const char *name, unsigned int cpuMask) + : eventName(name), eventId(-1), cpuMask(cpuMask), eventTime(convertAsciiToTime("now")){} + Event::Event(const char *name) - : eventName(name), eventId(-1), eventTime(convertAsciiToTime("now")) {} + : eventName(name), eventId(-1), cpuMask(0), eventTime(convertAsciiToTime("now")){} Event::~Event() { stop(); } diff --git a/mdsshr/MdsEvents.c b/mdsshr/MdsEvents.c index 1aa5cad3c3..bf56bbd145 100644 --- a/mdsshr/MdsEvents.c +++ b/mdsshr/MdsEvents.c @@ -889,6 +889,26 @@ EXPORT int MDSEventAst(const char *const eventNameIn, return status; } + +EXPORT int MDSEventAstMask(const char *const eventNameIn, + void (*const astadr)(void *, int, char *), + void *const astprm, int *const eventid, unsigned int cpuMask) { + char *eventName = malloc(strlen(eventNameIn) + 1); + unsigned int i, j; + int status; + for (i = 0, j = 0; i < strlen(eventNameIn); i++) { + if (eventNameIn[i] != 32) + eventName[j++] = (char)toupper(eventNameIn[i]); + } + eventName[j] = 0; + if (getenv("mds_event_server")) + status = RemoteMDSEventAst(eventName, astadr, astprm, eventid); + else + status = MDSUdpEventAstMask(eventName, astadr, astprm, eventid, cpuMask); + free(eventName); + return status; +} + EXPORT int MDSEvent(const char *const eventNameIn, const int bufLen, char *const buf) { char *eventName = alloca(strlen(eventNameIn) + 1); diff --git a/mdsshr/UdpEvents.c b/mdsshr/UdpEvents.c index b02f77ae3d..c7dcf1f22f 100644 --- a/mdsshr/UdpEvents.c +++ b/mdsshr/UdpEvents.c @@ -22,6 +22,10 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#define _GNU_SOURCE +#include +#include + #include #include @@ -35,6 +39,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include + extern int UdpEventGetPort(unsigned short *port); extern int UdpEventGetAddress(char **addr_format, unsigned char *arange); extern int UdpEventGetTtl(char *ttl); @@ -232,10 +237,11 @@ static void getMulticastAddr(char const *eventName, char *retIp) { free(addr_format); } -int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), - void *astprm, int *eventid) { +int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char *), + void *astprm, int *eventid, __attribute__((unused)) unsigned int cpuMask) { int check_bind_in_directive; struct sockaddr_in serverAddr; + #ifdef _WIN32 char flag = 1; #else @@ -320,11 +326,36 @@ int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), perror("pthread_create"); return 0; } +#ifdef CPU_SET + if(cpuMask != 0) + { + cpu_set_t processorCpuSet; + unsigned int j; + CPU_ZERO(&processorCpuSet); + for (j = 0u; (j < (sizeof(cpuMask) * 8u)) && (j < CPU_SETSIZE); j++) + { + if (((cpuMask >> j) & 0x1u) == 0x1u) + { + CPU_SET(j, &processorCpuSet); + } + } + pthread_setaffinity_np(thread, sizeof(processorCpuSet), &processorCpuSet); + } +#endif } + *eventid = pushEvent(thread, udpSocket); return 1; } + +int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), + void *astprm, int *eventid) +{ + return MDSUdpEventAstMask(eventName, astadr, astprm, eventid, 0); +} + + int MDSUdpEventCan(int eventid) { EventList *ev = popEvent(eventid); if (!ev) { @@ -353,34 +384,33 @@ int MDSUdpEventCan(int eventid) { } static SOCKET send_socket = INVALID_SOCKET; +static unsigned short sendPort = 0; static pthread_once_t send_socket_once = PTHREAD_ONCE_INIT; static void send_socket_get() { if ((send_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) print_error("Error creating socket"); + UdpEventGetPort(&sendPort); } int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) { char multiIp[64]; uint32_t buflen_net_order = (uint32_t)htonl(bufLen); SOCKET udpSocket; - struct sockaddr_in sin; + static struct sockaddr_in sin; char *msg = 0, *currPtr; unsigned int msgLen, nameLen = (unsigned int)strlen(eventName), actBufLen; uint32_t namelen_net_order = (uint32_t)htonl(nameLen); int status; - unsigned short port; char ttl, loop; struct in_addr *interface_addr = 0; getMulticastAddr(eventName, multiIp); pthread_once(&send_socket_once, &send_socket_get); udpSocket = send_socket; - memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; *(int *)&sin.sin_addr = LibGetHostAddr(multiIp); - UdpEventGetPort(&port); - sin.sin_port = htons(port); + sin.sin_port = htons(sendPort); nameLen = (unsigned int)strlen(eventName); if (bufLen < MAX_MSG_LEN - (4u + 4u + nameLen)) actBufLen = bufLen; @@ -403,6 +433,7 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) { memcpy(currPtr, buf, bufLen); pthread_mutex_lock(&sendEventMutex); + if (UdpEventGetTtl(&ttl)) setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); if (UdpEventGetLoop(&loop)) @@ -412,6 +443,7 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) { (char *)interface_addr, sizeof(*interface_addr)); free(interface_addr); } + if (sendto(udpSocket, msg, msgLen, 0, (struct sockaddr *)&sin, sizeof(sin)) == -1) { print_error("Error sending UDP message"); diff --git a/mdsshr/mdsshrp.h b/mdsshr/mdsshrp.h index ebe4602847..dc134bc71b 100644 --- a/mdsshr/mdsshrp.h +++ b/mdsshr/mdsshrp.h @@ -16,6 +16,9 @@ extern void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], extern int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), void *astprm, int *eventid); +extern int MDSUdpEventAstMask(char const *eventName, + void (*astadr)(void *, int, char *), void *astprm, + int *eventid, unsigned int cpuMask); extern int MDSUdpEventCan(int eventid); extern int MDSUdpEvent(char const *eventName, int bufLen, char const *buf); extern int LibSFree1Dd(struct descriptor *out); From 11c3935370fa962c150939c7208a7b5074a8ec8f Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Tue, 20 Apr 2021 20:37:46 +0200 Subject: [PATCH 04/27] Build: used standard clang-format tools with style file (#2293) * bootstrap: included for #2291 * yylex for treeshr * added echo-% recipe * python: merged if statements * TEsts: helgrind python suppression * STATUS_OK stuff with () for clang * added clang-format * fixup multi-line comments (-Wcomment) generated by clang-format * applied ./clang-format --- .clang-format | 16 + .gitignore | 3 +- Makefile.inc.in | 5 + actions/actions.c | 70 +- actions/actlog.c | 12 +- actions/actlogp.h | 71 +- actions/actmon.c | 134 +- bootstrap | 18 +- camshr/CDC.h | 3 +- camshr/ESR.h | 3 +- camshr/KsM.c | 27 +- camshr/KsS.c | 9 +- camshr/KsT.c | 18 +- camshr/QueryHighwayType.c | 50 +- camshr/RSD.h | 6 +- camshr/RemCamIosb.c | 21 +- camshr/RemCamMulti.c | 61 +- camshr/RemCamSingle.c | 45 +- camshr/SD.h | 9 +- camshr/ScsiCamac.h | 100 +- camshr/ScsiSystemStatus.c | 9 +- camshr/add_entry.c | 21 +- camshr/bisearch.c | 15 +- camshr/cam_functions.c | 360 +- camshr/check_for_file.c | 11 +- camshr/check_sema4.c | 3 +- camshr/commit_entry.c | 9 +- camshr/common.h | 27 +- camshr/compare_str.c | 20 +- camshr/contract_db.c | 33 +- camshr/copy.c | 24 +- camshr/crate.h | 25 +- camshr/create_sema4.c | 12 +- camshr/create_tmp_file.c | 21 +- camshr/debug.c | 24 +- camshr/expand_db.c | 33 +- camshr/get_crate_status.c | 3 +- camshr/get_db_file_size.c | 9 +- camshr/get_file_count.c | 18 +- camshr/get_file_name.c | 3 +- camshr/get_scsi_device_number.c | 17 +- camshr/inquiry.c | 9 +- camshr/issort.c | 9 +- camshr/lock_file.c | 12 +- camshr/lookup_entry.c | 24 +- camshr/map_data_file.c | 27 +- camshr/map_scsi_device.c | 45 +- camshr/module.h | 9 +- camshr/msg.c | 11 +- camshr/parse_crate_db.c | 3 +- camshr/parse_cts_db.c | 8 +- camshr/remove_entry.c | 21 +- camshr/scsi_io.c | 118 +- camshr/turn_crate_on_off_line.c | 16 +- camshr/unlock_file.c | 9 +- camshr/verbs.c | 249 +- camshr/xlate_logicalname.c | 20 +- ccl/ccl_commands.c | 34 +- ccl/ccl_verbs.c | 167 +- clang-format.sh | 16 + conf/valgrind.supp/fc32.supp | 5 + deploy/yylex.gen | 5 +- device_support/basler/BASLERACA.cpp | 568 +- device_support/basler/BASLERACA.h | 108 +- device_support/basler/main.cpp | 15 +- device_support/caen/caenInterface.cpp | 162 +- device_support/camera_utils/cammdsutils.cpp | 174 +- device_support/camera_utils/cammdsutils.h | 35 +- .../camera_utils/camstreamutils.cpp | 240 +- device_support/camera_utils/camstreamutils.h | 52 +- device_support/flir/FLIRSC65X.cpp | 936 +- device_support/flir/FLIRSC65X.h | 132 +- device_support/flir/fff.h | 43 +- device_support/flir/flirutils.h | 23 +- device_support/flir/main.cpp | 49 +- device_support/kappa/kappazelos.cpp | 166 +- device_support/kappa/kappazelos.h | 59 +- device_support/kappa/main.cpp | 40 +- device_support/national/AsyncStoreManager.cpp | 157 +- device_support/national/AsyncStoreManager.h | 28 +- .../national/NiFpga_FAU_cRIO_FPGA.h | 29 +- .../national/NiFpga_MainFPGA_9159.h | 38 +- .../national/NiFpga_MainFPGA_9159Simulator.h | 47 +- device_support/national/NiInterface.cpp | 968 +- device_support/national/cRioFAUfunction.cpp | 236 +- device_support/national/cRioFAUfunction.h | 53 +- device_support/national/cRioMPAGfunction.cpp | 260 +- device_support/national/cRioMPAGfunction.h | 52 +- device_support/national/generateWave-cotb.cpp | 154 +- device_support/national/generateWave.cpp | 154 +- device_support/national/print_device_info.cpp | 21 +- device_support/national/probeTermControl.cpp | 154 +- .../national/startStopTermControl.cpp | 36 +- device_support/national/writeDigitalOut.cpp | 54 +- device_support/ptgrey/PTGREY.cpp | 2087 ++--- device_support/ptgrey/PTGREY.h | 410 +- device_support/ptgrey/main.cpp | 306 +- device_support/raptor/cygnet.cpp | 115 +- device_support/raptor/cygnet.h | 31 +- device_support/redpitaya/axi_reg.h | 24 +- device_support/redpitaya/redpitaya.cpp | 199 +- device_support/redpitaya/rfx_stream.h | 141 +- device_support/redpitaya/rpadc_fifo_auto.c | 293 +- dwscope/RemoteDummies.c | 3 +- dwscope/dwpad.c | 208 +- dwscope/dwscope.c | 684 +- dwscope/dwscope.h | 15 +- dwscope/dwscopesubs.c | 291 +- dwscope/evaluate.c | 344 +- epics/cas/mdsServer.h | 12 +- epics/mdsrecords/devExprSoft.c | 24 +- epics/mdsrecords/devMeSoft.c | 21 +- epics/mdsrecords/mdsexprRecord.c | 101 +- epics/mdsrecords/mdsplusSupMain.cpp | 6 +- epics/mdsrecords/mdsplusSupUtilities.cpp | 283 +- epics/mdsrecords/mdsputRecord.c | 101 +- examples/demoadc/DemoAdc.c | 15 +- hdf5/MDSplus2HDF5.c | 232 +- hdf5/dynhdf5.c | 54 +- hdf5/hdf5ToMds.c | 159 +- hdf5/hdf5tdi.c | 168 +- idlmdsevent/mdsevent.c | 73 +- idlmdswidgets/cw_wveditv5.c | 359 +- include/WindowsUnnamedSemaphore.h | 24 +- include/Xmds/ListTree.h | 111 +- include/Xmds/ListTreeP.h | 21 +- include/Xmds/XmdsCallbacks.h | 6 +- include/Xmds/XmdsDigChans.h | 12 +- include/Xmds/XmdsExprP.h | 12 +- include/Xmds/XmdsInputs.h | 3 +- include/Xmds/XmdsNidOptionMenu.h | 14 +- include/Xmds/XmdsOnOffToggleButton.h | 4 +- include/Xmds/XmdsPath.h | 6 +- include/Xmds/XmdsWavedraw.h | 6 +- include/Xmds/XmdsWavedrawP.h | 15 +- include/Xmds/XmdsWaveform.h | 58 +- include/Xmds/XmdsWaveformP.h | 23 +- include/Xmds/XmdsXdBoxDialogButton.h | 4 +- include/Xmds/XmdsXdBoxOnOffButton.h | 4 +- include/Xmds/XmdsXdBoxP.h | 15 +- include/condition.h | 155 +- include/coz.h | 110 +- include/dbidef.h | 21 +- include/dtypedef.h | 26 +- include/getusername.h | 38 +- include/int128.h | 142 +- include/ipdesc.h | 48 +- include/mds_gendevice.h | 608 +- include/mds_stdarg.h | 24 +- include/mdsdescrip.h | 825 +- include/mdsevents.h | 3 +- include/mdslib.h | 45 +- include/mdsobjects.h | 8039 +++++++++-------- include/mdsplus/AutoPointer.hpp | 146 +- include/mdsplus/ConditionVar.hpp | 210 +- include/mdsplus/Mutex.hpp | 109 +- include/mdsplus/Traits.hpp | 18 +- include/mdsplus/mdsplus.h | 3 +- include/mdsplus/numeric_cast.hpp | 496 +- include/mdsserver.h | 46 +- include/mdsshr.h | 270 +- include/mdsversion.h | 3 +- include/mitdevices_msg.h | 332 +- include/msc_stdint.h | 10 +- include/ncidef.h | 7 +- include/pthread_port.h | 67 +- include/socket_port.h | 15 +- include/sqldb.h | 349 +- include/sqlfront.h | 360 +- include/status.h | 45 +- include/strroutines.h | 9 +- include/tdishr.h | 2 +- include/treeioperf.h | 3 +- include/treeshr.h | 667 +- include/treeshr_hooks.h | 3 +- include/usagedef.h | 4 +- javamds/MDSplus_Connection.h | 47 +- javamds/MDSplus_Data.h | 53 +- javamds/MDSplus_Event.h | 21 +- javamds/MDSplus_REvent.h | 29 +- javamds/MDSplus_Tree.h | 151 +- javamds/MDSplus_TreeNode.h | 279 +- javamds/MdsHelper.h | 7 +- javamds/ServerSupport.c | 110 +- javamds/mdsobjects.c | 1165 +-- kbsidevices/hpe1429.c | 1543 ++-- kbsidevices/hpe1564.c | 1948 ++-- kbsidevices/ni5122.c | 48 +- kbsidevices/nidaq.c | 68 +- kbsidevices/tkvx4244.c | 648 +- math/boxsmooth.c | 15 +- math/testing/csint.c | 25 +- math/testing/toms510.c | 9 +- mdsdcl/cmdExecute.c | 703 +- mdsdcl/cmdHelp.c | 77 +- mdsdcl/dcl_p.h | 50 +- mdsdcl/mdsdcl.c | 100 +- mdsdcl/mdsdclThreadStatic.c | 9 +- mdsdcl/mdsdcl_commands.c | 362 +- mdsdcl/mdsdcl_show_version.c | 15 +- mdsdcl/mdsdclthreadstatic.h | 3 +- mdsdcl/yylex/outfiles | 1 - mdsdebug.c | 15 +- mdsdebugc.c | 6 +- mdslib/MdsLib.c | 488 +- mdslib/fortran_aliases_mac.h | 18 +- mdslib/testing/dtype_test.c | 3 +- mdslib/testing/mdslib_ctest.c | 80 +- mdslib/visual_basic_api.h | 96 +- mdslibidl/MdsLibIdl.c | 191 +- mdsmisc/MdsFilter.c | 12 +- mdsmisc/ScopeUtilities.c | 573 +- mdsmisc/bessel.c | 146 +- mdsmisc/bessel.h | 42 +- mdsmisc/boxsmooth.c | 15 +- mdsmisc/butterworth.c | 59 +- mdsmisc/bwfilter.c | 39 +- mdsmisc/complex.c | 21 +- mdsmisc/complex.h | 3 +- mdsmisc/fformat.c | 3 +- mdsmisc/filter.c | 109 +- mdsmisc/filter.h | 9 +- mdsmisc/fir.c | 33 +- mdsmisc/getnidarray.c | 13 +- mdsmisc/getreferences.c | 46 +- mdsmisc/iir.c | 121 +- mdsmisc/resample.c | 18 +- mdsmisc/step_resample.c | 13 +- mdsmisc/whoami.c | 3 +- mdsobjects/cpp/mdsdata.c | 283 +- mdsobjects/cpp/mdsdataobjects.cpp | 491 +- mdsobjects/cpp/mdsdatastreams.cpp | 265 +- mdsobjects/cpp/mdseventobjects.cpp | 91 +- mdsobjects/cpp/mdsipobjects.cpp | 206 +- mdsobjects/cpp/mdsobjects.c | 279 +- mdsobjects/cpp/mdstree.c | 96 +- mdsobjects/cpp/mdstreeobjects.cpp | 808 +- mdsobjects/cpp/testing/MdsActionTest.cpp | 3 +- mdsobjects/cpp/testing/MdsApdTest.cpp | 3 +- mdsobjects/cpp/testing/MdsCallTest.cpp | 3 +- mdsobjects/cpp/testing/MdsCompoundTest.cpp | 3 +- mdsobjects/cpp/testing/MdsConglomTest.cpp | 3 +- .../cpp/testing/MdsConnectionSuppression.cpp | 3 +- mdsobjects/cpp/testing/MdsConnectionTest.cpp | 52 +- mdsobjects/cpp/testing/MdsDataStreamTest.c | 21 +- mdsobjects/cpp/testing/MdsDataTest.cpp | 3 +- mdsobjects/cpp/testing/MdsDataTest.h | 642 +- mdsobjects/cpp/testing/MdsDimensionTest.cpp | 3 +- .../cpp/testing/MdsEventSuppression.cpp | 7 +- mdsobjects/cpp/testing/MdsEventTest.cpp | 289 +- mdsobjects/cpp/testing/MdsExceptionTest.cpp | 17 +- .../cpp/testing/MdsExpressionCompileTest.cpp | 33 +- mdsobjects/cpp/testing/MdsFunctionTest.cpp | 9 +- mdsobjects/cpp/testing/MdsRangeTest.cpp | 3 +- .../MdsScalarTest_NumericConversion.cpp | 75 +- .../testing/MdsScalarTest_NumericLimits.cpp | 200 +- .../cpp/testing/MdsScalarTest_ScalarCast.cpp | 9 +- mdsobjects/cpp/testing/MdsSignalTest.cpp | 3 +- mdsobjects/cpp/testing/MdsStringTest.cpp | 10 +- mdsobjects/cpp/testing/MdsTdiTest.cpp | 66 +- mdsobjects/cpp/testing/MdsTreeNodeTest.cpp | 141 +- mdsobjects/cpp/testing/MdsTreeSegments.cpp | 79 +- mdsobjects/cpp/testing/MdsTreeSuppression.cpp | 3 +- mdsobjects/cpp/testing/MdsTreeTest.cpp | 3 +- mdsobjects/cpp/testing/MdsWindowTest.cpp | 3 +- mdsobjects/cpp/testing/buildtest.cpp | 3 +- mdsobjects/cpp/testing/testutils/CommaInit.h | 69 +- .../cpp/testing/testutils/FunctionTypes.h | 93 +- .../cpp/testing/testutils/MdsIpInstancer.h | 378 +- mdsobjects/cpp/testing/testutils/Singleton.h | 65 +- mdsobjects/cpp/testing/testutils/String.h | 12 +- mdsobjects/cpp/testing/testutils/Threads.h | 54 +- mdsobjects/cpp/testing/testutils/mdsipmain.c | 6 +- .../cpp/testing/testutils/testutils.cpp | 9 +- mdsobjects/cpp/testing/testutils/testutils.h | 11 +- .../cpp/testing/testutils/type_traits.h | 115 +- mdsobjects/cpp/testing/testutils/unique_ptr.h | 99 +- .../cpp/testing/testutils/vector_test.h | 68 +- mdsobjects/labview/lv.c | 12 +- mdsobjects/labview/mdsdataobjectswrp.cpp | 8017 ++++++++-------- mdsobjects/labview/mdseventobjectswrp.cpp | 95 +- mdsobjects/labview/mdsipobjectswrp.cpp | 63 +- mdsobjects/labview/mdsobjectswrp.h | 1658 ++-- mdsobjects/labview/mdstreeobjectswrp.cpp | 1217 ++- mdsshr/MDSprintf.c | 21 +- mdsshr/MdsCmprs.c | 96 +- mdsshr/MdsCompareXd.c | 52 +- mdsshr/MdsCompress.c | 61 +- mdsshr/MdsEvents.c | 575 +- mdsshr/MdsGet1DxA.c | 86 +- mdsshr/MdsGet1DxS.c | 17 +- mdsshr/MdsGetSetShotId.c | 6 +- mdsshr/MdsPk.c | 111 +- mdsshr/MdsSandbox.c | 3 +- mdsshr/MdsSerialize.c | 757 +- mdsshr/MdsThreadStatic.c | 34 +- mdsshr/MdsXdRoutines.c | 196 +- mdsshr/UdpEventSettings.c | 174 +- mdsshr/UdpEvents.c | 116 +- mdsshr/librtl.c | 701 +- mdsshr/mds_dsc_string.c | 26 +- mdsshr/mdsmsg.c | 62 +- mdsshr/mdsshrp.h | 4 +- mdsshr/mdsthreadstatic.h | 35 +- mdsshr/testing/UdpEventsTest.c | 25 +- mdsshr/testing/UdpEventsTestStatics.c | 44 +- mdssql/dynamic_syb.c | 127 +- mdstcpip/ArgLen.c | 6 +- mdstcpip/CheckClient.c | 141 +- mdstcpip/ClientType.c | 3 +- mdstcpip/CloseConnection.c | 11 +- mdstcpip/ConnectToMds.c | 79 +- mdstcpip/Connections.c | 224 +- mdstcpip/DoMessage.c | 21 +- mdstcpip/FlipData.c | 9 +- mdstcpip/FlipHeader.c | 7 +- mdstcpip/GetAnswerInfo.c | 67 +- mdstcpip/GetMdsMsg.c | 116 +- mdstcpip/GetSetSettings.c | 49 +- mdstcpip/IdlApi.c | 72 +- mdstcpip/IoRoutinesGsi.c | 180 +- mdstcpip/IoRoutinesThread.c | 42 +- mdstcpip/IoRoutinesTunnel.c | 75 +- mdstcpip/LoadIo.c | 6 +- mdstcpip/MakeDescrip.c | 6 +- mdstcpip/MdsClose.c | 3 +- mdstcpip/MdsDispatchEvent.c | 9 +- mdstcpip/MdsEventAst.c | 6 +- mdstcpip/MdsEventCan.c | 3 +- mdstcpip/MdsOpen.c | 3 +- mdstcpip/MdsPut.c | 35 +- mdstcpip/MdsSetCompression.c | 6 +- mdstcpip/MdsSetDefault.c | 3 +- mdstcpip/MdsValue.c | 116 +- mdstcpip/ParseCommand.c | 99 +- mdstcpip/ProcessMessage.c | 298 +- mdstcpip/RemoveConnection.c | 15 +- mdstcpip/SendArg.c | 36 +- mdstcpip/SendMdsMsg.c | 49 +- mdstcpip/cvtdef.h | 7 +- mdstcpip/ioroutines.h | 17 +- mdstcpip/ioroutinesV6.h | 28 +- mdstcpip/ioroutines_pipes.h | 25 +- mdstcpip/ioroutinestcp.h | 193 +- mdstcpip/ioroutinesudt.h | 143 +- mdstcpip/ioroutinesx.h | 204 +- mdstcpip/mdsIo.h | 50 +- mdstcpip/mdsip.c | 6 +- mdstcpip/mdsip.h | 15 +- mdstcpip/mdsip_connections.h | 48 +- mdstcpip/mdsip_service.c | 120 +- mdstcpip/testing/mdscp.c | 171 +- mdstcpip/testing/mdsiptest.c | 15 +- mdsvme/dmaexreg.h | 6 +- mdsvme/mdsvme.c | 116 +- mdsvme/vmp_reg.h | 9 +- mitdevices/a12_gen.c | 12 +- php/mdsplus.c | 232 +- python/MDSplus/mdsdcl.py | 3 +- remcam/CamIosb.c | 18 +- remcam/CamMulti.c | 61 +- remcam/CamSingle.c | 47 +- roam/roam_check_access.c | 77 +- roam/roam_gridmap_callout.c | 36 +- servershr/ServerAbortServer.c | 3 +- servershr/ServerBuildDispatchTable.c | 103 +- servershr/ServerCloseTrees.c | 3 +- servershr/ServerCreatePulse.c | 3 +- servershr/ServerDispatchAction.c | 3 +- servershr/ServerDispatchClose.c | 15 +- servershr/ServerDispatchCommand.c | 3 +- servershr/ServerDispatchPhase.c | 403 +- servershr/ServerFindServers.c | 32 +- servershr/ServerGetInfo.c | 44 +- servershr/ServerMonitorCheckin.c | 18 +- servershr/ServerQAction.c | 412 +- servershr/ServerSendMessage.c | 379 +- servershr/ServerSendMonitor.c | 9 +- servershr/ServerSetDetailProc.c | 3 +- servershr/ServerSetLogging.c | 3 +- servershr/ServerStopServer.c | 3 +- servershr/servershrp.h | 44 +- setevent/setevent.c | 10 +- tcl/tcl_add_node.c | 28 +- tcl/tcl_add_tag.c | 6 +- tcl/tcl_clean_datafile.c | 9 +- tcl/tcl_close.c | 13 +- tcl/tcl_compress_datafile.c | 9 +- tcl/tcl_create_pulse.c | 58 +- tcl/tcl_decompile.c | 18 +- tcl/tcl_delete_node.c | 42 +- tcl/tcl_delete_pulse.c | 6 +- tcl/tcl_directory.c | 133 +- tcl/tcl_directory_tag.c | 22 +- tcl/tcl_dispatch.c | 337 +- tcl/tcl_do_method.c | 129 +- tcl/tcl_do_node.c | 32 +- tcl/tcl_edit.c | 6 +- tcl/tcl_help_device.c | 17 +- tcl/tcl_p.h | 10 +- tcl/tcl_put_expression.c | 24 +- tcl/tcl_remove_tag.c | 6 +- tcl/tcl_rename.c | 27 +- tcl/tcl_set_callbacks.c | 40 +- tcl/tcl_set_current.c | 13 +- tcl/tcl_set_default.c | 12 +- tcl/tcl_set_node.c | 75 +- tcl/tcl_set_readonly.c | 6 +- tcl/tcl_set_tree.c | 30 +- tcl/tcl_set_view.c | 9 +- tcl/tcl_setevent.c | 3 +- tcl/tcl_setshow_attribute.c | 63 +- tcl/tcl_setshow_versions.c | 22 +- tcl/tcl_show_current.c | 10 +- tcl/tcl_show_data.c | 142 +- tcl/tcl_show_db.c | 9 +- tcl/tcl_verify_tree.c | 6 +- tcl/tcl_wfevent.c | 13 +- tcl/tcl_write.c | 13 +- tdic/TdiShrExt.c | 260 +- tdic/tdic.c | 141 +- tdishr/CvtConvertFloat.c | 980 +- tdishr/DummyRoutines.c | 9 +- tdishr/IsRoprand.c | 6 +- tdishr/TdiAbs.c | 347 +- tdishr/TdiAdd.c | 436 +- tdishr/TdiAnd.c | 78 +- tdishr/TdiApd.c | 71 +- tdishr/TdiArray.c | 268 +- tdishr/TdiBinary.c | 12 +- tdishr/TdiBound.c | 276 +- tdishr/TdiBuild.c | 66 +- tdishr/TdiCall.c | 190 +- tdishr/TdiChar.c | 168 +- tdishr/TdiCompile.c | 95 +- tdishr/TdiCompileDependency.c | 3 +- tdishr/TdiConstant.c | 100 +- tdishr/TdiConvert.c | 1929 ++-- tdishr/TdiCull.c | 278 +- tdishr/TdiCvtArgs.c | 71 +- tdishr/TdiCvtDxDx.c | 11 +- tdishr/TdiDecompile.c | 338 +- tdishr/TdiDecompileDependency.c | 63 +- tdishr/TdiDecompileR.c | 489 +- tdishr/TdiDecompress.c | 104 +- tdishr/TdiDefFunction.c | 50 +- tdishr/TdiDim.c | 618 +- tdishr/TdiDivide.c | 384 +- tdishr/TdiDoTask.c | 96 +- tdishr/TdiDtypeRange.c | 165 +- tdishr/TdiEq.c | 199 +- tdishr/TdiEvaluate.c | 56 +- tdishr/TdiExponent.c | 325 +- tdishr/TdiExpt.c | 65 +- tdishr/TdiExtFunction.c | 133 +- tdishr/TdiExtPython.c | 233 +- tdishr/TdiFaultHandler.c | 3 +- tdishr/TdiGetArgs.c | 194 +- tdishr/TdiGetData.c | 443 +- tdishr/TdiGetDbi.c | 219 +- tdishr/TdiGetNci.c | 384 +- tdishr/TdiGetShape.c | 34 +- tdishr/TdiGetSlope.c | 275 +- tdishr/TdiIand.c | 602 +- tdishr/TdiIntrinsic.c | 147 +- tdishr/TdiIo.c | 304 +- tdishr/TdiItoX.c | 944 +- tdishr/TdiMakeFunctionTable.c | 8 +- tdishr/TdiMasterData.c | 22 +- tdishr/TdiMath1.c | 310 +- tdishr/TdiMath2.c | 289 +- tdishr/TdiMatrix.c | 66 +- tdishr/TdiMaxVal.c | 518 +- tdishr/TdiMinMax.c | 54 +- tdishr/TdiPack.c | 143 +- tdishr/TdiPower.c | 142 +- tdishr/TdiReshape.c | 37 +- tdishr/TdiSame.c | 74 +- tdishr/TdiScalar.c | 236 +- tdishr/TdiSetRange.c | 121 +- tdishr/TdiShowVm.c | 5 +- tdishr/TdiSort.c | 829 +- tdishr/TdiSql.c | 285 +- tdishr/TdiSquare.c | 19 +- tdishr/TdiStatement.c | 243 +- tdishr/TdiSubscript.c | 421 +- tdishr/TdiThreadStatic.c | 13 +- tdishr/TdiTrans.c | 290 +- tdishr/TdiTrim.c | 63 +- tdishr/TdiUnary.c | 9 +- tdishr/TdiUndef.c | 2 +- tdishr/TdiVar.c | 809 +- tdishr/TdiVector.c | 151 +- tdishr/TdiXxx.c | 328 +- tdishr/TdiXxxOf.c | 1352 +-- tdishr/TdiYaccSubs.c | 54 +- tdishr/cvtdef.h | 9 +- tdishr/roprand.h | 18 +- tdishr/tdinelements.h | 2 +- tdishr/tdirefcat.h | 9 +- tdishr/tdireffunction.h | 3 +- tdishr/tdirefstandard.h | 13 +- tdishr/tdirefzone.h | 73 +- tdishr/tdithreadstatic.h | 9 +- tdishr/testing/build_test.c | 3 +- tdishr/yylex/TdiLex.l | 6 +- tdishr/yylex/TdiYacc.y | 2 +- tdishr/yylex/outfiles | 1 - tditest/tditest.c | 200 +- testing/backends/check/build_test.c | 3 +- testing/backends/check/check.c | 144 +- testing/backends/check/check.h | 111 +- testing/backends/check/check_error.c | 9 +- testing/backends/check/check_impl.h | 31 +- testing/backends/check/check_list.c | 42 +- testing/backends/check/check_log.c | 157 +- testing/backends/check/check_msg.c | 105 +- testing/backends/check/check_pack.c | 144 +- testing/backends/check/check_pack.h | 18 +- testing/backends/check/check_print.c | 61 +- testing/backends/check/check_run.c | 336 +- testing/backends/check/check_str.c | 27 +- testing/backends/check/lib/libcompat.c | 3 +- testing/backends/check/lib/libcompat.h | 12 +- testing/base_backend.c | 6 +- testing/check_backend.c | 299 +- testing/selftest/error_test.c | 3 +- testing/selftest/example.c | 15 +- testing/selftest/example2.c | 6 +- testing/selftest/example3.cpp | 6 +- testing/selftest/example4.c | 12 +- testing/selftest/example_assert.c | 3 +- testing/selftest/fork_fail.c | 3 +- testing/selftest/fork_success.c | 3 +- testing/selftest/leak_test.c | 10 +- testing/selftest/mdstestdummy.h | 7 +- testing/selftest/skip_test.c | 3 +- testing/selftest/test_options.c | 3 +- testing/selftest/timeout_fail.c | 3 +- testing/selftest/timeout_success.c | 3 +- testing/testing.h | 152 +- traverser/CallbacksUil.c | 694 +- traverser/GetNciString.c | 3 +- traverser/GetSupportedDevices.c | 9 +- traverser/ReadInt.c | 72 +- traverser/ReadString.c | 42 +- traverser/bxutils-uil.c | 467 +- traverser/main-uil.c | 9 +- treeshr/Makefile.in | 39 +- treeshr/{Notify.c => Notify.c.template} | 7 +- treeshr/RemoteAccess.c | 1036 ++- treeshr/TreeAddNode.c | 714 +- treeshr/TreeAddTag.c | 38 +- treeshr/TreeCallHook.c | 60 +- treeshr/TreeCleanDatafile.c | 289 +- treeshr/TreeCreatePulseFile.c | 130 +- treeshr/TreeDeleteNode.c | 143 +- treeshr/TreeDeletePulseFile.c | 73 +- treeshr/TreeDoMethod.c | 82 +- treeshr/TreeFindNode.c | 343 +- treeshr/TreeFindTag.c | 87 +- treeshr/TreeFindTagWild.c | 111 +- treeshr/TreeGetDbi.c | 47 +- treeshr/TreeGetNci.c | 451 +- treeshr/TreeGetRecord.c | 434 +- treeshr/TreeGetSetShotId.c | 54 +- treeshr/TreeOpen.c | 835 +- treeshr/TreePerf.c | 112 +- treeshr/TreePutRecord.c | 556 +- treeshr/TreeRemoveNodesTags.c | 33 +- treeshr/TreeRenameNode.c | 82 +- treeshr/TreeSegments.c | 2091 +++-- treeshr/TreeSerializeNci.c | 28 +- treeshr/TreeSetDbi.c | 19 +- treeshr/TreeSetDefault.c | 30 +- treeshr/TreeSetNci.c | 256 +- treeshr/TreeThreadStatic.c | 69 +- treeshr/TreeVerify.c | 45 +- treeshr/dummies.c | 22 +- treeshr/lex.yytreepath.c | 2104 ----- treeshr/testing/TreeDeleteNodeTest.c | 13 +- treeshr/testing/TreeSegmentTest.c | 52 +- treeshr/treeshr_xnci.h | 123 +- treeshr/treeshrp.h | 331 +- treeshr/treethreadstatic.h | 3 +- treeshr/{ => yylex}/TreeFindNodeWild.l | 29 +- treeshr/yylex/fixme-files | 1 + wfevent/wfevent.c | 73 +- xmdsshr/ListTree.c | 792 +- xmdsshr/UilDBDef.h | 28 +- xmdsshr/UilSymCSet.h | 90 +- xmdsshr/UilSymEnum.h | 473 +- xmdsshr/UilSymRArg.h | 378 +- xmdsshr/XmdsBells.c | 3 +- xmdsshr/XmdsComplain.c | 9 +- xmdsshr/XmdsDeviceSetup.c | 6 +- xmdsshr/XmdsDigChans.c | 33 +- xmdsshr/XmdsDisplay.c | 24 +- xmdsshr/XmdsExpr.c | 193 +- xmdsshr/XmdsGetPutNid.c | 126 +- xmdsshr/XmdsGetSetOptionIdx.c | 15 +- xmdsshr/XmdsInitialize.c | 3 +- xmdsshr/XmdsInput.c | 12 +- xmdsshr/XmdsInputs.c | 27 +- xmdsshr/XmdsNidOptionMenu.c | 99 +- xmdsshr/XmdsOkButtons.c | 42 +- xmdsshr/XmdsOnOffToggleButton.c | 33 +- xmdsshr/XmdsPath.c | 21 +- xmdsshr/XmdsPopupMenuPosition.c | 3 +- xmdsshr/XmdsSetSubvalues.c | 9 +- xmdsshr/XmdsSupport.c | 39 +- xmdsshr/XmdsUsageIcons.c | 9 +- xmdsshr/XmdsWavedraw.c | 395 +- xmdsshr/XmdsWaveform.c | 1068 ++- xmdsshr/XmdsWidgetCallbacks.c | 23 +- xmdsshr/XmdsXdBox.c | 735 +- xmdsshr/XmdsXdBoxDialog.c | 12 +- xmdsshr/XmdsXdBoxDialogButton.c | 33 +- xmdsshr/XmdsXdBoxOnOffButton.c | 27 +- xmdsshr/wmldbcreate-xmdsshr.c | 92 +- xtreeshr/XTreeConvertToLongTime.c | 68 +- xtreeshr/XTreeDefaultResample.c | 230 +- xtreeshr/XTreeDefaultSquish.c | 136 +- xtreeshr/XTreeGetSegmentList.c | 129 +- xtreeshr/XTreeGetTimedRecord.c | 199 +- 625 files changed, 59653 insertions(+), 43325 deletions(-) create mode 100644 .clang-format create mode 100755 clang-format.sh delete mode 100644 mdsdcl/yylex/outfiles delete mode 100644 tdishr/yylex/outfiles rename treeshr/{Notify.c => Notify.c.template} (98%) delete mode 100644 treeshr/lex.yytreepath.c rename treeshr/{ => yylex}/TreeFindNodeWild.l (90%) create mode 100644 treeshr/yylex/fixme-files diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..02d1b4e867 --- /dev/null +++ b/.clang-format @@ -0,0 +1,16 @@ +# clang-format --version +# clang-format version 7.0.1-8+deb10u2 (tags/RELEASE_701/final) +BasedOnStyle: LLVM +UseTab: Never +SortIncludes: false +IndentWidth: 2 +TabWidth: 2 +BreakBeforeBraces: Allman +AllowShortIfStatementsOnASingleLine: false +IndentCaseLabels: false +ColumnLimit: 0 +ReflowComments: true +Standard: Cpp03 +NamespaceIndentation: All +FixNamespaceComments: false +AccessModifierOffset: -2 diff --git a/.gitignore b/.gitignore index beb9cbba06..c9e054857a 100644 --- a/.gitignore +++ b/.gitignore @@ -185,6 +185,7 @@ testing/Makefile.in testing/backends/check/Makefile.in testing/selftest/Makefile.in treeshr/testing/Makefile.in +treeshr/TreeFindNodeWild.c wfevent/Makefile.in # Generated Java binaries @@ -198,4 +199,4 @@ java/jtraverser/CompileTree java/jtraverser/DecompileTree java/jtraverser/jTraverser java/jtraverser2/jTraverser2 -java/jtraverser2/setupDevice \ No newline at end of file +java/jtraverser2/setupDevice diff --git a/Makefile.inc.in b/Makefile.inc.in index 63ea4d3375..65efaee6c5 100644 --- a/Makefile.inc.in +++ b/Makefile.inc.in @@ -1,4 +1,9 @@ # @configure_input@ +.PHONY: --always +--always: + @ +echo-%: --always + @echo '$* = $($*)' DEFAULT_CFLAGS=-g -O3 diff --git a/actions/actions.c b/actions/actions.c index 1fdc6d74c0..17adf984c1 100644 --- a/actions/actions.c +++ b/actions/actions.c @@ -73,7 +73,8 @@ static void Exit(); static int OpenTree(String tree, int shot); static int Refresh(); static Widget mw; -typedef struct _info { +typedef struct _info +{ unsigned char on; unsigned char included; unsigned int phase; @@ -87,8 +88,10 @@ static int CompareActions(Info *a, Info *b); static Info *actions; static int num_actions; -int main(int argc, String *argv) { - static struct { +int main(int argc, String *argv) +{ + static struct + { String tree; int shot; } db; @@ -129,23 +132,27 @@ int main(int argc, String *argv) { } static void Modify(Widget w, XtPointer tag __attribute__((unused)), - XmListCallbackStruct *cb) { + XmListCallbackStruct *cb) +{ int i; Widget xdbox = XtNameToWidget(XtParent(XtParent(w)), "*modify_xdbox"); for (i = 0; i < num_actions && actions[i].item_idx != cb->item_position; i++) ; - if (i < num_actions) { + if (i < num_actions) + { XtManageChild(xdbox); XtVaSetValues(xdbox, XmdsNnid, actions[i].nid, NULL); } } static void ToggleEssential(Widget w, XtPointer tag __attribute__((unused)), - XmListCallbackStruct *cb) { + XmListCallbackStruct *cb) +{ int i; for (i = 0; i < num_actions && actions[i].item_idx != cb->item_position; i++) ; - if (i < num_actions) { + if (i < num_actions) + { XmString item; char *item_string; static int flags; @@ -155,7 +162,8 @@ static void ToggleEssential(Widget w, XtPointer tag __attribute__((unused)), TreeGetNci(actions[i].nid, itmlst); item_string = XmStringUnparse(cb->item, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (flags & NciM_ESSENTIAL) { + if (flags & NciM_ESSENTIAL) + { static int flags = NciM_ESSENTIAL; static NCI_ITM itmlst[] = { {sizeof(flags), NciCLEAR_FLAGS, (unsigned char *)&flags, 0}, @@ -163,7 +171,9 @@ static void ToggleEssential(Widget w, XtPointer tag __attribute__((unused)), TreeSetNci(actions[i].nid, itmlst); if (strlen(item_string) > 45) item_string[45] = ' '; - } else { + } + else + { static int flags = NciM_ESSENTIAL; static NCI_ITM itmlst[] = { {sizeof(flags), NciSET_FLAGS, (unsigned char *)&flags, 0}, @@ -183,7 +193,8 @@ static void Exit() { exit(0); } static int OpenTree(String tree, int shot) { return TreeOpen(tree, shot, 0); } -static int Refresh() { +static int Refresh() +{ void *ctx = 0; int nid; int i; @@ -202,12 +213,14 @@ static int Refresh() { while (TreeFindNodeWild("***", &nid, &ctx, mask) & 1) num_actions++; TreeFindNodeEnd(&ctx); - if (num_actions) { + if (num_actions) + { actions = (Info *)XtMalloc(sizeof(Info) * num_actions); memset(actions, 0, sizeof(Info) * num_actions); for (i = 0; (TreeFindNodeWild("***", &actions[i].nid, &ctx, mask) & 1) && i < num_actions; - i++) { + i++) + { static struct descriptor ident = {31, DTYPE_T, CLASS_S, 0}; static struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, 0}; static EMPTYXD(xd); @@ -231,10 +244,12 @@ static int Refresh() { actions[i].included = parent ? (p_flags & NciM_INCLUDE_IN_PULSE) != 0 : 1; StrCopyDx(&ident, (struct descriptor *)&blank); actions[i].idx = 0; - if (TdiDispatchOf(&niddsc, &xd MDS_END_ARG) & 1) { + if (TdiDispatchOf(&niddsc, &xd MDS_END_ARG) & 1) + { struct descriptor_dispatch *dispatch = (struct descriptor_dispatch *)xd.pointer; - if (dispatch->pointer && (dispatch->pointer[0] == TreeSCHED_SEQ)) { + if (dispatch->pointer && (dispatch->pointer[0] == TreeSCHED_SEQ)) + { static struct descriptor phase_d = {sizeof(int), DTYPE_L, CLASS_S, 0}; static DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); phase_d.pointer = (char *)&actions[i].phase; @@ -246,18 +261,22 @@ static int Refresh() { actions[i].phase = 254; if (!(TdiData(dispatch->ident, &ident MDS_END_ARG) & 1)) actions[i].phase = 253; - } else + } + else actions[i].phase = 252; - } else + } + else actions[i].phase = 251; } TreeFindNodeEnd(&ctx); qsort(actions, num_actions, sizeof(Info), (int (*)(const void *, const void *))CompareActions); - for (item_idx = 1, i = 0; i < num_actions; i++) { + for (item_idx = 1, i = 0; i < num_actions; i++) + { char line[256]; XmString item; - if (last_included != actions[i].included) { + if (last_included != actions[i].included) + { item = XmStringCreateSimple( "********************** The following nodes are not included in " "pulse *********************"); @@ -267,7 +286,8 @@ static int Refresh() { last_included = actions[i].included; last_on = 1; } - if (last_on != actions[i].on) { + if (last_on != actions[i].on) + { item = XmStringCreateSimple("****************************** The following " "nodes are turned off *********************"); @@ -276,7 +296,8 @@ static int Refresh() { item_idx++; last_on = actions[i].on; } - if (last_phase != actions[i].phase) { + if (last_phase != actions[i].phase) + { static String line_s = "************************** Phase: " "12345678901234567890123456789012*********************"; @@ -297,7 +318,8 @@ static int Refresh() { static struct descriptor phase_d = {sizeof(int), DTYPE_L, CLASS_S, 0}; phase_d.pointer = (char *)&actions[i].phase; strcpy(line, line_s); - switch (actions[i].phase) { + switch (actions[i].phase) + { case 0x10000001: StrCopyDx(&error, (struct descriptor *)&bad_phase); break; @@ -333,12 +355,14 @@ static int Refresh() { XmStringFree(item); actions[i].item_idx = item_idx++; } - } else + } + else status = TreeNNF; return status; } -static int CompareActions(Info *a, Info *b) { +static int CompareActions(Info *a, Info *b) +{ return (a->included == b->included) ? ((a->on == b->on) ? ((a->phase == b->phase) ? (int)a->idx - (int)b->idx diff --git a/actions/actlog.c b/actions/actlog.c index 5e49fb6ffb..ab70ead2b0 100644 --- a/actions/actlog.c +++ b/actions/actlog.c @@ -58,7 +58,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "actlogp.h" -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ char *monitor = "ACTION_MONITOR"; int i; for (i = 1; i < argc; i++) @@ -71,7 +72,8 @@ int main(int argc, char **argv) { } const struct timespec ms100 = {0, 100000000}; // 100ms -static void DoTimer() { +static void DoTimer() +{ while (!nanosleep(&ms100, NULL)) // not interrupted e.g. by Ctrl+C _DoTimer(); } @@ -79,14 +81,16 @@ static void DoTimer() { inline static void EventUpdate(LinkedEvent *event) { _EventUpdate(event); } static void PutLog(char *time, char *mode, char *status, char *server, - char *path) { + char *path) +{ fprintf(stdout, "%s %12d %-10.10s %-44.44s %-20.20s %s\n", time, current_shot, mode, status, server, path); fflush(stdout); } static void PutError(char *time, char *mode, char *status, char *server, - char *path) { + char *path) +{ fprintf(stderr, "%s %12d %-10.10s %-44.44s %-20.20s %s\n", time, current_shot, mode, status, server, path); } diff --git a/actions/actlogp.h b/actions/actlogp.h index 63a26c5a96..311b5be053 100644 --- a/actions/actlogp.h +++ b/actions/actlogp.h @@ -49,7 +49,8 @@ extern int str_element(); extern int TdiExecute(); -typedef struct _LinkedEvent { +typedef struct _LinkedEvent +{ char *msg; char *tree; int shot; @@ -95,13 +96,15 @@ static void PutLog(char *time, char *mode, char *status, char *server, static void PutError(char *time, char *mode, char *status, char *server, char *path); -static void ParseTime(LinkedEvent *event) { +static void ParseTime(LinkedEvent *event) +{ event->time = strtok(event->time, " "); while (event->time && strchr(event->time, ':') == 0) event->time = strtok(0, " "); } -static int parseMsg(char *msg, LinkedEvent *event) { +static int parseMsg(char *msg, LinkedEvent *event) +{ char *tmp; if (!msg) return C_ERROR; @@ -153,7 +156,8 @@ static int parseMsg(char *msg, LinkedEvent *event) { return C_OK; } -static LinkedEvent *GetQEvent() { +static LinkedEvent *GetQEvent() +{ pthread_mutex_lock(&event_mutex); LinkedEvent *ans = EventQueueHead; if (ans) @@ -164,17 +168,20 @@ static LinkedEvent *GetQEvent() { return ans; } -inline static void _DoTimer() { +inline static void _DoTimer() +{ LinkedEvent *ev; // while (sleep(100)==0) - while ((ev = GetQEvent())) { + while ((ev = GetQEvent())) + { EventUpdate(ev); free(ev->msg); free(ev); } } -static void QEvent(LinkedEvent *ev) { +static void QEvent(LinkedEvent *ev) +{ ev->next = NULL; pthread_mutex_lock(&event_mutex); if (EventQueueTail) @@ -185,10 +192,12 @@ static void QEvent(LinkedEvent *ev) { pthread_mutex_unlock(&event_mutex); } -static void MessageAst(void *dummy __attribute__((unused)), char *reply) { +static void MessageAst(void *dummy __attribute__((unused)), char *reply) +{ LinkedEvent *event = malloc(sizeof(LinkedEvent)); event->msg = NULL; - if (!parseMsg(reply, event)) { + if (!parseMsg(reply, event)) + { QEvent(event); return; } @@ -197,8 +206,10 @@ static void MessageAst(void *dummy __attribute__((unused)), char *reply) { CheckIn(0); } -inline static void _EventUpdate(LinkedEvent *event) { - switch (event->mode) { +inline static void _EventUpdate(LinkedEvent *event) +{ + switch (event->mode) + { case build_table_begin: DoOpenTree(event); case build_table: @@ -217,11 +228,13 @@ inline static void _EventUpdate(LinkedEvent *event) { } } -inline static void _DoOpenTree(LinkedEvent *event) { +inline static void _DoOpenTree(LinkedEvent *event) +{ current_node_entry = 0; current_on = -1; current_phase = 9999; - if ((event->shot != current_shot) || strcmp(event->tree, current_tree)) { + if ((event->shot != current_shot) || strcmp(event->tree, current_tree)) + { current_shot = event->shot; if (event->tree) strncpy(current_tree, event->tree, 12); @@ -230,7 +243,8 @@ inline static void _DoOpenTree(LinkedEvent *event) { } } -static void Phase(LinkedEvent *event) { +static void Phase(LinkedEvent *event) +{ static DESCRIPTOR(const unknown, "UNKNOWN"); static struct descriptor phase = {0, DTYPE_T, CLASS_D, 0}; static DESCRIPTOR(const phase_lookup, "PHASE_NAME_LOOKUP($)"); @@ -238,7 +252,8 @@ static void Phase(LinkedEvent *event) { phase_d.pointer = (char *)&event->phase; if (current_shot == -9999) current_shot = event->shot; - if (current_phase != event->phase) { + if (current_phase != event->phase) + { if (!(TdiExecute(&phase_lookup, &phase_d, &phase MDS_END_ARG) & 1)) StrCopyDx((struct descriptor *)&phase, (struct descriptor *)&unknown); char *str = MdsDescrToCstring(&phase); @@ -247,34 +262,38 @@ static void Phase(LinkedEvent *event) { current_phase = event->phase; } } -inline static void _Doing(LinkedEvent *event) { +inline static void _Doing(LinkedEvent *event) +{ Phase(event); PutLog(event->time, "DOING", " ", event->server, event->fullpath); } -inline static void _Done(LinkedEvent *event) { +inline static void _Done(LinkedEvent *event) +{ PutLog(event->time, "DONE", IS_OK(event->status) ? " " : event->status_text, event->server, event->fullpath); - if - IS_NOT_OK(event->status) - PutError(event->time, "DONE", event->status_text, event->server, - event->fullpath); + if (IS_NOT_OK(event->status)) + PutError(event->time, "DONE", event->status_text, event->server, + event->fullpath); } -static void Dispatched(LinkedEvent *event) { +static void Dispatched(LinkedEvent *event) +{ Phase(event); PutLog(event->time, "DISPATCHED", " ", event->server, event->fullpath); } -static void CheckIn(char *monitor_in) { +static void CheckIn(char *monitor_in) +{ static char *monitor; INIT_STATUS_ERROR; if (monitor_in) monitor = monitor_in; - for (;;) { + for (;;) + { status = ServerMonitorCheckin(monitor, MessageAst, 0); - if - STATUS_OK return; + if (STATUS_OK) + return; printf("Error %d connecting to monitor: %s, will try again shortly\n", status, monitor); sleep(2); diff --git a/actions/actmon.c b/actions/actmon.c index 06a86a215a..9a05a3043d 100644 --- a/actions/actmon.c +++ b/actions/actmon.c @@ -80,7 +80,8 @@ static void ConfirmAbort(Widget w, int *tag, XmListCallbackStruct *cb); static void ConfirmServerAbort(Widget w, void *tag, void *cb); static void SetKillSensitive(Widget top); -typedef struct _doingListItem { +typedef struct _doingListItem +{ int nid; int pos; struct _doingListItem *next; @@ -110,7 +111,8 @@ static char *expt = NULL; #define offset(strc, field) (int)((void *)&(strc).field - (void *)&(strc)) -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ static char *hierarchy_name[] = {"actmon.uid"}; static MrmRegisterArg callbacks[] = { {"Exit", (char *)Exit}, @@ -124,7 +126,8 @@ int main(int argc, char **argv) { {"-monitor", "*monitor", XrmoptionSepArg, NULL}, {"-expt", "*expt", XrmoptionSepArg, NULL}, }; - struct { + struct + { char *monitor; char *images; char *expt; @@ -148,7 +151,8 @@ int main(int argc, char **argv) { XtGetApplicationResources(top, &resource_list, resources, XtNumber(resources), (Arg *)NULL, 0); fprintf(stderr, "MONITOR: '%s'\n", resource_list.monitor); - if (resource_list.expt) { + if (resource_list.expt) + { int len = strlen(resource_list.expt); expt = malloc(sizeof(char) * (len + 1)); expt[len] = 0; @@ -168,7 +172,8 @@ int main(int argc, char **argv) { doing_label = XmStringCreateSimple("Doing"); done_label = XmStringCreateSimple("Done"); error_label = XmStringCreateSimple("Error"); - if (!kill_target_w) { + if (!kill_target_w) + { kill_target_w = XtNameToWidget(top, "*server_name"); } SetKillSensitive(top); @@ -180,11 +185,13 @@ int main(int argc, char **argv) { static void Exit(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ exit(0); } -typedef struct serverList { +typedef struct serverList +{ char *server; char path[512]; struct serverList *next; @@ -192,7 +199,8 @@ typedef struct serverList { static ServerList *Servers = NULL; -static Widget FindTop(Widget w) { +static Widget FindTop(Widget w) +{ for (; w && XtParent(w); w = XtParent(w)) ; return w; @@ -200,29 +208,35 @@ static Widget FindTop(Widget w) { static void SetKillTarget(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XmListCallbackStruct *cb __attribute__((unused))) { + XmListCallbackStruct *cb __attribute__((unused))) +{ static ServerList *server; int idx; - if (cb->selected_item_count == 1) { + if (cb->selected_item_count == 1) + { idx = cb->item_position; for (server = Servers; idx > 1; idx--, server = server->next) ; XmTextSetString(kill_target_w, server->server); - } else { + } + else + { XmTextSetString(kill_target_w, ""); } } static void ConfirmAbort(Widget w, int *tag, - XmListCallbackStruct *cb __attribute__((unused))) { + XmListCallbackStruct *cb __attribute__((unused))) +{ static int operation; static Widget dialog = NULL; XmString text_cs; char message[1024]; char *server; - if (!dialog) { + if (!dialog) + { dialog = XmCreateQuestionDialog(FindTop(w), "ConfirmServerAbort", NULL, 0); XtVaSetValues(dialog, XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL, XmNdefaultButtonType, XmDIALOG_CANCEL_BUTTON, XmNautoUnmanage, @@ -232,8 +246,10 @@ static void ConfirmAbort(Widget w, int *tag, } operation = *(int *)tag; server = XmTextGetString(kill_target_w); - if (strlen(server) > 0) { - switch (operation) { + if (strlen(server) > 0) + { + switch (operation) + { case 0: sprintf( message, @@ -251,7 +267,8 @@ static void ConfirmAbort(Widget w, int *tag, default: strcpy(message, ""); } - if (strlen(message) > 0) { + if (strlen(message) > 0) + { text_cs = XmStringCreateLtoR(message, XmSTRING_DEFAULT_CHARSET); XtVaSetValues(dialog, XmNmessageString, text_cs, XmNuserData, (void *)&operation, NULL); @@ -261,7 +278,8 @@ static void ConfirmAbort(Widget w, int *tag, } } -static int executable(const char *script) { +static int executable(const char *script) +{ int status; static const char *cmd_front = "/bin/sh -c '/usr/bin/which "; static const char *cmd_back = " > /dev/null 2>/dev/null'"; @@ -276,22 +294,26 @@ static int executable(const char *script) { return !status; } -static void SetKillSensitive(Widget top) { +static void SetKillSensitive(Widget top) +{ int i; static const char *widgets[] = {"*abort_server_b", "*kill_server_b", "*kill_dispatcher_b"}; static const char *scripts[] = {"mdsserver_abort", "mdsserver_kill", "mdsserver_kill_dispatcher"}; - for (i = 0; i < 3; i++) { + for (i = 0; i < 3; i++) + { Widget w = XtNameToWidget(top, widgets[i]); - if (executable(scripts[i])) { + if (executable(scripts[i])) + { XtVaSetValues(w, XmNsensitive, 1, NULL); } } } static void ConfirmServerAbort(Widget w, void *tag __attribute__((unused)), - void *cb __attribute__((unused))) { + void *cb __attribute__((unused))) +{ int *op_ptr; int operation; char *server; @@ -302,8 +324,10 @@ static void ConfirmServerAbort(Widget w, void *tag __attribute__((unused)), XtVaGetValues(w, XmNuserData, (void *)&op_ptr, NULL); operation = *op_ptr; server = XmTextGetString(kill_target_w); - if (strlen(server) > 0) { - switch (operation) { + if (strlen(server) > 0) + { + switch (operation) + { case 0: strcpy(cmd, "mdsserver_abort "); strcat(cmd, server); @@ -325,9 +349,11 @@ static void ConfirmServerAbort(Widget w, void *tag __attribute__((unused)), } static void Disable(Widget w __attribute__((unused)), int *tag, - XmToggleButtonCallbackStruct *cb) { + XmToggleButtonCallbackStruct *cb) +{ Widget dw = 0; - switch (*tag) { + switch (*tag) + { case 4: LogWidgetOff = cb->set; MDS_ATTR_FALLTHROUGH @@ -347,7 +373,8 @@ static void Disable(Widget w __attribute__((unused)), int *tag, dw = XtParent(CurrentWidget); break; } - if (dw) { + if (dw) + { if (cb->set) XtUnmanageChild(dw); else @@ -355,17 +382,20 @@ static void Disable(Widget w __attribute__((unused)), int *tag, } } -static void DoTimer() { +static void DoTimer() +{ _DoTimer(); XtAppAddTimeOut(app_ctx, 100, DoTimer, 0); } -static void EventUpdate(LinkedEvent *event) { +static void EventUpdate(LinkedEvent *event) +{ _EventUpdate(event); XmTextSetString(kill_target_w, ""); } -static int FindServer(char *name, ServerList **srv) { +static int FindServer(char *name, ServerList **srv) +{ ServerList *prev, *ptr, *newPtr; int idx; int match = 1; @@ -373,7 +403,8 @@ static int FindServer(char *name, ServerList **srv) { ptr && (match = strcasecmp(ptr->server, name)) < 0; prev = ptr, ptr = ptr->next, idx++) ; - if (match != 0) { + if (match != 0) + { XmString item; newPtr = (ServerList *)XtMalloc(sizeof(ServerList)); newPtr->server = (char *)XtMalloc(strlen(name) + 1); @@ -394,7 +425,8 @@ static int FindServer(char *name, ServerList **srv) { } static void PutLog(char *time, char *mode, char *status, char *server, - char *path) { + char *path) +{ ServerList *srv; char text[2048]; XmString item; @@ -403,12 +435,14 @@ static void PutLog(char *time, char *mode, char *status, char *server, return; sprintf(text, "%s %12d %-10.10s %-44.44s %-20.20s %s", time, current_shot, mode, status, server, path); - if (!LogWidgetOff) { + if (!LogWidgetOff) + { item = XmStringCreateSimple(text); XmListAddItemUnselected(LogWidget, item, 0); XmStringFree(item); XtVaGetValues(LogWidget, XmNitemCount, &items, NULL); - if (items > MaxLogLines) { + if (items > MaxLogLines) + { DoingListItem *doing; for (doing = DoingList; doing; doing = doing->next) doing->pos--; @@ -416,17 +450,22 @@ static void PutLog(char *time, char *mode, char *status, char *server, } XmListSetBottomPos(LogWidget, 0); } - if (!CurrentWidgetOff) { - if (strcmp(mode, "DOING") == 0) { + if (!CurrentWidgetOff) + { + if (strcmp(mode, "DOING") == 0) + { int idx = FindServer(server, &srv); strcpy(srv->path, path); sprintf(text, "%-20.20s %s %12d %s", server, time, current_shot, path); item = XmStringCreateSimple(text); XmListReplaceItemsPos(CurrentWidget, &item, 1, idx); XmStringFree(item); - } else if (strcmp(mode, "DONE") == 0) { + } + else if (strcmp(mode, "DONE") == 0) + { int idx = FindServer(server, &srv); - if (strcmp(srv->path, path) == 0) { + if (strcmp(srv->path, path) == 0) + { strcpy(srv->path, ""); item = XmStringCreateSimple(server); XmListReplaceItemsPos(CurrentWidget, &item, 1, idx); @@ -437,7 +476,8 @@ static void PutLog(char *time, char *mode, char *status, char *server, } static void PutError(char *time, char *mode, char *status, char *server, - char *path) { + char *path) +{ char text[2048]; XmString item; @@ -451,7 +491,8 @@ static void PutError(char *time, char *mode, char *status, char *server, XmListAddItemUnselected(ErrorWidget, item, 0); XmStringFree(item); XtVaGetValues(ErrorWidget, XmNitemCount, &items, NULL); - if (items > MaxLogLines) { + if (items > MaxLogLines) + { DoingListItem *doing; for (doing = DoingList; doing; doing = doing->next) doing->pos--; @@ -463,14 +504,16 @@ static void PutError(char *time, char *mode, char *status, char *server, */ } -static void DoOpenTree(LinkedEvent *event) { +static void DoOpenTree(LinkedEvent *event) +{ if (expt && strcmp(event->tree, expt)) return; DoingListItem *doing; DoingListItem *next; XmListDeleteAllItems(ErrorWidget); XmListDeselectAllItems(LogWidget); - for (doing = DoingList; doing; doing = next) { + for (doing = DoingList; doing; doing = next) + { next = doing->next; free(doing); } @@ -479,7 +522,8 @@ static void DoOpenTree(LinkedEvent *event) { unique_tag_seed = 0; } -static void Doing(LinkedEvent *event) { +static void Doing(LinkedEvent *event) +{ DoingListItem *doing = malloc(sizeof(DoingListItem)); DoingListItem *prev; DoingListItem *d; @@ -498,7 +542,8 @@ static void Doing(LinkedEvent *event) { doing->next = 0; } -static void Done(LinkedEvent *event) { +static void Done(LinkedEvent *event) +{ DoingListItem *doing; DoingListItem *prev; int *items; @@ -508,7 +553,8 @@ static void Done(LinkedEvent *event) { for (prev = 0, doing = DoingList; doing && (doing->nid != event->nid); prev = doing, doing = doing->next) ; - if (doing) { + if (doing) + { XmListDeselectPos(LogWidget, doing->pos); if (prev) prev->next = doing->next; diff --git a/bootstrap b/bootstrap index 0606b170b4..adeb30657a 100755 --- a/bootstrap +++ b/bootstrap @@ -1,10 +1,11 @@ #! /bin/sh cd $(dirname $0) +check() { which $1 > /dev/null 2>&1; } unset abort testprog() { # $1 prog, $2 package -if ! which $1 >/dev/null 2>&1 +if ! check $1 then export abort=$? echo "Please install package providing '$1' in order to bootstrap" @@ -15,11 +16,19 @@ then fi } + +if check python3 +then PYTHON=python3 +elif check python2 +then PYTHON=python2 +else PYTHON=python +fi + testprog aclocal automake testprog autoheader autoconf testprog automake automake testprog autoconf autoconf -testprog python python2 or python3 +testprog $PYTHON python2 or python3 testprog bison bison testprog flex flex @@ -40,8 +49,9 @@ automake --add-missing autoconf -python deploy/gen_messages.py -python deploy/gen_compound_opcbuiltins.py +$PYTHON deploy/gen_messages.py +$PYTHON deploy/gen_compound_opcbuiltins.py deploy/yylex.gen tdishr +deploy/yylex.gen treeshr deploy/yylex.gen mdsdcl diff --git a/camshr/CDC.h b/camshr/CDC.h index 43580bedee..dba2f99476 100644 --- a/camshr/CDC.h +++ b/camshr/CDC.h @@ -3,7 +3,8 @@ #define __CDC_H // for Linux on x86 -typedef struct { +typedef struct +{ __u8 opcode; __u8 zero1; diff --git a/camshr/ESR.h b/camshr/ESR.h index 58018d9fd8..7d86cd6b62 100644 --- a/camshr/ESR.h +++ b/camshr/ESR.h @@ -3,7 +3,8 @@ #define __ESR_H // for Linux on x86 -typedef struct { +typedef struct +{ __u32 noq : 1; __u32 nox : 1; __u32 ste : 1; diff --git a/camshr/KsM.c b/camshr/KsM.c index d9e1794e33..3046d2c316 100644 --- a/camshr/KsM.c +++ b/camshr/KsM.c @@ -47,7 +47,8 @@ static int KsMultiIo(CamKey Key, // module info TranslatedIosb *iosb, // status struct int dmode, // mode int Enhanced // enhanced -) { +) +{ char dev_name[12]; BYTE Command[COMMAND_SIZE(OpCodeBlockCAMAC)]; int scsiDevice, status; @@ -71,7 +72,8 @@ static int KsMultiIo(CamKey Key, // module info // sprintf(dev_name, "GK%c%d", Key.scsi_port, Key.scsi_address); sprintf(dev_name, "GK%c%2d%2.2d", Key.scsi_port, Key.scsi_address, Key.crate); - if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) { + if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) + { if (MSGLVL(IMPORTANT)) fprintf(stderr, "%s(): error -- no scsi device found for '%s'\n", KM_ROUTINE_NAME, dev_name); @@ -110,8 +112,10 @@ static int KsMultiIo(CamKey Key, // module info sizeof(sense), &sb_out_len, &transfer_len); #ifdef DEBUG - if (Verbose) { - struct { + if (Verbose) + { + struct + { char c2; char c3; char nb; @@ -140,12 +144,14 @@ static int KsMultiIo(CamKey Key, // module info {0x2, 0x00, 2, "Command Memory Address"}, {0x2, 0x02, 2, "Demand Message"}}; unsigned int i; - for (i = 0; i < (sizeof(reg) / sizeof(reg[0])); i++) { + for (i = 0; i < (sizeof(reg) / sizeof(reg[0])); i++) + { unsigned int l; unsigned short s; unsigned char c; char *dptr = 0; - switch (reg[i].nb) { + switch (reg[i].nb) + { case 1: dptr = (char *)&c; break; @@ -156,7 +162,8 @@ static int KsMultiIo(CamKey Key, // module info dptr = (char *)&l; break; } - if (!dptr) { + if (!dptr) + { printf("%s = invalid reg->nb = %d\n", reg[i].name, reg[i].nb); break; } @@ -168,7 +175,8 @@ static int KsMultiIo(CamKey Key, // module info Command[5] = 0; status = scsi_io(scsiDevice, 1, Command, 6, dptr, reg[i].nb, 0, 0, &sb_out_len, &dummy); - switch (reg[i].nb) { + switch (reg[i].nb) + { case 1: printf("%s = %d,%x\n", reg[i].name, c, c); break; @@ -208,7 +216,8 @@ static int KsMultiIo(CamKey Key, // module info printf("%s(): ScsiIo() returned %d\n", KM_ROUTINE_NAME, status); KsMultiIo_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("%s(): iosb->status [0x%x]\n", KM_ROUTINE_NAME, iosb->status); printf("%s(): iosb->x [0x%x]\n", KM_ROUTINE_NAME, iosb->x); printf("%s(): iosb->q [0x%x]\n", KM_ROUTINE_NAME, iosb->q); diff --git a/camshr/KsS.c b/camshr/KsS.c index 9758feeabf..170564b83b 100644 --- a/camshr/KsS.c +++ b/camshr/KsS.c @@ -40,7 +40,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------- static int KsSingleIo(CamKey Key, BYTE A, BYTE F, BYTE *Data, BYTE Mem, TranslatedIosb *iosb, // to be returned to caller - int dmode) { + int dmode) +{ char dev_name[12]; BYTE Command[COMMAND_SIZE(OpCodeSingleCAMAC)]; int scsiDevice; @@ -61,7 +62,8 @@ static int KsSingleIo(CamKey Key, BYTE A, BYTE F, BYTE *Data, BYTE Mem, // sprintf(dev_name, "GK%c%d", Key.scsi_port, Key.scsi_address); sprintf(dev_name, "GK%c%2d%2.2d", Key.scsi_port, Key.scsi_address, Key.crate); - if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) { + if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) + { if (MSGLVL(IMPORTANT)) fprintf(stderr, "%s(): error -- no scsi device found for '%s'\n", KS_ROUTINE_NAME, dev_name); @@ -113,7 +115,8 @@ static int KsSingleIo(CamKey Key, BYTE A, BYTE F, BYTE *Data, BYTE Mem, printf("%s(): ScsiIo() returned %d\n", KS_ROUTINE_NAME, status); KsSingleIo_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("%s(): iosb->status [0x%x]\n", KS_ROUTINE_NAME, iosb->status); printf("%s(): iosb->bytcnt [%d]\n", KS_ROUTINE_NAME, iosb->bytcnt); printf("%s(): iosb->x [0x%x]\n", KS_ROUTINE_NAME, iosb->x); diff --git a/camshr/KsT.c b/camshr/KsT.c index c7e13606b8..459eb72627 100644 --- a/camshr/KsT.c +++ b/camshr/KsT.c @@ -40,7 +40,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "prototypes.h" //----------------------------------------------------------- -int KsTranslateIosb(RequestSenseData *sense, int cam_status) { +int KsTranslateIosb(RequestSenseData *sense, int cam_status) +{ int status; // union { @@ -49,7 +50,8 @@ int KsTranslateIosb(RequestSenseData *sense, int cam_status) { // BYTE b[4]; // } u; - if (Verbose) { + if (Verbose) + { printf("SCSI Sense data: error code=%d,valid=%d,sense_key=%d\n\n", sense->error_code, sense->valid, sense->sense_key); printf(" CSR status register:\n\n"); @@ -88,8 +90,10 @@ int KsTranslateIosb(RequestSenseData *sense, int cam_status) { status = CamSERTRAERR; LastIosb.status = Shorten(CamSERTRAERR); - if (cam_status == 0 || cam_status == 1 || cam_status == 2) { - switch (sense->u2.esr.error_code) { + if (cam_status == 0 || cam_status == 1 || cam_status == 2) + { + switch (sense->u2.esr.error_code) + { case 0: status = 1; LastIosb.status = Shorten(CamDONE_Q); @@ -129,7 +133,8 @@ int KsTranslateIosb(RequestSenseData *sense, int cam_status) { LastIosb.no_sync = sense->u2.esr.no_sync; LastIosb.tmo = sense->u2.esr.tmo; LastIosb.adnr = sense->u2.esr.adnr; - if (sense->u2.esr.adnr) { + if (sense->u2.esr.adnr) + { status = CamDONE_NOX; LastIosb.status = Shorten(CamDONE_NOX); } @@ -137,7 +142,8 @@ int KsTranslateIosb(RequestSenseData *sense, int cam_status) { // LastIosb.lbytcnt = 0; // list processing not // supported } - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("%s(): LastIosb.status = %d [0x%x]\n", KT_ROUTINE_NAME, LastIosb.status, LastIosb.status); printf("%s(): LastIosb.x = %d\n", KT_ROUTINE_NAME, LastIosb.x); diff --git a/camshr/QueryHighwayType.c b/camshr/QueryHighwayType.c index f78183eae8..05bafc8391 100644 --- a/camshr/QueryHighwayType.c +++ b/camshr/QueryHighwayType.c @@ -78,7 +78,8 @@ static char *ShowType(int type); // NB! 'serial_hwy_driver' must point to an array at least 7 characters long, // and be of the form 'GKB5'..., ie physical name. //------------------------------------------------------------------------- -int QueryHighwayType(char *serial_hwy_driver) { +int QueryHighwayType(char *serial_hwy_driver) +{ char line[80]; char tmpVendor[9], tmpModel[17], tmpRev[5]; int foundHost, foundVendor, highwayType = TYPE_UNKNOWN, host_adapter, scsi_id, @@ -94,7 +95,8 @@ int QueryHighwayType(char *serial_hwy_driver) { host_adapter = toupper(*(serial_hwy_driver + 2)) - 'A'; scsi_id = NUMERIC(*(serial_hwy_driver + 3)); - if ((fp = fopen(PROC_FILE, "r")) == NULL) { + if ((fp = fopen(PROC_FILE, "r")) == NULL) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "could *NOT* open '%s' for reading\n", PROC_FILE); @@ -102,22 +104,28 @@ int QueryHighwayType(char *serial_hwy_driver) { goto QueryHighwayType_Exit; } - if (channels[host_adapter][scsi_id] == UNDEFINED) { // a new one ... + if (channels[host_adapter][scsi_id] == UNDEFINED) + { // a new one ... if (MSGLVL(DETAILS)) printf(" new, unknown highway type\n"); foundHost = FALSE; foundVendor = FALSE; - while (!foundHost && (fgets(line, sizeof(line), fp)) != NULL) { - if (strstr(line, "Host:")) { + while (!foundHost && (fgets(line, sizeof(line), fp)) != NULL) + { + if (strstr(line, "Host:")) + { sscanf(line, "Host: scsi%1d Channel: %*2d Id: %2d", &tmpHost, &tmpId); - if (tmpHost == host_adapter && tmpId == scsi_id) { + if (tmpHost == host_adapter && tmpId == scsi_id) + { foundHost = TRUE; if (MSGLVL(DETAILS)) printf("%s", line); - while (!foundVendor && fgets(line, sizeof(line), fp) != NULL) { - if (strstr(line, "Vendor:")) { + while (!foundVendor && fgets(line, sizeof(line), fp) != NULL) + { + if (strstr(line, "Vendor:")) + { sscanf(line, " Vendor: %8s Model: %16s Rev: %5s", tmpVendor, tmpModel, tmpRev); @@ -132,17 +140,22 @@ int QueryHighwayType(char *serial_hwy_driver) { highwayType = TYPE_UNKNOWN; // pesimistic here :< - if (foundHost && foundVendor) { - if (strstr(tmpVendor, "JORWAY")) { + if (foundHost && foundVendor) + { + if (strstr(tmpVendor, "JORWAY")) + { if (strstr(tmpModel, "73A")) highwayType = JORWAY_73A; - else { + else + { if (strtol(tmpRev, NULL, 0) >= 12) highwayType = JORWAY; else highwayType = JORWAY_OLD; } - } else { + } + else + { if (strstr(tmpVendor, "KINSYSCO")) if (strncmp(tmpModel, "2145", 4) == EQUAL) highwayType = KINSYSCO; @@ -150,7 +163,9 @@ int QueryHighwayType(char *serial_hwy_driver) { } channels[host_adapter][scsi_id] = highwayType; // save result - } else { // ... take a short cut, we already know the type + } + else + { // ... take a short cut, we already know the type highwayType = channels[host_adapter][scsi_id]; if (MSGLVL(DETAILS)) @@ -166,7 +181,8 @@ int QueryHighwayType(char *serial_hwy_driver) { if (fp) // ... still open fclose(fp); - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("\033[01;33m%s\033[0m", ShowType(highwayType)); // '33m' == yellow printf(" status %d\n", status); } @@ -175,8 +191,10 @@ int QueryHighwayType(char *serial_hwy_driver) { } //------------------------------------------------------------------------- -static char *ShowType(int type) { - switch (type) { +static char *ShowType(int type) +{ + switch (type) + { case KINSYSCO: return ("kinsysco"); case JORWAY: diff --git a/camshr/RSD.h b/camshr/RSD.h index e243e6e2ef..cdcb36af4d 100644 --- a/camshr/RSD.h +++ b/camshr/RSD.h @@ -6,7 +6,8 @@ // NB! order of members is different from original // to get data to pack into same size memory, ie // 40 bytes -typedef struct { +typedef struct +{ __u8 error_code : 7; __u8 valid : 1; @@ -34,7 +35,8 @@ typedef struct { union { __u16 stacsr; - struct { + struct + { __u8 noq : 1; __u8 nox : 1; __u8 done : 1; diff --git a/camshr/RemCamIosb.c b/camshr/RemCamIosb.c index ad3fbe0868..c330924a5f 100644 --- a/camshr/RemCamIosb.c +++ b/camshr/RemCamIosb.c @@ -30,37 +30,44 @@ extern unsigned short RemCamLastIosb[4]; int RemCamVerbose(int flag __attribute__((unused))) { return 1; } -int RemCamBytcnt(unsigned short *iosb) { +int RemCamBytcnt(unsigned short *iosb) +{ return (int)(iosb ? iosb[1] : RemCamLastIosb[1]); } -int RemCamError(int *xexp, int *qexp, unsigned short *iosb_in) { +int RemCamError(int *xexp, int *qexp, unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((!(iosb[0] & 1)) || (xexp && ((*xexp & 1) != (iosb[2] & 1))) || (qexp && ((*qexp & 1) != ((iosb[2] >> 1) & 1)))); } -int RemCamX(unsigned short *iosb_in) { +int RemCamX(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && (iosb[2] & 1)); } -int RemCamQ(unsigned short *iosb_in) { +int RemCamQ(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && (iosb[2] & 2)); } -int RemCamStatus(unsigned short *iosb_in) { +int RemCamStatus(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return (int)iosb[7]; } -int RemCamGetStat(unsigned short *iosb_in) { +int RemCamGetStat(unsigned short *iosb_in) +{ memcpy(iosb_in, RemCamLastIosb, sizeof(RemCamLastIosb)); return 1; } -int RemCamXandQ(unsigned short *iosb_in) { +int RemCamXandQ(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && ((iosb[2] & 3) == 3)); } diff --git a/camshr/RemCamMulti.c b/camshr/RemCamMulti.c index 1790cf4547..cc303baf8a 100644 --- a/camshr/RemCamMulti.c +++ b/camshr/RemCamMulti.c @@ -39,10 +39,11 @@ extern int RemoteServerId(); static int CamMulti(char *routine, char *name, int a, int f, int count, void *data, int mem, unsigned short *iosb); -#define MakeMulti(locnam, remnam) \ - int locnam(char *name, int a, int f, int count, void *data, int mem, \ - unsigned short *iosb) { \ - return CamMulti(#remnam, name, a, f, count, data, mem, iosb); \ +#define MakeMulti(locnam, remnam) \ + int locnam(char *name, int a, int f, int count, void *data, int mem, \ + unsigned short *iosb) \ + { \ + return CamMulti(#remnam, name, a, f, count, data, mem, iosb); \ } MakeMulti(RemCamFQrepw, FQrepw) MakeMulti(RemCamFQstopw, FQstopw) @@ -55,7 +56,8 @@ MakeMulti(RemCamFQrepw, FQrepw) MakeMulti(RemCamFQstopw, FQstopw) short *iosb); static int CamMulti(char *routine, char *name, int a, int f, int count, - void *data, int mem, unsigned short *iosb) { + void *data, int mem, unsigned short *iosb) +{ int status = 1; iosb = (iosb) ? iosb : (unsigned short *)&RemCamLastIosb; @@ -67,12 +69,14 @@ static int CamMulti(char *routine, char *name, int a, int f, int count, return status; } -static void getiosb(int serverid, short *iosb) { +static void getiosb(int serverid, short *iosb) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, NULL); if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && - ans_d.dims[0] == 4) { + ans_d.dims[0] == 4) + { memcpy(RemCamLastIosb, ans_d.ptr, 8); if (iosb) memcpy(iosb, ans_d.ptr, 8); @@ -80,7 +84,8 @@ static void getiosb(int serverid, short *iosb) { free(ans_d.ptr); } -static void getdata(int serverid, void *data) { +static void getdata(int serverid, void *data) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, NULL); @@ -92,26 +97,32 @@ static void getdata(int serverid, void *data) { } static int DoCamMulti(char *routine, char *name, int a, int f, int count, - void *data, int mem, short *iosb) { + void *data, int mem, short *iosb) +{ int serverid = RemoteServerId(); int status = 0; int writeData; - if (serverid) { + if (serverid) + { struct descrip data_d = {8, 1, {0}, 0, 0}; struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; writeData = (!(f & 0x08)) && (f > 8); sprintf(cmd, "CamMulti('%s','%s',%d,%d,%d,%s,%d,_iosb)", routine, name, a, f, count, writeData ? "_data=$" : "_data", mem); - if (writeData) { + if (writeData) + { data_d.dtype = mem < 24 ? DTYPE_SHORT : DTYPE_LONG; data_d.dims[0] = count; data_d.ptr = data; status = MdsValue(serverid, cmd, &data_d, &ans_d, NULL); - } else { + } + else + { status = MdsValue(serverid, cmd, &ans_d, NULL); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; @@ -123,37 +134,45 @@ static int DoCamMulti(char *routine, char *name, int a, int f, int count, return status; } -int RemCamSetMAXBUF(char *name, int new) { +int RemCamSetMAXBUF(char *name, int new) +{ int serverid = RemoteServerId(); int status = -1; - if (serverid) { + if (serverid) + { struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; sprintf(cmd, "CamSetMAXBUF('%s',%d)", name, new); status = MdsValue(serverid, cmd, &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; - } else + } + else status = -1; } return status; } -int RemCamGetMAXBUF(char *name) { +int RemCamGetMAXBUF(char *name) +{ int serverid = RemoteServerId(); int status = -1; - if (serverid) { + if (serverid) + { struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; sprintf(cmd, "CamGetMAXBUF('%s')", name); status = MdsValue(serverid, cmd, &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; - } else + } + else status = -1; } return status; diff --git a/camshr/RemCamSingle.c b/camshr/RemCamSingle.c index 635c8aa1a7..2082f6c60e 100644 --- a/camshr/RemCamSingle.c +++ b/camshr/RemCamSingle.c @@ -31,14 +31,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. short RemCamLastIosb[4]; -int RemoteServerId() { +int RemoteServerId() +{ static int socket = 0; - if (socket == 0) { + if (socket == 0) + { char *server = getenv("camac_server"); - if (server == 0) { + if (server == 0) + { printf("Set the camac_server environment variable to your camac server " "address\n"); - } else { + } + else + { socket = ConnectToMds(server); if (socket < 0) socket = 0; @@ -50,19 +55,22 @@ int RemoteServerId() { static int CamSingle(char *routine, char *name, int a, int f, void *data, int mem, short *iosb); -#define MakeSingle(locnam, remnam) \ - int locnam(char *name, int a, int f, void *data, int mem, short *iosb) { \ - return CamSingle(#remnam, name, a, f, data, mem, iosb); \ +#define MakeSingle(locnam, remnam) \ + int locnam(char *name, int a, int f, void *data, int mem, short *iosb) \ + { \ + return CamSingle(#remnam, name, a, f, data, mem, iosb); \ } MakeSingle(RemCamPiow, Piow) MakeSingle(RemCamPioQrepw, PioQrepw) - static void getiosb(int serverid, short *iosb) { + static void getiosb(int serverid, short *iosb) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, NULL); if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && - ans_d.dims[0] == 4) { + ans_d.dims[0] == 4) + { memcpy(RemCamLastIosb, ans_d.ptr, 8); if (iosb) memcpy(iosb, ans_d.ptr, 8); @@ -70,7 +78,8 @@ MakeSingle(RemCamPiow, Piow) MakeSingle(RemCamPioQrepw, PioQrepw) free(ans_d.ptr); } -static void getdata(int serverid, void *data) { +static void getdata(int serverid, void *data) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, NULL); @@ -81,11 +90,13 @@ static void getdata(int serverid, void *data) { } static int CamSingle(char *routine, char *name, int a, int f, void *data, - int mem, short *iosb) { + int mem, short *iosb) +{ int serverid = RemoteServerId(); int status = 0; int writeData; - if (serverid) { + if (serverid) + { struct descrip data_d = {8, 0, {0}, 0, 0}; struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; @@ -93,14 +104,18 @@ static int CamSingle(char *routine, char *name, int a, int f, void *data, writeData = (!(f & 0x08)) && (f > 8); sprintf(cmd, "CamSingle('%s','%s',%d,%d,%s,%d,_iosb)", routine, name, a, f, (writeData) ? "_data=$" : "_data", mem); - if (writeData) { + if (writeData) + { data_d.dtype = mem < 24 ? DTYPE_SHORT : DTYPE_LONG; data_d.ptr = data; status = MdsValue(serverid, cmd, &data_d, &ans_d, NULL); - } else { + } + else + { status = MdsValue(serverid, cmd, &ans_d, NULL); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; diff --git a/camshr/SD.h b/camshr/SD.h index fb473782c6..c75821b430 100644 --- a/camshr/SD.h +++ b/camshr/SD.h @@ -3,7 +3,8 @@ #define __SD_H // for Linux on x86 -typedef struct { +typedef struct +{ __u8 code : 7; __u8 valid : 1; @@ -16,7 +17,8 @@ typedef struct { __u8 additional_sense_length; - struct { + struct + { __u8 bdmd : 1; // branch demand present __u8 dsne : 1; // serial demand stack not empty __u8 bdsq : 1; // branch demand sequencer set @@ -27,7 +29,8 @@ typedef struct { __u8 no_q : 1; // module returned Q = 0 } main_status_reg; - struct { + struct + { // 'high' byte __u8 cret : 1; // command type message detected at receiver __u8 timos : 1; // serial time-out diff --git a/camshr/ScsiCamac.h b/camshr/ScsiCamac.h index 4781631d61..c343a1b069 100644 --- a/camshr/ScsiCamac.h +++ b/camshr/ScsiCamac.h @@ -53,73 +53,80 @@ #define QScan 3 #define OpCodeTestUnitReady 0 -#define CDBTestUnitReady(name) \ - struct { \ - char bytes[6]; \ +#define CDBTestUnitReady(name) \ + struct \ + { \ + char bytes[6]; \ } name = {{OpCodeTestUnitReady, 0, 0, 0, 0, 0}} #define OpCodeRequestSense 3 -#define CDBRequestSense(name) \ - struct { \ - char bytes[6]; \ +#define CDBRequestSense(name) \ + struct \ + { \ + char bytes[6]; \ } name = {{OpCodeRequestSense, 0, 0, 0, sizeof(RequestSenseData), 0}} #define OpCodeRegisterAccess 0x0D -#define CDBRegisterAccess(name, addr_l, addr_h) \ - struct { \ - char bytes[6]; \ +#define CDBRegisterAccess(name, addr_l, addr_h) \ + struct \ + { \ + char bytes[6]; \ } name = {{OpCodeRegisterAccess, 0, addr_h, addr_l, 1, 0}} #define OpCodeInquiryCommand 0x12 -#define CDBInquiryCommand(name) \ - struct { \ - char bytes[6]; \ +#define CDBInquiryCommand(name) \ + struct \ + { \ + char bytes[6]; \ } name = {{OpCodeInquiryCommand, 0, 0, 0, sizeof(InquiryData), 0}} #define OpCodeSendDiagnostic 0x1D -#define CDBSendDiagnostic(x) \ +#define CDBSendDiagnostic(x) \ SendDiagnostic x = {OpCodeSendDiagnostic, 0, 0, 1, 0, 0, 0, 0} #define OpCodeSingleCAMAC 0x21 #define OpCodeBlockCAMAC 0xA2 -typedef struct { +typedef struct +{ char bytes[6]; } CamacNonData; #define OpCodeCamacNonDataCommand 0xC1 -#define CDBCamacNonDataCommand(name) \ +#define CDBCamacNonDataCommand(name) \ CamacNonData name = {{OpCodeCamacNonDataCommand, 0, 0, 0, 0, 0}} #define OpCodeCamacDataCommand 0xE1 -#define CDBCamacDataCommand(name) \ - CamacDataCommand name = {OpCodeCamacDataCommand, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - 0, \ - {0, 0, 0}, \ +#define CDBCamacDataCommand(name) \ + CamacDataCommand name = {OpCodeCamacDataCommand, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + 0, \ + {0, 0, 0}, \ 0} #include "ESR.h" -typedef struct { +typedef struct +{ unsigned short status; unsigned short bytcnt; unsigned fill : 24; unsigned char scsi_status; } Iosb; -typedef struct { +typedef struct +{ unsigned short status; unsigned short bytcnt; unsigned x : 1; @@ -135,7 +142,8 @@ typedef struct { unsigned short lbytcnt; } TranslatedIosb; -typedef struct { +typedef struct +{ char scsi_port; char scsi_address; char slot; @@ -146,7 +154,8 @@ typedef struct { #include "RSD.h" // Inquiry Command - page 37 -typedef struct { +typedef struct +{ unsigned device_type : 5; unsigned device_qual : 3; unsigned reserved_1 : 7; @@ -175,7 +184,8 @@ typedef struct { // Send Diagnostic Command - page 41 // CAMAC NAF Specifications - Page 70 -typedef struct { +typedef struct +{ unsigned f : 5; unsigned a : 4; unsigned n : 5; @@ -185,7 +195,8 @@ typedef struct { // Executing Single Transfer Operations - Page 71 // and // Executing Block Transfer Operations - Page 74 -typedef struct { +typedef struct +{ unsigned ignore_x : 1; unsigned bits_16 : 1; unsigned zero1 : 1; @@ -196,7 +207,8 @@ typedef struct { } TransferOp; // Send Diagnostic Command - page 41 -typedef struct { +typedef struct +{ unsigned char opcode; unsigned unitofl : 1; unsigned devofl : 1; @@ -208,7 +220,8 @@ typedef struct { } SendDiagnostic; // Single CAMAC Operation Command - page 42 -typedef struct { +typedef struct +{ unsigned char opcode; unsigned char zero1; unsigned char crate; @@ -219,7 +232,8 @@ typedef struct { } SingleCAMAC; // Block CAMAC Operation Command - page 43 -typedef struct { +typedef struct +{ unsigned char opcode; unsigned char zero1; unsigned char crate; @@ -232,7 +246,8 @@ typedef struct { unsigned char zero2[3]; } BlockCAMAC; -typedef struct { +typedef struct +{ unsigned int opcode; unsigned direction : 1; unsigned disconnect : 1; @@ -262,7 +277,8 @@ typedef struct { #include "SD.h" -typedef struct { +typedef struct +{ Iosb actual_iosb; TranslatedIosb *iosb; int wait; diff --git a/camshr/ScsiSystemStatus.c b/camshr/ScsiSystemStatus.c index 72b6c74943..3621346cb3 100644 --- a/camshr/ScsiSystemStatus.c +++ b/camshr/ScsiSystemStatus.c @@ -52,7 +52,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------- static char *scsimsg = "Attached devices: none"; -int ScsiSystemStatus(void) { +int ScsiSystemStatus(void) +{ char line[80], *pline; int scsiSystemStatus = 0; // assume the worst :( FILE *fp, *fopen(); @@ -60,14 +61,16 @@ int ScsiSystemStatus(void) { if (MSGLVL(FUNCTION_NAME)) printf("ScsiSystemStatus()\n"); - if ((fp = fopen(PROC_FILE, "r")) == NULL) { + if ((fp = fopen(PROC_FILE, "r")) == NULL) + { fprintf(stderr, "can't open '%s' for read\n", PROC_FILE); scsiSystemStatus = 0; goto ScsiSystemStatus_Exit; } pline = &line[0]; - if ((pline = fgets(line, sizeof(line), fp)) != NULL) { + if ((pline = fgets(line, sizeof(line), fp)) != NULL) + { if (strncmp(pline, scsimsg, strlen(scsimsg))) scsiSystemStatus = 1; // something is attached } diff --git a/camshr/add_entry.c b/camshr/add_entry.c index 28308d69f8..af24bd99a2 100644 --- a/camshr/add_entry.c +++ b/camshr/add_entry.c @@ -68,7 +68,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // pointer to a c-string containing a complete entry // output: status //------------------------------------------------------------------------- -int add_entry(int dbType, char *newEntry) { +int add_entry(int dbType, char *newEntry) +{ void *dbptr; // re-usable pointer for dbs int entrySize, i, numOfEntries; int status = SUCCESS; // assume the best @@ -84,17 +85,20 @@ int add_entry(int dbType, char *newEntry) { //-- 'critical section' start //---------------------------- // 'lock' with semaphore - if (lock_file() != SUCCESS) { + if (lock_file() != SUCCESS) + { status = LOCK_ERROR; goto AddEntry_Exit; } // get current number of entries - if ((numOfEntries = get_file_count(dbType)) < 0) { + if ((numOfEntries = get_file_count(dbType)) < 0) + { status = FILE_ERROR; goto AddEntry_Exit; } // cull db specific info - switch (dbType) { + switch (dbType) + { case CTS_DB: dbptr = (void *)CTSdb; entrySize = MODULE_ENTRY; @@ -121,12 +125,14 @@ int add_entry(int dbType, char *newEntry) { // insertion sort if (numOfEntries > 0) // only insert if more than one entry exists already - if (issort(dbptr, numOfEntries + 1, entrySize, compare_str) != 0) { + if (issort(dbptr, numOfEntries + 1, entrySize, compare_str) != 0) + { status = ERROR; goto AddEntry_Exit; } // commit change to file - if (commit_entry(dbType) != SUCCESS) { + if (commit_entry(dbType) != SUCCESS) + { status = COMMIT_ERROR; goto AddEntry_Exit; } @@ -139,7 +145,8 @@ int add_entry(int dbType, char *newEntry) { //---------------------------- AddEntry_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("add_entry(): "); ShowStatus(status); } diff --git a/camshr/bisearch.c b/camshr/bisearch.c index f9d673d645..80deb5be71 100644 --- a/camshr/bisearch.c +++ b/camshr/bisearch.c @@ -67,7 +67,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // entry //------------------------------------------------------------------------- int bisearch(int dbType, const void *target, int size, - int (*compare)(const void *key1, const void *key2)) { + int (*compare)(const void *key1, const void *key2)) +{ void *dbptr; // generic pointer char *candidate, fmt[9]; int left, middle, right; @@ -87,7 +88,8 @@ int bisearch(int dbType, const void *target, int size, left = 0; right = size - 1; - switch (dbType) { + switch (dbType) + { case CTS_DB: dbptr = (void *)CTSdb; entrySize = MODULE_ENTRY; @@ -104,12 +106,14 @@ int bisearch(int dbType, const void *target, int size, candidate = (char *)malloc(entrySize); // allocate memory for item to compare with - while (left <= right) { + while (left <= right) + { middle = (left + right) / 2; if (MSGLVL(8)) printf("middle=%d\n", middle); - switch (dbType) { // [2002.05.15] + switch (dbType) + { // [2002.05.15] case CTS_DB: sprintf(tmp, "%.32s", (char *)(dbptr + @@ -131,7 +135,8 @@ int bisearch(int dbType, const void *target, int size, if (MSGLVL(8)) printf("calling compare('%s', '%s')\n", candidate, (char *)target); - switch (compare(candidate, target)) { + switch (compare(candidate, target)) + { case -1: /***************************************************************** * Prepare to search to the right of the middle index. * diff --git a/camshr/cam_functions.c b/camshr/cam_functions.c index 0fae890b98..87853c3de1 100644 --- a/camshr/cam_functions.c +++ b/camshr/cam_functions.c @@ -131,7 +131,7 @@ static BYTE JorwayModes[2][2][4] = { NO_MODE, NO_MODE}}}; #define JORWAY_DISCONNECT 0 -#define JORWAYMODE(mode, enhanced, multisample) \ +#define JORWAYMODE(mode, enhanced, multisample) \ JorwayModes[multisample][enhanced][mode] #define KSMODE(mode) mode @@ -152,7 +152,8 @@ static int KsSingleIo(CamKey Key, BYTE A, BYTE F, BYTE *Data, BYTE Mem, static int KsMultiIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, TranslatedIosb *iosb, int dmode, int Enhanced); -typedef struct { +typedef struct +{ __u8 code : 7; __u8 valid : 1; @@ -189,8 +190,10 @@ static int Jorway73ATranslateIosb(int datacmd, int reqbytcnt, static int KsTranslateIosb(RequestSenseData *sense, int scsi_status); static int isRemote = -1; -static int checkRemote() { - if (isRemote == -1) { +static int checkRemote() +{ + if (isRemote == -1) + { isRemote = getenv("camac_server") ? 1 : 0; } return isRemote; @@ -224,10 +227,14 @@ extern int RemCamStopw(); extern int RemCamSetMAXBUF(); extern int RemCamGetMAXBUF(); -EXPORT int CamVerbose(int mode) { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { +EXPORT int CamVerbose(int mode) +{ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamVerbose(mode); - } else { + } + else + { Verbose = mode; return 1; } @@ -235,9 +242,12 @@ EXPORT int CamVerbose(int mode) { EXPORT int CamQ(TranslatedIosb *iosb) // CAM$Q_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamQ(iosb); - } else { + } + else + { TranslatedIosb *iosb_use; iosb_use = (iosb) ? iosb : &LastIosb; @@ -255,9 +265,12 @@ EXPORT int CamQ(TranslatedIosb *iosb) // CAM$Q_SCSI() //----------------------------------------------------------- EXPORT int CamX(TranslatedIosb *iosb) // CAM$X_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamX(iosb); - } else { + } + else + { TranslatedIosb *iosb_use; iosb_use = (iosb) ? iosb : &LastIosb; @@ -276,9 +289,12 @@ EXPORT int CamX(TranslatedIosb *iosb) // CAM$X_SCSI() //----------------------------------------------------------- EXPORT int CamXandQ(TranslatedIosb *iosb) // CAM$XANDQ_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamXandQ(iosb); - } else { + } + else + { TranslatedIosb *iosb_use; iosb_use = (iosb) ? iosb : &LastIosb; @@ -298,9 +314,12 @@ EXPORT int CamXandQ(TranslatedIosb *iosb) // CAM$XANDQ_SCSI() //----------------------------------------------------------- EXPORT int CamBytcnt(TranslatedIosb *iosb) // CAM$BYTCNT_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamBytcnt(iosb); - } else { + } + else + { TranslatedIosb *iosb_use; iosb_use = (iosb) ? iosb : &LastIosb; @@ -319,9 +338,12 @@ EXPORT int CamBytcnt(TranslatedIosb *iosb) // CAM$BYTCNT_SCSI() //----------------------------------------------------------- EXPORT int CamStatus(TranslatedIosb *iosb) // CAM$STATUS_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamStatus(iosb); - } else { + } + else + { TranslatedIosb *iosb_use; iosb_use = (iosb) ? iosb : &LastIosb; @@ -336,9 +358,12 @@ EXPORT int CamStatus(TranslatedIosb *iosb) // CAM$STATUS_SCSI() //----------------------------------------------------------- EXPORT int CamGetStat(TranslatedIosb *iosb) // CAM$GET_STAT_SCSI() { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamGetStat(iosb); - } else { + } + else + { *iosb = LastIosb; // printf("CamGetStatus(iosb) ::->> bytecount= %d\n", iosb->bytcnt); // // [2002.12.13] printf("CamGetStatus(LastIosb)::->> bytecount= %d\n", @@ -348,10 +373,14 @@ EXPORT int CamGetStat(TranslatedIosb *iosb) // CAM$GET_STAT_SCSI() } //----------------------------------------------------------- -EXPORT int CamError(int xexp, int qexp, TranslatedIosb *iosb) { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { +EXPORT int CamError(int xexp, int qexp, TranslatedIosb *iosb) +{ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamError(xexp, qexp, iosb); - } else { + } + else + { int xexp_use; int qexp_use; TranslatedIosb *iosb_use; @@ -385,16 +414,19 @@ EXPORT int CamError(int xexp, int qexp, TranslatedIosb *iosb) { //----------------------------------------------------------- #define CallSingleIo(pname, dmode) \ EXPORT int Cam##pname(char *Name, BYTE A, BYTE F, void *Data, BYTE Mem, \ - TranslatedIosb *iosb) { \ + TranslatedIosb *iosb) \ + { \ int status; \ CamKey Key; \ static int debug = -1; \ \ - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { \ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) \ + { \ return RemCam##pname(Name, A, F, Data, Mem, iosb); \ } \ \ - if (debug == -1) { \ + if (debug == -1) \ + { \ char *tmp = getenv("CAM_DEBUG"); \ debug = tmp ? 1 : 0; \ } \ @@ -402,7 +434,8 @@ EXPORT int CamError(int xexp, int qexp, TranslatedIosb *iosb) { printf("Cam" #pname ": name=%s, A=%d, F=%d, data=%d, mem=%d\n", Name, A, \ F, Data ? *(int *)Data : -1, Mem); \ status = CamAssign(Name, &Key); \ - if (status == SUCCESS) { \ + if (status == SUCCESS) \ + { \ status = SingleIo(Key, A, F, Data, Mem, iosb, dmode); \ } \ \ @@ -412,32 +445,36 @@ EXPORT int CamError(int xexp, int qexp, TranslatedIosb *iosb) { //----------------------------------------------------------- // possibly enhanced modes //----------------------------------------------------------- -#define CallMultiIo(pname, dmode, enhanced) \ - EXPORT int Cam##pname(char *Name, BYTE A, BYTE F, int Count, void *Data, \ - BYTE Mem, TranslatedIosb *iosb) { \ - int status; \ - CamKey Key; \ - \ - static int debug = -1; \ - \ - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { \ - return RemCam##pname(Name, A, F, Count, Data, Mem, iosb); \ - } \ - \ - if (debug == -1) { \ - char *tmp = getenv("CAM_DEBUG"); \ - debug = tmp ? 1 : 0; \ - } \ - if (debug) \ - printf("Cam" #pname \ - ": name=%s, A=%d, F=%d, Count=%d, data=%p, mem=%d\n", \ - Name, A, F, Count, Data, Mem); \ - status = CamAssign(Name, &Key); \ - if (status == SUCCESS) { \ - status = MultiIo(Key, A, F, Count, Data, Mem, iosb, dmode, enhanced); \ - } \ - \ - return status; \ +#define CallMultiIo(pname, dmode, enhanced) \ + EXPORT int Cam##pname(char *Name, BYTE A, BYTE F, int Count, void *Data, \ + BYTE Mem, TranslatedIosb *iosb) \ + { \ + int status; \ + CamKey Key; \ + \ + static int debug = -1; \ + \ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) \ + { \ + return RemCam##pname(Name, A, F, Count, Data, Mem, iosb); \ + } \ + \ + if (debug == -1) \ + { \ + char *tmp = getenv("CAM_DEBUG"); \ + debug = tmp ? 1 : 0; \ + } \ + if (debug) \ + printf("Cam" #pname \ + ": name=%s, A=%d, F=%d, Count=%d, data=%p, mem=%d\n", \ + Name, A, F, Count, Data, Mem); \ + status = CamAssign(Name, &Key); \ + if (status == SUCCESS) \ + { \ + status = MultiIo(Key, A, F, Count, Data, Mem, iosb, dmode, enhanced); \ + } \ + \ + return status; \ } //----------------------------------------------------------- @@ -459,17 +496,20 @@ CallSingleIo(Piow, QIgnore) // yields: int = CamPiow( ... ) // : int = CamStopw( ... ) [2001.04.10] //----------------------------------------------------------- static int SingleIo(CamKey Key, BYTE A, BYTE F, BYTE *Data, BYTE Mem, - TranslatedIosb *iosb, int dmode) { + TranslatedIosb *iosb, int dmode) +{ char tmp[9]; int highwayType, status; if (MSGLVL(FUNCTION_NAME)) printf("\033[01;31mSingleIo(F=%d)-->\033[0m", F); sprintf(tmp, "GK%c%d", Key.scsi_port, Key.scsi_address); - if ((status = QueryHighwayType(tmp)) == SUCCESS) { + if ((status = QueryHighwayType(tmp)) == SUCCESS) + { highwayType = NUMERIC(tmp[5]); // extract type - switch (highwayType) { // check highway type + switch (highwayType) + { // check highway type case JORWAY: case JORWAY_OLD: if (MSGLVL(DETAILS)) @@ -525,7 +565,8 @@ CallSingleIo(Piow, QIgnore) // yields: int = CamPiow( ... ) break; } // end of switch() if (MSGLVL(FUNCTION_NAME)) // show data, if there is some - if (Data) { + if (Data) + { if (Mem == 16) printf("\033[01;31mSingleIo(F=%d)-->>%d\033[0m\n", F, *(short *)Data); else @@ -541,7 +582,8 @@ CallSingleIo(Piow, QIgnore) // yields: int = CamPiow( ... ) //----------------------------------------------------------- static int MultiIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, - TranslatedIosb *iosb, int dmode, int Enhanced) { + TranslatedIosb *iosb, int dmode, int Enhanced) +{ char tmp[10]; int highwayType, mode, status; @@ -549,10 +591,12 @@ static int MultiIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, printf("\033[01;31mMultiIo(F=%d, count=%d)-->>\033[0m\n", F, Count); sprintf(tmp, "GK%c%d", Key.scsi_port, Key.scsi_address); - if ((status = QueryHighwayType(tmp)) == SUCCESS) { + if ((status = QueryHighwayType(tmp)) == SUCCESS) + { highwayType = NUMERIC(tmp[5]); // extract type - switch (highwayType) { // check highway type + switch (highwayType) + { // check highway type case JORWAY: case JORWAY_OLD: if (MSGLVL(DETAILS)) @@ -619,7 +663,8 @@ static int MultiIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, } // end of switch() } // end of if() - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { if (!iosb) printf("MultiIo null iosb ptr"); else @@ -631,7 +676,8 @@ static int MultiIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, //----------------------------------------------------------- static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, - BYTE Mem, TranslatedIosb *iosb, int dmode, int Enhanced) { + BYTE Mem, TranslatedIosb *iosb, int dmode, int Enhanced) +{ char dev_name[12]; int IsDataCommand, scsiDevice; int status; @@ -653,7 +699,8 @@ static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, // [2002.12.13] sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, Key.crate); - if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) { + if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) + { if (MSGLVL(IMPORTANT)) fprintf(stderr, "%s(): error -- no scsi device found for '%s'\n", J_ROUTINE_NAME, dev_name); @@ -672,7 +719,8 @@ static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, IsDataCommand = (F & 0x08) ? FALSE : TRUE; - if (IsDataCommand) { + if (IsDataCommand) + { union { BYTE b[4]; unsigned int l; @@ -706,7 +754,9 @@ static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, cmd = (unsigned char *)&DATAcommand; cmdlen = sizeof(DATAcommand); direction = (F < 8) ? 1 : 2; - } else { + } + else + { NONDATAcommand.bytes[1] = F; NONDATAcommand.bytes[2] = Key.slot; NONDATAcommand.bytes[3] = A; @@ -729,7 +779,8 @@ static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, *iosb = LastIosb; // [2002.12.11] JorwayDoIo_Exit: - if (MSGLVL(DETAILS) && (cmd != NULL)) { + if (MSGLVL(DETAILS) && (cmd != NULL)) + { printf("%s(): iosb->status [0x%x]\n", J_ROUTINE_NAME, iosb->status); printf("%s(): iosb->x [0x%x]\n", J_ROUTINE_NAME, iosb->x); printf("%s(): iosb->q [0x%x]\n", J_ROUTINE_NAME, iosb->q); @@ -746,7 +797,8 @@ static int JorwayDoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, //----------------------------------------------------------- static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, BYTE Mem, TranslatedIosb *iosb, int dmode, - int Enhanced __attribute__((unused))) { + int Enhanced __attribute__((unused))) +{ char dev_name[12]; int IsDataCommand, scsiDevice; int status; @@ -760,7 +812,8 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, int online; int enhanced; - struct { + struct + { __u8 opcode; __u8 f : 5; @@ -776,7 +829,8 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, __u8 transfer_len; __u8 zero2; } NONDATAcommand = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - struct { + struct + { __u8 opcode; __u8 f : 5; @@ -792,7 +846,8 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, __u8 transfer_len; __u8 zero2; } ShortDATAcommand = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - struct { + struct + { __u8 opcode; __u8 zero1 : 5; @@ -820,7 +875,8 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, // [2002.12.13] sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, Key.crate); - if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) { + if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < 0) + { if (MSGLVL(IMPORTANT)) fprintf(stderr, "%s(): error -- no scsi device found for '%s'\n", J_ROUTINE_NAME, dev_name); @@ -831,7 +887,8 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, if (!online && Key.slot != 30) return CamOFFLINE; - if (online && Key.slot == 30 && F == 1 && A == 0) { + if (online && Key.slot == 30 && F == 1 && A == 0) + { *(short *)Data = 0x30; return CamDONE_Q; } @@ -841,14 +898,16 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, IsDataCommand = (F & 0x08) ? FALSE : TRUE; - if (IsDataCommand) { + if (IsDataCommand) + { union { BYTE b[4]; unsigned int l; } transfer_len; reqbytcnt = transfer_len.l = Count * ((Mem == 24) ? 4 : 2); direction = (F < 8) ? 1 : 2; - if (reqbytcnt < 256) { + if (reqbytcnt < 256) + { cmd = (unsigned char *)&ShortDATAcommand; cmdlen = sizeof(ShortDATAcommand); ShortDATAcommand.f = F; @@ -857,7 +916,9 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, ShortDATAcommand.m = Count > 1 ? modes[dmode] : singlemodes[dmode]; ShortDATAcommand.a = A; ShortDATAcommand.transfer_len = transfer_len.l; - } else { + } + else + { cmd = (unsigned char *)&LongDATAcommand; cmdlen = sizeof(LongDATAcommand); LongDATAcommand.f = F; @@ -869,7 +930,9 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, LongDATAcommand.transfer_len[1] = transfer_len.b[1]; LongDATAcommand.transfer_len[2] = transfer_len.b[0]; } - } else { + } + else + { NONDATAcommand.f = F; NONDATAcommand.n = Key.slot; NONDATAcommand.a = A; @@ -887,15 +950,19 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, *iosb = LastIosb; // [2002.12.11] Jorway73ADoIo_Exit: - if (MSGLVL(FUNCTION_NAME + 1) && (cmd != NULL)) { + if (MSGLVL(FUNCTION_NAME + 1) && (cmd != NULL)) + { // This is only rough - depends on the nature of the "overloaded" vars printf("scsi_mode opcode=%d, dmode=%d, modes[dmode]=%d, [1]=%d, [3]=%d, " "[5]=%d [7]=%d\n", cmd[0], dmode, modes[dmode], cmd[1], cmd[3], cmd[5], cmd[7]); - if (!iosb) { + if (!iosb) + { printf("Jorway73ADoIo_Exit: Null pointer to iosb\n"); - } else { + } + else + { printf("%s(): iosb->status [0x%x]\n", J_ROUTINE_NAME, iosb->status); printf("%s(): iosb->x [0x%x]\n", J_ROUTINE_NAME, iosb->x); printf("%s(): iosb->q [0x%x]\n", J_ROUTINE_NAME, iosb->q); @@ -921,20 +988,25 @@ static int Jorway73ADoIo(CamKey Key, BYTE A, BYTE F, int Count, BYTE *Data, //----------------------------------------------------------- // derive module address parameters //----------------------------------------------------------- -static int CamAssign(char *Name, CamKey *Key) { +static int CamAssign(char *Name, CamKey *Key) +{ static char ha; // NB! these must be static, or else doesn't work static int id, crate, slot; // NB! these must be static, or else doesn't work int status; - if (strchr(Name, ':')) { // physical names contain a ':' + if (strchr(Name, ':')) + { // physical names contain a ':' str2upcase(Name); sscanf(Name, "GK%1s%1d%2d:N%d", &ha, &id, &crate, &slot); Key->scsi_port = ha; Key->scsi_address = id; Key->crate = crate; Key->slot = slot; - } else { // ... logical module name does not - if ((status = xlate_logicalname(Name, Key)) != SUCCESS) { + } + else + { // ... logical module name does not + if ((status = xlate_logicalname(Name, Key)) != SUCCESS) + { status = LibNOTFOU; goto CamAssign_Exit; } @@ -955,7 +1027,8 @@ static int CamAssign(char *Name, CamKey *Key) { // extract CAMAC status info for Jorway highways //----------------------------------------------------------- static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, - unsigned int ret_bytcnt, int scsi_status) { + unsigned int ret_bytcnt, int scsi_status) +{ int status; int bytcnt = reqbytcnt - ((int)sense->word_count_defect[2]) + (((int)sense->word_count_defect[1]) << 8) + @@ -976,31 +1049,40 @@ static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, if (MSGLVL(FUNCTION_NAME)) printf("%s()\n", JT_ROUTINE_NAME); - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("%s(): scsi status 0x%x\n", JT_ROUTINE_NAME, scsi_status); } LastIosb.q = !sense->main_status_reg.no_q; LastIosb.x = !sense->main_status_reg.no_x; status = CamSERTRAERR; - switch (scsi_status) { + switch (scsi_status) + { case 0: status = 1; break; - case 1: { - switch (sense->sense_key) { + case 1: + { + switch (sense->sense_key) + { case SENSE_HARDWARE_ERROR: - if (sense->additional_sense_code == SENSE2_NOX) { + if (sense->additional_sense_code == SENSE2_NOX) + { LastIosb.q = 0; LastIosb.x = 0; if (sense->main_status_reg.snex) status = CamSCCFAIL; else status = CamDONE_NOX; - } else if (sense->additional_sense_code == SENSE2_NOQ) { + } + else if (sense->additional_sense_code == SENSE2_NOQ) + { LastIosb.q = 0; status = CamDONE_NOQ; - } else { + } + else + { LastIosb.err = 1; LastIosb.tmo = sense->main_status_reg.to | sense->serial_status_reg.timos; @@ -1031,7 +1113,8 @@ static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, status = CamDONE_Q; break; } - } break; + } + break; case 2: if (!LastIosb.x) status = CamDONE_NOX; @@ -1042,8 +1125,10 @@ static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, break; } LastIosb.status = (unsigned short)status & 0xffff; - if (Verbose || status == CamSERTRAERR) { - if (status == CamSERTRAERR) { + if (Verbose || status == CamSERTRAERR) + { + if (status == CamSERTRAERR) + { printf( "Serial Transmission Error detected, debug information follows \n\n" "******************************************************************" @@ -1081,7 +1166,8 @@ static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, printf(" Additional Sense Code=%d,slot=%d,crate=%d\n\n", sense->additional_sense_code, sense->slot_high_bit * 16 + sense->slot, sense->crate); - if (status == CamSERTRAERR) { + if (status == CamSERTRAERR) + { printf("*****************************************************************" "*\n\n"); } @@ -1092,14 +1178,16 @@ static int JorwayTranslateIosb(int reqbytcnt, SenseData *sense, char sensretlen, // extract CAMAC status info for Jorway highways //----------------------------------------------------------- static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, - J73ASenseData *sense, int scsi_status) { + J73ASenseData *sense, int scsi_status) +{ int status; int bytcnt = reqbytcnt - (int)(((unsigned int)sense->DMA_byte_count[2]) + (((unsigned int)sense->DMA_byte_count[1]) << 8) + (((unsigned int)sense->DMA_byte_count[0]) << 16)); - if (Verbose) { + if (Verbose) + { printf("SCSI Sense data: code=%d,valid=%d,sense_key=%d,DMA byte count=%d, " "additonal sense code=%d\n\n", sense->code, sense->valid, sense->sense_key, bytcnt, @@ -1139,8 +1227,10 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, LastIosb.bytcnt = (unsigned short)(bytcnt & 0xffff); LastIosb.lbytcnt = (unsigned short)(bytcnt >> 16); status = CamSCCFAIL; - if (isdatacmd) { - switch (scsi_status) { + if (isdatacmd) + { + switch (scsi_status) + { case 0: LastIosb.x = 1; LastIosb.q = 1; @@ -1156,10 +1246,12 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, case 1: LastIosb.x = sense->additional_sense_code != 0x44; if (sense->sense_key == 9 || - (sense->sense_key == 4 && sense->additional_sense_code == 0)) { + (sense->sense_key == 4 && sense->additional_sense_code == 0)) + { LastIosb.q = 0; status = CamDONE_NOQ; - } else + } + else LastIosb.q = sense->additional_sense_code != 0x80; LastIosb.err = 0; LastIosb.lpe = sense->additional_sense_code == 0x47; @@ -1168,7 +1260,8 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, LastIosb.tmo = 0; LastIosb.adnr = sense->additional_sense_code == 0x4; LastIosb.list = 0; - switch (sense->additional_sense_code) { + switch (sense->additional_sense_code) + { case 0x44: status = CamDONE_NOX; break; @@ -1178,8 +1271,11 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, } break; } - } else { - switch (scsi_status) { + } + else + { + switch (scsi_status) + { case 0: LastIosb.x = 1; LastIosb.q = 0; @@ -1202,7 +1298,8 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, LastIosb.tmo = 0; LastIosb.adnr = sense->additional_sense_code == 0x4; LastIosb.list = 0; - switch (sense->additional_sense_code) { + switch (sense->additional_sense_code) + { case 0x44: status = CamDONE_NOX; break; @@ -1239,63 +1336,84 @@ static int Jorway73ATranslateIosb(int isdatacmd, int reqbytcnt, //----------------------------------------------------------- //----------------------------------------------------------- -static void str2upcase(char *str) { +static void str2upcase(char *str) +{ char *ptr; ptr = str; - while (*ptr) { + while (*ptr) + { *ptr = toupper(*ptr); ptr++; } } //----------------------------------------------------------- -static int NOT_SUPPORTED() { +static int NOT_SUPPORTED() +{ printf("reference to unsupported call made\n"); return FAILURE; } -EXPORT int CamSetMAXBUF(char *Name, int new) { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { +EXPORT int CamSetMAXBUF(char *Name, int new) +{ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamSetMAXBUF(Name, new); - } else { + } + else + { int scsiDevice, enhanced, online; CamKey Key; int status = CamAssign(Name, &Key); - if (status & 1) { + if (status & 1) + { char dev_name[12]; sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, Key.crate); if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < - 0) { + 0) + { return -1; - } else + } + else return SGSetMAXBUF(scsiDevice, new); - } else { + } + else + { printf("Module: %s not defined\n", Name); return -1; } } } -EXPORT int CamGetMAXBUF(char *Name) { - if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) { +EXPORT int CamGetMAXBUF(char *Name) +{ + if ((isRemote == 1 || (isRemote == -1 && checkRemote()))) + { return RemCamGetMAXBUF(Name); - } else { + } + else + { int scsiDevice, enhanced, online; CamKey Key; int status = CamAssign(Name, &Key); - if (status & 1) { + if (status & 1) + { char dev_name[12]; sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, Key.crate); if ((scsiDevice = get_scsi_device_number(dev_name, &enhanced, &online)) < - 0) { + 0) + { return -1; - } else + } + else return SGGetMAXBUF(scsiDevice); - } else { + } + else + { printf("Module: %s not defined\n", Name); return -1; } diff --git a/camshr/check_for_file.c b/camshr/check_for_file.c index 1b07e61095..9e55782a8c 100644 --- a/camshr/check_for_file.c +++ b/camshr/check_for_file.c @@ -64,14 +64,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: file to check // output: status (ie SUCCESS or ERROR) //------------------------------------------------------------------------- -int check_for_file(char *FileName) { +int check_for_file(char *FileName) +{ int fd, status; if (MSGLVL(FUNCTION_NAME)) printf("check_for_file('%s')\n", FileName); - if ((fd = Open(FileName, O_RDONLY)) < 0) { // file does not exist, yet - status = FILE_ERROR; // :< + if ((fd = Open(FileName, O_RDONLY)) < 0) + { // file does not exist, yet + status = FILE_ERROR; // :< goto Filecheck_Exit; } // things are good ! @@ -79,7 +81,8 @@ int check_for_file(char *FileName) { status = SUCCESS; // :> Filecheck_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("check_for_file('%s'): ", FileName); ShowStatus(status); } diff --git a/camshr/check_sema4.c b/camshr/check_sema4.c index cc15da5eb3..c288cdfb21 100644 --- a/camshr/check_sema4.c +++ b/camshr/check_sema4.c @@ -76,7 +76,8 @@ union semun { // output: semaphore count // NB! count should be zero for success (ie binary semaphore) //------------------------------------------------------------------------- -int check_sema4() { +int check_sema4() +{ int count; union semun u; diff --git a/camshr/commit_entry.c b/camshr/commit_entry.c index 333b6b7c8e..678ca780d4 100644 --- a/camshr/commit_entry.c +++ b/camshr/commit_entry.c @@ -65,7 +65,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: db file type // output: status //------------------------------------------------------------------------- -int commit_entry(int dbType) { +int commit_entry(int dbType) +{ void *dbptr; // generic pointer to dbs int status = SUCCESS; // assume the best extern struct MODULE *CTSdb; // pointer to in-memory copy of data file @@ -74,7 +75,8 @@ int commit_entry(int dbType) { if (MSGLVL(FUNCTION_NAME)) printf("commit_entry()\n"); - switch (dbType) { + switch (dbType) + { case CTS_DB: dbptr = (void *)CTSdb; break; @@ -91,7 +93,8 @@ int commit_entry(int dbType) { if (msync(dbptr, 0, MS_SYNC | MS_INVALIDATE) == ERROR) status = COMMIT_ERROR; - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("commit_entry(): "); ShowStatus(status); } diff --git a/camshr/common.h b/camshr/common.h index 54fb0eb2c3..412bc19222 100644 --- a/camshr/common.h +++ b/camshr/common.h @@ -28,7 +28,8 @@ #define FAILURE 0 // MSGLVL() values -enum { +enum +{ ALWAYS = 1, // ... well, almost always -- for debug printout IMPORTANT, // not fatal FUNCTION_NAME = 5, @@ -43,10 +44,26 @@ enum { #define FALSE 0 #define TRUE 1 -enum { TO_CAMAC, FROM_CAMAC }; // ie WRITE and READ -enum { STATUS_BAD, STATUS_GOOD }; -enum { CTS_DB, CRATE_DB }; -enum { OFF, ON }; // crate offline/online command +enum +{ + TO_CAMAC, + FROM_CAMAC +}; // ie WRITE and READ +enum +{ + STATUS_BAD, + STATUS_GOOD +}; +enum +{ + CTS_DB, + CRATE_DB +}; +enum +{ + OFF, + ON +}; // crate offline/online command // semaphore values #define P_SEMA4 -1 diff --git a/camshr/compare_str.c b/camshr/compare_str.c index 011085e473..8b26c26d3c 100644 --- a/camshr/compare_str.c +++ b/camshr/compare_str.c @@ -75,7 +75,8 @@ static int strncmp_nocase(const char *s, const char *t, int n); // 0 for equal, // +1 for first greater than second //------------------------------------------------------------------------- -int compare_str(const void *key1, const void *key2) { +int compare_str(const void *key1, const void *key2) +{ int length, retval; if (MSGLVL(11)) // v v v v @@ -85,17 +86,22 @@ int compare_str(const void *key1, const void *key2) { length = (strlen(key1) >= strlen(key2)) ? strlen(key1) : strlen(key2); if ((retval = strncmp_nocase((const char *)key1, (const char *)key2, - length)) > 0) { + length)) > 0) + { if (MSGLVL(8)) printf("comp(): key1 > key2\n"); return 1; - } else if (retval < 0) { + } + else if (retval < 0) + { if (MSGLVL(8)) printf("comp(): key1 < key2\n"); return -1; - } else { + } + else + { if (MSGLVL(8)) printf("comp(): key1 == key2\n"); @@ -107,14 +113,16 @@ int compare_str(const void *key1, const void *key2) { // same as 'strncmp()' but ignores case // (shamelessly copied from other mdsplus code) //------------------------------------------------------------------------- -static int strncmp_nocase(const char *s, const char *t, int n) { +static int strncmp_nocase(const char *s, const char *t, int n) +{ int i = 0; if (MSGLVL(11)) printf("string sizes: *s(%d) *t(%d) n(%d)\n", (int)strlen(s), (int)strlen(t), n); - for (; n; n--, s++, t++) { + for (; n; n--, s++, t++) + { if (MSGLVL(11)) printf("*s='%c' *t='%c' n=%d\n", *s, *t, n); diff --git a/camshr/contract_db.c b/camshr/contract_db.c index 3067d8379f..8ec4474d50 100644 --- a/camshr/contract_db.c +++ b/camshr/contract_db.c @@ -64,7 +64,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // current number of entries in CTS data file // output: status //------------------------------------------------------------------------- -int contract_db(int dbType, int numOfEntries) { +int contract_db(int dbType, int numOfEntries) +{ char *FileName; int FileIncr, newCount; int status = SUCCESS; // optimistic, aren't we ... :> @@ -75,7 +76,8 @@ int contract_db(int dbType, int numOfEntries) { printf("contract_db()\n"); // assimilate db specific information ... - switch (dbType) { + switch (dbType) + { case CTS_DB: FileName = CTS_DB_FILE; FileIncr = CTS_DB_INCREMENT; @@ -94,23 +96,28 @@ int contract_db(int dbType, int numOfEntries) { newCount = (((int)numOfEntries / FileIncr) + 1) * FileIncr; // create a TMP file - if ((status = create_tmp_file(dbType, newCount, tmpfile)) != SUCCESS) { + if ((status = create_tmp_file(dbType, newCount, tmpfile)) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error creating TMP file\n"); goto ContractDB_Exit; } // only need to copy old data if there is any - if (numOfEntries) { // copy current db file to TMP file - if ((status = copy(dbType, FileName, tmpfile, numOfEntries)) != SUCCESS) { + if (numOfEntries) + { // copy current db file to TMP file + if ((status = copy(dbType, FileName, tmpfile, numOfEntries)) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error copying db to TMP file\n"); goto ContractDB_Exit; } // remove old db file - if (Remove(FileName)) { // non-zero is an error - if (MSGLVL(ALWAYS)) { + if (Remove(FileName)) + { // non-zero is an error + if (MSGLVL(ALWAYS)) + { fprintf(stderr, "error removing old db file\n"); perror("remove()"); } @@ -120,8 +127,10 @@ int contract_db(int dbType, int numOfEntries) { } } - if (rename(tmpfile, get_file_name(FileName))) { // non-zero is an error - if (MSGLVL(ALWAYS)) { + if (rename(tmpfile, get_file_name(FileName))) + { // non-zero is an error + if (MSGLVL(ALWAYS)) + { fprintf(stderr, "error renaming temp db file\n"); perror("rename()"); } @@ -131,7 +140,8 @@ int contract_db(int dbType, int numOfEntries) { } chmod(get_file_name(FileName), O666); // re-map file - if (map_data_file(dbType) != SUCCESS) { + if (map_data_file(dbType) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "unable to map contracted file\n"); @@ -140,7 +150,8 @@ int contract_db(int dbType, int numOfEntries) { } ContractDB_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("contract_db('%s'): ", get_file_name(FileName)); ShowStatus(status); } diff --git a/camshr/copy.c b/camshr/copy.c index d38af2266b..edd37d5ebe 100644 --- a/camshr/copy.c +++ b/camshr/copy.c @@ -69,7 +69,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // number of items to copy // output: status //------------------------------------------------------------------------- -int copy(int dbType, char *inFile, char *outFile, int count) { +int copy(int dbType, char *inFile, char *outFile, int count) +{ int Read_fd, Write_fd; int entrySize, i; int status = SUCCESS; // optimistic @@ -78,7 +79,8 @@ int copy(int dbType, char *inFile, char *outFile, int count) { printf("copy()\n"); // get a read file descriptor - if ((Read_fd = Open(inFile, O_RDONLY)) == -1) { + if ((Read_fd = Open(inFile, O_RDONLY)) == -1) + { if (MSGLVL(ALWAYS)) perror("open(rd)"); @@ -86,7 +88,8 @@ int copy(int dbType, char *inFile, char *outFile, int count) { goto Copy_Exit_1; } // get a write file descriptor - if ((Write_fd = open(outFile, O_WRONLY)) == -1) { + if ((Write_fd = open(outFile, O_WRONLY)) == -1) + { printf("Error opening %s\n", outFile); perror("open(wr)"); @@ -94,7 +97,8 @@ int copy(int dbType, char *inFile, char *outFile, int count) { goto Copy_Exit_2; } // figure out size - switch (dbType) { + switch (dbType) + { case CTS_DB: entrySize = MODULE_ENTRY; break; @@ -111,9 +115,11 @@ int copy(int dbType, char *inFile, char *outFile, int count) { char line[entrySize]; // read 'n write ... - for (i = 0; i < count; ++i) { + for (i = 0; i < count; ++i) + { // read ... - if (read(Read_fd, line, entrySize) != entrySize) { + if (read(Read_fd, line, entrySize) != entrySize) + { if (MSGLVL(ALWAYS)) perror("read()"); @@ -121,7 +127,8 @@ int copy(int dbType, char *inFile, char *outFile, int count) { goto Copy_Exit_3; } // ... then write - if (write(Write_fd, line, entrySize) != entrySize) { + if (write(Write_fd, line, entrySize) != entrySize) + { if (MSGLVL(ALWAYS)) perror("write()"); @@ -140,7 +147,8 @@ int copy(int dbType, char *inFile, char *outFile, int count) { close(Read_fd); Copy_Exit_1: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("copy(): "); ShowStatus(status); } diff --git a/camshr/crate.h b/camshr/crate.h index eda19aadfc..7254ea2f76 100644 --- a/camshr/crate.h +++ b/camshr/crate.h @@ -24,7 +24,8 @@ //------------------------------------------------------------------------- //------------------------------------------------------------------------- -struct CRATE_NAME { +struct CRATE_NAME +{ // physical CAMAC crate name char prefix[2]; // 'GK' <<-- fixed characters @@ -36,23 +37,25 @@ struct CRATE_NAME { char Crate[2]; // 01, 02, ..., 99 (NB! this field is two chars) }; -struct CRATE { +struct CRATE +{ struct CRATE_NAME Phys_Name; // e.g. GKA109 char r1; // ':' - char DSFname[3]; // devive special file name, eg '/dev/sg#', eg 001 - char r2; // ':' - char HwyType; // e.g. Jorway, KineticSystems - char r3; // ':' - char enhanced; // '1'=enhanced '0'=not - char r4; // ':' - char online; // '1'=online '0'=not - char r5; // room for '\n' + char DSFname[3]; // devive special file name, eg '/dev/sg#', eg 001 + char r2; // ':' + char HwyType; // e.g. Jorway, KineticSystems + char r3; // ':' + char enhanced; // '1'=enhanced '0'=not + char r4; // ':' + char online; // '1'=online '0'=not + char r5; // room for '\n' }; #define CRATE_ENTRY sizeof(struct CRATE) //------------------------------------------------------------------------- // internal structure -typedef struct Crate_ { +typedef struct Crate_ +{ char name[7]; int device; int type; diff --git a/camshr/create_sema4.c b/camshr/create_sema4.c index 81345aa2db..74d0cbba0c 100644 --- a/camshr/create_sema4.c +++ b/camshr/create_sema4.c @@ -81,7 +81,8 @@ int sema4Exists = FALSE; // initially doesn't exist // input: none // output: SUCCESS, otherwise fatal error //------------------------------------------------------------------------- -int create_sema4() { +int create_sema4() +{ key_t key; union semun arg; @@ -91,18 +92,21 @@ int create_sema4() { printf("create_sema4()\n"); // obtain a key - if ((key = ftok(SEMAPHORE_KEY_SEED, 'A')) == ERROR) { + if ((key = ftok(SEMAPHORE_KEY_SEED, 'A')) == ERROR) + { perror("ftok(create_sema4)"); exit(-1); // fatal error !!! } // get a semaphore id - if ((semid = semget(key, 1, 0666 | IPC_CREAT)) == ERROR) { + if ((semid = semget(key, 1, 0666 | IPC_CREAT)) == ERROR) + { perror("semget(create_sema4)"); exit(-2); // fatal error !!! } // create semaphore and initialize it arg.val = 1; - if (semctl(semid, 0, SETVAL, arg) == ERROR) { + if (semctl(semid, 0, SETVAL, arg) == ERROR) + { perror("semctl(create_asema4)"); exit(-3); // fatal error !!! } diff --git a/camshr/create_tmp_file.c b/camshr/create_tmp_file.c index 76c5694ed2..4fea555f6f 100644 --- a/camshr/create_tmp_file.c +++ b/camshr/create_tmp_file.c @@ -67,15 +67,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: db type, number of place holders // output: status //------------------------------------------------------------------------- -int create_tmp_file(int dbType, int count, char *filename) { +int create_tmp_file(int dbType, int count, char *filename) +{ char fmt[10]; int entrySize, fd, i, status = SUCCESS; if (MSGLVL(FUNCTION_NAME)) printf("create_tmp_file()\n"); - if ((fd = mkstemp(filename)) == -1) { - if (MSGLVL(ALWAYS)) { + if ((fd = mkstemp(filename)) == -1) + { + if (MSGLVL(ALWAYS)) + { fprintf(stderr, "create_tmp_file(): file error %d\n", fd); perror("creat()"); } @@ -85,7 +88,8 @@ int create_tmp_file(int dbType, int count, char *filename) { } chmod(filename, 0666); // figure out size of each entry - switch (dbType) { + switch (dbType) + { case CTS_DB: entrySize = MODULE_ENTRY; break; @@ -108,8 +112,10 @@ int create_tmp_file(int dbType, int count, char *filename) { // 'blank' entry sprintf(line, fmt, " "); - for (i = 0; i < count; ++i) { - if (write(fd, line, entrySize) != entrySize) { + for (i = 0; i < count; ++i) + { + if (write(fd, line, entrySize) != entrySize) + { if (MSGLVL(ALWAYS)) perror("write()"); @@ -122,7 +128,8 @@ int create_tmp_file(int dbType, int count, char *filename) { close(fd); // only get here if all is OK CreateTmpFile_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("create_tmp_file(): "); ShowStatus(status); } diff --git a/camshr/debug.c b/camshr/debug.c index 46e3cd505a..1ccb57ef2a 100644 --- a/camshr/debug.c +++ b/camshr/debug.c @@ -56,7 +56,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // debug functions //************************************************************************* //************************************************************************* -void dump_db(int count) { +void dump_db(int count) +{ int i; extern struct MODULE *CTSdb; @@ -68,10 +69,12 @@ void dump_db(int count) { //------------------------------------------------------------------------- // display error messages for diagnostics purposes //------------------------------------------------------------------------- -void ShowStatus(int statcode) { +void ShowStatus(int statcode) +{ #if 1 // various status conditions - switch (statcode) { + switch (statcode) + { // good things :-) case SUCCESS: printf("SUCCESS !!!\n"); @@ -142,7 +145,8 @@ void ShowStatus(int statcode) { //------------------------------------------------------------------------- // runs once, on startup. MSGLVL = 0, displays library version //------------------------------------------------------------------------- -void _init() { +void _init() +{ char base[] = "libCamShr.so"; char file[64]; char *pDIR; @@ -156,17 +160,21 @@ void _init() { CTSdbFileIsMapped = FALSE; // initial state [2002.01.03] CRATEdbFileIsMapped = FALSE; // initial state [2002.01.03] - if (MSGLVL(0)) { + if (MSGLVL(0)) + { pDIR = getenv("MDSPLUS_DIR"); - while (!major_done) { + while (!major_done) + { sprintf(file, "%s/lib/%s.%d", pDIR, base, major); if (stat(file, &sbuf) == -1) ++major; - else { + else + { major_done = 1; - while (!minor_done) { + while (!minor_done) + { sprintf(file, "%s/lib/%s.%d.%d", pDIR, base, major, minor); if (stat(file, &sbuf) == -1) ++minor; diff --git a/camshr/expand_db.c b/camshr/expand_db.c index 00b36ce222..51d44e181f 100644 --- a/camshr/expand_db.c +++ b/camshr/expand_db.c @@ -65,7 +65,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // current number of entries in CTS data file // output: status //------------------------------------------------------------------------- -int expand_db(int dbType, int numOfEntries) { +int expand_db(int dbType, int numOfEntries) +{ char *FileName; int FileIncr, newCount; int status = SUCCESS; // optimistic, aren't we ... :> @@ -75,7 +76,8 @@ int expand_db(int dbType, int numOfEntries) { printf("expand_db()\n"); // assimilate db specific information ... - switch (dbType) { + switch (dbType) + { case CTS_DB: FileName = CTS_DB_FILE; FileIncr = CTS_DB_INCREMENT; @@ -94,23 +96,28 @@ int expand_db(int dbType, int numOfEntries) { newCount = (((int)numOfEntries / FileIncr) + 1) * FileIncr; // create a TMP file - if ((status = create_tmp_file(dbType, newCount, tmpfile)) != SUCCESS) { + if ((status = create_tmp_file(dbType, newCount, tmpfile)) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error creating TMP file\n"); goto ExpandDB_Exit; } // only need to copy old data if there is any - if (numOfEntries) { // copy current db file to TMP file - if ((status = copy(dbType, FileName, tmpfile, numOfEntries)) != SUCCESS) { + if (numOfEntries) + { // copy current db file to TMP file + if ((status = copy(dbType, FileName, tmpfile, numOfEntries)) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error copying db to TMP file\n"); goto ExpandDB_Exit; } // remove old db file - if (Remove(FileName)) { // non-zero is an error - if (MSGLVL(ALWAYS)) { + if (Remove(FileName)) + { // non-zero is an error + if (MSGLVL(ALWAYS)) + { fprintf(stderr, "error removing old db file\n"); perror("remove()"); } @@ -120,8 +127,10 @@ int expand_db(int dbType, int numOfEntries) { } } - if (rename(tmpfile, get_file_name(FileName))) { // non-zero is an error - if (MSGLVL(ALWAYS)) { + if (rename(tmpfile, get_file_name(FileName))) + { // non-zero is an error + if (MSGLVL(ALWAYS)) + { fprintf(stderr, "error renaming temp db file\n"); perror("rename()"); } @@ -131,7 +140,8 @@ int expand_db(int dbType, int numOfEntries) { } chmod(get_file_name(FileName), 0666); // re-map file - if (map_data_file(dbType) != SUCCESS) { + if (map_data_file(dbType) != SUCCESS) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "unable to map expanded file\n"); @@ -140,7 +150,8 @@ int expand_db(int dbType, int numOfEntries) { } ExpandDB_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("expand_db('%s'): ", get_file_name(FileName)); ShowStatus(status); } diff --git a/camshr/get_crate_status.c b/camshr/get_crate_status.c index 5fd47257ce..538e59b01b 100644 --- a/camshr/get_crate_status.c +++ b/camshr/get_crate_status.c @@ -51,7 +51,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Fri Aug 24 15:59:54 EDT 2001 -- fixed powered off condition (???) // Mon Aug 27 11:26:10 EDT 2001 -- re-fixed (?) powered off condition //----------------------------------------------------------- -int get_crate_status(char *crate_name, int *ptr_crate_status) { +int get_crate_status(char *crate_name, int *ptr_crate_status) +{ char controller[11]; short SCCdata; int status = SUCCESS; // optimistic ... diff --git a/camshr/get_db_file_size.c b/camshr/get_db_file_size.c index 48967f5cf9..536cf2b549 100644 --- a/camshr/get_db_file_size.c +++ b/camshr/get_db_file_size.c @@ -64,17 +64,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: name of file // output: return the size of the db file, or error //------------------------------------------------------------------------- -int get_db_file_size(char *FileName) { +int get_db_file_size(char *FileName) +{ int retval; struct stat sbuf; if (MSGLVL(FUNCTION_NAME)) printf("get_db_file_size('%s')\n", FileName); - if (Stat(FileName, &sbuf) == ERROR) { + if (Stat(FileName, &sbuf) == ERROR) + { perror("stat()"); retval = FAILURE; // error code is negative and odd - } else + } + else retval = sbuf.st_size; if (MSGLVL(DETAILS)) diff --git a/camshr/get_file_count.c b/camshr/get_file_count.c index 4960f50280..1bf8bca9ca 100644 --- a/camshr/get_file_count.c +++ b/camshr/get_file_count.c @@ -70,7 +70,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: db type // output: number of entries [0..n]; FILE_ERROR [-2 * 2] if error //------------------------------------------------------------------------- -int get_file_count(int dbType) { +int get_file_count(int dbType) +{ void *dbptr; // generic pointer to struct's char dbFileName[16]; int dbFileSize, entrySize, i, numOfEntries; @@ -80,7 +81,8 @@ int get_file_count(int dbType) { extern int CTSdbFileIsMapped; extern int CRATEdbFileIsMapped; - switch (dbType) { + switch (dbType) + { case CTS_DB: dbptr = (void *)CTSdb; entrySize = MODULE_ENTRY; @@ -103,20 +105,24 @@ int get_file_count(int dbType) { printf("get_file_count()\n"); // check for memory mapped file - if (*FileIsMapped == FALSE) { - if (map_data_file(dbType) != SUCCESS) { + if (*FileIsMapped == FALSE) + { + if (map_data_file(dbType) != SUCCESS) + { numOfEntries = MAP_ERROR; goto GetFileCount_Exit; } } // get total db file size in bytes - if ((dbFileSize = get_db_file_size(dbFileName)) < 0) { + if ((dbFileSize = get_db_file_size(dbFileName)) < 0) + { numOfEntries = FAILURE; goto GetFileCount_Exit; } // get the appropriate count numOfEntries = 0; - for (i = 0;; i += entrySize) { + for (i = 0;; i += entrySize) + { if ((i + entrySize) > dbFileSize) // make sure we don't fall off the end ... break; diff --git a/camshr/get_file_name.c b/camshr/get_file_name.c index dbd801d6d4..1c5ad4a338 100644 --- a/camshr/get_file_name.c +++ b/camshr/get_file_name.c @@ -55,7 +55,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Fri Apr 13 12:29:02 EDT 2001 // Tue Apr 17 11:42:55 EDT 2001 -- more concice processing of '/' character //------------------------------------------------------------------------- -char *get_file_name(char *filename) { +char *get_file_name(char *filename) +{ char *pEnv; // pointer to environment var static char db_dir[256], *pChar; // needs to be persistant diff --git a/camshr/get_scsi_device_number.c b/camshr/get_scsi_device_number.c index 838ac3e338..eac6f3097e 100644 --- a/camshr/get_scsi_device_number.c +++ b/camshr/get_scsi_device_number.c @@ -56,7 +56,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // and return O/S specific device number, eg '/dev/sg#' // returns '/dev/sg#' value; if non-existant, parse_crate_db() returns -1 //------------------------------------------------------------------------- -int get_scsi_device_number(char *highway_name, int *enhanced, int *online) { +int get_scsi_device_number(char *highway_name, int *enhanced, int *online) +{ char highway[5]; // temp copy int device_num, i; struct Crate_ crate; @@ -67,9 +68,11 @@ int get_scsi_device_number(char *highway_name, int *enhanced, int *online) { printf("get_scsi_device_number('%s')\n", highway_name); // check to see if db file is memory mapped - if (CRATEdbFileIsMapped == FALSE) { // not mapped so ... - if (map_data_file(CRATE_DB) != SUCCESS) { // ... try to map - device_num = MAP_ERROR; // bummer :-( + if (CRATEdbFileIsMapped == FALSE) + { // not mapped so ... + if (map_data_file(CRATE_DB) != SUCCESS) + { // ... try to map + device_num = MAP_ERROR; // bummer :-( goto GetScsiDeviceNumber_Exit; } } @@ -77,7 +80,8 @@ int get_scsi_device_number(char *highway_name, int *enhanced, int *online) { sprintf(highway, "%.4s", highway_name); // trim to highway name, only if ((i = lookup_entry(CRATE_DB, highway_name)) < - 0) { // lookup actual device num + 0) + { // lookup actual device num if (MSGLVL(IMPORTANT)) fprintf(stderr, "no such highway in 'crate.db'\n"); @@ -91,7 +95,8 @@ int get_scsi_device_number(char *highway_name, int *enhanced, int *online) { *online = crate.online; GetScsiDeviceNumber_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { if (device_num >= 0) printf("gsdn(): (lookup[%d]=%s) = devnum(%d)\n", i, highway, device_num); } diff --git a/camshr/inquiry.c b/camshr/inquiry.c index 4d2feda1ec..ac2bf381eb 100644 --- a/camshr/inquiry.c +++ b/camshr/inquiry.c @@ -24,18 +24,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ char inqdat[56]; unsigned char inqcmd[] = {0x12, 0, 0, 0, sizeof(inqdat) - 1, 0}; int scsi_stat; int numgot; - if (argc < 2) { + if (argc < 2) + { printf("usage: inquiry scsi-device-number (i.e. 0,1,2,3)\n"); return 0; } scsi_stat = scsi_io(strtol(argv[1], NULL, 0), 1, inqcmd, 6, &inqdat, sizeof(inqdat) - 1, 0, 0, 0, &numgot); - if (scsi_stat == 0 && (numgot > 8)) { + if (scsi_stat == 0 && (numgot > 8)) + { inqdat[numgot] = 0; printf("Got: %s\n", &inqdat[8]); } diff --git a/camshr/issort.c b/camshr/issort.c index e0248420fa..65d7524bbe 100644 --- a/camshr/issort.c +++ b/camshr/issort.c @@ -68,7 +68,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ISBN: 1-56592-453-3 //------------------------------------------------------------------------- int issort(void *data, int size, int esize, - int (*compare)(const void *key1, const void *key2)) { + int (*compare)(const void *key1, const void *key2)) +{ void *key; char *a = data; int i, j; @@ -78,12 +79,14 @@ int issort(void *data, int size, int esize, return -1; // Repeatedly insert a key element among the sorted elements. - for (j = 1; j < size; ++j) { + for (j = 1; j < size; ++j) + { memcpy(key, &a[j * esize], esize); i = j - 1; // Determine the position at which to insert the key element. - while (i >= 0 && compare(&a[i * esize], key) > 0) { + while (i >= 0 && compare(&a[i * esize], key) > 0) + { memcpy(&a[(i + 1) * esize], &a[i * esize], esize); i--; } diff --git a/camshr/lock_file.c b/camshr/lock_file.c index 071adf1f1e..4fdc25cce1 100644 --- a/camshr/lock_file.c +++ b/camshr/lock_file.c @@ -63,7 +63,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: none // output: status //------------------------------------------------------------------------- -int lock_file() { +int lock_file() +{ int status = SUCCESS; // assume the best case struct sembuf sb = {0, P_SEMA4, 0}; extern int semid; // see 'create_sema4()' @@ -79,8 +80,10 @@ int lock_file() { if (sema4Exists == FALSE) create_sema4(); - do { - if (semop(semid, &sb, 1) == ERROR) { + do + { + if (semop(semid, &sb, 1) == ERROR) + { if (MSGLVL(ALWAYS)) perror("semop()"); @@ -94,7 +97,8 @@ int lock_file() { } while (check_sema4()); LockFile_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("lock_file(): "); ShowStatus(status); } diff --git a/camshr/lookup_entry.c b/camshr/lookup_entry.c index 11d9f5c1c8..e5c2adf5f8 100644 --- a/camshr/lookup_entry.c +++ b/camshr/lookup_entry.c @@ -81,14 +81,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // pointer to the name of a logical module name // output: -1 indicates not found; >= 0 is index in db file //------------------------------------------------------------------------- -int lookup_entry(int dbType, char *entry_name) { +int lookup_entry(int dbType, char *entry_name) +{ int numOfEntries, retval; if (MSGLVL(FUNCTION_NAME)) printf("lookup_entry('%s')\n", entry_name); // get number of entries in db file - if ((numOfEntries = get_file_count(dbType)) <= 0) { + if ((numOfEntries = get_file_count(dbType)) <= 0) + { if (MSGLVL(DETAILS)) fprintf(stderr, "no entries in db -- lookup() failed\n"); @@ -104,25 +106,30 @@ int lookup_entry(int dbType, char *entry_name) { extern struct CRATE *CRATEdb; -int find_crate(char *wild, char **crate, void **ctx) { +int find_crate(char *wild, char **crate, void **ctx) +{ struct descriptor wild_d = {strlen(wild), DTYPE_T, CLASS_S, wild}; - struct context { + struct context + { int numEntries; int next; } * context; int status = 0; if (wild[wild_d.length - 1] == ':') wild_d.length--; - if (*ctx == 0) { + if (*ctx == 0) + { *ctx = malloc(sizeof(struct context)); ((struct context *)*ctx)->next = 0; ((struct context *)*ctx)->numEntries = get_file_count(CRATE_DB); } context = (struct context *)*ctx; - while (context->next < context->numEntries) { + while (context->next < context->numEntries) + { struct descriptor crate_d = {sizeof(struct CRATE_NAME), DTYPE_T, CLASS_S, (char *)&CRATEdb[context->next++]}; - if (StrMatchWild(&crate_d, &wild_d) & 1) { + if (StrMatchWild(&crate_d, &wild_d) & 1) + { *crate = memcpy(malloc(crate_d.length + 1), crate_d.pointer, sizeof(struct CRATE_NAME)); (*crate)[crate_d.length] = 0; @@ -133,7 +140,8 @@ int find_crate(char *wild, char **crate, void **ctx) { return status; } -void find_crate_end(void **ctx) { +void find_crate_end(void **ctx) +{ free(*ctx); *ctx = 0; } diff --git a/camshr/map_data_file.c b/camshr/map_data_file.c index d7dc582b3e..aec5078b13 100644 --- a/camshr/map_data_file.c +++ b/camshr/map_data_file.c @@ -70,7 +70,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: db type // output: status //------------------------------------------------------------------------- -int map_data_file(int dbType) { +int map_data_file(int dbType) +{ char *FileName = 0; int db_size, fd = ERROR, *FileIsMapped = FALSE; int status = SUCCESS; @@ -80,7 +81,8 @@ int map_data_file(int dbType) { extern struct CRATE *CRATEdb; // set db specific parameters - switch (dbType) { + switch (dbType) + { case CTS_DB: FileName = CTS_DB_FILE; FileIsMapped = &CTSdbFileIsMapped; @@ -96,27 +98,32 @@ int map_data_file(int dbType) { printf("map_data_file('%s')\n", FileName); // check to see if db file exists - if (check_for_file(FileName) != SUCCESS) { + if (check_for_file(FileName) != SUCCESS) + { status = FILE_ERROR; goto MapData_Exit; // no file, so we're out'a here } // get file size - if ((db_size = get_db_file_size(FileName)) == ERROR) { + if ((db_size = get_db_file_size(FileName)) == ERROR) + { status = ERROR; goto MapData_Exit; } // get a file descriptor -- NB! special version of 'Open()' - if ((fd = Open(FileName, O_RDWR)) == ERROR) { + if ((fd = Open(FileName, O_RDWR)) == ERROR) + { perror("open()"); status = FILE_ERROR; // error flag goto MapData_Exit; } // now, memory map database file - switch (dbType) { + switch (dbType) + { case CTS_DB: if ((CTSdb = (struct MODULE *)mmap( (caddr_t)0, db_size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, - fd, 0)) == MAP_FAILED) { + fd, 0)) == MAP_FAILED) + { if (MSGLVL(ALWAYS)) perror("mmap(CTS)"); @@ -130,7 +137,8 @@ int map_data_file(int dbType) { case CRATE_DB: if ((CRATEdb = (struct CRATE *)mmap( (caddr_t)0, db_size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, - fd, 0)) == MAP_FAILED) { + fd, 0)) == MAP_FAILED) + { if (MSGLVL(ALWAYS)) perror("mmap(CRATE)"); @@ -158,7 +166,8 @@ int map_data_file(int dbType) { return status; if (status != SUCCESS) printf("Error mapping %s\n", FileName); - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("map_data_file('%s'): ", FileName); ShowStatus(status); } diff --git a/camshr/map_scsi_device.c b/camshr/map_scsi_device.c index d1ad2e5f8b..46730a4e5b 100644 --- a/camshr/map_scsi_device.c +++ b/camshr/map_scsi_device.c @@ -48,7 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------- // local struct //------------------------------------------------------------------------- -struct scsi_info { +struct scsi_info +{ char adapter; int scsi_id; }; @@ -66,7 +67,8 @@ struct scsi_info { // puts value into crate.db; leaves unchanged if not found // NB! called by 'autoconfig()' in cts::verbs //------------------------------------------------------------------------- -int map_scsi_device(char *highway_name) { +int map_scsi_device(char *highway_name) +{ char line[80], *pline, tmp[7]; char dsf[11], hwytype = '.'; int adapter, i, numOfEntries, scsi_id, sg_number; @@ -79,7 +81,8 @@ int map_scsi_device(char *highway_name) { printf("map_scsi_device('%s')\n", highway_name); // open '/proc' filesystem scsi info - if ((fp = fopen(PROC_FILE, "r")) == NULL) { + if ((fp = fopen(PROC_FILE, "r")) == NULL) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "failure to open '%s'\n", PROC_FILE); @@ -87,7 +90,8 @@ int map_scsi_device(char *highway_name) { goto MapScsiDevice_Exit; } // get current db file count - if ((numOfEntries = get_file_count(CRATE_DB)) <= 0) { + if ((numOfEntries = get_file_count(CRATE_DB)) <= 0) + { status = FILE_ERROR; goto MapScsiDevice_Exit; // we're done :< } @@ -97,7 +101,8 @@ int map_scsi_device(char *highway_name) { // lookup highway name if (MSGLVL(DETAILS)) printf("msd() looking up '%s'\n", highway_name); - if ((i = lookup_entry(CRATE_DB, highway_name)) < 0) { + if ((i = lookup_entry(CRATE_DB, highway_name)) < 0) + { status = NO_DEVICE; // no such device in db file goto MapScsiDevice_Exit; } @@ -109,29 +114,35 @@ int map_scsi_device(char *highway_name) { // scan all scsi devices sg_number = 0; // start at the beginning - while (!found && (pline = fgets(line, sizeof(line), fp)) != NULL) { - if (strncmp(pline, "Host:", 5) == EQUAL) { + while (!found && (pline = fgets(line, sizeof(line), fp)) != NULL) + { + if (strncmp(pline, "Host:", 5) == EQUAL) + { sscanf(line, "Host: scsi%d Channel: %*2c Id: %d %*s", &adapter, &scsi_id); sprintf(tmp, "GK%c%d", 'A' + adapter, scsi_id); - if (strncmp(tmp, highway_name, 4) == EQUAL) { // found it - if (QueryHighwayType(tmp) == SUCCESS) // determine highway type + if (strncmp(tmp, highway_name, 4) == EQUAL) + { // found it + if (QueryHighwayType(tmp) == SUCCESS) // determine highway type hwytype = tmp[5]; // we're done, so exit found = TRUE; - } else + } + else sg_number++; } // end of if() .... } // end of while() ... // 'lock' file with semaphore - if (lock_file() != SUCCESS) { + if (lock_file() != SUCCESS) + { status = FAILURE; // LOCK_ERROR; [2001.07.12] goto MapScsiDevice_Exit; } // update memory mapped version - if (found) { + if (found) + { sprintf(dsf, "%03d", sg_number); // format conversion #pragma GCC diagnostic push #if defined __GNUC__ && 800 <= __GNUC__ * 100 + __GNUC_MINOR__ @@ -140,7 +151,9 @@ int map_scsi_device(char *highway_name) { strncpy((CRATEdb + i)->DSFname, dsf, 3); // real device number #pragma GCC diagnostic pop (CRATEdb + i)->HwyType = hwytype; // highway type - } else { + } + else + { #pragma GCC diagnostic push #if defined __GNUC__ && 800 <= __GNUC__ * 100 + __GNUC_MINOR__ _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"") @@ -151,7 +164,8 @@ int map_scsi_device(char *highway_name) { } // commit changes to file - if (commit_entry(CRATE_DB) != SUCCESS) { + if (commit_entry(CRATE_DB) != SUCCESS) + { status = FAILURE; // COMMIT_ERROR; [2001.07.12] goto MapScsiDevice_Exit; } @@ -160,7 +174,8 @@ int map_scsi_device(char *highway_name) { (CRATEdb + i)->HwyType); // unlock file - if (unlock_file() != SUCCESS) { + if (unlock_file() != SUCCESS) + { status = FAILURE; // UNLOCK_ERROR; [2001.07.12] goto MapScsiDevice_Exit; } diff --git a/camshr/module.h b/camshr/module.h index 8360913ffd..699e682b8c 100644 --- a/camshr/module.h +++ b/camshr/module.h @@ -4,7 +4,8 @@ #define __MODULE_H // structure of CTS_DB_FILE -struct MODULE { +struct MODULE +{ //-------------------------- // logical CAMAC module name //-------------------------- @@ -39,7 +40,8 @@ struct MODULE { #define MODULE_ENTRY sizeof(struct MODULE) // internal structure -typedef struct Module_ { +typedef struct Module_ +{ char name[32]; // 2002.02.07 int adapter; int id; @@ -49,7 +51,8 @@ typedef struct Module_ { } Module; // linked list structure -struct t_mod { +struct t_mod +{ char mod_name[32]; // module logical name struct t_mod *next; // pointer to next element }; diff --git a/camshr/msg.c b/camshr/msg.c index 9b0b6652b5..0b1b0aeeed 100644 --- a/camshr/msg.c +++ b/camshr/msg.c @@ -54,14 +54,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // To use: e.g. // if( MSGLVL(1) ) printf("debug info ...\n"); //----------------------------------------------------------- -int MSGLVL(int level) { +int MSGLVL(int level) +{ char *c; int dbglvl; - c = getenv(DEBUG_VAR_NAME); // get debug variable - if (c) { // if not NULL ... + c = getenv(DEBUG_VAR_NAME); // get debug variable + if (c) + { // if not NULL ... dbglvl = strtol(c, NULL, 0); // convert to numeric return (dbglvl >= level) ? TRUE : FALSE; - } else // ... is not set + } + else // ... is not set return FALSE; } diff --git a/camshr/parse_crate_db.c b/camshr/parse_crate_db.c index 40ea6b5d04..1ddde8b140 100644 --- a/camshr/parse_crate_db.c +++ b/camshr/parse_crate_db.c @@ -70,7 +70,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // pointer to struct of crate data // output: none //------------------------------------------------------------------------- -void parse_crate_db(struct CRATE *in, struct Crate_ *out) { +void parse_crate_db(struct CRATE *in, struct Crate_ *out) +{ if (MSGLVL(FUNCTION_NAME)) printf("parse_crate_db()\n"); diff --git a/camshr/parse_cts_db.c b/camshr/parse_cts_db.c index e18dd1efd6..94a9945cd2 100644 --- a/camshr/parse_cts_db.c +++ b/camshr/parse_cts_db.c @@ -70,7 +70,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: pointer to cts.db data (in memory) // output: pointer to struct of db data //------------------------------------------------------------------------- -void parse_cts_db(struct MODULE *in, struct Module_ *out) { +void parse_cts_db(struct MODULE *in, struct Module_ *out) +{ char adpt, fmt[6], line[MODULE_ENTRY + 1]; char comm[41]; int i; @@ -80,7 +81,7 @@ void parse_cts_db(struct MODULE *in, struct Module_ *out) { sprintf(fmt, "%%.%ds", (int)(MODULE_ENTRY - 1)); // create format string memset(line, ' ', MODULE_ENTRY + 1); // 2002.02.06 - sprintf(line, fmt, (char *)in); // extract first (single) line + sprintf(line, fmt, (char *)in); // extract first (single) line // parse ... sscanf(line, "%32s GK%c%1d%02d:N%2d %40c", out->name, &adpt, // temporary @@ -89,7 +90,8 @@ void parse_cts_db(struct MODULE *in, struct Module_ *out) { out->adapter = adpt - 'A'; // adjustment ... // find end of comment - for (i = sizeof(comm) - 1; i >= 0; --i) { + for (i = sizeof(comm) - 1; i >= 0; --i) + { if (comm[i] != ' ') break; } diff --git a/camshr/remove_entry.c b/camshr/remove_entry.c index 1e93f25da3..6ac06ff47f 100644 --- a/camshr/remove_entry.c +++ b/camshr/remove_entry.c @@ -72,7 +72,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // index of entry in db file, zero-based // outout: status //------------------------------------------------------------------------- -int remove_entry(int dbType, int index) { +int remove_entry(int dbType, int index) +{ void *dbptr; // re-usable, generic db pointer char fmt[10]; int entrySize, i, numOfEntries; @@ -89,7 +90,8 @@ int remove_entry(int dbType, int index) { //-- 'critical section' start //---------------------------- // 'lock' with semaphore - if (lock_file() == ERROR) { + if (lock_file() == ERROR) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error locking file\n"); @@ -98,7 +100,8 @@ int remove_entry(int dbType, int index) { } // get number of current entries if ((numOfEntries = get_file_count(dbType)) == - 0) { // no entries in cts db file + 0) + { // no entries in cts db file if (MSGLVL(IMPORTANT)) fprintf(stderr, "db file empty, no entries to remove\n"); @@ -106,7 +109,8 @@ int remove_entry(int dbType, int index) { goto RemoveEntry_Exit; } // cull db specific info - switch (dbType) { + switch (dbType) + { case CTS_DB: dbptr = (void *)CTSdb; entrySize = MODULE_ENTRY; @@ -139,12 +143,14 @@ int remove_entry(int dbType, int index) { } // commit change to file - if (commit_entry(dbType) != SUCCESS) { + if (commit_entry(dbType) != SUCCESS) + { status = COMMIT_ERROR; goto RemoveEntry_Exit; } // release semaphore - if (unlock_file() == ERROR) { + if (unlock_file() == ERROR) + { if (MSGLVL(ALWAYS)) fprintf(stderr, "error unlocking file\n"); @@ -155,7 +161,8 @@ int remove_entry(int dbType, int index) { //-- 'critical section' finish //---------------------------- RemoveEntry_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("remove_entry(): "); ShowStatus(status); } diff --git a/camshr/scsi_io.c b/camshr/scsi_io.c index e8c369d0d4..77e4a969df 100644 --- a/camshr/scsi_io.c +++ b/camshr/scsi_io.c @@ -82,17 +82,21 @@ static int BUFFSIZE[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static int OpenScsi(int scsiDevice, char **buff_out); -int SGSetMAXBUF(int scsiDevice, int new) { +int SGSetMAXBUF(int scsiDevice, int new) +{ int old = -1; char *bufptr; int fd = -1; - if (scsiDevice >= 0 || scsiDevice <= 9) { + if (scsiDevice >= 0 || scsiDevice <= 9) + { old = MAXBUF[scsiDevice]; - if (new >= MIN_MAXBUF) { + if (new >= MIN_MAXBUF) + { int pagesize = getpagesize(); int reqsize = ((new + pagesize - 1) / pagesize) * pagesize; MAXBUF[scsiDevice] = reqsize; - if (FDS[scsiDevice] != -1) { + if (FDS[scsiDevice] != -1) + { close(FDS[scsiDevice]); FDS[scsiDevice] = -1; } @@ -106,34 +110,46 @@ int SGSetMAXBUF(int scsiDevice, int new) { return old; } -int SGGetMAXBUF(int scsiDevice) { - if (scsiDevice >= 0 || scsiDevice <= 9) { +int SGGetMAXBUF(int scsiDevice) +{ + if (scsiDevice >= 0 || scsiDevice <= 9) + { char *bufptr; OpenScsi(scsiDevice, &bufptr); return BUFFSIZE[scsiDevice]; - } else + } + else return -1; } -static int OpenScsi(int scsiDevice, char **buff_out) { +static int OpenScsi(int scsiDevice, char **buff_out) +{ char *buff = 0; static char *BUFFS[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int fd = -1; - if (scsiDevice >= 0 || scsiDevice <= 9) { - if (FDS[scsiDevice] >= 0) { + if (scsiDevice >= 0 || scsiDevice <= 9) + { + if (FDS[scsiDevice] >= 0) + { fd = FDS[scsiDevice]; buff = BUFFS[scsiDevice]; - } else { + } + else + { char devnam[9]; sprintf(devnam, "/dev/sg%d", scsiDevice); - if ((fd = open(devnam, O_RDWR)) < 0) { + if ((fd = open(devnam, O_RDWR)) < 0) + { char msg[512]; sprintf(msg, "%s(): Error opening device \"%s\"", ROUTINE_NAME, devnam); perror(msg); - } else { + } + else + { int reqsize; int pagesize = getpagesize(); - if (MAXBUF[scsiDevice] < MIN_MAXBUF) { + if (MAXBUF[scsiDevice] < MIN_MAXBUF) + { char *env = getenv("CAMAC_BUFFSIZE"); if (env) MAXBUF[scsiDevice] = strtol(env, NULL, 0); @@ -145,34 +161,44 @@ static int OpenScsi(int scsiDevice, char **buff_out) { BUFFSIZE[scsiDevice] = 0; if ((ioctl(fd, SG_SET_RESERVED_SIZE, &reqsize) < 0) || (ioctl(fd, SG_GET_RESERVED_SIZE, &BUFFSIZE[scsiDevice]) < 0) || - (BUFFSIZE[scsiDevice] < MIN_MAXBUF)) { + (BUFFSIZE[scsiDevice] < MIN_MAXBUF)) + { fprintf(stderr, "%s(): could NOT allocate %d byte kernel buffer, max is %d\n", ROUTINE_NAME, reqsize, BUFFSIZE[scsiDevice]); close(fd); fd = -1; - } else { + } + else + { buff = mmap(0, BUFFSIZE[scsiDevice], (PROT_READ | PROT_WRITE), MAP_SHARED, fd, 0); - if (buff == (char *)-1) { + if (buff == (char *)-1) + { fprintf(stderr, "%s(): error in mmap to scsi buffer, buffer = %d bytes\n", ROUTINE_NAME, BUFFSIZE[scsiDevice]); perror("mmap error"); - if (MAXBUF[scsiDevice] != MIN_MAXBUF) { + if (MAXBUF[scsiDevice] != MIN_MAXBUF) + { MAXBUF[scsiDevice] = MIN_MAXBUF; goto try_again; - } else { + } + else + { close(fd); fd = -1; } - } else + } + else BUFFS[scsiDevice] = buff; FDS[scsiDevice] = fd; } } } - } else { + } + else + { fprintf(stderr, "%s: scsi device number (%d) is out of range, must be between 0 " "and 9\n", @@ -182,32 +208,41 @@ static int OpenScsi(int scsiDevice, char **buff_out) { return fd; } -int scsi_lock(int scsiDevice, int lock) { +int scsi_lock(int scsiDevice, int lock) +{ static int semId = 0; int status = 0; struct sembuf psembuf; - if (!semId) { + if (!semId) + { semId = semget(SEM_ID, 10, 0); - if (semId == -1) { - if (errno == ENOENT) { + if (semId == -1) + { + if (errno == ENOENT) + { int status; semId = semget(SEM_ID, 10, IPC_CREAT | 0x1ff); - if (semId == -1) { + if (semId == -1) + { perror("Error creating locking semaphore"); semId = 0; - } else { + } + else + { int i; union semun { int val; } arg; arg.val = 1; - for (i = 0; i < 10; i++) { + for (i = 0; i < 10; i++) + { status = semctl(semId, i, SETVAL, arg); if (status == -1) perror("Error accessing locking semaphore"); } } - } else + } + else perror("Error accessing locking semaphore"); } } @@ -223,7 +258,8 @@ int scsi_lock(int scsiDevice, int lock) { int scsi_io(int scsiDevice, int direction, unsigned char *cmdp, unsigned char cmd_len, char *buffer, unsigned int buflen, unsigned char *sbp, unsigned char mx_sb_len, - unsigned char *sb_out_len, int *transfer_len) { + unsigned char *sb_out_len, int *transfer_len) +{ char *buf; int fd; int bytes_transfered = -1; @@ -233,7 +269,8 @@ int scsi_io(int scsiDevice, int direction, unsigned char *cmdp, if (sb_out_len != 0) *sb_out_len = 0; fd = OpenScsi(scsiDevice, &buf); - if (fd >= 0) { + if (fd >= 0) + { sghdr.interface_id = 'S'; int use_mmap = buflen <= (unsigned int)MAXBUF[scsiDevice]; // if (buflen > MAXBUF[scsiDevice]) @@ -243,7 +280,8 @@ int scsi_io(int scsiDevice, int direction, unsigned char *cmdp, //} // else //{ - switch (direction) { + switch (direction) + { case 0: sghdr.dxfer_direction = SG_DXFER_NONE; break; @@ -266,7 +304,8 @@ int scsi_io(int scsiDevice, int direction, unsigned char *cmdp, sghdr.timeout = timeout > 10000 ? timeout : 10000; sghdr.flags = use_mmap ? SG_FLAG_MMAP_IO : 0; sghdr.pack_id = 0; - if (ioctl(fd, SG_IO, &sghdr) >= 0) { + if (ioctl(fd, SG_IO, &sghdr) >= 0) + { status = sghdr.masked_status; if (512 - (buflen % 512) == (unsigned int)sghdr.resid) bytes_transfered = buflen; @@ -276,18 +315,23 @@ int scsi_io(int scsiDevice, int direction, unsigned char *cmdp, bytes_transfered = buflen; if ((direction == 1) && (bytes_transfered > 0) && use_mmap) memcpy(buffer, buf, bytes_transfered); - if ((sghdr.sb_len_wr == 0) && (mx_sb_len > 0)) { + if ((sghdr.sb_len_wr == 0) && (mx_sb_len > 0)) + { int len = 0; unsigned char sense_cmd[] = {3, 0, 0, 0, mx_sb_len, 0}; scsi_io(scsiDevice, 1, sense_cmd, sizeof(sense_cmd), (char *)sbp, mx_sb_len, 0, 0, 0, &len); if (sb_out_len != 0) *sb_out_len = (unsigned char)len; - } else if (sb_out_len != 0) + } + else if (sb_out_len != 0) *sb_out_len = sghdr.sb_len_wr; - } else + } + else perror("ioctl error performing SCSI I/O"); - } else { + } + else + { fprintf(stderr, "Error opening scsi device\n"); } if (transfer_len != 0) diff --git a/camshr/turn_crate_on_off_line.c b/camshr/turn_crate_on_off_line.c index 56c1ec478b..edfddecb60 100644 --- a/camshr/turn_crate_on_off_line.c +++ b/camshr/turn_crate_on_off_line.c @@ -55,7 +55,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tue Apr 10 11:11:48 EDT 2001 // eg. *crate_name == "GKB509" //----------------------------------------------------------- -int turn_crate_on_off_line(char *crate_name, int state) { +int turn_crate_on_off_line(char *crate_name, int state) +{ char controller[12], *pController; short SCCdata; size_t i; @@ -81,7 +82,8 @@ int turn_crate_on_off_line(char *crate_name, int state) { // lookup name -- make sure a valid device if ((idx = lookup_entry(CRATE_DB, crate_name)) < - 0) { // lookup actual device num + 0) + { // lookup actual device num if (MSGLVL(IMPORTANT)) fprintf(stderr, "no such crate in 'crate.db'\n"); @@ -93,7 +95,8 @@ int turn_crate_on_off_line(char *crate_name, int state) { pController = &controller[0]; - if (CRATEdb[idx].HwyType != ('0' + JORWAY_73A)) { + if (CRATEdb[idx].HwyType != ('0' + JORWAY_73A)) + { SCCdata = 1; // initiates Dataway Z status = CamPiow(pController, // serial crate controller name 0, // A --\__ write status register @@ -111,7 +114,8 @@ int turn_crate_on_off_line(char *crate_name, int state) { 16, // mem == 16-bit data &iosb // *iosb ); - if (status & 1) { + if (status & 1) + { status = get_crate_status(pController, &crateStatus); online = ((crateStatus & 0x1000) != 0x1000) ? TRUE : FALSE; if (!crateStatus || crateStatus == 0x3) @@ -120,7 +124,9 @@ int turn_crate_on_off_line(char *crate_name, int state) { enhanced = (online && (crateStatus & 0x4000)) ? TRUE : FALSE; CRATEdb[idx].enhanced = enhanced ? '1' : '0'; } - } else { + } + else + { CRATEdb[idx].online = (state == ON) ? '1' : '0'; CRATEdb[idx].enhanced = '0'; status = 1; diff --git a/camshr/unlock_file.c b/camshr/unlock_file.c index 81c0fc88d9..842d342dcb 100644 --- a/camshr/unlock_file.c +++ b/camshr/unlock_file.c @@ -64,7 +64,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: none // output: status //------------------------------------------------------------------------- -int unlock_file() { +int unlock_file() +{ int status = SUCCESS; // assume the best case struct sembuf sb = {0, P_SEMA4, 0}; extern int semid; @@ -73,14 +74,16 @@ int unlock_file() { printf("unlock_file()\n"); sb.sem_op = V_SEMA4; // prepare to 'vend' a semaphore - if (semop(semid, &sb, 1) == ERROR) { + if (semop(semid, &sb, 1) == ERROR) + { if (MSGLVL(ALWAYS)) perror("semop()"); status = ERROR; } - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("unlock_file(): "); ShowStatus(status); } diff --git a/camshr/verbs.c b/camshr/verbs.c index b5cb5b8d83..a41935d382 100644 --- a/camshr/verbs.c +++ b/camshr/verbs.c @@ -103,7 +103,8 @@ extern int cli_present(); //------------------------------------------------------------------------- // helper routine //------------------------------------------------------------------------- -static void str_upcase(char *str) { +static void str_upcase(char *str) +{ size_t i; for (i = 0; i < strlen(str); i++) @@ -114,7 +115,8 @@ static void str_upcase(char *str) { // assign a new module to CTS database //------------------------------------------------------------------------- EXPORT int Assign(void *ctx, char **error, - char *output __attribute__((unused))) { + char *output __attribute__((unused))) +{ char line[MODULE_ENTRY + 1]; int dbFileSize, fd, nullMask, numOfEntries; size_t i; @@ -131,34 +133,42 @@ EXPORT int Assign(void *ctx, char **error, cli_get_value(ctx, "COMMENT", &comment); // check to see if db file exists - if (check_for_file(CTS_DB_FILE) != SUCCESS) { // does not exist, yet + if (check_for_file(CTS_DB_FILE) != SUCCESS) + { // does not exist, yet // try to creat (sic) it - if ((fd = Creat(CTS_DB_FILE, 0666)) == ERROR) { + if ((fd = Creat(CTS_DB_FILE, 0666)) == ERROR) + { *error = strdup("Error: cts db file does not exist and error attempting " "to create one.\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] goto Assign_Exit; // we're done :< - } else + } + else close(fd); } // check to see if db file is memory mapped - if (CTSdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CTS_DB) != SUCCESS) { // we're dead in the water + if (CTSdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CTS_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: problem mapping cts db file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] goto Assign_Exit; } } // get current db file count - if ((numOfEntries = get_file_count(CTS_DB)) < 0) { + if ((numOfEntries = get_file_count(CTS_DB)) < 0) + { *error = strdup( "Error: Error obtaining number of entries. cts db file corrupted?\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] goto Assign_Exit; } - if (numOfEntries) { // 1 or more - if (lookup_entry(CTS_DB, log_name) >= 0) { // duplicate ! + if (numOfEntries) + { // 1 or more + if (lookup_entry(CTS_DB, log_name) >= 0) + { // duplicate ! *error = malloc(strlen(log_name) + 100); sprintf(*error, "Error: duplicate module name '%s' -- not allowed\n", log_name); @@ -168,7 +178,8 @@ EXPORT int Assign(void *ctx, char **error, } } // get db file size - if ((dbFileSize = get_db_file_size(CTS_DB_FILE)) == ERROR) { + if ((dbFileSize = get_db_file_size(CTS_DB_FILE)) == ERROR) + { *error = strdup("Error: problem determining cts db file size. cts db file " "corrupted?\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] @@ -178,8 +189,10 @@ EXPORT int Assign(void *ctx, char **error, MODULE_ENTRY; // .. current maximum number of possible module entries // do we need to expand db file? - if ((dbFileSize == 0) || (numOfEntries == dbFileSize)) { // ... yes - if (expand_db(CTS_DB, numOfEntries) != SUCCESS) { // expand ... + if ((dbFileSize == 0) || (numOfEntries == dbFileSize)) + { // ... yes + if (expand_db(CTS_DB, numOfEntries) != SUCCESS) + { // expand ... *error = strdup("Error: problem expanding cts db file\n"); status = FAILURE; // EXPAND_ERROR; [2001.07.12] // ... failure goto Assign_Exit; @@ -202,14 +215,16 @@ EXPORT int Assign(void *ctx, char **error, line[i] = ' '; // make it spaces // add it ... - if (add_entry(CTS_DB, line) != SUCCESS) { + if (add_entry(CTS_DB, line) != SUCCESS) + { *error = strdup("Error: problem adding new line to cts db file\n"); status = FAILURE; // ASSIGN_ERROR; [2001.07.12] goto Assign_Exit; } #if NEED_WARM_N_FUZZY // write to a buffer file for a warm fuzzy ... - if ((fd = Creat("buffer.db", 0666)) == ERROR) { + if ((fd = Creat("buffer.db", 0666)) == ERROR) + { *error = strdup("Error: problem creating buffer file\n"); perror("creat()"); @@ -219,7 +234,8 @@ EXPORT int Assign(void *ctx, char **error, rc = write(fd, line, sizeof(line)); close(fd); - if (rc != sizeof(line)) { + if (rc != sizeof(line)) + { perror("write()"); *error = strdup("Error: problem writing to buffer file\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] @@ -237,7 +253,8 @@ EXPORT int Assign(void *ctx, char **error, // map generic scsi device names to crate table names //------------------------------------------------------------------------- EXPORT int Autoconfig(void *ctx __attribute__((unused)), char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char highway_name[CRATE_NAME_SIZE + 1], *pHighwayName; char line[CRATE_ENTRY]; int i, numOfEntries; @@ -247,20 +264,24 @@ EXPORT int Autoconfig(void *ctx __attribute__((unused)), char **error, int j; // check to see if db file memory mapped - if (CRATEdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CRATE_DB) != SUCCESS) { // we're dead in the water + if (CRATEdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CRATE_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: problem mapping crate db file\n"); status = MAP_ERROR; goto AutoConfig_Exit; // we're done :< } } // get current db file count - if ((numOfEntries = get_file_count(CRATE_DB)) <= 0) { // nothing to do ... + if ((numOfEntries = get_file_count(CRATE_DB)) <= 0) + { // nothing to do ... status = FILE_ERROR; goto AutoConfig_Exit; // we're done :< } // open file for read-only - if ((fp = Fopen(CRATE_DB_FILE, "r")) == NULL) { + if ((fp = Fopen(CRATE_DB_FILE, "r")) == NULL) + { *error = strdup("Error: crate.db does not exist\n"); status = FILE_ERROR; @@ -270,13 +291,17 @@ EXPORT int Autoconfig(void *ctx __attribute__((unused)), char **error, pHighwayName = highway_name; // point to real memory ... // loop thru list - for (i = 0; i < numOfEntries; ++i) { - if (fscanf(fp, "%s", line) == 1) { // get a crate.db entry + for (i = 0; i < numOfEntries; ++i) + { + if (fscanf(fp, "%s", line) == 1) + { // get a crate.db entry sprintf(pHighwayName, "%.6s", line); // trim it // NB! this is a work-around -- seems necessary for the moment - for (j = 0; j < 2; j++) { - if (map_scsi_device(pHighwayName) != SUCCESS) { // map it if possible + for (j = 0; j < 2; j++) + { + if (map_scsi_device(pHighwayName) != SUCCESS) + { // map it if possible *error = malloc(strlen(pHighwayName) + 100); sprintf(*error, "Error: problem mapping scsi device '%s'\n", pHighwayName); @@ -298,7 +323,8 @@ EXPORT int Autoconfig(void *ctx __attribute__((unused)), char **error, // deassign a module //------------------------------------------------------------------------- EXPORT int Deassign(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char db_tmp[128]; int i, modulesToDeassign, modulesDeassigned, numOfEntries, physical_name; int status = SUCCESS; @@ -316,15 +342,18 @@ EXPORT int Deassign(void *ctx, char **error, physical_name = cli_present(ctx, "PHYSICAL") & 1; // check to see if db file memory mapped - if (CTSdbFileIsMapped == FALSE) { // is not, so try ... - if (map_data_file(CTS_DB) != SUCCESS) { // we're dead in the water - status = MAP_ERROR; // [2002.02.21] + if (CTSdbFileIsMapped == FALSE) + { // is not, so try ... + if (map_data_file(CTS_DB) != SUCCESS) + { // we're dead in the water + status = MAP_ERROR; // [2002.02.21] goto Deassign_Exit; } } // get number of current entries if ((numOfEntries = get_file_count(CTS_DB)) == - 0) { // no entries in cts db file + 0) + { // no entries in cts db file *error = strdup("Error: db file empty, no entries to remove\n"); status = DEASSIGN_ERROR; // [2002.02.21] @@ -335,7 +364,8 @@ EXPORT int Deassign(void *ctx, char **error, pMod = &Mod; // point to some actual storage // first, we need to count the number to deassign ... - for (i = 0; i < numOfEntries; ++i) { // scan entire list + for (i = 0; i < numOfEntries; ++i) + { // scan entire list // look up module name(s). NB! more than one logical name may be // assigned to the same, unique physical name. parse_cts_db(CTSdb + i, pMod); // extract info from db @@ -353,14 +383,17 @@ EXPORT int Deassign(void *ctx, char **error, pattern.pointer = db_tmp; pattern.length = strlen(db_tmp); - if (StrMatchWild(&pattern, &wild_d) & 1) { + if (StrMatchWild(&pattern, &wild_d) & 1) + { ++modulesToDeassign; // } } // end of for() loop, all entries checked // now actually remove them - while (modulesToDeassign) { - for (i = 0; i < get_file_count(CTS_DB); ++i) { + while (modulesToDeassign) + { + for (i = 0; i < get_file_count(CTS_DB); ++i) + { // look up module name(s). NB! more than one logical name may be // assigned to the same, unique physical name. parse_cts_db(CTSdb + i, pMod); // extract info from db @@ -378,11 +411,14 @@ EXPORT int Deassign(void *ctx, char **error, pattern.pointer = db_tmp; pattern.length = strlen(db_tmp); - if (StrMatchWild(&pattern, &wild_d) & 1) { - if (remove_entry(CTS_DB, i) != SUCCESS) { // removal failed - status = DEASSIGN_ERROR; // [2002.02.21] + if (StrMatchWild(&pattern, &wild_d) & 1) + { + if (remove_entry(CTS_DB, i) != SUCCESS) + { // removal failed + status = DEASSIGN_ERROR; // [2002.02.21] goto Deassign_Exit; - } else + } + else ++modulesDeassigned; // keep track of successes :) } } @@ -400,7 +436,8 @@ EXPORT int Deassign(void *ctx, char **error, // set a crate on-line or off-line //------------------------------------------------------------------------- EXPORT int SetCrate(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status; char *cratename; void *ctx2 = 0; @@ -413,8 +450,10 @@ EXPORT int SetCrate(void *ctx, char **error, str_upcase(wild); // check to see if db file memory mapped - if (CRATEdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CRATE_DB) != SUCCESS) { // we're dead in the water + if (CRATEdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CRATE_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: problem mapping crate db file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] @@ -422,10 +461,12 @@ EXPORT int SetCrate(void *ctx, char **error, } } - while (find_crate(wild, &cratename, &ctx2)) { + while (find_crate(wild, &cratename, &ctx2)) + { status = turn_crate_on_off_line(cratename, (on) ? ON : OFF); - if (!(status & 1) && !quiet) { + if (!(status & 1) && !quiet) + { if (*error == NULL) *error = strdup(""); *error = realloc(*error, strlen(*error) + strlen(cratename) + 100); @@ -444,7 +485,8 @@ EXPORT int SetCrate(void *ctx, char **error, //------------------------------------------------------------------------- // show crate status, using crates in 'crate.db' file //------------------------------------------------------------------------- -EXPORT int ShowCrate(void *ctx, char **error, char **output) { +EXPORT int ShowCrate(void *ctx, char **error, char **output) +{ char colorENH[9], colorON[9]; int enhanced, i, online, moduleFound, numOfCrates, numOfModules; int crateStatus; @@ -454,7 +496,8 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { struct descriptor wild_d = {0, DTYPE_T, CLASS_S, 0}; struct descriptor crate_d = {0, DTYPE_T, CLASS_S, 0}; - if (ScsiSystemStatus() == 0) { + if (ScsiSystemStatus() == 0) + { status = SUCCESS; // this is the function's status *output = malloc(100); sprintf(*output, "scsi system is %sdown!%s\n", RED, NORMAL); @@ -468,8 +511,10 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { str_upcase(wild); // check to see if crate db file memory mapped - if (CRATEdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CRATE_DB) != SUCCESS) { // we're dead in the water + if (CRATEdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CRATE_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: problem memory mapping crate.db file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] @@ -477,8 +522,10 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { } } // check to see if module db file memory mapped - if (CTSdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CTS_DB) != SUCCESS) { // we're dead in the water + if (CTSdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CTS_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: error memory mapping cts.db file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] @@ -491,19 +538,25 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { // get number of crates in db file if ((numOfCrates = get_file_count(CRATE_DB)) > - 0) { // possibly something to show + 0) + { // possibly something to show if ((numOfModules = get_file_count(CTS_DB)) > - 0) { // maybe some crates controllers .. - for (i = 0; i < numOfCrates; i++) { + 0) + { // maybe some crates controllers .. + for (i = 0; i < numOfCrates; i++) + { parse_crate_db(CRATEdb + i, pCr8); crate_d.length = strlen(pCr8->name); crate_d.pointer = pCr8->name; - if (StrMatchWild(&crate_d, &wild_d) & 1) { + if (StrMatchWild(&crate_d, &wild_d) & 1) + { moduleFound = TRUE; - if (moduleFound) { + if (moduleFound) + { crateStatus = 0; status = get_crate_status(pCr8->name, &crateStatus); - if (status == SUCCESS) { + if (status == SUCCESS) + { // online = // !(crateStatus // & @@ -552,7 +605,8 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { (enhanced) ? '*' : '-', NORMAL); } } // end of if(moduleFound) ... - else { + else + { *output = realloc(*output, strlen(*output) + strlen(pCr8->name) + 100); sprintf(*output + strlen(*output), "%.6s: . . . .\n", @@ -574,7 +628,8 @@ EXPORT int ShowCrate(void *ctx, char **error, char **output) { //------------------------------------------------------------------------- //------------------------------------------------------------------------- -EXPORT int ShowModule(void *ctx, char **error, char **output) { +EXPORT int ShowModule(void *ctx, char **error, char **output) +{ char db_tmp[128]; // enough space for a logical name and a cstring terminator // [2002.02.20] int i, numOfEntries, status = SUCCESS; @@ -599,8 +654,10 @@ EXPORT int ShowModule(void *ctx, char **error, char **output) { str_upcase(wild); // convert to upper case // check to see if db file memory mapped - if (CTSdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CTS_DB) != SUCCESS) { // we're dead in the water + if (CTSdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CTS_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: error memory mapping database file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] @@ -610,12 +667,14 @@ EXPORT int ShowModule(void *ctx, char **error, char **output) { *output = strdup(""); // db file now mapped, continue pMod = &Mod; // point to some actual storage - if ((numOfEntries = get_file_count(CTS_DB)) > 0) { // something to show + if ((numOfEntries = get_file_count(CTS_DB)) > 0) + { // something to show *output = realloc(*output, strlen(*output) + strlen(heading1) + strlen(heading2) + 100); sprintf(*output + strlen(*output), "%s\n%s%d\n", heading1, heading2, numOfEntries); - for (i = 0; i < numOfEntries; i++) { + for (i = 0; i < numOfEntries; i++) + { parse_cts_db(CTSdb + i, pMod); // extract info from db memset(db_tmp, ' ', 32); @@ -630,7 +689,8 @@ EXPORT int ShowModule(void *ctx, char **error, char **output) { pattern.pointer = db_tmp; pattern.length = strlen(db_tmp); - if (StrMatchWild(&pattern, &wild_d) & 1) { + if (StrMatchWild(&pattern, &wild_d) & 1) + { *output = realloc(*output, strlen(*output) + 100); sprintf(*output + strlen(*output), "%3d: %.84s<\n", i + 1, (char *)CTSdb + (i * MODULE_ENTRY)); @@ -639,7 +699,9 @@ EXPORT int ShowModule(void *ctx, char **error, char **output) { } // end of for() loop *output = realloc(*output, strlen(*output) + strlen(heading2) + 10); sprintf(*output + strlen(*output), "%s\n", heading2); - } else { + } + else + { *error = strdup("Error: db file is empty, no modules to show\n"); status = FAILURE; // Not necessarily an ERROR; [2002.02.19] goto Showmodule_Exit; @@ -653,7 +715,8 @@ EXPORT int ShowModule(void *ctx, char **error, char **output) { //------------------------------------------------------------------------- // Add a crate to the crate db //------------------------------------------------------------------------- -EXPORT int AddCrate(void *ctx, char **error, char **output) { +EXPORT int AddCrate(void *ctx, char **error, char **output) +{ char line[CRATE_ENTRY + 1]; int dbFileSize, fd, numOfEntries; int status = SUCCESS; // assume the best @@ -665,34 +728,42 @@ EXPORT int AddCrate(void *ctx, char **error, char **output) { str_upcase(phy_name); // [2002.01.08] - if (CRATEdbFileIsMapped == FALSE) { // ... no - if (check_for_file(CRATE_DB_FILE) != SUCCESS) { // ... no - if ((fd = Creat(CRATE_DB_FILE, 0666)) == ERROR) { // no + if (CRATEdbFileIsMapped == FALSE) + { // ... no + if (check_for_file(CRATE_DB_FILE) != SUCCESS) + { // ... no + if ((fd = Creat(CRATE_DB_FILE, 0666)) == ERROR) + { // no status = FAILURE; *error = strdup("Error: Unable to open crate db file\n"); goto AddCrate_Exit; - } else + } + else close(fd); // yes } - if (map_data_file(CRATE_DB) != SUCCESS) { // failure :( + if (map_data_file(CRATE_DB) != SUCCESS) + { // failure :( *error = strdup("Error: Unable to map crate db file\n"); status = MAP_ERROR; goto AddCrate_Exit; } // else OK :) } // get current db file count - if ((numOfEntries = get_file_count(CRATE_DB)) == FILE_ERROR) { + if ((numOfEntries = get_file_count(CRATE_DB)) == FILE_ERROR) + { *error = strdup("Error: problem getting number of entries in crate db file\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] goto AddCrate_Exit; } - if (numOfEntries) { // 1 or more + if (numOfEntries) + { // 1 or more char pname[7]; sprintf(pname, "%.6s", phy_name); - if (lookup_entry(CRATE_DB, pname) >= 0) { // duplicate ! + if (lookup_entry(CRATE_DB, pname) >= 0) + { // duplicate ! *error = malloc(strlen(phy_name) + 100); sprintf(*error, "Error: duplicate crate name '%.6s' -- not allowed\n", phy_name); @@ -701,7 +772,8 @@ EXPORT int AddCrate(void *ctx, char **error, char **output) { } } // get db file size - if ((dbFileSize = get_db_file_size(CRATE_DB_FILE)) == ERROR) { + if ((dbFileSize = get_db_file_size(CRATE_DB_FILE)) == ERROR) + { *error = strdup("Error: problem getting crate db file size\n"); status = FAILURE; // FILE_ERROR; [2001.07.12] goto AddCrate_Exit; @@ -710,8 +782,10 @@ EXPORT int AddCrate(void *ctx, char **error, char **output) { CRATE_ENTRY; // .. current maximum number of possible crate entries // do we need to expand db file? - if ((dbFileSize == 0) || (numOfEntries == dbFileSize)) { // ... yes - if ((status = expand_db(CRATE_DB, numOfEntries)) != SUCCESS) { // expand + if ((dbFileSize == 0) || (numOfEntries == dbFileSize)) + { // ... yes + if ((status = expand_db(CRATE_DB, numOfEntries)) != SUCCESS) + { // expand *error = strdup("Error: problem expanding crate db file\n"); status = FAILURE; // EXPAND_ERROR; [2001.07.12] // failure goto AddCrate_Exit; @@ -722,7 +796,8 @@ EXPORT int AddCrate(void *ctx, char **error, char **output) { sprintf(line, "%-.6s:...:.:.:.\n", phy_name); // add it ... - if ((status = add_entry(CRATE_DB, line)) != SUCCESS) { + if ((status = add_entry(CRATE_DB, line)) != SUCCESS) + { *error = strdup("Error: problem adding entry to crate db file\n"); status = FAILURE; // ASSIGN_ERROR; [2001.07.12] goto AddCrate_Exit; @@ -741,7 +816,8 @@ EXPORT int AddCrate(void *ctx, char **error, char **output) { // Delete a crate from the crate db //------------------------------------------------------------------------- EXPORT int DelCrate(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char crateName[CRATE_NAME_SIZE + 1]; int index, numOfEntries; int status = SUCCESS; @@ -754,8 +830,10 @@ EXPORT int DelCrate(void *ctx, char **error, sprintf(crateName, "%.6s", phy_name); // check to see if db file memory mapped - if (CRATEdbFileIsMapped == FALSE) { // is not, so try - if (map_data_file(CRATE_DB) != SUCCESS) { // we're dead in the water + if (CRATEdbFileIsMapped == FALSE) + { // is not, so try + if (map_data_file(CRATE_DB) != SUCCESS) + { // we're dead in the water *error = strdup("Error: Unable to map crate db file\n"); status = FAILURE; // MAP_ERROR; [2001.07.12] goto DelCrate_Exit; @@ -763,19 +841,24 @@ EXPORT int DelCrate(void *ctx, char **error, } // get number of current entries if ((numOfEntries = get_file_count(CRATE_DB)) == - 0) { // no entries in crate db file + 0) + { // no entries in crate db file *error = strdup("Error: db file empty, no entries to remove\n"); status = FAILURE; // DELCRATE_ERROR; [2001.07.12] goto DelCrate_Exit; } // try to remove from crate.db - if ((index = lookup_entry(CRATE_DB, crateName)) >= 0) { // module does exist - if (remove_entry(CRATE_DB, index) != SUCCESS) { // removal failed + if ((index = lookup_entry(CRATE_DB, crateName)) >= 0) + { // module does exist + if (remove_entry(CRATE_DB, index) != SUCCESS) + { // removal failed *error = strdup("Error: problem removing entry from crate db\n"); status = FAILURE; // DELCRATE_ERROR; [2001.07.12] goto DelCrate_Exit; } - } else { // no such module + } + else + { // no such module *error = malloc(strlen(crateName) + 100); sprintf(*error, "Error: entry '%s' not found\n", crateName); status = FAILURE; // DELCRATE_ERROR; [2001.07.12] diff --git a/camshr/xlate_logicalname.c b/camshr/xlate_logicalname.c index c9ad602434..e3a202ed90 100644 --- a/camshr/xlate_logicalname.c +++ b/camshr/xlate_logicalname.c @@ -55,7 +55,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // input: logical module name // output: status, and modified data referenced by pointer //------------------------------------------------------------------------- -int xlate_logicalname(char *Name, CamKey *key) { +int xlate_logicalname(char *Name, CamKey *key) +{ int i; int status = SUCCESS; // otpimistic struct Module_ Mod; @@ -65,19 +66,23 @@ int xlate_logicalname(char *Name, CamKey *key) { if (MSGLVL(FUNCTION_NAME)) printf("xlate_logicalname()\n"); - if (strchr(Name, ':') != NULL) { // invalid logical name ... - status = ERROR; // ... was passed a physical name + if (strchr(Name, ':') != NULL) + { // invalid logical name ... + status = ERROR; // ... was passed a physical name goto Xlate_LogicalName_Exit; } // check to see if CTS db is memory mapped - if (CTSdbFileIsMapped == FALSE) { - if (map_data_file(CTS_DB) != SUCCESS) { + if (CTSdbFileIsMapped == FALSE) + { + if (map_data_file(CTS_DB) != SUCCESS) + { status = MAP_ERROR; // not mapped, we're done :< goto Xlate_LogicalName_Exit; } } // look up entry in db file - if ((i = lookup_entry(CTS_DB, Name)) < 0) { + if ((i = lookup_entry(CTS_DB, Name)) < 0) + { status = NO_DEVICE; goto Xlate_LogicalName_Exit; } @@ -91,7 +96,8 @@ int xlate_logicalname(char *Name, CamKey *key) { key->slot = Mod.slot; // CAMAC slot (ie station) Xlate_LogicalName_Exit: - if (MSGLVL(DETAILS)) { + if (MSGLVL(DETAILS)) + { printf("xlate(): name['%s'] ==>> HA[%c] id[%d] crate[%02d] slot[%d]\n", Name, key->scsi_port, key->scsi_address, key->crate, key->slot); } diff --git a/ccl/ccl_commands.c b/ccl/ccl_commands.c index 28f6e5d3bf..1c13521d7c 100644 --- a/ccl/ccl_commands.c +++ b/ccl/ccl_commands.c @@ -1217,8 +1217,8 @@ static struct cduParam SET_XANDQ_params[2] = { static struct cduKeyword XANDQ_KEYWORDS[4] = { /* "Type" def */ - "ANY", 0x4000, 0, 0, 0, 0, "NO", 0x4000, 0, 0, - 0, 0, "YES", 0x4000, 0, 0, 0, 0, 0 /* null entry at end + "ANY", 0x4000, 0, 0, 0, 0, "NO", 0x4000, 0, 0, + 0, 0, "YES", 0x4000, 0, 0, 0, 0, 0 /* null entry at end */ }; @@ -1236,7 +1236,7 @@ static struct cduQualifier SET_XANDQ_qualifiers[3] = { static struct cduVerb SET_XANDQ = {/* Syntax def */ - "SET_XANDQ", 0x0000, 0, 0, ccl_set_xandq, SET_XANDQ_params, + "SET_XANDQ", 0x0000, 0, 0, ccl_set_xandq, SET_XANDQ_params, SET_XANDQ_qualifiers}; extern int ccl_set_memory(); @@ -1249,7 +1249,7 @@ static struct cduValue SET_MEMORY_16_q01value = { static struct cduQualifier SET_MEMORY_16_qualifiers[2] = { "MEMORY", 0x2005, 0, 0, &SET_MEMORY_16_q01value, - 0, 0 /* null entry at end */ + 0, 0 /* null entry at end */ }; static struct cduVerb SET_MEMORY_16 = @@ -1261,7 +1261,7 @@ static struct cduValue SET_MEMORY_24_q01value = { static struct cduQualifier SET_MEMORY_24_qualifiers[2] = { "MEMORY", 0x2005, 0, 0, &SET_MEMORY_24_q01value, - 0, 0 /* null entry at end */ + 0, 0 /* null entry at end */ }; static struct cduVerb SET_MEMORY_24 = @@ -1271,7 +1271,7 @@ static struct cduVerb SET_MEMORY_24 = static struct cduKeyword MEMORY_KEYWORDS[3] = { /* "Type" def */ "16", 0x4000, 0, &SET_MEMORY_16, 0, 0, "24", 0x4000, 0, &SET_MEMORY_24, - 0, 0, 0 /* null entry at end */ + 0, 0, 0 /* null entry at end */ }; static struct cduValue SET_MEMORY_p02value = { @@ -1279,7 +1279,7 @@ static struct cduValue SET_MEMORY_p02value = { static struct cduParam SET_MEMORY_params[3] = { "P1", 0x1000, 0, "What", &SET_MEMORY_p01value, 0, - "P2", 0x1000, 0, 0, &SET_MEMORY_p02value, 0, + "P2", 0x1000, 0, 0, &SET_MEMORY_p02value, 0, 0 /* null entry at end */ }; @@ -1296,7 +1296,7 @@ static struct cduValue SET_MODULE_p02value = { 0x2000, 0, 0, {0, DSC_K_DTYPE_T, DSC_K_CLASS_D, 0}, 0}; static struct cduParam SET_MODULE_params[3] = { - "P1", 0x1000, 0, 0, &SET_MODULE_p01value, 0, + "P1", 0x1000, 0, 0, &SET_MODULE_p01value, 0, "P2", 0x1000, "NAME", "Module", &SET_MODULE_p02value, 0, 0 /* null entry at end */ }; @@ -1308,14 +1308,14 @@ static struct cduVerb SET_MODULE = extern int ccl_set_noverbose(); static struct cduVerb SET_NOVERBOSE = {/* Syntax def */ - "SET_NOVERBOSE", 0x0000, 0, 0, - ccl_set_noverbose, 0, 0}; + "SET_NOVERBOSE", 0x0000, 0, 0, + ccl_set_noverbose, 0, 0}; extern int ccl_set_verbose(); static struct cduVerb SET_VERBOSE = {/* Syntax def */ - "SET_VERBOSE", 0x0000, 0, 0, - ccl_set_verbose, 0, 0}; + "SET_VERBOSE", 0x0000, 0, 0, + ccl_set_verbose, 0, 0}; static struct cduKeyword SET_KEYWORDS[6] = { /* "Type" def */ @@ -1423,7 +1423,7 @@ static struct cduQualifier SHOW_DATA_qualifiers[8] = { static struct cduVerb SHOW_DATA = {/* Syntax def */ - "SHOW_DATA", 0x0000, 0, 0, ccl_show_data, SHOW_DATA_params, + "SHOW_DATA", 0x0000, 0, 0, ccl_show_data, SHOW_DATA_params, SHOW_DATA_qualifiers}; extern int ccl_show_module(); @@ -1454,7 +1454,7 @@ static struct cduVerb SHOW_STATUS = static struct cduKeyword SHOW_KEYWORDS[4] = { /* "Type" def */ - "DATA", 0x4000, 0, &SHOW_DATA, 0, 0, + "DATA", 0x4000, 0, &SHOW_DATA, 0, 0, "MODULE", 0x4000, 0, &SHOW_MODULE, 0, 0, "STATUS", 0x4000, 0, &SHOW_STATUS, 0, 0, 0 /* null entry at end */ @@ -1482,9 +1482,9 @@ static struct cduValue v21q04value = { 0x0000, "RETRO", 0, {0, DSC_K_DTYPE_T, DSC_K_CLASS_D, 0}, 0}; static struct cduQualifier v21qualifiers[5] = { - "START", 0x2005, 0, 0, &v21q01value, 0, - "END", 0x2005, 0, 0, &v21q02value, 0, - "DEVICE", 0x2005, 0, 0, &v21q03value, 0, + "START", 0x2005, 0, 0, &v21q01value, 0, + "END", 0x2005, 0, 0, &v21q02value, 0, + "DEVICE", 0x2005, 0, 0, &v21q03value, 0, "DEVTYPE", 0x2005, 0, 0, &v21q04value, 0, 0 /* null entry at end */ }; diff --git a/ccl/ccl_verbs.c b/ccl/ccl_verbs.c index 66c7509563..fd74bc3b9c 100644 --- a/ccl/ccl_verbs.c +++ b/ccl/ccl_verbs.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static int ParseQualifiers(); static int CheckErrors(); -typedef struct { +typedef struct +{ unsigned short condition; unsigned short bytcnt; unsigned int devstat; @@ -50,26 +51,29 @@ static int Xrequired = 1; static int Qrequired = 0; #define not_implemented(a) \ - EXPORT int a() { \ + EXPORT int a() \ + { \ printf("\n==> %s : This command is not implemented on this platform\n\n", \ #a); \ return 0; \ } -#define multi_io(ccl_name, cam_name) \ - EXPORT int ccl_name(void *ctx, char **error, char **output) { \ - int status = ParseQualifiers(ctx, error, output); \ - if (status & 1) \ - status = cam_name(Name, A, F, Count, D, Mem, (unsigned short *)&iosb); \ - return CheckErrors(status, (unsigned short *)&iosb, error, output); \ +#define multi_io(ccl_name, cam_name) \ + EXPORT int ccl_name(void *ctx, char **error, char **output) \ + { \ + int status = ParseQualifiers(ctx, error, output); \ + if (status & 1) \ + status = cam_name(Name, A, F, Count, D, Mem, (unsigned short *)&iosb); \ + return CheckErrors(status, (unsigned short *)&iosb, error, output); \ } -#define single_io(ccl_name, cam_name) \ - EXPORT int ccl_name(void *ctx, char **error, char **output) { \ - int status = ParseQualifiers(ctx, error); \ - if (status & 1) \ - status = cam_name(Name, A, F, D, Mem, (unsigned short *)&iosb); \ - return CheckErrors(status, (unsigned short *)&iosb, error, output); \ +#define single_io(ccl_name, cam_name) \ + EXPORT int ccl_name(void *ctx, char **error, char **output) \ + { \ + int status = ParseQualifiers(ctx, error); \ + if (status & 1) \ + status = cam_name(Name, A, F, D, Mem, (unsigned short *)&iosb); \ + return CheckErrors(status, (unsigned short *)&iosb, error, output); \ } single_io(ccl_pio, CamPiow) multi_io(ccl_fstop, CamFStopw) @@ -84,30 +88,39 @@ int ccl_show_module(); int ccl_show_status(); multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) - static int ParseQualifiers(void *ctx, char **error) { + static int ParseQualifiers(void *ctx, char **error) +{ int *d32; short *d16; int binary, hex, octal; int i; char *module = 0; char *value = 0; - if (cli_get_value(ctx, "module", &module) & 1) { + if (cli_get_value(ctx, "module", &module) & 1) + { free(Name); Name = module; - } else { - if (DefName) { + } + else + { + if (DefName) + { free(Name); Name = strdup(DefName); - } else { + } + else + { *error = strdup("No module selected\n"); return 0; } } A = 0; - if (cli_get_value(ctx, "address", &value) & 1) { + if (cli_get_value(ctx, "address", &value) & 1) + { char *endptr; A = strtol(value, &endptr, 0); - if (*endptr != '\0' || (A < 0) || (A > 15)) { + if (*endptr != '\0' || (A < 0) || (A > 15)) + { *error = malloc(strlen(value) + 100); sprintf(*error, "Error: invalid /ADDRESS value specified '%s'. Use a number from " @@ -119,10 +132,12 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) free(value); } F = 0; - if (cli_get_value(ctx, "function", &value) & 1) { + if (cli_get_value(ctx, "function", &value) & 1) + { char *endptr; F = strtol(value, &endptr, 0); - if (*endptr != '\0' || (F < 0) || (F > 31)) { + if (*endptr != '\0' || (F < 0) || (F > 31)) + { *error = malloc(strlen(value) + 100); sprintf(*error, "Error: invalid /FUNCTION value specified '%s'. Use a number " @@ -134,10 +149,12 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) free(value); } Count = 1; - if (cli_get_value(ctx, "count", &value) & 1) { + if (cli_get_value(ctx, "count", &value) & 1) + { char *endptr; Count = strtol(value, &endptr, 0); - if (*endptr != '\0' && (Count < 0)) { + if (*endptr != '\0' && (Count < 0)) + { *error = malloc(strlen(value) + 100); sprintf(*error, "Error: invalid /COUNT value specified '%s'. Use a number > 0.\n", @@ -148,10 +165,12 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) free(value); } Mem = 24; - if (cli_get_value(ctx, "memory", &value) & 1) { + if (cli_get_value(ctx, "memory", &value) & 1) + { char *endptr; Mem = strtol(value, &endptr, 0); - if (*endptr != '\0' || ((Mem != 16) && (Mem != 24))) { + if (*endptr != '\0' || ((Mem != 16) && (Mem != 24))) + { *error = malloc(strlen(value) + 100); sprintf(*error, "Error: invalid /MEMORY value specified '%s'. Use 16 or 24.\n", @@ -168,15 +187,20 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) binary = cli_present(ctx, "binary") & 1; hex = cli_present(ctx, "hex") & 1; octal = cli_present(ctx, "octal") & 1; - for (i = 0; i < Count; i++) { + for (i = 0; i < Count; i++) + { char *value = 0; int val = 0; - if (cli_get_value(ctx, "data", &value) & 1) { - if (binary) { + if (cli_get_value(ctx, "data", &value) & 1) + { + if (binary) + { size_t j; - for (j = 0; j < strlen(value); j++) { + for (j = 0; j < strlen(value); j++) + { char v = value[strlen(value) - j - 1]; - if (v != '0' && v != '1') { + if (v != '0' && v != '1') + { *error = malloc(strlen(value) + 200); sprintf( *error, @@ -188,11 +212,17 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) } val = val | ((v - '0') << j); } - } else if (hex) { + } + else if (hex) + { sscanf(value, "%x", &val); - } else if (octal) { + } + else if (octal) + { sscanf(value, "%o", &val); - } else { + } + else + { sscanf(value, "%d", &val); } free(value); @@ -205,7 +235,8 @@ multi_io(ccl_stop, CamStopw) not_implemented(ccl_wdata) return 1; } -static void append(char **target, char *string) { +static void append(char **target, char *string) +{ if (*target == NULL) *target = strdup(string); else @@ -213,25 +244,32 @@ static void append(char **target, char *string) { strcat(realloc(*target, strlen(*target) + strlen(string) + 1), string); } -static int CheckErrors(int status, IOSB *iosb, char **error, char **output) { +static int CheckErrors(int status, IOSB *iosb, char **error, char **output) +{ LastStatus = status; - if (status & 1) { - if (Xrequired) { + if (status & 1) + { + if (Xrequired) + { int x = CamX((unsigned short *)iosb) & 1; if (x && (Xrequired == -1)) *output = strdup("CAMX: got X=1, expecting X=0\n"); else if (!x && (Xrequired == 1)) *output = strdup("CAMNOX: got X=0, expecting X=1\n"); } - if (Qrequired) { + if (Qrequired) + { int q = CamQ((unsigned short *)iosb) & 1; if (q && (Qrequired == -1)) *output = strdup("CAMQ: got Q=1, expecting Q=0\n"); else if (!q && (Qrequired == 1)) *output = strdup("CAMNOQ: got Q=0, expecting Q=1\n"); } - } else { - if (*error == NULL) { + } + else + { + if (*error == NULL) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); sprintf(*error, "Error detected in CAMAC call, %s\n", msg); @@ -241,9 +279,11 @@ static int CheckErrors(int status, IOSB *iosb, char **error, char **output) { } EXPORT int ccl_set_xandq(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *value = 0; - if (cli_get_value(ctx, "x", &value) & 1) { + if (cli_get_value(ctx, "x", &value) & 1) + { if (value[0] == 'N' || value[0] == 'n') Xrequired = -1; else if (value[0] == 'Y' || value[0] == 'y') @@ -252,7 +292,8 @@ EXPORT int ccl_set_xandq(void *ctx, char **error __attribute__((unused)), Xrequired = 0; free(value); } - if (cli_get_value(ctx, "q", &value) & 1) { + if (cli_get_value(ctx, "q", &value) & 1) + { if (value[0] == 'N' || value[0] == 'n') Qrequired = -1; else if (value[0] == 'Y' || value[0] == 'y') @@ -265,14 +306,16 @@ EXPORT int ccl_set_xandq(void *ctx, char **error __attribute__((unused)), } EXPORT int ccl_set_module(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status = cli_get_value(ctx, "name", &DefName) & 1; return status; } EXPORT int ccl_show_module(void *ctx __attribute__((unused)), char **error __attribute__((unused)), - char **output) { + char **output) +{ *output = malloc((DefName ? strlen(DefName) : 12) + 100); sprintf(*output, "Module set to %s\n", DefName ? DefName : ""); return 1; @@ -280,7 +323,8 @@ EXPORT int ccl_show_module(void *ctx __attribute__((unused)), EXPORT int ccl_show_status(void *ctx __attribute__((unused)), char **error __attribute__((unused)), - char **output) { + char **output) +{ *output = malloc(100); sprintf(*output, "Last status = 0x%x, iosb status = 0x%x, bytcnt = %d, %s, %s\n", @@ -291,7 +335,8 @@ EXPORT int ccl_show_status(void *ctx __attribute__((unused)), } EXPORT int ccl_show_data(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ int *d32 = (int *)D; short *d16 = (short *)D; int binary = cli_present(ctx, "binary") & 1; @@ -321,7 +366,8 @@ EXPORT int ccl_show_data(void *ctx, char **error __attribute__((unused)), last = first; if (last > maxsmps) last = maxsmps; - for (i = first, chars = 0; (first > 0) && (i <= last); i++) { + for (i = first, chars = 0; (first > 0) && (i <= last); i++) + { if (chars == 0) chars = sprintf(outline, "%06d ", i); if (octal) @@ -330,9 +376,11 @@ EXPORT int ccl_show_data(void *ctx, char **error __attribute__((unused)), format = (Mem == 24) ? " %#011x" : " %#06hx"; else format = (Mem == 24) ? " %11d" : " %6hd"; - if (binary) { + if (binary) + { int j, mask, first = 1; - for (j = Mem - 1; j >= 0; j--) { + for (j = Mem - 1; j >= 0; j--) + { char c; mask = 1 << j; c = ((Mem == 24) ? d32[i - 1] : d16[i - 1]) & mask ? '1' : '0'; @@ -342,17 +390,20 @@ EXPORT int ccl_show_data(void *ctx, char **error __attribute__((unused)), outline[chars++] = c; } outline[chars] = '\0'; - } else + } + else chars += sprintf(&outline[chars], format, (Mem == 24) ? d32[i - 1] : d16[i - 1]); - if (chars > 72) { + if (chars > 72) + { outline[chars++] = '\n'; outline[chars] = '\0'; append(output, outline); chars = 0; } } - if (chars > 0) { + if (chars > 0) + { outline[chars++] = '\n'; outline[chars] = '\0'; append(output, outline); @@ -362,12 +413,14 @@ EXPORT int ccl_show_data(void *ctx, char **error __attribute__((unused)), EXPORT int ccl_set_verbose(void *cts __attribute__((unused)), char **error __attribute__((unused)), - char **output __attribute((unused))) { + char **output __attribute((unused))) +{ return CamVerbose(1); } EXPORT int ccl_set_noverbose(void *cts __attribute__((unused)), char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ return CamVerbose(0); } diff --git a/clang-format.sh b/clang-format.sh new file mode 100755 index 0000000000..2df2ac0c34 --- /dev/null +++ b/clang-format.sh @@ -0,0 +1,16 @@ +#!/bin/sh +dir=$(dirname $0) +exclude_path="-path .git" +exclude_file= +for o in build mitdevices opcbuiltins.h 3rd-party-apis mdstcpip/udt4 mdstcpip/zlib mdsobjects/cpp/rapidjson +do + if test -d $o + then exclude_path="$exclude_path -o -path $dir/$o" + else exclude_file="$exclude_file ! -name $o" + fi +done + +find $dir/$1 \( $exclude_path \) -prune -false\ + -o \( -type f \( -regex '.*\.\(c\|h\)\(pp\|\)$' $exclude_file \) \)\ + -exec clang-format -i -style=file \{\} \;\ + -exec sed -i -E '{N;s/(\/\/[^\n]*)\\\n\s*\/\//\1/g;P;D}' \{\} \; diff --git a/conf/valgrind.supp/fc32.supp b/conf/valgrind.supp/fc32.supp index 70de0b8cc7..a5f82df54c 100644 --- a/conf/valgrind.supp/fc32.supp +++ b/conf/valgrind.supp/fc32.supp @@ -242,6 +242,11 @@ obj:/usr/lib64/libpython3.8.so.1.0 fun:_PyEval_EvalFrameDefault } +{ + memmove + Helgrind:Race + fun:memmove + obj:/usr/lib64/libpython3.8.so.1.0 { PyEval_AcquireThread Helgrind:Race diff --git a/deploy/yylex.gen b/deploy/yylex.gen index a1d8092294..80dc4b801d 100755 --- a/deploy/yylex.gen +++ b/deploy/yylex.gen @@ -35,4 +35,7 @@ loop() { for o in $1/yylex/*.$2; do job $2 $o; done; } loop $1 y loop $1 l loop $1 gen -# sed -i 's/int num_to_read/size_t num_to_read/g' $(echo $(cat $1/yylex/outfiles)) +if [ -f $1/yylex/fixme-files ]; then +sed -i 's/\(size_t\|int\)\ n\;\s*\\/typeof(max_size) n\; \\/g'\ + $(echo $(cat $1/yylex/fixme-files)) +fi \ No newline at end of file diff --git a/device_support/basler/BASLERACA.cpp b/device_support/basler/BASLERACA.cpp index 4f75db13bd..f5dba51fa1 100644 --- a/device_support/basler/BASLERACA.cpp +++ b/device_support/basler/BASLERACA.cpp @@ -53,198 +53,231 @@ static BASLER_ACA *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int baslerOpen(const char *ipAddress, int *camHandle) { - BASLER_ACA *cam; - int cameraHandle; + int baslerOpen(const char *ipAddress, int *camHandle) + { + BASLER_ACA *cam; + int cameraHandle; - errorOnOpen[0] = 0; + errorOnOpen[0] = 0; - cam = new BASLER_ACA(ipAddress); + cam = new BASLER_ACA(ipAddress); - if (cam->checkLastOp() == ERROR) { - cam->getLastError(errorOnOpen); - delete (cam); - return ERROR; - } + if (cam->checkLastOp() == ERROR) + { + cam->getLastError(errorOnOpen); + delete (cam); + return ERROR; + } - for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; - cameraHandle++) - ; + for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; + cameraHandle++) + ; - if (cameraHandle < MAX_CAM) { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } else { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; + if (cameraHandle < MAX_CAM) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } } -} -int baslerIsConnected(int camHandle) { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; + int baslerIsConnected(int camHandle) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; } - return SUCCESS; -} -int baslerClose(int camHandle) { - delete (camPtr[camHandle]); - camPtr[camHandle] = 0; + int baslerClose(int camHandle) + { + delete (camPtr[camHandle]); + camPtr[camHandle] = 0; - return SUCCESS; -} + return SUCCESS; + } -int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } + int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } -int readInternalTemperature(int camHandle) { - return camPtr[camHandle]->readInternalTemperature(); -} + int readInternalTemperature(int camHandle) + { + return camPtr[camHandle]->readInternalTemperature(); + } -int setExposure(int camHandle, double exposure) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposure(exposure); - return ERROR; -} + int setExposure(int camHandle, double exposure) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setExposure(exposure); + return ERROR; + } -int setExposureAuto(int camHandle, char *exposureAuto) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposureAuto(exposureAuto); - return ERROR; -} + int setExposureAuto(int camHandle, char *exposureAuto) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setExposureAuto(exposureAuto); + return ERROR; + } -int setGain(int camHandle, int gain) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGain(gain); - return ERROR; -} + int setGain(int camHandle, int gain) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGain(gain); + return ERROR; + } -int setGainAuto(int camHandle, char *gainAuto) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGainAuto(gainAuto); - return ERROR; -} + int setGainAuto(int camHandle, char *gainAuto) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGainAuto(gainAuto); + return ERROR; + } -int setGammaEnable(int camHandle, char *gammaEnable) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGammaEnable(gammaEnable); - return ERROR; -} + int setGammaEnable(int camHandle, char *gammaEnable) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGammaEnable(gammaEnable); + return ERROR; + } -int setFrameRate(int camHandle, double frameRate) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate); - return ERROR; -} + int setFrameRate(int camHandle, double frameRate) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setFrameRate(frameRate); + return ERROR; + } -int setReadoutArea(int camHandle, int x, int y, int width, int height) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; -} + int setReadoutArea(int camHandle, int x, int y, int width, int height) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; + } -int setPixelFormat(int camHandle, char *pixelFormat) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setPixelFormat(pixelFormat); - return ERROR; -} + int setPixelFormat(int camHandle, char *pixelFormat) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setPixelFormat(pixelFormat); + return ERROR; + } -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; -} + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; + } -int stopAcquisition(int camHandle) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; -} + int stopAcquisition(int camHandle) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; + } -int getFrame(int camHandle, int *status, void *frame, void *metaData) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; -} + int getFrame(int camHandle, int *status, void *frame, void *metaData) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; + } -int setAcquisitionMode(int camHandle, int storeEnabled, - int acqSkipFrameNumber) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setAcquisitionMode(storeEnabled, - acqSkipFrameNumber); - return ERROR; -} + int setAcquisitionMode(int camHandle, int storeEnabled, + int acqSkipFrameNumber) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setAcquisitionMode(storeEnabled, + acqSkipFrameNumber); + return ERROR; + } -int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, - numTrigger); - return ERROR; -} + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, + int numTrigger) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, + numTrigger); + return ERROR; + } -int softwareTrigger(int camHandle) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; -} + int softwareTrigger(int camHandle) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; + } -int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, - framesMetadNid, frame0TimeNid); - return ERROR; -} + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, + int framesMetadNid, int frame0TimeNid) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, + framesMetadNid, frame0TimeNid); + return ERROR; + } -int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, int lowLim, - int highLim, int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setStreamingMode( - streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, - lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); - return ERROR; -} + int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, + int highLim, int adjRoiX, int adjRoiY, int adjRoiW, + int adjRoiH, const char *deviceName) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setStreamingMode( + streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, + lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + return ERROR; + } -int startFramesAcquisition(int camHandle) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; -} + int startFramesAcquisition(int camHandle) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; + } -int stopFramesAcquisition(int camHandle) { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; -} + int stopFramesAcquisition(int camHandle) + { + if (baslerIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; + } -void getLastError(int camHandle, char *msg) { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) { - sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); - return; + void getLastError(int camHandle, char *msg) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); } - camPtr[camHandle]->getLastError(msg); -} #ifdef __cplusplus } #endif -BASLER_ACA::BASLER_ACA(const char *ipAddress) { - try { +BASLER_ACA::BASLER_ACA(const char *ipAddress) +{ + try + { memset(error, 0, sizeof(error)); memcpy(this->ipAddress, ipAddress, strlen(ipAddress) + 1); this->pCamera = NULL; printf("\n Init COUNT = %d %d\n", this->getCount()); - if (this->getCount() == 1) { + if (this->getCount() == 1) + { printf("\n\n%s:Pylon Inizialize.\n\n", this->ipAddress); PylonInitialize(); } @@ -258,7 +291,9 @@ BASLER_ACA::BASLER_ACA(const char *ipAddress) { pCamera->Open(); printf("%s: Device Connected.\n", this->ipAddress); lastOpRes = SUCCESS; - } catch (const GenericException &e) { + } + catch (const GenericException &e) + { cerr << this->ipAddress << ": Error Device connection. Reason: " << e.GetDescription() << endl; lastOpRes = ERROR; @@ -273,20 +308,23 @@ BASLER_ACA::BASLER_ACA() // new 25/07/2013: let to use the device without the // telecamera } -BASLER_ACA::~BASLER_ACA() { +BASLER_ACA::~BASLER_ACA() +{ printf("COUNT = %d %d\n", this->getCount(), pCamera); /* if ( pCamera != NULL && pCamera->IsOpen() ) pCamera->Close(); */ - if (this->getCount() == 1) { + if (this->getCount() == 1) + { printf("PylonTerminate.\n"); PylonTerminate(); } printf("%s: Device Disconnected.\n", this->ipAddress); } -int BASLER_ACA::checkLastOp() { +int BASLER_ACA::checkLastOp() +{ /* printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii() ); if ( !this->lResult.IsOK() ) @@ -296,7 +334,8 @@ int BASLER_ACA::checkLastOp() { return lastOpRes; } -int BASLER_ACA::readInternalTemperature() { +int BASLER_ACA::readInternalTemperature() +{ // Select the kind of internal temperature as the device temperature pCamera->TemperatureSelector.SetValue(TemperatureSelector_Coreboard); // Read the device temperature @@ -307,8 +346,10 @@ int BASLER_ACA::readInternalTemperature() { return SUCCESS; } -int BASLER_ACA::setExposure(double exposure) { - if (IsWritable(pCamera->ExposureTimeAbs)) { +int BASLER_ACA::setExposure(double exposure) +{ + if (IsWritable(pCamera->ExposureTimeAbs)) + { pCamera->ExposureTimeAbs.SetValue(exposure); // pCamera->ExposureTimeRaw.SetValue(exposure); //not to use! cout << this->ipAddress << ": Exposure set to: " << exposure << endl; @@ -318,7 +359,8 @@ int BASLER_ACA::setExposure(double exposure) { return SUCCESS; } -int BASLER_ACA::setExposureAuto(char *exposureAuto) { +int BASLER_ACA::setExposureAuto(char *exposureAuto) +{ INodeMap &nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("ExposureAuto")); @@ -332,7 +374,8 @@ int BASLER_ACA::setExposureAuto(char *exposureAuto) { return SUCCESS; } -int BASLER_ACA::setGainAuto(char *gainAuto) { +int BASLER_ACA::setGainAuto(char *gainAuto) +{ INodeMap &nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("GainAuto")); @@ -346,8 +389,10 @@ int BASLER_ACA::setGainAuto(char *gainAuto) { return SUCCESS; } -int BASLER_ACA::setGain(int gain) { - if (IsWritable(pCamera->GainRaw)) { +int BASLER_ACA::setGain(int gain) +{ + if (IsWritable(pCamera->GainRaw)) + { pCamera->GainRaw.SetValue(gain); cout << this->ipAddress << ": Gain set to: " << gain << endl; } @@ -356,11 +401,14 @@ int BASLER_ACA::setGain(int gain) { return SUCCESS; } -int BASLER_ACA::setGammaEnable(char *gammaEnable) { - if (strcmp(gammaEnable, "On") == 0) { +int BASLER_ACA::setGammaEnable(char *gammaEnable) +{ + if (strcmp(gammaEnable, "On") == 0) + { pCamera->GammaEnable.SetValue(true); } - if (strcmp(gammaEnable, "Off") == 0) { + if (strcmp(gammaEnable, "Off") == 0) + { pCamera->GammaEnable.SetValue(false); } @@ -368,7 +416,8 @@ int BASLER_ACA::setGammaEnable(char *gammaEnable) { return SUCCESS; } -int BASLER_ACA::setFrameRate(double frameRate) { +int BASLER_ACA::setFrameRate(double frameRate) +{ pCamera->AcquisitionFrameRateEnable.SetValue(true); pCamera->AcquisitionFrameRateAbs.SetValue(frameRate); cout << this->ipAddress << ": Frame Rate set to: " << frameRate << endl; @@ -376,10 +425,12 @@ int BASLER_ACA::setFrameRate(double frameRate) { return SUCCESS; } -int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) { +int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) +{ INodeMap &nodeMap = pCamera->GetNodeMap(); - try { + try + { CIntegerPtr offsetX(nodeMap.GetNode("OffsetX")); CIntegerPtr offsetY(nodeMap.GetNode("OffsetY")); CIntegerPtr widthCI(nodeMap.GetNode("Width")); @@ -392,7 +443,8 @@ int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) { { offsetX->SetValue(offsetX->GetMin()); } - if (IsWritable(offsetY)) { + if (IsWritable(offsetY)) + { offsetY->SetValue(offsetY->GetMin()); } @@ -406,7 +458,8 @@ int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) { lastOpRes = ERROR; return ERROR; } - if ((y + height) > heightCI->GetMax()) { + if ((y + height) > heightCI->GetMax()) + { printf("%s: ERROR in setReadoutArea: OffsetY + Height exceed maximum " "allowed.", this->ipAddress); @@ -431,20 +484,24 @@ int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) { << endl; return SUCCESS; - } catch (const GenericException &e) { + } + catch (const GenericException &e) + { cerr << "Error in setReadoutArea. Reason: " << e.GetDescription() << endl; lastOpRes = ERROR; } return ERROR; } -int BASLER_ACA::setPixelFormat(char *pixelFormat) { +int BASLER_ACA::setPixelFormat(char *pixelFormat) +{ INodeMap &nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("PixelFormat")); if (IsAvailable(pFormat->GetEntryByName(pixelFormat)) == false) // if not available set to Mono12 or Mono8 { - if (IsAvailable(pFormat->GetEntryByName("Mono12"))) { + if (IsAvailable(pFormat->GetEntryByName("Mono12"))) + { pFormat->FromString("Mono12"); cout << this->ipAddress << ": (WARNING) Selected PixelFormat is NOT available. Pixel format " @@ -453,7 +510,9 @@ int BASLER_ACA::setPixelFormat(char *pixelFormat) { this->pixelFormat = CSU_PIX_FMT_GRAY16; this->Bpp = 2; return SUCCESS; - } else { + } + else + { pFormat->FromString("Mono8"); cout << this->ipAddress << ": (WARNING) Selected PixelFormat is NOT available. PixelFormat " @@ -463,23 +522,29 @@ int BASLER_ACA::setPixelFormat(char *pixelFormat) { this->Bpp = 1; return SUCCESS; } - } else { + } + else + { pFormat->FromString(pixelFormat); cout << this->ipAddress << ": PixelFormat set to : " << pFormat->ToString() << endl; - if (strcmp(pixelFormat, "Mono8") == 0) { + if (strcmp(pixelFormat, "Mono8") == 0) + { this->pixelFormat = CSU_PIX_FMT_GRAY8; this->Bpp = 1; } - if (strcmp(pixelFormat, "Mono12") == 0) { + if (strcmp(pixelFormat, "Mono12") == 0) + { this->pixelFormat = CSU_PIX_FMT_GRAY16; this->Bpp = 2; } - if (strcmp(pixelFormat, "BayerRG8") == 0) { + if (strcmp(pixelFormat, "BayerRG8") == 0) + { this->pixelFormat = CSU_PIX_FMT_BAYER_RGGB8; this->Bpp = 1; } - if (strcmp(pixelFormat, "YUV422Packed") == 0) { + if (strcmp(pixelFormat, "YUV422Packed") == 0) + { this->pixelFormat = CSU_PIX_FMT_YUV422_Packed; this->Bpp = 2; } @@ -489,7 +554,8 @@ int BASLER_ACA::setPixelFormat(char *pixelFormat) { return ERROR; } -int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) { +int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) +{ INodeMap &nodeMap = pCamera->GetNodeMap(); INode *node; @@ -513,27 +579,33 @@ int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) { // Enable chunks in general. node = nodeMap.GetNode("ChunkModeActive"); - if (IsWritable(node)) { + if (IsWritable(node)) + { CBooleanPtr(node)->SetValue(true); - } else { + } + else + { throw RUNTIME_EXCEPTION("The camera doesn't support chunk features"); } // Enable time stamp chunks. CEnumerationPtr ChunkSelector(nodeMap.GetNode("ChunkSelector")); - if (IsAvailable(ChunkSelector->GetEntryByName("Timestamp"))) { + if (IsAvailable(ChunkSelector->GetEntryByName("Timestamp"))) + { ChunkSelector->FromString("Timestamp"); } node = nodeMap.GetNode("ChunkEnable"); CBooleanPtr(node)->SetValue(true); - if (IsAvailable(ChunkSelector->GetEntryByName("PayloadCRC16"))) { + if (IsAvailable(ChunkSelector->GetEntryByName("PayloadCRC16"))) + { ChunkSelector->FromString("PayloadCRC16"); } node = nodeMap.GetNode("ChunkEnable"); CBooleanPtr(node)->SetValue(true); // new fede 20170918 - if (IsAvailable(ChunkSelector->GetEntryByName("ExposureTime"))) { + if (IsAvailable(ChunkSelector->GetEntryByName("ExposureTime"))) + { ChunkSelector->FromString("ExposureTime"); cout << this->ipAddress << ": New ChunkSelector_ExposureTime: " << ChunkSelector->ToString() @@ -542,7 +614,8 @@ int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) { node = nodeMap.GetNode("ChunkEnable"); CBooleanPtr(node)->SetValue(true); - if (IsAvailable(ChunkSelector->GetEntryByName("GainAll"))) { + if (IsAvailable(ChunkSelector->GetEntryByName("GainAll"))) + { ChunkSelector->FromString("GainAll"); cout << this->ipAddress << ": New ChunkSelector_GainAll: " << ChunkSelector->ToString() @@ -567,23 +640,29 @@ int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) { return SUCCESS; } -int BASLER_ACA::stopAcquisition() { +int BASLER_ACA::stopAcquisition() +{ pCamera->StopGrabbing(); printf("%s: Stop Acquisition\n", this->ipAddress); return SUCCESS; } -int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) { +int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) +{ // This smart pointer will receive the grab result data. CGrabResultPtr ptrGrabResult; - if (pCamera->IsGrabbing()) { + if (pCamera->IsGrabbing()) + { // printf("getframe is grabbing\n"); // Wait for an image and then retrieve it. A timeout of 5000 ms is used. - try { + try + { pCamera->RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException); - } catch (const GenericException &e) { + } + catch (const GenericException &e) + { // Error handling. cerr << this->ipAddress << "An exception occurred." << endl << e.GetDescription() << endl; @@ -605,7 +684,8 @@ int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) { // (uint32_t) dataPtr[0] << endl << endl; // Check to see if a buffer containing chunk data has been received. - if (PayloadType_ChunkData != ptrGrabResult->GetPayloadType()) { + if (PayloadType_ChunkData != ptrGrabResult->GetPayloadType()) + { throw RUNTIME_EXCEPTION("Unexpected payload type received."); } // Since we have activated the CRC Checksum feature, we can check @@ -613,25 +693,29 @@ int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) { // Note: Enabling the CRC Checksum feature is not a prerequisite for using // chunks. Chunks can also be handled when the CRC Checksum feature is // deactivated. - if (ptrGrabResult->HasCRC() && ptrGrabResult->CheckCRC() == false) { + if (ptrGrabResult->HasCRC() && ptrGrabResult->CheckCRC() == false) + { throw RUNTIME_EXCEPTION("Image was damaged!"); } int64_t ts; - if (ptrGrabResult->IsChunkDataAvailable()) { + if (ptrGrabResult->IsChunkDataAvailable()) + { INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); ts = CIntegerPtr(nodeMap.GetNode("ChunkTimestamp"))->GetValue(); // printf("%I64d\n", ts); } int gain = 0; - if (ptrGrabResult->IsChunkDataAvailable()) { + if (ptrGrabResult->IsChunkDataAvailable()) + { INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); gain = CIntegerPtr(nodeMap.GetNode("ChunkGainAll"))->GetValue(); // printf("fede gainall chunk:%d\n", gain); } double exp = 0; - if (ptrGrabResult->IsChunkDataAvailable()) { + if (ptrGrabResult->IsChunkDataAvailable()) + { INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); exp = CFloatPtr(nodeMap.GetNode("ChunkExposureTime"))->GetValue(); // printf("fede exp chunk:%f\n", exp); @@ -646,7 +730,8 @@ int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) { memcpy(metaData, (unsigned char *)&bMeta, sizeof(BASLERMETADATA)); } // if (ptrGrabResult->GrabSucceeded() - else { + else + { cout << this->ipAddress << ": Grab Error: " << ptrGrabResult->GetErrorCode() << " " << ptrGrabResult->GetErrorDescription() << endl; @@ -658,10 +743,12 @@ int BASLER_ACA::setStreamingMode(int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) { + int adjRoiH, const char *deviceName) +{ this->streamingEnabled = streamingEnabled; - if (streamingEnabled) { + if (streamingEnabled) + { memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); this->streamingPort = streamingPort; @@ -681,7 +768,8 @@ int BASLER_ACA::setStreamingMode(int streamingEnabled, bool autoAdjustLimit, return SUCCESS; } -int BASLER_ACA::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) { +int BASLER_ACA::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) +{ this->storeEnabled = storeEnabled; this->acqSkipFrameNumber = acqSkipFrameNumber; @@ -689,7 +777,8 @@ int BASLER_ACA::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) { } int BASLER_ACA::setTriggerMode(int triggerMode, double burstDuration, - int numTrigger) { + int numTrigger) +{ this->triggerMode = triggerMode; this->burstDuration = burstDuration; this->numTrigger = numTrigger; @@ -697,13 +786,15 @@ int BASLER_ACA::setTriggerMode(int triggerMode, double burstDuration, return SUCCESS; } -int BASLER_ACA::softwareTrigger() { +int BASLER_ACA::softwareTrigger() +{ this->startStoreTrg = 1; return SUCCESS; } int BASLER_ACA::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) { + int framesMetadNid, int frame0TimeNid) +{ this->treePtr = treePtr; this->framesNid = framesNid; this->timebaseNid = timebaseNid; @@ -724,11 +815,13 @@ void FLIR_SC65X::printLastError(const char *format, const char *msg) } */ -void BASLER_ACA::getLastError(char *msg) { +void BASLER_ACA::getLastError(char *msg) +{ sprintf(msg, "%s:%s", this->ipAddress, (error[0] == 0) ? "" : error); } -int BASLER_ACA::stopFramesAcquisition() { +int BASLER_ACA::stopFramesAcquisition() +{ int count = 0; if (acqFlag == 0) @@ -736,12 +829,14 @@ int BASLER_ACA::stopFramesAcquisition() { acqStopped = 0; acqFlag = 0; - while (!acqStopped & count < 20) { + while (!acqStopped & count < 20) + { count++; usleep(50000); } - if (count == 20) { + if (count == 20) + { sprintf(error, "%s: Cannot stop acquisition loop\n", this->ipAddress); return ERROR; } @@ -749,7 +844,8 @@ int BASLER_ACA::stopFramesAcquisition() { return SUCCESS; } -int BASLER_ACA::startFramesAcquisition() { +int BASLER_ACA::startFramesAcquisition() +{ int frameTriggerCounter; int frameCounter; int frameStatus; @@ -775,11 +871,14 @@ int BASLER_ACA::startFramesAcquisition() { int64_t timeStamp; int64_t timeStamp0; TreeNode *t0Node; - try { + try + { t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); Data *nodeData = t0Node->getData(); timeStamp0 = (int64_t)nodeData->getLong(); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { sprintf(error, "%s: Error getting frame0 time\n", this->ipAddress); } @@ -787,11 +886,14 @@ int BASLER_ACA::startFramesAcquisition() { // (ex. T_START_SPIDER) { TreeNode *tStartOffset; - try { + try + { tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); Data *nodeData = tStartOffset->getData(); timeOffset = (float)nodeData->getFloatArray()[0]; - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { sprintf(error, "%s: Error getting timebaseNid (offset time set to 0.0s)\n", this->ipAddress); @@ -799,10 +901,12 @@ int BASLER_ACA::startFramesAcquisition() { } } - if (this->Bpp == 1) { + if (this->Bpp == 1) + { frameBuffer = (char *)calloc(1, width * height * sizeof(char)); } - if (this->Bpp == 2) { + if (this->Bpp == 2) + { frameBuffer = (short *)calloc(1, width * height * sizeof(short)); } frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); @@ -822,10 +926,12 @@ int BASLER_ACA::startFramesAcquisition() { startStoreTrg = 0; // manage the mdsplus saving process. SAVE always start // with a SW or HW trigger. (0=no-save; 1=save) - while (acqFlag) { + while (acqFlag) + { getFrame(&frameStatus, frameBuffer, metaData); // get the frame - if (storeEnabled) { + if (storeEnabled) + { if (triggerMode == 1) // External trigger source { @@ -837,7 +943,8 @@ int BASLER_ACA::startFramesAcquisition() { printf("%s: TRIGGERED:\n", this->ipAddress); } - if (frameTriggerCounter == burstNframe) { + if (frameTriggerCounter == burstNframe) + { triggered = 0; startStoreTrg = 0; // disable storing NtriggerCount++; @@ -855,29 +962,34 @@ int BASLER_ACA::startFramesAcquisition() { // break; } } // if (frameTriggerCounter == burstNframe) - - } else //( triggerMode == 1 ) //Internal trigger source + } + else //( triggerMode == 1 ) //Internal trigger source { // Multiple trigger acquisition: first trigger save 64bit timestamp timebaseNid = -1; // used in cammdsutils to use internal triggered = 1; // debug - if (startStoreTrg == 1) { + if (startStoreTrg == 1) + { gettimeofday(&tv, NULL); timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - if (timeStamp0 == 0) { + if (timeStamp0 == 0) + { Int64 *tsMDS = new Int64(timeStamp); t0Node->putData(tsMDS); timeStamp0 = timeStamp; - } else { + } + else + { frameTime = (float)((timeStamp - timeStamp0) / 1000.0); // interval from first frame [s] // printf("frameTime: %f", frameTime); } } // if startStoreTrg == 1 - if (frameTriggerCounter == burstNframe) { + if (frameTriggerCounter == burstNframe) + { startStoreTrg = 0; // disable storing frameTriggerCounter = 0; NtriggerCount++; @@ -894,7 +1006,8 @@ int BASLER_ACA::startFramesAcquisition() { // # status=4 triggered frame + complete if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && (acqSkipFrameNumber <= 0 || - (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) { + (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) + { int frameTimeBaseIdx; frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; // printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, @@ -917,15 +1030,20 @@ int BASLER_ACA::startFramesAcquisition() { enqueueFrameNumber++; } - if (streamingEnabled) { - if (tcpStreamHandle == -1) { + if (streamingEnabled) + { + if (tcpStreamHandle == -1) + { rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); - if (rstatus != -1) { + if (rstatus != -1) + { printf("%s: Connected to FFMPEG on %s : %d\n", this->ipAddress, streamingServer, streamingPort); - } else { + } + else + { printf("%s, Cannot connect to FFMPEG on %s : %d. Disable streaming\n", this->ipAddress, streamingServer, streamingPort); streamingEnabled = 0; diff --git a/device_support/basler/BASLERACA.h b/device_support/basler/BASLERACA.h index 0cab82d466..6f03db7740 100644 --- a/device_support/basler/BASLERACA.h +++ b/device_support/basler/BASLERACA.h @@ -16,65 +16,87 @@ using namespace Basler_GigECameraParams; using namespace Pylon; // Namespace for using pylon objects. using namespace GenApi; // Namespace for using GenApi objects. -enum FPS_ENUM { fps_200, fps_100, fps_50, fps_25, fps_12, fps_6, fps_3 }; -enum IRFMT_ENUM { radiometric, linear10mK, linear100mK }; -enum EXPMODE_ENUM { internal_mode, external_mode }; +enum FPS_ENUM +{ + fps_200, + fps_100, + fps_50, + fps_25, + fps_12, + fps_6, + fps_3 +}; +enum IRFMT_ENUM +{ + radiometric, + linear10mK, + linear100mK +}; +enum EXPMODE_ENUM +{ + internal_mode, + external_mode +}; #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -// Wrapper for Python that must see the cpp class as standard C functions + // Wrapper for Python that must see the cpp class as standard C functions -int baslerOpen(const char *cameraName, int *camHandle); -int baslerClose(int camHandle); -/* + int baslerOpen(const char *cameraName, int *camHandle); + int baslerClose(int camHandle); + /* int checkLastOp(int camHandle); int printAllParameters(int camHandle); */ -int readInternalTemperature(int camHandle); -int setExposureAuto(int camHandle, char *exposureAuto); -int setExposure(int camHandle, double exposure); -int setGainAuto(int camHandle, char *gainAuto); -int setGammaEnable(int camHandle, char *gammaEnable); -int setGain(int camHandle, int gain); -int setFrameRate(int camHandle, double frameRate); -int setReadoutArea(int camHandle, int x, int y, int width, int height); -int setPixelFormat(int camHandle, char *pixelFormat); -int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); - -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); -int stopAcquisition(int camHandle); -int getFrame(int camHandle, int *status, void *frame, void *metaData); - -int startFramesAcquisition(int camHandle); -int stopFramesAcquisition(int camHandle); - -int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, int lowLim, - int highLim, int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName); - -int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger); -int softwareTrigger(int camHandle); -int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid); - -void getLastError(int camHandle, char *msg); + int readInternalTemperature(int camHandle); + int setExposureAuto(int camHandle, char *exposureAuto); + int setExposure(int camHandle, double exposure); + int setGainAuto(int camHandle, char *gainAuto); + int setGammaEnable(int camHandle, char *gammaEnable); + int setGain(int camHandle, int gain); + int setFrameRate(int camHandle, double frameRate); + int setReadoutArea(int camHandle, int x, int y, int width, int height); + int setPixelFormat(int camHandle, char *pixelFormat); + int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); + + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); + int stopAcquisition(int camHandle); + int getFrame(int camHandle, int *status, void *frame, void *metaData); + + int startFramesAcquisition(int camHandle); + int stopFramesAcquisition(int camHandle); + + int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, + int highLim, int adjRoiX, int adjRoiY, int adjRoiW, + int adjRoiH, const char *deviceName); + + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, + int numTrigger); + int softwareTrigger(int camHandle); + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, + int framesMetadNid, int frame0TimeNid); + + void getLastError(int camHandle, char *msg); #ifdef __cplusplus } #endif -typedef struct _baslerMetaData { +typedef struct _baslerMetaData +{ int gain; double exposure; double internalTemperature; int64_t timestamp; } BASLERMETADATA; -template class Counted { +template +class Counted +{ static int count; public: @@ -84,9 +106,11 @@ template class Counted { static int getCount() { return count; } }; -template int Counted::count = 0; +template +int Counted::count = 0; -class BASLER_ACA : public Counted { +class BASLER_ACA : public Counted +{ private: IPylonDevice *pDevice; // device handle Camera_t *pCamera; // camera handle diff --git a/device_support/basler/main.cpp b/device_support/basler/main.cpp index bfaa2666c1..a92732fb3b 100644 --- a/device_support/basler/main.cpp +++ b/device_support/basler/main.cpp @@ -7,10 +7,11 @@ using namespace MDSplus; #include #include -#define USETHECAMERA // this let to use the camera or if not defined to read +#define USETHECAMERA // this let to use the camera or if not defined to read \ // data from a pulse file. -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ if ((argv[1] == NULL) || (argv[2] == NULL) || (argv[3] == NULL)) // argv[4] is OPTIONAL @@ -24,7 +25,8 @@ int main(int argc, char **argv) { int res; void *treePtr; res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); - if (res == -1) { + if (res == -1) + { printf("Error opening tree...\n"); exit(0); } @@ -34,7 +36,8 @@ int main(int argc, char **argv) { TreeNode *nodeMeta; int framesNid, timebaseNid, framesMetadNid, frame0TimeNid; - try { + try + { tree = (Tree *)treePtr; node = tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAMES"); framesNid = node->getNid(); @@ -44,7 +47,9 @@ int main(int argc, char **argv) { framesMetadNid = node->getNid(); node = tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAME0_TIME"); frame0TimeNid = node->getNid(); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } diff --git a/device_support/caen/caenInterface.cpp b/device_support/caen/caenInterface.cpp index cf0ce6a6f6..265fbd108f 100644 --- a/device_support/caen/caenInterface.cpp +++ b/device_support/caen/caenInterface.cpp @@ -41,10 +41,10 @@ int caenLibDebug = 1; // sampling rate = 100MHz // gain at 10 MHz is about 1. #define FILTER_LEN 25 -int16_t coeffs[FILTER_LEN] = {547, 469, 95, -872, -2261, -3518, -3845, - -2528, 677, 5300, 10204, 13951, 15353, 13951, - 10204, 5300, 677, -2528, -3845, -3518, -2261, - -872, 95, 469, 547}; +int16_t coeffs[FILTER_LEN] = {547, 469, 95, -872, -2261, -3518, -3845, + -2528, 677, 5300, 10204, 13951, 15353, 13951, + 10204, 5300, 677, -2528, -3845, -3518, -2261, + -872, 95, 469, 547}; #define SAMPLES 8000 @@ -61,7 +61,8 @@ int16_t insamp[BUFFER_LEN]; void firFixedInit(void) { memset(insamp, 0, sizeof(insamp)); } // the FIR filter function void firFixed(int16_t *coeffs, int16_t *input, int16_t *output, int length, - int filterLength) { + int filterLength) +{ int32_t acc; // accumulator for MACs int16_t *coeffp; // pointer to coefficients int16_t *inputp; // pointer to input samples @@ -70,20 +71,25 @@ void firFixed(int16_t *coeffs, int16_t *input, int16_t *output, int length, // put the new samples at the high end of the buffer memcpy(&insamp[filterLength - 1], input, length * sizeof(int16_t)); // apply the filter to each input sample - for (n = 0; n < length; n++) { + for (n = 0; n < length; n++) + { // calculate output n coeffp = coeffs; inputp = &insamp[filterLength - 1 + n]; // load rounding constant acc = 1 << 14; // perform the multiply-accumulate - for (k = 0; k < filterLength; k++) { + for (k = 0; k < filterLength; k++) + { acc += (int32_t)(*coeffp++) * (int32_t)(*inputp--); } // saturate the result - if (acc > 0x3fffffff) { + if (acc > 0x3fffffff) + { acc = 0x3fffffff; - } else if (acc < -0x40000000) { + } + else if (acc < -0x40000000) + { acc = -0x40000000; } // convert from Q30 to Q15 @@ -98,7 +104,8 @@ void firFixed(int16_t *coeffs, int16_t *input, int16_t *output, int length, ////////////////////////////////////////////////////////////// // Support class for enqueueing storage requests -class SaveItem { +class SaveItem +{ void *segment; char dataType; int segmentSize; @@ -114,7 +121,8 @@ class SaveItem { public: SaveItem(void *segment, int segmentSize, char dataType, int startIdx_c, int endIdx_c, int segmentCount, int dataNid, int clockNid, - int triggerNid, void *treePtr) { + int triggerNid, void *treePtr) + { this->segment = segment; this->segmentSize = segmentSize; this->dataType = dataType; @@ -132,7 +140,8 @@ class SaveItem { SaveItem *getNext() { return nxt; } - void save() { + void save() + { TreeNode *dataNode = new TreeNode(dataNid, (Tree *)treePtr); TreeNode *clockNode = new TreeNode(clockNid, (Tree *)treePtr); @@ -160,23 +169,29 @@ class SaveItem { (Tree *)treePtr, 9, triggerNode, segCount, clockNode, startIdx, triggerNode, segCount, clockNode, endIdx, clockNode); - try { + try + { - switch (dataType) { - case DTYPE_W: { + switch (dataType) + { + case DTYPE_W: + { Int16Array *sData = new Int16Array((short *)segment, segmentSize); printf("Save short data segment idx %d endIdx_c %d\n", segmentCount, endIdx_c); dataNode->makeSegment(startTime, endTime, dim, sData); deleteData(sData); - } break; - case DTYPE_F: { + } + break; + case DTYPE_F: + { Float32Array *fData = new Float32Array((float *)segment, segmentSize); printf("Save flat data segment idx %d endIdx_c %d\n", segmentCount, endIdx_c); dataNode->makeSegment(startTime, endTime, dim, fData); deleteData(fData); - } break; + } + break; } free(segment); deleteData(startIdx); @@ -184,8 +199,9 @@ class SaveItem { deleteData(startTime); deleteData(endTime); deleteData(segCount); - - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Cannot put segment: %s\n", exc->what()); } delete dataNode; @@ -196,7 +212,8 @@ class SaveItem { extern "C" void *handleSave(void *listPtr); -class SaveList { +class SaveList +{ public: pthread_cond_t itemAvailable; pthread_t thread; @@ -206,7 +223,8 @@ class SaveList { pthread_mutex_t mutex; public: - SaveList() { + SaveList() + { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&itemAvailable, NULL); saveHead = saveTail = NULL; @@ -216,16 +234,20 @@ class SaveList { void addItem(void *segment, int segmentSize, char dataType, int startIdx_c, int endIdx_c, int segmentCount, int dataNid, int clockNid, - int triggerNid, void *treePtr) { + int triggerNid, void *treePtr) + { // printf("add Item\n"); int noFilter = 1; void *segmentc = calloc(1, segmentSize * sizeof(short)); int size; - if (noFilter) { + if (noFilter) + { memcpy(segmentc, segment, segmentSize * sizeof(short)); - } else { + } + else + { int cIdx = 0, currSize; // initialize the filter firFixedInit(); @@ -233,7 +255,8 @@ class SaveList { currSize = segmentSize; size = SAMPLES; printf("----Start Filter\n"); - while (currSize > 0) { + while (currSize > 0) + { size = (size > currSize ? currSize : size); firFixed(coeffs, &((int16_t *)segment)[cIdx], &((int16_t *)segmentc)[cIdx], size, FILTER_LEN); @@ -248,24 +271,30 @@ class SaveList { pthread_mutex_lock(&mutex); if (saveHead == NULL) saveHead = saveTail = newItem; - else { + else + { saveTail->setNext(newItem); saveTail = newItem; } pthread_cond_signal(&itemAvailable); pthread_mutex_unlock(&mutex); } - void executeItems() { - while (true) { + void executeItems() + { + while (true) + { pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } - while (saveHead == NULL) { + while (saveHead == NULL) + { pthread_cond_wait(&itemAvailable, &mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } @@ -289,52 +318,64 @@ class SaveList { delete currItem; } } - void start() { + void start() + { pthread_create(&thread, NULL, handleSave, (void *)this); threadCreated = true; } - void stop() { + void stop() + { stopReq = true; pthread_cond_signal(&itemAvailable); - if (threadCreated) { + if (threadCreated) + { pthread_join(thread, NULL); printf("SAVE THREAD TERMINATED\n"); } } }; -extern "C" void *handleSave(void *listPtr) { +extern "C" void *handleSave(void *listPtr) +{ SaveList *list = (SaveList *)listPtr; list->executeItems(); return NULL; } -extern "C" void startSave(void **retList) { +extern "C" void startSave(void **retList) +{ SaveList *saveList = new SaveList; saveList->start(); *retList = (void *)saveList; } -extern "C" void stopSave(void *listPtr) { - if (listPtr) { +extern "C" void stopSave(void *listPtr) +{ + if (listPtr) + { SaveList *list = (SaveList *)listPtr; list->stop(); delete list; } } -extern "C" void openTree(char *name, int shot, void **treePtr) { - try { +extern "C" void openTree(char *name, int shot, void **treePtr) +{ + try + { Tree *tree = new Tree(name, shot); *treePtr = (void *)tree; - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Cannot open tree %s %d: %s\n", name, shot, exc->what()); } } #define MAX_CHANNELS 4 -struct segment_struct { +struct segment_struct +{ int eventSize; int boardGroup; int counter; @@ -369,7 +410,8 @@ readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, // Read number of buffers status = CAENVME_ReadCycle(handle, (vmeAddress + 0x812C), &actSegments, cvA32_S_DATA, cvD32); - if (status != 0) { + if (status != 0) + { onError("Error reading number of acquired segments"); return 0; } @@ -383,12 +425,14 @@ readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, short *buff = (short *)calloc(1, 16 + nActChans * segmentSamples * sizeof(short)); - for (int chan = 0; chan < numChannels; chan++) { + for (int chan = 0; chan < numChannels; chan++) + { channels[chan] = (short *)calloc(1, currChanSamples * actSegments * sizeof(short)); } - for (int segmentIdx = 0; segmentIdx < actSegments; segmentIdx++) { + for (int segmentIdx = 0; segmentIdx < actSegments; segmentIdx++) + { int retLen = 0; // printf("Read CAENVME_FIFOBLTReadCycle %d vmeAddress %d segmentSize %d\n", @@ -396,7 +440,8 @@ readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, status = CAENVME_FIFOBLTReadCycle(handle, vmeAddress, buff, segmentSize, cvA32_S_DATA, cvD64, &retLen); - if (status != 0) { + if (status != 0) + { free(buff); onError("ASYNCH: Error reading data segment"); return 0; @@ -414,8 +459,10 @@ readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, printf("Read actSize %d counter %d sizeInInts %d retLen %d Index %d\n", actSize, counter, sizeInInts, retLen, segment.time % actSize); - for (int chan = 0; chan < numChannels; chan++) { - if ((chanMask & (1 << chan)) != 0) { + for (int chan = 0; chan < numChannels; chan++) + { + if ((chanMask & (1 << chan)) != 0) + { if (caenLibDebug) printf("---Seg Idx %d - channels[%d][%d : %d], &buff[%d : %d]\n", segmentIdx, chan, segmentIdx * currChanSamples, @@ -431,12 +478,17 @@ readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, free(buff); - if (actSegments > 0) { - - for (int chan = 0; chan < numChannels; chan++) { - if ((chanMask & (1 << chan)) != 0) { - for (int seg = 0; seg < actSegments; seg++) { - if (numSegment > 0 && segmentCounter + seg > numSegment) { + if (actSegments > 0) + { + + for (int chan = 0; chan < numChannels; chan++) + { + if ((chanMask & (1 << chan)) != 0) + { + for (int seg = 0; seg < actSegments; seg++) + { + if (numSegment > 0 && segmentCounter + seg > numSegment) + { if (caenLibDebug) printf("skip seg %d for channel %d\n", (segmentCounter + seg), chan); diff --git a/device_support/camera_utils/cammdsutils.cpp b/device_support/camera_utils/cammdsutils.cpp index 5fdbc27cf6..9c244761cf 100644 --- a/device_support/camera_utils/cammdsutils.cpp +++ b/device_support/camera_utils/cammdsutils.cpp @@ -33,7 +33,8 @@ using namespace std; //#define DEBUG // Support class for enqueueing Frame storage requests -class SaveFrame { +class SaveFrame +{ void *frame; int width; @@ -56,7 +57,8 @@ class SaveFrame { public: SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, - void *frameMetadata, int metaSize, int metaNid) { + void *frameMetadata, int metaSize, int metaNid) + { this->frame = frame; this->width = width; this->height = height; @@ -76,7 +78,8 @@ class SaveFrame { nxt = 0; } SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, - void *treePtr, int dataNid, int timebaseNid, int frameIdx) { + void *treePtr, int dataNid, int timebaseNid, int frameIdx) + { this->frame = frame; this->width = width; this->height = height; @@ -100,7 +103,8 @@ class SaveFrame { SaveFrame *getNext() { return nxt; } - void save() { + void save() + { int dataDims[] = {1, height, width}; int metaDims[] = {1, metaSize}; @@ -117,18 +121,23 @@ class SaveFrame { metaData = new Int8Array((char *)frameMetadata, 2, metaDims); // check pixel size format - if (pixelSize <= 8) { + if (pixelSize <= 8) + { data = new Int8Array((char *)frame, 3, dataDims); #ifdef DEBUG printf("Pixel Format: 8bit.\n"); #endif - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { data = new Int16Array((short *)frame, 3, dataDims); #ifdef DEBUG printf("Pixel Format: 16bit. %d %d %d\n", dataDims[0], dataDims[1], dataDims[2]); #endif - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { data = new Int32Array((int *)frame, 3, dataDims); #ifdef DEBUG printf("Pixel Format: 32bit.\n"); @@ -142,7 +151,8 @@ class SaveFrame { Data *time; Data *dim; - try { + try + { timebaseNode = new TreeNode(timebaseNid, (Tree *)treePtr); #ifdef DEBUG printf("SAVE Frame IDX %d %s\n", frameIdx, dataNode->decompile()); @@ -153,10 +163,13 @@ class SaveFrame { dim = compileWithArgs("fs_float([$1[$2]])", (Tree *)treePtr, 2, timebaseNode, idxData); dataNode->makeSegment(time, time, dim, (Array *)data); - if (hasMetadata && metaSize > 0) { + if (hasMetadata && metaSize > 0) + { metaNode->makeSegment(time, time, dim, (Array *)metaData); } - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { cout << "ERROR WRITING SEGMENT: " << exc->what() << "\n"; } deleteData(data); @@ -173,32 +186,39 @@ class SaveFrame { delete (short *)frame; else if (pixelSize <= 32) delete (int *)frame; - - } else // timebase NOT defined (int. trigger) + } + else // timebase NOT defined (int. trigger) { Data *dim; Data *time = new Float32(frameTime); - try { + try + { dim = compileWithArgs("[$1]", (Tree *)treePtr, 1, time); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { cout << "ERROR CompileWithArgs: " << exc->what() << "\n"; } - try { + try + { // cout << "WRITING SEGMENT " << time << dim << data << " " << // dataNode->getFullPath() <<"\n"; dataNode->makeSegment(time, time, dim, (Array *)data); - if (hasMetadata && metaSize > 0) { + if (hasMetadata && metaSize > 0) + { metaNode->makeSegment(time, time, dim, (Array *)metaData); } - - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { cout << "ERROR WRITING SEGMENT " << exc->what() << "\n"; } - try { + try + { deleteData(data); deleteData(time); deleteData(dim); @@ -212,14 +232,17 @@ class SaveFrame { delete (short *)frame; else if (pixelSize <= 32) delete (int *)frame; - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { cout << "ERROR deleting data" << exc->what() << "\n"; } } } }; -class SaveFrameList { +class SaveFrameList +{ public: pthread_cond_t itemAvailable; pthread_t thread; @@ -231,7 +254,8 @@ class SaveFrameList { public: void setDeferredSave(bool deferredSave) { this->deferredSave = deferredSave; } - SaveFrameList() { + SaveFrameList() + { int status = pthread_mutex_init(&mutex, NULL); pthread_cond_init(&itemAvailable, NULL); saveHead = saveTail = NULL; @@ -240,11 +264,15 @@ class SaveFrameList { threadCreated = false; } - void addFrame(SaveFrame *newItem) { + void addFrame(SaveFrame *newItem) + { pthread_mutex_lock(&mutex); - if (saveHead == NULL) { + if (saveHead == NULL) + { saveHead = saveTail = newItem; - } else { + } + else + { saveTail->setNext(newItem); saveTail = newItem; } @@ -254,7 +282,8 @@ class SaveFrameList { void addFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx, void *frameMetadata, int metaSize, int metaNid) { + int frameIdx, void *frameMetadata, int metaSize, int metaNid) + { SaveFrame *newItem = new SaveFrame( frame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx, frameMetadata, metaSize, metaNid); @@ -263,28 +292,37 @@ class SaveFrameList { void addFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx) { + int frameIdx) + { SaveFrame *newItem = new SaveFrame(frame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx); addFrame(newItem); } - void executeItems() { - while (true) { + void executeItems() + { + while (true) + { pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } - if (deferredSave) { + if (deferredSave) + { pthread_cond_wait(&itemAvailable, &mutex); - if (!stopReq) { + if (!stopReq) + { pthread_mutex_unlock(&mutex); continue; - } else { + } + else + { // Empty pending queue - while (saveHead) { + while (saveHead) + { SaveFrame *currItem = saveHead; saveHead = saveHead->getNext(); @@ -304,9 +342,11 @@ class SaveFrameList { } } - while (saveHead == NULL) { + while (saveHead == NULL) + { pthread_cond_wait(&itemAvailable, &mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } @@ -326,14 +366,17 @@ class SaveFrameList { delete currItem; } } - void start() { + void start() + { pthread_create(&thread, NULL, handleSave, (void *)this); threadCreated = true; } - void stop() { + void stop() + { stopReq = true; pthread_cond_signal(&itemAvailable); - if (threadCreated) { + if (threadCreated) + { pthread_join(thread, NULL); #ifdef DEBUG printf("SAVE THREAD TERMINATED\n"); @@ -342,27 +385,32 @@ class SaveFrameList { } }; -static void *handleSave(void *listPtr) { +static void *handleSave(void *listPtr) +{ SaveFrameList *list = (SaveFrameList *)listPtr; list->executeItems(); return NULL; } -void camStartSave(void **retList) { +void camStartSave(void **retList) +{ SaveFrameList *saveFrameList = new SaveFrameList; saveFrameList->start(); *retList = (void *)saveFrameList; } -void camStartSaveDeferred(void **retList) { +void camStartSaveDeferred(void **retList) +{ SaveFrameList *saveFrameList = new SaveFrameList; saveFrameList->setDeferredSave(true); saveFrameList->start(); *retList = (void *)saveFrameList; } -void camStopSave(void *listPtr) { - if (listPtr) { +void camStopSave(void *listPtr) +{ + if (listPtr) + { SaveFrameList *list = (SaveFrameList *)listPtr; list->stop(); delete list; @@ -370,12 +418,16 @@ void camStopSave(void *listPtr) { } // Open Mdsplus Tree -int camOpenTree(char *treeName, int shot, void **treePtr) { - try { +int camOpenTree(char *treeName, int shot, void **treePtr) +{ + try + { Tree *tree = new Tree(treeName, shot); *treePtr = (void *)tree; return 0; - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { cout << "Error opening Tree " << treeName << ": " << exc->what() << "\n"; return -1; } @@ -404,19 +456,25 @@ int metaNid MdsPlus NodeID for the metadata void camSaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void *frameMetadata, int metaSize, int metaNid, - void *saveListPtr) { + void *saveListPtr) +{ void *bufFrame; void *bufMdata; int frameSize = width * height; - if (pixelSize <= 8) { + if (pixelSize <= 8) + { bufFrame = new char[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(char)); - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { bufFrame = new short[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(short)); - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { bufFrame = new int[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(int)); } @@ -432,17 +490,23 @@ void camSaveFrame(void *frame, int width, int height, float frameTime, void camSaveFrameDirect(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, - int timebaseNid, int frameIdx, void *saveListPtr) { + int timebaseNid, int frameIdx, void *saveListPtr) +{ void *bufFrame; int frameSize = width * height; - if (pixelSize <= 8) { + if (pixelSize <= 8) + { bufFrame = new char[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(char)); - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { bufFrame = new short[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(short)); - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { bufFrame = new int[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(int)); } diff --git a/device_support/camera_utils/cammdsutils.h b/device_support/camera_utils/cammdsutils.h index 7fcd13f464..8228b929c9 100644 --- a/device_support/camera_utils/cammdsutils.h +++ b/device_support/camera_utils/cammdsutils.h @@ -1,24 +1,25 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int camOpenTree(char *treeName, int shot, void **treePtr); -int camCloseTree(void *treePtr); -// int camSaveFrame(void *frame, int width, int height, float frameTime, int -// pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void -// *frameMetadata, int metaSize, int metaNid); -void camSaveFrame(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx, void *frameMetadata, int metaSize, int metaNid, - void *saveListPtr); -void camSaveFrameDirect(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, - int timebaseNid, int frameIdx, void *saveListPtr); + int camOpenTree(char *treeName, int shot, void **treePtr); + int camCloseTree(void *treePtr); + // int camSaveFrame(void *frame, int width, int height, float frameTime, int + // pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void + // *frameMetadata, int metaSize, int metaNid); + void camSaveFrame(void *frame, int width, int height, float frameTime, + int pixelSize, void *treePtr, int dataNid, int timebaseNid, + int frameIdx, void *frameMetadata, int metaSize, int metaNid, + void *saveListPtr); + void camSaveFrameDirect(void *frame, int width, int height, float frameTime, + int pixelSize, void *treePtr, int dataNid, + int timebaseNid, int frameIdx, void *saveListPtr); -static void *handleSave(void *listPtr); -void camStartSaveDeferred(void **retList); -void camStartSave(void **retList); -void camStopSave(void *listPtr); + static void *handleSave(void *listPtr); + void camStartSaveDeferred(void **retList); + void camStartSave(void **retList); + void camStopSave(void *listPtr); #ifdef __cplusplus } diff --git a/device_support/camera_utils/camstreamutils.cpp b/device_support/camera_utils/camstreamutils.cpp index 7b40a37c63..f13fa36441 100644 --- a/device_support/camera_utils/camstreamutils.cpp +++ b/device_support/camera_utils/camstreamutils.cpp @@ -63,7 +63,8 @@ int getPixelSize( } // Support class for enqueueing Frame streaming requests -class StreamingFrame { +class StreamingFrame +{ void *frame; int width; @@ -92,7 +93,8 @@ class StreamingFrame { unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName) { + const char *deviceName) + { this->tcpStreamHandle = tcpStreamHandle; this->frame = frame; this->width = width; @@ -118,7 +120,8 @@ class StreamingFrame { StreamingFrame *getNext() { return nxt; } - void streaming() { + void streaming() + { unsigned char *frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); camFrameTo8bit(frame, width, height, pixelFormat, frame8bit, adjLimit, @@ -156,7 +159,8 @@ class StreamingFrame { } }; -class StreamingFrameList { +class StreamingFrameList +{ public: pthread_cond_t itemAvailable; pthread_t thread; @@ -166,7 +170,8 @@ class StreamingFrameList { pthread_mutex_t mutex; public: - StreamingFrameList() { + StreamingFrameList() + { int status = pthread_mutex_init(&mutex, NULL); pthread_cond_init(&itemAvailable, NULL); streamingHead = streamingTail = NULL; @@ -179,16 +184,20 @@ class StreamingFrameList { bool adjLimit, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, - int adjRoiW, int adjRoiH, const char *deviceName) { + int adjRoiW, int adjRoiH, const char *deviceName) + { // printf("add streaming frame\n"); StreamingFrame *newItem = new StreamingFrame( tcpStreamHandle, frame, width, height, pixelFormat, irFrameFormat, adjLimit, lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); pthread_mutex_lock(&mutex); - if (streamingHead == NULL) { + if (streamingHead == NULL) + { streamingHead = streamingTail = newItem; - } else { + } + else + { streamingTail->setNext(newItem); streamingTail = newItem; } @@ -196,15 +205,20 @@ class StreamingFrameList { pthread_mutex_unlock(&mutex); } - void executeItems() { - while (true) { - if (stopReq && streamingHead == NULL) { + void executeItems() + { + while (true) + { + if (stopReq && streamingHead == NULL) + { pthread_mutex_destroy(&mutex); pthread_exit(NULL); } - while (streamingHead == NULL) { - if (stopReq && streamingHead == NULL) { + while (streamingHead == NULL) + { + if (stopReq && streamingHead == NULL) + { pthread_mutex_destroy(&mutex); pthread_exit(NULL); } @@ -241,35 +255,42 @@ class StreamingFrameList { } } - void start() { + void start() + { pthread_create(&thread, NULL, handleStreaming, (void *)this); threadCreated = true; } - void stop() { + void stop() + { stopReq = true; pthread_cond_signal(&itemAvailable); - if (threadCreated) { + if (threadCreated) + { pthread_join(thread, NULL); printf("Streaming THREAD TERMINATED\n"); } } }; -void *handleStreaming(void *listPtr) { +void *handleStreaming(void *listPtr) +{ StreamingFrameList *list = (StreamingFrameList *)listPtr; list->executeItems(); return NULL; } -void camStartStreaming(void **retList) { +void camStartStreaming(void **retList) +{ StreamingFrameList *streamingFrameList = new StreamingFrameList; streamingFrameList->start(); *retList = (void *)streamingFrameList; } -void camStopStreaming(void *listPtr) { - if (listPtr) { +void camStopStreaming(void *listPtr) +{ + if (listPtr) + { StreamingFrameList *list = (StreamingFrameList *)listPtr; list->stop(); delete list; @@ -281,19 +302,25 @@ void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName, void *streamingListPtr) { + const char *deviceName, void *streamingListPtr) +{ void *bufFrame; int pixelSize = getPixelSize(pixelFormat); int frameSize = width * height; - if (pixelSize <= 8) { + if (pixelSize <= 8) + { bufFrame = new char[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(char)); - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { bufFrame = new short[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(short)); - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { bufFrame = new int[frameSize]; memcpy(bufFrame, frame, frameSize * sizeof(int)); } @@ -311,7 +338,8 @@ void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, * (connection to FFMPEG)*/ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, int *kSockHandle, int width, int height, - int pixelFormat) { + int pixelFormat) +{ struct sockaddr_in sin; struct hostent *hp; @@ -321,7 +349,8 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, /* Resolve the passed name and store the resulting long representation in the * struct hostent variable */ - if ((hp = gethostbyname(streamingServer)) == 0) { + if ((hp = gethostbyname(streamingServer)) == 0) + { // perror("gethostbyname"); return -1; } @@ -333,8 +362,10 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, sin.sin_port = htons(StreamingPort); /* create a new socket */ - if (*kSockHandle == -1) { - if ((*kSockHandle = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + if (*kSockHandle == -1) + { + if ((*kSockHandle = socket(AF_INET, SOCK_STREAM, 0)) == -1) + { // perror("socket"); return -1; } @@ -371,7 +402,8 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, // 20170615 fede end new /* connect the socket to the port and host specified in struct sockaddr_in */ - if (connect(*kSockHandle, (struct sockaddr *)&sin, sizeof(sin)) == -1) { + if (connect(*kSockHandle, (struct sockaddr *)&sin, sizeof(sin)) == -1) + { // perror("connect"); // char lDoodle[] = "-+*"; // printf("%c Error: connection refused!\r", lDoodle[rand()%3]); @@ -388,17 +420,20 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, int netPixelFormat = htonl(pixelFormat); /* init frame size streaming */ - if (send(*kSockHandle, &netWidth, sizeof(netWidth), 0) == -1) { + if (send(*kSockHandle, &netWidth, sizeof(netWidth), 0) == -1) + { // perror("send width"); return -1; } - if (send(*kSockHandle, &netHeight, sizeof(netHeight), 0) == -1) { + if (send(*kSockHandle, &netHeight, sizeof(netHeight), 0) == -1) + { // perror("send height"); return -1; } - if (send(*kSockHandle, &netPixelFormat, sizeof(netPixelFormat), 0) == -1) { + if (send(*kSockHandle, &netPixelFormat, sizeof(netPixelFormat), 0) == -1) + { // perror("send pixel format"); return -1; } @@ -407,9 +442,12 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, } // close TCP connection -int camCloseTcpConnection(int *kSockHandle) { - if (*kSockHandle != -1) { - if (close(*kSockHandle) == -1) { +int camCloseTcpConnection(int *kSockHandle) +{ + if (*kSockHandle != -1) + { + if (close(*kSockHandle) == -1) + { perror("close"); return -1; } @@ -420,12 +458,14 @@ int camCloseTcpConnection(int *kSockHandle) { // send 8bit frame over the opened TCP connection int camSendFrameOnTcp(int *kSockHandle, int width, int height, - void *frame8bit) { + void *frame8bit) +{ #ifdef debug cout << "camSendFrameOnTcp. Handle:" << *kSockHandle << endl; #endif - if (*kSockHandle != -1) { + if (*kSockHandle != -1) + { int total = 0; // how many bytes we've sent int bytesleft = width * height; // how many we have left to send int n; @@ -434,28 +474,35 @@ int camSendFrameOnTcp(int *kSockHandle, int width, int height, { n = send(*kSockHandle, (void *)((char *)frame8bit + total), bytesleft, 0); // flags: 0, MSG_DONTWAIT - if (n == -1) { + if (n == -1) + { printf("TCP send failed. Code: %d | %s\n", errno, strerror(errno)); if (errno == 11) // Resource temporarily unavailable { return -1; - } // return without close the connection + } // return without close the connection camCloseTcpConnection(kSockHandle); // if send fail -> close socket return -1; - } else { + } + else + { total += n; bytesleft -= n; // printf("Sent %d bytes. Bytesleft %d.\n", n, bytesleft); //%zu - if (bytesleft != 0) { + if (bytesleft != 0) + { printf("Wait for sending remaining bytes...\n"); // usleep(100000);//100ms } } } #ifdef debug - cout << "Frame spedito su TCP.\n" << endl; + cout << "Frame spedito su TCP.\n" + << endl; #endif - } else { + } + else + { return -1; } return 0; @@ -465,7 +512,8 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, unsigned char *frame8bit, bool adjLimits, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH) { + int adjRoiY, int adjRoiW, int adjRoiH) +{ // when adjLimits==0, lowLim and highLim are used to adjust the frame. minLim // and maxLim are NOT used. minLim & maxLim depend on specific camera and are // used only if adjLimits==1. In this case lowLim and highLim are calculated in @@ -476,7 +524,8 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, unsigned int minpix, maxpix; - if (adjLimits) { + if (adjLimits) + { maxpix = 0; if (pixelSize <= 8) @@ -489,30 +538,42 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, for (int row = adjRoiY; row < adjRoiY + adjRoiH; row++) // calculate min & max pixel only in ROI { - for (int col = adjRoiX; col < adjRoiX + adjRoiW; col++) { + for (int col = adjRoiX; col < adjRoiX + adjRoiW; col++) + { int i = (row * width) + col; - if (pixelSize <= 8) { + if (pixelSize <= 8) + { char *framePtr = (char *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) { + if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) + { minpix = framePtr[i]; } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) { + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { maxpix = framePtr[i]; } - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { short *framePtr = (short *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) { + if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) + { minpix = framePtr[i]; } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) { + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { maxpix = framePtr[i]; } - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { int *framePtr = (int *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) { + if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) + { minpix = framePtr[i]; } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) { + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { maxpix = framePtr[i]; } } @@ -520,7 +581,9 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, } // for rows *lowLim = minpix; *highLim = maxpix; - } else { + } + else + { minpix = *lowLim; maxpix = *highLim; } @@ -529,40 +592,61 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, float span = (float)(maxpix - minpix + 1); // for(int i=0; i maxpix) { + } + else if (sample > maxpix) + { nsample = 255; - } else { + } + else + { nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); } frame8bit[i] = nsample; - } else if (pixelSize <= 16) { + } + else if (pixelSize <= 16) + { short *framePtr = (short *)frame; unsigned short sample = framePtr[i]; - if (sample < minpix) { + if (sample < minpix) + { nsample = 0; - } else if (sample > maxpix) { + } + else if (sample > maxpix) + { nsample = 255; - } else { + } + else + { nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); } frame8bit[i] = nsample; - } else if (pixelSize <= 32) { + } + else if (pixelSize <= 32) + { int *framePtr = (int *)frame; unsigned int sample = framePtr[i]; - if (sample < minpix) { + if (sample < minpix) + { nsample = 0; - } else if (sample > maxpix) { + } + else if (sample > maxpix) + { nsample = 255; - } else { + } + else + { nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); } frame8bit[i] = nsample; @@ -584,7 +668,8 @@ int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, // IMPORTANT: the file used by drawtext filter in ffmpeg is reload every frame // processed and so any operation on it MUST BE an atomic operation!!! -int camFFMPEGoverlay(const char *filename, const char *textString) { +int camFFMPEGoverlay(const char *filename, const char *textString) +{ char pathname[100]; strcpy(pathname, ""); // Clear local filename strcat(pathname, getenv("HOME")); // get home dir @@ -598,26 +683,31 @@ int camFFMPEGoverlay(const char *filename, const char *textString) { mode_t default_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int fd = open(tmp_pathname, O_RDWR | O_CREAT | O_TRUNC, default_mode); - if (fd == -1) { + if (fd == -1) + { printf("Failed to open new file for writing\n"); return -1; } size_t count = write(fd, textString, strlen(textString)); - if (count != strlen(textString)) { + if (count != strlen(textString)) + { printf("Failed to write new content on file\n"); return -1; } - if (fsync(fd) == -1) { + if (fsync(fd) == -1) + { printf("Failed to flush new file content to disc\n"); return -1; } - if (close(fd) == -1) { + if (close(fd) == -1) + { printf("Failed to close new file\n"); return -1; } - if (rename(tmp_pathname, pathname) == -1) { + if (rename(tmp_pathname, pathname) == -1) + { printf("Failed to move new file to final location\n"); return -1; } diff --git a/device_support/camera_utils/camstreamutils.h b/device_support/camera_utils/camstreamutils.h index 23dd039e83..e582cf0519 100644 --- a/device_support/camera_utils/camstreamutils.h +++ b/device_support/camera_utils/camstreamutils.h @@ -1,41 +1,41 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif // SUPPORTED PIXEL FORMATS derived from 'ffmpeg/libavutil/pixfmt.h' // DEFINES MUST BE ALSO IN ffmpeg/libavdevices/tcpframes.c #define CSU_PIX_FMT_NONE 0 #define CSU_PIX_FMT_GRAY8 1 ///< Y , 8bpp -#define CSU_PIX_FMT_GRAY16 \ - 2 ///< Y , 16bpp (should have big-endian and little-endian - ///< formats) -#define CSU_PIX_FMT_BAYER_RGGB8 \ +#define CSU_PIX_FMT_GRAY16 \ + 2 ///< Y , 16bpp (should have big-endian and little-endian /< formats) +#define CSU_PIX_FMT_BAYER_RGGB8 \ 3 ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ -#define CSU_PIX_FMT_YUV422_Packed \ +#define CSU_PIX_FMT_YUV422_Packed \ 4 ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) -int camOpenTcpConnection(const char *streamingServer, int StreamingPort, - int *kSockHandle, int width, int height, - int pixelFormat); -int camCloseTcpConnection(int *kSockHandle); -int camSendFrameOnTcp(int *kSockHandle, int width, int height, void *frame8bit); -int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, - unsigned char *frame8bit, bool adjLimits, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH); -int camFFMPEGoverlay(const char *filename, const char *textString); + int camOpenTcpConnection(const char *streamingServer, int StreamingPort, + int *kSockHandle, int width, int height, + int pixelFormat); + int camCloseTcpConnection(int *kSockHandle); + int camSendFrameOnTcp(int *kSockHandle, int width, int height, void *frame8bit); + int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, + unsigned char *frame8bit, bool adjLimits, + unsigned int *lowLim, unsigned int *highLim, + unsigned int minLim, unsigned int maxLim, int adjRoiX, + int adjRoiY, int adjRoiW, int adjRoiH); + int camFFMPEGoverlay(const char *filename, const char *textString); -void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, - int pixelFormat, int irFrameFormat, bool adjLimit, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName, void *streamingListPtr); + void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, + int pixelFormat, int irFrameFormat, bool adjLimit, + unsigned int *lowLim, unsigned int *highLim, + unsigned int minLim, unsigned int maxLim, int adjRoiX, + int adjRoiY, int adjRoiW, int adjRoiH, + const char *deviceName, void *streamingListPtr); -static void *handleStreaming(void *listPtr); -void camStartStreaming(void **retList); -void camStopStreaming(void *listPtr); + static void *handleStreaming(void *listPtr); + void camStartStreaming(void **retList); + void camStopStreaming(void *listPtr); #ifdef __cplusplus } diff --git a/device_support/flir/FLIRSC65X.cpp b/device_support/flir/FLIRSC65X.cpp index 8258317052..1a79fa10d8 100644 --- a/device_support/flir/FLIRSC65X.cpp +++ b/device_support/flir/FLIRSC65X.cpp @@ -53,237 +53,274 @@ static FLIR_SC65X *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int flirOpen(const char *ipAddress, int *camHandle) { - FLIR_SC65X *cam; - int cameraHandle; + int flirOpen(const char *ipAddress, int *camHandle) + { + FLIR_SC65X *cam; + int cameraHandle; - errorOnOpen[0] = 0; + errorOnOpen[0] = 0; - cam = new FLIR_SC65X(ipAddress); - if (!cam->checkLastOp()) { - cam->getLastError(errorOnOpen); - delete (cam); - return ERROR; - } + cam = new FLIR_SC65X(ipAddress); + if (!cam->checkLastOp()) + { + cam->getLastError(errorOnOpen); + delete (cam); + return ERROR; + } - for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; - cameraHandle++) - ; + for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; + cameraHandle++) + ; - if (cameraHandle < MAX_CAM) { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } else { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; + if (cameraHandle < MAX_CAM) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } } -} -int flirIsConnected(int camHandle) { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; + int flirIsConnected(int camHandle) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; } - return SUCCESS; -} -int flirClose(int camHandle) { - delete (camPtr[camHandle]); - camPtr[camHandle] = 0; + int flirClose(int camHandle) + { + delete (camPtr[camHandle]); + camPtr[camHandle] = 0; - return SUCCESS; -} + return SUCCESS; + } -int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } + int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } -int printAllParameters(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->printAllParameters(); - return ERROR; -} + int printAllParameters(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->printAllParameters(); + return ERROR; + } -int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposureMode(exposureMode); - return ERROR; -} + int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setExposureMode(exposureMode); + return ERROR; + } -int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate, frameToSkip); - return ERROR; -} + int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setFrameRate(frameRate, frameToSkip); + return ERROR; + } -int setFrameRateNew(int camHandle, double frameRate) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate); - return ERROR; -} + int setFrameRateNew(int camHandle, double frameRate) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setFrameRate(frameRate); + return ERROR; + } -int setIrFormat(int camHandle, IRFMT_ENUM irFormat) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setIrFormat(irFormat); - return ERROR; -} + int setIrFormat(int camHandle, IRFMT_ENUM irFormat) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setIrFormat(irFormat); + return ERROR; + } -int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getReadoutArea(x, y, width, height); - return ERROR; -} + int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->getReadoutArea(x, y, width, height); + return ERROR; + } -int setReadoutArea(int camHandle, int x, int y, int width, int height) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; -} + int setReadoutArea(int camHandle, int x, int y, int width, int height) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; + } -int setObjectParameters(int camHandle, double reflectedTemperature, - double atmosphericTemperature, double objectDistance, - double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, - double extOpticsTransmission, - double estimatedTransmission) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setObjectParameters( - reflectedTemperature, atmosphericTemperature, objectDistance, - objectEmissivity, relativeHumidity, extOpticsTemperature, - extOpticsTransmission, estimatedTransmission); - return ERROR; -} + int setObjectParameters(int camHandle, double reflectedTemperature, + double atmosphericTemperature, double objectDistance, + double objectEmissivity, double relativeHumidity, + double extOpticsTemperature, + double extOpticsTransmission, + double estimatedTransmission) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setObjectParameters( + reflectedTemperature, atmosphericTemperature, objectDistance, + objectEmissivity, relativeHumidity, extOpticsTemperature, + extOpticsTransmission, estimatedTransmission); + return ERROR; + } -int setMeasurementRange(int camHandle, int measRange) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setMeasurementRange(measRange); - return ERROR; -} + int setMeasurementRange(int camHandle, int measRange) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setMeasurementRange(measRange); + return ERROR; + } -int getFocusAbsPosition(int camHandle, int *focusPos) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFocusAbsPosition(focusPos); - return ERROR; -} + int getFocusAbsPosition(int camHandle, int *focusPos) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->getFocusAbsPosition(focusPos); + return ERROR; + } -int setFocusAbsPosition(int camHandle, int focusPos) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFocusAbsPosition(focusPos); - return ERROR; -} + int setFocusAbsPosition(int camHandle, int focusPos) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setFocusAbsPosition(focusPos); + return ERROR; + } -int executeAutoFocus(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->executeAutoFocus(); - return ERROR; -} + int executeAutoFocus(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->executeAutoFocus(); + return ERROR; + } -int setCalibMode(int camHandle, int calMode) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setCalibMode(calMode); - return ERROR; -} + int setCalibMode(int camHandle, int calMode) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setCalibMode(calMode); + return ERROR; + } -int executeAutoCalib(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->executeAutoCalib(); - return ERROR; -} + int executeAutoCalib(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->executeAutoCalib(); + return ERROR; + } -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; -} + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; + } -int stopAcquisition(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; -} + int stopAcquisition(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; + } -int getFrame(int camHandle, int *status, void *frame, void *metaData) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; -} + int getFrame(int camHandle, int *status, void *frame, void *metaData) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; + } -int frameConv(int camHandle, unsigned short *frame, int width, int height) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->frameConv(frame, width, height); - return ERROR; -} + int frameConv(int camHandle, unsigned short *frame, int width, int height) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->frameConv(frame, width, height); + return ERROR; + } -int setAcquisitionMode(int camHandle, int storeEnabled, - int acqSkipFrameNumber) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setAcquisitionMode(storeEnabled, - acqSkipFrameNumber); - return ERROR; -} + int setAcquisitionMode(int camHandle, int storeEnabled, + int acqSkipFrameNumber) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setAcquisitionMode(storeEnabled, + acqSkipFrameNumber); + return ERROR; + } -int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, - numTrigger); - return ERROR; -} + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, + int numTrigger) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, + numTrigger); + return ERROR; + } -int softwareTrigger(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; -} + int softwareTrigger(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; + } -int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, - framesMetadNid, frame0TimeNid); - return ERROR; -} + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, + int framesMetadNid, int frame0TimeNid) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, + framesMetadNid, frame0TimeNid); + return ERROR; + } -int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, const char *streamingServer, - int streamingPort, int lowLim, int highLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setStreamingMode( - irFormat, streamingEnabled, autoAdjustLimit, streamingServer, - streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, - deviceName); - return ERROR; -} -int startFramesAcquisition(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; -} + int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, + bool autoAdjustLimit, const char *streamingServer, + int streamingPort, int lowLim, int highLim, int adjRoiX, + int adjRoiY, int adjRoiW, int adjRoiH, + const char *deviceName) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setStreamingMode( + irFormat, streamingEnabled, autoAdjustLimit, streamingServer, + streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, + deviceName); + return ERROR; + } + int startFramesAcquisition(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; + } -int stopFramesAcquisition(int camHandle) { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; -} + int stopFramesAcquisition(int camHandle) + { + if (flirIsConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; + } -void getLastError(int camHandle, char *msg) { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) { - sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); - return; + void getLastError(int camHandle, char *msg) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); } - camPtr[camHandle]->getLastError(msg); -} #ifdef __cplusplus } #endif -FLIR_SC65X::FLIR_SC65X(const char *ipAddress) { +FLIR_SC65X::FLIR_SC65X(const char *ipAddress) +{ this->ipAddress = PvString(ipAddress); /* SDK 3 @@ -291,14 +328,18 @@ FLIR_SC65X::FLIR_SC65X(const char *ipAddress) { this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); */ - try { + try + { this->lDevice = PvDevice::CreateAndConnect( this->ipAddress, &this->lResult); // 20160309 SDK4 //sometimes goes in coredump - } catch (...) { + } + catch (...) + { printf("Core dump detected on PvDevice::CreateAndConnect\n"); } - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printf( "--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); @@ -306,7 +347,9 @@ FLIR_SC65X::FLIR_SC65X(const char *ipAddress) { { PvDevice::Free(this->lDevice); } - } else { + } + else + { printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii()); } @@ -320,7 +363,8 @@ FLIR_SC65X::FLIR_SC65X() // new 25/07/2013: let to use the device without the // telecamera } -FLIR_SC65X::~FLIR_SC65X() { +FLIR_SC65X::~FLIR_SC65X() +{ printf("FLIR_SC65X destructor %p\n", this->lDevice); if (this->lDevice != nullptr) // CT 2019-03-27 { @@ -335,7 +379,8 @@ FLIR_SC65X::~FLIR_SC65X() { } } -int FLIR_SC65X::checkLastOp() { +int FLIR_SC65X::checkLastOp() +{ printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii()); if (!this->lResult.IsOK()) @@ -343,18 +388,21 @@ int FLIR_SC65X::checkLastOp() { return this->lResult.IsOK(); } -int FLIR_SC65X::printAllParameters() { +int FLIR_SC65X::printAllParameters() +{ PvGenParameterArray *aArray = lDevice->GetParameters(); uint32_t lParameterArrayCount = aArray->GetCount(); printf("\nArray has %d parameters\n", lParameterArrayCount); // Traverse through Array and print out parameters available - for (uint32_t x = 0; x < lParameterArrayCount; x++) { + for (uint32_t x = 0; x < lParameterArrayCount; x++) + { // Get a parameter PvGenParameter *lGenParameter = aArray->Get(x); // Don't show invisible parameters - display everything up to Guru - if (!lGenParameter->IsVisible(PvGenVisibilityGuru)) { + if (!lGenParameter->IsVisible(PvGenVisibilityGuru)) + { continue; } @@ -365,13 +413,15 @@ int FLIR_SC65X::printAllParameters() { printf("%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii()); // Parameter available? - if (!lGenParameter->IsAvailable()) { + if (!lGenParameter->IsAvailable()) + { printf("{Not Available}\n"); continue; } // Parameter readable? - if (!lGenParameter->IsReadable()) { + if (!lGenParameter->IsReadable()) + { printf("{Not readable}\n"); continue; } @@ -379,45 +429,59 @@ int FLIR_SC65X::printAllParameters() { // Get the parameter type PvGenType lType; lGenParameter->GetType(lType); - switch (lType) { + switch (lType) + { // If the parameter is of type PvGenTypeInteger - case PvGenTypeInteger: { + case PvGenTypeInteger: + { int64_t lValue; static_cast(lGenParameter)->GetValue(lValue); printf("Integer: %d", lValue); - } break; + } + break; // If the parameter is of type PvGenTypeEnum - case PvGenTypeEnum: { + case PvGenTypeEnum: + { PvString lValue; static_cast(lGenParameter)->GetValue(lValue); printf("Enum: %s", lValue.GetAscii()); - } break; + } + break; // If the parameter is of type PvGenTypeBoolean - case PvGenTypeBoolean: { + case PvGenTypeBoolean: + { bool lValue; static_cast(lGenParameter)->GetValue(lValue); - if (lValue) { + if (lValue) + { printf("Boolean: TRUE"); - } else { + } + else + { printf("Boolean: FALSE"); } - } break; + } + break; // If the parameter is of type PvGenTypeString - case PvGenTypeString: { + case PvGenTypeString: + { PvString lValue; static_cast(lGenParameter)->GetValue(lValue); printf("String: %s", lValue.GetAscii()); - } break; + } + break; // If the parameter is of type PvGenTypeCommand case PvGenTypeCommand: printf("Command"); break; // If the parameter is of type PvGenTypeFloat - case PvGenTypeFloat: { + case PvGenTypeFloat: + { double lValue; static_cast(lGenParameter)->GetValue(lValue); printf("Float: %f", lValue); - } break; + } + break; } printf("\n"); } @@ -425,7 +489,8 @@ int FLIR_SC65X::printAllParameters() { return SUCCESS; } -int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) { +int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *currPort = dynamic_cast(lDeviceParams->Get("CurrentPort")); @@ -433,32 +498,40 @@ int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) { dynamic_cast(lDeviceParams->Get("CurrentIOConfig")); this->lResult = currPort->SetValue(0); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting current port to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } - switch (exposureMode) { + switch (exposureMode) + { case internal_mode: usleep(3000); this->lResult = currCfg->SetValue("GeneralPurpose"); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting exposure mode!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; - } else { + } + else + { printf("Sync. INTERNAL configured.\n"); } break; case external_mode: usleep(3000); this->lResult = currCfg->SetValue("MarkImage"); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting exposure mode!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; - } else { + } + else + { printf("Sync. EXTERNAL configured.\n"); } break; @@ -467,7 +540,8 @@ int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) { return SUCCESS; } -int FLIR_SC65X::setFrameRate(double frameRate) { +int FLIR_SC65X::setFrameRate(double frameRate) +{ FPS_ENUM fps; if (frameRate == 200.) @@ -490,7 +564,8 @@ int FLIR_SC65X::setFrameRate(double frameRate) { return (setFrameRate(fps, &streamingSkipFrameNumber)); } -int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { +int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); @@ -501,32 +576,37 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { PvGenEnum *sFrameRate = dynamic_cast(lDeviceParams->Get("IRFrameRate")); - switch (fps) { + switch (fps) + { case fps_200: usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(123); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Quarter"); //"Quarter" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -541,28 +621,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_100: usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(243); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Half"); //"Half" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -577,28 +661,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_50: usleep(3000); this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -612,28 +700,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_25: usleep(3000); this->lResult = sFrameRate->SetValue(1); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -647,28 +739,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_12: usleep(3000); this->lResult = sFrameRate->SetValue(2); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -682,28 +778,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_6: usleep(3000); this->lResult = sFrameRate->SetValue(3); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -717,28 +817,32 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { case fps_3: usleep(3000); this->lResult = sFrameRate->SetValue(4); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -759,39 +863,50 @@ int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { return SUCCESS; } -int FLIR_SC65X::setIrFormat(IRFMT_ENUM irFormat) { +int FLIR_SC65X::setIrFormat(IRFMT_ENUM irFormat) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenEnum *sFormat = dynamic_cast(lDeviceParams->Get("IRFormat")); - switch (irFormat) { + switch (irFormat) + { case radiometric: this->lResult = sFormat->SetValue("Radiometric"); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Radiometric in setIrFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; - } else { + } + else + { printf("IR FORMAT set to radiometric.\n"); } break; case linear100mK: this->lResult = sFormat->SetValue("TemperatureLinear100mK"); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting TemperatureLinear100mK!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; - } else { + } + else + { printf("IR FORMAT set to TemperatureLinear100mK.\n"); } break; case linear10mK: this->lResult = sFormat->SetValue("TemperatureLinear10mK"); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting TemperatureLinear10mK!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; - } else { + } + else + { printf("IR FORMAT set to TemperatureLinear10mK.\n"); } break; @@ -802,7 +917,8 @@ int FLIR_SC65X::setIrFormat(IRFMT_ENUM irFormat) { return SUCCESS; } -int FLIR_SC65X::getReadoutArea(int *x, int *y, int *width, int *height) { +int FLIR_SC65X::getReadoutArea(int *x, int *y, int *width, int *height) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); @@ -819,28 +935,32 @@ int FLIR_SC65X::getReadoutArea(int *x, int *y, int *width, int *height) { int64_t h = 0; this->lResult = lWidth->GetValue(w); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting Width in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->GetValue(h); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting Height in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lOffsetX->GetValue(ox); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting OffsetX in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lOffsetY->GetValue(oy); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting OffsetY in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -854,7 +974,8 @@ int FLIR_SC65X::getReadoutArea(int *x, int *y, int *width, int *height) { return SUCCESS; } -int FLIR_SC65X::setReadoutArea(int x, int y, int width, int height) { +int FLIR_SC65X::setReadoutArea(int x, int y, int width, int height) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); @@ -871,28 +992,32 @@ int FLIR_SC65X::setReadoutArea(int x, int y, int width, int height) { int64_t oy = y; this->lResult = lWidth->SetValue(w); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lHeight->SetValue(h + 3); // add 3 lines of metadata - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lOffsetX->SetValue(ox); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } usleep(3000); this->lResult = lOffsetY->SetValue(oy); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -910,7 +1035,8 @@ int FLIR_SC65X::setObjectParameters( double reflectedTemperature, double atmosphericTemperature, double objectDistance, double objectEmissivity, double relativeHumidity, double extOpticsTemperature, double extOpticsTransmission, - double estimatedTransmission) { + double estimatedTransmission) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenFloat *RefTemp = dynamic_cast(lDeviceParams->Get("ReflectedTemperature")); @@ -930,7 +1056,8 @@ int FLIR_SC65X::setObjectParameters( dynamic_cast(lDeviceParams->Get("EstimatedTransmission")); this->lResult = RefTemp->SetValue(reflectedTemperature + 273.15); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting reflectedTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -938,7 +1065,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = AtmTemp->SetValue(atmosphericTemperature + 273.15); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting atmosphericTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -946,7 +1074,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = ObjDist->SetValue(objectDistance); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting objectDistance!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -954,7 +1083,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = ObjEmis->SetValue(objectEmissivity); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting objectEmissivity!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -962,7 +1092,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = RelHumi->SetValue(relativeHumidity); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting relativeHumidity!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -970,7 +1101,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = EopTemp->SetValue(extOpticsTemperature + 273.15); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting extOpticsTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -978,7 +1110,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = EopTran->SetValue(extOpticsTransmission); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting extOpticsTransmission!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -986,7 +1119,8 @@ int FLIR_SC65X::setObjectParameters( usleep(3000); this->lResult = EstTran->SetValue(estimatedTransmission); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting estimatedTransmission!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -995,10 +1129,12 @@ int FLIR_SC65X::setObjectParameters( return SUCCESS; } -int FLIR_SC65X::setMeasurementRange(int measRange) { +int FLIR_SC65X::setMeasurementRange(int measRange) +{ // with new FLIR CAMERAS range is 0-5 instead of 0-2 - if (measRange < 0 or measRange > 5) { + if (measRange < 0 or measRange > 5) + { printLastError( "Error: measRange in setMeasurementRange must be in range 0-5!!!\n", 0); return ERROR; @@ -1023,7 +1159,8 @@ int FLIR_SC65X::setMeasurementRange(int measRange) { int64_t val = measRange; this->lResult = queryCase->SetValue(val); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error: case not defined in setMeasurementRange!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1031,7 +1168,8 @@ int FLIR_SC65X::setMeasurementRange(int measRange) { usleep(3000); this->lResult = currCase->SetValue(val); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error in setMeasurementRange!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1041,7 +1179,8 @@ int FLIR_SC65X::setMeasurementRange(int measRange) { usleep(3000); this->lResult = lowLim->GetValue(limitLow); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error in low limit !!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1050,7 +1189,8 @@ int FLIR_SC65X::setMeasurementRange(int measRange) { usleep(3000); this->lResult = highLim->GetValue(limitHigh); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error in high limit !!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1064,7 +1204,8 @@ int FLIR_SC65X::setMeasurementRange(int measRange) { return SUCCESS; } -int FLIR_SC65X::getFocusAbsPosition(int *focusPos) { +int FLIR_SC65X::getFocusAbsPosition(int *focusPos) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lfocusPos = dynamic_cast(lDeviceParams->Get("FocusPos")); @@ -1072,7 +1213,8 @@ int FLIR_SC65X::getFocusAbsPosition(int *focusPos) { int64_t val = 0; this->lResult = lfocusPos->GetValue(val); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1085,7 +1227,8 @@ int FLIR_SC65X::getFocusAbsPosition(int *focusPos) { return SUCCESS; } -int FLIR_SC65X::setFocusAbsPosition(int focusPos) { +int FLIR_SC65X::setFocusAbsPosition(int focusPos) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lfocusPos = dynamic_cast(lDeviceParams->Get("FocusPos")); @@ -1101,14 +1244,16 @@ int FLIR_SC65X::setFocusAbsPosition(int focusPos) { int64_t val = 0; this->lResult = lfocusPos->GetValue(val); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } this->lResult = lfocusSpeed->SetValue(1); // maybe not necessary - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting focus speed\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1120,7 +1265,8 @@ int FLIR_SC65X::setFocusAbsPosition(int focusPos) { this->lResult = lfocusPos->SetValue(newFocPos); // set is not fine as read!!! maybe motor // is not a step by step one. - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1129,13 +1275,15 @@ int FLIR_SC65X::setFocusAbsPosition(int focusPos) { return SUCCESS; } -int FLIR_SC65X::executeAutoFocus() { +int FLIR_SC65X::executeAutoFocus() +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenCommand *autoFocus = dynamic_cast(lDeviceParams->Get("AutoFocus")); this->lResult = autoFocus->Execute(); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error executing auto focus!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1155,7 +1303,8 @@ int FLIR_SC65X::setCalibMode(int calMode) // 0=off 1=automatic dynamic_cast(lDeviceParams->Get("NUCMode")); this->lResult = calibMode->SetValue(calMode); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting calibration mode!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1172,13 +1321,15 @@ int FLIR_SC65X::setCalibMode(int calMode) // 0=off 1=automatic return SUCCESS; } -int FLIR_SC65X::executeAutoCalib() { +int FLIR_SC65X::executeAutoCalib() +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenCommand *autoCalib = dynamic_cast(lDeviceParams->Get("NUCAction")); this->lResult = autoCalib->Execute(); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error executing calibration!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1191,7 +1342,8 @@ int FLIR_SC65X::executeAutoCalib() { return SUCCESS; } -int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { +int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); @@ -1218,7 +1370,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { PvGenInteger *lTickFreq = dynamic_cast( lDeviceParams->Get("GevTimestampTickFrequency")); this->lResult = lTickFreq->GetValue(tickFreq); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting GevTimestampTickFrequency in " "startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); @@ -1230,19 +1383,22 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { int64_t lSize = 0; this->lResult = lWidth->GetValue(w); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } this->lResult = lHeight->GetValue(h); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } this->lResult = lPayloadSize->GetValue(lSize); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1267,7 +1423,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // Negotiate streaming packet size // this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 this->lResult = lDeviceGEV->NegotiatePacketSize(); // SDK 4 - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError( "Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); @@ -1279,7 +1436,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { int64_t lPacketSizeValue = 0; lResult = lPacketSize->GetValue(lPacketSizeValue); - if (!lResult.IsOK()) { + if (!lResult.IsOK()) + { printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1291,7 +1449,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); // 20160309 SDK4 - if ((this->lStream == NULL) || !this->lResult.IsOK()) { + if ((this->lStream == NULL) || !this->lResult.IsOK()) + { printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); PvStream::Free(this->lStream); @@ -1308,18 +1467,24 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // parameters PvStreamGEV *lStreamGEV = static_cast(this->lStream); - if (this->lStream->IsOpen()) { + if (this->lStream->IsOpen()) + { // printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK // 3 printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort()); // SDK 4 not working.... segmentation // fault to check! - } else { + } + else + { printf("lStream NOT OPEN\n"); } - if (lDevice->IsConnected()) { + if (lDevice->IsConnected()) + { printf("PvDevice connect \n"); - } else { + } + else + { printf("PvDevice not connect \n"); } @@ -1327,7 +1492,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // Create, alloc buffers this->lBuffers = new PvBuffer[lBufferCount]; - for (uint32_t i = 0; i < lBufferCount; i++) { + for (uint32_t i = 0; i < lBufferCount; i++) + { lResult = lBuffers[i].Alloc(static_cast(lSize)); if (!lResult.IsOK()) printf("Error memory buffer allocation %d !!!\n(%s)\n", (i + 1), @@ -1350,7 +1516,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { this->lResult = lDeviceGEV->SetStreamDestination( lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort()); // SDK 4 - 9 mar 2016 - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1367,7 +1534,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { printf("PvDevice not connect \n"); // Queue all buffers in the stream - for (uint32_t i = 0; i < lBufferCount; i++) { + for (uint32_t i = 0; i < lBufferCount; i++) + { printf("------------------------ Queuing Buffer " "-----------------------------------\n"); lResult = lStream->QueueBuffer(&lBuffers[i]); @@ -1391,11 +1559,13 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // TLParamsLocked is optional but when present, it MUST be set to 1 // before sending the AcquisitionStart command - if (lTLLocked != NULL) { + if (lTLLocked != NULL) + { usleep(3000); this->lResult = lTLLocked->SetValue(1); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1404,14 +1574,16 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { // reset timestamp counter this->lResult = lResetTimestamp->Execute(); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; } // Tell the device to start sending images this->lResult = lStart->Execute(); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError( "Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); @@ -1442,7 +1614,8 @@ int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { return SUCCESS; } -int FLIR_SC65X::stopAcquisition() { +int FLIR_SC65X::stopAcquisition() +{ PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); @@ -1451,7 +1624,8 @@ int FLIR_SC65X::stopAcquisition() { // Tell the device to stop sending images this->lResult = lStop->Execute(); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError( "Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); @@ -1460,9 +1634,11 @@ int FLIR_SC65X::stopAcquisition() { // If present reset TLParamsLocked to 0. Must be done AFTER the // streaming has been stopped - if (lTLLocked != NULL) { + if (lTLLocked != NULL) + { this->lResult = lTLLocked->SetValue(0); - if (!this->lResult.IsOK()) { + if (!this->lResult.IsOK()) + { printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii()); return ERROR; @@ -1471,7 +1647,8 @@ int FLIR_SC65X::stopAcquisition() { // printf( "Aborting buffers still in stream\n" ); lStream->AbortQueuedBuffers(); - while (lStream->GetQueuedBufferCount() > 0) { + while (lStream->GetQueuedBufferCount() > 0) + { PvBuffer *lBuffer = NULL; PvResult lOperationResult; lStream->RetrieveBuffer(&lBuffer, &lOperationResult); @@ -1489,7 +1666,8 @@ int FLIR_SC65X::stopAcquisition() { return SUCCESS; } -int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { +int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) +{ // status=1 complete # status=2 incomplete # status=3 timeout # status=4 // triggered frame + complete // char lDoodle[] = "|\\-|-/"; @@ -1517,8 +1695,10 @@ int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { this->lResult = lStream->RetrieveBuffer(&lBuffer, &lOperationResult, 1000); // this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); - if (this->lResult.IsOK()) { - if (lOperationResult.IsOK()) { + if (this->lResult.IsOK()) + { + if (lOperationResult.IsOK()) + { // lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 // segmentation fault lFrameRate->GetValue(lFrameRateVal); @@ -1526,7 +1706,8 @@ int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { // If the buffer contains an image, display width and height uint32_t lWidth = 0, lHeight = 0; - if (lBuffer->GetPayloadType() == PvPayloadTypeImage) { + if (lBuffer->GetPayloadType() == PvPayloadTypeImage) + { // Get image specific buffer interface PvImage *lImage = lBuffer->GetImage(); // Read width, height @@ -1579,7 +1760,8 @@ int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { triggered = 1; } } - } else // new 28 agosto 2012 + } + else // new 28 agosto 2012 { *status = 2; // incomplete // printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); @@ -1591,7 +1773,8 @@ int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { // re-queue the buffer in the stream object lStream->QueueBuffer(lBuffer); return SUCCESS; - } else // Timeout + } + else // Timeout { printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii()); @@ -1604,9 +1787,11 @@ int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { } // Convert frame pixels from Kelvin to Celsius -int FLIR_SC65X::frameConv(unsigned short *frame, int width, int height) { +int FLIR_SC65X::frameConv(unsigned short *frame, int width, int height) +{ short sub = 0; - switch (irFrameFormat) { + switch (irFrameFormat) + { case linear100mK: sub = 2731; // 1 = 100mK = 100mC -> precisione decimo di grado break; @@ -1615,7 +1800,8 @@ int FLIR_SC65X::frameConv(unsigned short *frame, int width, int height) { break; } - for (int i = 0; i < width * height; i++) { + for (int i = 0; i < width * height; i++) + { frame[i] = frame[i] - sub; } @@ -1627,10 +1813,12 @@ int FLIR_SC65X::setStreamingMode(IRFMT_ENUM irFormat, int streamingEnabled, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) { + int adjRoiH, const char *deviceName) +{ this->streamingEnabled = streamingEnabled; - if (streamingEnabled) { + if (streamingEnabled) + { memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); this->streamingPort = streamingPort; @@ -1640,7 +1828,8 @@ int FLIR_SC65X::setStreamingMode(IRFMT_ENUM irFormat, int streamingEnabled, // unsigned int minLim = 2000; // 200 K or -73 deg Celsius // unsigned int maxLim = 62000; // 6200 K or 5927 deg Celsius - switch (irFormat) { + switch (irFormat) + { case radiometric: this->lowLim = lowLim * 10; // 20170918: streaming is already converted in @@ -1667,14 +1856,16 @@ int FLIR_SC65X::setStreamingMode(IRFMT_ENUM irFormat, int streamingEnabled, this->adjRoiY = adjRoiY; this->adjRoiW = adjRoiW; this->adjRoiH = adjRoiH; - - } else { + } + else + { printf("Streaming DISABLED\n"); } return SUCCESS; } -int FLIR_SC65X::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) { +int FLIR_SC65X::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) +{ this->storeEnabled = storeEnabled; this->acqSkipFrameNumber = acqSkipFrameNumber; @@ -1682,7 +1873,8 @@ int FLIR_SC65X::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) { } int FLIR_SC65X::setTriggerMode(int triggerMode, double burstDuration, - int numTrigger) { + int numTrigger) +{ this->triggerMode = triggerMode; this->burstDuration = burstDuration; this->numTrigger = numTrigger; @@ -1690,13 +1882,15 @@ int FLIR_SC65X::setTriggerMode(int triggerMode, double burstDuration, return setExposureMode((EXPMODE_ENUM)triggerMode); } -int FLIR_SC65X::softwareTrigger() { +int FLIR_SC65X::softwareTrigger() +{ this->startStoreTrg = 1; return SUCCESS; } int FLIR_SC65X::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) { + int framesMetadNid, int frame0TimeNid) +{ this->treePtr = treePtr; this->framesNid = framesNid; this->timebaseNid = timebaseNid; @@ -1706,7 +1900,8 @@ int FLIR_SC65X::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, return SUCCESS; } -void FLIR_SC65X::printLastError(const char *format, const char *msg) { +void FLIR_SC65X::printLastError(const char *format, const char *msg) +{ error[0] = 0; if (msg) sprintf(error, format, msg); @@ -1714,11 +1909,13 @@ void FLIR_SC65X::printLastError(const char *format, const char *msg) { sprintf(error, format); } -void FLIR_SC65X::getLastError(char *msg) { +void FLIR_SC65X::getLastError(char *msg) +{ sprintf(msg, "%s", (error[0] == 0) ? "" : error); } -int FLIR_SC65X::stopFramesAcquisition() { +int FLIR_SC65X::stopFramesAcquisition() +{ int count = 0; if (acqFlag == 0) @@ -1726,12 +1923,14 @@ int FLIR_SC65X::stopFramesAcquisition() { acqStopped = 0; acqFlag = 0; - while (!acqStopped & count < 10) { + while (!acqStopped & count < 10) + { count++; usleep(50000); // 20190829 FM: 5000->50000 } - if (count == 10) { + if (count == 10) + { printLastError("Cannot stop acquisition loop", 0); return ERROR; } @@ -1739,7 +1938,8 @@ int FLIR_SC65X::stopFramesAcquisition() { return SUCCESS; } -int FLIR_SC65X::startFramesAcquisition() { +int FLIR_SC65X::startFramesAcquisition() +{ int frameTriggerCounter; int frameCounter; int frameStatus; @@ -1766,11 +1966,14 @@ int FLIR_SC65X::startFramesAcquisition() { int64_t timeStamp0; TreeNode *t0Node; - try { + try + { t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); Data *nodeData = t0Node->getData(); timeStamp0 = (int64_t)nodeData->getLong(); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Error getting frame0 time\n"); } @@ -1796,10 +1999,12 @@ int FLIR_SC65X::startFramesAcquisition() { startStoreTrg = 0; // manage the mdsplus saving process. SAVE always start // with a SW or HW trigger. (0=no-save; 1=save) - while (acqFlag) { + while (acqFlag) + { getFrame(&frameStatus, frameBuffer, metaData); // get the frame - if (storeEnabled) { + if (storeEnabled) + { if (triggerMode == 1) // External trigger source { @@ -1811,7 +2016,8 @@ int FLIR_SC65X::startFramesAcquisition() { printf("TRIGGERED:\n"); } - if (frameTriggerCounter == burstNframe) { + if (frameTriggerCounter == burstNframe) + { triggered = 0; startStoreTrg = 0; // disable storing NtriggerCount++; @@ -1834,30 +2040,35 @@ int FLIR_SC65X::startFramesAcquisition() { // break; } } // if (frameTriggerCounter == burstNframe) - - } else //( triggerMode == 1 ) //Internal trigger source + } + else //( triggerMode == 1 ) //Internal trigger source { // Multiple trigger acquisition: first trigger save 64bit timestamp timebaseNid = -1; // used in cammdsutils to use internal triggered = 1; // debug - if (startStoreTrg == 1) { + if (startStoreTrg == 1) + { gettimeofday(&tv, NULL); timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - if (timeStamp0 == 0) { + if (timeStamp0 == 0) + { Int64 *tsMDS = new Int64(timeStamp); t0Node->putData(tsMDS); timeStamp0 = timeStamp; - } else { + } + else + { frameTime = (float)((timeStamp - timeStamp0) / 1000.0); // interval from first frame [s] // printf("frameTime: %f", frameTime); } } // if startStoreTrg == 1 - if (frameTriggerCounter == burstNframe) { + if (frameTriggerCounter == burstNframe) + { startStoreTrg = 0; // disable storing frameTriggerCounter = 0; NtriggerCount++; @@ -1877,7 +2088,8 @@ int FLIR_SC65X::startFramesAcquisition() { // # status=4 triggered frame + complete if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && (acqSkipFrameNumber <= 0 || - (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) { + (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) + { int frameTimeBaseIdx; frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; // printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, @@ -1896,15 +2108,20 @@ int FLIR_SC65X::startFramesAcquisition() { savedFrameNumber++; } - if (streamingEnabled) { - if (tcpStreamHandle == -1) { + if (streamingEnabled) + { + if (tcpStreamHandle == -1) + { rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, CSU_PIX_FMT_GRAY16); - if (rstatus != -1) { + if (rstatus != -1) + { printf("Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); - } else { + } + else + { printf("Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); streamingEnabled = 0; @@ -1917,7 +2134,8 @@ int FLIR_SC65X::startFramesAcquisition() { 0) // send frame @ 10Hz. Reduce CPU usage when radiometric // conversion must be performed. { - if (irFrameFormat == radiometric) { + if (irFrameFormat == radiometric) + { flirRadiometricConv( frameBuffer, width, height, metaData); // radiometric conversion in Celsius using metadata diff --git a/device_support/flir/FLIRSC65X.h b/device_support/flir/FLIRSC65X.h index 2a6ee61833..f38c2964ee 100644 --- a/device_support/flir/FLIRSC65X.h +++ b/device_support/flir/FLIRSC65X.h @@ -3,71 +3,91 @@ #include #include //new 9mar2016 for SDK4 -enum FPS_ENUM { fps_200, fps_100, fps_50, fps_25, fps_12, fps_6, fps_3 }; -enum IRFMT_ENUM { radiometric, linear10mK, linear100mK }; -enum EXPMODE_ENUM { internal_mode, external_mode }; +enum FPS_ENUM +{ + fps_200, + fps_100, + fps_50, + fps_25, + fps_12, + fps_6, + fps_3 +}; +enum IRFMT_ENUM +{ + radiometric, + linear10mK, + linear100mK +}; +enum EXPMODE_ENUM +{ + internal_mode, + external_mode +}; #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -extern int flirRadiometricConv(void *frame, int width, int height, - void *metaData); - -// Wrapper for Python that must see the cpp class as standard C functions - -int flirOpen(const char *cameraName, int *camHandle); -int flirClose(int camHandle); -int checkLastOp(int camHandle); -int printAllParameters(int camHandle); -int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode); - -int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); -int setFrameRateNew(int camHandle, double frameRate); - -int setIrFormat(int camHandle, IRFMT_ENUM irFormat); -int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); -int setReadoutArea(int camHandle, int x, int y, int width, int height); -int setObjectParameters(int camHandle, double reflectedTemperature, - double atmosphericTemperature, double objectDistance, - double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, - double extOpticsTransmission, - double estimatedTransmission); -int setMeasurementRange(int camHandle, int measRange); -int getFocusAbsPosition(int camHandle, int *focusPos); -int setFocusAbsPosition(int camHandle, int focusPos); -int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); - -int executeAutoFocus(int camHandle); -int setCalibMode(int camHandle, int calMode); -int executeAutoCalib(int camHandle); -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); -int stopAcquisition(int camHandle); -int getFrame(int camHandle, int *status, void *frame, void *metaData); -int frameConv(int camHandle, unsigned short *frame, int width, int height); -int startFramesAcquisition(int camHandle); -int stopFramesAcquisition(int camHandle); - -int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, const char *streamingServer, - int streamingPort, int lowLim, int highLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName); - -int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger); -int softwareTrigger(int camHandle); -int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid); - -void getLastError(int camHandle, char *msg); + extern int flirRadiometricConv(void *frame, int width, int height, + void *metaData); + + // Wrapper for Python that must see the cpp class as standard C functions + + int flirOpen(const char *cameraName, int *camHandle); + int flirClose(int camHandle); + int checkLastOp(int camHandle); + int printAllParameters(int camHandle); + int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode); + + int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); + int setFrameRateNew(int camHandle, double frameRate); + + int setIrFormat(int camHandle, IRFMT_ENUM irFormat); + int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); + int setReadoutArea(int camHandle, int x, int y, int width, int height); + int setObjectParameters(int camHandle, double reflectedTemperature, + double atmosphericTemperature, double objectDistance, + double objectEmissivity, double relativeHumidity, + double extOpticsTemperature, + double extOpticsTransmission, + double estimatedTransmission); + int setMeasurementRange(int camHandle, int measRange); + int getFocusAbsPosition(int camHandle, int *focusPos); + int setFocusAbsPosition(int camHandle, int focusPos); + int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); + + int executeAutoFocus(int camHandle); + int setCalibMode(int camHandle, int calMode); + int executeAutoCalib(int camHandle); + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); + int stopAcquisition(int camHandle); + int getFrame(int camHandle, int *status, void *frame, void *metaData); + int frameConv(int camHandle, unsigned short *frame, int width, int height); + int startFramesAcquisition(int camHandle); + int stopFramesAcquisition(int camHandle); + + int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, + bool autoAdjustLimit, const char *streamingServer, + int streamingPort, int lowLim, int highLim, int adjRoiX, + int adjRoiY, int adjRoiW, int adjRoiH, + const char *deviceName); + + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, + int numTrigger); + int softwareTrigger(int camHandle); + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, + int framesMetadNid, int frame0TimeNid); + + void getLastError(int camHandle, char *msg); #ifdef __cplusplus } #endif -class FLIR_SC65X { +class FLIR_SC65X +{ private: PvDevice *lDevice; // camera handle PvStream *lStream; // stream handle diff --git a/device_support/flir/fff.h b/device_support/flir/fff.h index 02412c2396..9b2a678b40 100644 --- a/device_support/flir/fff.h +++ b/device_support/flir/fff.h @@ -11,8 +11,8 @@ #define FLIR_FILE_FORMAT 0x46464600 /* FFF\0 */ #define FILE_FORMAT_VERSION 100 /* 1.00 */ -#define FFF_EXT \ - "FFF" /* Default file name \ +#define FFF_EXT \ + "FFF" /* Default file name \ extention */ // Bit mask for trig types @@ -29,7 +29,8 @@ typedef unsigned char BYTE; typedef unsigned short USHORT; typedef unsigned int ULONG; -struct _fpgaheader_t { +struct _fpgaheader_t +{ unsigned char major; unsigned char minor; unsigned char dp1_trig_type; // Digital port 1, trig type @@ -54,7 +55,8 @@ typedef struct _fpgaheader_t FPGA_HEADER; // main types -typedef enum { +typedef enum +{ /* General tags */ FFF_TAGID_FREE = 0, /* Marks unused tag descriptor */ @@ -89,7 +91,8 @@ typedef enum { /* Sub Tags for FFF_TAGID_Pixels */ -enum { +enum +{ FFF_Pixels_BE = 1, /* Big endian pixel data block */ FFF_Pixels_LE = 2, /* Little endian pixel data block */ FFF_Pixels_PNG = 3 /* PNG compressed pixel data block (BE or LE) */ @@ -97,11 +100,15 @@ enum { /* When appropriate, add subID enums for other TAG_MAIN_T too */ /* When subtype isn't used, fill subtype with FFF_SubID_default */ -enum { FFF_SubID_default = 1 }; +enum +{ + FFF_SubID_default = 1 +}; #pragma pack(push, 1) -typedef struct tagFLIRFILEHEAD { +typedef struct tagFLIRFILEHEAD +{ char szFormatID[4]; /* Fileformat ID 'FFF\0' 4 4 */ char szOrigin[16]; /* File origin 16 20 */ unsigned int dwVersion; /* File format version 4 24 */ @@ -111,10 +118,11 @@ typedef struct tagFLIRFILEHEAD { unsigned short usSwapPattern; /* Swap pattern (0=MSBF) 2 38 */ unsigned short usSpare[7]; /* Spare 14 52 */ unsigned int reserved[2]; /* reserved 8 60 */ - unsigned int dwChecksum; /* Head & index checksum 4 64 unsigned chars */ + unsigned int dwChecksum; /* Head & index checksum 4 64 unsigned chars */ } FLIRFILEHEAD; -typedef struct _geometric_info_t { +typedef struct _geometric_info_t +{ /** Size of one pixel in unsigned chars. Normal size is 2 unsigned chars (16 bit pixels) or 3 (for colorized YCbCr pixels) */ @@ -162,8 +170,9 @@ typedef struct _geometric_info_t { unsigned short reserved1; //!< For future use - should be set to 0 } GEOMETRIC_INFO_T; //!< sizeof struct == 32 unsigned chars -struct IMAGEINFO_T { - unsigned int imageTime; //!< Time in seconds since 1970-01-01 00:00 (UTC) +struct IMAGEINFO_T +{ + unsigned int imageTime; //!< Time in seconds since 1970-01-01 00:00 (UTC) unsigned long imageMilliTime; //!< Milliseconds since last second short timeZoneBias; //!< Time zone bias in minutes @@ -191,7 +200,8 @@ struct IMAGEINFO_T { /** Distribution information */ -struct DISTR_DATA_T { +struct DISTR_DATA_T +{ /** Framegrab independent distribution data */ char imgName[16]; /* (4 longs) */ @@ -233,7 +243,8 @@ struct DISTR_DATA_T { int reserved2[3]; }; //!< sizeof struct == 64 unsigned chars -typedef struct _pres_par_t { +typedef struct _pres_par_t +{ signed int level; /* Level as normalized pixel value (apix), Level is defined as middle of span (in pixel units) */ signed int span; /* Span as normalized pixel value (apix) */ @@ -243,7 +254,8 @@ typedef struct _pres_par_t { /** * FFF tag index */ -typedef struct tagFLIRFILEINDEX { +typedef struct tagFLIRFILEINDEX +{ unsigned short wMainType; /**< Main type of index 2 2 Should be one of TAG_MAIN_T */ unsigned short wSubType; /**< Sub type of index 2 4 */ @@ -262,7 +274,8 @@ typedef struct tagFLIRFILEINDEX { Ethernet polynom. */ } FLIRFILEINDEX; -struct _bidata_t { +struct _bidata_t +{ GEOMETRIC_INFO_T GeometricInfo; // 32 unsigned chars unsigned char ObjectParameters[48]; unsigned char CalibParameters[132]; diff --git a/device_support/flir/flirutils.h b/device_support/flir/flirutils.h index 411fd416dc..dc550cf491 100644 --- a/device_support/flir/flirutils.h +++ b/device_support/flir/flirutils.h @@ -3,18 +3,19 @@ Radiometric Conversion functions for FLIR Camera */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int flirRadiometricConv(void *frame, int width, int height, void *metaData); -int flirRadiometricConvPar(void *frame, int width, int height, void *metaData, - float atmTemp, float emissivity, - float objectDistance, float ambTemp, float relHum); -void flirRadiometricConvFrames(void *frame, int width, int height, - int numFrames, void *metaData); -void flirRadiometricConvFramesPar(void *frame, int width, int height, - int numFrames, void *metaData, float *atmTemp, - float *emissivity, float *objectDistance, - float *ambTemp, float *relHum); + int flirRadiometricConv(void *frame, int width, int height, void *metaData); + int flirRadiometricConvPar(void *frame, int width, int height, void *metaData, + float atmTemp, float emissivity, + float objectDistance, float ambTemp, float relHum); + void flirRadiometricConvFrames(void *frame, int width, int height, + int numFrames, void *metaData); + void flirRadiometricConvFramesPar(void *frame, int width, int height, + int numFrames, void *metaData, float *atmTemp, + float *emissivity, float *objectDistance, + float *ambTemp, float *relHum); #ifdef __cplusplus } #endif diff --git a/device_support/flir/main.cpp b/device_support/flir/main.cpp index 0a646a209b..3ca1b54a10 100644 --- a/device_support/flir/main.cpp +++ b/device_support/flir/main.cpp @@ -34,10 +34,10 @@ using namespace MDSplus; #include "flirutils.h" //flir radiometric conversion #include "fff.h" -#define USETHECAMERA // this let to use the camera or if not defined to read - // data from a pulse file. +#define USETHECAMERA // this let to use the camera or if not defined to read data from a pulse file. -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ if ((argv[1] == NULL) || (argv[2] == NULL) || (argv[3] == NULL)) // argv[4] is OPTIONAL { @@ -50,7 +50,8 @@ int main(int argc, char **argv) { int res; void *treePtr; res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); - if (res == -1) { + if (res == -1) + { printf("Error opening tree...\n"); exit(0); } @@ -60,13 +61,16 @@ int main(int argc, char **argv) { TreeNode *nodeMeta; int dataNid; - try { + try + { tree = (Tree *)treePtr; node = tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES"); nodeMeta = tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES_METAD"); dataNid = node->getNid(); // Node id to save the acquired frames - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } @@ -88,7 +92,8 @@ int main(int argc, char **argv) { short *framePtr; char *framePtrMeta; - try { + try + { frameArray = node->getSegment(0); // idx frameArrayMeta = nodeMeta->getSegment(0); // idx @@ -107,7 +112,9 @@ int main(int argc, char **argv) { int dataDimsMeta[3]; framePtr = (frameData)->getShortArray(dataDims); framePtrMeta = (frameDataMeta)->getByteArray(dataDimsMeta); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } @@ -129,7 +136,8 @@ int main(int argc, char **argv) { int i = 1; int canStream = -1; - if (argv[4] != NULL) { + if (argv[4] != NULL) + { while (canStream == -1 && i <= 5) // try 5 times to open the connection { @@ -139,9 +147,12 @@ int main(int argc, char **argv) { sleep(1); i++; } - if (canStream == 0) { + if (canStream == 0) + { printf("Streaming OK!\n"); - } else { + } + else + { printf("CANNOT Streaming!\n"); } } @@ -152,10 +163,13 @@ int main(int argc, char **argv) { FLIR_SC65X *FlirCam; FlirCam = new FLIR_SC65X("192.168.100.18"); // vecchia 169.254.169.249 //nuova // 169.254.76.254 //192.168.50.20 - if (!FlirCam->checkLastOp()) { + if (!FlirCam->checkLastOp()) + { printf("Unable to connect!!!\n"); exit(0); - } else { + } + else + { printf("Successfully connected...\n"); } @@ -216,7 +230,8 @@ int main(int argc, char **argv) { FlirCam->getFrame(&status, frame, metaData); gettimeofday(&tv, NULL); timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - switch (status) { + switch (status) + { case 1: printf("get frame %d complete @ %ld\n", frameNumber, timeStamp); break; @@ -231,7 +246,8 @@ int main(int argc, char **argv) { break; } - if (status == 1 or status == 4) { + if (status == 1 or status == 4) + { // SAVE FRAME IN MDSPLUS /* res=camSaveFrame(frame, width, height, &timeStamp, 14, @@ -248,7 +264,8 @@ int main(int argc, char **argv) { if (skipFrame == 0) printf("ERROR SKIPFRAME=0\n"); int sendFrame = i % skipFrame; - if (canStream == 0 and sendFrame == 0) { + if (canStream == 0 and sendFrame == 0) + { // streaming is set to 640 x 480 in "camOpenTcpConnection". // It must be changed to prevent strange image transmission! unsigned int lowLim = 0; diff --git a/device_support/kappa/kappazelos.cpp b/device_support/kappa/kappazelos.cpp index b7b2f5efa6..1b3453447b 100644 --- a/device_support/kappa/kappazelos.cpp +++ b/device_support/kappa/kappazelos.cpp @@ -34,13 +34,14 @@ using namespace std; #include "kappazelos.h" -#define _CHECK(f) \ - { \ - SDK4_ERROR err = (f); \ - if (SDK4_ERR_SUCCESS != err) { \ - cerr << #f << " failed: " << err << endl; \ - goto Exit; \ - } \ +#define _CHECK(f) \ + { \ + SDK4_ERROR err = (f); \ + if (SDK4_ERR_SUCCESS != err) \ + { \ + cerr << #f << " failed: " << err << endl; \ + goto Exit; \ + } \ } #define error -1 #define success 0 @@ -48,8 +49,10 @@ using namespace std; // debug mode if defined #define debug -const char *ExposureModeToString(SDK4_ENUM_EXPOSUREMODE eExposureMode) { - switch (eExposureMode) { +const char *ExposureModeToString(SDK4_ENUM_EXPOSUREMODE eExposureMode) +{ + switch (eExposureMode) + { case ZELOS_ENUM_EXPOSUREMODE_FREERUNNINGPARALLEL: return "FreeRunningParallel"; case ZELOS_ENUM_EXPOSUREMODE_FREERUNNINGSEQUENTIAL: @@ -67,11 +70,12 @@ const char *ExposureModeToString(SDK4_ENUM_EXPOSUREMODE eExposureMode) { #define swapShort(data) (((data) >> 8) & 0x00ff) | (((data) << 8) & 0xff00) -#define swapInt(data) \ - ((((data) >> 24) & 0x000000ff) | (((data) >> 8) & 0x0000ff00) | \ +#define swapInt(data) \ + ((((data) >> 24) & 0x000000ff) | (((data) >> 8) & 0x0000ff00) | \ (((data) << 8) & 0x00ff0000) | (((data) << 24) & 0xff000000)) -int swapPixel(short *buf, int32_t size) { +int swapPixel(short *buf, int32_t size) +{ int i; for (i = 0; i < size; i++) buf[i] = swapShort(buf[i]); @@ -79,7 +83,8 @@ int swapPixel(short *buf, int32_t size) { return 0; } -int kappaOpen(const char *cameraName, void **cameraHandle) { +int kappaOpen(const char *cameraName, void **cameraHandle) +{ vector devnames; int32_t numDevices = 0; DEV_HANDLE hDev; @@ -108,7 +113,8 @@ int kappaOpen(const char *cameraName, void **cameraHandle) { return error; } -int kappaClose(void *cameraHandle) { +int kappaClose(void *cameraHandle) +{ _CHECK(SDK4CloseDevice(cameraHandle)); _CHECK(SDK4CloseLib()); @@ -118,13 +124,15 @@ int kappaClose(void *cameraHandle) { } int kappaSetColorCoding(void *cameraHandle, - SDK4_ENUM_COLORCODING color_coding) { + SDK4_ENUM_COLORCODING color_coding) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetColorCoding(hCtrl, color_coding)); #ifdef debug - switch (color_coding) { + switch (color_coding) + { case SDK4_ENUM_COLORCODING_Y8: cout << "Color Coding set to Y8" << endl; break; @@ -145,7 +153,8 @@ int kappaSetColorCoding(void *cameraHandle, return error; } -int kappaSetExposureMode(void *cameraHandle, SDK4_ENUM_EXPOSUREMODE expmode) { +int kappaSetExposureMode(void *cameraHandle, SDK4_ENUM_EXPOSUREMODE expmode) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetExposureMode(hCtrl, expmode)); @@ -157,28 +166,34 @@ int kappaSetExposureMode(void *cameraHandle, SDK4_ENUM_EXPOSUREMODE expmode) { return error; } -int kappaSetExposure(void *cameraHandle, float expTime) { +int kappaSetExposure(void *cameraHandle, float expTime) +{ CTRL_HANDLE hCtrl; SDK4_KEXPOSURE kExposure; kExposure.base = SDK4_ENUM_EXPOSUREBASE_1us; kExposure.counter = (int)(expTime / 1E-6); - if (kExposure.counter > 256) { + if (kExposure.counter > 256) + { kExposure.base = SDK4_ENUM_EXPOSUREBASE_10us; kExposure.counter = (int)(expTime / 1E-5); } - if (kExposure.counter > 256) { + if (kExposure.counter > 256) + { kExposure.base = SDK4_ENUM_EXPOSUREBASE_100us; kExposure.counter = (int)(expTime / 1E-4); } - if (kExposure.counter > 256) { + if (kExposure.counter > 256) + { kExposure.base = SDK4_ENUM_EXPOSUREBASE_1ms; kExposure.counter = (int)(expTime / 1E-3); } - if (kExposure.counter > 256) { + if (kExposure.counter > 256) + { kExposure.base = SDK4_ENUM_EXPOSUREBASE_10ms; kExposure.counter = (int)(expTime / 1E-2); } - if (kExposure.counter > 256) { + if (kExposure.counter > 256) + { kExposure.base = SDK4_ENUM_EXPOSUREBASE_100ms; kExposure.counter = (int)(expTime / 1E-1); } @@ -189,7 +204,8 @@ int kappaSetExposure(void *cameraHandle, float expTime) { #ifdef debug double espo; espo = 0; - switch (kExposure.base) { + switch (kExposure.base) + { case 0: espo = 0; break; @@ -223,12 +239,14 @@ int kappaSetExposure(void *cameraHandle, float expTime) { return error; } -int kappaSetAET(void *cameraHandle, SDK4_ENUM_AET aet) { +int kappaSetAET(void *cameraHandle, SDK4_ENUM_AET aet) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetAET(hCtrl, aet)); #ifdef debug - switch (aet) { + switch (aet) + { case 0: cout << "AET OFF" << endl; break; @@ -248,15 +266,19 @@ int kappaSetAET(void *cameraHandle, SDK4_ENUM_AET aet) { return error; } -int kappaSetAutoExposureLevel(void *cameraHandle, uint32_t lev) { +int kappaSetAutoExposureLevel(void *cameraHandle, uint32_t lev) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); - if (lev >= 0 && lev <= 255) { + if (lev >= 0 && lev <= 255) + { _CHECK(SDK4SetAutoExposureLevel(hCtrl, lev)); #ifdef debug cout << "Auto Exposure level set to: " << lev << endl; #endif - } else { + } + else + { #ifdef debug cout << "Auto Exposure level must be in range 0-255." << endl; return error; @@ -268,16 +290,20 @@ int kappaSetAutoExposureLevel(void *cameraHandle, uint32_t lev) { return error; } -int kappaSetGain(void *cameraHandle, uint32_t gain) { +int kappaSetGain(void *cameraHandle, uint32_t gain) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); - if (gain >= 0 && gain <= 511) { + if (gain >= 0 && gain <= 511) + { _CHECK(SDK4SetGain(hCtrl, gain)); #ifdef debug cout << "Gain set to: " << gain << endl; #endif - } else { + } + else + { #ifdef debug cout << "Gain must be in range 0-511." << endl; return error; @@ -288,12 +314,14 @@ int kappaSetGain(void *cameraHandle, uint32_t gain) { return error; } -int kappaSetAGC(void *cameraHandle, SDK4_ENUM_AGC agc) { +int kappaSetAGC(void *cameraHandle, SDK4_ENUM_AGC agc) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetAGC(hCtrl, agc)); #ifdef debug - switch (agc) { + switch (agc) + { case 0: cout << "AGC OFF" << endl; break; @@ -310,12 +338,14 @@ int kappaSetAGC(void *cameraHandle, SDK4_ENUM_AGC agc) { return error; } -int kappaSetSoftTrigger(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff) { +int kappaSetSoftTrigger(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetSoftTrigger(hCtrl, uOnOff)); #ifdef debug - switch (uOnOff) { + switch (uOnOff) + { case 0: cout << "Soft Trigger Switch OFF" << endl; break; @@ -343,12 +373,14 @@ int kappaSetTriggerTimer(void *cameraHandle, return error; } -int kappaSetSlowScan(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff) { +int kappaSetSlowScan(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff) +{ CTRL_HANDLE hCtrl; _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetSlowScan(hCtrl, uOnOff)); #ifdef debug - switch (uOnOff) { + switch (uOnOff) + { case 0: cout << "Slow Scan OFF" << endl; break; @@ -363,7 +395,8 @@ int kappaSetSlowScan(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff) { } int kappaGetReadoutAreaLimits(void *cameraHandle, SDK4_ENUM_ROADOMAIN select, - int *x, int *y, int *width, int *height) { + int *x, int *y, int *width, int *height) +{ CTRL_HANDLE hCtrl; SDK4_KAREA roa; @@ -376,7 +409,8 @@ int kappaGetReadoutAreaLimits(void *cameraHandle, SDK4_ENUM_ROADOMAIN select, *height = roa.end.yPos - *y; #ifdef debug - switch (select) { + switch (select) + { case 0: cout << "Readout Area MIN" << endl; break; @@ -398,7 +432,8 @@ int kappaGetReadoutAreaLimits(void *cameraHandle, SDK4_ENUM_ROADOMAIN select, } int kappaSetReadoutArea(void *cameraHandle, int x, int y, int width, - int height) { + int height) +{ CTRL_HANDLE hCtrl; SDK4_KAREA roa; roa.start.xPos = x; @@ -419,7 +454,8 @@ int kappaSetReadoutArea(void *cameraHandle, int x, int y, int width, return error; } -int kappaSetBinning(void *cameraHandle, int binHor, int binVer) { +int kappaSetBinning(void *cameraHandle, int binHor, int binVer) +{ SDK4_KBINNING bin; CTRL_HANDLE hCtrl; bin.horizontal = binHor; @@ -438,7 +474,8 @@ int kappaSetBinning(void *cameraHandle, int binHor, int binVer) { #ifdef debug cout << "Horizontal binning set to "; - switch (bin.horizontal) { + switch (bin.horizontal) + { case 1: cout << "1x" << endl; break; @@ -465,7 +502,8 @@ int kappaSetBinning(void *cameraHandle, int binHor, int binVer) { break; } cout << "Vertical binning set to "; - switch (bin.vertical) { + switch (bin.vertical) + { case 1: cout << "1x" << endl; break; @@ -498,7 +536,8 @@ int kappaSetBinning(void *cameraHandle, int binHor, int binVer) { } int kappaSetMeasureWindow(void *cameraHandle, int x, int y, int width, - int height) { + int height) +{ SDK4_ENUM_MEASUREWINDOWSELECT select = 0; SDK4_KAREA mwin; CTRL_HANDLE hCtrl; @@ -509,7 +548,8 @@ int kappaSetMeasureWindow(void *cameraHandle, int x, int y, int width, _CHECK(SDK4DevGetControl(cameraHandle, &hCtrl)); _CHECK(SDK4SetMeasureWindow(hCtrl, select, mwin)); #ifdef debug - switch (select) { + switch (select) + { case 0: cout << "Measure Window 1" << endl; break; @@ -529,7 +569,8 @@ int kappaSetMeasureWindow(void *cameraHandle, int x, int y, int width, return error; } -int kappaGetIp(void *cameraHandle, char *ip) { +int kappaGetIp(void *cameraHandle, char *ip) +{ int32_t size = 24; CTRL_HANDLE hCtrl; @@ -544,7 +585,8 @@ int kappaGetIp(void *cameraHandle, char *ip) { return error; } -int kappaPrintInfo(void *cameraHandle) { +int kappaPrintInfo(void *cameraHandle) +{ static char sModel[256]; int32_t sizeModel = sizeof(sModel); @@ -578,7 +620,8 @@ int kappaPrintInfo(void *cameraHandle) { cout << "Width = " << dec << width << endl; cout << "Height = " << dec << height << endl; cout << "Format = " << hex << format << endl; - cout << "PayloadSize = " << dec << uPayloadSize << endl << endl; + cout << "PayloadSize = " << dec << uPayloadSize << endl + << endl; return success; Exit: @@ -586,7 +629,8 @@ int kappaPrintInfo(void *cameraHandle) { } int kappaStartAcquisition(void *cameraHandle, void **buffer, int32_t *width, - int32_t *height, uint32_t *payloadSize) { + int32_t *height, uint32_t *payloadSize) +{ DS_HANDLE hDataStream; _CHECK(SDK4DevGetDataStream(cameraHandle, &hDataStream)); @@ -598,7 +642,8 @@ int kappaStartAcquisition(void *cameraHandle, void **buffer, int32_t *width, tmpBuffer = (BUFFER_HANDLE *)malloc(sizeof(BUFFER_HANDLE) * 5); *buffer = (void *)tmpBuffer; - for (uint32_t i = 0; i < 5; i++) { + for (uint32_t i = 0; i < 5; i++) + { _CHECK(SDK4DSAllocAndAnnounceBuffer(hDataStream, *payloadSize, NULL, &tmpBuffer[i])); _CHECK(SDK4DSQueueBuffer(hDataStream, tmpBuffer[i])); @@ -610,7 +655,8 @@ int kappaStartAcquisition(void *cameraHandle, void **buffer, int32_t *width, return error; } -int kappaStopAcquisition(void *cameraHandle, void *buffer) { +int kappaStopAcquisition(void *cameraHandle, void *buffer) +{ _CHECK(SDK4DevStopAcquisition(cameraHandle)); @@ -618,7 +664,8 @@ int kappaStopAcquisition(void *cameraHandle, void *buffer) { _CHECK(SDK4DevGetDataStream(cameraHandle, &hDataStream)); _CHECK(SDK4DSFlushQueue(hDataStream)); - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) + { _CHECK(SDK4DSRevokeBuffer(hDataStream, ((BUFFER_HANDLE *)buffer)[i], NULL, NULL)); } @@ -629,7 +676,8 @@ int kappaStopAcquisition(void *cameraHandle, void *buffer) { return error; } -int kappaGetFrame(void *cameraHandle, int32_t *status, void *frame) { +int kappaGetFrame(void *cameraHandle, int32_t *status, void *frame) +{ BUFFER_HANDLE hTempBuffer; int32_t bComplete; void *pBuffer; @@ -642,15 +690,19 @@ int kappaGetFrame(void *cameraHandle, int32_t *status, void *frame) { SDK4_ERROR err; err = SDK4DSWaitForBuffer(hDataStream, &hTempBuffer, 900); - switch (err) { + switch (err) + { case SDK4_ERR_SUCCESS: _CHECK(SDK4BufferGetPtr(hTempBuffer, &pBuffer)); _CHECK(SDK4BufferGetSize(hTempBuffer, &size)); _CHECK(SDK4BufferIsComplete(hTempBuffer, &bComplete)); - if (bComplete) { + if (bComplete) + { *status = 1; // complete memcpy(frame, pBuffer, uPayloadSize); - } else { + } + else + { *status = 2; // incomplete memset(frame, 0, uPayloadSize); } diff --git a/device_support/kappa/kappazelos.h b/device_support/kappa/kappazelos.h index 7514913ed9..6dad5cfcac 100644 --- a/device_support/kappa/kappazelos.h +++ b/device_support/kappa/kappazelos.h @@ -2,41 +2,42 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -// camera -int kappaOpen(const char *cameraName, void **cameraHandle); -int kappaClose(void *cameraHandle); + // camera + int kappaOpen(const char *cameraName, void **cameraHandle); + int kappaClose(void *cameraHandle); -// settings -int kappaSetColorCoding(void *cameraHandle, SDK4_ENUM_COLORCODING color_coding); -int kappaSetExposureMode(void *cameraHandle, SDK4_ENUM_EXPOSUREMODE expmode); -int kappaSetExposure(void *cameraHandle, float expTime); -int kappaSetAET(void *cameraHandle, SDK4_ENUM_AET aet); -int kappaSetAutoExposureLevel(void *cameraHandle, uint32_t lev); -int kappaSetGain(void *cameraHandle, uint32_t gain); -int kappaSetAGC(void *cameraHandle, SDK4_ENUM_AGC agc); -int kappaSetSoftTrigger(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff); -int kappaSetTriggerTimer(void *cameraHandle, uint32_t time); -int kappaSetSlowScan(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff); -int kappaGetReadoutAreaLimits(void *cameraHandle, SDK4_ENUM_ROADOMAIN select, - int *x, int *y, int *width, int *height); -int kappaSetReadoutArea(void *cameraHandle, int x, int y, int width, - int height); -int kappaSetBinning(void *cameraHandle, int binHor, int binVer); -int kappaSetMeasureWindow(void *cameraHandle, int x, int y, int width, + // settings + int kappaSetColorCoding(void *cameraHandle, SDK4_ENUM_COLORCODING color_coding); + int kappaSetExposureMode(void *cameraHandle, SDK4_ENUM_EXPOSUREMODE expmode); + int kappaSetExposure(void *cameraHandle, float expTime); + int kappaSetAET(void *cameraHandle, SDK4_ENUM_AET aet); + int kappaSetAutoExposureLevel(void *cameraHandle, uint32_t lev); + int kappaSetGain(void *cameraHandle, uint32_t gain); + int kappaSetAGC(void *cameraHandle, SDK4_ENUM_AGC agc); + int kappaSetSoftTrigger(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff); + int kappaSetTriggerTimer(void *cameraHandle, uint32_t time); + int kappaSetSlowScan(void *cameraHandle, SDK4_ENUM_SWITCH uOnOff); + int kappaGetReadoutAreaLimits(void *cameraHandle, SDK4_ENUM_ROADOMAIN select, + int *x, int *y, int *width, int *height); + int kappaSetReadoutArea(void *cameraHandle, int x, int y, int width, int height); + int kappaSetBinning(void *cameraHandle, int binHor, int binVer); + int kappaSetMeasureWindow(void *cameraHandle, int x, int y, int width, + int height); -// info -int kappaGetIp(void *cameraHandle, char *ip); -int kappaPrintInfo(void *cameraHandle); + // info + int kappaGetIp(void *cameraHandle, char *ip); + int kappaPrintInfo(void *cameraHandle); -// acquisition -int kappaStartAcquisition(void *cameraHandle, void **buffer, int32_t *width, - int32_t *height, uint32_t *payloadSize); -int kappaStopAcquisition(void *cameraHandle, void *buffer); -int kappaGetFrame(void *cameraHandle, int32_t *status, void *frame); + // acquisition + int kappaStartAcquisition(void *cameraHandle, void **buffer, int32_t *width, + int32_t *height, uint32_t *payloadSize); + int kappaStopAcquisition(void *cameraHandle, void *buffer); + int kappaGetFrame(void *cameraHandle, int32_t *status, void *frame); #ifdef __cplusplus } diff --git a/device_support/kappa/main.cpp b/device_support/kappa/main.cpp index a725ba8c3b..64ed32a2b4 100644 --- a/device_support/kappa/main.cpp +++ b/device_support/kappa/main.cpp @@ -36,7 +36,8 @@ void *cameraHandle; int kSockHandle = -1; // MUST BE -1 THE FIRST TIME !!! void *hBuffer; -void signal_callback_handler(int signum) { +void signal_callback_handler(int signum) +{ printf("Caught signal %d\n", signum); // Cleanup and close up stuff here @@ -50,7 +51,8 @@ void signal_callback_handler(int signum) { exit(signum); } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int streamingPort = 0; int numFrame = 100; @@ -64,7 +66,8 @@ int main(int argc, char **argv) { numFrame = atoi(argv[3]); - if (argv[4]) { + if (argv[4]) + { streamingPort = atoi(argv[4]); } @@ -72,7 +75,8 @@ int main(int argc, char **argv) { int res; void *treePtr; res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); - if (res == -1) { + if (res == -1) + { printf("Error opening tree...\n"); exit(0); } @@ -93,7 +97,8 @@ int main(int argc, char **argv) { int i = 1; int canStream = -1; - if (streamingPort) { + if (streamingPort) + { while (canStream == -1 && i <= 1) // try 5 times to open the connection { @@ -101,9 +106,12 @@ int main(int argc, char **argv) { sleep(1); i++; } - if (canStream == 0) { + if (canStream == 0) + { printf("Streaming OK!\n"); - } else { + } + else + { printf("CANNOT Streaming!\n"); } } @@ -163,19 +171,23 @@ int main(int argc, char **argv) { kappaGetFrame(cameraHandle, &status, frame); // get the frame - gettimeofday(&tv, NULL); // get the timestamp + gettimeofday(&tv, NULL); // get the timestamp frameTime = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // ms - if (i == 1) { + if (i == 1) + { prevFrameTime = frameTime; totFrameTime = 0; - } else { + } + else + { deltaT = int(frameTime - prevFrameTime); prevFrameTime = frameTime; totFrameTime = totFrameTime + deltaT; } timeStamp = float(totFrameTime) / float(1000.0); - switch (status) { + switch (status) + { case 1: printf("get frame %d complete @ %.3f\n", frameNumber, timeStamp); break; @@ -190,13 +202,15 @@ int main(int argc, char **argv) { break; } - if (status == 1) { + if (status == 1) + { // SAVE FRAME IN MDSPLUS // camSaveFrame(frame, width, height, timeStamp, 14, treePtr, dataNid, -1, // frameNumber, 0, 0, 0, void *saveListPtr); // STREAMING - if (canStream == 0) { + if (canStream == 0) + { unsigned int lowLim = 0; unsigned int highLim = 20000; camFrameTo8bit((unsigned short *)frame, 1920, 1080, diff --git a/device_support/national/AsyncStoreManager.cpp b/device_support/national/AsyncStoreManager.cpp index bc8c7de14c..3e2a947d8a 100644 --- a/device_support/national/AsyncStoreManager.cpp +++ b/device_support/national/AsyncStoreManager.cpp @@ -38,7 +38,8 @@ SaveItem::SaveItem(void *buffer, int bufSize, int sampleToRead, char dataType, float timeIdx0, void *treePtr, int shot, int streamFactor, char *streamName, float streamGain, float streamOffset, double period, float gain, float *coeffs, int numCoeffs, - int resampledNid = -1) { + int resampledNid = -1) +{ this->buffer = buffer; this->dataType = dataType; this->bufSize = bufSize; @@ -123,13 +124,16 @@ SaveItem::SaveItem(void *buffer, int bufSize, int sampleToRead, char dataType, } ***********************/ -void SaveItem::save() { +void SaveItem::save() +{ // Streaming stuff - if (streamName && streamFactor > 0 && (counter % streamFactor) == 0) { + if (streamName && streamFactor > 0 && (counter % streamFactor) == 0) + { // Computation of value to be streamed - try { + try + { Data *nidData = new Int32(dataNid); int sampleInterval = (int)(0.1 / period); if (sampleInterval < 1) @@ -142,7 +146,8 @@ void SaveItem::save() { float *samples = new float[numSamples]; float *times = new float[numSamples]; int actSamples = 0; - for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) { + for (int sampleIdx = 0; sampleIdx < numSamples; sampleIdx++) + { if (sampleIdx * sampleInterval >= bufSize) break; float sample = @@ -151,7 +156,8 @@ void SaveItem::save() { : ((float *)buffer)[sampleIdx * sampleInterval]); float scaled = coeffs[numCoeffs - 1]; - for (int c = numCoeffs - 2; c >= 0; c--) { + for (int c = numCoeffs - 2; c >= 0; c--) + { scaled *= sample; scaled += coeffs[c]; } @@ -177,8 +183,9 @@ void SaveItem::save() { // timeIdx0), sample); delete[] samples; delete[] times; - - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Cannot convert stream sample: %s\n", exc.what()); } } @@ -187,7 +194,8 @@ void SaveItem::save() { // printf("Counter = %d Sample to read = %d\n", counter, sampleToRead ); // if((counter % segmentSize) == 0 || ((int)(counter / segmentSize) * // segmentSize) < counter + bufSize ) - if ((counter % segmentSize) == 0) { + if ((counter % segmentSize) == 0) + { // Create Segment Data *startIdx = new Int32(counter); Data *endIdx; @@ -222,8 +230,9 @@ void SaveItem::save() { (Tree *)treePtr, 3, clockNode, startIdx, endIdx); dim = compileWithArgs("NIADCClockSegment($1, $2, $3, 0, 'dim')", (Tree *)treePtr, 3, clockNode, startIdx, endIdx); - - } else { + } + else + { Data *timeAtIdx0 = new Float32(timeIdx0); /* startTime = tree->tdiCompile("$+slope_of($)*$", timeAtIdx0, clockNode, @@ -242,47 +251,58 @@ void SaveItem::save() { (Tree *)treePtr, 4, clockNode, startIdx, endIdx, timeAtIdx0); } - switch (dataType) { - case SHORT: { + switch (dataType) + { + case SHORT: + { short *fBuf = new short[segmentSize]; memset(fBuf, 0, sizeof(short) * segmentSize); Int16Array *fData = new Int16Array((short *)fBuf, segmentSize); pthread_mutex_lock(&segmentMutex); - try { + try + { if (resampledNode) dataNode->beginSegmentMinMax(startTime, endTime, dim, fData, resampledNode, 100); // dataNode->beginSegment(startTime, endTime, dim, fData); else dataNode->beginSegment(startTime, endTime, dim, fData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("BEGIN SEGMENT FAILED FOR NODE %s: %s\n", dataNode->getFullPath(), exc.what()); } pthread_mutex_unlock(&segmentMutex); delete[] fBuf; deleteData(fData); - } break; - case FLOAT: { + } + break; + case FLOAT: + { float *fBuf = new float[segmentSize]; memset(fBuf, 0, sizeof(float) * segmentSize); Float32Array *fData = new Float32Array((float *)fBuf, segmentSize); pthread_mutex_lock(&segmentMutex); - try { + try + { if (resampledNode) dataNode->beginSegmentMinMax(startTime, endTime, dim, fData, resampledNode, 100); // dataNode->beginSegment(startTime, endTime, dim, fData); else dataNode->beginSegment(startTime, endTime, dim, fData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("BEGIN SEGMENT FAILED FOR NODE %s: %s\n", dataNode->getFullPath(), exc.what()); } pthread_mutex_unlock(&segmentMutex); delete[] fBuf; deleteData(fData); - } break; + } + break; } deleteData(startIdx); deleteData(endIdx); @@ -290,53 +310,66 @@ void SaveItem::save() { deleteData(endTime); } - try { - switch (dataType) { - case SHORT: { + try + { + switch (dataType) + { + case SHORT: + { // printf("Short Save data %s counter %d\n", dataNode->getPath(), counter // ); Int16Array *data = new Int16Array((short *)buffer, bufSize); pthread_mutex_lock(&segmentMutex); - try { + try + { if (resampledNode) dataNode->putSegmentMinMax(data, -1, resampledNode, 100); // dataNode->putSegment(data, -1); else dataNode->putSegment(data, -1); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("PUT SEGMENT FAILED FOR NODE: %s: %s\n", dataNode->getFullPath(), exc.what()); } pthread_mutex_unlock(&segmentMutex); deleteData(data); delete[](short *) buffer; - } break; - case FLOAT: { + } + break; + case FLOAT: + { // printf("Float Save data %s counter %d\n", dataNode->getPath(), counter // ); Float32Array *data = new Float32Array((float *)buffer, bufSize); pthread_mutex_lock(&segmentMutex); - try { + try + { if (resampledNode) dataNode->putSegmentMinMax(data, -1, resampledNode, 100); // dataNode->putSegment(data, -1); else dataNode->putSegment(data, -1); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("PUT SEGMENT FAILED FOR NODE: %s: %s\n", dataNode->getFullPath(), exc.what()); } pthread_mutex_unlock(&segmentMutex); deleteData(data); delete[](float *) buffer; - } break; + } + break; } /* Send Event on Segment update __CH*/ // sendChannelSegmentPutEvent(dataNode); - - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Cannot put segment: %s\n", exc->what()); } delete dataNode; @@ -358,7 +391,8 @@ class SaveList pthread_mutex_t mutex; public: */ -SaveList::SaveList() { +SaveList::SaveList() +{ int status = pthread_mutex_init(&mutex, NULL); pthread_cond_init(&itemAvailable, NULL); saveHead = saveTail = NULL; @@ -397,7 +431,8 @@ void SaveList::addItem(void *buffer, int bufSize, int sampleToRead, if (saveHead == NULL) saveHead = saveTail = newItem; - else { + else + { saveTail->setNext(newItem); saveTail = newItem; } @@ -408,17 +443,22 @@ void SaveList::addItem(void *buffer, int bufSize, int sampleToRead, reportQueueLen(dataNid, treePtr, getQueueLen(), shot); #endif } -void SaveList::executeItems() { - while (true) { +void SaveList::executeItems() +{ + while (true) + { pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } - while (saveHead == NULL) { + while (saveHead == NULL) + { pthread_cond_wait(&itemAvailable, &mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } @@ -449,21 +489,25 @@ void SaveList::executeItems() { delete currItem; } } -void SaveList::start() { +void SaveList::start() +{ pthread_create(&thread, NULL, handleSave, (void *)this); threadCreated = true; } -void SaveList::stop() { +void SaveList::stop() +{ stopReq = true; pthread_cond_signal(&itemAvailable); - if (threadCreated) { + if (threadCreated) + { pthread_join(thread, NULL); printf("SAVE THREAD TERMINATED\n"); } } // Queue length streaming support -void reportQueueLen(int dataNid, void *treePtr, int len, int shot) { +void reportQueueLen(int dataNid, void *treePtr, int len, int shot) +{ static long prevTimeMs = 0; static int prevShot = -1; static unordered_map prevTimes; @@ -476,13 +520,15 @@ void reportQueueLen(int dataNid, void *treePtr, int len, int shot) { currTimeMs = retTime.tv_sec * 1000 + retTime.tv_nsec / 1000000; pthread_mutex_lock(&globalMutex); - if (shot != prevShot) { + if (shot != prevShot) + { prevTimes.clear(); prevShot = shot; startTimeMs = currTimeMs; } - if (prevTimes.count(dataNid) > 0 && currTimeMs <= prevTimes[dataNid]) { + if (prevTimes.count(dataNid) > 0 && currTimeMs <= prevTimes[dataNid]) + { pthread_mutex_unlock(&globalMutex); return; } @@ -490,19 +536,22 @@ void reportQueueLen(int dataNid, void *treePtr, int len, int shot) { pthread_mutex_unlock(&globalMutex); TreeNode *currNode = new TreeNode(dataNid, (Tree *)treePtr); - while (currNode->getNid() > 0 && strcmp(currNode->getUsage(), "DEVICE")) { + while (currNode->getNid() > 0 && strcmp(currNode->getUsage(), "DEVICE")) + { TreeNode *prevNode = currNode; currNode = currNode->getParent(); delete prevNode; } - if (currNode->getNid() == 0) { + if (currNode->getNid() == 0) + { if (debug) std::cout << "INTERNAL ERROR: wrong data nid to reportQueueLen" << std::endl; return; } StringArray *tags = currNode->findTags(); - if (tags->getSize() < 1) { + if (tags->getSize() < 1) + { if (debug) std::cout << "WARNING: no tags for data node to reportQueueLen" << std::endl; @@ -520,20 +569,24 @@ void reportQueueLen(int dataNid, void *treePtr, int len, int shot) { delete[] buf; } -void *handleSave(void *listPtr) { +void *handleSave(void *listPtr) +{ SaveList *list = (SaveList *)listPtr; list->executeItems(); return NULL; } -void startSave(void **retList) { +void startSave(void **retList) +{ SaveList *saveList = new SaveList; saveList->start(); *retList = (void *)saveList; } -void stopSave(void *listPtr) { - if (listPtr) { +void stopSave(void *listPtr) +{ + if (listPtr) + { SaveList *list = (SaveList *)listPtr; list->stop(); delete list; diff --git a/device_support/national/AsyncStoreManager.h b/device_support/national/AsyncStoreManager.h index 4322f62f3d..ef6357473f 100644 --- a/device_support/national/AsyncStoreManager.h +++ b/device_support/national/AsyncStoreManager.h @@ -15,7 +15,8 @@ using namespace MDSplus; using namespace std; -class SaveItem { +class SaveItem +{ private: void *buffer; @@ -44,10 +45,12 @@ class SaveItem { int numCoeffs; float *coeffs; - vector split(const char *str, char c = ' ') { + vector split(const char *str, char c = ' ') + { vector result; - do { + do + { const char *begin = str; while (*str != c && *str) @@ -59,8 +62,10 @@ class SaveItem { return result; } - void sendChannelSegmentPutEvent(TreeNode *dataNode) { - try { + void sendChannelSegmentPutEvent(TreeNode *dataNode) + { + try + { char *path; vector tokens; char event[256]; @@ -74,7 +79,9 @@ class SaveItem { sprintf(event, "%s_%s_CH%s", treeStr, tokens[0].data(), (tokens[1].substr(8)).data()); Event::setevent(event); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Send Event Error: %s\n", exc->what()); } } @@ -96,7 +103,8 @@ class SaveItem { void save(); }; -class SaveList { +class SaveList +{ public: pthread_cond_t itemAvailable; pthread_t thread; @@ -106,11 +114,13 @@ class SaveList { pthread_mutex_t mutex; private: - int getQueueLen() { + int getQueueLen() + { pthread_mutex_lock(&mutex); int len = 0; SaveItem *currItem = saveHead; - while (currItem) { + while (currItem) + { len++; currItem = currItem->getNext(); } diff --git a/device_support/national/NiFpga_FAU_cRIO_FPGA.h b/device_support/national/NiFpga_FAU_cRIO_FPGA.h index ca9811022c..0972ca15e9 100644 --- a/device_support/national/NiFpga_FAU_cRIO_FPGA.h +++ b/device_support/national/NiFpga_FAU_cRIO_FPGA.h @@ -19,7 +19,7 @@ * * static const char* const Bitfile = "C:\\" NiFpga_FAU_cRIO_FPGA_Bitfile; */ -#define NiFpga_FAU_cRIO_FPGA_Bitfile \ +#define NiFpga_FAU_cRIO_FPGA_Bitfile \ "/opt/mdsplus/device_support/national/NiFpga_FAU_cRIO_FPGA.lvbitx" /** @@ -28,7 +28,8 @@ static const char *const NiFpga_FAU_cRIO_FPGA_Signature = "5BAB1AB939BB25A7D9803AFFB15DDE16"; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_IndicatorBool_FifoOverflowed = 0x816E, NiFpga_FAU_cRIO_FPGA_IndicatorBool_Mod1DIO4 = 0x8146, NiFpga_FAU_cRIO_FPGA_IndicatorBool_Mod1DIO5 = 0x814A, @@ -37,22 +38,26 @@ typedef enum { NiFpga_FAU_cRIO_FPGA_IndicatorBool_ready = 0x813A, } NiFpga_FAU_cRIO_FPGA_IndicatorBool; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_IndicatorI16_FauVersion = 0x8112, } NiFpga_FAU_cRIO_FPGA_IndicatorI16; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_IndicatorU16_AcqState = 0x8172, NiFpga_FAU_cRIO_FPGA_IndicatorU16_acq_ctd = 0x812E, NiFpga_FAU_cRIO_FPGA_IndicatorU16_test_ctd = 0x8132, NiFpga_FAU_cRIO_FPGA_IndicatorU16_tick_ctd = 0x8136, } NiFpga_FAU_cRIO_FPGA_IndicatorU16; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_IndicatorU64_tick = 0x8168, } NiFpga_FAU_cRIO_FPGA_IndicatorU64; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_ControlBool_AcqEna = 0x8176, NiFpga_FAU_cRIO_FPGA_ControlBool_Ch64 = 0x8116, NiFpga_FAU_cRIO_FPGA_ControlBool_Mod5DIO4 = 0x8156, @@ -63,23 +68,27 @@ typedef enum { NiFpga_FAU_cRIO_FPGA_ControlBool_stop2 = 0x8166, } NiFpga_FAU_cRIO_FPGA_ControlBool; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_ControlU16_CountFreq = 0x813E, NiFpga_FAU_cRIO_FPGA_ControlU16_CountMode = 0x8142, } NiFpga_FAU_cRIO_FPGA_ControlU16; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_ControlU32_ContAcqPreiod = 0x8128, NiFpga_FAU_cRIO_FPGA_ControlU32_PTEcountFast = 0x8118, NiFpga_FAU_cRIO_FPGA_ControlU32_PTEcountSlow = 0x8120, } NiFpga_FAU_cRIO_FPGA_ControlU32; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_ControlU64_PTEEnaMask = 0x8124, NiFpga_FAU_cRIO_FPGA_ControlU64_PTEFastSlowMask = 0x811C, } NiFpga_FAU_cRIO_FPGA_ControlU64; -typedef enum { +typedef enum +{ NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64_AcquisitionFIFOR = 1, NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64_AcquisitionFIFORT = 0, } NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64; diff --git a/device_support/national/NiFpga_MainFPGA_9159.h b/device_support/national/NiFpga_MainFPGA_9159.h index 62ab46dd7c..b2b830a916 100644 --- a/device_support/national/NiFpga_MainFPGA_9159.h +++ b/device_support/national/NiFpga_MainFPGA_9159.h @@ -20,7 +20,7 @@ * static const char* const Bitfile = "C:\\" NiFpga_MainFPGA_9159_Bitfile; */ //#define NiFpga_MainFPGA_9159_Bitfile "NiFpga_MainFPGA_9159.lvbitx" -#define NiFpga_MainFPGA_9159_Bitfile \ +#define NiFpga_MainFPGA_9159_Bitfile \ "/opt/mdsplus/device_support/national/NiFpga_MainFPGA_9159.lvbitx" /** @@ -29,7 +29,8 @@ static const char *const NiFpga_MainFPGA_9159_Signature = "EAB8E96CABC7B0809FBBCB198A3D7DF1"; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorBool_DeepSW0 = 0x811E, NiFpga_MainFPGA_9159_IndicatorBool_DeepSW1 = 0x811A, NiFpga_MainFPGA_9159_IndicatorBool_DeepSW2 = 0x8116, @@ -40,18 +41,21 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorBool_Mod14DI4 = 0x8122, } NiFpga_MainFPGA_9159_IndicatorBool; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU8_SelectSet = 0x8112, NiFpga_MainFPGA_9159_IndicatorU8_SelectedSetMonitorAO = 0x813E, } NiFpga_MainFPGA_9159_IndicatorU8; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_A = 0x81C2, NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_B = 0x81B2, NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_C = 0x818A, } NiFpga_MainFPGA_9159_IndicatorI16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU16_PeriodToAOus = 0x8142, NiFpga_MainFPGA_9159_IndicatorU16_ToRT_Periodus_A = 0x81C6, NiFpga_MainFPGA_9159_IndicatorU16_ToRT_Periodus_B = 0x81B6, @@ -59,7 +63,8 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorU16_Ver = 0x8146, } NiFpga_MainFPGA_9159_IndicatorU16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorI32_Ciclo1 = 0x81E8, NiFpga_MainFPGA_9159_IndicatorI32_Ciclo2_A = 0x81CC, NiFpga_MainFPGA_9159_IndicatorI32_Ciclo2_B = 0x8194, @@ -78,7 +83,8 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorI32_RoundsToGetTrigger_C = 0x8180, } NiFpga_MainFPGA_9159_IndicatorI32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU32_Period2t_A = 0x81D0, NiFpga_MainFPGA_9159_IndicatorU32_Period2t_B = 0x8198, NiFpga_MainFPGA_9159_IndicatorU32_Period2t_C = 0x8170, @@ -93,11 +99,13 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorU32_Receaved2_C = 0x8190, } NiFpga_MainFPGA_9159_IndicatorU32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU64_ChannelLiving = 0x8138, } NiFpga_MainFPGA_9159_IndicatorU64; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlBool_ForceLocal = 0x816A, NiFpga_MainFPGA_9159_ControlBool_ResetReader_A = 0x81DE, NiFpga_MainFPGA_9159_ControlBool_ResetReader_B = 0x81A6, @@ -106,24 +114,28 @@ typedef enum { NiFpga_MainFPGA_9159_ControlBool_Stop = 0x81E6, } NiFpga_MainFPGA_9159_ControlBool; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlU16_FrameStrobePerioduSec = 0x81EE, NiFpga_MainFPGA_9159_ControlU16_HighPhaseFrameStrobeDurationTicks = 0x81F2, } NiFpga_MainFPGA_9159_ControlU16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_A = 0x8160, NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_B = 0x8154, NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_C = 0x814C, } NiFpga_MainFPGA_9159_IndicatorArrayI16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_A = 18, NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_B = 18, NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_C = 18, } NiFpga_MainFPGA_9159_IndicatorArrayI16Size; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A = 2, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_B = 1, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_C = 0, diff --git a/device_support/national/NiFpga_MainFPGA_9159Simulator.h b/device_support/national/NiFpga_MainFPGA_9159Simulator.h index 65be723275..3df66dd781 100644 --- a/device_support/national/NiFpga_MainFPGA_9159Simulator.h +++ b/device_support/national/NiFpga_MainFPGA_9159Simulator.h @@ -20,7 +20,7 @@ * static const char* const Bitfile = "C:\\" NiFpga_MainFPGA_9159_Bitfile; */ //#define NiFpga_MainFPGA_9159_Bitfile "NiFpga_MainFPGA_9159.lvbitx" -#define NiFpga_MainFPGA_9159_Bitfile \ +#define NiFpga_MainFPGA_9159_Bitfile \ "/opt/mdsplus/device_support/national/NiFpga_MainFPGA_9159Simulator.lvbitx" /** @@ -32,13 +32,15 @@ static const char *const NiFpga_MainFPGA_9159_Signature = "548F078B3618EB26C2F9C8C5D8B7A5CB"; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_A = 0x8196, NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_B = 0x8186, NiFpga_MainFPGA_9159_IndicatorI16_TransmittedNum_C = 0x815E, } NiFpga_MainFPGA_9159_IndicatorI16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU16_PeriodToAOus = 0x8116, NiFpga_MainFPGA_9159_IndicatorU16_ToRT_Periodus_A = 0x819A, NiFpga_MainFPGA_9159_IndicatorU16_ToRT_Periodus_B = 0x818A, @@ -46,7 +48,8 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorU16_Ver = 0x810E, } NiFpga_MainFPGA_9159_IndicatorU16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorI32_Ciclo1 = 0x81BC, NiFpga_MainFPGA_9159_IndicatorI32_Ciclo2_A = 0x81A0, NiFpga_MainFPGA_9159_IndicatorI32_Ciclo2_B = 0x8168, @@ -64,7 +67,8 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorI32_RoundsToGetTrigger_C = 0x8154, } NiFpga_MainFPGA_9159_IndicatorI32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorU32_Period2t_A = 0x81A4, NiFpga_MainFPGA_9159_IndicatorU32_Period2t_B = 0x816C, NiFpga_MainFPGA_9159_IndicatorU32_Period2t_C = 0x8144, @@ -79,7 +83,8 @@ typedef enum { NiFpga_MainFPGA_9159_IndicatorU32_Receaved2_C = 0x8164, } NiFpga_MainFPGA_9159_IndicatorU32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlBool_ForceLocal = 0x813E, NiFpga_MainFPGA_9159_ControlBool_ResetReader_A = 0x81B2, NiFpga_MainFPGA_9159_ControlBool_ResetReader_B = 0x817A, @@ -87,51 +92,61 @@ typedef enum { NiFpga_MainFPGA_9159_ControlBool_Stop = 0x81BA, } NiFpga_MainFPGA_9159_ControlBool; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlU16_FrameStrobePerioduSec = 0x81C2, NiFpga_MainFPGA_9159_ControlU16_HighPhaseFrameStrobeDurationTicks = 0x81C6, } NiFpga_MainFPGA_9159_ControlU16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayBool_outputarray = 0x8112, } NiFpga_MainFPGA_9159_IndicatorArrayBool; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayBoolSize_outputarray = 3, } NiFpga_MainFPGA_9159_IndicatorArrayBoolSize; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_A = 0x8134, NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_B = 0x8128, NiFpga_MainFPGA_9159_IndicatorArrayI16_AI_C = 0x8120, } NiFpga_MainFPGA_9159_IndicatorArrayI16; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_A = 18, NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_B = 18, NiFpga_MainFPGA_9159_IndicatorArrayI16Size_AI_C = 18, } NiFpga_MainFPGA_9159_IndicatorArrayI16Size; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlArrayI32_IndexArray = 0x811C, } NiFpga_MainFPGA_9159_ControlArrayI32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_ControlArrayI32Size_IndexArray = 16, } NiFpga_MainFPGA_9159_ControlArrayI32Size; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A = 2, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_B = 1, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_C = 0, } NiFpga_MainFPGA_9159_TargetToHostFifoI16; //=================================================================== -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159Simulator_ControlI32_SinSamp = 0x8118, } NiFpga_MainFPGA_9159Simulator_ControlI32; -typedef enum { +typedef enum +{ NiFpga_MainFPGA_9159Simulator_ControlSgl_frequency = 0x8110, } NiFpga_MainFPGA_9159Simulator_ControlSgl; diff --git a/device_support/national/NiInterface.cpp b/device_support/national/NiInterface.cpp index c00c456af3..f22e1360b9 100644 --- a/device_support/national/NiInterface.cpp +++ b/device_support/national/NiInterface.cpp @@ -93,7 +93,8 @@ extern "C" void setStopAcqFlag(void *stopAcq); extern "C" int PXIeTriggerRTSI1(int *devNums, int numChassis); -void pxi6259_create_ai_conf_ptr(void **confPtr) { +void pxi6259_create_ai_conf_ptr(void **confPtr) +{ pxi6259_ai_conf_t *conf = (pxi6259_ai_conf_t *)malloc(sizeof(pxi6259_ai_conf_t)); *conf = pxi6259_create_ai_conf(); @@ -104,7 +105,8 @@ void pxi6259_create_ai_conf_ptr(void **confPtr) { void pxi6259_free_ai_conf_ptr(void *conf) { free((char *)conf); } -void pxi6259_create_ao_conf_ptr(void **confPtr) { +void pxi6259_create_ao_conf_ptr(void **confPtr) +{ pxi6259_ao_conf_t *conf = (pxi6259_ao_conf_t *)malloc(sizeof(pxi6259_ao_conf_t)); *conf = pxi6259_create_ao_conf(); @@ -113,13 +115,15 @@ void pxi6259_create_ao_conf_ptr(void **confPtr) { void pxi6259_free_ao_conf_ptr(void *conf) { free((char *)conf); } -int _xseries_get_device_info(int fd, void *cardInfo) { +int _xseries_get_device_info(int fd, void *cardInfo) +{ xseries_device_info_t *data = (xseries_device_info_t *)cardInfo; // printf("file descriptor %d\n", fd); // printf("card info %x\n", cardInfo); - if (xseries_get_device_info(fd, data) < 0) { + if (xseries_get_device_info(fd, data) < 0) + { printf("Error %d %s\n", errno, strerror(errno)); return -1; } @@ -142,7 +146,8 @@ int getErrno() { return errno; } void xseries_create_ai_conf_ptr(void **confPtr, unsigned int pre_trig_smp, unsigned int post_trig_smp, - char multi_trigger) { + char multi_trigger) +{ xseries_ai_conf_t *conf = (xseries_ai_conf_t *)malloc(sizeof(xseries_ai_conf_t)); @@ -150,23 +155,32 @@ void xseries_create_ai_conf_ptr(void **confPtr, unsigned int pre_trig_smp, // *conf = xseries_software_timed_ai();int xseries_set_ai_conf_ptr(int fd, // void *conf_ptr) - if (post_trig_smp > 0) { - if (pre_trig_smp > 0) { + if (post_trig_smp > 0) + { + if (pre_trig_smp > 0) + { printf("PXI 6368 Ptretrigger analog input acquisition. pre %d post %d \n", pre_trig_smp, post_trig_smp); *conf = xseries_reference_ai(pre_trig_smp, post_trig_smp); - } else { - if (multi_trigger) { + } + else + { + if (multi_trigger) + { printf("PXI 6368 Retriggerable finite analog input acquisition. %d \n", post_trig_smp); *conf = xseries_retriggerable_finite_ai(post_trig_smp); - } else { + } + else + { printf("PXI 6368 Finite analog input acquisition. %d \n", post_trig_smp); *conf = xseries_finite_ai(post_trig_smp); } } - } else { + } + else + { printf("Continuous analog input acquisition.\n"); *conf = xseries_continuous_ai(); } @@ -174,14 +188,16 @@ void xseries_create_ai_conf_ptr(void **confPtr, unsigned int pre_trig_smp, *confPtr = (void *)conf; } -int xseries_set_ai_conf_ptr(int fd, void *conf_ptr) { +int xseries_set_ai_conf_ptr(int fd, void *conf_ptr) +{ int retval; xseries_ai_conf_t conf; memcpy(&conf, conf_ptr, sizeof(xseries_ai_conf_t)); retval = xseries_load_ai_conf(fd, *(xseries_ai_conf_t *)conf_ptr); - if (retval) { + if (retval) + { printf("PXI 6368 Cannot load AI configuration! %s (%d)\n", strerror(errno), errno); return -1; @@ -195,20 +211,28 @@ int xseries_set_ai_conf_ptr(int fd, void *conf_ptr) { void xseries_free_ai_conf_ptr(void *conf) { free((char *)conf); } -void openTree(char *name, int shot, void **treePtr) { - try { +void openTree(char *name, int shot, void **treePtr) +{ + try + { Tree *tree = new Tree(name, shot); *treePtr = (void *)tree; TreeNode *n = tree->getNode("\\TOP"); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Cannot open tree %s %d: %s\n", name, shot, exc->what()); } } -void closeTree(void *treePtr) { - try { +void closeTree(void *treePtr) +{ + try + { delete ((Tree *)treePtr); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Cannot close tree %s %d: %s\n", exc->what()); } } @@ -710,7 +734,8 @@ extern "C" void stopSave(void *listPtr) **********************************************************************************************************************************************/ #define MAX_ITERATIONS 100000 -void readAiConfiguration(int fd) { +void readAiConfiguration(int fd) +{ int status; pxi6259_ai_conf_t conf; @@ -733,7 +758,8 @@ void readAiConfiguration(int fd) { extern "C" int pxi6259_getCalibrationParams(int chanfd, int range, float *coeff, int *coeff_num); int pxi6259_getCalibrationParams(int chanfd, int range, float *coeffVal, - int *coeff_num) { + int *coeff_num) +{ ai_scaling_coefficients_t ai_coefs; int32_t i, j; int retval; @@ -779,21 +805,24 @@ int pxi6259_getCalibrationParams(int chanfd, int range, float *coeffVal, /* Gain divider lookup table */ static float gain_divider[] = { - 1.0, 1.0, 2.0, 5.0, 10.0, + 1.0, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0}; // 1: 10V, 2 :5V, 3: 2V, 4:1V, 5, 500mv, 6, 200mv, 7 // :100mv void pxi6259_ai_polynomial_scaler(int16_t *raw, float *scaled, uint32_t num_samples, float *coeff, int order, - int gain) { + int gain) +{ int32_t i, j; float rawf; - for (i = 0; i < num_samples; i++) { + for (i = 0; i < num_samples; i++) + { rawf = (float)raw[i]; scaled[i] = coeff[order]; - for (j = order - 1; j >= 0; j--) { + for (j = order - 1; j >= 0; j--) + { scaled[i] *= rawf; scaled[i] += coeff[j]; } @@ -804,7 +833,8 @@ void pxi6259_ai_polynomial_scaler(int16_t *raw, float *scaled, #define XSERIES_MAX_BUFSIZE 100000 extern "C" int getCalibrationParams(int chanfd, int range, float *coeff); -void getStopAcqFlag(void **stopAcq) { +void getStopAcqFlag(void **stopAcq) +{ *stopAcq = (void *)malloc(sizeof(int)); (*(int *)(*stopAcq)) = 0; printf("getStopAcqFlag pointer = %p = %d\n", *stopAcq, (*(int *)stopAcq)); @@ -812,7 +842,8 @@ void getStopAcqFlag(void **stopAcq) { void freeStopAcqFlag(void *stopAcq) { free((char *)stopAcq); } -void setStopAcqFlag(void *stopAcq) { +void setStopAcqFlag(void *stopAcq) +{ // printf("Before setStopAcqFlag pointer = %p = %d\n", stopAcq, // *((int*)stopAcq) ); //(*(int*)stopAcq) = 1; @@ -828,7 +859,8 @@ void setStopAcqFlag(void *stopAcq) { */ int xseries_AI_scale(int16_t *raw, float *scaled, uint32_t num_samples, - float *coeff) { + float *coeff) +{ int32_t i, j; float rawf; /* @@ -836,10 +868,12 @@ int xseries_AI_scale(int16_t *raw, float *scaled, uint32_t num_samples, printf("Coeff[%d] : %e\n", j, coeff[j] ); */ - for (i = 0; i < num_samples; i++) { + for (i = 0; i < num_samples; i++) + { scaled[i] = 0.0; rawf = (double)raw[i]; - for (j = NUM_AI_SCALING_COEFFICIENTS - 1; j >= 0; j--) { + for (j = NUM_AI_SCALING_COEFFICIENTS - 1; j >= 0; j--) + { scaled[i] *= rawf; scaled[i] += coeff[j]; } @@ -866,7 +900,8 @@ inline static void ai_scale(int16_t *raw, float *scaled, } */ -int getCalibrationParams(int chanfd, int range, float *coeffVal) { +int getCalibrationParams(int chanfd, int range, float *coeffVal) +{ xseries_ai_scaling_coef_t ai_coefs; int32_t i, j; int retval; @@ -883,15 +918,18 @@ int getCalibrationParams(int chanfd, int range, float *coeffVal) { */ retval = ioctl(chanfd, XSERIES_IOC_GET_AI_SCALING_COEF, &ai_coefs); - if (retval) { + if (retval) + { printf("Get ai scaling error %s\n", strerror(errno)); return retval; } - for (i = 0; i < NUM_AI_SCALING_COEFFICIENTS; ++i) { + for (i = 0; i < NUM_AI_SCALING_COEFFICIENTS; ++i) + { coeffVal[i] = ai_coefs.cal_info.modes[0].coefficients[i].f * ai_coefs.cal_info.intervals[range].gain.f; - if (i == 0) { + if (i == 0) + { coeffVal[i] += ai_coefs.cal_info.intervals[range].offset.f; } } @@ -910,7 +948,8 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, void *coeffsNidPtr, int clockNid, float timeIdx0, float period, void *treePtr, void *saveListPtr, void *stopAcq, int shot, - void *resampledNidPtr) { + void *resampledNidPtr) +{ char saveConv = 0; // Acquisition format flags 0 raw data 1 convrted dta int skipping = 0; // Number of samples to not save when start time is > 0 @@ -920,7 +959,7 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, int chan; int currReadSamples; // Number of samples read SaveList *saveList = (SaveList *) - saveListPtr; // Class to equeu data buffer to save in pulse file + saveListPtr; // Class to equeu data buffer to save in pulse file int *chanFd = (int *)chanFdPtr; // Channe file descriptor int *dataNid = (int *)dataNidPtr; // Channel node identifier float *gains = (float *)gainsPtr; @@ -929,10 +968,10 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, int readCalls[nChan]; // For statistic number of read operation pe channel unsigned short * - buffers_s[nChan]; // Raw data buffer used when not converted data are read - float *buffers_f[nChan]; // Converted data buffer uesed when converted dta are - // read - int readChanSmp[nChan]; // Numebr of samples to read from each channel + buffers_s[nChan]; // Raw data buffer used when not converted data are read + float *buffers_f[nChan]; // Converted data buffer uesed when converted dta are + // read + int readChanSmp[nChan]; // Numebr of samples to read from each channel int bufReadChanSmp[nChan]; // Number of sample read in the buffer for each // channel float streamGains[nChan]; @@ -967,7 +1006,8 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, (*(int *)stopAcq) = 0; // Allocate buffer for each channels - for (chan = 0; chan < nChan; chan++) { + for (chan = 0; chan < nChan; chan++) + { if (saveConv) buffers_f[chan] = new float[bufSize]; else @@ -975,24 +1015,33 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, // Check if resampling TreeNode *dataNode = new TreeNode(dataNid[chan], (Tree *)treePtr); - try { + try + { Data *streamNameData = dataNode->getExtendedAttribute("STREAM_NAME"); streamNames[chan] = streamNameData->getString(); deleteData(streamNameData); - try { + try + { Data *streamGainData = dataNode->getExtendedAttribute("STREAM_GAIN"); streamGains[chan] = streamGainData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamGains[chan] = 1; } - try { + try + { Data *streamOffsetData = dataNode->getExtendedAttribute("STREAM_OFFSET"); streamOffsets[chan] = streamOffsetData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamOffsets[chan] = 0; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamNames[chan] = NULL; streamGains[chan] = 0; streamOffsets[chan] = 0; @@ -1005,14 +1054,18 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, float *coeffs[nChan]; int numCoeffs[nChan]; printf("prima TreeNode %p\n", treePtr); - for (int chanIdx = 0; chanIdx < nChan; chanIdx++) { - try { + for (int chanIdx = 0; chanIdx < nChan; chanIdx++) + { + try + { TreeNode *rangeNode = new TreeNode(coeffsNid[chanIdx], (MDSplus::Tree *)treePtr); Data *rangeData = rangeNode->getData(); coeffs[chanIdx] = rangeData->getFloatArray(&numCoeffs[chanIdx]); deleteData(rangeData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("%s\n", exc.what()); } } @@ -1022,14 +1075,16 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, xseries_start_ai(aiFd); // Start main acquisition loop - while (!(*(int *)stopAcq)) { + while (!(*(int *)stopAcq)) + { int testCount = 0; // Check if there are samples to skip common for each channel. // sampleToSkip is an argument of the function. // ATTENTION : to check with external trigger - if (!skipping && sampleToSkip > 0) { + if (!skipping && sampleToSkip > 0) + { printf("PXI 6368 Skipping data %d Nun samples %d\n", sampleToSkip, numSamples); skipping = numSamples; // save in skipping flag the number of sample to be @@ -1044,10 +1099,12 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, chan = 0; channelRead = 0; // Acquisition loop on each channel of numSamples values - while (channelRead != nChan) { + while (channelRead != nChan) + { // Check if for the current channel has been acquired all sample // and stop acquisition has not beeen asserted - if (readChanSmp[chan] == numSamples || (*(int *)stopAcq)) { + if (readChanSmp[chan] == numSamples || (*(int *)stopAcq)) + { if (transientRec) printf( "Complete acquisition for channel %d samples %d stop flag %d \n", @@ -1087,12 +1144,17 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, // currDataToRead - bufReadChanSmp[chan], currReadSamples >> 1); // Check if no data is available - if (currReadSamples <= 0) { + if (currReadSamples <= 0) + { currReadSamples = 0; - if (errno == EAGAIN || errno == ENODATA) { + if (errno == EAGAIN || errno == ENODATA) + { currReadSamples = 0; // No data currently available... Try again - } else { - if (errno == EOVERFLOW) { + } + else + { + if (errno == EOVERFLOW) + { printf("PXI 6368 Error reading samples on ai%d: (%d) %s \n", chan, errno, strerror(errno)); for (chan = 0; chan < nChan; chan++) @@ -1106,7 +1168,8 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, } // If sample are read the module has been triggered - if (!triggered && currReadSamples > 0) { + if (!triggered && currReadSamples > 0) + { triggered = 1; printf("6368 TRIGGER!!!\n"); } @@ -1123,7 +1186,8 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, bufReadChanSmp[chan] , currDataToRead); */ // Enqueue data to store in the pulse file - if (bufReadChanSmp[chan] == currDataToRead) { + if (bufReadChanSmp[chan] == currDataToRead) + { // Check if have been read more than required samples if (readChanSmp[chan] + bufReadChanSmp[chan] > numSamples) bufReadChanSmp[chan] = numSamples - readChanSmp[chan]; @@ -1137,11 +1201,13 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, readChanSmp[%d] = %d sampleToRead = %d\n", chan, bufReadChanSmp[chan], chan, readChanSmp[chan], chan, readChanSmp[chan], sampleToRead ); */ - if (!skipping) { + if (!skipping) + { int streamFactor = (int)(0.1 / period); if (bufSize > streamFactor) streamFactor = bufSize; - else { + else + { if (streamFactor % bufSize != 0) streamFactor = (bufSize + 1) * (streamFactor / bufSize); } @@ -1191,7 +1257,8 @@ int xseriesReadAndSaveAllChannels(int aiFd, int nChan, void *chanFdPtr, } // End Segment acquisition loop for each channel // Reset variables for skiping samples - if (!(*(int *)stopAcq) && skipping) { + if (!(*(int *)stopAcq) && skipping) + { // printf("Data to saved %d\n", readChanSmp[0]); memset(readChanSmp, 0, sizeof(int) * nChan); @@ -1229,7 +1296,8 @@ int pxi6259_readAndSaveAllChannels( int nChan, void *chanFdPtr, int bufSize, int segmentSize, int sampleToSkip, int numSamples, void *dataNidPtr, void *gainsPtr, void *coeffsNidPtr, int clockNid, float timeIdx0, float period, void *treePtr, - void *saveListPtr, void *stopAcq, int shot, void *resampledNidPtr) { + void *saveListPtr, void *stopAcq, int shot, void *resampledNidPtr) +{ char saveConv = 0; // Acquisition format flags 0 raw data 1 convrted dta int skipping = 0; @@ -1270,40 +1338,54 @@ int pxi6259_readAndSaveAllChannels( memset(readChanSmp, 0, sizeof(int) * nChan); // Delete first all data nids - for (int i = 0; i < nChan; i++) { - try { + for (int i = 0; i < nChan; i++) + { + try + { TreeNode *currNode = new TreeNode(dataNid[i], (Tree *)treePtr); currNode->deleteData(); // Check if resampling - try { + try + { Data *streamNameData = currNode->getExtendedAttribute("STREAM_NAME"); streamNames[i] = streamNameData->getString(); deleteData(streamNameData); - try { + try + { Data *streamGainData = currNode->getExtendedAttribute("STREAM_GAIN"); streamGains[i] = streamGainData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamGains[i] = 1; } - try { + try + { Data *streamOffsetData = currNode->getExtendedAttribute("STREAM_OFFSET"); streamOffsets[i] = streamOffsetData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamOffsets[i] = 0; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamNames[i] = NULL; streamGains[i] = 0; streamOffsets[i] = 0; } delete currNode; - if (resampledNid) { + if (resampledNid) + { currNode = new TreeNode(resampledNid[i], (Tree *)treePtr); currNode->deleteData(); delete currNode; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Error deleting data nodes\n"); } } @@ -1326,7 +1408,8 @@ int pxi6259_readAndSaveAllChannels( // Read calibration coeffs float *coeffs[nChan]; int numCoeffs[nChan]; - for (int chanIdx = 0; chanIdx < nChan; chanIdx++) { + for (int chanIdx = 0; chanIdx < nChan; chanIdx++) + { TreeNode *rangeNode = new TreeNode(coeffsNid[chanIdx], (MDSplus::Tree *)treePtr); Data *rangeData = rangeNode->getData(); @@ -1336,11 +1419,13 @@ int pxi6259_readAndSaveAllChannels( ////////////////// - while (!(*(int *)stopAcq)) { + while (!(*(int *)stopAcq)) + { // printf("stopAcq %d\n", *(int *)stopAcq ); - if (!skipping && sampleToSkip > 0) { + if (!skipping && sampleToSkip > 0) + { printf("PXI 6259 Skipping data %d Nun samples %d\n", sampleToSkip, numSamples); skipping = numSamples; @@ -1351,8 +1436,10 @@ int pxi6259_readAndSaveAllChannels( chan = 0; channelRead = 0; - while (channelRead != nChan) { - if (readChanSmp[chan] == numSamples || (*(int *)stopAcq)) { + while (channelRead != nChan) + { + if (readChanSmp[chan] == numSamples || (*(int *)stopAcq)) + { channelRead++; chan = (chan + 1) % nChan; continue; @@ -1378,14 +1465,19 @@ int pxi6259_readAndSaveAllChannels( // data %d \n",chan, bufReadChanSmp[chan] , currDataToRead, currDataToRead // - bufReadChanSmp[chan], currReadSamples >> 1); - if (currReadSamples <= 0) { + if (currReadSamples <= 0) + { currReadSamples = 0; - if (errno == EAGAIN || errno == ENODATA) { + if (errno == EAGAIN || errno == ENODATA) + { // usleep(50); currReadSamples = 0; // No data currently available... Try again // continue; - } else { - if (errno == EOVERFLOW) { + } + else + { + if (errno == EOVERFLOW) + { printf("PXI 6259 Error reading samples on ai%d: (%d) %s \n", chan, errno, strerror(errno)); @@ -1400,20 +1492,25 @@ int pxi6259_readAndSaveAllChannels( } } - if (!triggered && currReadSamples > 0) { + if (!triggered && currReadSamples > 0) + { triggered = 1; printf("6259 TRIGGER!!!\n"); } - if (saveConv) { + if (saveConv) + { // readChanSmp[chan] += currReadSamples; bufReadChanSmp[chan] += currReadSamples; - } else { + } + else + { // readChanSmp[chan] += ( currReadSamples >> 1 ); bufReadChanSmp[chan] += (currReadSamples >> 1); } - if (bufReadChanSmp[chan] == currDataToRead) { + if (bufReadChanSmp[chan] == currDataToRead) + { /* if ( counters[chan] + bufReadChanSmp[chan] > numSamples ) bufReadChanSmp[chan] = numSamples - counters[chan]; sampleToRead = @@ -1427,12 +1524,14 @@ int pxi6259_readAndSaveAllChannels( // = %d sampleToRead = %d\n", chan, bufReadChanSmp[chan], chan, // readChanSmp[chan], chan, readChanSmp[chan], sampleToRead ); - if (!skipping) { + if (!skipping) + { int streamFactor = (int)(0.1 / period); if (bufSize > streamFactor) streamFactor = bufSize; - else { + else + { if (streamFactor % bufSize != 0) streamFactor = (bufSize + 1) * (streamFactor / bufSize); } @@ -1480,7 +1579,8 @@ int pxi6259_readAndSaveAllChannels( */ } - if (!(*(int *)stopAcq) && skipping) { + if (!(*(int *)stopAcq) && skipping) + { // printf("Data to saved %d\n", readChanSmp[0]); // memset(counters, 0, sizeof(int) * nChan); memset(readChanSmp, 0, sizeof(int) * nChan); @@ -1552,7 +1652,8 @@ extern "C" int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, #define DEVICE_FILE "/dev/pxi6259" int configureDigital(int *chanDigitFD, uint32_t deviceNum, - uint32_t outChanOnOff) { + uint32_t outChanOnOff) +{ pxi6259_dio_conf_t dioConfig; char filename[256]; int devFD; @@ -1562,7 +1663,8 @@ int configureDigital(int *chanDigitFD, uint32_t deviceNum, // open DIO file descriptor sprintf(filename, "%s.%u.dio", DEVICE_FILE, deviceNum); devFD = open(filename, O_RDWR); - if (devFD < 0) { + if (devFD < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -1571,20 +1673,23 @@ int configureDigital(int *chanDigitFD, uint32_t deviceNum, dioConfig = pxi6259_create_dio_conf(); // configure DIO P0.0 ports - if (pxi6259_add_dio_channel(&dioConfig, DIO_PORT0, port0Mask)) { + if (pxi6259_add_dio_channel(&dioConfig, DIO_PORT0, port0Mask)) + { fprintf(stderr, "Failed to configure DIO port 0!\n"); return -1; } // load DIO configuration and let it apply - if (pxi6259_load_dio_conf(devFD, &dioConfig)) { + if (pxi6259_load_dio_conf(devFD, &dioConfig)) + { fprintf(stderr, "Loading DIO configuration failed!\n"); return -1; } sprintf(filename, "%s.%u.dio.%u", DEVICE_FILE, deviceNum, 0); *chanDigitFD = open(filename, O_RDWR | O_NONBLOCK); - if (*chanDigitFD < 0) { + if (*chanDigitFD < 0) + { fprintf(stderr, "Failed to open port: %s\n", strerror(errno)); return -1; } @@ -1593,7 +1698,8 @@ int configureDigital(int *chanDigitFD, uint32_t deviceNum, } int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, - uint32_t outChanOnOff) { + uint32_t outChanOnOff) +{ char filename[256]; int i; pxi6259_ao_conf_t aoConfig; @@ -1602,7 +1708,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // open AO file descriptor sprintf(filename, "%s.%u.ao", DEVICE_FILE, deviceNum); devFD = open(filename, O_RDWR); - if (devFD < 0) { + if (devFD < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -1611,7 +1718,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // aoConfig = pxi6259_create_ao_conf(); // configure AO channel reference - if (pxi6259_add_ao_channel(&aoConfig, outChanRef, AO_DAC_POLARITY_BIPOLAR)) { + if (pxi6259_add_ao_channel(&aoConfig, outChanRef, AO_DAC_POLARITY_BIPOLAR)) + { fprintf(stderr, "Failed to configure channel %d reference! %s\n", outChanRef, strerror(errno)); return -1; @@ -1619,7 +1727,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // configure AO channel on/off if (pxi6259_add_ao_channel(&aoConfig, outChanOnOff, - AO_DAC_POLARITY_BIPOLAR)) { + AO_DAC_POLARITY_BIPOLAR)) + { fprintf(stderr, "Failed to configure channel %d reference! : %s\n", outChanOnOff, strerror(errno)); return -1; @@ -1627,20 +1736,23 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // enable signal generation if (pxi6259_set_ao_attribute(&aoConfig, AO_SIGNAL_GENERATION, - AO_SIGNAL_GENERATION_STATIC)) { + AO_SIGNAL_GENERATION_STATIC)) + { fprintf(stderr, "Failed to enable generating static signal!: %s\n", strerror(errno)); return -1; } // set continuous mode - if (pxi6259_set_ao_attribute(&aoConfig, AO_CONTINUOUS, 0)) { + if (pxi6259_set_ao_attribute(&aoConfig, AO_CONTINUOUS, 0)) + { fprintf(stderr, "Failed to set continuous mode!: %s\n", strerror(errno)); return -1; } // load AO configuration and let it apply - if (pxi6259_load_ao_conf(devFD, &aoConfig)) { + if (pxi6259_load_ao_conf(devFD, &aoConfig)) + { fprintf(stderr, "Failed to load output configuration! : %s\n", strerror(errno)); return -1; @@ -1649,7 +1761,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // open file descriptor for each AO channel sprintf(filename, "%s.%u.ao.%u", DEVICE_FILE, deviceNum, outChanRef); chanOutFD[0] = open(filename, O_RDWR | O_NONBLOCK); - if (*chanOutFD < 0) { + if (*chanOutFD < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", outChanRef, strerror(errno)); return -1; @@ -1657,14 +1770,16 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, sprintf(filename, "%s.%u.ao.%u", DEVICE_FILE, deviceNum, outChanOnOff); chanOutFD[1] = open(filename, O_RDWR | O_NONBLOCK); - if (*chanOutFD < 0) { + if (*chanOutFD < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", outChanOnOff, strerror(errno)); return -1; } // start AO segment (signal generation) - if (pxi6259_start_ao(devFD)) { + if (pxi6259_start_ao(devFD)) + { fprintf(stderr, "Failed to start segment!n"); return -1; } @@ -1673,8 +1788,9 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, } int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], - double frequency, int numChan) { - int diffMapChannel[17] = {-1, 0, 1, 2, 3, 4, 5, 6, 7, + double frequency, int numChan) +{ + int diffMapChannel[17] = {-1, 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23}; char filename[256]; int i; @@ -1685,7 +1801,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], // open AI file descriptor sprintf(filename, "%s.%u.ai", DEVICE_FILE, deviceNum); devFD = open(filename, O_RDWR); - if (devFD < 0) { + if (devFD < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -1694,7 +1811,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], aiConfig = pxi6259_create_ai_conf(); // configure AI channels 0 - 5 V differential - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { if (pxi6259_add_ai_channel(&aiConfig, diffMapChannel[inChan[i]], AI_POLARITY_BIPOLAR, 2, @@ -1717,25 +1835,29 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], period = (int)(20000000. / frequency); if (pxi6259_set_ai_sample_clk( &aiConfig, period, 3, AI_SAMPLE_SELECT_SI_TC, - AI_SAMPLE_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)) { + AI_SAMPLE_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)) + { fprintf(stderr, "Failed to configure AI sampling clock!\n"); return -1; } // load AI configuration and let it apply - if (pxi6259_load_ai_conf(devFD, &aiConfig)) { + if (pxi6259_load_ai_conf(devFD, &aiConfig)) + { fprintf(stderr, "Failed to load input configuration! %s\n", strerror(errno)); return -1; } // open file descriptor for each AI channel - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { sprintf(filename, "%s.%u.ai.%u", DEVICE_FILE, deviceNum, diffMapChannel[inChan[i]]); // printf("%s\n", filename); chanInFd[i] = open(filename, O_RDWR | O_NONBLOCK); - if (chanInFd[i] < 0) { + if (chanInFd[i] < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", inChan[i], strerror(errno)); return -1; @@ -1743,7 +1865,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], } // start AI segment (data acquisition) - if (pxi6259_start_ai(devFD)) { + if (pxi6259_start_ai(devFD)) + { fprintf(stderr, "Failed to start data acquisition!\n"); return -1; } @@ -1753,34 +1876,41 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], return devFD; } -int temperatureCtrlCommand(char *cmd) { +int temperatureCtrlCommand(char *cmd) +{ sem_t *semPause_id; sem_t *semWake_id; int wakeState; int i; semPause_id = sem_open("PauseControl", O_CREAT, 0666, 0); - if (semPause_id == SEM_FAILED) { + if (semPause_id == SEM_FAILED) + { perror("child sem_open"); return -1; } semWake_id = sem_open("WakeControl", O_CREAT, 0666, 0); - if (semWake_id == SEM_FAILED) { + if (semWake_id == SEM_FAILED) + { perror("child sem_open"); return -1; } - if (strcmp(cmd, "stop") == 0) { + if (strcmp(cmd, "stop") == 0) + { printf("============= STOP Warmer =====================\n"); - if (sem_getvalue(semWake_id, &wakeState) < 0) { + if (sem_getvalue(semWake_id, &wakeState) < 0) + { perror("Control sem_getvalue"); return -1; } // printf("STOP wake state %d\n", wakeState); - for (i = 0; i < wakeState; i++) { - if (sem_wait(semWake_id) < 0) { + for (i = 0; i < wakeState; i++) + { + if (sem_wait(semWake_id) < 0) + { perror("sem_wait WakeControl"); return -1; } @@ -1794,31 +1924,38 @@ int temperatureCtrlCommand(char *cmd) { } } - if (strcmp(cmd, "start") == 0 || strcmp(cmd, "exit") == 0) { + if (strcmp(cmd, "start") == 0 || strcmp(cmd, "exit") == 0) + { if (strcmp(cmd, "start") == 0) printf("============= START Warmer ====================\n"); - if (sem_getvalue(semWake_id, &wakeState) < 0) { + if (sem_getvalue(semWake_id, &wakeState) < 0) + { perror("Control sem_getvalue"); return -1; } // printf("START wake state %d\n", wakeState); - if (wakeState == 0) { + if (wakeState == 0) + { // printf("START pause state %d\n", wakeState); - if (sem_post(semPause_id) < 0) { + if (sem_post(semPause_id) < 0) + { perror("sem_post PauseControl"); return -1; } - if (sem_post(semWake_id) < 0) { + if (sem_post(semWake_id) < 0) + { perror("sem_post WakeControl"); return -1; } } - if (strcmp(cmd, "exit") == 0) { + if (strcmp(cmd, "exit") == 0) + { printf("============= EXIT Warmer Control =============\n"); - if (sem_post(semWake_id) < 0) { + if (sem_post(semWake_id) < 0) + { perror("sem_post WakeControl"); return -1; } @@ -1835,7 +1972,8 @@ int temperatureCtrlCommand(char *cmd) { return 0; } -double calibTCN(double val) { +double calibTCN(double val) +{ double out; double K = 47.513 * 1.e-3 / 5.; @@ -1872,7 +2010,8 @@ double calibTCN(double val) { int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, int aiFdChanIdx, double frequency, int aochan, - int dochan, double tempRef) { + int dochan, double tempRef) +{ static char log[5] = "|/-\\"; static int count = 0; @@ -1911,7 +2050,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, float E; bool enableTcCheck = true; - if (aiFdChanIdx < 0) { + if (aiFdChanIdx < 0) + { aiFdChanIdx = -aiFdChanIdx; enableTcCheck = false; printf("Disable check on TC1 TC2 temperature difference\n"); @@ -1919,7 +2059,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, printf("BoardID %d\n", boardID); printf("numChan %d\n", numChan); - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { printf("chan %d = %d\n", i, inChan[i]); } printf("numChan %d\n", numChan); @@ -1948,18 +2089,21 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, sem_t *wakeSem_id; pauseSem_id = sem_open("PauseControl", O_CREAT, 0666, 0); - if (pauseSem_id == SEM_FAILED) { + if (pauseSem_id == SEM_FAILED) + { perror("pause Control sem_open"); return -1; } wakeSem_id = sem_open("WakeControl", O_CREAT, 0666, 1); - if (pauseSem_id == SEM_FAILED) { + if (pauseSem_id == SEM_FAILED) + { perror("wake Control sem_open"); return -1; } - try { + try + { time_t rawtime; struct tm *timeinfo; char strShot[256]; @@ -1980,16 +2124,20 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, // strShot, dataFile); FILE *fd = fopen(dataFile, "r"); - if (!fd) { + if (!fd) + { t = new Tree((char *)"ipp_tc_trend", -1); t->createPulse(shot); - } else { + } + else + { fclose(fd); } t = new Tree((char *)"ipp_tc_trend", shot); - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { char path[256]; sprintf(path, "\\IPP_TC_TREND::TC%d", inChan[i]); printf("NODO %s \n", path); @@ -1998,17 +2146,21 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, errorNode = t->getNode((char *)"\\IPP_TC_TREND::ERROR"); vRefNode = t->getNode((char *)"\\IPP_TC_TREND::VREF"); - - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("%s\n", exc->what()); return -1; } - while (!error) { + while (!error) + { - if (!wakeState) { + if (!wakeState) + { printf("WAIT\n"); - if (sem_wait(pauseSem_id) < 0) { + if (sem_wait(pauseSem_id) < 0) + { perror("Control sem_wait"); return -1; } @@ -2016,19 +2168,22 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, } if ((devInFD = configureInput(chanInFD, deviceNum, inChan, frequency, - numChan)) < 0) { + numChan)) < 0) + { fprintf(stderr, "Error configure input channel!\n"); return -1; } if ((devOutFD = configureOutput(chanOutFD, deviceNum, outChanRef, - outChanOnOff)) < 0) { + outChanOnOff)) < 0) + { fprintf(stderr, "Error configure ouput channel!\n"); return -1; } if ((devDigitFD = configureDigital(&chanDigitFD, deviceNum, outChanOnOff)) < - 0) { + 0) + { fprintf(stderr, "Error configure digital channel!\n"); return -1; } @@ -2036,7 +2191,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, printf("START controll\n"); // Control tc - while (wakeState) { + while (wakeState) + { int n = 0; int i = 0; int nChRead; @@ -2051,7 +2207,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, ON/OFF: %u\n", outChanOnOff); error = 1; goto out; } */ - if (write(chanDigitFD, &ON, 4) != 4) { + if (write(chanDigitFD, &ON, 4) != 4) + { fprintf(stderr, "Error writing ON to port 0! Error: %s\n", strerror(errno)); error = 1; @@ -2060,19 +2217,24 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, memset(scans_read, 0, sizeof(scans_read)); nChRead = 0; - while (nChRead < numChan) { - if (scans_read[i] <= 0) { + while (nChRead < numChan) + { + if (scans_read[i] <= 0) + { // printf("read channel %d n chan %d \n", i, nChRead); scans_read[i] = pxi6259_read_ai(chanInFD[i], &value[i], 1); - if (scans_read[i] < 0) { - if (errno != EAGAIN) { + if (scans_read[i] < 0) + { + if (errno != EAGAIN) + { fprintf(stderr, "Failed while reading channel: %u: %s %d\n", inChan[i], strerror(errno), errno); error = 1; goto out; } - } else + } + else nChRead++; } i = (i + 1) % numChan; @@ -2083,14 +2245,17 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, tempVal = (float)calibTCN((double)value[aiFdChanIdx]); // printf("Temp %f V %f C \n", value[aiFdChanIdx] , tempVal); E = setPointT - tempVal; - if (E >= 0) { + if (E >= 0) + { vRef = 0.2 * E; if (vRef > 3.0) vRef = 3.0; - } else + } + else vRef = 0.0; - if (fabs(value[0] - value[1]) > 30. && enableTcCheck) { + if (fabs(value[0] - value[1]) > 30. && enableTcCheck) + { fprintf(stderr, "Difference between TC1 and TC2 > than 30 C reset " "reference signal \n"); vRef = 0.0; @@ -2102,7 +2267,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, // End control algoritm rc = pxi6259_write_ao(chanOutFD[0], &vRef, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel reference: %u\n", outChanRef); error = 1; @@ -2111,11 +2277,13 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, struct timeb tb; int64_t currTime; - try { + try + { ftime(&tb); Float32 *currData; currTime = (int64_t)(tb.time * 1000 + tb.millitm); - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { currData = new Float32(value[i]); node[i]->putRow(currData, &currTime); } @@ -2125,13 +2293,16 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, currData = new Float32(vRef); vRefNode->putRow(currData, &currTime); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("%s\n", exc->what()); error = 1; goto out; } - if (sem_getvalue(wakeSem_id, &wakeState) < 0 || wakeState == 2) { + if (sem_getvalue(wakeSem_id, &wakeState) < 0 || wakeState == 2) + { if (wakeState != 2) perror("Control sem_open"); error = 1; @@ -2153,7 +2324,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, out: rc = pxi6259_write_ao(chanOutFD[0], &ZERO_VOLT, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel reference: %u\n", outChanRef); error = 1; @@ -2166,7 +2338,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, %u\n", outChanOnOff); error = 1; goto out; } */ - if (write(chanDigitFD, &OFF, 4) != 4) { + if (write(chanDigitFD, &OFF, 4) != 4) + { fprintf(stderr, "Error writing OFF to port 0! Error: %s\n", strerror(errno)); error = 1; @@ -2176,7 +2349,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, printf("Close open ADC fd\n"); // stop AI segment - if (pxi6259_stop_ai(devInFD)) { + if (pxi6259_stop_ai(devInFD)) + { fprintf(stderr, "Failed to stop data acquisition!\n"); } @@ -2187,7 +2361,8 @@ int temperatureProbeControl(uint32_t boardID, uint32_t *inChan, int numChan, close(devInFD); // stop AO segment - if (pxi6259_stop_ao(devOutFD)) { + if (pxi6259_stop_ao(devOutFD)) + { fprintf(stderr, "Failed to stop generating signal!\n"); } @@ -2212,7 +2387,8 @@ This function is implemented in PXI 6259 device. One module of device must de configure with TRIGGER_MODE in SW_RTSI1 the other modules im EXTERNAL_RSTI. ***************************************************************************************/ -int PXIeTriggerRTSI1(int *devNums, int numChassis) { +int PXIeTriggerRTSI1(int *devNums, int numChassis) +{ pxi6259_dio_conf_t dioConfig[10]; pxi6259_dio_conf_t dioConfig1; @@ -2227,11 +2403,13 @@ int PXIeTriggerRTSI1(int *devNums, int numChassis) { int i; - for (i = 0; i < numChassis; i++) { + for (i = 0; i < numChassis; i++) + { // open DIO file descriptor sprintf(filename, "%s.%u.dio", DEVICE_FILE, devNums[i]); devFD[i] = open(filename, O_RDWR); - if (devFD[i] < 0) { + if (devFD[i] < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -2240,37 +2418,44 @@ int PXIeTriggerRTSI1(int *devNums, int numChassis) { dioConfig[i] = pxi6259_create_dio_conf(); // configure DIO ports - if (pxi6259_add_dio_channel(&dioConfig[i], DIO_PORT1, portMask1)) { + if (pxi6259_add_dio_channel(&dioConfig[i], DIO_PORT1, portMask1)) + { fprintf(stderr, "Failed to configure DIO port 0!\n"); return -1; } - if (pxi6259_load_dio_conf(devFD[i], &dioConfig[i])) { + if (pxi6259_load_dio_conf(devFD[i], &dioConfig[i])) + { fprintf(stderr, "Loading DIO configuration failed!\n"); return -1; } sprintf(filename, "%s.%u.dio.%u", DEVICE_FILE, devNums[i], 1); portFDs[i] = open(filename, O_RDWR | O_NONBLOCK); - if (portFDs[i] < 0) { + if (portFDs[i] < 0) + { fprintf(stderr, "Failed to open port: %s %s\n", strerror(errno), filename); return -1; } } - for (i = 0; i < numChassis; i++) { - if (write(portFDs[i], &writeValue1, 4) != 4) { + for (i = 0; i < numChassis; i++) + { + if (write(portFDs[i], &writeValue1, 4) != 4) + { fprintf(stderr, "Error writing to port 1! Error: %s\n", strerror(errno)); } writeValue1 = 0; - if (write(portFDs[i], &writeValue1, 4) != 4) { + if (write(portFDs[i], &writeValue1, 4) != 4) + { fprintf(stderr, "Error writing to port 1! Error: %s\n", strerror(errno)); } writeValue1 = 2; } - for (i = 0; i < numChassis; i++) { + for (i = 0; i < numChassis; i++) + { close(portFDs[i]); close(devFD[i]); } @@ -2294,7 +2479,8 @@ generateWaveformOnOneChannel_6259(int selectedCard, int channel, double offset, extern "C" int stopWaveGeneration(); static void createWaveform(int number_of_samples, double offset, double level, - float *buf) { + float *buf) +{ int i; // create one complete triangular period in volts @@ -2314,7 +2500,8 @@ static void createWaveform(int number_of_samples, double offset, double level, uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, double offset, double level, int waverate, float *values, - int nPoint, int softwareTrigger) { + int nPoint, int softwareTrigger) +{ int silent = 0; int retval = 0; int number_of_channels = 1; @@ -2328,10 +2515,13 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, sampleRate = number_of_samples * waverate; update_period_divisor = 100000000 / sampleRate; - if (nPoint == 0) { + if (nPoint == 0) + { printf("Generate default triangular waveform\n"); number_of_samples = 4000; - } else { + } + else + { printf("Generate EXPRESSION waveform\n"); number_of_samples = nPoint; } @@ -2352,7 +2542,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, float *write_array[number_of_channels]; xseries_ao_conf_t ao_conf; - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { write_array[i] = (float *)calloc(1, sizeof(float) * number_of_samples); } @@ -2361,7 +2552,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* open AO segment file descriptor */ sprintf(str, "%s.%u.ao", device_name, selectedCard); ao_fd = open(str, O_RDWR); - if (ao_fd <= 0) { + if (ao_fd <= 0) + { if (!silent) printf("Could not open AO segment!\n"); retval = -1; @@ -2373,7 +2565,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* reset AO segment */ retval = xseries_reset_ao(ao_fd); - if (retval) { + if (retval) + { if (!silent) printf("Error reseting card!\n"); goto out_6368; @@ -2393,13 +2586,15 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, XSERIES_AO_EXTERNAL_GATE_DISABLED, // No external pause signal XSERIES_AO_POLARITY_RISING_EDGE, // Don't care 0); // Disable - if (retval) { + if (retval) + { if (!silent) printf("Error setting external gate!\n"); goto out_6368; } - if (softwareTrigger) { + if (softwareTrigger) + { /* Program the START1 signal (start trigger) to assert from a software * rising edge */ @@ -2408,12 +2603,15 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, XSERIES_AO_START_TRIGGER_SW_PULSE, // Set the line to software-driven XSERIES_AO_POLARITY_RISING_EDGE, // Make line active on rising... 1); // ...edge (not high level) - if (retval) { + if (retval) + { if (!silent) printf("Error setting start software trigger!\n"); goto out_6368; } - } else { + } + else + { /* Program the START1 signal (start trigger) to assert from a PFI1 rising * edge */ @@ -2423,7 +2621,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, XSERIES_AO_START_TRIGGER_PFI1, // Set the line to PFI1-driven XSERIES_AO_POLARITY_RISING_EDGE, // Make line active on rising... 1); // ...edge (not high level) - if (retval) { + if (retval) + { if (!silent) printf("Error setting start PFI 1 trigger!\n"); goto out_6368; @@ -2436,7 +2635,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, XSERIES_AO_UPDATE_COUNTER_UI_TC, // Derive the clock line from the Update // Interval Terminal Count XSERIES_AO_POLARITY_RISING_EDGE); // Make the line active on rising edge - if (retval) { + if (retval) + { if (!silent) printf("Error setting update counter!\n"); goto out_6368; @@ -2448,23 +2648,26 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_TB3, // Source the Update // Interval from the // internal timebase - XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising - // edge - update_period_divisor, // Number of clock intervals between successive - // updates - 2 // Number of clock intervals after the start trigger before the first - // update + XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising + // edge + update_period_divisor, // Number of clock intervals between successive + // updates + 2 // Number of clock intervals after the start trigger before the first + // update ); - if (retval) { + if (retval) + { if (!silent) printf("Error setting update interval counter!\n"); goto out_6368; } /* Add channels */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { retval = xseries_add_ao_channel(&ao_conf, i, XSERIES_OUTPUT_RANGE_10V); - if (retval) { + if (retval) + { if (!silent) printf("Cannot add AI channel %d to configuration!\n", i); goto out_6368; @@ -2473,7 +2676,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* load configuration to the device */ retval = xseries_load_ao_conf(ao_fd, ao_conf); - if (retval) { + if (retval) + { if (!silent) printf("Cannot load AO configuration! %s (%d)\n", strerror(errno), errno); goto out_6368; @@ -2482,20 +2686,26 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* wait for the AO devices */ sleep(1); - if (nPoint == 0) { + if (nPoint == 0) + { createWaveform(number_of_samples, offset, level, write_array[0]); - } else { - for (i = 0; i < nPoint; i++) { + } + else + { + for (i = 0; i < nPoint; i++) + { write_array[0][i] = offset + level * values[i]; // printf( "Wave %d %f \n", i, write_array[0][i] ); } } /* Open channels */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { sprintf(str, "%s.%u.ao.%u", device_name, selectedCard, i); ao_chan_fd[i] = open(str, O_RDWR | O_NONBLOCK); - if (ao_chan_fd[i] < 0) { + if (ao_chan_fd[i] < 0) + { if (!silent) printf("Cannot add AO channel %d to configuration!\n", i); goto out_6368; @@ -2503,12 +2713,15 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, } /* Write samples */ - for (i = 0; i < number_of_samples; i++) { - for (k = 0; k < number_of_channels; k++) { + for (i = 0; i < number_of_samples; i++) + { + for (k = 0; k < number_of_channels; k++) + { // Write is not blocking !!! retval = xseries_write_ao(ao_chan_fd[k], &write_array[k][i], 1); // printf("write_array[%d][%d] = %f\n", k, i, write_array[k][i]); - if (retval == -1 && errno != EAGAIN) { + if (retval == -1 && errno != EAGAIN) + { if (!silent) printf("Error writing samples to FIFO buffer!\n"); goto out_6368; @@ -2518,15 +2731,18 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* put segment in started state */ retval = xseries_start_ao(ao_fd); - if (retval) { + if (retval) + { printf("Cannot start AO segment! %s (%d)\n", strerror(errno), errno); goto out_6368; } - if (softwareTrigger) { + if (softwareTrigger) + { /* pulse start trigger */ retval = xseries_pulse_ao(ao_fd, XSERIES_START_TRIGGER); - if (retval) { + if (retval) + { printf("Error generating start pulse!\n"); goto out_6368; } @@ -2536,18 +2752,22 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, int semVal; semWaveGen_id = sem_open("WaveGen", O_CREAT, 0666, 0); - if (semWaveGen_id == SEM_FAILED) { + if (semWaveGen_id == SEM_FAILED) + { perror("WaveGen sem_open"); return 0; } - if (sem_getvalue(semWaveGen_id, &semVal) < 0) { + if (sem_getvalue(semWaveGen_id, &semVal) < 0) + { perror("SemWaveGen sem_getvalue"); } printf("Waveform generation START\n"); - for (int i = 0; i < semVal + 1; i++) { - if (sem_wait(semWaveGen_id) < 0) { + for (int i = 0; i < semVal + 1; i++) + { + if (sem_wait(semWaveGen_id) < 0) + { perror("sem_wait on semWaveGen_id"); } } @@ -2559,7 +2779,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, xseries_stop_ao(ao_fd); /* close all used file descriptors */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { close(ao_chan_fd[i]); } @@ -2572,7 +2793,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, /* close card's file descriptor */ // close(dev_fd); - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { free(write_array[i]); } @@ -2588,7 +2810,8 @@ uint32_t generateWaveformOnOneChannel_6368(int selectedCard, int channel, uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, double offset, double level, int waverate, float *values, - int nPoint, int softwareTrigger) { + int nPoint, int softwareTrigger) +{ uint32_t retval = 0; pxi6259_ao_conf_t ao_conf; @@ -2611,10 +2834,13 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, // %d\nTrigger %d\n", selectedCard, channel, offset, level, waverate, nPoint, // softwareTrigger); printf("nPoint ==== %d\n", nPoint); - if (nPoint == 0) { + if (nPoint == 0) + { printf("Generate default triangular waveform\n"); number_of_samples = 1000; - } else { + } + else + { printf("Generate EXPRESSION waveform\n"); number_of_samples = nPoint; } @@ -2632,7 +2858,8 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, // get configuration file descriptor sprintf(str, "%s.%d.ao", RESOURCE_NAME_DAQ, selectedCard); fdConfig = open(str, O_RDWR | O_NONBLOCK); - if (fdConfig < 0) { + if (fdConfig < 0) + { printf("Error Opening Device! fd: %d\n", fdConfig); return -1; } @@ -2645,16 +2872,21 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, } */ - if (nPoint == 0) { + if (nPoint == 0) + { createWaveform(number_of_samples, offset, level, scaledWriteArray); - } else { - for (i = 0; i < nPoint; i++) { + } + else + { + for (i = 0; i < nPoint; i++) + { scaledWriteArray[i] = offset + level * values[i]; } } // retval = pxi6259_reset_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: reset ao. retval: %x\n", retval * -1); return -1; } @@ -2675,39 +2907,46 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, periodDivisor)) return -1; - if (softwareTrigger) { + if (softwareTrigger) + { // Program the START1 signal (start trigger) to assert from a software // rising edge if (pxi6259_set_ao_attribute(&ao_conf, AO_START1_SOURCE_SELECT, - AO_START1_SELECT_PULSE)) { + AO_START1_SELECT_PULSE)) + { printf("Error setting start software trigger!\n"); goto out_6259; } if (pxi6259_set_ao_attribute(&ao_conf, AO_START1_POLARITY_SELECT, - AO_START1_POLARITY_RISING_EDGE)) { + AO_START1_POLARITY_RISING_EDGE)) + { printf("Error setting start software trigger!\n"); goto out_6259; } - - } else { + } + else + { // Program the START1 signal (start trigger) to assert from a PFI1 rising // edge if (pxi6259_set_ao_attribute(&ao_conf, AO_START1_SOURCE_SELECT, - AO_START1_SELECT_PFI1)) { + AO_START1_SELECT_PFI1)) + { printf("Error setting start PFI1 trigger!\n"); goto out_6259; } if (pxi6259_set_ao_attribute(&ao_conf, AO_START1_POLARITY_SELECT, - AO_START1_POLARITY_RISING_EDGE)) { + AO_START1_POLARITY_RISING_EDGE)) + { printf("Error setting start PFI1 trigger!\n"); goto out_6259; } } retval = pxi6259_load_ao_conf(fdConfig, &ao_conf); - if (retval) { + if (retval) + { printf("err: load task. retval: %x\n", retval * -1); goto out_6259; } @@ -2717,19 +2956,22 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, // Open channels sprintf(str, "%s.%d.ao.%d", RESOURCE_NAME_DAQ, selectedCard, channel); fdChannel = open(str, O_RDWR | O_NONBLOCK); - if (fdChannel < 0) { + if (fdChannel < 0) + { printf("Error Opening Channel! FD: %d\n", fdChannel); return -1; } retval = pxi6259_write_ao(fdChannel, scaledWriteArray, number_of_samples); - if (retval != number_of_samples) { + if (retval != number_of_samples) + { printf("err: writing. retval: %d\n", retval); goto out_6259; } retval = pxi6259_start_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: Starting task. retval: %d\n", retval); return -1; } @@ -2749,18 +2991,22 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, int semVal; semWaveGen_id = sem_open("WaveGen", O_CREAT, 0666, 0); - if (semWaveGen_id == SEM_FAILED) { + if (semWaveGen_id == SEM_FAILED) + { perror("WaveGen sem_open"); return 0; } - if (sem_getvalue(semWaveGen_id, &semVal) < 0) { + if (sem_getvalue(semWaveGen_id, &semVal) < 0) + { perror("SemWaveGen sem_getvalue"); } printf("Waveform generation START\n"); - for (int i = 0; i < semVal + 1; i++) { - if (sem_wait(semWaveGen_id) < 0) { + for (int i = 0; i < semVal + 1; i++) + { + if (sem_wait(semWaveGen_id) < 0) + { perror("sem_wait on semWaveGen_id"); } } @@ -2774,7 +3020,8 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, // sleep(1); // retval = pxi6259_reset_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: reset ao. retval: %x\n", retval * -1); return -1; } @@ -2818,16 +3065,19 @@ uint32_t generateWaveformOnOneChannel_6259(int selectedCard, int channel, return 0; } -int stopWaveGeneration() { +int stopWaveGeneration() +{ sem_t *semWaveGen_id; semWaveGen_id = sem_open("WaveGen", O_CREAT, 0666, 0); - if (semWaveGen_id == SEM_FAILED) { + if (semWaveGen_id == SEM_FAILED) + { perror("WaveGen sem_open"); return 0; } - if (sem_post(semWaveGen_id) < 0) { + if (sem_post(semWaveGen_id) < 0) + { perror("sem_post semWaveGen"); return 0; } @@ -2848,7 +3098,8 @@ int stopWaveGeneration() { // Support class for enqueueing storage requests, specific for NI6259 EV // management -class SaveItemEV { +class SaveItemEV +{ int operation; // BEGIN UPDATE PUT MAKE MDSplus::Data *startData; MDSplus::Data *endData; @@ -2860,7 +3111,8 @@ class SaveItemEV { public: SaveItemEV(int operation, MDSplus::Data *startData, MDSplus::Data *endData, MDSplus::Data *dimData, MDSplus::Array *segData, - MDSplus::TreeNode *node) { + MDSplus::TreeNode *node) + { this->operation = operation; this->startData = startData; this->endData = endData; @@ -2874,50 +3126,64 @@ class SaveItemEV { SaveItemEV *getNext() { return nxt; } - void save() { - switch (operation) { + void save() + { + switch (operation) + { case SEGMENT_OP_BEGIN: - try { + try + { std::cout << "SAVE ITEM OP_BEGIN START:" << startData << " END: " << endData << " DIM: " << dimData << std::endl; node->beginSegment(startData, endData, dimData, segData); MDSplus::deleteData(startData); MDSplus::deleteData(endData); MDSplus::deleteData(dimData); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << "Error in BeginSegment: " << exc.what() << std::endl; } // std::cout << "OP_BEGIN FINITO" << std::endl; break; case SEGMENT_OP_MAKE: - try { + try + { std::cout << "SAVE ITEM OP_MAKE" << std::endl; node->makeSegment(startData, endData, dimData, segData); MDSplus::deleteData(startData); MDSplus::deleteData(endData); MDSplus::deleteData(dimData); MDSplus::deleteData(segData); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << "Error in MakeSegment: " << exc.what() << std::endl; } break; case SEGMENT_OP_UPDATE: - try { + try + { std::cout << "SAVE ITEM OP_UPDATE" << std::endl; node->updateSegment(startData, endData, dimData); MDSplus::deleteData(startData); MDSplus::deleteData(endData); MDSplus::deleteData(dimData); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << "Error in UpdateSegment: " << exc.what() << std::endl; } break; case SEGMENT_OP_PUT: - try { + try + { std::cout << "SAVE ITEM OP_PUT" << std::endl; node->putSegment(segData, -1); MDSplus::deleteData(segData); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << "Error in PutSegment: " << exc.what() << std::endl; } break; @@ -2928,7 +3194,8 @@ class SaveItemEV { extern "C" void *handleSaveEV(void *listPtr); -class SaveListEV { +class SaveListEV +{ public: pthread_cond_t itemAvailable; pthread_t thread; @@ -2936,7 +3203,8 @@ class SaveListEV { SaveItemEV *saveHead, *saveTail; bool stopReq; pthread_mutex_t mutex; - SaveListEV() { + SaveListEV() + { int status = pthread_mutex_init(&mutex, NULL); pthread_cond_init(&itemAvailable, NULL); saveHead = saveTail = NULL; @@ -2945,32 +3213,39 @@ class SaveListEV { } void addItem(int operation, MDSplus::Data *startData, MDSplus::Data *endData, MDSplus::Data *dimData, MDSplus::Array *segData, - MDSplus::TreeNode *node) { + MDSplus::TreeNode *node) + { SaveItemEV *newItem = new SaveItemEV(operation, startData, endData, dimData, segData, node); pthread_mutex_lock(&mutex); if (saveHead == NULL) saveHead = saveTail = newItem; - else { + else + { saveTail->setNext(newItem); saveTail = newItem; } pthread_cond_signal(&itemAvailable); pthread_mutex_unlock(&mutex); } - void executeItems() { - while (true) { + void executeItems() + { + while (true) + { pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { pthread_mutex_unlock(&mutex); pthread_exit(NULL); } - while (saveHead == NULL) { + while (saveHead == NULL) + { std::cout << "SAVE LIST WAIT..." << std::endl; pthread_cond_wait(&itemAvailable, &mutex); std::cout << "SAVE LIST CONDITION" << std::endl; - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { std::cout << "SAVE LIST EXIT" << std::endl; pthread_mutex_unlock(&mutex); @@ -2984,21 +3259,25 @@ class SaveListEV { delete currItem; } } - void start() { + void start() + { pthread_create(&thread, NULL, handleSaveEV, (void *)this); threadCreated = true; } - void stop() { + void stop() + { stopReq = true; pthread_cond_signal(&itemAvailable); - if (threadCreated) { + if (threadCreated) + { pthread_join(thread, NULL); printf("SAVE THREAD TERMINATED\n"); } } }; -extern "C" void *handleSaveEV(void *listPtr) { +extern "C" void *handleSaveEV(void *listPtr) +{ SaveListEV *list = (SaveListEV *)listPtr; list->executeItems(); @@ -3006,21 +3285,25 @@ extern "C" void *handleSaveEV(void *listPtr) { return NULL; } -extern "C" void startSaveEV(void **retList) { +extern "C" void startSaveEV(void **retList) +{ SaveListEV *saveList = new SaveListEV; saveList->start(); *retList = (void *)saveList; } -extern "C" void stopSaveEV(void *listPtr) { - if (listPtr) { +extern "C" void stopSaveEV(void *listPtr) +{ + if (listPtr) + { SaveListEV *list = (SaveListEV *)listPtr; list->stop(); delete list; } } -class BufferHandler { +class BufferHandler +{ size_t bufSize; short *buffer; size_t bufferIdx, oldestBufferIdx; @@ -3034,7 +3317,8 @@ class BufferHandler { public: BufferHandler(MDSplus::Tree *tree, MDSplus::TreeNode *rawNode, double maxDelay, double preTime, double baseFreq, - SaveListEV *saveList) { + SaveListEV *saveList) + { this->tree = tree; this->rawNode = rawNode; this->bufSize = (preTime + maxDelay) * baseFreq; @@ -3045,18 +3329,23 @@ class BufferHandler { } ~BufferHandler() { delete[] buffer; } - void processSample(short sample) { + void processSample(short sample) + { buffer[bufferIdx] = sample; sampleCount++; - if (sampleCount >= bufSize - 1) { + if (sampleCount >= bufSize - 1) + { processSampleDelayed(buffer[oldestBufferIdx]); oldestBufferIdx = (oldestBufferIdx + 1) % bufSize; } bufferIdx = (bufferIdx + 1) % bufSize; } - void terminate() { - if (sampleCount > bufSize) { - for (size_t i = 0; i < bufSize - 2; i++) { + void terminate() + { + if (sampleCount > bufSize) + { + for (size_t i = 0; i < bufSize - 2; i++) + { processSampleDelayed(buffer[oldestBufferIdx]); oldestBufferIdx = (oldestBufferIdx + 1) % bufSize; } @@ -3069,7 +3358,8 @@ class BufferHandler { virtual void flushBuffer() = 0; }; -class ClockBufferHandler : public BufferHandler { +class ClockBufferHandler : public BufferHandler +{ short *segBuffer; MDSplus::Array *initSegData; size_t bufIdx; @@ -3098,7 +3388,8 @@ class ClockBufferHandler : public BufferHandler { double maxDelay, int f1Div, int f2Div, double baseFreq, int segBufSize, int segmentSize, double startTime, double preTime, double postTime, SaveListEV *saveList) - : BufferHandler(tree, rawNode, maxDelay, preTime, baseFreq, saveList) { + : BufferHandler(tree, rawNode, maxDelay, preTime, baseFreq, saveList) + { this->basePeriod = 1. / baseFreq; this->baseFreq = baseFreq; this->segBufSize = segBufSize; @@ -3142,12 +3433,14 @@ class ClockBufferHandler : public BufferHandler { this->bufferCount = 0; this->freqSwitched = false; } - ~ClockBufferHandler() { + ~ClockBufferHandler() + { delete[] segBuffer; MDSplus::deleteData(initSegData); } - void processSampleDelayed(short sample) { + void processSampleDelayed(short sample) + { baseSampleCount++; currBaseSampleCount++; // Check whether frequency switched @@ -3160,7 +3453,8 @@ class ClockBufferHandler : public BufferHandler { std::cout << switchTimes[0] << std::endl; } */ - if (currBaseSampleCount % f12Div[currDivIdx] == 0) { + if (currBaseSampleCount % f12Div[currDivIdx] == 0) + { segBuffer[segBufSampleCount] = sample; segBufSampleCount++; if (segBufSampleCount >= segBufSize) // buffer filled @@ -3221,7 +3515,9 @@ class ClockBufferHandler : public BufferHandler { bufStartTimes.push_back(switchTimes[0] + basePeriod * f12Div[currDivIdx]); bufEndTimes[bufEndTimes.size() - 1] = switchTimes[0] + minPeriod / 2.; - } else { + } + else + { currBaseSampleCount = -1; // Next sample is being written bufStartTimes.push_back(switchTimes[0]); bufEndTimes[bufEndTimes.size() - 1] = switchTimes[0] - minPeriod / 2.; @@ -3263,12 +3559,14 @@ class ClockBufferHandler : public BufferHandler { } } // processSample() - virtual void trigger(double trigTime) { + virtual void trigger(double trigTime) + { double startTime = trigTime - preTime; if (switchTimes.size() == 0 || switchTimes[switchTimes.size() - 1] <= startTime) switchTimes.push_back(startTime); - else { + else + { size_t idx; for (idx = switchTimes.size() - 1; idx > 0 && switchTimes[idx] >= startTime; idx--) @@ -3278,7 +3576,8 @@ class ClockBufferHandler : public BufferHandler { double endTime = trigTime + postTime; if (switchTimes[switchTimes.size() - 1] <= endTime) switchTimes.push_back(endTime); - else { + else + { size_t idx; for (idx = switchTimes.size() - 1; idx > 0 && switchTimes[idx] >= endTime; idx--) @@ -3286,14 +3585,16 @@ class ClockBufferHandler : public BufferHandler { switchTimes.insert(switchTimes.begin() + idx, endTime); } } - virtual void flushBuffer() { + virtual void flushBuffer() + { std::cout << "FLUSH BUFFER " << segBufSampleCount << std::endl; MDSplus::Array *bufferData = new Int16Array(segBuffer, segBufSampleCount); saveList->addItem(SEGMENT_OP_PUT, NULL, NULL, NULL, bufferData, rawNode); } }; -class BurstBufferHandler : public BufferHandler { +class BurstBufferHandler : public BufferHandler +{ short *segBuffer; std::vector startTimes; int freqDiv; @@ -3311,7 +3612,8 @@ class BurstBufferHandler : public BufferHandler { double maxDelay, int freqDiv, double baseFreq, double startTime, double preTime, double postTime, int segmentSize, SaveListEV *saveList) - : BufferHandler(tree, rawNode, maxDelay, preTime, baseFreq, saveList) { + : BufferHandler(tree, rawNode, maxDelay, preTime, baseFreq, saveList) + { this->preTime = preTime; this->baseFreq = baseFreq; this->basePeriod = 1. / baseFreq; @@ -3325,13 +3627,15 @@ class BurstBufferHandler : public BufferHandler { this->inBurst = false; this->baseSampleCount = 0; } - ~BurstBufferHandler() { + ~BurstBufferHandler() + { std::cout << "DISTRUTTORE BURST" << std::endl; delete[] segBuffer; std::cout << "DISTRUTTO" << std::endl; } - virtual void processSampleDelayed(short sample) { + virtual void processSampleDelayed(short sample) + { baseSampleCount++; currBaseSampleCount++; // Check whether frequency switched @@ -3353,10 +3657,12 @@ class BurstBufferHandler : public BufferHandler { startTimes.erase(startTimes.begin()); } - if (inBurst && (currBaseSampleCount % freqDiv == 0)) { + if (inBurst && (currBaseSampleCount % freqDiv == 0)) + { segBuffer[burstCount++] = sample; windowCount++; - if (burstCount >= segmentSize) { + if (burstCount >= segmentSize) + { double segEnd = segStart + (segmentSize - 1) * basePeriod * freqDiv; MDSplus::Data *startSegData = new MDSplus::Float64(segStart); MDSplus::Data *endSegData = new MDSplus::Float64(segEnd); @@ -3379,7 +3685,8 @@ class BurstBufferHandler : public BufferHandler { burstCount = 0; segStart = currTime; } - } else if (windowCount > windowSize) // Last piece of burst + } + else if (windowCount > windowSize) // Last piece of burst { double segEnd = segStart + (burstCount - 1) * basePeriod * freqDiv; MDSplus::Data *startSegData = new MDSplus::Float64(segStart); @@ -3400,13 +3707,15 @@ class BurstBufferHandler : public BufferHandler { } } } - virtual void trigger(double trigTime) { + virtual void trigger(double trigTime) + { double startTime = trigTime - preTime; size_t idx; if (startTimes.size() == 0 || startTimes[startTimes.size() - 1] <= startTime) startTimes.push_back(startTime); - else { + else + { size_t idx; for (idx = startTimes.size() - 1; idx > 0 && startTimes[idx] >= startTime; idx--) @@ -3417,15 +3726,18 @@ class BurstBufferHandler : public BufferHandler { virtual void flushBuffer() { std::cout << "FLUSH BUFFERS" << std::endl; } }; -class EventHandler : public Event { +class EventHandler : public Event +{ BufferHandler *bufHandler; public: - EventHandler(char *name, BufferHandler *buf) : Event(name) { + EventHandler(char *name, BufferHandler *buf) : Event(name) + { std::cout << "Created event handler for " << name << std::endl; this->bufHandler = buf; } - void run() { + void run() + { int bufSize; MDSplus::Data *evData = getData(); // Get raw data double triggerTime = evData->getDouble(); @@ -3441,7 +3753,8 @@ int pxi6259EV_readAndSaveAllChannels( int nChan, void *chanFdPtr, int *isBurst, int *f1Div, int *f2Div, double maxDelay, double baseFreq, double *preTimes, double *postTimes, double startTime, int bufSize, int segmentSize, char **eventNames, - void *dataNidPtr, void *treePtr, void *saveListPtr, void *stopAcq) { + void *dataNidPtr, void *treePtr, void *saveListPtr, void *stopAcq) +{ int chan; SaveListEV *saveList = (SaveListEV *)saveListPtr; int *chanFd = (int *)chanFdPtr; @@ -3452,12 +3765,15 @@ int pxi6259EV_readAndSaveAllChannels( treeNodes = new MDSplus::TreeNode *[nChan]; // Delete first all data nids - for (int i = 0; i < nChan; i++) { - try { + for (int i = 0; i < nChan; i++) + { + try + { treeNodes[i] = new TreeNode(dataNid[i], (Tree *)treePtr); treeNodes[i]->deleteData(); - - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Error deleting data nodes\n"); } } @@ -3468,7 +3784,8 @@ int pxi6259EV_readAndSaveAllChannels( memset(bufferHandlers, 0, sizeof(BufferHandler *) * nChan); eventHandlers = new EventHandler *[nChan]; memset(eventHandlers, 0, sizeof(EventHandler *) * nChan); - for (chan = 0; chan < nChan; chan++) { + for (chan = 0; chan < nChan; chan++) + { if (isBurst[chan]) bufferHandlers[chan] = new BurstBufferHandler( (MDSplus::Tree *)treePtr, treeNodes[chan], maxDelay, f1Div[chan], @@ -3484,24 +3801,34 @@ int pxi6259EV_readAndSaveAllChannels( eventHandlers[chan] = new EventHandler(eventNames[chan], bufferHandlers[chan]); eventHandlers[chan]->start(); - } else + } + else eventHandlers[chan] = NULL; } - while (!(*(int *)stopAcq)) { + while (!(*(int *)stopAcq)) + { short buffer[ADC_BUFFER_SIZE]; - for (chan = 0; chan < nChan; chan++) { + for (chan = 0; chan < nChan; chan++) + { int currReadSamples = read(chanFd[chan], buffer, ADC_BUFFER_SIZE * 2); - if (currReadSamples <= 0) { - if (errno == EAGAIN || errno == ENODATA) { + if (currReadSamples <= 0) + { + if (errno == EAGAIN || errno == ENODATA) + { usleep(50); currReadSamples = 0; // No data currently available... Try again // continue; - } else { - if (errno == EOVERFLOW) { + } + else + { + if (errno == EOVERFLOW) + { printf("PXI 6259 Error reading samples on ai%d: (%d) %s \n", chan, errno, strerror(errno)); - for (chan = 0; chan < nChan; chan++) { - if (eventHandlers[chan]) { + for (chan = 0; chan < nChan; chan++) + { + if (eventHandlers[chan]) + { eventHandlers[chan]->stop(); delete eventHandlers[chan]; } @@ -3512,9 +3839,12 @@ int pxi6259EV_readAndSaveAllChannels( return -2; } } - } else { + } + else + { for (int sampleIdx = 0; sampleIdx < currReadSamples / sizeof(short); - sampleIdx++) { + sampleIdx++) + { bufferHandlers[chan]->processSample(buffer[sampleIdx]); // std::cout << buffer[sampleIdx] << std::endl; } @@ -3522,8 +3852,10 @@ int pxi6259EV_readAndSaveAllChannels( } } - for (chan = 0; chan < nChan; chan++) { - if (eventHandlers[chan]) { + for (chan = 0; chan < nChan; chan++) + { + if (eventHandlers[chan]) + { std::cout << "STOPPING EVENT HANDLER...." << std::endl; eventHandlers[chan]->stop(); std::cout << "STOPPED" << std::endl; diff --git a/device_support/national/cRioFAUfunction.cpp b/device_support/national/cRioFAUfunction.cpp index abd5e8318e..14ff38fa13 100644 --- a/device_support/national/cRioFAUfunction.cpp +++ b/device_support/national/cRioFAUfunction.cpp @@ -5,7 +5,8 @@ using namespace MDSplus; /********************/ // Support class for enqueueing storage requests -class FAUSaveItem { +class FAUSaveItem +{ uint8_t *data; double *time; double trigTime; @@ -29,7 +30,8 @@ class FAUSaveItem { // FAUSaveItem(uint8_t *data, double *time, double trigTime, int currSize, // size_t nDio, int *dataNids, Tree *treePtr) FAUSaveItem(uint8_t *data, double *time, double trigTime, int *currSizeA, - int currSize, size_t nDio, int *dataNids, Tree *treePtr) { + int currSize, size_t nDio, int *dataNids, Tree *treePtr) + { this->data = data; this->time = time; this->trigTime = trigTime; @@ -45,7 +47,8 @@ class FAUSaveItem { FAUSaveItem *getNext() { return nxt; } - void save() { + void save() + { #include @@ -54,11 +57,13 @@ class FAUSaveItem { /* handle connection */ - try { + try + { clock_gettime(CLOCK_REALTIME, &before); - for (int j = 0; j < nDio; j++) { + for (int j = 0; j < nDio; j++) + { TreeNode *currNode = new TreeNode(((int *)dataNids)[j], (Tree *)treePtr); timeArrData = new Float64Array(&time[j * currSize], currSizeA[j]); @@ -90,8 +95,9 @@ class FAUSaveItem { printf("Elapsed time %0.2f Segment Size %d\n", elapsed_nsecs/1000000000., currSize); */ - - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Class FAUSaveItem: Error saving data %s\n", exc->what()); } } @@ -99,7 +105,8 @@ class FAUSaveItem { extern "C" void *FAUhandleSave(void *listPtr); -class FAUSaveList { +class FAUSaveList +{ public: pthread_cond_t FAUitemAvailable; pthread_t thread; @@ -109,7 +116,8 @@ class FAUSaveList { pthread_mutex_t mutex; public: - FAUSaveList() { + FAUSaveList() + { int status = pthread_mutex_init(&mutex, NULL); status = pthread_cond_init(&FAUitemAvailable, NULL); saveHead = saveTail = NULL; @@ -117,14 +125,16 @@ class FAUSaveList { threadCreated = false; } void addItem(uint8_t *value, double *time, double trigTime, int *currSizeA, - int currSize, size_t nDio, int *dataNids, Tree *treePtr) { + int currSize, size_t nDio, int *dataNids, Tree *treePtr) + { FAUSaveItem *newItem = new FAUSaveItem(value, time, trigTime, currSizeA, currSize, nDio, dataNids, treePtr); pthread_mutex_lock(&mutex); if (saveHead == NULL) saveHead = saveTail = newItem; - else { + else + { saveTail->setNext(newItem); saveTail = newItem; } @@ -132,22 +142,27 @@ class FAUSaveList { pthread_mutex_unlock(&mutex); } - void executeItems() { + void executeItems() + { int __count = 0; // printf("Start executeItems\n"); - while (true) { + while (true) + { // printf("Get mutex executeItems\n"); pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { // printf("Stop executeItems\n"); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } - while (saveHead == NULL) { + while (saveHead == NULL) + { // printf("Wait executeItems %p\n", &FAUitemAvailable); pthread_cond_wait(&FAUitemAvailable, &mutex); - if (stopReq && saveHead == NULL) { + if (stopReq && saveHead == NULL) + { // printf("Stop executeItems\n"); pthread_mutex_unlock(&mutex); pthread_exit(NULL); @@ -168,7 +183,8 @@ class FAUSaveList { } } - int getItemPending() { + int getItemPending() + { int nItems = 0; pthread_mutex_lock(&mutex); for (FAUSaveItem *itm = saveHead; itm; itm = itm->getNext(), nItems++) @@ -177,16 +193,19 @@ class FAUSaveList { return nItems; } - void start() { + void start() + { pthread_create(&thread, NULL, FAUhandleSave, (void *)this); threadCreated = true; } - void stop() { + void stop() + { printf("START SAVE THREAD TERMINATED\n"); printf("Pendig Items %d\n", getItemPending()); stopReq = true; pthread_cond_signal(&FAUitemAvailable); - if (threadCreated) { + if (threadCreated) + { printf("Join thread\n"); pthread_join(thread, NULL); } @@ -194,22 +213,26 @@ class FAUSaveList { } }; -extern "C" void *FAUhandleSave(void *listPtr) { +extern "C" void *FAUhandleSave(void *listPtr) +{ FAUSaveList *list = (FAUSaveList *)listPtr; list->executeItems(); return NULL; } -extern "C" void FAUstartSave(void **retList) { +extern "C" void FAUstartSave(void **retList) +{ printf("FAU Start Queued Save Thread\n"); FAUSaveList *fauSaveList = new FAUSaveList; fauSaveList->start(); *retList = (void *)fauSaveList; } -extern "C" void FAUstopSave(void *listPtr) { +extern "C" void FAUstopSave(void *listPtr) +{ printf("FAU Stop Queued Save Thread\n"); - if (listPtr) { + if (listPtr) + { FAUSaveList *list = (FAUSaveList *)listPtr; list->stop(); delete list; @@ -218,7 +241,8 @@ extern "C" void FAUstopSave(void *listPtr) { /*********************/ -NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) { +NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) +{ NiFpga_Status status = NiFpga_Status_Success; NiFpga_Status status1 = NiFpga_Status_Success; size_t requestedDepth, actualDepth; @@ -231,7 +255,8 @@ NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) { NiFpga_FAU_cRIO_FPGA_Signature, "RIO0", NiFpga_OpenAttribute_NoRun, session)); - if (NiFpga_IsNotError(status)) { + if (NiFpga_IsNotError(status)) + { NiFpga_MergeStatus( &status, NiFpga_ConfigureFifo2( @@ -241,7 +266,8 @@ NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) { printf("Host FIFO %d data resize %d status %d\n", actualDepth, FifoDepthSize, status); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); printf("Host FIFO data resize error\n"); return -1; @@ -253,7 +279,8 @@ NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) { NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64_AcquisitionFIFORT, FifoDepthSize, &actualDepth)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); printf("Host FIFO time resize error\n"); return -1; @@ -261,20 +288,23 @@ NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize) { NiFpga_MergeStatus(&status, NiFpga_Reset(*session)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); printf("VI Reset error\n"); return -1; } - - } else { + } + else + { printf("FPGA Open error\n"); return -1; } return status; } -NiFpga_Status closeFauFpgaSession(NiFpga_Session session) { +NiFpga_Status closeFauFpgaSession(NiFpga_Session session) +{ /* CODAC NOTE: NiFpga_Initialize() is no longer necessary! */ /* must be called before any other calls */ @@ -308,7 +338,8 @@ NiFpga_Status closeFauFpgaSession(NiFpga_Session session) { NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, uint64_t PTECountSlowFastMask, uint32_t PTESlowCount, uint32_t PTEFastCount, - uint16_t tickFreqCode) { + uint16_t tickFreqCode) +{ NiFpga_Status status = NiFpga_Status_Success; uint32_t PTEcount; @@ -318,7 +349,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, NiFpga_FAU_cRIO_FPGA_ControlU64_PTEEnaMask, PTEEnaMask)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting enable channels Pulse Train Mask"); return -1; } @@ -328,7 +360,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, NiFpga_WriteU64(session, NiFpga_FAU_cRIO_FPGA_ControlU64_PTEFastSlowMask, PTECountSlowFastMask)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting slow fast channels frequency Pulse Train Mask"); return -1; } @@ -338,7 +371,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, NiFpga_WriteU32(session, NiFpga_FAU_cRIO_FPGA_ControlU32_PTEcountSlow, PTESlowCount)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting Pulse Train slow frequency"); return -1; } @@ -348,7 +382,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, NiFpga_WriteU32(session, NiFpga_FAU_cRIO_FPGA_ControlU32_PTEcountFast, PTEFastCount)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting Pulse Train fast frequency"); return -1; } @@ -357,7 +392,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, NiFpga_WriteU16(session, NiFpga_FAU_cRIO_FPGA_ControlU16_CountFreq, tickFreqCode)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting time base tick frequency"); return -1; } @@ -366,7 +402,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, &status, NiFpga_WriteBool(session, NiFpga_FAU_cRIO_FPGA_ControlBool_goToIdle, 1)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error setting idle state"); return -1; } @@ -375,7 +412,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, &status, NiFpga_WriteBool(session, NiFpga_FAU_cRIO_FPGA_ControlBool_AcqEna, 0)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error reset enable acquisition flag"); return -1; } @@ -385,7 +423,8 @@ NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, /***************************************/ -NiFpga_Status startFauAcquisition(NiFpga_Session session) { +NiFpga_Status startFauAcquisition(NiFpga_Session session) +{ NiFpga_Status status = NiFpga_Status_Success; printf("startFauAcquisition\n"); @@ -394,7 +433,8 @@ NiFpga_Status startFauAcquisition(NiFpga_Session session) { &status, NiFpga_WriteBool(session, NiFpga_FAU_cRIO_FPGA_ControlBool_AcqEna, 1)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting enable acquisition flag"); return -1; } @@ -402,14 +442,16 @@ NiFpga_Status startFauAcquisition(NiFpga_Session session) { return status; } -NiFpga_Status pauseFauAcquisition(NiFpga_Session session) { +NiFpga_Status pauseFauAcquisition(NiFpga_Session session) +{ NiFpga_Status status = NiFpga_Status_Success; NiFpga_MergeStatus( &status, NiFpga_WriteBool(session, NiFpga_FAU_cRIO_FPGA_ControlBool_AcqEna, 0)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting enable acquisition flag"); return -1; } @@ -422,7 +464,8 @@ NiFpga_Status pauseFauAcquisition(NiFpga_Session session) { int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, double trigTime, size_t maxSamp, size_t nDio, - void *treePtr, void *dataNidPtr, uint8_t *stopFlag) { + void *treePtr, void *dataNidPtr, uint8_t *stopFlag) +{ NiFpga_Status status = NiFpga_Status_Success; int currSize = 0; @@ -431,7 +474,8 @@ int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, double *time; int __count = 0; - if (nDio > 64) { + if (nDio > 64) + { printf("Invalid arguments\n"); return -1; } @@ -442,11 +486,13 @@ int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, data = (uint8_t *)calloc(maxSamp * nDio, sizeof(uint8_t)); time = (double *)calloc(maxSamp, sizeof(double)); - while ((!*(uint8_t *)stopFlag) == 1) { + while ((!*(uint8_t *)stopFlag) == 1) + { currSize = readFauFifoData(session, data, time, tickPeriod, &maxSamp, nDio, stopFlag); - if (currSize > 0) { + if (currSize > 0) + { printf("\rFau Acq %c", simb[__count++ % 5]); fflush(stdout); @@ -457,12 +503,15 @@ int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, double *timeQ = (double *)calloc(currSize * nDio, sizeof(double)); int *currSizeA = (int *)calloc(nDio, sizeof(int)); - for (int i = 0; i < currSize; i++) { - for (int j = 0; j < nDio; j++) { + for (int i = 0; i < currSize; i++) + { + for (int j = 0; j < nDio; j++) + { b = data[i + j * maxSamp]; if (i == 0 || i == (currSize - 1) || - (i >= 1 && data[(i - 1) + j * maxSamp] != b)) { + (i >= 1 && data[(i - 1) + j * maxSamp] != b)) + { dataQ[currSizeA[j] + j * currSize] = b; timeQ[currSizeA[j] + j * currSize] = time[i] + trigTime; currSizeA[j]++; @@ -486,7 +535,8 @@ int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, size_t maxSamp, size_t nDio, void *treePtr, void *dataNidPtr, - uint8_t *stopFlag) { + uint8_t *stopFlag) +{ NiFpga_Status status = NiFpga_Status_Success; int currSize = 0; int *currSizeA; @@ -504,11 +554,14 @@ int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, timeDio = (double *)calloc(currSize * nDio, sizeof(double)); currSizeA = (int *)calloc(nDio, sizeof(int)); - for (int i = 0; i < currSize; i++) { - for (int j = 0; j < nDio; j++) { + for (int i = 0; i < currSize; i++) + { + for (int j = 0; j < nDio; j++) + { b = data[i + j * maxSamp]; if (i == 0 || i == (currSize - 1) || - (i >= 1 && data[(i - 1) + j * maxSamp] != b)) { + (i >= 1 && data[(i - 1) + j * maxSamp] != b)) + { data[currSizeA[j] + j * maxSamp] = b; timeDio[currSizeA[j] + j * currSize] = time[i] + trigTime; currSizeA[j]++; @@ -518,7 +571,8 @@ int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, // currSize = 0; - if (currSize > 0) { + if (currSize > 0) + { printf("fauSaveAcqData %d maxSamp %d \n", currSize, maxSamp); Float64Array *timeArrData; @@ -527,15 +581,20 @@ int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, Uint8Array *dataArrData; TreeNode *currNode[NUM_DIO]; - for (int i = 0; i < NUM_DIO; i++) { - try { + for (int i = 0; i < NUM_DIO; i++) + { + try + { currNode[i] = new TreeNode(dataNids[i], (Tree *)treePtr); - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("Error collecting data nodes %s\n", exc->what()); } } - for (int j = 0; j < nDio; j++) { + for (int j = 0; j < nDio; j++) + { timeArrData = new Float64Array(&timeDio[j * currSize], currSizeA[j]); start = new Float64(timeDio[j * currSize]); end = new Float64(timeDio[(currSizeA[j] - 1) + j * currSize]); @@ -564,7 +623,8 @@ int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, double tickPeriod, size_t *maxSampPtr, size_t nDio, - uint8_t *stopFlag) { + uint8_t *stopFlag) +{ NiFpga_Status status = NiFpga_Status_Success; size_t currSize = 0; uint32_t count = 0, noDataCount = 0; @@ -579,7 +639,8 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, uint64_t elem[MAX_FPGA_READ_BUF_SIZE]; uint64_t tickTime[MAX_FPGA_READ_BUF_SIZE]; - if (data == NULL || time == NULL || nDio > 64 || stopFlag == NULL) { + if (data == NULL || time == NULL || nDio > 64 || stopFlag == NULL) + { printf("Invalid arguments\n"); return -1; } @@ -590,7 +651,8 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, // while( currSize < maxSamp && count < MAX_COUNT && !( count > MAX_COUNT/2 && // currSize > MIN_SEGMENT ) ) while (currSize < maxSamp && count < MAX_COUNT && currSize < MIN_SEGMENT && - *(int *)stopFlag == 0) { + *(int *)stopFlag == 0) + { count++; /* @@ -608,12 +670,14 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, session, NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64_AcquisitionFIFOR, &dummy, 0, 0, &nElem)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Read Error\n"); return -1; } - if (nElem == 0) { + if (nElem == 0) + { noDataCount++; usleep(1000); // Acquisition isn't enabled @@ -644,12 +708,14 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, session, NiFpga_FAU_cRIO_FPGA_TargetToHostFifoU64_AcquisitionFIFORT, &dummy, 0, 0, &nTime)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Read Error\n"); return -1; } - if (nElem >= nTime) { + if (nElem >= nTime) + { // if (nElem > nTime) // printf("Difference nElem %d nTime %d\n", nElem,nTime); nElem = nTime; @@ -678,7 +744,8 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, &elem[currSize], currElem, 500, &rElem)); // FIFO Remaining Element - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("\nNiFpga_ReadFifoU64 Read Error data %d elem %d\n", status, currElem); printf("DataElem %d TimeElem %d ReadElem %d Remaining Elem %d \n", nElem, @@ -695,7 +762,8 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, currElem, // nTime, 500, &rElem)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("\nNiFpga_ReadFifoU64 Read Error time %d elem %d\n ", status, currElem); printf("DataElem %d TimeElem %d ReadElem %d Remaining Elem %d \n", nElem, @@ -708,15 +776,18 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, currSize += currElem; } - if (currSize > 0) { + if (currSize > 0) + { // printf("====== Complete Segment %d count %d noDataCount %d\n\n", // currSize, count, noDataCount); - for (int i = 0; i < currSize; i++) { + for (int i = 0; i < currSize; i++) + { // if(i < 10 ) // printf("%d ",i); - for (int j = 0; j < nDio; j++) { + for (int j = 0; j < nDio; j++) + { data[i + j * maxSamp] = (elem[i] & (((uint64_t)1) << j)) ? 1 : 0; // if(i < 10 ) @@ -735,23 +806,27 @@ int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, return currSize; } -NiFpga_Status startFauFpga(NiFpga_Session session) { +NiFpga_Status startFauFpga(NiFpga_Session session) +{ NiFpga_Status status = NiFpga_Status_Success; // run the FPGA application printf("Running the FPGA...\n"); NiFpga_MergeStatus(&status, NiFpga_Run(session, 0)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error running FPGA\n"); return -1; - } else + } + else printf("OK running FPGA\n"); return status; } -NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState) { +NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState) +{ NiFpga_Status status = NiFpga_Status_Success; @@ -760,7 +835,8 @@ NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState) { NiFpga_FAU_cRIO_FPGA_IndicatorU16_AcqState, acqState)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error reading FAU acquisition state\n"); return -1; } @@ -768,7 +844,8 @@ NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState) { return status; } -uint16_t IsFauFIFOOverflow(NiFpga_Session session) { +uint16_t IsFauFIFOOverflow(NiFpga_Session session) +{ NiFpga_Status status = NiFpga_Status_Success; NiFpga_Bool fifoOverflowed; @@ -778,7 +855,8 @@ uint16_t IsFauFIFOOverflow(NiFpga_Session session) { session, NiFpga_FAU_cRIO_FPGA_IndicatorBool_FifoOverflowed, &fifoOverflowed)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error reading FAU FIFO overflow flag\n"); return 1; } diff --git a/device_support/national/cRioFAUfunction.h b/device_support/national/cRioFAUfunction.h index 82123b1ddb..f5eb70c971 100644 --- a/device_support/national/cRioFAUfunction.h +++ b/device_support/national/cRioFAUfunction.h @@ -18,30 +18,31 @@ #define MAX_FPGA_READ_BUF_SIZE 40000 const char *simb = "|/-\\"; -extern "C" { -NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize); -NiFpga_Status closeFauFpgaSession(NiFpga_Session session); -// NiFpga_Status setFauAcqParam(NiFpga_Session session, uint16_t PTEmask, -// uint32_t PTEfrequency, uint16_t tickFreqCode); -NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, - uint64_t PTECountSlowFastMask, - uint32_t PTESlowCount, uint32_t PTEFastCount, - uint16_t tickFreqCode); -NiFpga_Status startFauFpga(NiFpga_Session session); -int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, - double tickPeriod, size_t *maxSamp, size_t nDio, - uint8_t *stopFlag); -int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, - size_t maxSamp, size_t nDio, void *treePtr, void *dataNidPtr, - uint8_t *stopFlag); -// int fauQueuedAcqData(NiFpga_Session session, void *fauList, uint8_t *data, -// double *time, double tickPeriod, size_t maxSamp, size_t nDio, void *treePtr, -// void *dataNidPtr, uint8_t *stopFlag); -int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, - double trigTime, size_t maxSamp, size_t nDio, - void *treePtr, void *dataNidPtr, uint8_t *stopFlag); -NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState); -uint16_t IsFauFIFOOverflow(NiFpga_Session session); -NiFpga_Status startFauAcquisition(NiFpga_Session session); -NiFpga_Status pauseFauAcquisition(NiFpga_Session session); +extern "C" +{ + NiFpga_Status crioFauInit(NiFpga_Session *session, size_t FifoDepthSize); + NiFpga_Status closeFauFpgaSession(NiFpga_Session session); + // NiFpga_Status setFauAcqParam(NiFpga_Session session, uint16_t PTEmask, + // uint32_t PTEfrequency, uint16_t tickFreqCode); + NiFpga_Status setFauAcqParam(NiFpga_Session session, uint64_t PTEEnaMask, + uint64_t PTECountSlowFastMask, + uint32_t PTESlowCount, uint32_t PTEFastCount, + uint16_t tickFreqCode); + NiFpga_Status startFauFpga(NiFpga_Session session); + int readFauFifoData(NiFpga_Session session, uint8_t *data, double *time, + double tickPeriod, size_t *maxSamp, size_t nDio, + uint8_t *stopFlag); + int fauSaveAcqData(NiFpga_Session session, double tickPeriod, double trigTime, + size_t maxSamp, size_t nDio, void *treePtr, void *dataNidPtr, + uint8_t *stopFlag); + // int fauQueuedAcqData(NiFpga_Session session, void *fauList, uint8_t *data, + // double *time, double tickPeriod, size_t maxSamp, size_t nDio, void *treePtr, + // void *dataNidPtr, uint8_t *stopFlag); + int fauQueuedAcqData(NiFpga_Session session, void *fauList, double tickPeriod, + double trigTime, size_t maxSamp, size_t nDio, + void *treePtr, void *dataNidPtr, uint8_t *stopFlag); + NiFpga_Status getFauAcqState(NiFpga_Session session, uint16_t *acqState); + uint16_t IsFauFIFOOverflow(NiFpga_Session session); + NiFpga_Status startFauAcquisition(NiFpga_Session session); + NiFpga_Status pauseFauAcquisition(NiFpga_Session session); } diff --git a/device_support/national/cRioMPAGfunction.cpp b/device_support/national/cRioMPAGfunction.cpp index f034e6df64..44ad9dcb3c 100644 --- a/device_support/national/cRioMPAGfunction.cpp +++ b/device_support/national/cRioMPAGfunction.cpp @@ -3,7 +3,8 @@ int DEBUG = 0; NiFpga_Status crioMpagInitFifo(NiFpga_Session session, const char *fifoName, - NiFpgaEx_DmaFifo fifoId, size_t fifoDepthSize) { + NiFpgaEx_DmaFifo fifoId, size_t fifoDepthSize) +{ NiFpga_Status status = NiFpga_Status_Success; size_t actualDepth; @@ -16,7 +17,8 @@ NiFpga_Status crioMpagInitFifo(NiFpga_Session session, const char *fifoName, printf("Host %s actual size %d data resize %d status %d\n", fifoName, actualDepth, fifoDepthSize, status); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Host %s data fifo depth resize error\n", fifoName); return status; } @@ -37,7 +39,8 @@ NiFpga_Status crioMpagInitFifo(NiFpga_Session session, const char *fifoName, } NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, - NiFpgaEx_DmaFifo fifoId) { + NiFpgaEx_DmaFifo fifoId) +{ NiFpga_Status status = NiFpga_Status_Success; size_t nElem; size_t rElem; @@ -51,7 +54,8 @@ NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, NiFpga_MergeStatus(&status, NiFpga_ReadFifoI16(session, fifoId, &dummy, 0, 0, &nElem)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(session, 0); printf("Host %s error reading num elements in fifo\n", fifoName); return status; @@ -59,14 +63,16 @@ NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, printf("Num elements in %s %d\n", fifoName, nElem); - if (nElem > 0) { + if (nElem > 0) + { dummyElem = (int16_t *)calloc(nElem, sizeof(int16_t)); NiFpga_MergeStatus(&status, NiFpga_ReadFifoI16(session, fifoId, dummyElem, nElem, 0, &rElem)); // FIFO Remaining Element - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(session, 0); printf("Host %s error reading fifo\n", fifoName); return status; @@ -81,7 +87,8 @@ NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, } NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, - size_t fifoDepthSize) { + size_t fifoDepthSize) +{ NiFpga_Status status = NiFpga_Status_Success; if (DEBUG == 1) @@ -96,12 +103,14 @@ NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, NiFpga_MainFPGA_9159_Signature, cRioId, NiFpga_OpenAttribute_NoRun, session)); - if (NiFpga_IsNotError(status)) { + if (NiFpga_IsNotError(status)) + { status = crioMpagInitFifo( *session, "FIFO A", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A, fifoDepthSize); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); return -1; } @@ -109,7 +118,8 @@ NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, status = crioMpagInitFifo( *session, "FIFO B", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_B, fifoDepthSize); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); return -1; } @@ -117,27 +127,31 @@ NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, status = crioMpagInitFifo( *session, "FIFO C", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_C, fifoDepthSize); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); return -1; } NiFpga_MergeStatus(&status, NiFpga_Reset(*session)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { NiFpga_Close(*session, 0); printf("VI Reset error\n"); return -1; } - - } else { + } + else + { printf("FPGA Open error : %d\n", status); return -1; } return status; } -NiFpga_Status closeMpagFpgaSession(NiFpga_Session session) { +NiFpga_Status closeMpagFpgaSession(NiFpga_Session session) +{ /* CODAC NOTE: NiFpga_Initialize() is no longer necessary! */ /* must be called before any other calls */ @@ -159,19 +173,22 @@ NiFpga_Status closeMpagFpgaSession(NiFpga_Session session) { status = NiFpga_StopFifo(session, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Host SLAVE A stop fifo error\n"); } status = NiFpga_StopFifo(session, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_B); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Host SLAVE B stop fifo error\n"); } status = NiFpga_StopFifo(session, NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_C); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Host SLAVE C stop fifo error\n"); } @@ -191,7 +208,8 @@ NiFpga_Status closeMpagFpgaSession(NiFpga_Session session) { NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, float freq, uint16_t highStrobeTick, - const int32_t *chanAOmap) { + const int32_t *chanAOmap) +{ NiFpga_Status status = NiFpga_Status_Success; uint16_t acqPeriod; @@ -207,7 +225,8 @@ NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, NiFpga_WriteBool(session, NiFpga_MainFPGA_9159_ControlBool_ForceLocal, clockMode)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error setting closk mode"); return -1; } @@ -220,7 +239,8 @@ NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, NiFpga_MainFPGA_9159_ControlU16_FrameStrobePerioduSec, acqPeriod)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting slave acquisition frequency"); return -1; } @@ -232,7 +252,8 @@ NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, NiFpga_MainFPGA_9159_ControlU16_HighPhaseFrameStrobeDurationTicks, highStrobeTick)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error Setting high strobe Tick count"); return -1; } @@ -254,7 +275,8 @@ NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, /************************* Thread Function ************************************/ -void *acquisitionThreadFPGA(void *args) { +void *acquisitionThreadFPGA(void *args) +{ NiFpga_Status status = NiFpga_Status_Success; int currSize = 0; @@ -277,7 +299,8 @@ void *acquisitionThreadFPGA(void *args) { int slaveIdx = structFpga->slaveIdx; struct_FPGA_ACQ *fpgaAcq = ((struct_FPGA *)args)->structFpgaAcq; - switch (slaveIdx) { + switch (slaveIdx) + { case SLAVE_A: fifoId = NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A; fifoName = "SLAVE A"; @@ -317,7 +340,8 @@ void *acquisitionThreadFPGA(void *args) { readChanSmp = (int *)calloc(NUM_SLAVE_CHANNEL, sizeof(int)); bufReadChanSmp = (int *)calloc(NUM_SLAVE_CHANNEL, sizeof(int)); - for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) { + for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) + { bufReadChanSmp[chan] = bufSize; readChanSmp[chan] = 0; coeffs[chan] = dummyCalibCoeff; @@ -331,9 +355,12 @@ void *acquisitionThreadFPGA(void *args) { status = crioMpagResetFifo(session, fifoName, fifoId); - if (DEBUG) { - for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) { - for (int smp = 0; smp < bufSize; smp++) { + if (DEBUG) + { + for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) + { + for (int smp = 0; smp < bufSize; smp++) + { data[chan + smp * NUM_SLAVE_CHANNEL] = (int16_t)( (chan + 1) * 1000 * sin(2 * 3.14 * smp / slaveDataSamples * 100.) + 500 * slaveIdx); @@ -344,11 +371,13 @@ void *acquisitionThreadFPGA(void *args) { printf("\n"); } - while ((!*(uint8_t *)stopAcq) == 1) { + while ((!*(uint8_t *)stopAcq) == 1) + { readElem = readMpagFifoData(session, fifoName, fifoId, data, slaveDataSamples, stopAcq); - if (readElem == -1 || readElem != slaveDataSamples) { + if (readElem == -1 || readElem != slaveDataSamples) + { // Report error contition only if system in in acquisizione ande the read // data are less than requested if (readElem != slaveDataSamples && (!*(uint8_t *)stopAcq) == 1) @@ -358,10 +387,13 @@ void *acquisitionThreadFPGA(void *args) { } int chanIdx = 0; - for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) { - if (chanState[chan + slaveIdx * NUM_SLAVE_CHANNEL]) { + for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) + { + if (chanState[chan + slaveIdx * NUM_SLAVE_CHANNEL]) + { buffers_s[chanIdx] = new short[bufSize]; - for (int smp = 0; smp < bufSize; smp++) { + for (int smp = 0; smp < bufSize; smp++) + { // if(smp == 0)printf("%s %d buffers_s[%d] = data[%d]\n",fifoName, // chanIdx,(chanIdx + smp * NUM_SLAVE_CHANNEL), (chan + smp * // NUM_SLAVE_CHANNEL)); @@ -378,7 +410,8 @@ void *acquisitionThreadFPGA(void *args) { // for( int chan = 0; chan < nChan; chan++) { chan = slaveCh + slaveIdx * NUM_SLAVE_CHANNEL; - if (chanState[chan]) { + if (chanState[chan]) + { /* for(int smp = 0; smp < 10; smp++) printf(" %d ", buffers_s[slaveCh][smp] ); @@ -418,7 +451,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int numSamples, void *dataNidPtr, int clockNid, float timeIdx0, float period, void *treePtr, void *saveListPtr, void *stopAcq, int shot, - void *resampledNidPtr) { + void *resampledNidPtr) +{ NiFpga_Status status = NiFpga_Status_Success; int currSize = 0; @@ -433,7 +467,7 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int8_t slaveTimeout[NUM_SLAVE] = {0, 0, 0}; SaveList *saveList = (SaveList *) - saveListPtr; // Class to equeu data buffer to save in pulse file + saveListPtr; // Class to equeu data buffer to save in pulse file int *dataNid = (int *)dataNidPtr; // Channel node identifier int *resampledNid = (int *)resampledNidPtr; // Channel node identifier @@ -450,40 +484,54 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, float gains[nChan]; // Delete first all data nids - for (int i = 0; i < nChan; i++) { - try { + for (int i = 0; i < nChan; i++) + { + try + { TreeNode *currNode = new TreeNode(dataNid[i], (Tree *)treePtr); currNode->deleteData(); // Check if resampling - try { + try + { Data *streamNameData = currNode->getExtendedAttribute("STREAM_NAME"); streamNames[i] = streamNameData->getString(); deleteData(streamNameData); - try { + try + { Data *streamGainData = currNode->getExtendedAttribute("STREAM_GAIN"); streamGains[i] = streamGainData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamGains[i] = 1; } - try { + try + { Data *streamOffsetData = currNode->getExtendedAttribute("STREAM_OFFSET"); streamOffsets[i] = streamOffsetData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamOffsets[i] = 0; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamNames[i] = NULL; streamGains[i] = 0; streamOffsets[i] = 0; } delete currNode; - if (resampledNid) { + if (resampledNid) + { currNode = new TreeNode(resampledNid[i], (Tree *)treePtr); currNode->deleteData(); delete currNode; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Error deleting data nodes\n"); } } @@ -501,7 +549,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int streamFactor = (int)(0.1 / period); if (bufSize > streamFactor) streamFactor = bufSize; - else { + else + { if (streamFactor % bufSize != 0) streamFactor = (bufSize + 1) * (streamFactor / bufSize); } @@ -589,7 +638,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int readMpagFifoData(NiFpga_Session session, const char *fifoName, NiFpgaEx_DmaFifo fifoId, int16_t *data, - size_t slaveBufSize, void *stopAcq) { + size_t slaveBufSize, void *stopAcq) +{ NiFpga_Status status = NiFpga_Status_Success; size_t currSize = 0; uint32_t count = 0; @@ -599,17 +649,20 @@ int readMpagFifoData(NiFpga_Session session, const char *fifoName, int16_t *elem; - if (data == NULL) { + if (data == NULL) + { printf("Invalid arguments\n"); return -1; } - if (DEBUG == 1) { + if (DEBUG == 1) + { usleep(2000000); return slaveBufSize; } - while (currSize < slaveBufSize) { + while (currSize < slaveBufSize) + { count++; @@ -617,7 +670,8 @@ int readMpagFifoData(NiFpga_Session session, const char *fifoName, NiFpga_MergeStatus(&status, NiFpga_ReadFifoI16(session, fifoId, data, 0, 0, &nElem)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Read Error\n"); return -1; } @@ -642,7 +696,8 @@ int readMpagFifoData(NiFpga_Session session, const char *fifoName, // Time out is not an error condition. Must be acquired bufSize samples per // channel - if (status != -50400 && NiFpga_IsError(status)) { // Timeout -50400 + if (status != -50400 && NiFpga_IsError(status)) + { // Timeout -50400 printf("\nNiFpga_ReadFifoI16 %s Read Error data (status %d) elem %d\n", fifoName, status, slaveBufSize); return -1; @@ -660,7 +715,8 @@ int readMpagFifoData(NiFpga_Session session, const char *fifoName, return currSize; } -NiFpga_Status startMpagFpga(NiFpga_Session session) { +NiFpga_Status startMpagFpga(NiFpga_Session session) +{ NiFpga_Status status = NiFpga_Status_Success; if (DEBUG == 1) @@ -670,10 +726,12 @@ NiFpga_Status startMpagFpga(NiFpga_Session session) { printf("Running the FPGA...\n"); NiFpga_MergeStatus(&status, NiFpga_Run(session, 0)); - if (NiFpga_IsError(status)) { + if (NiFpga_IsError(status)) + { printf("Error running FPGA\n"); return -1; - } else + } + else printf("OK running FPGA\n"); printf("Start Acquisition ...\n"); @@ -701,7 +759,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int numSamples, void *dataNidPtr, int clockNid, float timeIdx0, float period, void *treePtr, void *saveListPtr, void *stopAcq, int shot, - void *resampledNidPtr) { + void *resampledNidPtr) +{ NiFpga_Status status = NiFpga_Status_Success; int currSize = 0; @@ -716,7 +775,7 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int8_t slaveTimeout[NUM_SLAVE] = {0, 0, 0}; SaveList *saveList = (SaveList *) - saveListPtr; // Class to equeu data buffer to save in pulse file + saveListPtr; // Class to equeu data buffer to save in pulse file int *dataNid = (int *)dataNidPtr; // Channel node identifier int *resampledNid = (int *)resampledNidPtr; // Channel node identifier @@ -733,45 +792,60 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, float gains[nChan]; // Delete first all data nids - for (int i = 0; i < nChan; i++) { - try { + for (int i = 0; i < nChan; i++) + { + try + { TreeNode *currNode = new TreeNode(dataNid[i], (Tree *)treePtr); currNode->deleteData(); // Check if resampling - try { + try + { Data *streamNameData = currNode->getExtendedAttribute("STREAM_NAME"); streamNames[i] = streamNameData->getString(); deleteData(streamNameData); - try { + try + { Data *streamGainData = currNode->getExtendedAttribute("STREAM_GAIN"); streamGains[i] = streamGainData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamGains[i] = 1; } - try { + try + { Data *streamOffsetData = currNode->getExtendedAttribute("STREAM_OFFSET"); streamOffsets[i] = streamOffsetData->getFloat(); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamOffsets[i] = 0; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { streamNames[i] = NULL; streamGains[i] = 0; streamOffsets[i] = 0; } delete currNode; - if (resampledNid) { + if (resampledNid) + { currNode = new TreeNode(resampledNid[i], (Tree *)treePtr); currNode->deleteData(); delete currNode; } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Error deleting data nodes\n"); } } - for (int chan = 0; chan < nChan; chan++) { + for (int chan = 0; chan < nChan; chan++) + { buffers_s[chan] = new short[bufSize]; bufReadChanSmp[chan] = bufSize; readChanSmp[chan] = 0; @@ -786,7 +860,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, int streamFactor = (int)(0.1 / period); if (bufSize > streamFactor) streamFactor = bufSize; - else { + else + { if (streamFactor % bufSize != 0) streamFactor = (bufSize + 1) * (streamFactor / bufSize); } @@ -817,63 +892,77 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, startMpagFpga(session); /**************************************************************/ - while ((!*(uint8_t *)stopAcq) == 1) { + while ((!*(uint8_t *)stopAcq) == 1) + { readElem = readMpagFifoData( session, "SLAVE A", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_A, &data[0], slaveDataSamples); - if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) { + if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) + { if (readElem != slaveDataSamples) printf("SLAVE A Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); break; } - if (readElem == -2) { // timeout + if (readElem == -2) + { // timeout printf("SLAVE A Fifo reading timeout\n"); slaveTimeout[0] = 1; - } else + } + else printf("SLAVE A Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); readElem = readMpagFifoData( session, "SLAVE B", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_B, &data[slaveDataSamples], slaveDataSamples); - if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) { + if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) + { if (readElem != slaveDataSamples) printf("SLAVE B Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); break; } - if (readElem == -2) { // timeout + if (readElem == -2) + { // timeout printf("SLAVE B Fifo reading timeout\n"); slaveTimeout[1] = 1; - } else + } + else printf("SLAVE B Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); readElem = readMpagFifoData( session, "SLAVE C", NiFpga_MainFPGA_9159_TargetToHostFifoI16_FIFOTOPC_C, &data[2 * slaveDataSamples], slaveDataSamples); - if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) { + if (readElem != -2 && (readElem == -1 || readElem != slaveDataSamples)) + { if (readElem != slaveDataSamples) printf("SLAVE C Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); break; } - if (readElem == -2) { // timeout + if (readElem == -2) + { // timeout printf("SLAVE C Fifo reading timeout\n"); slaveTimeout[2] = 1; - } else + } + else printf("SLAVE C Fifo reading samples requested %d read %d\n", slaveDataSamples, readElem); int chanIdx = 0; - for (int slave = 0; slave < NUM_SLAVE; slave++) { + for (int slave = 0; slave < NUM_SLAVE; slave++) + { if (slaveTimeout[slave]) continue; - for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) { - if (chanState[chan + slave * NUM_SLAVE_CHANNEL]) { - for (int smp = 0; smp < bufSize; smp++) { + for (int chan = 0; chan < NUM_SLAVE_CHANNEL; chan++) + { + if (chanState[chan + slave * NUM_SLAVE_CHANNEL]) + { + for (int smp = 0; smp < bufSize; smp++) + { // if(smp == 0)printf("%d %d buffers_s[%d] = data[%d]\n",slave, // chan,(chanIdx + slave * NUM_SLAVE_CHANNEL), (chan + smp * // NUM_SLAVE_CHANNEL + slave * slaveDataSamples)); @@ -887,7 +976,8 @@ int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, printf("OK\n"); - for (int slave = 0; slave < NUM_SLAVE; slave++) { + for (int slave = 0; slave < NUM_SLAVE; slave++) + { if (slaveTimeout[slave]) continue; for (int slaveCh = 0; slaveCh < NUM_SLAVE_CHANNEL; slaveCh++) diff --git a/device_support/national/cRioMPAGfunction.h b/device_support/national/cRioMPAGfunction.h index a6231c276e..be33a1a410 100644 --- a/device_support/national/cRioMPAGfunction.h +++ b/device_support/national/cRioMPAGfunction.h @@ -27,36 +27,39 @@ #define MAX_FPGA_READ_BUF_SIZE 40000 static const char *simb = "|/-\\"; -extern "C" { -NiFpga_Status crioMpagInitFifo(NiFpga_Session session, const char *fifoName, - NiFpgaEx_DmaFifo fifoId, size_t fifoDepthSize); -NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, - NiFpgaEx_DmaFifo fifoId); -NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, - size_t fifoDepthSize); -NiFpga_Status closeMpagFpgaSession(NiFpga_Session session); -NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, - float freq, uint16_t highStrobeTick, - const int32_t *chanAOmap); -int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, - int *chanState, int bufSize, int segmentSize, - int numSamples, void *dataNidPtr, int clockNid, - float timeIdx0, float period, void *treePtr, - void *saveListPtr, void *stopAcq, int shot, - void *resampledNidPtr); -int readMpagFifoData(NiFpga_Session session, const char *fifoName, - NiFpgaEx_DmaFifo fifoId, int16_t *data, - size_t slaveBufSize, void *stopAcq); -NiFpga_Status startMpagFpga(NiFpga_Session session); +extern "C" +{ + NiFpga_Status crioMpagInitFifo(NiFpga_Session session, const char *fifoName, + NiFpgaEx_DmaFifo fifoId, size_t fifoDepthSize); + NiFpga_Status crioMpagResetFifo(NiFpga_Session session, const char *fifoName, + NiFpgaEx_DmaFifo fifoId); + NiFpga_Status crioMpagInit(NiFpga_Session *session, const char *cRioId, + size_t fifoDepthSize); + NiFpga_Status closeMpagFpgaSession(NiFpga_Session session); + NiFpga_Status setMpagAcqParam(NiFpga_Session session, uint8_t clockMode, + float freq, uint16_t highStrobeTick, + const int32_t *chanAOmap); + int mpag_readAndSaveAllChannels(NiFpga_Session session, int nChan, + int *chanState, int bufSize, int segmentSize, + int numSamples, void *dataNidPtr, int clockNid, + float timeIdx0, float period, void *treePtr, + void *saveListPtr, void *stopAcq, int shot, + void *resampledNidPtr); + int readMpagFifoData(NiFpga_Session session, const char *fifoName, + NiFpgaEx_DmaFifo fifoId, int16_t *data, + size_t slaveBufSize, void *stopAcq); + NiFpga_Status startMpagFpga(NiFpga_Session session); } -typedef enum { +typedef enum +{ SLAVE_A, SLAVE_B, SLAVE_C, } enum_FPGA; -typedef struct t_struct_FPGA_ACQ { +typedef struct t_struct_FPGA_ACQ +{ NiFpga_Session session; int bufSize; int *chanState; @@ -78,7 +81,8 @@ typedef struct t_struct_FPGA_ACQ { int streamFactor; } struct_FPGA_ACQ; -typedef struct t_struct_FPGA { +typedef struct t_struct_FPGA +{ enum_FPGA slaveIdx; struct_FPGA_ACQ *structFpgaAcq; sem_t semThreadStart; diff --git a/device_support/national/generateWave-cotb.cpp b/device_support/national/generateWave-cotb.cpp index eae4769066..e785f5683c 100644 --- a/device_support/national/generateWave-cotb.cpp +++ b/device_support/national/generateWave-cotb.cpp @@ -17,7 +17,8 @@ #define SAWTOOTH 4 static void createSawtoothWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete Sawtooth period in volts @@ -29,7 +30,8 @@ static void createSawtoothWaveform(int number_of_samples, double offset, } static void createTriangularWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete triangular period in volts @@ -47,7 +49,8 @@ static void createTriangularWaveform(int number_of_samples, double offset, } static void createSquareWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete square period in volts @@ -62,7 +65,8 @@ static void createSquareWaveform(int number_of_samples, double offset, } static void createSinusoidalWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete sinus period in volts @@ -76,7 +80,8 @@ static void createSinusoidalWaveform(int number_of_samples, double offset, uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, uint8_t channel, double offset, double level, uint32_t waverate, - int waveType) { + int waveType) +{ int silent = 0; int retval = 0; int number_of_channels = 4; @@ -102,7 +107,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, float *write_array[number_of_channels]; xseries_ao_conf_t ao_conf; - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { write_array[i] = (float *)calloc(1, sizeof(float) * number_of_samples); } @@ -111,7 +117,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* open AO segment file descriptor */ sprintf(str, "%s.%u.ao", device_name, selectedCard); ao_fd = open(str, O_RDWR); - if (ao_fd <= 0) { + if (ao_fd <= 0) + { if (!silent) printf("Could not open AO segment! %s \n", strerror(errno)); retval = -1; @@ -123,7 +130,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* reset AO segment */ retval = xseries_reset_ao(ao_fd); - if (retval) { + if (retval) + { if (!silent) printf("Error reseting card!\n"); goto out_6368; @@ -143,7 +151,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_EXTERNAL_GATE_DISABLED, // No external pause signal XSERIES_AO_POLARITY_RISING_EDGE, // Don't care 0); // Disable - if (retval) { + if (retval) + { if (!silent) printf("Error setting external gate!\n"); goto out_6368; @@ -157,7 +166,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_START_TRIGGER_SW_PULSE, // Set the line to software-driven XSERIES_AO_POLARITY_RISING_EDGE, // Make line active on rising... 1); // ...edge (not high level) - if (retval) { + if (retval) + { if (!silent) printf("Error setting start trigger!\n"); goto out_6368; @@ -182,7 +192,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_UPDATE_COUNTER_UI_TC, // Derive the clock line from the Update // Interval Terminal Count XSERIES_AO_POLARITY_RISING_EDGE); // Make the line active on rising edge - if (retval) { + if (retval) + { if (!silent) printf("Error setting update counter!\n"); goto out_6368; @@ -194,24 +205,28 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_TB3, // Source the Update // Interval from the // internal timebase - XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising - // edge - update_period_divisor, // Number of clock intervals between successive - // updates - 2 // Number of clock intervals after the start trigger before the first - // update + XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising + // edge + update_period_divisor, // Number of clock intervals between successive + // updates + 2 // Number of clock intervals after the start trigger before the first + // update ); - if (retval) { + if (retval) + { if (!silent) printf("Error setting update interval counter!\n"); goto out_6368; } /* Add channels */ - for (i = 0; i < number_of_channels; i++) { - if (i == channel) { + for (i = 0; i < number_of_channels; i++) + { + if (i == channel) + { retval = xseries_add_ao_channel(&ao_conf, i, XSERIES_OUTPUT_RANGE_10V); - if (retval) { + if (retval) + { if (!silent) printf("Cannot add AI channel %d to configuration!\n", i); goto out_6368; @@ -221,7 +236,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* load configuration to the device */ retval = xseries_load_ao_conf(ao_fd, ao_conf); - if (retval) { + if (retval) + { if (!silent) printf("Cannot load AO configuration! %s (%d)\n", strerror(errno), errno); goto out_6368; @@ -230,9 +246,11 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* wait for the AO devices */ sleep(1); - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { - switch (waveType) { + switch (waveType) + { case TRIANGULAR: createTriangularWaveform(number_of_samples, offset, level, write_array[i]); @@ -251,13 +269,16 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, } /* Open channels */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { sprintf(str, "%s.%u.ao.%u", device_name, selectedCard, i); - if (i == channel) { + if (i == channel) + { printf("%s\n", str); ao_chan_fd[i] = open(str, O_RDWR | O_NONBLOCK); - if (ao_chan_fd[i] < 0) { + if (ao_chan_fd[i] < 0) + { if (!silent) printf("Cannot add AO channel %d to configuration!\n", i); goto out_6368; @@ -266,14 +287,18 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, } /* Write samples */ - for (i = 0; i < number_of_samples; i++) { - for (k = 0; k < number_of_channels; k++) { - if (k == channel) { + for (i = 0; i < number_of_samples; i++) + { + for (k = 0; k < number_of_channels; k++) + { + if (k == channel) + { // Write is not blocking !!! retval = xseries_write_ao(ao_chan_fd[k], &write_array[k][i], 1); // if( i < 10 ) // printf("write_array[%d][%d] = %f\n", k, i, write_array[k][i]); - if (retval == -1 && errno != EAGAIN) { + if (retval == -1 && errno != EAGAIN) + { if (!silent) printf("Error writing samples to FIFO buffer!\n"); goto out_6368; @@ -284,14 +309,16 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* put segment in started state */ retval = xseries_start_ao(ao_fd); - if (retval) { + if (retval) + { printf("Cannot start AO segment! %s (%d)\n", strerror(errno), errno); goto out_6368; } /* pulse start trigger */ retval = xseries_pulse_ao(ao_fd, XSERIES_START_TRIGGER); - if (retval) { + if (retval) + { printf("Error generating start pulse!\n"); goto out_6368; } @@ -307,7 +334,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, xseries_stop_ao(ao_fd); /* close all used file descriptors */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { if (i == channel) close(ao_chan_fd[i]); } @@ -321,7 +349,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* close card's file descriptor */ close(dev_fd); - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { free(write_array[i]); } @@ -331,7 +360,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, uint8_t channel, double offset, double level, uint32_t waverate, - int waveType) { + int waveType) +{ uint32_t retval = 0; pxi6259_ao_conf_t ao_conf; @@ -358,7 +388,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // get configuration file descriptor sprintf(str, "%s.%d.ao", RESOURCE_NAME_DAQ, selectedCard); fdConfig = open(str, O_RDWR | O_NONBLOCK); - if (fdConfig < 0) { + if (fdConfig < 0) + { printf("Error Opening Device! fd: %d\n", fdConfig); return -1; } @@ -371,7 +402,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, } */ - switch (waveType) { + switch (waveType) + { case TRIANGULAR: createTriangularWaveform(number_of_samples, offset, level, scaledWriteArray); @@ -405,7 +437,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, return -1; retval = pxi6259_load_ao_conf(fdConfig, &ao_conf); - if (retval) { + if (retval) + { printf("err: load task. retval: %x\n", retval * -1); goto out_6259; } @@ -415,13 +448,15 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // Open channels sprintf(str, "%s.%d.ao.%d", RESOURCE_NAME_DAQ, selectedCard, channel); fdChannel = open(str, O_RDWR | O_NONBLOCK); - if (fdChannel < 0) { + if (fdChannel < 0) + { printf("Error Opening Channel! FD: %d\n", fdChannel); return -1; } retval = pxi6259_write_ao(fdChannel, scaledWriteArray, number_of_samples); - if (retval != number_of_samples) { + if (retval != number_of_samples) + { printf("err: writing. retval: %d\n", retval); goto out_6259; } @@ -429,7 +464,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, close(fdChannel); retval = pxi6259_start_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: Starting task. retval: %d\n", retval); return -1; } @@ -463,18 +499,21 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // Open channels sprintf(str, "%s.%d.ao.%d", RESOURCE_NAME_DAQ, selectedCard, channel); fdChannel = open(str, O_RDWR | O_NONBLOCK); - if (fdChannel < 0) { + if (fdChannel < 0) + { printf("Error Opening Channel! FD: %d\n", fdChannel); return -1; } retval = pxi6259_write_ao(fdChannel, scaledWriteArray, number_of_samples); - if (retval != number_of_samples) { + if (retval != number_of_samples) + { printf("err: writing. retval: %d\n", retval); } retval = pxi6259_start_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: Starting task. retval: %d\n", retval); } @@ -489,7 +528,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, return 0; } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int retval = 0; uint8_t selectedCard = 0; uint8_t channel = 0; @@ -501,7 +541,8 @@ int main(int argc, char **argv) { const char *device; int waveType; - if (argc == 8 && (!strcmp(argv[1], "6368") || !strcmp(argv[1], "6259"))) { + if (argc == 8 && (!strcmp(argv[1], "6368") || !strcmp(argv[1], "6259"))) + { device = argv[1]; selectedCard = atoi(argv[2]); channel = atoi(argv[3]); @@ -516,8 +557,9 @@ int main(int argc, char **argv) { waveType = SINUSOIDAL; else if (strcmp(argv[7], "Sa") == 0) waveType = SAWTOOTH; - - } else if (argc == 1) { + } + else if (argc == 1) + { device = "6368"; selectedCard = 0; channel = 0; @@ -527,8 +569,9 @@ int main(int argc, char **argv) { waveType = TRIANGULAR; printf("Default values: device: 6368 card: 0, channels: 0, MinValue : 0.0, " "MaxValue : 5.0, ferquency : 100, Wave : Triangular\n\n"); - - } else { + } + else + { printf("\nPlease define arguments for AO waveform signal generation " "example! Run as:\n"); printf("\n./generateTriangularWave [device {6368/6259}] [card] [channel " @@ -546,15 +589,18 @@ int main(int argc, char **argv) { printf("Offset %f level %f\n", offset, level); - if (!strcmp(device, "6368")) { + if (!strcmp(device, "6368")) + { retval = generateWaveformOnOneChannel_6368(selectedCard, channel, offset, level, frequency, waveType); } - if (!strcmp(device, "6259")) { + if (!strcmp(device, "6259")) + { retval = generateWaveformOnOneChannel_6259(selectedCard, channel, offset, level, frequency, waveType); } - if (retval) { + if (retval) + { printf("Error generating waveform signal\n"); return -1; } diff --git a/device_support/national/generateWave.cpp b/device_support/national/generateWave.cpp index 2620dcbdcf..5bd1c9dbf2 100644 --- a/device_support/national/generateWave.cpp +++ b/device_support/national/generateWave.cpp @@ -41,7 +41,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SAWTOOTH 4 static void createSawtoothWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete Sawtooth period in volts @@ -53,7 +54,8 @@ static void createSawtoothWaveform(int number_of_samples, double offset, } static void createTriangularWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete triangular period in volts @@ -71,7 +73,8 @@ static void createTriangularWaveform(int number_of_samples, double offset, } static void createSquareWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete square period in volts @@ -86,7 +89,8 @@ static void createSquareWaveform(int number_of_samples, double offset, } static void createSinusoidalWaveform(int number_of_samples, double offset, - double level, float *buf) { + double level, float *buf) +{ int i; // create one complete sinus period in volts @@ -100,7 +104,8 @@ static void createSinusoidalWaveform(int number_of_samples, double offset, uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, uint8_t channel, double offset, double level, uint32_t waverate, - int waveType) { + int waveType) +{ int silent = 0; int retval = 0; int number_of_channels = 4; @@ -126,7 +131,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, float *write_array[number_of_channels]; xseries_ao_conf_t ao_conf; - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { write_array[i] = (float *)calloc(1, sizeof(float) * number_of_samples); } @@ -135,7 +141,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* open AO segment file descriptor */ sprintf(str, "%s.%u.ao", device_name, selectedCard); ao_fd = open(str, O_RDWR); - if (ao_fd <= 0) { + if (ao_fd <= 0) + { if (!silent) printf("Could not open AO segment! %s \n", strerror(errno)); retval = -1; @@ -147,7 +154,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* reset AO segment */ retval = xseries_reset_ao(ao_fd); - if (retval) { + if (retval) + { if (!silent) printf("Error reseting card!\n"); goto out_6368; @@ -167,7 +175,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_EXTERNAL_GATE_DISABLED, // No external pause signal XSERIES_AO_POLARITY_RISING_EDGE, // Don't care 0); // Disable - if (retval) { + if (retval) + { if (!silent) printf("Error setting external gate!\n"); goto out_6368; @@ -181,7 +190,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_START_TRIGGER_SW_PULSE, // Set the line to software-driven XSERIES_AO_POLARITY_RISING_EDGE, // Make line active on rising... 1); // ...edge (not high level) - if (retval) { + if (retval) + { if (!silent) printf("Error setting start trigger!\n"); goto out_6368; @@ -206,7 +216,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_AO_UPDATE_COUNTER_UI_TC, // Derive the clock line from the Update // Interval Terminal Count XSERIES_AO_POLARITY_RISING_EDGE); // Make the line active on rising edge - if (retval) { + if (retval) + { if (!silent) printf("Error setting update counter!\n"); goto out_6368; @@ -218,24 +229,28 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_TB3, // Source the Update // Interval from the // internal timebase - XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising - // edge - update_period_divisor, // Number of clock intervals between successive - // updates - 2 // Number of clock intervals after the start trigger before the first - // update + XSERIES_OUTTIMER_POLARITY_RISING_EDGE, // Make the line active on rising + // edge + update_period_divisor, // Number of clock intervals between successive + // updates + 2 // Number of clock intervals after the start trigger before the first + // update ); - if (retval) { + if (retval) + { if (!silent) printf("Error setting update interval counter!\n"); goto out_6368; } /* Add channels */ - for (i = 0; i < number_of_channels; i++) { - if (i == channel) { + for (i = 0; i < number_of_channels; i++) + { + if (i == channel) + { retval = xseries_add_ao_channel(&ao_conf, i, XSERIES_OUTPUT_RANGE_10V); - if (retval) { + if (retval) + { if (!silent) printf("Cannot add AI channel %d to configuration!\n", i); goto out_6368; @@ -245,7 +260,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* load configuration to the device */ retval = xseries_load_ao_conf(ao_fd, ao_conf); - if (retval) { + if (retval) + { if (!silent) printf("Cannot load AO configuration! %s (%d)\n", strerror(errno), errno); goto out_6368; @@ -254,9 +270,11 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* wait for the AO devices */ sleep(1); - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { - switch (waveType) { + switch (waveType) + { case TRIANGULAR: createTriangularWaveform(number_of_samples, offset, level, write_array[i]); @@ -275,13 +293,16 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, } /* Open channels */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { sprintf(str, "%s.%u.ao.%u", device_name, selectedCard, i); - if (i == channel) { + if (i == channel) + { printf("%s\n", str); ao_chan_fd[i] = open(str, O_RDWR | O_NONBLOCK); - if (ao_chan_fd[i] < 0) { + if (ao_chan_fd[i] < 0) + { if (!silent) printf("Cannot add AO channel %d to configuration!\n", i); goto out_6368; @@ -290,14 +311,18 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, } /* Write samples */ - for (i = 0; i < number_of_samples; i++) { - for (k = 0; k < number_of_channels; k++) { - if (k == channel) { + for (i = 0; i < number_of_samples; i++) + { + for (k = 0; k < number_of_channels; k++) + { + if (k == channel) + { // Write is not blocking !!! retval = xseries_write_ao(ao_chan_fd[k], &write_array[k][i], 1); // if( i < 10 ) // printf("write_array[%d][%d] = %f\n", k, i, write_array[k][i]); - if (retval == -1 && errno != EAGAIN) { + if (retval == -1 && errno != EAGAIN) + { if (!silent) printf("Error writing samples to FIFO buffer!\n"); goto out_6368; @@ -308,14 +333,16 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* put segment in started state */ retval = xseries_start_ao(ao_fd); - if (retval) { + if (retval) + { printf("Cannot start AO segment! %s (%d)\n", strerror(errno), errno); goto out_6368; } /* pulse start trigger */ retval = xseries_pulse_ao(ao_fd, XSERIES_START_TRIGGER); - if (retval) { + if (retval) + { printf("Error generating start pulse!\n"); goto out_6368; } @@ -331,7 +358,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, xseries_stop_ao(ao_fd); /* close all used file descriptors */ - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { if (i == channel) close(ao_chan_fd[i]); } @@ -345,7 +373,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, /* close card's file descriptor */ close(dev_fd); - for (i = 0; i < number_of_channels; i++) { + for (i = 0; i < number_of_channels; i++) + { free(write_array[i]); } @@ -355,7 +384,8 @@ uint32_t generateWaveformOnOneChannel_6368(uint8_t selectedCard, uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, uint8_t channel, double offset, double level, uint32_t waverate, - int waveType) { + int waveType) +{ uint32_t retval = 0; pxi6259_ao_conf_t ao_conf; @@ -382,7 +412,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // get configuration file descriptor sprintf(str, "%s.%d.ao", RESOURCE_NAME_DAQ, selectedCard); fdConfig = open(str, O_RDWR | O_NONBLOCK); - if (fdConfig < 0) { + if (fdConfig < 0) + { printf("Error Opening Device! fd: %d\n", fdConfig); return -1; } @@ -395,7 +426,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, } */ - switch (waveType) { + switch (waveType) + { case TRIANGULAR: createTriangularWaveform(number_of_samples, offset, level, scaledWriteArray); @@ -429,7 +461,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, return -1; retval = pxi6259_load_ao_conf(fdConfig, &ao_conf); - if (retval) { + if (retval) + { printf("err: load task. retval: %x\n", retval * -1); goto out_6259; } @@ -439,13 +472,15 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // Open channels sprintf(str, "%s.%d.ao.%d", RESOURCE_NAME_DAQ, selectedCard, channel); fdChannel = open(str, O_RDWR | O_NONBLOCK); - if (fdChannel < 0) { + if (fdChannel < 0) + { printf("Error Opening Channel! FD: %d\n", fdChannel); return -1; } retval = pxi6259_write_ao(fdChannel, scaledWriteArray, number_of_samples); - if (retval != number_of_samples) { + if (retval != number_of_samples) + { printf("err: writing. retval: %d\n", retval); goto out_6259; } @@ -453,7 +488,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, close(fdChannel); retval = pxi6259_start_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: Starting task. retval: %d\n", retval); return -1; } @@ -487,18 +523,21 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, // Open channels sprintf(str, "%s.%d.ao.%d", RESOURCE_NAME_DAQ, selectedCard, channel); fdChannel = open(str, O_RDWR | O_NONBLOCK); - if (fdChannel < 0) { + if (fdChannel < 0) + { printf("Error Opening Channel! FD: %d\n", fdChannel); return -1; } retval = pxi6259_write_ao(fdChannel, scaledWriteArray, number_of_samples); - if (retval != number_of_samples) { + if (retval != number_of_samples) + { printf("err: writing. retval: %d\n", retval); } retval = pxi6259_start_ao(fdConfig); - if (retval) { + if (retval) + { printf("err: Starting task. retval: %d\n", retval); } @@ -513,7 +552,8 @@ uint32_t generateWaveformOnOneChannel_6259(uint8_t selectedCard, return 0; } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int retval = 0; uint8_t selectedCard = 0; uint8_t channel = 0; @@ -525,7 +565,8 @@ int main(int argc, char **argv) { const char *device; int waveType; - if (argc == 8 && (!strcmp(argv[1], "6368") || !strcmp(argv[1], "6259"))) { + if (argc == 8 && (!strcmp(argv[1], "6368") || !strcmp(argv[1], "6259"))) + { device = argv[1]; selectedCard = atoi(argv[2]); channel = atoi(argv[3]); @@ -540,8 +581,9 @@ int main(int argc, char **argv) { waveType = SINUSOIDAL; else if (strcmp(argv[7], "Sa") == 0) waveType = SAWTOOTH; - - } else if (argc == 1) { + } + else if (argc == 1) + { device = "6368"; selectedCard = 0; channel = 0; @@ -551,8 +593,9 @@ int main(int argc, char **argv) { waveType = TRIANGULAR; printf("Default values: device: 6368 card: 0, channels: 0, MinValue : 0.0, " "MaxValue : 5.0, ferquency : 100, Wave : Triangular\n\n"); - - } else { + } + else + { printf("\nPlease define arguments for AO waveform signal generation " "example! Run as:\n"); printf("\n./generateTriangularWave [device {6368/6259}] [card] [channel " @@ -570,15 +613,18 @@ int main(int argc, char **argv) { printf("Offset %f level %f\n", offset, level); - if (!strcmp(device, "6368")) { + if (!strcmp(device, "6368")) + { retval = generateWaveformOnOneChannel_6368(selectedCard, channel, offset, level, frequency, waveType); } - if (!strcmp(device, "6259")) { + if (!strcmp(device, "6259")) + { retval = generateWaveformOnOneChannel_6259(selectedCard, channel, offset, level, frequency, waveType); } - if (retval) { + if (retval) + { printf("Error generating waveform signal\n"); return -1; } diff --git a/device_support/national/print_device_info.cpp b/device_support/national/print_device_info.cpp index 2a76ac4aed..58177059f3 100644 --- a/device_support/national/print_device_info.cpp +++ b/device_support/national/print_device_info.cpp @@ -15,12 +15,14 @@ #include #include -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int retval, fd; xseries_device_info_t devinfo; uint32_t serial_number; - if (argc < 2) { + if (argc < 2) + { printf("Usage: %s \n", argv[0]); printf("Example:\n %s /dev/pxie-6368.0 \n", argv[0]); printf("Example:\n %s /dev/pxi6259.0 \n", argv[0]); @@ -29,15 +31,18 @@ int main(int argc, char **argv) { /* Open device file descriptor */ fd = open(argv[1], O_RDWR); - if (fd < 0) { + if (fd < 0) + { printf("Err, opening device node: %s\n", strerror(errno)); exit(EXIT_FAILURE); } - if (strstr(argv[1], "6368") != 0) { + if (strstr(argv[1], "6368") != 0) + { /* Get device info */ retval = xseries_get_device_info(fd, &devinfo); - if (retval) { + if (retval) + { printf("Err, cannot read device info: %s\n", strerror(errno)); exit(EXIT_FAILURE); } @@ -52,11 +57,13 @@ int main(int argc, char **argv) { printf(" Number of DIO lines: %d\n", devinfo.port0_length); } - if (strstr(argv[1], "6259") != 0) { + if (strstr(argv[1], "6259") != 0) + { /* Get device info */ retval = xseries_get_device_info(fd, &devinfo); retval = pxi6259_get_board_serial_number(fd, &serial_number); - if (retval) { + if (retval) + { printf("Err, cannot read device info: %s\n", strerror(errno)); exit(EXIT_FAILURE); } diff --git a/device_support/national/probeTermControl.cpp b/device_support/national/probeTermControl.cpp index 0750dfecf3..597c3775d5 100644 --- a/device_support/national/probeTermControl.cpp +++ b/device_support/national/probeTermControl.cpp @@ -39,7 +39,8 @@ using namespace MDSplus; #define DEVICE_FILE "/dev/pxi6259" -void usage(char *name) { +void usage(char *name) +{ printf(" Usage: %s " " \n" "Example: %s 0 10 11 10 0 1\n", @@ -47,7 +48,8 @@ void usage(char *name) { } int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, - uint32_t outChanOnOff) { + uint32_t outChanOnOff) +{ char filename[256]; int i; pxi6259_ao_conf_t aoConfig; @@ -56,7 +58,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // open AO file descriptor sprintf(filename, "%s.%u.ao", DEVICE_FILE, deviceNum); devFD = open(filename, O_RDWR); - if (devFD < 0) { + if (devFD < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -65,7 +68,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, aoConfig = pxi6259_create_ao_conf(); // configure AO channel reference - if (pxi6259_add_ao_channel(&aoConfig, outChanRef, AO_DAC_POLARITY_BIPOLAR)) { + if (pxi6259_add_ao_channel(&aoConfig, outChanRef, AO_DAC_POLARITY_BIPOLAR)) + { fprintf(stderr, "Failed to configure channel %d reference! %s\n", outChanRef, strerror(errno)); return -1; @@ -73,7 +77,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // configure AO channel on/off if (pxi6259_add_ao_channel(&aoConfig, outChanOnOff, - AO_DAC_POLARITY_BIPOLAR)) { + AO_DAC_POLARITY_BIPOLAR)) + { fprintf(stderr, "Failed to configure channel %d reference! : %s\n", outChanOnOff, strerror(errno)); return -1; @@ -81,20 +86,23 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // enable signal generation if (pxi6259_set_ao_attribute(&aoConfig, AO_SIGNAL_GENERATION, - AO_SIGNAL_GENERATION_STATIC)) { + AO_SIGNAL_GENERATION_STATIC)) + { fprintf(stderr, "Failed to enable generating static signal!: %s\n", strerror(errno)); return -1; } // set continuous mode - if (pxi6259_set_ao_attribute(&aoConfig, AO_CONTINUOUS, 0)) { + if (pxi6259_set_ao_attribute(&aoConfig, AO_CONTINUOUS, 0)) + { fprintf(stderr, "Failed to set continuous mode!: %s\n", strerror(errno)); return -1; } // load AO configuration and let it apply - if (pxi6259_load_ao_conf(devFD, &aoConfig)) { + if (pxi6259_load_ao_conf(devFD, &aoConfig)) + { fprintf(stderr, "Failed to load output configuration! : %s\n", strerror(errno)); return -1; @@ -103,7 +111,8 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, // open file descriptor for each AO channel sprintf(filename, "%s.%u.ao.%u", DEVICE_FILE, deviceNum, outChanRef); chanOutFD[0] = open(filename, O_RDWR | O_NONBLOCK); - if (*chanOutFD < 0) { + if (*chanOutFD < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", outChanRef, strerror(errno)); return -1; @@ -111,14 +120,16 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, sprintf(filename, "%s.%u.ao.%u", DEVICE_FILE, deviceNum, outChanOnOff); chanOutFD[1] = open(filename, O_RDWR | O_NONBLOCK); - if (*chanOutFD < 0) { + if (*chanOutFD < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", outChanOnOff, strerror(errno)); return -1; } // start AO segment (signal generation) - if (pxi6259_start_ao(devFD)) { + if (pxi6259_start_ao(devFD)) + { fprintf(stderr, "Failed to start segment!n"); return -1; } @@ -127,9 +138,10 @@ int configureOutput(int *chanOutFD, uint32_t deviceNum, uint32_t outChanRef, } int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], - double frequency, int numChan) { - int diffMapChannel[16] = {-1, 0, 1, 2, 3, 4, 5, 6, - 7, 16, 17, 18, 19, 20.21, 22, 23}; + double frequency, int numChan) +{ + int diffMapChannel[16] = {-1, 0, 1, 2, 3, 4, 5, 6, + 7, 16, 17, 18, 19, 20.21, 22, 23}; char filename[256]; int i; pxi6259_ai_conf_t aiConfig; @@ -139,7 +151,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], // open AI file descriptor sprintf(filename, "%s.%u.ai", DEVICE_FILE, deviceNum); devFD = open(filename, O_RDWR); - if (devFD < 0) { + if (devFD < 0) + { fprintf(stderr, "Failed to open device: %s\n", strerror(errno)); return -1; } @@ -148,7 +161,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], aiConfig = pxi6259_create_ai_conf(); // configure AI channels 0 - 5 V differential - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { if (pxi6259_add_ai_channel(&aiConfig, diffMapChannel[inChan[i]], AI_POLARITY_BIPOLAR, 2, @@ -171,24 +185,28 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], period = (int)(20000000. / frequency); if (pxi6259_set_ai_sample_clk( &aiConfig, period, 3, AI_SAMPLE_SELECT_SI_TC, - AI_SAMPLE_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)) { + AI_SAMPLE_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)) + { fprintf(stderr, "Failed to configure AI sampling clock!\n"); return -1; } // load AI configuration and let it apply - if (pxi6259_load_ai_conf(devFD, &aiConfig)) { + if (pxi6259_load_ai_conf(devFD, &aiConfig)) + { fprintf(stderr, "Failed to load input configuration!\n"); return -1; } // open file descriptor for each AI channel - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { sprintf(filename, "%s.%u.ai.%u", DEVICE_FILE, deviceNum, diffMapChannel[inChan[i]]); printf("%s\n", filename); chanInFd[i] = open(filename, O_RDWR | O_NONBLOCK); - if (chanInFd[i] < 0) { + if (chanInFd[i] < 0) + { fprintf(stderr, "Failed to open channel %u: %s\n", inChan[i], strerror(errno)); return -1; @@ -196,7 +214,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], } // start AI segment (data acquisition) - if (pxi6259_start_ai(devFD)) { + if (pxi6259_start_ai(devFD)) + { fprintf(stderr, "Failed to start data acquisition!\n"); return -1; } @@ -206,7 +225,8 @@ int configureInput(int *chanInFd, uint32_t deviceNum, uint32_t inChan[], return devFD; } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ static char log[5] = "|/-\\"; static int count = 0; @@ -231,7 +251,8 @@ int main(int argc, char **argv) { float ZERO_VOLT = 0; float FIVE_VOLT = 5.; - if (argc != 7) { + if (argc != 7) + { usage(argv[0]); return 1; } @@ -249,18 +270,21 @@ int main(int argc, char **argv) { sem_t *wakeSem_id; pauseSem_id = sem_open("PauseControl", O_CREAT, 0666, 0); - if (pauseSem_id == SEM_FAILED) { + if (pauseSem_id == SEM_FAILED) + { perror("pause Control sem_open"); exit(1); } wakeSem_id = sem_open("WakeControl", O_CREAT, 0666, 1); - if (pauseSem_id == SEM_FAILED) { + if (pauseSem_id == SEM_FAILED) + { perror("wake Control sem_open"); exit(1); } - try { + try + { time_t rawtime; struct tm *timeinfo; char strShot[256]; @@ -281,31 +305,40 @@ int main(int argc, char **argv) { // strShot, dataFile); FILE *fd = fopen(dataFile, "r"); - if (!fd) { + if (!fd) + { t = new Tree((char *)"ipp_tc_trend", -1); t->createPulse(shot); - } else { + } + else + { fclose(fd); } t = new Tree((char *)"ipp_tc_trend", shot); - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { char path[256]; sprintf(path, "\\IPP_TC_TREND::TC%d", inChan[i]); printf("NODO %s \n", path); node[i] = t->getNode(path); } - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("%s\n", exc->what()); exit(1); } - while (!error) { + while (!error) + { - if (!wakeState) { + if (!wakeState) + { printf("WAIT\n"); - if (sem_wait(pauseSem_id) < 0) { + if (sem_wait(pauseSem_id) < 0) + { perror("Control sem_wait"); return -1; } @@ -313,13 +346,15 @@ int main(int argc, char **argv) { } if ((devInFD = configureInput(chanInFD, deviceNum, inChan, frequency, 2)) < - 0) { + 0) + { fprintf(stderr, "Error configure input channel!\n"); return -1; } if ((devOutFD = configureOutput(chanOutFD, deviceNum, outChanRef, - outChanOnOff)) < 0) { + outChanOnOff)) < 0) + { fprintf(stderr, "Error configure ouput channel!\n"); return -1; } @@ -327,7 +362,8 @@ int main(int argc, char **argv) { printf("START controll\n"); // Control tc - while (wakeState) { + while (wakeState) + { int n = 0; int i = 0; int nChRead; @@ -336,7 +372,8 @@ int main(int argc, char **argv) { float voltage; rc = pxi6259_write_ao(chanOutFD[1], &FIVE_VOLT, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel ON/OFF: %u\n", outChanOnOff); error = 1; @@ -345,19 +382,24 @@ int main(int argc, char **argv) { memset(scans_read, 0, sizeof(scans_read)); nChRead = 0; - while (nChRead < numChan) { - if (scans_read[i] <= 0) { + while (nChRead < numChan) + { + if (scans_read[i] <= 0) + { // printf("read channel %d n chan %d \n", i, nChRead); scans_read[i] = pxi6259_read_ai(chanInFD[i], &value[i], 1); - if (scans_read[i] < 0) { - if (errno != EAGAIN) { + if (scans_read[i] < 0) + { + if (errno != EAGAIN) + { fprintf(stderr, "Failed while reading channel: %u: %s %d\n", inChan[i], strerror(errno), errno); error = 1; goto out; } - } else + } + else nChRead++; } i = (i + 1) % numChan; @@ -368,7 +410,8 @@ int main(int argc, char **argv) { // End control algoritm rc = pxi6259_write_ao(chanOutFD[0], &voltage, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel reference: %u\n", outChanRef); error = 1; @@ -377,20 +420,25 @@ int main(int argc, char **argv) { struct timeb tb; int64_t currTime; - try { + try + { ftime(&tb); currTime = (int64_t)(tb.time * 1000 + tb.millitm); - for (int i = 0; i < numChan; i++) { + for (int i = 0; i < numChan; i++) + { Float32 *currData = new Float32(value[i]); node[i]->putRow(currData, &currTime); } - } catch (MdsException *exc) { + } + catch (MdsException *exc) + { printf("%s\n", exc->what()); error = 1; goto out; } - if (sem_getvalue(wakeSem_id, &wakeState) < 0) { + if (sem_getvalue(wakeSem_id, &wakeState) < 0) + { perror("Control sem_open"); error = 1; goto out; @@ -411,7 +459,8 @@ int main(int argc, char **argv) { out: rc = pxi6259_write_ao(chanOutFD[0], &ZERO_VOLT, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel reference: %u\n", outChanRef); error = 1; @@ -419,7 +468,8 @@ int main(int argc, char **argv) { } rc = pxi6259_write_ao(chanOutFD[1], &ZERO_VOLT, 1); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to write to AO channel ON/OFF: %u\n", outChanOnOff); error = 1; @@ -429,7 +479,8 @@ int main(int argc, char **argv) { printf("Close open ADC fd\n"); // stop AI segment - if (pxi6259_stop_ai(devInFD)) { + if (pxi6259_stop_ai(devInFD)) + { fprintf(stderr, "Failed to stop data acquisition!\n"); } @@ -440,7 +491,8 @@ int main(int argc, char **argv) { close(devInFD); // stop AO segment - if (pxi6259_stop_ao(devOutFD)) { + if (pxi6259_stop_ao(devOutFD)) + { fprintf(stderr, "Failed to stop generating signal!\n"); return -1; } diff --git a/device_support/national/startStopTermControl.cpp b/device_support/national/startStopTermControl.cpp index 56a0d60164..2f1da29d3c 100644 --- a/device_support/national/startStopTermControl.cpp +++ b/device_support/national/startStopTermControl.cpp @@ -31,33 +31,40 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ sem_t *semPause_id; sem_t *semWake_id; int wakeState; int i; semPause_id = sem_open("PauseControl", O_CREAT, 0666, 0); - if (semPause_id == SEM_FAILED) { + if (semPause_id == SEM_FAILED) + { perror("child sem_open"); return 0; } semWake_id = sem_open("WakeControl", O_CREAT, 0666, 0); - if (semWake_id == SEM_FAILED) { + if (semWake_id == SEM_FAILED) + { perror("child sem_open"); return 0; } - if (strcmp(argv[1], "stop") == 0) { - if (sem_getvalue(semWake_id, &wakeState) < 0) { + if (strcmp(argv[1], "stop") == 0) + { + if (sem_getvalue(semWake_id, &wakeState) < 0) + { perror("Control sem_getvalue"); return 0; } printf("STOP wake state %d\n", wakeState); - for (i = 0; i < wakeState; i++) { - if (sem_wait(semWake_id) < 0) { + for (i = 0; i < wakeState; i++) + { + if (sem_wait(semWake_id) < 0) + { perror("sem_wait WakeControl"); return 0; } @@ -71,21 +78,26 @@ int main(int argc, char **argv) { } } - if (strcmp(argv[1], "start") == 0) { - if (sem_getvalue(semWake_id, &wakeState) < 0) { + if (strcmp(argv[1], "start") == 0) + { + if (sem_getvalue(semWake_id, &wakeState) < 0) + { perror("Control sem_getvalue"); return 0; } printf("START wake state %d\n", wakeState); - if (wakeState == 0) { + if (wakeState == 0) + { printf("START pause state %d\n", wakeState); - if (sem_post(semPause_id) < 0) { + if (sem_post(semPause_id) < 0) + { perror("sem_post PauseControl"); return 0; } - if (sem_post(semWake_id) < 0) { + if (sem_post(semWake_id) < 0) + { perror("sem_post WakeControl"); return 0; } diff --git a/device_support/national/writeDigitalOut.cpp b/device_support/national/writeDigitalOut.cpp index 422a3c3882..3673f4235e 100644 --- a/device_support/national/writeDigitalOut.cpp +++ b/device_support/national/writeDigitalOut.cpp @@ -49,7 +49,8 @@ int number_of_ports = 3; // int number_of_repeats = 10; // uint32_t update_period_divisor = 20000; -int test(char *device_name, int silent) { +int test(char *device_name, int silent) +{ int retval = 0; int dio_fd = 0; @@ -80,7 +81,8 @@ int test(char *device_name, int silent) { /* open DIO segment file descriptor */ sprintf(str, "%s.dio", device_name); dio_fd = open(str, O_RDWR); - if (dio_fd <= 0) { + if (dio_fd <= 0) + { printf("Could not open AO segment!\n"); retval = -1; goto out; @@ -113,7 +115,8 @@ int test(char *device_name, int silent) { /* reset DIO segment */ retval = xseries_reset_dio(dio_fd); - if (retval) { + if (retval) + { printf("Error reseting DIO segment!\n"); goto out; } @@ -157,31 +160,36 @@ int test(char *device_name, int silent) { /* Load DIO configuration */ retval = xseries_load_di_conf(dio_fd, di_conf); - if (retval) { + if (retval) + { printf("Error loading DI configuration!\n"); goto out; } retval = xseries_load_do_conf(dio_fd, do_conf); - if (retval) { + if (retval) + { printf("Error loading DO configuration!\n"); goto out; } /* start DIO*/ retval = xseries_start_di(dio_fd); - if (retval) { + if (retval) + { printf("Error loading DI configuration!\n"); goto out; } retval = xseries_start_do(dio_fd); - if (retval) { + if (retval) + { printf("Error loading DO configuration!\n"); goto out; } /* Write values to ports */ retval = xseries_write_do(dio_fd, &do_value, 1); - if (retval != 1) { + if (retval != 1) + { printf("Error writing DO value!\n"); goto out; } @@ -237,7 +245,8 @@ int test(char *device_name, int silent) { return retval; } -void print_text(void) { +void print_text(void) +{ printf("\n"); printf("Test software-timed, static DIO and PFI operation using DIO and PFI " @@ -245,31 +254,41 @@ void print_text(void) { printf("\n"); } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int retval = 0; char *device_name; int silent = false; - if (argc == 2) { + if (argc == 2) + { device_name = argv[1]; print_text(); - } else if (argc == 3) { + } + else if (argc == 3) + { device_name = argv[1]; - if (strcmp(argv[2], "-silent")) { + if (strcmp(argv[2], "-silent")) + { print_text(); silent = false; - } else { + } + else + { silent = true; } - } else { + } + else + { printf("Usage: %s \n", argv[0]); printf("Example:\n %s /dev/pxie-6368.0\n", argv[0]); printf("\n"); exit(EXIT_FAILURE); } - if (silent) { + if (silent) + { printf("%-10s%-100s", argv[0], "Test software-timed, static DIO and PFI operation using DIO and " "PFI ports."); @@ -279,7 +298,8 @@ int main(int argc, char **argv) { /* run test */ retval = test(device_name, silent); - if (!silent) { + if (!silent) + { printf("Test: "); fflush(stdout); } diff --git a/device_support/ptgrey/PTGREY.cpp b/device_support/ptgrey/PTGREY.cpp index b7c8758e5a..3654b2b96a 100644 --- a/device_support/ptgrey/PTGREY.cpp +++ b/device_support/ptgrey/PTGREY.cpp @@ -36,11 +36,10 @@ using namespace MDSplus; #include #include - #include #include -#define BUFFER_COUNT 16 +#define BUFFER_COUNT 16 #define ERROR -1 #define SUCCESS 0 @@ -48,496 +47,473 @@ using namespace MDSplus; //if defined, print to stdout messages. #define debug - #define MAX_CAM 10 static PTGREY *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; - -#ifdef __cplusplus -extern "C" -{ -#endif - - -int PGopen(const char *ipAddress, int *camHandle) +#ifdef __cplusplus +extern "C" { - PTGREY *cam; - int cameraHandle; - - errorOnOpen[0] = 0; - - cam = new PTGREY(ipAddress); - if(!cam->checkLastOp()) - { - cam->getLastError(errorOnOpen); - delete(cam); - return ERROR; - } - - for( cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle] ; cameraHandle++); - - if( cameraHandle < MAX_CAM ) - { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } - else - { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; - } -} +#endif + int PGopen(const char *ipAddress, int *camHandle) + { + PTGREY *cam; + int cameraHandle; -int isConnected( int camHandle ) -{ - if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) - { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; - } - return SUCCESS; -} + errorOnOpen[0] = 0; -int PGclose(int camHandle) -{ - delete(camPtr[camHandle]); - camPtr[camHandle] = 0; - - return SUCCESS; -} + cam = new PTGREY(ipAddress); + if (!cam->checkLastOp()) + { + cam->getLastError(errorOnOpen); + delete (cam); + return ERROR; + } + for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; cameraHandle++) + ; -int checkLastOp(int camHandle) -{ - return camPtr[camHandle]->checkLastOp(); -} + if (cameraHandle < MAX_CAM) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } + } + int isConnected(int camHandle) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; + } -int printAllParameters(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->printAllParameters(); - return ERROR; -} + int PGclose(int camHandle) + { + delete (camPtr[camHandle]); + camPtr[camHandle] = 0; + return SUCCESS; + } -int readInternalTemperature(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->readInternalTemperature(); - return ERROR; -} + int checkLastOp(int camHandle) + { + return camPtr[camHandle]->checkLastOp(); + } -int setExposure(int camHandle, float exposure) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setExposure(exposure); - return ERROR; -} + int printAllParameters(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->printAllParameters(); + return ERROR; + } + int readInternalTemperature(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->readInternalTemperature(); + return ERROR; + } -int setExposureAuto(int camHandle, char *exposureAuto) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setExposureAuto(exposureAuto); - return ERROR; -} + int setExposure(int camHandle, float exposure) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setExposure(exposure); + return ERROR; + } + int setExposureAuto(int camHandle, char *exposureAuto) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setExposureAuto(exposureAuto); + return ERROR; + } -int setGain(int camHandle, float gain) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setGain(gain); - return ERROR; -} + int setGain(int camHandle, float gain) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGain(gain); + return ERROR; + } + int setGainAuto(int camHandle, char *gainAuto) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGainAuto(gainAuto); + return ERROR; + } -int setGainAuto(int camHandle, char *gainAuto) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setGainAuto(gainAuto); - return ERROR; -} + int setGammaEnable(int camHandle, char *gammaEnable) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setGammaEnable(gammaEnable); + return ERROR; + } + int setFrameRate(int camHandle, double *frameRate) + { + if (isConnected(camHandle) == SUCCESS) + { + double fRate; + int status; + fRate = *frameRate; + status = camPtr[camHandle]->setFrameRate(fRate); + *frameRate = fRate; + return status; + } + return ERROR; + } -int setGammaEnable(int camHandle, char *gammaEnable) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setGammaEnable(gammaEnable); - return ERROR; -} + int setReadoutArea(int camHandle, int x, int y, int width, int height) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; + } + int setPixelFormat(int camHandle, char *pixelFormat) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setPixelFormat(pixelFormat); + return ERROR; + } -int setFrameRate(int camHandle, double *frameRate) -{ - if( isConnected( camHandle ) == SUCCESS ) + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) { - double fRate; - int status; - fRate = *frameRate; - status = camPtr[camHandle]->setFrameRate(fRate); - *frameRate = fRate; - return status; + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; } - return ERROR; -} + int stopAcquisition(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; + } -int setReadoutArea(int camHandle, int x, int y, int width, int height) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; -} + int getFrame(int camHandle, int *status, void *frame, void *metaData) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; + } + int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setAcquisitionMode(storeEnabled, acqSkipFrameNumber); + return ERROR; + } -int setPixelFormat(int camHandle, char *pixelFormat) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setPixelFormat(pixelFormat); - return ERROR; -} + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, numTrigger); + return ERROR; + } + int softwareTrigger(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; + } -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; -} + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid); + return ERROR; + } + int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->setStreamingMode(streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + return ERROR; + } + int startFramesAcquisition(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; + } -int stopAcquisition(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; -} + int stopFramesAcquisition(int camHandle) + { + if (isConnected(camHandle) == SUCCESS) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; + } + void getLastError(int camHandle, char *msg) + { + if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) + { + sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); + } -int getFrame(int camHandle, int *status, void *frame, void *metaData) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; +#ifdef __cplusplus } +#endif - -int setAcquisitionMode( int camHandle, int storeEnabled, int acqSkipFrameNumber) +PTGREY::PTGREY(const char *ipAddress) { - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setAcquisitionMode( storeEnabled, acqSkipFrameNumber); - return ERROR; -} + this->ipAddress = PvString(ipAddress); + trigEvent = NULL; -int setTriggerMode( int camHandle, int triggerMode, double burstDuration, int numTrigger ) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setTriggerMode( triggerMode, burstDuration, numTrigger ); - return ERROR; -} + /* SDK 3 + this->lDevice = new PvDevice(); + this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); +*/ + try + { + this->lDevice = PvDevice::CreateAndConnect(this->ipAddress, &this->lResult); //20160309 SDK4 //sometimes goes in coredump + } + catch (...) + { + printf("Core dump detected on PvDevice::CreateAndConnect\n"); + } + if (!this->lResult.IsOK()) + { + printf("--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); + if (this->lDevice != nullptr) //CT 2019-03-29 + { + PvDevice::Free(this->lDevice); + } + } + else + { + printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii()); + } -int softwareTrigger(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; + printf("EVENTO abilitato \n"); + //CT MDSplus acquisition Triggered on MDSevent + eventTrigger = 0; + trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); + trigEvent->start(); } -int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +PTGREY::PTGREY() //new 25/07/2013: let to use the device without the camera { - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setTreeInfo( treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid ); - return ERROR; + //this->lDevice = new PvDevice(); //SDK 3 + //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera } -int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +PTGREY::~PTGREY() { - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->setStreamingMode(streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); - return ERROR; -} -int startFramesAcquisition(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; -} + printf("PTGREY destructor %p\n", this->lDevice); + if (this->lDevice != nullptr) //CT 2019-03-27 + { + this->lResult = this->lDevice->Disconnect(); + if (!this->lResult.IsOK()) + printLastError("Error Device disconnection !!!\n(%s)\n", lResult.GetDescription().GetAscii()); + else + printf("PTGREY destructor class executed\n"); + //delete(this->lDevice); //SDK 3 + PvDevice::Free(this->lDevice); //SDK 4 09/03/2016 + } -int stopFramesAcquisition(int camHandle) -{ - if( isConnected( camHandle ) == SUCCESS ) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; + if (trigEvent != NULL) + delete trigEvent; } -void getLastError(int camHandle, char *msg) +int PTGREY::checkLastOp() { - if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) - { - sprintf(msg, "%s", (errorOnOpen[0]==0) ? "" : errorOnOpen); - return; - } - camPtr[camHandle]->getLastError(msg); + printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii()); + if (!this->lResult.IsOK()) + printLastError("(%s)\n", lResult.GetDescription().GetAscii()); + return this->lResult.IsOK(); } +int PTGREY::printAllParameters() +{ + PvGenParameterArray *aArray = lDevice->GetParameters(); + uint32_t lParameterArrayCount = aArray->GetCount(); + printf("\nArray has %d parameters\n", lParameterArrayCount); -#ifdef __cplusplus -} -#endif + // Traverse through Array and print out parameters available + for (uint32_t x = 0; x < lParameterArrayCount; x++) + { + // Get a parameter + PvGenParameter *lGenParameter = aArray->Get(x); + // Don't show invisible parameters - display everything up to Guru + if (!lGenParameter->IsVisible(PvGenVisibilityGuru)) + { + continue; + } + // Get and print parameter's name + PvString lGenParameterName, lCategory; + lGenParameter->GetCategory(lCategory); + lGenParameter->GetName(lGenParameterName); + printf("%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii()); + // Parameter available? + if (!lGenParameter->IsAvailable()) + { + printf("{Not Available}\n"); + continue; + } -PTGREY::PTGREY(const char *ipAddress) -{ - this->ipAddress = PvString(ipAddress); - trigEvent = NULL; + // Parameter readable? + if (!lGenParameter->IsReadable()) + { + printf("{Not readable}\n"); + continue; + } -/* SDK 3 - this->lDevice = new PvDevice(); - this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); -*/ - try{ - this->lDevice = PvDevice::CreateAndConnect(this->ipAddress, &this->lResult); //20160309 SDK4 //sometimes goes in coredump + // Get the parameter type + PvGenType lType; + lGenParameter->GetType(lType); + switch (lType) + { + // If the parameter is of type PvGenTypeInteger + case PvGenTypeInteger: + { + int64_t lValue; + static_cast(lGenParameter)->GetValue(lValue); + printf("Integer: %d", lValue); } - catch(...) + break; + // If the parameter is of type PvGenTypeEnum + case PvGenTypeEnum: { - printf("Core dump detected on PvDevice::CreateAndConnect\n"); + PvString lValue; + static_cast(lGenParameter)->GetValue(lValue); + printf("Enum: %s", lValue.GetAscii()); } - if ( !this->lResult.IsOK() ) + break; + // If the parameter is of type PvGenTypeBoolean + case PvGenTypeBoolean: { - printf("--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); - if( this->lDevice != nullptr ) //CT 2019-03-29 - { - PvDevice::Free(this->lDevice); - } + bool lValue; + static_cast(lGenParameter)->GetValue(lValue); + if (lValue) + { + printf("Boolean: TRUE"); + } + else + { + printf("Boolean: FALSE"); + } } - else - { - printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii() ); + break; + // If the parameter is of type PvGenTypeString + case PvGenTypeString: + { + PvString lValue; + static_cast(lGenParameter)->GetValue(lValue); + printf("String: %s", lValue.GetAscii()); } - - printf("EVENTO abilitato \n"); - //CT MDSplus acquisition Triggered on MDSevent - eventTrigger = 0; - trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); - trigEvent->start(); - -} - - -PTGREY::PTGREY() //new 25/07/2013: let to use the device without the camera -{ - //this->lDevice = new PvDevice(); //SDK 3 - //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera -} - - -PTGREY::~PTGREY() -{ - - printf("PTGREY destructor %p\n", this->lDevice ); - if( this->lDevice != nullptr ) //CT 2019-03-27 + break; + // If the parameter is of type PvGenTypeCommand + case PvGenTypeCommand: + printf("Command"); + break; + // If the parameter is of type PvGenTypeFloat + case PvGenTypeFloat: { - this->lResult = this->lDevice->Disconnect(); - if ( !this->lResult.IsOK() ) - printLastError("Error Device disconnection !!!\n(%s)\n", lResult.GetDescription().GetAscii() ); - else - printf("PTGREY destructor class executed\n"); - //delete(this->lDevice); //SDK 3 - PvDevice::Free(this->lDevice); //SDK 4 09/03/2016 + double lValue; + static_cast(lGenParameter)->GetValue(lValue); + printf("Float: %f", lValue); } + break; + } + printf("\n"); + } - if( trigEvent != NULL ) - delete trigEvent; - -} - - - -int PTGREY::checkLastOp() -{ - printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii() ); - if ( !this->lResult.IsOK() ) - printLastError("(%s)\n", lResult.GetDescription().GetAscii() ); - return this->lResult.IsOK(); -} - - - -int PTGREY::printAllParameters() -{ - PvGenParameterArray *aArray = lDevice->GetParameters(); - uint32_t lParameterArrayCount = aArray->GetCount(); - printf( "\nArray has %d parameters\n", lParameterArrayCount ); - - // Traverse through Array and print out parameters available - for( uint32_t x = 0; x < lParameterArrayCount; x++ ) - { - // Get a parameter - PvGenParameter *lGenParameter = aArray->Get( x ); - - // Don't show invisible parameters - display everything up to Guru - if ( !lGenParameter->IsVisible( PvGenVisibilityGuru ) ) - { - continue; - } - - // Get and print parameter's name - PvString lGenParameterName, lCategory; - lGenParameter->GetCategory( lCategory ); - lGenParameter->GetName( lGenParameterName ); - printf( "%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii() ); - - // Parameter available? - if ( !lGenParameter->IsAvailable() ) - { - printf( "{Not Available}\n" ); - continue; - } - - // Parameter readable? - if ( !lGenParameter->IsReadable() ) - { - printf( "{Not readable}\n" ); - continue; - } - - // Get the parameter type - PvGenType lType; - lGenParameter->GetType( lType ); - switch ( lType ) - { - // If the parameter is of type PvGenTypeInteger - case PvGenTypeInteger: - { - int64_t lValue; - static_cast( lGenParameter )->GetValue( lValue ); - printf( "Integer: %d", lValue ); - } - break; - // If the parameter is of type PvGenTypeEnum - case PvGenTypeEnum: - { - PvString lValue; - static_cast( lGenParameter )->GetValue( lValue ); - printf( "Enum: %s", lValue.GetAscii() ); - } - break; - // If the parameter is of type PvGenTypeBoolean - case PvGenTypeBoolean: - { - bool lValue; - static_cast( lGenParameter )->GetValue( lValue ); - if( lValue ) - { - printf( "Boolean: TRUE" ); - } - else - { - printf( "Boolean: FALSE" ); - } - } - break; - // If the parameter is of type PvGenTypeString - case PvGenTypeString: - { - PvString lValue; - static_cast( lGenParameter )->GetValue( lValue ); - printf( "String: %s", lValue.GetAscii() ); - } - break; - // If the parameter is of type PvGenTypeCommand - case PvGenTypeCommand: - printf( "Command" ); - break; - // If the parameter is of type PvGenTypeFloat - case PvGenTypeFloat: - { - double lValue; - static_cast( lGenParameter )->GetValue( lValue ); - printf( "Float: %f", lValue ); - } - break; - } - printf("\n"); - } - - return SUCCESS; + return SUCCESS; } - int PTGREY::readInternalTemperature() { - double t; - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *linternalTemp = dynamic_cast( lDeviceParams->Get( "DeviceTemperature" ) ); - this->lResult = linternalTemp->GetValue( t ); - if ( !this->lResult.IsOK() ) - {printLastError("Error reading Internal Temperature!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + double t; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenFloat *linternalTemp = dynamic_cast(lDeviceParams->Get("DeviceTemperature")); + this->lResult = linternalTemp->GetValue(t); + if (!this->lResult.IsOK()) + { + printLastError("Error reading Internal Temperature!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - this->internalTemperature=t; //t must be double but is a float - printf("%s: Camera Temperature is now %3.2f°C\n", (this->ipAddress).GetAscii(), this->internalTemperature); + this->internalTemperature = t; //t must be double but is a float + printf("%s: Camera Temperature is now %3.2f°C\n", (this->ipAddress).GetAscii(), this->internalTemperature); return SUCCESS; } - -int PTGREY::setExposure(float exposure) //[us] - Min: 15 Max: 3e+07 attenzione double-float +int PTGREY::setExposure(float exposure) //[us] - Min: 15 Max: 3e+07 attenzione double-float { PvString lValue; PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *lExposureAuto = dynamic_cast( lDeviceParams->Get( "ExposureAuto" ) ); - if(exposure<15.0 or exposure>30000000.0) + PvGenEnum *lExposureAuto = dynamic_cast(lDeviceParams->Get("ExposureAuto")); + if (exposure < 15.0 or exposure > 30000000.0) { printf("ERROR: exposure should be in range 15.0 - 3e+07 [us]...\n"); return ERROR; } - this->lResult = lExposureAuto->GetValue( lValue ); - if(strcmp(lValue.GetAscii(), "Off")==0) + this->lResult = lExposureAuto->GetValue(lValue); + if (strcmp(lValue.GetAscii(), "Off") == 0) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *lExposure = dynamic_cast( lDeviceParams->Get( "ExposureTime" ) ); - this->lResult = lExposure->SetValue( exposure ); - if ( !this->lResult.IsOK() ) - {printLastError("Error setting exposure!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + PvGenFloat *lExposure = dynamic_cast(lDeviceParams->Get("ExposureTime")); + this->lResult = lExposure->SetValue(exposure); + if (!this->lResult.IsOK()) + { + printLastError("Error setting exposure!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } } else { printf("WARNING: to set the exposure value the ExposureAuto must be Off\n"); } - this->exposure=exposure; - printf("%s: Exposure set to %.1fus\n", (this->ipAddress).GetAscii(), exposure); + this->exposure = exposure; + printf("%s: Exposure set to %.1fus\n", (this->ipAddress).GetAscii(), exposure); return SUCCESS; } - int PTGREY::setExposureAuto(char *exposureAuto) { - if(strcmp(exposureAuto, "Off")!=0 & strcmp(exposureAuto, "Once")!=0 & strcmp(exposureAuto, "Continuous")!=0) + if (strcmp(exposureAuto, "Off") != 0 & strcmp(exposureAuto, "Once") != 0 & strcmp(exposureAuto, "Continuous") != 0) { printf("ERROR: setExposureAuto must be Off, Once or Continuous\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue( "ExposureAuto", exposureAuto ); - if ( !this->lResult.IsOK() ) - {printLastError("Error setting exposureAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue("ExposureAuto", exposureAuto); + if (!this->lResult.IsOK()) + { + printLastError("Error setting exposureAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } return SUCCESS; } int PTGREY::setGammaEnable(char *gammaEnable) { -/* + /* if(strcmp(gammaEnable, "On")==0) { pCamera->GammaEnable.SetValue(true); @@ -546,97 +522,115 @@ int PTGREY::setGammaEnable(char *gammaEnable) { pCamera->GammaEnable.SetValue(false); } -*/ - printf("%s: setGammaEnable BYPASSED 4 TEST\n", (this->ipAddress).GetAscii()); +*/ + printf("%s: setGammaEnable BYPASSED 4 TEST\n", (this->ipAddress).GetAscii()); return SUCCESS; } -int PTGREY::setGain(float gain) //Off impostabile solo in gainAuto=Off +int PTGREY::setGain(float gain) //Off impostabile solo in gainAuto=Off { PvString lValue; PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *lGainAuto = dynamic_cast( lDeviceParams->Get( "GainAuto" ) ); - if(gain<0.0 or gain>47.9943) + PvGenEnum *lGainAuto = dynamic_cast(lDeviceParams->Get("GainAuto")); + if (gain < 0.0 or gain > 47.9943) { printf("ERROR: gain should be in range 0.0 - 47.9943 [dB]...\n"); return ERROR; } - this->lResult = lGainAuto->GetValue( lValue ); - if(strcmp(lValue.GetAscii(), "Off")==0) + this->lResult = lGainAuto->GetValue(lValue); + if (strcmp(lValue.GetAscii(), "Off") == 0) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *lGain = dynamic_cast( lDeviceParams->Get( "Gain" ) ); - this->lResult = lGain->SetValue( gain ); - if ( !this->lResult.IsOK() ) - {printLastError("Error setting gain!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + PvGenFloat *lGain = dynamic_cast(lDeviceParams->Get("Gain")); + this->lResult = lGain->SetValue(gain); + if (!this->lResult.IsOK()) + { + printLastError("Error setting gain!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } } else { printf("WARNING: to set the gain value the gainAuto must be Off\n"); } - this->gain=gain; - printf("%s: Gain set to %.2fdB\n", (this->ipAddress).GetAscii(), gain); + this->gain = gain; + printf("%s: Gain set to %.2fdB\n", (this->ipAddress).GetAscii(), gain); return SUCCESS; } - -int PTGREY::setGainAuto(char *gainAuto) //Off(0), Once(1), Continuous(2) +int PTGREY::setGainAuto(char *gainAuto) //Off(0), Once(1), Continuous(2) { - if(strcmp(gainAuto, "Off")!=0 & strcmp(gainAuto, "Once")!=0 & strcmp(gainAuto, "Continuous")!=0) + if (strcmp(gainAuto, "Off") != 0 & strcmp(gainAuto, "Once") != 0 & strcmp(gainAuto, "Continuous") != 0) { printf("ERROR: setGainAuto must be Off, Once or Continuous\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue( "GainAuto", gainAuto ); - if ( !this->lResult.IsOK() ) - {printLastError("Error setting gainAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue("GainAuto", gainAuto); + if (!this->lResult.IsOK()) + { + printLastError("Error setting gainAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } return SUCCESS; } - - int PTGREY::setFrameRate(double &frameRate) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenBoolean *sFrameRateEn = dynamic_cast( lDeviceParams->Get("AcquisitionFrameRateEnable")); - if(frameRate<1.0 or frameRate>39.2221) + PvGenBoolean *sFrameRateEn = dynamic_cast(lDeviceParams->Get("AcquisitionFrameRateEnable")); + if (frameRate < 1.0 or frameRate > 39.2221) { - double resFrameRate; + double resFrameRate; - this->lResult = sFrameRateEn->SetValue( 0 ); - if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - usleep(3000); + this->lResult = sFrameRateEn->SetValue(0); + if (!this->lResult.IsOK()) + { + printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + usleep(3000); + PvGenFloat *sResFrameRate = dynamic_cast(lDeviceParams->Get("AcquisitionResultingFrameRate")); + this->lResult = sResFrameRate->GetValue(resFrameRate); - PvGenFloat *sResFrameRate = dynamic_cast( lDeviceParams->Get("AcquisitionResultingFrameRate")); - this->lResult = sResFrameRate->GetValue( resFrameRate ); + if (!this->lResult.IsOK()) + { + printLastError("Error setting AcquisitionResultingFrameRate in getFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionResultingFrameRate in getFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - - printf("%s: Resulting Framerate %f fps\n", (this->ipAddress).GetAscii(), resFrameRate); + printf("%s: Resulting Framerate %f fps\n", (this->ipAddress).GetAscii(), resFrameRate); - this->frameRate = resFrameRate; + this->frameRate = resFrameRate; - frameRate = resFrameRate; + frameRate = resFrameRate; //printf("ERROR: frameRate should be in range 1.0 - 39.2221 [Hz]...\n"); return SUCCESS; } - this->lResult = sFrameRateEn->SetValue( 1 ); - if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - usleep(3000); - - PvGenFloat *sFrameRate = dynamic_cast( lDeviceParams->Get("AcquisitionFrameRate")); - this->lResult = sFrameRate->SetValue( (float)frameRate ); - if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = sFrameRateEn->SetValue(1); + if (!this->lResult.IsOK()) + { + printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + usleep(3000); + + PvGenFloat *sFrameRate = dynamic_cast(lDeviceParams->Get("AcquisitionFrameRate")); + this->lResult = sFrameRate->SetValue((float)frameRate); + if (!this->lResult.IsOK()) + { + printLastError("Error setting AcquisitionFrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } usleep(3000); this->frameRate = frameRate; - printf("%s: Framerate set to %.2ffps\n", (this->ipAddress).GetAscii(), frameRate); + printf("%s: Framerate set to %.2ffps\n", (this->ipAddress).GetAscii(), frameRate); return SUCCESS; } @@ -679,255 +673,303 @@ usleep(3000); } */ - int PTGREY::setReadoutArea(int x, int y, int width, int height) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); - PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); - PvGenInteger *lOffsetX = dynamic_cast( lDeviceParams->Get( "OffsetX" ) ); - PvGenInteger *lOffsetY = dynamic_cast( lDeviceParams->Get( "OffsetY" ) ); - - this->lResult = lWidth->SetValue(width); - if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - usleep(3000); -// this->lResult = lHeight->SetValue(h+3); //add 3 lines of metadata - this->lResult = lHeight->SetValue(height); //add 3 lines of metadata - if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - usleep(3000); - this->lResult = lOffsetX->SetValue(x); - if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - usleep(3000); - this->lResult = lOffsetY->SetValue(y); - if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - - this->x = x; - this->y = y; - this->width = width; - this->height = height; - - return SUCCESS; -} + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); + PvGenInteger *lHeight = dynamic_cast(lDeviceParams->Get("Height")); + PvGenInteger *lOffsetX = dynamic_cast(lDeviceParams->Get("OffsetX")); + PvGenInteger *lOffsetY = dynamic_cast(lDeviceParams->Get("OffsetY")); + this->lResult = lWidth->SetValue(width); + if (!this->lResult.IsOK()) + { + printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + usleep(3000); + // this->lResult = lHeight->SetValue(h+3); //add 3 lines of metadata + this->lResult = lHeight->SetValue(height); //add 3 lines of metadata + if (!this->lResult.IsOK()) + { + printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + usleep(3000); + this->lResult = lOffsetX->SetValue(x); + if (!this->lResult.IsOK()) + { + printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + usleep(3000); + this->lResult = lOffsetY->SetValue(y); + if (!this->lResult.IsOK()) + { + printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } -int PTGREY::setPixelFormat(char *pixelFormat) //Enum: Mono8 - Mono16 (others not used: Mono10Packed, Mono12Packed) + this->x = x; + this->y = y; + this->width = width; + this->height = height; + + return SUCCESS; +} + +int PTGREY::setPixelFormat(char *pixelFormat) //Enum: Mono8 - Mono16 (others not used: Mono10Packed, Mono12Packed) { - if(strcmp(pixelFormat, "Mono8")!=0 & strcmp(pixelFormat, "Mono16")!=0) + if (strcmp(pixelFormat, "Mono8") != 0 & strcmp(pixelFormat, "Mono16") != 0) { printf("ERROR: PixelFormat must be Mono8 or Mono16\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue( "PixelFormat", pixelFormat ); - if ( !this->lResult.IsOK() ) - {printLastError("Error setting PixelFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue("PixelFormat", pixelFormat); + if (!this->lResult.IsOK()) + { + printLastError("Error setting PixelFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - if(strcmp(pixelFormat, "Mono8")==0) + if (strcmp(pixelFormat, "Mono8") == 0) { - this->pixelFormat = CSU_PIX_FMT_GRAY8; - this->Bpp = 1; + this->pixelFormat = CSU_PIX_FMT_GRAY8; + this->Bpp = 1; } - if(strcmp(pixelFormat, "Mono16")==0) + if (strcmp(pixelFormat, "Mono16") == 0) { - this->pixelFormat = CSU_PIX_FMT_GRAY16; - this->Bpp = 2; + this->pixelFormat = CSU_PIX_FMT_GRAY16; + this->Bpp = 2; } - printf("%s: PixelFormat set to %s\n", (this->ipAddress).GetAscii(), pixelFormat); + printf("%s: PixelFormat set to %s\n", (this->ipAddress).GetAscii(), pixelFormat); return SUCCESS; } - int PTGREY::startAcquisition(int *width, int *height, int *payloadSize) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); - PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); - PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); - PvGenInteger *lPayloadSize = dynamic_cast( lDeviceParams->Get( "PayloadSize" ) ); - PvGenCommand *lResetTimestamp = dynamic_cast( lDeviceParams->Get( "GevTimestampControlReset" ) ); - PvGenCommand *lStart = dynamic_cast( lDeviceParams->Get( "AcquisitionStart" ) ); - - // Get stream parameters/stats -//17-10-2016: segmentation fault with SDK4. to check! -/* + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); + PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); + PvGenInteger *lHeight = dynamic_cast(lDeviceParams->Get("Height")); + PvGenInteger *lPayloadSize = dynamic_cast(lDeviceParams->Get("PayloadSize")); + PvGenCommand *lResetTimestamp = dynamic_cast(lDeviceParams->Get("GevTimestampControlReset")); + PvGenCommand *lStart = dynamic_cast(lDeviceParams->Get("AcquisitionStart")); + + // Get stream parameters/stats + //17-10-2016: segmentation fault with SDK4. to check! + /* PvGenParameterArray *lStreamParams = lStream->GetParameters(); PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); */ + PvGenInteger *lTickFreq = dynamic_cast(lDeviceParams->Get("GevTimestampTickFrequency")); + this->lResult = lTickFreq->GetValue(tickFreq); + if (!this->lResult.IsOK()) + { + printLastError("Error getting GevTimestampTickFrequency in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + } + //printf("---> GevTimestampTickFrequency = %d\n", tickFreq); - PvGenInteger *lTickFreq = dynamic_cast( lDeviceParams->Get( "GevTimestampTickFrequency" ) ); - this->lResult = lTickFreq->GetValue( tickFreq ); - if ( !this->lResult.IsOK() ) {printLastError("Error getting GevTimestampTickFrequency in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() );} - //printf("---> GevTimestampTickFrequency = %d\n", tickFreq); + int64_t w = 0; + int64_t h = 0; + int64_t lSize = 0; - int64_t w = 0; - int64_t h = 0; - int64_t lSize = 0; - - this->lResult = lWidth->GetValue( w ); - if ( !this->lResult.IsOK() ) {printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - this->lResult = lHeight->GetValue( h ); - if ( !this->lResult.IsOK() ) {printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - this->lResult = lPayloadSize->GetValue( lSize ); - if ( !this->lResult.IsOK() ) {printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = lWidth->GetValue(w); + if (!this->lResult.IsOK()) + { + printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + this->lResult = lHeight->GetValue(h); + if (!this->lResult.IsOK()) + { + printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + this->lResult = lPayloadSize->GetValue(lSize); + if (!this->lResult.IsOK()) + { + printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - this->width = *width = (int)w; -// this->height = *height= (int)h-3; //first 3 rows are metadata - this->height = *height= (int)h; + this->width = *width = (int)w; + // this->height = *height= (int)h-3; //first 3 rows are metadata + this->height = *height = (int)h; - *payloadSize=lSize; //payload = width*height*2 + metadata - printf("w:%d h:%d p:%d\n", this->width, this->height, (int)lSize); -/* + *payloadSize = lSize; //payload = width*height*2 + metadata + printf("w:%d h:%d p:%d\n", this->width, this->height, (int)lSize); + /* new 09 mar 2016 for SDK4 // If this is a GigE Vision device, configure GigE Vision specific streaming parameters */ - PvDeviceGEV *lDeviceGEV = static_cast( this->lDevice ); - //17-10-2016 lStreamGEV moved down -/* + PvDeviceGEV *lDeviceGEV = static_cast(this->lDevice); + //17-10-2016 lStreamGEV moved down + /* end new */ - // Negotiate streaming packet size - //this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 - this->lResult = lDeviceGEV->NegotiatePacketSize(); //SDK 4 + // Negotiate streaming packet size + //this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 + this->lResult = lDeviceGEV->NegotiatePacketSize(); //SDK 4 - if ( !this->lResult.IsOK() ) - { - printLastError("Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); - return ERROR; - } + if (!this->lResult.IsOK()) + { + printLastError("Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - PvGenInteger *lPacketSize = dynamic_cast( lDevice->GetParameters()->Get( "GevSCPSPacketSize" ) ); + PvGenInteger *lPacketSize = dynamic_cast(lDevice->GetParameters()->Get("GevSCPSPacketSize")); - int64_t lPacketSizeValue = 0; - lResult = lPacketSize->GetValue( lPacketSizeValue ); - if ( !lResult.IsOK() ) - { - printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); - return ERROR; - //fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); - } + int64_t lPacketSizeValue = 0; + lResult = lPacketSize->GetValue(lPacketSizeValue); + if (!lResult.IsOK()) + { + printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + //fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); + } + + printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); - printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); - // PvString aID; - // this->lResult = lDevice->GetUniqueID(aID); - - // Open stream - //this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 - this->lStream = NULL; - - //this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 - this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 - - //if ( ( this->lStream == NULL ) || !this->lResult.IsOK() ) - if ( this->lStream == NULL ) - { - printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); - PvStream::Free( this->lStream ); - return ERROR; - } + // this->lResult = lDevice->GetUniqueID(aID); + // Open stream + //this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 + this->lStream = NULL; - // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream - uint32_t lBufferCount = ( lStream->GetQueuedBufferMaximum() < BUFFER_COUNT ) ? - lStream->GetQueuedBufferMaximum() : - BUFFER_COUNT; + //this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 + this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 - //new 17-10-2016 for SDK4 - // If this is a GigE Vision device, configure GigE Vision specific streaming parameters - PvStreamGEV *lStreamGEV = static_cast( this->lStream ); - - if( this->lStream->IsOpen() ) - { - //printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK 3 - printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort() ); //SDK 4 not working.... segmentation fault to check! - } - else - { - printf("lStream NOT OPEN\n"); - } - if(lDevice->IsConnected()) - {printf( "PvDevice connect \n");} - else - {printf( "PvDevice not connect \n");} - - printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); - - // Create, alloc buffers - this->lBuffers = new PvBuffer[ lBufferCount ]; - for ( uint32_t i = 0; i < lBufferCount; i++ ) - { - lResult = lBuffers[ i ].Alloc( static_cast( lSize ) ); - if ( !lResult.IsOK() ) - printf("Error memory buffer allocation %d !!!\n(%s)\n", (i+1) , lResult.GetDescription().GetAscii() ); - } + //if ( ( this->lStream == NULL ) || !this->lResult.IsOK() ) + if (this->lStream == NULL) + { + printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + PvStream::Free(this->lStream); + return ERROR; + } - if( lStream->IsOpen() ) printf("lStream OPEN\n"); - else printf("lStream NOT OPEN\n"); + // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream + uint32_t lBufferCount = (lStream->GetQueuedBufferMaximum() < BUFFER_COUNT) ? lStream->GetQueuedBufferMaximum() : BUFFER_COUNT; - if(lDevice->IsConnected()) - printf( "PvDevice connect \n"); - else - printf( "PvDevice not connect \n"); + //new 17-10-2016 for SDK4 + // If this is a GigE Vision device, configure GigE Vision specific streaming parameters + PvStreamGEV *lStreamGEV = static_cast(this->lStream); - // Have to set the Device IP destination to the Stream - //this->lResult = lDevice->SetStreamDestination( lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 - this->lResult = lDeviceGEV->SetStreamDestination( lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort() ); //SDK 4 - 9 mar 2016 - if ( !this->lResult.IsOK() ) {printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + if (this->lStream->IsOpen()) + { + //printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK 3 + printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort()); //SDK 4 not working.... segmentation fault to check! + } + else + { + printf("lStream NOT OPEN\n"); + } + if (lDevice->IsConnected()) + { + printf("PvDevice connect \n"); + } + else + { + printf("PvDevice not connect \n"); + } - if( lStream->IsOpen() ) printf("lStream OPEN\n"); - else printf("lStream NOT OPEN\n"); + printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); - if(lDevice->IsConnected()) - printf( "PvDevice connect \n"); - else - printf( "PvDevice not connect \n"); + // Create, alloc buffers + this->lBuffers = new PvBuffer[lBufferCount]; + for (uint32_t i = 0; i < lBufferCount; i++) + { + lResult = lBuffers[i].Alloc(static_cast(lSize)); + if (!lResult.IsOK()) + printf("Error memory buffer allocation %d !!!\n(%s)\n", (i + 1), lResult.GetDescription().GetAscii()); + } + if (lStream->IsOpen()) + printf("lStream OPEN\n"); + else + printf("lStream NOT OPEN\n"); - // Queue all buffers in the stream - for ( uint32_t i = 0; i < lBufferCount; i++ ) - { -printf("------------------------ Queuing Buffer -----------------------------------\n"); - lResult = lStream->QueueBuffer( &lBuffers[i] ); -printf("------------------------ Queued Buffer -----------------------------------\n"); - if ( !lResult.IsPending() ) - printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i+1) , lResult.GetDescription().GetAscii(), lResult.GetCodeString().GetAscii() ); - } + if (lDevice->IsConnected()) + printf("PvDevice connect \n"); + else + printf("PvDevice not connect \n"); - if( lStream->IsOpen() ) printf("lStream OPEN\n"); - else printf("lStream NOT OPEN\n"); + // Have to set the Device IP destination to the Stream + //this->lResult = lDevice->SetStreamDestination( lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 + this->lResult = lDeviceGEV->SetStreamDestination(lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort()); //SDK 4 - 9 mar 2016 + if (!this->lResult.IsOK()) + { + printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - if(lDevice->IsConnected()) - printf( "PvDevice connect \n"); - else - printf( "PvDevice not connect \n"); + if (lStream->IsOpen()) + printf("lStream OPEN\n"); + else + printf("lStream NOT OPEN\n"); - // TLParamsLocked is optional but when present, it MUST be set to 1 - // before sending the AcquisitionStart command - if ( lTLLocked != NULL ) - { -usleep(3000); - this->lResult = lTLLocked->SetValue( 1 ); + if (lDevice->IsConnected()) + printf("PvDevice connect \n"); + else + printf("PvDevice not connect \n"); + + // Queue all buffers in the stream + for (uint32_t i = 0; i < lBufferCount; i++) + { + printf("------------------------ Queuing Buffer -----------------------------------\n"); + lResult = lStream->QueueBuffer(&lBuffers[i]); + printf("------------------------ Queued Buffer -----------------------------------\n"); + if (!lResult.IsPending()) + printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i + 1), lResult.GetDescription().GetAscii(), lResult.GetCodeString().GetAscii()); + } + + if (lStream->IsOpen()) + printf("lStream OPEN\n"); + else + printf("lStream NOT OPEN\n"); + + if (lDevice->IsConnected()) + printf("PvDevice connect \n"); + else + printf("PvDevice not connect \n"); + + // TLParamsLocked is optional but when present, it MUST be set to 1 + // before sending the AcquisitionStart command + if (lTLLocked != NULL) + { + usleep(3000); + this->lResult = lTLLocked->SetValue(1); - if ( !this->lResult.IsOK() ) {printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + if (!this->lResult.IsOK()) + { + printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; } - //reset timestamp counter -printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); -//2019-09-17 fede comment out for test with point gray visible camera -// this->lResult = lResetTimestamp->Execute(); -// if ( !this->lResult.IsOK() ) {printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - // Tell the device to start sending images - this->lResult = lStart->Execute(); - if ( !this->lResult.IsOK() ) {printLastError("Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - -//debug - triggered = 0; -/* + } + //reset timestamp counter + printf("2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); + //2019-09-17 fede comment out for test with point gray visible camera + // this->lResult = lResetTimestamp->Execute(); + // if ( !this->lResult.IsOK() ) {printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + // Tell the device to start sending images + this->lResult = lStart->Execute(); + if (!this->lResult.IsOK()) + { + printLastError("Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } + + //debug + triggered = 0; + /* printf( "Get Local IP Address %s \n", lStream->GetLocalIPAddress().GetAscii() ); printf( "QueuedBuffer %d \n", lStream->GetQueuedBufferCount() ); printf( "QueuedBuffer Maximum %d \n", lStream->GetQueuedBufferMaximum() ); @@ -944,114 +986,119 @@ printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); else printf( "PvStream not open \n"); */ - return SUCCESS; + return SUCCESS; } - - int PTGREY::stopAcquisition() { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); - PvGenCommand *lStop = dynamic_cast( lDeviceParams->Get( "AcquisitionStop" ) ); + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); + PvGenCommand *lStop = dynamic_cast(lDeviceParams->Get("AcquisitionStop")); - printf("PTGREY : device stop acquisition"); + printf("PTGREY : device stop acquisition"); - // Tell the device to stop sending images + // Tell the device to stop sending images + this->lResult = lStop->Execute(); + for (int i = 0; i < 3 && !this->lResult.IsOK(); i++) + { + usleep(30000); this->lResult = lStop->Execute(); - for(int i = 0; i < 3 && !this->lResult.IsOK(); i++) + if (!this->lResult.IsOK()) { - usleep(30000); - this->lResult = lStop->Execute(); - if ( !this->lResult.IsOK() ) {printf( RED "Try %d : Error sending AcquisitionStop command to the device!!!\n(%s)\n" RESET , i, lResult.GetDescription().GetAscii() ); } - } - if ( !this->lResult.IsOK() ) {printLastError("Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - - // If present reset TLParamsLocked to 0. Must be done AFTER the - // streaming has been stopped - if ( lTLLocked != NULL ) - { - this->lResult = lTLLocked->SetValue( 0 ); - if ( !this->lResult.IsOK() ) {printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + printf(RED "Try %d : Error sending AcquisitionStop command to the device!!!\n(%s)\n" RESET, i, lResult.GetDescription().GetAscii()); } + } + if (!this->lResult.IsOK()) + { + printLastError("Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; + } - //printf( "Aborting buffers still in stream\n" ); - lStream->AbortQueuedBuffers(); - while ( lStream->GetQueuedBufferCount() > 0 ) + // If present reset TLParamsLocked to 0. Must be done AFTER the + // streaming has been stopped + if (lTLLocked != NULL) + { + this->lResult = lTLLocked->SetValue(0); + if (!this->lResult.IsOK()) { - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - lStream->RetrieveBuffer( &lBuffer, &lOperationResult ); - //printf( " Post-abort retrieved buffer: %s\n", lOperationResult.GetCodeString().GetAscii() ); + printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + return ERROR; } + } - //printf( "Releasing buffers\n" ); - delete []lBuffers; + //printf( "Aborting buffers still in stream\n" ); + lStream->AbortQueuedBuffers(); + while (lStream->GetQueuedBufferCount() > 0) + { + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + lStream->RetrieveBuffer(&lBuffer, &lOperationResult); + //printf( " Post-abort retrieved buffer: %s\n", lOperationResult.GetCodeString().GetAscii() ); + } - // Now close the stream. Also optionnal but nice to have - printf( "Closing stream\n" ); - lStream->Close(); + //printf( "Releasing buffers\n" ); + delete[] lBuffers; + // Now close the stream. Also optionnal but nice to have + printf("Closing stream\n"); + lStream->Close(); - return SUCCESS; + return SUCCESS; } - int PTGREY::getFrame(int *status, void *frame, void *metaData) { -//status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete - // char lDoodle[] = "|\\-|-/"; - // static int lDoodleIndex = 0; - int64_t lImageCountVal = 0; - double lFrameRateVal = 0.0; - double lBandwidthVal = 0.0; - - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - - // Get stream parameters/stats - PvGenParameterArray *lStreamParams = lStream->GetParameters(); - PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); - PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); - PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); - - *status=2; //frame incomplete by default - // ++lDoodleIndex %= 6; - - // Retrieve next buffer - //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); - int timeOut = int (1./this->frameRate * 1000.) + 100; - this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, timeOut ); //Set timeOut to the frame period plus 100ms - - - - //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); - if ( this->lResult.IsOK() ) + //status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + // char lDoodle[] = "|\\-|-/"; + // static int lDoodleIndex = 0; + int64_t lImageCountVal = 0; + double lFrameRateVal = 0.0; + double lBandwidthVal = 0.0; + + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + + // Get stream parameters/stats + PvGenParameterArray *lStreamParams = lStream->GetParameters(); + PvGenInteger *lCount = dynamic_cast(lStreamParams->Get("ImagesCount")); + PvGenFloat *lFrameRate = dynamic_cast(lStreamParams->Get("AcquisitionRateAverage")); + PvGenFloat *lBandwidth = dynamic_cast(lStreamParams->Get("BandwidthAverage")); + + *status = 2; //frame incomplete by default + // ++lDoodleIndex %= 6; + + // Retrieve next buffer + //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); + int timeOut = int(1. / this->frameRate * 1000.) + 100; + this->lResult = lStream->RetrieveBuffer(&lBuffer, &lOperationResult, timeOut); //Set timeOut to the frame period plus 100ms + + //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); + if (this->lResult.IsOK()) + { + if (lOperationResult.IsOK()) { - if(lOperationResult.IsOK()) - { - //lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 segmentation fault - lFrameRate->GetValue( lFrameRateVal ); - lBandwidth->GetValue( lBandwidthVal ); - - // If the buffer contains an image, display width and height - uint32_t lWidth = 0, lHeight = 0; - if ( lBuffer->GetPayloadType() == PvPayloadTypeImage ) - { - // Get image specific buffer interface - PvImage *lImage = lBuffer->GetImage(); - // Read width, height - lWidth = lImage->GetWidth(); - lHeight = lImage->GetHeight(); - currTime = lBuffer->GetTimestamp(); - - currIdx = lBuffer->GetBlockID(); - //if( triggered && currIdx != lastIdx+1) - //if( triggered) - // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); - lastTime = currTime; - lastIdx = currIdx; -/* + //lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 segmentation fault + lFrameRate->GetValue(lFrameRateVal); + lBandwidth->GetValue(lBandwidthVal); + + // If the buffer contains an image, display width and height + uint32_t lWidth = 0, lHeight = 0; + if (lBuffer->GetPayloadType() == PvPayloadTypeImage) + { + // Get image specific buffer interface + PvImage *lImage = lBuffer->GetImage(); + // Read width, height + lWidth = lImage->GetWidth(); + lHeight = lImage->GetHeight(); + currTime = lBuffer->GetTimestamp(); + + currIdx = lBuffer->GetBlockID(); + //if( triggered && currIdx != lastIdx+1) + //if( triggered) + // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); + lastTime = currTime; + lastIdx = currIdx; + /* printf( "%c Timestamp: %016llX BlockID: %04X W: %i H: %i %.01f FPS %.01f Mb/s\r", lDoodle[ lDoodleIndex ], lBuffer->GetTimestamp(), @@ -1061,381 +1108,371 @@ int PTGREY::getFrame(int *status, void *frame, void *metaData) lFrameRateVal, lBandwidthVal / 1000000.0 ); */ - unsigned int width = lWidth; - unsigned int height = lHeight; - - // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! - // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for SDK3 - uint8_t* dataPtr = lBuffer->GetDataPointer(); //8 mar 2016 for SDK4 - - //last 3 rows of the frame are metadata - //memcpy( frame , (unsigned char *)dataPtr, width*height ); //20191107 - memcpy( frame , (unsigned char *)dataPtr, width*height*this->Bpp ); //20191107 - // memcpy( metaData , (unsigned char *)dataPtr+(width*2*(height-3)), width*2*3 ); - - - //printf("metadata size: %d\n", sizeof(BASLERMETADATA)); - PTGREYMETADATA pgMeta; - pgMeta.gain=this->gain; - pgMeta.exposure=this->exposure; - pgMeta.internalTemperature=this->internalTemperature; - pgMeta.timestamp=currTime; - memcpy( metaData , (unsigned char *)&pgMeta, sizeof(PTGREYMETADATA)); - - *status=1; //complete - } - } - else //new 28 agosto 2012 - { - *status=2; //incomplete - //printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); - printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), lBuffer->GetPayloadType() ); - incompleteFrame++; - } - // We have an image - do some processing (...) and VERY IMPORTANT, - // re-queue the buffer in the stream object - lStream->QueueBuffer( lBuffer ); - return SUCCESS; + unsigned int width = lWidth; + unsigned int height = lHeight; + + // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! + // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for SDK3 + uint8_t *dataPtr = lBuffer->GetDataPointer(); //8 mar 2016 for SDK4 + + //last 3 rows of the frame are metadata + //memcpy( frame , (unsigned char *)dataPtr, width*height ); //20191107 + memcpy(frame, (unsigned char *)dataPtr, width * height * this->Bpp); //20191107 + // memcpy( metaData , (unsigned char *)dataPtr+(width*2*(height-3)), width*2*3 ); + + //printf("metadata size: %d\n", sizeof(BASLERMETADATA)); + PTGREYMETADATA pgMeta; + pgMeta.gain = this->gain; + pgMeta.exposure = this->exposure; + pgMeta.internalTemperature = this->internalTemperature; + pgMeta.timestamp = currTime; + memcpy(metaData, (unsigned char *)&pgMeta, sizeof(PTGREYMETADATA)); + + *status = 1; //complete + } } - else// Timeout - { - printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii() ); - printLastError("Error reading frame!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); - *status=3; //timeout -// printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); - return ERROR; + else //new 28 agosto 2012 + { + *status = 2; //incomplete + //printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); + printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), lBuffer->GetPayloadType()); + incompleteFrame++; } - + // We have an image - do some processing (...) and VERY IMPORTANT, + // re-queue the buffer in the stream object + lStream->QueueBuffer(lBuffer); + return SUCCESS; + } + else // Timeout + { + printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii()); + printLastError("Error reading frame!!!\n(%s)\n", lResult.GetDescription().GetAscii()); + *status = 3; //timeout + // printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); + return ERROR; + } } +int PTGREY::setStreamingMode(int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + this->streamingEnabled = streamingEnabled; + if (streamingEnabled) + { + memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); + memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); + this->streamingPort = streamingPort; + this->autoAdjustLimit = autoAdjustLimit; -int PTGREY::setStreamingMode( int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) -{ - this->streamingEnabled = streamingEnabled; - - if( streamingEnabled ) - { - memcpy( this->streamingServer, streamingServer, strlen(streamingServer)+1 ); - memcpy( this->deviceName, deviceName, strlen(deviceName)+1 ); - this->streamingPort = streamingPort; - this->autoAdjustLimit = autoAdjustLimit; - - this->lowLim = lowLim; - this->highLim = highLim; - - this->adjRoiX = adjRoiX; - this->adjRoiY = adjRoiY; - this->adjRoiW = adjRoiW; - this->adjRoiH = adjRoiH; - - this->minLim= 0; - this->maxLim= 4096; //max value for 12bit resolution of BASLER - } - else - { - printf("Streaming DISABLED\n"); - } - return SUCCESS; -} - - -int PTGREY::setAcquisitionMode( int storeEnabled , int acqSkipFrameNumber) + this->lowLim = lowLim; + this->highLim = highLim; + + this->adjRoiX = adjRoiX; + this->adjRoiY = adjRoiY; + this->adjRoiW = adjRoiW; + this->adjRoiH = adjRoiH; + + this->minLim = 0; + this->maxLim = 4096; //max value for 12bit resolution of BASLER + } + else + { + printf("Streaming DISABLED\n"); + } + return SUCCESS; +} + +int PTGREY::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) { - this->storeEnabled = storeEnabled; - this->acqSkipFrameNumber = acqSkipFrameNumber; - return SUCCESS; + this->storeEnabled = storeEnabled; + this->acqSkipFrameNumber = acqSkipFrameNumber; + return SUCCESS; } -int PTGREY::setTriggerMode( int triggerMode, double burstDuration, int numTrigger ) +int PTGREY::setTriggerMode(int triggerMode, double burstDuration, int numTrigger) { - this->triggerMode = triggerMode; - this->burstDuration = burstDuration; - this->numTrigger = numTrigger; + this->triggerMode = triggerMode; + this->burstDuration = burstDuration; + this->numTrigger = numTrigger; - return SUCCESS; + return SUCCESS; } int PTGREY::softwareTrigger() { - this->startStoreTrg = 1; - return SUCCESS; + this->startStoreTrg = 1; + return SUCCESS; } -int PTGREY::setTreeInfo( void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +int PTGREY::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) { - this->treePtr = treePtr ; - this->framesNid = framesNid; - this->timebaseNid = timebaseNid; - this->framesMetadNid = framesMetadNid; - this->frame0TimeNid = frame0TimeNid; + this->treePtr = treePtr; + this->framesNid = framesNid; + this->timebaseNid = timebaseNid; + this->framesMetadNid = framesMetadNid; + this->frame0TimeNid = frame0TimeNid; - return SUCCESS; + return SUCCESS; } - void PTGREY::printLastError(const char *format, const char *msg) { - error[0] = 0; - if(msg) - sprintf(error, format, msg ); - else - sprintf(error, format); + error[0] = 0; + if (msg) + sprintf(error, format, msg); + else + sprintf(error, format); } - void PTGREY::getLastError(char *msg) { - sprintf(msg, RED "%s" RESET, (error[0]==0) ? "" : error); + sprintf(msg, RED "%s" RESET, (error[0] == 0) ? "" : error); } int PTGREY::stopFramesAcquisition() { - int count = 0; - - if (acqFlag == 0) - return SUCCESS; - - acqFlag = 0; - while( !acqStopped & count < 20 ) - { - count++; - usleep(50000); //20190829 FM: 5000->50000 - } - - if(count == 20) - { - printLastError("Cannot stop acquisition loop", 0); - return ERROR; - } - - - return SUCCESS; + int count = 0; + + if (acqFlag == 0) + return SUCCESS; + + acqFlag = 0; + while (!acqStopped & count < 20) + { + count++; + usleep(50000); //20190829 FM: 5000->50000 + } + + if (count == 20) + { + printLastError("Cannot stop acquisition loop", 0); + return ERROR; + } + + return SUCCESS; } int PTGREY::startFramesAcquisition() { - int frameTriggerCounter; - int frameCounter; - int frameStatus; - - int NtriggerCount = 0; - int burstNframe; - int rstatus; - int tcpStreamHandle = -1; - - int metaSize; - int savedFrameNumber; - float frameTime = 0.0; - float timeOffset = 0.0; //20200901 - void *saveList; - void *streamingList; - -// short *frameBuffer; //20191107 -// short *metaData; - - void *frameBuffer; - unsigned char *metaData; - unsigned char *frame8bit; - - struct timeval tv; //manage frame timestamp in internal mode - int64_t timeStamp; - int64_t timeStamp0; - - TreeNode *t0Node; - try{ - t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); - Data *nodeData = t0Node->getData(); - timeStamp0 = (int64_t)nodeData->getLong(); - }catch(MdsException *exc) - { - printf("Error getting frame0 time\n"); - } - - - if ( triggerMode != 1 ) //20200901: in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) - { - TreeNode *tStartOffset; - try{ - tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); - Data *nodeData = tStartOffset->getData(); - timeOffset = (float)nodeData->getFloatArray()[0]; - }catch(MdsException *exc) - { - printf("Error getting timebaseNid (offset time set to 0.0s)\n"); - timeOffset=0.0; - } - } + int frameTriggerCounter; + int frameCounter; + int frameStatus; + + int NtriggerCount = 0; + int burstNframe; + int rstatus; + int tcpStreamHandle = -1; + + int metaSize; + int savedFrameNumber; + float frameTime = 0.0; + float timeOffset = 0.0; //20200901 + void *saveList; + void *streamingList; + + // short *frameBuffer; //20191107 + // short *metaData; + + void *frameBuffer; + unsigned char *metaData; + unsigned char *frame8bit; + + struct timeval tv; //manage frame timestamp in internal mode + int64_t timeStamp; + int64_t timeStamp0; + + TreeNode *t0Node; + try + { + t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); + Data *nodeData = t0Node->getData(); + timeStamp0 = (int64_t)nodeData->getLong(); + } + catch (MdsException *exc) + { + printf("Error getting frame0 time\n"); + } + if (triggerMode != 1) //20200901: in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) + { + TreeNode *tStartOffset; + try + { + tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); + Data *nodeData = tStartOffset->getData(); + timeOffset = (float)nodeData->getFloatArray()[0]; + } + catch (MdsException *exc) + { + printf("Error getting timebaseNid (offset time set to 0.0s)\n"); + timeOffset = 0.0; + } + } - if(this->Bpp==1) - { - frameBuffer = (char *) calloc(1, width * height * sizeof(char)); - } - if(this->Bpp==2) - { - frameBuffer = (short *) calloc(1, width * height * sizeof(short)); - } - frame8bit = (unsigned char *) calloc(1, width * height * sizeof(char)); + if (this->Bpp == 1) + { + frameBuffer = (char *)calloc(1, width * height * sizeof(char)); + } + if (this->Bpp == 2) + { + frameBuffer = (short *)calloc(1, width * height * sizeof(short)); + } + frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); - metaSize = sizeof(PTGREYMETADATA); - metaData = (unsigned char *)calloc(1, metaSize); + metaSize = sizeof(PTGREYMETADATA); + metaData = (unsigned char *)calloc(1, metaSize); - camStartSave(&saveList); // # Initialize save frame Linked list reference + camStartSave(&saveList); // # Initialize save frame Linked list reference - camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference + camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference - burstNframe = (int) ( burstDuration * frameRate + 1 ); + burstNframe = (int)(burstDuration * frameRate + 1); - acqFlag = 1; - frameTriggerCounter = 0; - frameCounter = 0; - incompleteFrame = 0; - savedFrameNumber = 0; + acqFlag = 1; + frameTriggerCounter = 0; + frameCounter = 0; + incompleteFrame = 0; + savedFrameNumber = 0; - startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) + startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) - acqStopped = 0;//CT 2021 02 04 + acqStopped = 0; //CT 2021 02 04 - while ( acqFlag ) - { - getFrame( &frameStatus, frameBuffer, metaData); //get the frame - - if(storeEnabled) + while (acqFlag) + { + getFrame(&frameStatus, frameBuffer, metaData); //get the frame + + if (storeEnabled) + { + if (triggerMode == 1) // External trigger source + { + + if ((frameStatus == 4 || eventTrigger == 1) && (startStoreTrg == 0)) //start data storing @ 1st trigger seen (trigger is on image header!) + //CT In External Trigger Mode acquisition is also triggered on MDSevent { - if ( triggerMode == 1 ) // External trigger source - { - - if ( (frameStatus == 4 || eventTrigger == 1 ) && (startStoreTrg == 0) ) //start data storing @ 1st trigger seen (trigger is on image header!) - //CT In External Trigger Mode acquisition is also triggered on MDSevent - { - startStoreTrg = 1; - eventTrigger = 0; //CT Reset MDSplus trigger event flag - printf("TRIGGERED: %d %d\n", frameStatus, eventTrigger); - } - - if (frameTriggerCounter == burstNframe) - { - triggered = 0; - startStoreTrg = 0; //disable storing - NtriggerCount++; - - printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", frameTriggerCounter-1, NtriggerCount ); - frameTriggerCounter = 0; - - if ( NtriggerCount == numTrigger ) //stop store when all trigger will be received - { - printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger ); - storeEnabled=0; - //break; - } - }//if (frameTriggerCounter == burstNframe) - - } - else //( triggerMode == 1 ) //Internal trigger source - { - //Multiple trigger acquisition: first trigger save 64bit timestamp - timebaseNid = -1; //used in cammdsutils to use internal - triggered = 1; //debug - - if(startStoreTrg == 1) - { - gettimeofday(&tv, NULL); - timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] - - if(timeStamp0==0) - { - Int64 *tsMDS = new Int64(timeStamp); - t0Node->putData(tsMDS); - timeStamp0=timeStamp; - } - else - { - frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] - //printf("frameTime: %f", frameTime); - } - }//if startStoreTrg == 1 - - if ( frameTriggerCounter == burstNframe ) - { - startStoreTrg = 0; //disable storing - frameTriggerCounter = 0; - NtriggerCount++; - printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, burstDuration, frameRate); - //storeEnabled=0; //infinite trigger until stop acquisition - //break; - } - }//else Internal trigger source - }//if(storeEnabled) - - - //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete - if( (frameStatus != 3 ) && ( storeEnabled == 1 && startStoreTrg == 1 ) && ( acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1) ) == 0 ) ) - { - int frameTimeBaseIdx; - frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; - - // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene - // utilizzato per individuare nell'array della base temporale il tempo associato al frame. - - // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 - if (timebaseNid == -1 ) - printf("DEBUG TO REMOVE 20200904 - FRAME TIME: (%s) %f\n", this->ipAddress.GetAscii(), frameTime+timeOffset); + startStoreTrg = 1; + eventTrigger = 0; //CT Reset MDSplus trigger event flag + printf("TRIGGERED: %d %d\n", frameStatus, eventTrigger); + } + + if (frameTriggerCounter == burstNframe) + { + triggered = 0; + startStoreTrg = 0; //disable storing + NtriggerCount++; + + printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", frameTriggerCounter - 1, NtriggerCount); + frameTriggerCounter = 0; + + if (NtriggerCount == numTrigger) //stop store when all trigger will be received + { + printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger); + storeEnabled = 0; + //break; + } + } //if (frameTriggerCounter == burstNframe) + } + else //( triggerMode == 1 ) //Internal trigger source + { + //Multiple trigger acquisition: first trigger save 64bit timestamp + timebaseNid = -1; //used in cammdsutils to use internal + triggered = 1; //debug + + if (startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] + + if (timeStamp0 == 0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0 = timeStamp; + } else - printf("(%s) SAVE Num Tr : %2d Frame Tr. Cnt : %5d timebase Idx : %5d\n", this->ipAddress.GetAscii(), NtriggerCount, frameTriggerCounter, frameTimeBaseIdx); - camSaveFrame((void *)frameBuffer, width, height, frameTime+timeOffset, 8*this->Bpp, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); - savedFrameNumber++; - } - - if( streamingEnabled ) - { - if( tcpStreamHandle == -1) - { - rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); - if( rstatus !=-1 ) - { - printf( "Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); - } - else - { - printf( "Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); - streamingEnabled = 0; - } - } - //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL - else if((this->frameRate<10) || (frameCounter % int(this->frameRate/10.0))==0) //send frame @ 10Hz. Reduce CPU usage when radiometric conversion must be performed. - { - camStreamingFrame( tcpStreamHandle, frameBuffer, width, height, pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); - } - } // if( streamingEnabled ) - - frameCounter++; //never resetted, used for frame timestamp - if ( startStoreTrg == 1 ) //CT incremento l'indice dei frame salvato solo se l'acquisizione e' stata triggerata + { + frameTime = (float)((timeStamp - timeStamp0) / 1000.0); //interval from first frame [s] + //printf("frameTime: %f", frameTime); + } + } //if startStoreTrg == 1 + + if (frameTriggerCounter == burstNframe) { - frameTriggerCounter++; + startStoreTrg = 0; //disable storing + frameTriggerCounter = 0; + NtriggerCount++; + printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, burstDuration, frameRate); + //storeEnabled=0; //infinite trigger until stop acquisition + //break; } - }//endwhile + } //else Internal trigger source + } //if(storeEnabled) - camStopSave(saveList); // Stop asynhronous store stream - camStopStreaming(streamingList); // Stop asynhronous frame streaming + //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && (acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) + { + int frameTimeBaseIdx; + frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; + + // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene + // utilizzato per individuare nell'array della base temporale il tempo associato al frame. + + // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 + if (timebaseNid == -1) + printf("DEBUG TO REMOVE 20200904 - FRAME TIME: (%s) %f\n", this->ipAddress.GetAscii(), frameTime + timeOffset); + else + printf("(%s) SAVE Num Tr : %2d Frame Tr. Cnt : %5d timebase Idx : %5d\n", this->ipAddress.GetAscii(), NtriggerCount, frameTriggerCounter, frameTimeBaseIdx); + camSaveFrame((void *)frameBuffer, width, height, frameTime + timeOffset, 8 * this->Bpp, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); + savedFrameNumber++; + } - if( tcpStreamHandle != -1 ) - camCloseTcpConnection(&tcpStreamHandle); + if (streamingEnabled) + { + if (tcpStreamHandle == -1) + { + rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); + if (rstatus != -1) + { + printf("Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); + } + else + { + printf("Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); + streamingEnabled = 0; + } + } + //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL + else if ((this->frameRate < 10) || (frameCounter % int(this->frameRate / 10.0)) == 0) //send frame @ 10Hz. Reduce CPU usage when radiometric conversion must be performed. + { + camStreamingFrame(tcpStreamHandle, frameBuffer, width, height, pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); + } + } // if( streamingEnabled ) + + frameCounter++; //never resetted, used for frame timestamp + if (startStoreTrg == 1) //CT incremento l'indice dei frame salvato solo se l'acquisizione e' stata triggerata + { + frameTriggerCounter++; + } + } //endwhile - rstatus = stopAcquisition(); //stop camera acquisition - if (rstatus < 0) - printf(RED " Cannot stop camera acquisition \n" RESET ); + camStopSave(saveList); // Stop asynhronous store stream + camStopStreaming(streamingList); // Stop asynhronous frame streaming - - free(frameBuffer); - free(frame8bit); - free(metaData); + if (tcpStreamHandle != -1) + camCloseTcpConnection(&tcpStreamHandle); - printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\tIncomplete frame %d\n", frameCounter, savedFrameNumber, numTrigger * (1+(int)( burstDuration * (frameRate-acqSkipFrameNumber))), NtriggerCount + startStoreTrg, numTrigger, incompleteFrame ); + rstatus = stopAcquisition(); //stop camera acquisition + if (rstatus < 0) + printf(RED " Cannot stop camera acquisition \n" RESET); - acqStopped = 1; + free(frameBuffer); + free(frame8bit); + free(metaData); - return rstatus; -} + printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\tIncomplete frame %d\n", frameCounter, savedFrameNumber, numTrigger * (1 + (int)(burstDuration * (frameRate - acqSkipFrameNumber))), NtriggerCount + startStoreTrg, numTrigger, incompleteFrame); + + acqStopped = 1; + return rstatus; +} diff --git a/device_support/ptgrey/PTGREY.h b/device_support/ptgrey/PTGREY.h index 51dae69500..baedfbb14c 100644 --- a/device_support/ptgrey/PTGREY.h +++ b/device_support/ptgrey/PTGREY.h @@ -5,236 +5,230 @@ #include #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 using namespace MDSplus; -#define RESET "\033[0m" -#define BLACK "\033[30m" /* Black */ -#define RED "\033[31m" /* Red */ -#define GREEN "\033[32m" /* Green */ -#define YELLOW "\033[33m" /* Yellow */ -#define BLUE "\033[34m" /* Blue */ -#define MAGENTA "\033[35m" /* Magenta */ -#define CYAN "\033[36m" /* Cyan */ -#define WHITE "\033[37m" /* White */ -#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ -#define BOLDRED "\033[1m\033[31m" /* Bold Red */ -#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ -#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ -#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ -#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ -#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ -#define BOLDWHITE "\033[1m\033[37m" /* Bold White */ - - -#ifdef __cplusplus -extern "C" -{ -#endif - -//extern int flirRadiometricConv(void *frame, int width, int height, void *metaData); - -// Wrapper for Python that must see the cpp class as standard C functions +#define RESET "\033[0m" +#define BLACK "\033[30m" /* Black */ +#define RED "\033[31m" /* Red */ +#define GREEN "\033[32m" /* Green */ +#define YELLOW "\033[33m" /* Yellow */ +#define BLUE "\033[34m" /* Blue */ +#define MAGENTA "\033[35m" /* Magenta */ +#define CYAN "\033[36m" /* Cyan */ +#define WHITE "\033[37m" /* White */ +#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ +#define BOLDRED "\033[1m\033[31m" /* Bold Red */ +#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ +#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ +#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ +#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ +#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ +#define BOLDWHITE "\033[1m\033[37m" /* Bold White */ + +#ifdef __cplusplus +extern "C" +{ +#endif -int PGopen(const char *cameraName, int *camHandle); -int PGclose(int camHandle); -int checkLastOp(int camHandle); -int printAllParameters(int camHandle); -int readInternalTemperature(int camHandle); -int setExposure(int camHandle, float exposure); -int setExposureAuto(int camHandle, char *exposureAuto); -int setGammaEnable(int camHandle, char *gammaEnable); -int setGain(int camHandle, float gain); -int setGainAuto(int camHandle, char *gainAuto); + //extern int flirRadiometricConv(void *frame, int width, int height, void *metaData); + // Wrapper for Python that must see the cpp class as standard C functions -//int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); -//int setFrameRateNew(int camHandle, double frameRate); -int setFrameRate(int camHandle, double *frameRate); + int PGopen(const char *cameraName, int *camHandle); + int PGclose(int camHandle); + int checkLastOp(int camHandle); + int printAllParameters(int camHandle); + int readInternalTemperature(int camHandle); + int setExposure(int camHandle, float exposure); + int setExposureAuto(int camHandle, char *exposureAuto); + int setGammaEnable(int camHandle, char *gammaEnable); + int setGain(int camHandle, float gain); + int setGainAuto(int camHandle, char *gainAuto); -//int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); -int setReadoutArea(int camHandle, int x, int y, int width, int height); - -int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber ); + //int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); + //int setFrameRateNew(int camHandle, double frameRate); + int setFrameRate(int camHandle, double *frameRate); -int setPixelFormat(int camHandle, char *pixelFormat); + //int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); + int setReadoutArea(int camHandle, int x, int y, int width, int height); -int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); -int stopAcquisition(int camHandle); -int getFrame(int camHandle, int *status, void *frame, void *metaData); -//int frameConv(int camHandle, unsigned short *frame, int width, int height); -int startFramesAcquisition(int camHandle); -int stopFramesAcquisition(int camHandle); + int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); + int setPixelFormat(int camHandle, char *pixelFormat); -int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); + int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); + int stopAcquisition(int camHandle); + int getFrame(int camHandle, int *status, void *frame, void *metaData); + //int frameConv(int camHandle, unsigned short *frame, int width, int height); + int startFramesAcquisition(int camHandle); + int stopFramesAcquisition(int camHandle); -int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger ); -int softwareTrigger(int camHandle); -int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); + int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); -void getLastError(int camHandle, char *msg); + int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger); + int softwareTrigger(int camHandle); + int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); -#ifdef __cplusplus -} -#endif + void getLastError(int camHandle, char *msg); +#ifdef __cplusplus +} +#endif -typedef struct _ptgreyMetaData +typedef struct _ptgreyMetaData { - float gain; - float exposure; - float internalTemperature; - int64_t timestamp; -}PTGREYMETADATA; - + float gain; + float exposure; + float internalTemperature; + int64_t timestamp; +} PTGREYMETADATA; class PTGREY { - class TriggerMdsEvent:public Event - { - private: - PTGREY* ptGray; - public: - TriggerMdsEvent(const char *name, PTGREY* ptGr):Event(name) - { - ptGray = ptGr; - } - - void run() - { - size_t bufSize; - const char *name = getName(); //Get the name of the event - char *date = getTime()->getDate(); //Get the event reception date in string format - const char *buf = getRaw(&bufSize); //Get raw data - char *str = new char[bufSize+1]; //Make it a string - memcpy(str, buf, bufSize); - str[bufSize] = 0; - //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. - //An event trigger received during acquisition can reset the trigger count to extend the acquisition - if(ptGray->acqFlag && ptGray->storeEnabled && ptGray->startStoreTrg == 0) - { - printf("%s EVENT Trigger Start!!!!\n", (ptGray->ipAddress).GetAscii()); - ptGray->eventTrigger = 1; - } else { - printf("%s EVENT Trigger Reset!!!!\n", (ptGray->ipAddress).GetAscii()); - ptGray->eventTrigger = 0; - } - printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n",(ptGray->ipAddress).GetAscii() ,name, date, str, ptGray->eventTrigger); - delete str; - } - }; - - private: - PvDevice *lDevice; //camera handle - PvStream *lStream; //stream handle - PvBuffer *lBuffers; //buffer handle - PvResult lResult; //result of the latest operation - PvString ipAddress; //camera ip address - TriggerMdsEvent *trigEvent; - - int x; - int y; - int width; - int height; - int pixelFormat; //all pixelFormat supported are in camstreamutils.h - int Bpp; //Bytes per pixel - double frameRate; - float gain; - float exposure; - float internalTemperature; - - int storeEnabled; - int triggerMode; - int startStoreTrg; - int autoCalibration; - int irFrameFormat; - int eventTrigger; //CT on MDSplus event trigger flag - - - int streamingEnabled; - int streamingSkipFrameNumber; - char streamingServer[512]; - int streamingPort; - int autoScale; - unsigned int lowLim; - unsigned int highLim; - unsigned int minLim; - unsigned int maxLim; - bool autoAdjustLimit; - int adjRoiX; - int adjRoiY; - int adjRoiW; - int adjRoiH; - char deviceName[64]; - - int imageMode; - int acqSkipFrameNumber; - double burstDuration; - int numTrigger; - - void* treePtr; - int framesNid; - int timebaseNid; - int framesMetadNid; - int frame0TimeNid; - - int acqFlag; - int acqStopped; - char error[512]; - int incompleteFrame; - - //debug - uint64_t currTime, lastTime, currIdx, lastIdx, triggered; - int64_t tickFreq; - - - public: - //camera - PTGREY(const char *ipAddress); - PTGREY(); //new 23 July 2013 for test purposes - ~PTGREY(); - - //info - int checkLastOp(); - int printAllParameters(); - - //settings - int readInternalTemperature(); - int setExposure(float exposure); - int setExposureAuto(char *exposureAuto); - int setGain(float gain); - int setGainAuto(char *gainAuto); - int setGammaEnable(char *gammaEnable); - int setFrameRate(double &frameRate); -// int setFrameRate(FPS_ENUM fps, int *frameToSkip); -// int getReadoutArea(int *x, int *y, int *width, int *height); - int setReadoutArea(int x, int y, int width, int height); - int setPixelFormat(char *pixelFormat); - - int setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber); - int setStreamingMode( int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); - - int setTriggerMode( int triggerMode, double burstDuration, int numTrigger ); - int setTreeInfo( void *treePtr, int frameNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); - - void getLastError(char *msg); - void printLastError(const char *format, const char *msg); - - //acquisition - int startAcquisition(int *width, int *height, int *payloadSize); - int stopAcquisition(); - int softwareTrigger(); - int getFrame(int *status, void *frame, void *metaData); + class TriggerMdsEvent : public Event + { + private: + PTGREY *ptGray; + + public: + TriggerMdsEvent(const char *name, PTGREY *ptGr) : Event(name) + { + ptGray = ptGr; + } + + void run() + { + size_t bufSize; + const char *name = getName(); //Get the name of the event + char *date = getTime()->getDate(); //Get the event reception date in string format + const char *buf = getRaw(&bufSize); //Get raw data + char *str = new char[bufSize + 1]; //Make it a string + memcpy(str, buf, bufSize); + str[bufSize] = 0; + //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. + //An event trigger received during acquisition can reset the trigger count to extend the acquisition + if (ptGray->acqFlag && ptGray->storeEnabled && ptGray->startStoreTrg == 0) + { + printf("%s EVENT Trigger Start!!!!\n", (ptGray->ipAddress).GetAscii()); + ptGray->eventTrigger = 1; + } + else + { + printf("%s EVENT Trigger Reset!!!!\n", (ptGray->ipAddress).GetAscii()); + ptGray->eventTrigger = 0; + } + printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n", (ptGray->ipAddress).GetAscii(), name, date, str, ptGray->eventTrigger); + delete str; + } + }; + +private: + PvDevice *lDevice; //camera handle + PvStream *lStream; //stream handle + PvBuffer *lBuffers; //buffer handle + PvResult lResult; //result of the latest operation + PvString ipAddress; //camera ip address + TriggerMdsEvent *trigEvent; + + int x; + int y; + int width; + int height; + int pixelFormat; //all pixelFormat supported are in camstreamutils.h + int Bpp; //Bytes per pixel + double frameRate; + float gain; + float exposure; + float internalTemperature; + + int storeEnabled; + int triggerMode; + int startStoreTrg; + int autoCalibration; + int irFrameFormat; + int eventTrigger; //CT on MDSplus event trigger flag + + int streamingEnabled; + int streamingSkipFrameNumber; + char streamingServer[512]; + int streamingPort; + int autoScale; + unsigned int lowLim; + unsigned int highLim; + unsigned int minLim; + unsigned int maxLim; + bool autoAdjustLimit; + int adjRoiX; + int adjRoiY; + int adjRoiW; + int adjRoiH; + char deviceName[64]; + + int imageMode; + int acqSkipFrameNumber; + double burstDuration; + int numTrigger; + + void *treePtr; + int framesNid; + int timebaseNid; + int framesMetadNid; + int frame0TimeNid; + + int acqFlag; + int acqStopped; + char error[512]; + int incompleteFrame; + + //debug + uint64_t currTime, lastTime, currIdx, lastIdx, triggered; + int64_t tickFreq; + +public: + //camera + PTGREY(const char *ipAddress); + PTGREY(); //new 23 July 2013 for test purposes + ~PTGREY(); + + //info + int checkLastOp(); + int printAllParameters(); + + //settings + int readInternalTemperature(); + int setExposure(float exposure); + int setExposureAuto(char *exposureAuto); + int setGain(float gain); + int setGainAuto(char *gainAuto); + int setGammaEnable(char *gammaEnable); + int setFrameRate(double &frameRate); + // int setFrameRate(FPS_ENUM fps, int *frameToSkip); + // int getReadoutArea(int *x, int *y, int *width, int *height); + int setReadoutArea(int x, int y, int width, int height); + int setPixelFormat(char *pixelFormat); + + int setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber); + int setStreamingMode(int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); + + int setTriggerMode(int triggerMode, double burstDuration, int numTrigger); + int setTreeInfo(void *treePtr, int frameNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); + + void getLastError(char *msg); + void printLastError(const char *format, const char *msg); + + //acquisition + int startAcquisition(int *width, int *height, int *payloadSize); + int stopAcquisition(); + int softwareTrigger(); + int getFrame(int *status, void *frame, void *metaData); // int frameConv(unsigned short *frame, int width, int height); - int startFramesAcquisition(); - int stopFramesAcquisition(); - - - protected: + int startFramesAcquisition(); + int stopFramesAcquisition(); +protected: }; diff --git a/device_support/ptgrey/main.cpp b/device_support/ptgrey/main.cpp index ec15ffdd10..cd2e0e11bf 100644 --- a/device_support/ptgrey/main.cpp +++ b/device_support/ptgrey/main.cpp @@ -31,33 +31,30 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include - //using namespace MDSplus; using namespace std; +#define USETHECAMERA //this let to use the camera or if not defined to read data from a pulse file. -#define USETHECAMERA //this let to use the camera or if not defined to read data from a pulse file. - - -int main(int argc, char **argv ) +int main(int argc, char **argv) { - if((argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL)) // argv[4] is OPTIONAL - { - printf("Please insert: 1)tree name 2)shot number 3)number of frame to acquire 4) Streaming Port (OPTIONAL)\n"); - exit(0); + if ((argv[1] == NULL) || (argv[2] == NULL) || (argv[3] == NULL)) // argv[4] is OPTIONAL + { + printf("Please insert: 1)tree name 2)shot number 3)number of frame to acquire 4) Streaming Port (OPTIONAL)\n"); + exit(0); } -//MDSPLUS + //MDSPLUS int res; void *treePtr; - res=camOpenTree(argv[1], atoi( argv[2] ), &treePtr); - if(res==-1) + res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); + if (res == -1) { - printf("Error opening tree...\n"); - exit(0); + printf("Error opening tree...\n"); + exit(0); } - MDSplus::Tree *tree; + MDSplus::Tree *tree; MDSplus::TreeNode *node; MDSplus::TreeNode *nodeMeta; int dataNid; @@ -65,147 +62,152 @@ int main(int argc, char **argv ) try { tree = (MDSplus::Tree *)treePtr; - node=tree->getNode((char *)"\\CAMERATEST::TOP:POINTGREY:FRAMES"); - nodeMeta=tree->getNode((char *)"\\CAMERATEST::TOP:POINTGREY:FRAMES_METAD"); - dataNid=node->getNid(); //Node id to save the acquired frames - }catch (MDSplus::MdsException *exc ) - { std::cout << "ERROR reading data" << exc->what() << "\n"; } + node = tree->getNode((char *)"\\CAMERATEST::TOP:POINTGREY:FRAMES"); + nodeMeta = tree->getNode((char *)"\\CAMERATEST::TOP:POINTGREY:FRAMES_METAD"); + dataNid = node->getNid(); //Node id to save the acquired frames + } + catch (MDSplus::MdsException *exc) + { + std::cout << "ERROR reading data" << exc->what() << "\n"; + } printf("frame node path: %s\n", node->getPath()); -//MDSPLUS END - - + //MDSPLUS END #ifndef USETHECAMERA -/*read frame and metadata from stored pulse file and use Radiometric Conversion*/ + /*read frame and metadata from stored pulse file and use Radiometric Conversion*/ - Array *frameArray; - Array *frameArrayMeta; - int *shape; - int *shapeMeta; - int nEle = 3; + Array *frameArray; + Array *frameArrayMeta; + int *shape; + int *shapeMeta; + int nEle = 3; - Data *frameData; - Data *frameDataMeta; - short *framePtr; - char *framePtrMeta; + Data *frameData; + Data *frameDataMeta; + short *framePtr; + char *framePtrMeta; - try - { - frameArray = node->getSegment(0); //idx - frameArrayMeta = nodeMeta->getSegment(0); //idx - - shape = (frameArray)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte - shapeMeta = (frameArrayMeta)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte + try + { + frameArray = node->getSegment(0); //idx + frameArrayMeta = nodeMeta->getSegment(0); //idx - int numbytes = shape[1]; - int numframes = shape[0]; + shape = (frameArray)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte + shapeMeta = (frameArrayMeta)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte - frameData = (frameArray)->getElementAt(0); - frameDataMeta = (frameArrayMeta)->getElementAt(0); + int numbytes = shape[1]; + int numframes = shape[0]; - int dataDims[3]; - int dataDimsMeta[3]; - framePtr = (frameData)->getShortArray(dataDims); - framePtrMeta = (frameDataMeta)->getByteArray(dataDimsMeta); - } - catch ( MdsException *exc ) - { std::cout << "ERROR reading data" << exc->what() << "\n"; } + frameData = (frameArray)->getElementAt(0); + frameDataMeta = (frameArrayMeta)->getElementAt(0); + int dataDims[3]; + int dataDimsMeta[3]; + framePtr = (frameData)->getShortArray(dataDims); + framePtrMeta = (frameDataMeta)->getByteArray(dataDimsMeta); + } + catch (MdsException *exc) + { + std::cout << "ERROR reading data" << exc->what() << "\n"; + } - PTGREY *PtgreyCam; - PtgreyCam = new PTGREY(); //open without ip adress because we not use a phisical camera! + PTGREY *PtgreyCam; + PtgreyCam = new PTGREY(); //open without ip adress because we not use a phisical camera! #endif - #ifdef USETHECAMERA -//INIT STREAMING - int kSockHandle=-1; //MUST BE -1 THE FIRST TIME !!! - int i=1; - int canStream=-1; + //INIT STREAMING + int kSockHandle = -1; //MUST BE -1 THE FIRST TIME !!! + int i = 1; + int canStream = -1; -if(argv[4]!=NULL) -{ + if (argv[4] != NULL) + { - while(canStream==-1 && i<=5) //try 5 times to open the connection - { - canStream=camOpenTcpConnection((const char *)"127.0.0.1", atoi(argv[4]), &kSockHandle, 640, 480, CSU_PIX_FMT_GRAY16); - sleep(1); - i++; + while (canStream == -1 && i <= 5) //try 5 times to open the connection + { + canStream = camOpenTcpConnection((const char *)"127.0.0.1", atoi(argv[4]), &kSockHandle, 640, 480, CSU_PIX_FMT_GRAY16); + sleep(1); + i++; + } + if (canStream == 0) + { + printf("Streaming OK!\n"); + } + else + { + printf("CANNOT Streaming!\n"); + } } - if(canStream==0) - { - printf("Streaming OK!\n"); + //END STREAMING + + //FLIR + + PTGREY *PtgreyCam; + PtgreyCam = new PTGREY("192.168.100.18"); + if (!PtgreyCam->checkLastOp()) + { + printf("Unable to connect!!!\n"); + exit(0); } else - { - printf("CANNOT Streaming!\n"); + { + printf("Successfully connected...\n"); } -} -//END STREAMING + int skipFrame = 0; + int width = 0; + int height = 0; + int payloadSize = 0; + int x, y = 0; + printf("\nGETTING ALL CAMERA PARAMETERS: start\n"); + PtgreyCam->printAllParameters(); + printf("\nGETTING ALL CAMERA PARAMETERS: end\n\n"); -//FLIR - - PTGREY *PtgreyCam; - PtgreyCam = new PTGREY("192.168.100.18"); - if(!PtgreyCam->checkLastOp()) - { - printf("Unable to connect!!!\n"); - exit(0); - } - else - { - printf("Successfully connected...\n"); - } - - int skipFrame = 0; - int width=0; - int height=0; - int payloadSize=0; - int x,y=0; - - - printf("\nGETTING ALL CAMERA PARAMETERS: start\n"); - PtgreyCam->printAllParameters(); - printf("\nGETTING ALL CAMERA PARAMETERS: end\n\n"); - - - PtgreyCam->startAcquisition(&width, &height, &payloadSize); -// printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); + PtgreyCam->startAcquisition(&width, &height, &payloadSize); + // printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); int status; - void *metaData; - void *frame; + void *metaData; + void *frame; void *frame8bit; int frameNumber = 0; struct timeval tv; int64_t timeStamp; - frame=malloc(width*height*sizeof(short)); - frame8bit=malloc(width*height*sizeof(char)); - -// metaData=malloc(payloadSize-(width*height*sizeof(short))); - - for(int i=1; i<=atoi(argv[3]); i++) //acquire i=argv[3] frames - { - frameNumber++; - PtgreyCam->getFrame(&status, frame, metaData); - gettimeofday(&tv, NULL); - timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] - switch(status) - { - case 1: printf("get frame %d complete @ %ld\n", frameNumber, timeStamp); break; - case 2: printf("get frame %d incomplete @ %ld\n", frameNumber, timeStamp); break; - case 3: printf("get frame %d timeout @ %ld\n", frameNumber, timeStamp); break; - case 4: printf("get frame %d complete+triggered @ %ld\n", frameNumber, timeStamp); break; - } - - if(status==1 or status==4) - { - //SAVE FRAME IN MDSPLUS - -/* res=camSaveFrame(frame, width, height, &timeStamp, 14, treePtr, dataNid, -1, frameNumber); + frame = malloc(width * height * sizeof(short)); + frame8bit = malloc(width * height * sizeof(char)); + + // metaData=malloc(payloadSize-(width*height*sizeof(short))); + + for (int i = 1; i <= atoi(argv[3]); i++) //acquire i=argv[3] frames + { + frameNumber++; + PtgreyCam->getFrame(&status, frame, metaData); + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] + switch (status) + { + case 1: + printf("get frame %d complete @ %ld\n", frameNumber, timeStamp); + break; + case 2: + printf("get frame %d incomplete @ %ld\n", frameNumber, timeStamp); + break; + case 3: + printf("get frame %d timeout @ %ld\n", frameNumber, timeStamp); + break; + case 4: + printf("get frame %d complete+triggered @ %ld\n", frameNumber, timeStamp); + break; + } + + if (status == 1 or status == 4) + { + //SAVE FRAME IN MDSPLUS + + /* res=camSaveFrame(frame, width, height, &timeStamp, 14, treePtr, dataNid, -1, frameNumber); if(res==-1) { printf("Error in 'camSaveFrame'...\n"); @@ -216,35 +218,35 @@ if(argv[4]!=NULL) } */ + if (canStream == 0) + { + //STREAMING + if (skipFrame == 0) + printf("ERROR SKIPFRAME=0\n"); + int sendFrame = i % skipFrame; + if (canStream == 0 and sendFrame == 0) + { + //streaming is set to 640 x 480 in "camOpenTcpConnection". + //It must be changed to prevent strange image transmission! + unsigned int lowLim = 0; + unsigned int highLim = 32000; - if(canStream==0) - { - //STREAMING - if(skipFrame==0) printf("ERROR SKIPFRAME=0\n"); - int sendFrame = i % skipFrame; - if( canStream==0 and sendFrame==0 ) - { - //streaming is set to 640 x 480 in "camOpenTcpConnection". - //It must be changed to prevent strange image transmission! - unsigned int lowLim = 0; - unsigned int highLim = 32000; - - camFrameTo8bit((unsigned short *)frame, 640, 480, CSU_PIX_FMT_GRAY16, (unsigned char *)frame8bit, 1, &lowLim, &highLim, 2000, 62000, 0, 0, 640, 480); - // printf("LowLim:%d HighLim:%d\n",lowLim, highLim); - camSendFrameOnTcp(&kSockHandle, width, height, frame8bit); - } - }//if canStream - - } //if status=1 or 4 - - }//for - - if(kSockHandle!=-1) camCloseTcpConnection(&kSockHandle); //close streaming + camFrameTo8bit((unsigned short *)frame, 640, 480, CSU_PIX_FMT_GRAY16, (unsigned char *)frame8bit, 1, &lowLim, &highLim, 2000, 62000, 0, 0, 640, 480); + // printf("LowLim:%d HighLim:%d\n",lowLim, highLim); + camSendFrameOnTcp(&kSockHandle, width, height, frame8bit); + } + } //if canStream + + } //if status=1 or 4 + + } //for + + if (kSockHandle != -1) + camCloseTcpConnection(&kSockHandle); //close streaming // PtgreyCam->setCalibMode(1); //auto calib -// PtgreyCam->stopAcquisition(); - delete PtgreyCam; + // PtgreyCam->stopAcquisition(); + delete PtgreyCam; #endif - } diff --git a/device_support/raptor/cygnet.cpp b/device_support/raptor/cygnet.cpp index bff1a677a6..4cd31bab00 100644 --- a/device_support/raptor/cygnet.cpp +++ b/device_support/raptor/cygnet.cpp @@ -66,7 +66,8 @@ static double dSecPerTick = 1E-3; * In other environments, such as DOS, the operating system * isn't as helpful and the driver & frame grabber would remain open. */ -void sigintfunc(int sig) { +void sigintfunc(int sig) +{ /* * Some languages/environments don't allow * use of printf from a signal catcher. @@ -91,7 +92,8 @@ static void videoirqfunc(int sig) { fieldirqcount++; } /* * Open the XCLIB C Library for use. */ -int epixOpen(char *pcConfFile) { +int epixOpen(char *pcConfFile) +{ int status; if (isOpen) return 0; @@ -104,12 +106,15 @@ int epixOpen(char *pcConfFile) { DRIVERPARMS, "", pcConfFile); // ConfFile includes exposure time which seems to take // precedence over later serial commands - if (status >= 0) { + if (status >= 0) + { #ifdef DEBUG printf("Open OK\n"); #endif isOpen = true; - } else { + } + else + { printf("Open Error %d\a\a\n", status); pxd_mesgFault(UNITSMAP); return status; @@ -119,7 +124,8 @@ int epixOpen(char *pcConfFile) { printImageInfo(); #endif uint32 ticku[2]; - if (pxd_infoSysTicksUnits(ticku) == 0) { + if (pxd_infoSysTicksUnits(ticku) == 0) + { dSecPerTick = (double)ticku[0] / (double)ticku[1] * 1E-6; #ifdef DEBUG printf("Microseconds per tick: %f\n", dSecPerTick * 1E6); @@ -128,7 +134,8 @@ int epixOpen(char *pcConfFile) { return status; } -void epixClose(void) { +void epixClose(void) +{ pxd_PIXCIclose(); isOpen = false; } @@ -137,7 +144,8 @@ void epixClose(void) { /* * Report image frame buffer memory size */ -static void printFrameInfo(void) { +static void printFrameInfo(void) +{ printf("Image frame buffer memory size: %.3f Kbytes\n", (double)pxd_infoMemsize(UNITSMAP) / 1024); printf("Image frame buffers : %d\n", pxd_imageZdim()); @@ -147,7 +155,8 @@ static void printFrameInfo(void) { /* * Report image resolution. */ -static void printImageInfo(void) { +static void printImageInfo(void) +{ printf("Image resolution:\n"); printf("xdim = %d\n", pxd_imageXdim()); printf("ydim = %d\n", pxd_imageYdim()); @@ -159,14 +168,16 @@ static void printImageInfo(void) { /* * Capture */ -void epixStartVideoCapture(int iID) { +void epixStartVideoCapture(int iID) +{ pxd_goLivePair(iID, 1, 2); // should iID be converted to a unitmap? #ifdef DEBUG printf("Video capture started.\n"); #endif } -void epixStopVideoCapture(int iID) { +void epixStopVideoCapture(int iID) +{ pxd_goUnLive(iID); // should iID be converted to a unitmap? #ifdef DEBUG printf("Video capture stopped.\n"); @@ -191,7 +202,8 @@ void epixStopVideoCapture(int iID) { //since reference t=0 int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, int iTimeoutMs, void *pTree, void *pList, int *piBufIdx, - int *piFrameIdx, int *piBaseTicks, double *pdCurrTime) { + int *piFrameIdx, int *piBaseTicks, double *pdCurrTime) +{ int iUnitMap = 1 << (iID - 1); int iLastBufIdx, iCurrTicks; int iPixelsRead, iPixelsToRead, iPixelsX, iPixelsY; @@ -202,15 +214,18 @@ int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, iPixelsToRead = iPixelsX * iPixelsY; waitTime.tv_sec = 0; waitTime.tv_nsec = 5000000; // 5ms delay - if (*piBufIdx < 0) { + if (*piBufIdx < 0) + { iLastBufIdx = pxd_capturedBuffer(iUnitMap); // The first time captureFrame is called *piFrameIdx = 0; - } else + } + else iLastBufIdx = *piBufIdx; int iMaxCount = iTimeoutMs / 5; // Maximum number of iterations before timing out - for (int i = 0; i < iMaxCount; i++) { + for (int i = 0; i < iMaxCount; i++) + { int iLastCaptured = pxd_capturedBuffer(iUnitMap); if (iLastCaptured != iLastBufIdx) // A new frame arrived { @@ -226,7 +241,8 @@ int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, #ifdef DEBUG printf("FRAME %d READ AT TIME %f\n", *piFrameIdx, *pdCurrTime); #endif - if (iPixelsRead != iPixelsToRead) { + if (iPixelsRead != iPixelsToRead) + { if (iPixelsRead < 0) printf("pxd_readushort: %s\n", pxd_mesgErrorCode(iPixelsRead)); else @@ -239,7 +255,8 @@ int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, *piBufIdx = iLastCaptured; *piFrameIdx += 1; return 1; - } else // No new frame + } + else // No new frame nanosleep(&waitTime, NULL); } // If code arrives here timeout occurred @@ -247,22 +264,26 @@ int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, } int doTransaction(int iID, const char *pcOutBufIn, int iOutBytes, - char *pcReadBuf, int iBytesToRead) { + char *pcReadBuf, int iBytesToRead) +{ int iBytesRead; int iUnitMap = 1 << (iID - 1); struct timespec waitTime; static bool isInitialized = false; char *pcOutBuf = new char[iOutBytes + 1]; pcOutBuf[iOutBytes] = 0; - for (int i = 0; i < iOutBytes; i++) { + for (int i = 0; i < iOutBytes; i++) + { pcOutBuf[i] = pcOutBufIn[i]; pcOutBuf[iOutBytes] ^= pcOutBuf[i]; } waitTime.tv_sec = 0; waitTime.tv_nsec = 20000000; // 20ms - if (!isInitialized) { + if (!isInitialized) + { iBytesRead = pxd_serialConfigure(iUnitMap, 0, 115200, 8, 0, 1, 0, 0, 0); - if (iBytesRead < 0) { + if (iBytesRead < 0) + { printf("ERROR CONFIGURING SERIAL CAMERALINK PORT\n"); return iBytesRead; // error } @@ -270,7 +291,8 @@ int doTransaction(int iID, const char *pcOutBufIn, int iOutBytes, } nanosleep(&waitTime, NULL); iBytesRead = pxd_serialWrite(iUnitMap, 0, pcOutBuf, iOutBytes + 1); - if (iBytesRead < 0) { + if (iBytesRead < 0) + { printf("ERROR IN SERIAL WRITE\n"); return iBytesRead; // error } @@ -284,7 +306,8 @@ int doTransaction(int iID, const char *pcOutBufIn, int iOutBytes, return iBytesRead; } -short epixGetCMOSTemp(int iID) { +short epixGetCMOSTemp(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x7E, 0x50}; const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x72, 0x50}; @@ -309,7 +332,8 @@ short epixGetCMOSTemp(int iID) { return sTemp; } -short epixGetPCBTemp(int iID) { +short epixGetPCBTemp(int iID) +{ // const char queryBuf[] = {0x4F, 0x56, 0x50}; const char queryBuf1[] = {0x53, 0xE0, 0x02, 0x70, 0x00, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; @@ -328,7 +352,8 @@ short epixGetPCBTemp(int iID) { return sTemp; } -static double getFrameRate(int iID) { +static double getFrameRate(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xDD, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xDE, 0x50}; @@ -355,7 +380,8 @@ static double getFrameRate(int iID) { return (double)iFrameRate / 6E7; } -static void setFrameRate(int iID, double dFrameRate) { +static void setFrameRate(int iID, double dFrameRate) +{ int iFrameRate = fabs(6E7 * dFrameRate); const char queryBuf1[] = { 0x53, 0xE0, 0x02, 0xDD, (iFrameRate & 0xFF000000) >> 24, 0x50}; @@ -373,7 +399,8 @@ static void setFrameRate(int iID, double dFrameRate) { doTransaction(iID, queryBuf4, 6, cRetBuf, 1); } -static double getExposure(int iID) { +static double getExposure(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xED, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xEE, 0x50}; @@ -405,7 +432,8 @@ static double getExposure(int iID) { return (double)lExposure / 6E4; } -static void setExposure(int iID, double dExposureMs) { +static void setExposure(int iID, double dExposureMs) +{ long lExposure = fabs(6E4 * dExposureMs); // 60MHz: 1E6/16.6666 = 6e4 // long lExposure = fabs(6E7 * dExposure); const char queryBuf1[] = { @@ -426,7 +454,8 @@ static void setExposure(int iID, double dExposureMs) { doTransaction(iID, queryBuf4, 6, cRetBuf, 1); } -static float getGain(int iID) { +static float getGain(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD5, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xD6, 0x50}; @@ -443,7 +472,8 @@ static float getGain(int iID) { return sGain / 512.; } -static char getTrigMode(int iID) { +static char getTrigMode(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD4, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; @@ -453,14 +483,16 @@ static char getTrigMode(int iID) { return cRetBuf[0]; } -static void setTrigMode(int iID, char cTrigMode) { +static void setTrigMode(int iID, char cTrigMode) +{ const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xD4, cTrigMode, 0x50}; char cRetBuf[1]; doTransaction(iID, queryBuf1, 6, cRetBuf, 1); } -static char getBinning(int iID) { +static char getBinning(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xDB, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; @@ -470,7 +502,8 @@ static char getBinning(int iID) { return cRetBuf[0]; } -static short getRoiXSize(int iID) { +static short getRoiXSize(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD7, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xD8, 0x50}; @@ -487,7 +520,8 @@ static short getRoiXSize(int iID) { return sSize; } -static short getRoiXOffset(int iID) { +static short getRoiXOffset(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD9, 0x50}; const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xDA, 0x50}; @@ -504,7 +538,8 @@ static short getRoiXOffset(int iID) { return sOffset; } -static short getRoiYSize(int iID) { +static short getRoiYSize(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x01, 0x50}; const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x73, 0x50}; @@ -529,7 +564,8 @@ static short getRoiYSize(int iID) { return sSize; } -static short getRoiYOffset(int iID) { +static short getRoiYOffset(int iID) +{ const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x03, 0x50}; const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50}; const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x73, 0x50}; @@ -554,14 +590,16 @@ static short getRoiYOffset(int iID) { return sSize; } -void epixSetConfiguration(int iID, double dFrameRate, char cTrigMode) { +void epixSetConfiguration(int iID, double dFrameRate, char cTrigMode) +{ setFrameRate(iID, dFrameRate); setTrigMode(iID, cTrigMode); } void epixGetConfiguration(int iID, char *pcBinning, short *psRoiXSize, short *psRoiXOffset, short *psRoiYSize, - short *psRoiYOffset) { + short *psRoiYOffset) +{ *pcBinning = getBinning(iID); *psRoiXSize = getRoiXSize(iID); *psRoiXOffset = getRoiXOffset(iID); @@ -572,7 +610,8 @@ void epixGetConfiguration(int iID, char *pcBinning, short *psRoiXSize, #endif } -void epixGetTemp(int iID, float *pfPcbTemp, short *psCmosTemp) { +void epixGetTemp(int iID, float *pfPcbTemp, short *psCmosTemp) +{ *pfPcbTemp = epixGetPCBTemp(iID) / 16.; *psCmosTemp = epixGetCMOSTemp(iID); } \ No newline at end of file diff --git a/device_support/raptor/cygnet.h b/device_support/raptor/cygnet.h index 0d1249d0a5..4889941019 100644 --- a/device_support/raptor/cygnet.h +++ b/device_support/raptor/cygnet.h @@ -1,20 +1,21 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int epixOpen(char *pcConfFile); -void epixClose(); -void epixStartVideoCapture(int iID); -void epixStopVideoCapture(int iID); -int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, - int iTimeoutMs, void *pTree, void *pList, int *piBufIdx, - int *piFrameIdx, int *piBaseTicks, double *pdCurrTime); -void epixSetConfiguration(int iID, double dFrameRate, char cTrigMode); -void epixGetConfiguration(int iID, char *pcBinning, short *psRoiXSize, - short *psRoiXOffset, short *psRoiYSize, - short *psRoiYOffset); -void epixGetTemp(int iID, float *pfPcbTemp, short *psCmosTemp); -short epixGetPCBTemp(int iID); -short epixGetCMOSTemp(int iID); + int epixOpen(char *pcConfFile); + void epixClose(); + void epixStartVideoCapture(int iID); + void epixStopVideoCapture(int iID); + int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, + int iTimeoutMs, void *pTree, void *pList, int *piBufIdx, + int *piFrameIdx, int *piBaseTicks, double *pdCurrTime); + void epixSetConfiguration(int iID, double dFrameRate, char cTrigMode); + void epixGetConfiguration(int iID, char *pcBinning, short *psRoiXSize, + short *psRoiXOffset, short *psRoiYSize, + short *psRoiYOffset); + void epixGetTemp(int iID, float *pfPcbTemp, short *psCmosTemp); + short epixGetPCBTemp(int iID); + short epixGetCMOSTemp(int iID); #ifdef __cplusplus } #endif diff --git a/device_support/redpitaya/axi_reg.h b/device_support/redpitaya/axi_reg.h index 1b57e6527d..bb0e3009c2 100644 --- a/device_support/redpitaya/axi_reg.h +++ b/device_support/redpitaya/axi_reg.h @@ -13,26 +13,34 @@ #define RP_EOMD 1; static int dev_mem_fd = 0; -int axi_reg_Init() { - if (!dev_mem_fd) { - if ((dev_mem_fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) { +int axi_reg_Init() +{ + if (!dev_mem_fd) + { + if ((dev_mem_fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) + { return RP_EOMD; } } return RP_OK; } -int axi_reg_Release() { - if (dev_mem_fd) { - if (close(dev_mem_fd) < 0) { +int axi_reg_Release() +{ + if (dev_mem_fd) + { + if (close(dev_mem_fd) < 0) + { return RP_ECMD; } } return RP_OK; } -void *axi_reg_Map(size_t size, size_t offset) { - if (dev_mem_fd == -1) { +void *axi_reg_Map(size_t size, size_t offset) +{ + if (dev_mem_fd == -1) + { return NULL; } return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem_fd, diff --git a/device_support/redpitaya/redpitaya.cpp b/device_support/redpitaya/redpitaya.cpp index fed0305fb0..8fea10f673 100644 --- a/device_support/redpitaya/redpitaya.cpp +++ b/device_support/redpitaya/redpitaya.cpp @@ -8,18 +8,20 @@ #include #include -extern "C" { -void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, - int triggerNid, int preSamples, int postSamples, - int inSegmentSamples, double freq, double freq1, int single); -int rpadcInit(int mode, int clock_mode, int preSamples, int postSamples, - int trigFromChanA, int trigAboveThreshold, int trigThreshold, - int thresholdSamples, int decimation, int event_code); -int rpadcTrigger(int fd); -void rpadcStop(int fd); -void openTree(char *name, int shot, MDSplus::Tree **treePtr); +extern "C" +{ + void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, + int triggerNid, int preSamples, int postSamples, + int inSegmentSamples, double freq, double freq1, int single); + int rpadcInit(int mode, int clock_mode, int preSamples, int postSamples, + int trigFromChanA, int trigAboveThreshold, int trigThreshold, + int thresholdSamples, int decimation, int event_code); + int rpadcTrigger(int fd); + void rpadcStop(int fd); + void openTree(char *name, int shot, MDSplus::Tree **treePtr); } -enum rpadc_mode { +enum rpadc_mode +{ STREAMING = 0, EVENT_STREAMING, EVENT_SINGLE, @@ -27,7 +29,8 @@ enum rpadc_mode { TRIGGER_SINGLE }; -enum rpadc_clock_mode { +enum rpadc_clock_mode +{ INTERNAL = 0, TRIG_EXTERNAL, EXTERNAL, @@ -38,19 +41,20 @@ enum rpadc_clock_mode { #define DMA_STREAMING_SAMPLES 1024 -struct rpadc_configuration { +struct rpadc_configuration +{ enum rpadc_mode mode; enum rpadc_clock_mode clock_mode; unsigned short trig_threshold; // Signal level for trigger char trig_above_threshold; // If true, trigger when above threshold, below - // threshold otherwise - char trig_from_chana; // If true, the trigger is derived from channel A - unsigned char trig_samples; // Number of samples above/below threshol for - // validating trigger - unsigned short pre_samples; // Number of pre-trigger samples - unsigned int post_samples; // Number of post-trigger samples - unsigned int decimation; // Decimation factor (base frequency: 125MHz) - unsigned int event_code; // Trigger event code (if HIGHWAY clock mode) + // threshold otherwise + char trig_from_chana; // If true, the trigger is derived from channel A + unsigned char trig_samples; // Number of samples above/below threshol for + // validating trigger + unsigned short pre_samples; // Number of pre-trigger samples + unsigned int post_samples; // Number of post-trigger samples + unsigned int decimation; // Decimation factor (base frequency: 125MHz) + unsigned int event_code; // Trigger event code (if HIGHWAY clock mode) }; static bool stopped = false; @@ -58,7 +62,8 @@ static bool isStream = false; static int deviceFd = 0; -static void writeConfig(int fd, struct rpadc_configuration *config) { +static void writeConfig(int fd, struct rpadc_configuration *config) +{ struct rfx_stream_registers regs; memset(®s, 0, sizeof(regs)); unsigned int currVal = 0; @@ -124,32 +129,39 @@ static void writeConfig(int fd, struct rpadc_configuration *config) { ioctl(fd, RFX_STREAM_FIFO_INT_FIRST_SAMPLE, NULL); } -static void readConfig(int fd, struct rpadc_configuration *config) { +static void readConfig(int fd, struct rpadc_configuration *config) +{ unsigned int currVal; struct rfx_stream_registers regs; ioctl(fd, RFX_STREAM_GET_REGISTERS, ®s); currVal = regs.mode_register; if (currVal & 0x00000001) config->mode = STREAMING; - else { - if (currVal & 0x00000008) { + else + { + if (currVal & 0x00000008) + { if (currVal & 0x00000010) config->mode = EVENT_STREAMING; else config->mode = EVENT_SINGLE; - } else { + } + else + { if (currVal & 0x00000010) config->mode = TRIGGER_STREAMING; else config->mode = TRIGGER_SINGLE; } } - if (currVal & 0x00000020) { + if (currVal & 0x00000020) + { if (currVal & 0x00000040) config->clock_mode = EXTERNAL; else config->clock_mode = TRIG_EXTERNAL; - } else + } + else config->clock_mode = INTERNAL; if (currVal & 0x00000002) @@ -175,7 +187,8 @@ static void fifoFlush(int fd) { ioctl(fd, RFX_STREAM_FIFO_FLUSH, NULL); } static void stopRead(int fd) { ioctl(fd, RFX_STREAM_STOP_READ, NULL); } -static void adcStop(int fd) { +static void adcStop(int fd) +{ unsigned int val = 0x00000002; ioctl(fd, RFX_STREAM_SET_COMMAND_REGISTER, &val); } @@ -187,7 +200,8 @@ static void dmaStop(int fd) } */ -static void adcArm(int fd) { +static void adcArm(int fd) +{ unsigned int command = 0; std::cout << "ARM " << fd << std::endl; @@ -198,7 +212,8 @@ static void adcArm(int fd) { command = 0x00000001; // Arm ioctl(fd, RFX_STREAM_SET_COMMAND_REGISTER, &command); } -static void adcTrigger(int fd) { +static void adcTrigger(int fd) +{ unsigned int command = 0x00000004; ioctl(fd, RFX_STREAM_SET_COMMAND_REGISTER, &command); usleep(1000); @@ -219,9 +234,12 @@ static void dmaStart(int fd, int cyclic) ioctl(fd, RFX_STREAM_START_DMA, &cyclic); } */ -static void sigHandler(int signo) { - if (signo == SIGINT) { - if (deviceFd) { +static void sigHandler(int signo) +{ + if (signo == SIGINT) + { + if (deviceFd) + { stopped = true; adcStop(deviceFd); usleep(1000); @@ -236,14 +254,16 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, MDSplus::TreeNode *chan2, MDSplus::Data *triggerTime, unsigned int *dataSamples, double *startTimes, double *endTimes, int segmentSamples, - int blocksInSegment, double freq) { + int blocksInSegment, double freq) +{ short *chan1Samples, *chan2Samples; std::cout << "WRITE SEGMENT SAMPLES: " << segmentSamples << std::endl; chan1Samples = new short[segmentSamples]; chan2Samples = new short[segmentSamples]; - for (int i = 0; i < segmentSamples; i++) { + for (int i = 0; i < segmentSamples; i++) + { chan1Samples[i] = dataSamples[i] & 0x0000ffff; chan2Samples[i] = (dataSamples[i] >> 16) & 0x0000ffff; } @@ -258,10 +278,13 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, MDSplus::Data *startTimeData; MDSplus::Data *endTimeData; MDSplus::Data *deltaData = new MDSplus::Float64(1 / freq); - if (blocksInSegment == 1) { + if (blocksInSegment == 1) + { startTimeData = new MDSplus::Float64(startTimes[0]); endTimeData = new MDSplus::Float64(endTimes[0]); - } else { + } + else + { startTimeData = new MDSplus::Float64Array(startTimes, blocksInSegment); endTimeData = new MDSplus::Float64Array(endTimes, blocksInSegment); } @@ -278,11 +301,14 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, MDSplus::compileWithArgs("$1+$2", t, 2, startData, triggerTime); MDSplus::Data *endSegData = MDSplus::compileWithArgs("$1+$2", t, 2, endData, triggerTime); - try { + try + { // std::cout << "MAKE SEGMENT "<< chan1 << chan1Data << std::endl; chan1->makeSegment(startSegData, endSegData, timebase, chan1Data); chan2->makeSegment(startSegData, endSegData, timebase, chan2Data); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << "Error writing segment: " << exc.what() << std::endl; } MDSplus::deleteData(chan1Data); @@ -297,7 +323,8 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, // std::cout << "WRITESEGMENT END" << std::endl; } // Stop -void rpadcStop(int fd) { +void rpadcStop(int fd) +{ adcStop(fd); usleep(100000); fifoFlush(fd); @@ -314,10 +341,11 @@ void rpadcStop(int fd) { void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, int triggerNid, int preSamples, int postSamples, - int inSegmentSamples, double freq, double freq1, int single) { - int segmentSamples; // True segment dimension - int blockSamples; // post samples + pre samples for event streaming, - // segmentSize for continuous streaming + int inSegmentSamples, double freq, double freq1, int single) +{ + int segmentSamples; // True segment dimension + int blockSamples; // post samples + pre samples for event streaming, + // segmentSize for continuous streaming int blocksInSegment; // 1 fir cintinous streaming unsigned int *dataSamples; double *startTimes, *endTimes; @@ -333,7 +361,9 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, blockSamples = segmentSamples = inSegmentSamples; blocksInSegment = 1; isStream = true; - } else if (single) { + } + else if (single) + { segmentSamples = preSamples + postSamples; if (segmentSamples > 1000000 && segmentSamples % 1000000 == 0) segmentSamples = @@ -350,7 +380,9 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, // segmentSamples = preSamples + postSamples; blockSamples = segmentSamples; blocksInSegment = 1; - } else { + } + else + { int eventSamples = preSamples + postSamples; if (eventSamples > inSegmentSamples) inSegmentSamples = eventSamples; // Force consistenct @@ -372,10 +404,13 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, usleep(1000); int segmentIdx = 0; prevTime = 0; - while (true) { - for (int currBlock = 0; currBlock < blocksInSegment; currBlock++) { + while (true) + { + for (int currBlock = 0; currBlock < blocksInSegment; currBlock++) + { unsigned int currSample = 0; - while (currSample < blockSamples) { + while (currSample < blockSamples) + { int rb = read(fd, &dataSamples[currBlock * blockSamples + currSample], (blockSamples - currSample) * sizeof(int)); @@ -388,9 +423,11 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, if (!(currBlock == 0 && currSample == 0) && !isStream) // if any data has been acquired { - if (rb > 0) { + if (rb > 0) + { // Make sure no data are left - while (rb > 0) { + while (rb > 0) + { rb = read(fd, &dataSamples[currBlock * blockSamples + currSample], (blockSamples - currSample) * sizeof(int)); @@ -399,7 +436,8 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, currSample += rb / sizeof(int); } - if (single) { + if (single) + { startTimes[0] = (segmentIdx * segmentSamples - preSamples) / freq1; endTimes[0] = @@ -407,7 +445,8 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, currBlock * blockSamples + currSample, 1, freq1); - } else // Some data for new window have been read + } + else // Some data for new window have been read { unsigned long long currTime; unsigned int time1, time2; @@ -425,8 +464,9 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, currBlock * blockSamples + currSample, currBlock + 1, freq1); } - } else // Some windows have been read before and the segment is - // partially filled + } + else // Some windows have been read before and the segment is + // partially filled { writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, currBlock * blockSamples + currSample, @@ -444,7 +484,8 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, delete trigger; return; } - if (rb < 0 && !stopped) { + if (rb < 0 && !stopped) + { printf("DEVICE FIFO OVERFLOW!!!!\n"); return; } @@ -455,11 +496,13 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, { unsigned long long currTime; unsigned int time1, time2; - if (single) { + if (single) + { startTimes[0] = (segmentIdx * segmentSamples - preSamples) / freq1; endTimes[0] = ((segmentIdx + 1) * segmentSamples - preSamples) / freq1; - } else // If referring to a new window, the time must be read + } + else // If referring to a new window, the time must be read { ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &time1); ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &time2); @@ -480,7 +523,8 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, } } } - if (preSamples == 0 && postSamples == 0) { + if (preSamples == 0 && postSamples == 0) + { startTimes[0] = segmentIdx * segmentSamples / freq1; endTimes[0] = (segmentIdx + 1) * segmentSamples / freq1; } @@ -490,9 +534,11 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, segmentSamples, blocksInSegment, freq1); } } -static void printConfig(struct rpadc_configuration *config) { +static void printConfig(struct rpadc_configuration *config) +{ printf("CONFIG:\n"); - switch (config->mode) { + switch (config->mode) + { case STREAMING: printf("\tmode: STREAMING\n"); break; @@ -509,7 +555,8 @@ static void printConfig(struct rpadc_configuration *config) { printf("\tmode: TRIGGER_SINGLE\n"); break; } - switch (config->clock_mode) { + switch (config->clock_mode) + { case INTERNAL: printf("\tclock_mode: INTERNAL\n"); break; @@ -551,7 +598,8 @@ static void printConfig(struct rpadc_configuration *config) { // return either NULL or an error string int rpadcInit(int mode, int clock_mode, int preSamples, int postSamples, int trigFromChanA, int trigAboveThreshold, int trigThreshold, - int thresholdSamples, int decimation, int event_code) { + int thresholdSamples, int decimation, int event_code) +{ struct rpadc_configuration inConfig, outConfig; int fd = open("/dev/rfx_stream", O_RDWR | O_SYNC); @@ -603,22 +651,28 @@ int rpadcInit(int mode, int clock_mode, int preSamples, int postSamples, return fd; } -int rpadcTrigger(int fd) { +int rpadcTrigger(int fd) +{ adcTrigger(fd); // int status = ioctl(fd, RFX_RPADC_TRIGGER, 0); usleep(10); return 0; } -void openTree(char *name, int shot, MDSplus::Tree **treePtr) { - try { +void openTree(char *name, int shot, MDSplus::Tree **treePtr) +{ + try + { *treePtr = new MDSplus::Tree(name, shot); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { *treePtr = 0; } } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ // int preSamples = 0, postSamples = 30; // if (signal(SIGINT, sigHandler) == SIG_ERR) // std::cout << "\ncan't catch SIGINT\n"; @@ -626,7 +680,8 @@ int main(int argc, char *argv[]) { int preSamples = 100, postSamples = 200; int fd = rpadcInit(0, 0, preSamples, postSamples, 1, 1, 5000, 2, atoi(argv[1]), 0); - try { + try + { MDSplus::Tree *t = new MDSplus::Tree("redpitaya", -1); t->createPulse(1); @@ -640,7 +695,9 @@ int main(int argc, char *argv[]) { 125E6 / atoi(argv[1]), 125E6 / atoi(argv[1]), 0); rpadcStop(fd); - } catch (MDSplus::MdsException &exc) { + } + catch (MDSplus::MdsException &exc) + { std::cout << exc.what() << std::endl; return 0; } diff --git a/device_support/redpitaya/rfx_stream.h b/device_support/redpitaya/rfx_stream.h index ab557de2e4..bd1a71997a 100644 --- a/device_support/redpitaya/rfx_stream.h +++ b/device_support/redpitaya/rfx_stream.h @@ -5,17 +5,18 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif // Temporaneo #define DMA_SOURCE 1 -//////////////// + //////////////// #define DEVICE_NAME "rfx_stream" /* Dev name as it appears in /proc/devices */ #define MODULE_NAME "rfx_stream" -// Generic IOCTL commands + // Generic IOCTL commands #define RFX_STREAM_IOCTL_BASE 'W' #define RFX_STREAM_ARM_DMA _IO(RFX_STREAM_IOCTL_BASE, 1) @@ -59,77 +60,81 @@ extern "C" { #ifndef AXI_ENUMS_DEFINED #define AXI_ENUMS_DEFINED -enum AxiStreamFifo_Register { - ISR = 0x00, ///< Interrupt Status Register (ISR) - IER = 0x04, ///< Interrupt Enable Register (IER) - TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) - TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) - TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port - TDFD4 = 0x1000, ///< Transmit Data FIFO for AXI4 Data Write Port - TLR = 0x14, ///< Transmit Length Register (TLR) - RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) - RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) - RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) - RDFD4 = 0x1000, ///< Receive Data FIFO for AXI4 Data Read Port (RDFD) - RLR = 0x24, ///< Receive Length Register (RLR) - SRR = 0x28, ///< AXI4-Stream Reset (SRR) - TDR = 0x2c, ///< Transmit Destination Register (TDR) - RDR = 0x30, ///< Receive Destination Register (RDR) - /// not supported yet .. /// - TID = 0x34, ///< Transmit ID Register - TUSER = 0x38, ///< Transmit USER Register - RID = 0x3c, ///< Receive ID Register - RUSER = 0x40 ///< Receive USER Register -}; + enum AxiStreamFifo_Register + { + ISR = 0x00, ///< Interrupt Status Register (ISR) + IER = 0x04, ///< Interrupt Enable Register (IER) + TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) + TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) + TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port + TDFD4 = 0x1000, ///< Transmit Data FIFO for AXI4 Data Write Port + TLR = 0x14, ///< Transmit Length Register (TLR) + RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) + RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) + RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) + RDFD4 = 0x1000, ///< Receive Data FIFO for AXI4 Data Read Port (RDFD) + RLR = 0x24, ///< Receive Length Register (RLR) + SRR = 0x28, ///< AXI4-Stream Reset (SRR) + TDR = 0x2c, ///< Transmit Destination Register (TDR) + RDR = 0x30, ///< Receive Destination Register (RDR) + /// not supported yet .. /// + TID = 0x34, ///< Transmit ID Register + TUSER = 0x38, ///< Transmit USER Register + RID = 0x3c, ///< Receive ID Register + RUSER = 0x40 ///< Receive USER Register + }; -enum AxiStreamFifo_ISREnum { - ISR_RFPE = 1 << 19, ///< Receive FIFO Programmable Empty - ISR_RFPF = 1 << 20, ///< Receive FIFO Programmable Full - ISR_TFPE = 1 << 21, ///< Transmit FIFO Programmable Empty - ISR_TFPF = 1 << 22, ///< Transmit FIFO Programmable Full - ISR_RRC = 1 << 23, ///< Receive Reset Complete - ISR_TRC = 1 << 24, ///< Transmit Reset Complete - ISR_TSE = 1 << 25, ///< Transmit Size Error - ISR_RC = 1 << 26, ///< Receive Complete - ISR_TC = 1 << 27, ///< Transmit Complete - ISR_TPOE = 1 << 28, ///< Transmit Packet Overrun Error - ISR_RPUE = 1 << 29, ///< Receive Packet Underrun Error - ISR_RPORE = 1 << 30, ///< Receive Packet Overrun Read Error - ISR_RPURE = 1 << 31, ///< Receive Packet Underrun Read Error -}; + enum AxiStreamFifo_ISREnum + { + ISR_RFPE = 1 << 19, ///< Receive FIFO Programmable Empty + ISR_RFPF = 1 << 20, ///< Receive FIFO Programmable Full + ISR_TFPE = 1 << 21, ///< Transmit FIFO Programmable Empty + ISR_TFPF = 1 << 22, ///< Transmit FIFO Programmable Full + ISR_RRC = 1 << 23, ///< Receive Reset Complete + ISR_TRC = 1 << 24, ///< Transmit Reset Complete + ISR_TSE = 1 << 25, ///< Transmit Size Error + ISR_RC = 1 << 26, ///< Receive Complete + ISR_TC = 1 << 27, ///< Transmit Complete + ISR_TPOE = 1 << 28, ///< Transmit Packet Overrun Error + ISR_RPUE = 1 << 29, ///< Receive Packet Underrun Error + ISR_RPORE = 1 << 30, ///< Receive Packet Overrun Read Error + ISR_RPURE = 1 << 31, ///< Receive Packet Underrun Read Error + }; -enum RegisterIdx { - FIFO_00_IDX = 0, - FIFO_01_IDX = 1, - FIFO_10_IDX = 2, - FIFO11_IDX = 3, - COMMAND_REG_IDX = 4, - PRE_POST_REG_IDX = 5, - DEC_REG_IDX = 6, - MODE_REG_IDX = 8 -}; + enum RegisterIdx + { + FIFO_00_IDX = 0, + FIFO_01_IDX = 1, + FIFO_10_IDX = 2, + FIFO11_IDX = 3, + COMMAND_REG_IDX = 4, + PRE_POST_REG_IDX = 5, + DEC_REG_IDX = 6, + MODE_REG_IDX = 8 + }; #endif #pragma pack(1) -struct rfx_stream_registers { - char command_register_enable; - unsigned int command_register; - char decimator_register_enable; - unsigned int decimator_register; - char mode_register_enable; - unsigned int mode_register; - char packetizer_enable; - unsigned int packetizer; - char post_register_enable; - unsigned int post_register; - char pre_register_enable; - unsigned int pre_register; - char trig_event_code_enable; - unsigned int trig_event_code; - char event_code_enable; - unsigned int event_code; -}; + struct rfx_stream_registers + { + char command_register_enable; + unsigned int command_register; + char decimator_register_enable; + unsigned int decimator_register; + char mode_register_enable; + unsigned int mode_register; + char packetizer_enable; + unsigned int packetizer; + char post_register_enable; + unsigned int post_register; + char pre_register_enable; + unsigned int pre_register; + char trig_event_code_enable; + unsigned int trig_event_code; + char event_code_enable; + unsigned int event_code; + }; #ifdef __cplusplus } diff --git a/device_support/redpitaya/rpadc_fifo_auto.c b/device_support/redpitaya/rpadc_fifo_auto.c index 9122c7a2c2..56716c61e0 100644 --- a/device_support/redpitaya/rpadc_fifo_auto.c +++ b/device_support/redpitaya/rpadc_fifo_auto.c @@ -62,7 +62,8 @@ static struct file_operations fops = { #define BUFSIZE 200000 -struct rpadc_fifo_auto_dev { +struct rpadc_fifo_auto_dev +{ struct platform_device *pdev; struct cdev cdev; int busy; @@ -109,15 +110,18 @@ struct rpadc_fifo_auto_dev { // FIFO IO /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void writeFifo(void *addr, enum AxiStreamFifo_Register op, u32 data) { +void writeFifo(void *addr, enum AxiStreamFifo_Register op, u32 data) +{ *(u32 *)(addr + op) = data; } -u32 readFifo(void *addr, enum AxiStreamFifo_Register op) { +u32 readFifo(void *addr, enum AxiStreamFifo_Register op) +{ return *(u32 *)(addr + op); } -static void clearFifo(void *dev, void *dev1) { +static void clearFifo(void *dev, void *dev1) +{ u32 occ, i; writeFifo(dev, ISR, 0xFFFFFFFF); writeFifo(dev, RDFR, 0xa5); @@ -136,13 +140,17 @@ static void dma_start_transfer(struct dma_chan *chan, struct completion *cmp, dma_cookie_t cookie, int wait); #endif // HAS_DMA -int writeBuf(struct rpadc_fifo_auto_dev *dev, u32 sample) { +int writeBuf(struct rpadc_fifo_auto_dev *dev, u32 sample) +{ spin_lock_irq(&dev->spinLock); - if (dev->bufCount >= dev->bufSize) { + if (dev->bufCount >= dev->bufSize) + { printk(KERN_DEBUG "ADC FIFO BUFFER OVERFLOW!\n"); spin_unlock_irq(&dev->spinLock); return -1; - } else { + } + else + { dev->fifoBuffer[dev->wIdx] = sample; dev->wIdx = (dev->wIdx + 1) % dev->bufSize; dev->bufCount++; @@ -151,16 +159,21 @@ int writeBuf(struct rpadc_fifo_auto_dev *dev, u32 sample) { return 0; } -int writeBufSet(struct rpadc_fifo_auto_dev *dev, u32 *buf, int nSamples) { +int writeBufSet(struct rpadc_fifo_auto_dev *dev, u32 *buf, int nSamples) +{ int i; spin_lock_irq(&dev->spinLock); - for (i = 0; i < nSamples; i++) { - if (dev->bufCount >= dev->bufSize) { + for (i = 0; i < nSamples; i++) + { + if (dev->bufCount >= dev->bufSize) + { printk(KERN_DEBUG "ADC FIFO BUFFER OVERFLOW %d %d!\n", dev->bufCount, dev->bufSize); spin_unlock_irq(&dev->spinLock); return -1; - } else { + } + else + { dev->fifoBuffer[dev->wIdx] = buf[i]; dev->wIdx = (dev->wIdx + 1) % dev->bufSize; dev->bufCount++; @@ -170,13 +183,17 @@ int writeBufSet(struct rpadc_fifo_auto_dev *dev, u32 *buf, int nSamples) { return 0; } -u32 readBuf(struct rpadc_fifo_auto_dev *dev) { +u32 readBuf(struct rpadc_fifo_auto_dev *dev) +{ u32 data; spin_lock_irq(&dev->spinLock); - if (dev->bufCount <= 0) { + if (dev->bufCount <= 0) + { printk(KERN_DEBUG "ADC FIFO BUFFER UNDERFLOW!\n"); // Should never happen data = 0; - } else { + } + else + { data = dev->fifoBuffer[dev->rIdx]; dev->rIdx = (dev->rIdx + 1) % dev->bufSize; dev->bufCount--; @@ -190,7 +207,8 @@ u32 readBuf(struct rpadc_fifo_auto_dev *dev) { //////////////////////////////////////////////////////////////////////////////// #ifdef HAS_DMA -static void dma_buffer2fifo_buffer(struct rpadc_fifo_auto_dev *dev) { +static void dma_buffer2fifo_buffer(struct rpadc_fifo_auto_dev *dev) +{ int i; int dmaSamples = dev->dma_buf_size / sizeof(u32); writeBufSet(dev, dev->dma_buffer, dmaSamples); @@ -200,17 +218,20 @@ static void dma_buffer2fifo_buffer(struct rpadc_fifo_auto_dev *dev) { /* Handle a callback called when the DMA transfer is complete to another * thread of control */ -static int dma_sync_callback(struct rpadc_fifo_auto_dev *dev) { +static int dma_sync_callback(struct rpadc_fifo_auto_dev *dev) +{ int status, i; dma_cookie_t lastCookie; // printk("DMA SYNC CALLBACK\n"); status = dma_async_is_tx_complete(dev->dma_chan, dev->dma_cookie, &lastCookie, NULL); - if (status != DMA_COMPLETE) { + if (status != DMA_COMPLETE) + { printk(KERN_ERR "DMA returned completion callback status of: %s\n", status == DMA_ERROR ? "error" : "in progress"); } - if (lastCookie != dev->dma_cookie) { + if (lastCookie != dev->dma_cookie) + { printk("DMA NOT TERMINATED FOR THIS COOKIE %d %d\n", lastCookie, dev->dma_cookie); dmaengine_terminate_all(dev->dma_chan); @@ -232,7 +253,8 @@ static int dma_sync_callback(struct rpadc_fifo_auto_dev *dev) { dev->dma_cookie = dma_prep_buffer(dev, dev->dma_chan, dev->dma_handle, dev->dma_buf_size, DMA_DEV_TO_MEM, &dev->dma_cmp); - if (dma_submit_error(dev->dma_cookie)) { + if (dma_submit_error(dev->dma_cookie)) + { printk(KERN_ERR "dma_prep_buffer error\n"); return -EIO; } @@ -248,16 +270,20 @@ static int dma_sync_callback(struct rpadc_fifo_auto_dev *dev) { static dma_cookie_t dma_prep_buffer(struct rpadc_fifo_auto_dev *dev, struct dma_chan *chan, dma_addr_t buf, size_t len, enum dma_transfer_direction dir, - struct completion *cmp) { + struct completion *cmp) +{ enum dma_ctrl_flags flags = /*DMA_CTRL_ACK | */ DMA_PREP_INTERRUPT; struct dma_async_tx_descriptor *chan_desc; dma_cookie_t cookie; chan_desc = dmaengine_prep_slave_single(chan, buf, len, dir, flags); - if (!chan_desc) { + if (!chan_desc) + { printk(KERN_ERR "dmaengine_prep_slave_single error\n"); cookie = -EBUSY; - } else { + } + else + { chan_desc->callback = dma_sync_callback; chan_desc->callback_param = dev; // printk("SUBMIT DMA \n"); @@ -271,19 +297,24 @@ static dma_cookie_t dma_prep_buffer(struct rpadc_fifo_auto_dev *dev, * wait for it complete, timeout or have an error */ static void dma_start_transfer(struct dma_chan *chan, struct completion *cmp, - dma_cookie_t cookie, int wait) { + dma_cookie_t cookie, int wait) +{ unsigned long timeout = msecs_to_jiffies(10000); enum dma_status status; init_completion(cmp); dma_async_issue_pending(chan); - if (wait) { + if (wait) + { timeout = wait_for_completion_timeout(cmp, timeout); status = dma_async_is_tx_complete(chan, cookie, NULL, NULL); - if (timeout == 0) { + if (timeout == 0) + { printk(KERN_ERR "DMA timed out\n"); - } else if (status != DMA_COMPLETE) { + } + else if (status != DMA_COMPLETE) + { printk(KERN_ERR "DMA returned completion callback status of: %s\n", status == DMA_ERROR ? "error" : "in progress"); } @@ -295,16 +326,19 @@ static void dma_start_transfer(struct dma_chan *chan, struct completion *cmp, //////////////////////////////////////////////////////////////////////////////// // Interrupt Management for FIFO ////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static void Write(void *addr, enum AxiStreamFifo_Register op, u32 data) { +static void Write(void *addr, enum AxiStreamFifo_Register op, u32 data) +{ *(u32 *)(addr + op) = data; } -static u32 Read(void *addr, enum AxiStreamFifo_Register op) { +static u32 Read(void *addr, enum AxiStreamFifo_Register op) +{ return *(u32 *)(addr + op); } // interrupt handler // -irqreturn_t IRQ_cb(int irq, void *dev_id, struct pt_regs *regs) { +irqreturn_t IRQ_cb(int irq, void *dev_id, struct pt_regs *regs) +{ struct rpadc_fifo_auto_dev *dev = dev_id; // struct rpadc_fifo_dev *rpadc = dev_id; static int isFirst = 1; @@ -318,18 +352,22 @@ irqreturn_t IRQ_cb(int irq, void *dev_id, struct pt_regs *regs) { static u32 prev1, prev2; u32 occ = Read(fifo, RDFO); - { isFirst = 0; } + { + isFirst = 0; + } // printk("--INTERRUPT: Available samples: %d\n", occ); - if (occ >= FIFO_LEN) { + if (occ >= FIFO_LEN) + { dev->fifoOverflow = 1; wake_up(&dev->readq); // When oveflow is detected, disable interrupts } int i; - for (i = 0; i < occ; i++) { + for (i = 0; i < occ; i++) + { u32 currSample = Read(fifo1, RDFD4); if (writeBuf(dev, currSample) < 0) // In case of ADC FIFO overflow, abort data readout from FPGA @@ -352,8 +390,10 @@ irqreturn_t IRQ_cb(int irq, void *dev_id, struct pt_regs *regs) { #endif // HAS_FIFO_INTERRUPT // OPEN // -static int device_open(struct inode *inode, struct file *file) { - if (!file->private_data) { +static int device_open(struct inode *inode, struct file *file) +{ + if (!file->private_data) + { u32 off; struct rpadc_fifo_auto_dev *privateInfo = @@ -393,11 +433,13 @@ static int device_open(struct inode *inode, struct file *file) { } // CLOSE // -static int device_release(struct inode *inode, struct file *file) { +static int device_release(struct inode *inode, struct file *file) +{ struct rpadc_fifo_auto_dev *dev = file->private_data; if (!dev) return -EFAULT; - if (--dev->busy == 0) { + if (--dev->busy == 0) + { printk(KERN_DEBUG "CLOSE\n"); wake_up(&dev->readq); } @@ -405,7 +447,8 @@ static int device_release(struct inode *inode, struct file *file) { } static ssize_t device_read(struct file *filp, char *buffer, size_t length, - loff_t *offset) { + loff_t *offset) +{ u32 i = 0; struct rpadc_fifo_auto_dev *dev = (struct rpadc_fifo_auto_dev *)filp->private_data; @@ -414,7 +457,8 @@ static ssize_t device_read(struct file *filp, char *buffer, size_t length, if (dev->fifoOverflow) return -1; #endif - while (dev->bufCount == 0) { + while (dev->bufCount == 0) + { if (filp->f_flags & O_NONBLOCK) return -EAGAIN; #ifdef HAS_DMA @@ -433,7 +477,8 @@ static ssize_t device_read(struct file *filp, char *buffer, size_t length, } u32 occ = dev->bufCount; - for (i = 0; i < min(length / sizeof(u32), occ); ++i) { + for (i = 0; i < min(length / sizeof(u32), occ); ++i) + { u32 curr = readBuf(dev); put_user(curr, b32++); } @@ -442,47 +487,58 @@ static ssize_t device_read(struct file *filp, char *buffer, size_t length, // WRITE // static ssize_t device_write(struct file *filp, const char *buff, size_t len, - loff_t *off) { + loff_t *off) +{ printk("<1>Sorry, this operation isn't supported yet.\n"); return -EINVAL; } // MMAP // -static int device_mmap(struct file *filp, struct vm_area_struct *vma) { +static int device_mmap(struct file *filp, struct vm_area_struct *vma) +{ printk("<1>Sorry, this operation isn't supported.\n"); return -EINVAL; } // LSEEK // -static loff_t memory_lseek(struct file *file, loff_t offset, int orig) { +static loff_t memory_lseek(struct file *file, loff_t offset, int orig) +{ printk("<1>Sorry, this operation isn't supported.\n"); return -EINVAL; } // IOCTL // static long device_ioctl(struct file *file, unsigned int cmd, - unsigned long arg) { + unsigned long arg) +{ int i; int status = 0; struct rpadc_fifo_auto_dev *dev = file->private_data; - switch (cmd) { + switch (cmd) + { #ifdef HAS_DMA - case RPADC_FIFO_AUTO_ARM_DMA: { + case RPADC_FIFO_AUTO_ARM_DMA: + { u32 newDmaBufSize; - if (!arg) { + if (!arg) + { if (dev->dma_buf_size > 0) newDmaBufSize = dev->dma_buf_size; else newDmaBufSize = DMA_STREAMING_SAMPLES * sizeof(u32); - } else { + } + else + { copy_from_user(&newDmaBufSize, (void __user *)arg, sizeof(u32)); } - if (dev->dma_buf_size > 0 && dev->dma_buf_size != newDmaBufSize) { + if (dev->dma_buf_size > 0 && dev->dma_buf_size != newDmaBufSize) + { dma_free_coherent(dev->dma_chan->device->dev, dev->dma_buf_size, dev->dma_buffer, dev->dma_handle); } - if (newDmaBufSize != dev->dma_buf_size) { + if (newDmaBufSize != dev->dma_buf_size) + { dev->dma_buf_size = newDmaBufSize; dev->dma_buffer = dma_alloc_coherent(dev->dma_chan->device->dev, dev->dma_buf_size, @@ -497,15 +553,18 @@ static long device_ioctl(struct file *file, unsigned int cmd, dev->dma_buf_size, DMA_FROM_DEVICE); return 0; } - case RPADC_FIFO_AUTO_START_DMA: { + case RPADC_FIFO_AUTO_START_DMA: + { // Start DMA if DMA buffer previusly allocated int cyclic; copy_from_user(&cyclic, (void __user *)arg, sizeof(u32)); - if (dev->dma_buf_size > 0) { + if (dev->dma_buf_size > 0) + { dev->dma_cookie = dma_prep_buffer(dev, dev->dma_chan, dev->dma_handle, dev->dma_buf_size, DMA_DEV_TO_MEM, &dev->dma_cmp); - if (dma_submit_error(dev->dma_cookie)) { + if (dma_submit_error(dev->dma_cookie)) + { printk(KERN_ERR "dma_prep_buffer error\n"); return -EIO; } @@ -520,29 +579,34 @@ static long device_ioctl(struct file *file, unsigned int cmd, dev->bufCount = 0; return 0; } - case RPADC_FIFO_AUTO_STOP_DMA: { + case RPADC_FIFO_AUTO_STOP_DMA: + { // dmaengine_terminate_all(dev->dma_chan); dev->dma_started = 0; dev->dma_cyclic = 0; wake_up(&dev->readq); return 0; } - case RPADC_FIFO_AUTO_IS_DMA_RUNNING: { + case RPADC_FIFO_AUTO_IS_DMA_RUNNING: + { copy_to_user((void __user *)arg, &dev->dma_started, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_DMA_BUFLEN: { + case RPADC_FIFO_AUTO_GET_DMA_BUFLEN: + { copy_to_user((void __user *)arg, &dev->dma_buf_size, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_DMA_DATA: { + case RPADC_FIFO_AUTO_GET_DMA_DATA: + { copy_to_user((void __user *)arg, dev->dma_buffer, dev->dma_buf_size); return 0; } #endif // HAS_DMA - case RPADC_FIFO_AUTO_SET_DRIVER_BUFLEN: { + case RPADC_FIFO_AUTO_SET_DRIVER_BUFLEN: + { if (dev->dma_started) return 0; dev->wIdx = 0; @@ -554,107 +618,131 @@ static long device_ioctl(struct file *file, unsigned int cmd, dev->fifoBuffer = (u32 *)kmalloc(dev->bufSize * sizeof(u32), GFP_KERNEL); return 0; } - case RPADC_FIFO_AUTO_GET_DRIVER_BUFLEN: { + case RPADC_FIFO_AUTO_GET_DRIVER_BUFLEN: + { copy_to_user((void __user *)arg, &dev->bufSize, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_COMMAND_REGISTER: { + case RPADC_FIFO_AUTO_GET_COMMAND_REGISTER: + { copy_to_user((void __user *)arg, dev->iomap_command_register, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_COMMAND_REGISTER: { + case RPADC_FIFO_AUTO_SET_COMMAND_REGISTER: + { copy_from_user(dev->iomap_command_register, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_DECIMATOR_REGISTER: { + case RPADC_FIFO_AUTO_GET_DECIMATOR_REGISTER: + { copy_to_user((void __user *)arg, dev->iomap_decimator_register, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_DECIMATOR_REGISTER: { + case RPADC_FIFO_AUTO_SET_DECIMATOR_REGISTER: + { copy_from_user(dev->iomap_decimator_register, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_MODE_REGISTER: { + case RPADC_FIFO_AUTO_GET_MODE_REGISTER: + { copy_to_user((void __user *)arg, dev->iomap_mode_register, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_MODE_REGISTER: { + case RPADC_FIFO_AUTO_SET_MODE_REGISTER: + { copy_from_user(dev->iomap_mode_register, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_PACKETIZER: { + case RPADC_FIFO_AUTO_GET_PACKETIZER: + { copy_to_user((void __user *)arg, dev->iomap_packetizer, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_PACKETIZER: { + case RPADC_FIFO_AUTO_SET_PACKETIZER: + { copy_from_user(dev->iomap_packetizer, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_POST_REGISTER: { + case RPADC_FIFO_AUTO_GET_POST_REGISTER: + { copy_to_user((void __user *)arg, dev->iomap_post_register, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_POST_REGISTER: { + case RPADC_FIFO_AUTO_SET_POST_REGISTER: + { copy_from_user(dev->iomap_post_register, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_PRE_REGISTER: { + case RPADC_FIFO_AUTO_GET_PRE_REGISTER: + { copy_to_user((void __user *)arg, dev->iomap_pre_register, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_PRE_REGISTER: { + case RPADC_FIFO_AUTO_SET_PRE_REGISTER: + { copy_from_user(dev->iomap_pre_register, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_TRIG_EVENT_CODE: { + case RPADC_FIFO_AUTO_GET_TRIG_EVENT_CODE: + { copy_to_user((void __user *)arg, dev->iomap_trig_event_code, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_TRIG_EVENT_CODE: { + case RPADC_FIFO_AUTO_SET_TRIG_EVENT_CODE: + { copy_from_user(dev->iomap_trig_event_code, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_EVENT_CODE: { + case RPADC_FIFO_AUTO_GET_EVENT_CODE: + { copy_to_user((void __user *)arg, dev->iomap_event_code, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_SET_EVENT_CODE: { + case RPADC_FIFO_AUTO_SET_EVENT_CODE: + { copy_from_user(dev->iomap_event_code, (void __user *)arg, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_DATA_FIFO_LEN: { + case RPADC_FIFO_AUTO_GET_DATA_FIFO_LEN: + { u32 val = readFifo(dev->iomap_data_fifo, RDFO); copy_to_user((void __user *)arg, &val, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_DATA_FIFO_VAL: { + case RPADC_FIFO_AUTO_GET_DATA_FIFO_VAL: + { u32 val = readFifo(dev->iomap1_data_fifo, RDFD4); copy_to_user((void __user *)arg, &val, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_CLEAR_DATA_FIFO: { + case RPADC_FIFO_AUTO_CLEAR_DATA_FIFO: + { clearFifo(dev->iomap_data_fifo, dev->iomap1_data_fifo); return 0; } - case RPADC_FIFO_AUTO_GET_TIME_FIFO_LEN: { + case RPADC_FIFO_AUTO_GET_TIME_FIFO_LEN: + { u32 val = readFifo(dev->iomap_time_fifo, RDFO); copy_to_user((void __user *)arg, &val, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_GET_TIME_FIFO_VAL: { + case RPADC_FIFO_AUTO_GET_TIME_FIFO_VAL: + { u32 val = readFifo(dev->iomap1_time_fifo, RDFD4); copy_to_user((void __user *)arg, &val, sizeof(u32)); return 0; } - case RPADC_FIFO_AUTO_CLEAR_TIME_FIFO: { + case RPADC_FIFO_AUTO_CLEAR_TIME_FIFO: + { clearFifo(dev->iomap_time_fifo, dev->iomap1_time_fifo); return 0; } - case RPADC_FIFO_AUTO_GET_REGISTERS: { + case RPADC_FIFO_AUTO_GET_REGISTERS: + { struct rpadc_fifo_auto_registers currConf; memset(&currConf, 0, sizeof(currConf)); currConf.command_register = *((u32 *)dev->iomap_command_register); @@ -667,7 +755,8 @@ static long device_ioctl(struct file *file, unsigned int cmd, currConf.event_code = *((u32 *)dev->iomap_event_code); copy_to_user((void __user *)arg, &currConf, sizeof(currConf)); } - case RPADC_FIFO_AUTO_SET_REGISTERS: { + case RPADC_FIFO_AUTO_SET_REGISTERS: + { struct rpadc_fifo_auto_registers currConf; copy_from_user(&currConf, (void __user *)arg, sizeof(currConf)); if (currConf.command_register_enable) @@ -719,7 +808,8 @@ static long device_ioctl(struct file *file, unsigned int cmd, } static unsigned int device_poll(struct file *file, - struct poll_table_struct *p) { + struct poll_table_struct *p) +{ unsigned int mask = 0; struct rpadc_fifo_auto_dev *dev = (struct rpadc_fifo_auto_dev *)file->private_data; @@ -741,7 +831,8 @@ static struct class *rpadc_fifo_auto_class; static struct rpadc_fifo_auto_dev staticPrivateInfo; #ifdef HAS_FIFO_INTERRUPT -static void setIrq(struct platform_device *pdev) { +static void setIrq(struct platform_device *pdev) +{ staticPrivateInfo.irq = platform_get_irq(pdev, 0); printk(KERN_DEBUG "IRQ: %x\n", staticPrivateInfo.irq); int res = request_irq(staticPrivateInfo.irq, IRQ_cb, IRQF_TRIGGER_RISING, @@ -755,7 +846,8 @@ static void setIrq(struct platform_device *pdev) { } #endif -static int rpadc_fifo_auto_probe(struct platform_device *pdev) { +static int rpadc_fifo_auto_probe(struct platform_device *pdev) +{ int i; u32 off; static int memIdx; @@ -766,7 +858,8 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { printk("rpadc_fifo_auto_probe %s\n", pdev->name); // CHAR DEV // - if (!deviceAllocated) { + if (!deviceAllocated) + { deviceAllocated = 1; memIdx = 0; printk("registering char dev %s ...\n", pdev->name); @@ -777,7 +870,8 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { err = alloc_chrdev_region(&newDev, 0, 1, DEVICE_NAME); id_major = MAJOR(newDev); printk("MAJOR ID...%d\n", id_major); - if (err < 0) { + if (err < 0) + { printk("alloc_chrdev_region failed\n"); return err; } @@ -786,7 +880,8 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { staticPrivateInfo.cdev.ops = &fops; devno = MKDEV(id_major, 0); // Minor Id is 0 err = cdev_add(&staticPrivateInfo.cdev, devno, 1); - if (err < 0) { + if (err < 0) + { printk("cdev_add failed\n"); return err; } @@ -814,7 +909,8 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { staticPrivateInfo.dma_chan = NULL; // Declare DMA Channel staticPrivateInfo.dma_chan = dma_request_slave_channel(&pdev->dev, "dma0"); - if (IS_ERR(staticPrivateInfo.dma_chan)) { + if (IS_ERR(staticPrivateInfo.dma_chan)) + { pr_err("xilinx_dmatest: No Tx channel\n"); dma_release_channel(staticPrivateInfo.dma_chan); return -EFAULT; @@ -824,13 +920,14 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { off = r_mem->start & ~PAGE_MASK; staticPrivateInfo.iomap_command_register = devm_ioremap(&pdev->dev, r_mem->start + off, 0xffff); - - } else // Further calls for memory resources + } + else // Further calls for memory resources { // printk("SUCCESSIVA CHIAMATA A rfx_rpadc_fifo_auto_probe: %s, memIdx: // %d\n", pdev->name, memIdx); r_mem = platform_get_resource(pdev, // IORESOURCE_MEM, 0); off = r_mem->start & ~PAGE_MASK; - switch (memIdx) { + switch (memIdx) + { case 0: r_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); @@ -907,9 +1004,11 @@ static int rpadc_fifo_auto_probe(struct platform_device *pdev) { return 0; } -static int rpadc_fifo_auto_remove(struct platform_device *pdev) { +static int rpadc_fifo_auto_remove(struct platform_device *pdev) +{ printk("PLATFORM DEVICE REMOVE...\n"); - if (rpadc_fifo_auto_class) { + if (rpadc_fifo_auto_class) + { device_destroy(rpadc_fifo_auto_class, MKDEV(id_major, 0)); class_destroy(rpadc_fifo_auto_class); } @@ -949,13 +1048,15 @@ static struct platform_driver rpadc_fifo_auto_driver = { .remove = rpadc_fifo_auto_remove, }; -static int __init rpadc_fifo_auto_init(void) { +static int __init rpadc_fifo_auto_init(void) +{ printk(KERN_INFO "inizializing AXI module ...\n"); deviceAllocated = 0; return platform_driver_register(&rpadc_fifo_auto_driver); } -static void __exit rpadc_fifo_auto_exit(void) { +static void __exit rpadc_fifo_auto_exit(void) +{ printk(KERN_INFO "exiting AXI module ...\n"); platform_driver_unregister(&rpadc_fifo_auto_driver); } diff --git a/dwscope/RemoteDummies.c b/dwscope/RemoteDummies.c index 2c07d7ddd6..fb3eb20001 100644 --- a/dwscope/RemoteDummies.c +++ b/dwscope/RemoteDummies.c @@ -30,7 +30,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif - void XmdsInitialize() { + void XmdsInitialize() +{ xmdsWaveformWidgetClass = (WidgetClass)&xmdsWaveformClassRec; MrmRegisterClass(MrmwcUnknown, "XmdsWaveformWidgetClass", "XmdsCreateWaveform", (Widget(*)(void))XmdsCreateWaveform, diff --git a/dwscope/dwpad.c b/dwscope/dwpad.c index d1975e9698..d49779c4a1 100644 --- a/dwscope/dwpad.c +++ b/dwscope/dwpad.c @@ -232,7 +232,8 @@ static int ApplyStatus = 0; static int Modified = 0; static String defaultfile; -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ /*------------------------------------------------------------------------------ Local variables: */ @@ -285,8 +286,8 @@ int main(int argc, char **argv) { XtAppContext app_ctx; MrmHierarchy drm_hierarchy; static const char *fontfamilies[] = { - "adobe", "b&h", "bitstream", "bold", "bolditalic", "isas", - "italic", "misc", "schumacher", "sony", "sun", "xfree86"}; + "adobe", "b&h", "bitstream", "bold", "bolditalic", "isas", + "italic", "misc", "schumacher", "sony", "sun", "xfree86"}; static const char *fontfmt = "-%s-%s-medium-r-normal-*-*-*-%3.3d-%3.3d-*-*-*-*"; #define MAXFONTNAMELEN 255 @@ -315,17 +316,20 @@ int main(int argc, char **argv) { XtManageChild(MainWidget); sprintf(fontname, fontfmt, "*", "menu", 100, 100); font[0] = XLoadQueryFont(XtDisplay(TopWidget), fontname); - for (i = 0; ((!font[0]) && (i < N_ELEMENTS(fontfamilies))); i++) { + for (i = 0; ((!font[0]) && (i < N_ELEMENTS(fontfamilies))); i++) + { sprintf(fontname, fontfmt, fontfamilies[i], "*", 100, 100); font[0] = XLoadQueryFont(XtDisplay(TopWidget), fontname); } sprintf(fontname, fontfmt, "*", "menu", 120, 120); font[1] = XLoadQueryFont(XtDisplay(TopWidget), fontname); - for (i = 0; ((!font[1]) && (i < N_ELEMENTS(fontfamilies))); i++) { + for (i = 0; ((!font[1]) && (i < N_ELEMENTS(fontfamilies))); i++) + { sprintf(fontname, fontfmt, fontfamilies[i], "*", 120, 120); font[1] = XLoadQueryFont(XtDisplay(TopWidget), fontname); } - if ((!font[0]) && (!font[1])) { + if ((!font[0]) && (!font[1])) + { printf( "No useable Fonts found-Please check your X-Windows configuration\n"); exit(0); @@ -340,7 +344,8 @@ int main(int argc, char **argv) { return 0; } -static void LabelSetString(Widget w, String string) { +static void LabelSetString(Widget w, String string) +{ XmString label = XmStringCreateSimple(strlen(string) ? string : " "); XtVaSetValues(w, XmNlabelString, label, NULL); XmStringFree(label); @@ -348,7 +353,8 @@ static void LabelSetString(Widget w, String string) { static void ExitWithCheck(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ if (Modified) XtManageChild(WriteBeforeExitWidget); else @@ -357,14 +363,16 @@ static void ExitWithCheck(Widget w __attribute__((unused)), static void Exit(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ exit(1); } static void ApplyCustomizeWindow(Widget w __attribute__((unused)), int *tag __attribute__((unused)), XtPointer callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ String title = XmTextGetString(XtNameToWidget(CustomizeWindowWidget, "window_title")); String icon = @@ -392,7 +400,8 @@ static void ApplyCustomizeWindow(Widget w __attribute__((unused)), PopupComplaint(TopWidget, "Rows value is invalid."); else if (rows * cols > 1000) PopupComplaint(TopWidget, "Cannot have more than 1000 buttons"); - else { + else + { ResetWindow(0, title, icon, cols, rows, bigfont, btnwidth); ApplyStatus = 1; Modified = 1; @@ -405,7 +414,8 @@ static void ApplyCustomizeWindow(Widget w __attribute__((unused)), static void ResetCustomizeWindow(Widget w __attribute__((unused)), int *tag __attribute__((unused)), XtPointer callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ char number[12]; XmTextSetString(XtNameToWidget(CustomizeWindowWidget, "window_title"), PadTitle); @@ -424,13 +434,15 @@ static void ResetCustomizeWindow(Widget w __attribute__((unused)), static void ApplyLabel(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ WaveInfo *info; XtVaGetValues(CurrentWidget, XmNuserData, &info, NULL); if (ReplaceString(&info->pad_label, XmTextGetString( XtNameToWidget(PadLabelWidget, "pad_label_expression")), - 1)) { + 1)) + { LabelSetString(CurrentWidget, info->pad_label); Modified = 1; } @@ -438,7 +450,8 @@ static void ApplyLabel(Widget w __attribute__((unused)), static void ApplyDataSetup(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ WaveInfo *info; int change_mask; XtVaGetValues(CurrentWidget, XmNuserData, &info, NULL); @@ -450,12 +463,14 @@ static void ApplyDataSetup(Widget w __attribute__((unused)), } static void Ok(Widget w, int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ if (ApplyStatus & 1) XtUnmanageChild(XtParent(w)); } -static void UpdatePopups() { +static void UpdatePopups() +{ if (XtIsManaged(DataSetupWidget)) ResetDataSetup(NULL, NULL, NULL); else if (XtIsManaged(PadLabelWidget)) @@ -464,7 +479,8 @@ static void UpdatePopups() { static void EraseDataSetup(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ WaveInfo *info; XtVaGetValues(PendingWidget, XmNuserData, &info, NULL); ResetWave(info); @@ -476,22 +492,29 @@ static void EraseDataSetup(Widget w __attribute__((unused)), static void /*XtCallbackProc */ Restore(Widget w __attribute__((unused)), int *option, - XmFileSelectionBoxCallbackStruct *reason) { + XmFileSelectionBoxCallbackStruct *reason) +{ int opt = option ? *option : 0; - switch (opt) { - case 0: { - if (reason->length) { + switch (opt) + { + case 0: + { + if (reason->length) + { String filename; filename = XmStringUnparse(reason->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (filename) { + if (filename) + { int length = strlen(filename); - if (length) { + if (length) + { RestoreDatabase(filename); if (defaultfile) XtFree(defaultfile); defaultfile = filename; - } else + } + else XtFree(filename); } } @@ -500,7 +523,8 @@ Restore(Widget w __attribute__((unused)), int *option, case 1: RestoreDatabase(defaultfile); break; - case 2: { + case 2: + { Widget w = XtNameToWidget(TopWidget, "*file_dialog"); XmString title = XmStringCreateSimple("Restore Current Settings From"); XmString label = @@ -524,22 +548,29 @@ Restore(Widget w __attribute__((unused)), int *option, static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), int *option, - XmFileSelectionBoxCallbackStruct *reason) { + XmFileSelectionBoxCallbackStruct *reason) +{ int opt = option ? *option : 0; - switch (opt) { - case 0: { - if (reason->length) { + switch (opt) + { + case 0: + { + if (reason->length) + { String filename; filename = XmStringUnparse(reason->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (filename) { + if (filename) + { int length = strlen(filename); - if (length) { + if (length) + { WriteDatabase(filename); if (defaultfile) XtFree(defaultfile); defaultfile = filename; - } else + } + else XtFree(filename); } } @@ -548,7 +579,8 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), case 1: WriteDatabase(defaultfile); break; - case 2: { + case 2: + { Widget w = XtNameToWidget(TopWidget, "*file_dialog"); XmString title = XmStringCreateSimple("Save Current Settings As"); XmString label = @@ -572,7 +604,8 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), static void ResetLabel(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ WaveInfo *info; XmString title = XmStringCreateSimple(SetupTitle()); CurrentWidget = PendingWidget; @@ -586,7 +619,8 @@ static void ResetLabel(Widget w __attribute__((unused)), static void ResetDataSetup(Widget w __attribute__((unused)), int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ WaveInfo *info; CurrentWidget = PendingWidget; XtVaGetValues(CurrentWidget, XmNuserData, &info, NULL); @@ -595,7 +629,8 @@ static void ResetDataSetup(Widget w __attribute__((unused)), static void Setup(Widget w, XtPointer client_data __attribute__((unused)), XButtonEvent *event, - Boolean *continue_to_dispatch __attribute__((unused))) { + Boolean *continue_to_dispatch __attribute__((unused))) +{ int i; int num_waves; Widget *widgets; @@ -610,16 +645,19 @@ static void Setup(Widget w, XtPointer client_data __attribute__((unused)), event_x -= x_offset; event_y -= y_offset; widg = 0; - for (i = 0; i < num_waves; i++) { + for (i = 0; i < num_waves; i++) + { int w_x = XtX(widgets[i]); int w_y = XtY(widgets[i]); if (event_x > w_x && event_x < w_x + (int)XtWidth(widgets[i]) && - event_y > w_y && event_y < w_y + (int)XtHeight(widgets[i])) { + event_y > w_y && event_y < w_y + (int)XtHeight(widgets[i])) + { widg = widgets[i]; break; } } - if (widg && event->button == Button3) { + if (widg && event->button == Button3) + { PendingWidget = widg; PositionPopupMenu(Button3Widget, event); XtManageChild(Button3Widget); @@ -627,20 +665,24 @@ static void Setup(Widget w, XtPointer client_data __attribute__((unused)), } static void ComputeOffsets(Widget child, Widget ancestor, int *x_offset, - int *y_offset) { + int *y_offset) +{ Widget parent; *x_offset = 0; *y_offset = 0; for (parent = XtParent(child); parent != ancestor; - parent = XtParent(parent)) { + parent = XtParent(parent)) + { (*x_offset) += XtX(parent); (*y_offset) += XtY(parent); } return; } -static void SetPadVideo(Widget w, Boolean reverse) { - if (w) { +static void SetPadVideo(Widget w, Boolean reverse) +{ + if (w) + { int fore, back; XtVaGetValues(MainWidget, XmNbackground, &back, XmNforeground, &fore, NULL); XtVaSetValues(w, XmNbackground, reverse ? fore : back, XmNforeground, @@ -650,12 +692,14 @@ static void SetPadVideo(Widget w, Boolean reverse) { static void Cut(Widget w, XEvent *event __attribute__((unused)), String *params __attribute__((unused)), - Cardinal *num_params __attribute__((unused))) { + Cardinal *num_params __attribute__((unused))) +{ if (w == SelectedWidget) XtDisownSelection(w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w))); else if (XtOwnSelection(w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w)), (XtConvertSelectionProc)ConvertSelection, - (XtLoseSelectionProc)LoseSelection, NULL)) { + (XtLoseSelectionProc)LoseSelection, NULL)) + { SetPadVideo(w, 1); SelectedWidget = w; } @@ -664,7 +708,8 @@ static void Cut(Widget w, XEvent *event __attribute__((unused)), static Boolean ConvertSelection(Widget w, Atom *selection __attribute__((unused)), Atom *target, Atom *type, XtPointer *value, - unsigned int *length, int *format) { + unsigned int *length, int *format) +{ int r = 0; int c = 0; char prefix[36]; @@ -676,13 +721,15 @@ static Boolean ConvertSelection(Widget w, format); } -static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) { +static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) +{ SetPadVideo(w, 0); if (SelectedWidget == w) SelectedWidget = 0; } -static void MakeWaves(int cols, int rows) { +static void MakeWaves(int cols, int rows) +{ int old_numwaves; int num_waves = cols * rows; int i; @@ -691,8 +738,10 @@ static void MakeWaves(int cols, int rows) { if (!translations) translations = XtParseTranslationTable(":Cut()\n :Paste()"); - if (old_numwaves < num_waves) { - for (i = old_numwaves; i < num_waves; i++) { + if (old_numwaves < num_waves) + { + for (i = old_numwaves; i < num_waves; i++) + { WaveInfo *info = (WaveInfo *)XtMalloc(sizeof(WaveInfo)); memset(info, 0, sizeof(WaveInfo)); ResetWave(info); @@ -706,7 +755,8 @@ static void MakeWaves(int cols, int rows) { } static void ResetWindow(String geometry, String title, String icon, int cols, - int rows, Boolean bigfont, int btnwidth) { + int rows, Boolean bigfont, int btnwidth) +{ int x; int y; unsigned int width; @@ -718,7 +768,8 @@ static void ResetWindow(String geometry, String title, String icon, int cols, XtUnmanageChild(PadWidget); XtVaGetValues(PadWidget, XmNnumChildren, &num, XmNchildren, &widgets, NULL); XtUnmanageChildren(widgets, num); - if (geometry) { + if (geometry) + { XParseGeometry(geometry, &x, &y, &width, &height); if (x >= WidthOfScreen(XtScreen(PadWidget))) x = WidthOfScreen(XtScreen(PadWidget)) - 50; @@ -741,7 +792,8 @@ static void ResetWindow(String geometry, String title, String icon, int cols, MakeWaves(cols, rows); num = Rows * Columns; XtVaGetValues(PadWidget, XmNchildren, &widgets, NULL); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { WaveInfo *info; XtVaGetValues(widgets[i], XmNuserData, &info, NULL); XtVaSetValues(widgets[i], XmNwidth, width, XmNheight, height, XmNfontList, @@ -759,7 +811,8 @@ static void ResetWindow(String geometry, String title, String icon, int cols, NULL); } -static void RestoreDatabase(String dbname) { +static void RestoreDatabase(String dbname) +{ int c; int r; Widget *widgets; @@ -769,7 +822,8 @@ static void RestoreDatabase(String dbname) { MakeWaves(cols, rows); XtVaGetValues(PadWidget, XmNchildren, &widgets, NULL); for (c = 0; c < cols; c++) - for (r = 0; r < rows; r++) { + for (r = 0; r < rows; r++) + { WaveInfo *info; XtVaGetValues(widgets[c * Rows + r], XmNuserData, &info, NULL); GetWaveFromDb(paddb, "Pad.pad", r, c, info); @@ -785,7 +839,8 @@ static void RestoreDatabase(String dbname) { static void Paste(Widget w, XEvent *event __attribute__((unused)), String *params __attribute__((unused)), - Cardinal *num_params __attribute__((unused))) { + Cardinal *num_params __attribute__((unused))) +{ XtGetSelectionValue(w, XA_PRIMARY, XA_TARGETS, (XtSelectionCallbackProc)PasteTypesComplete, 0, XtLastTimestampProcessed(XtDisplay(w))); @@ -796,12 +851,14 @@ static void PasteTypesComplete(Widget w, Atom *selection __attribute__((unused)), Atom *type __attribute__((unused)), XtPointer value, unsigned int *length, - int *format __attribute__((unused))) { + int *format __attribute__((unused))) +{ unsigned int i; Atom req_type = XA_STRING; Atom *values = (Atom *)value; for (i = 0; i < *length; i++) - if (values[i] == XA_DWSCOPE_PANEL) { + if (values[i] == XA_DWSCOPE_PANEL) + { req_type = XA_DWSCOPE_PANEL; break; } @@ -815,15 +872,18 @@ static void PasteTypesComplete(Widget w, static void PasteComplete(Widget w, XtPointer cdata __attribute__((unused)), Atom *selection __attribute__((unused)), Atom *type, XtPointer value, unsigned int *length, - int *format __attribute__((unused))) { + int *format __attribute__((unused))) +{ WaveInfo *info; XtVaGetValues(w, XmNuserData, &info, NULL); - if (ConvertSelectionToWave(w, *type, *length, value, info)) { + if (ConvertSelectionToWave(w, *type, *length, value, info)) + { if (w == CurrentWidget) UpdatePopups(); if (strlen(info->pad_label)) LabelSetString(w, info->pad_label); - else { + else + { PendingWidget = w; ResetLabel(w, 0, 0); XtManageChild(PadLabelWidget); @@ -834,7 +894,8 @@ static void PasteComplete(Widget w, XtPointer cdata __attribute__((unused)), XtFree(value); } -static String SetupTitle() { +static String SetupTitle() +{ static char title[80]; int r = 0; int c = 0; @@ -843,7 +904,8 @@ static String SetupTitle() { return title; } -static int FindWave(Widget w, int *c, int *r) { +static int FindWave(Widget w, int *c, int *r) +{ int num; Widget *widgets; XtVaGetValues(PadWidget, XmNnumChildren, &num, XmNchildren, &widgets, NULL); @@ -854,7 +916,8 @@ static int FindWave(Widget w, int *c, int *r) { return 0; } -static void WriteDatabase(String dbname) { +static void WriteDatabase(String dbname) +{ int r; int c; Position x; @@ -863,7 +926,8 @@ static void WriteDatabase(String dbname) { Dimension height; Widget *widgets; FILE *file = fopen(dbname, "w"); - if (file) { + if (file) + { XtVaGetValues(PadWidget, XmNchildren, &widgets, NULL); XtVaGetValues(TopWidget, XtNx, &x, XtNy, &y, NULL); XtVaGetValues(MainWidget, XtNwidth, &width, XtNheight, &height, NULL); @@ -874,8 +938,10 @@ static void WriteDatabase(String dbname) { fprintf(file, "Pad.rows: %d\n", Rows); fprintf(file, "Pad.padlabelwidth: %d\n", PadLabelWidth); fprintf(file, "Pad.font: %d\n", PadBigFont); - for (c = 0; c < Columns; c++) { - for (r = 0; r < Rows; r++) { + for (c = 0; c < Columns; c++) + { + for (r = 0; r < Rows; r++) + { WaveInfo *info; char prefix[36]; int ctx = 0; @@ -883,13 +949,15 @@ static void WriteDatabase(String dbname) { fprintf(file, "\n"); sprintf(prefix, "Pad.pad_%d_%d", r + 1, c + 1); XtVaGetValues(widgets[c * Rows + r], XmNuserData, &info, NULL); - while ((text = WaveToText(prefix, info, 0, &ctx))) { + while ((text = WaveToText(prefix, info, 0, &ctx))) + { fprintf(file, "%s", text); XtFree(text); } } } fclose(file); - } else + } + else PopupComplaint(MainWidget, "Error writing setup file"); } diff --git a/dwscope/dwscope.c b/dwscope/dwscope.c index 0bd787de67..c8b6522251 100644 --- a/dwscope/dwscope.c +++ b/dwscope/dwscope.c @@ -322,7 +322,8 @@ static float DeltaY; static XtAppContext AppContext; static XtWorkProcId UpdateWaveformsWorkProcID; -int main(int argc, String *argv) { +int main(int argc, String *argv) +{ int i; static String hierarchy_names[] = {"dwscope.uid"}; String fallback_resources[] = { @@ -384,7 +385,8 @@ int main(int argc, String *argv) { {"Shrink", Shrink}, {"Expand", Expand}}; MrmType class; - typedef struct { + typedef struct + { String defaultfile; Boolean icon_update; } AppResourcesRec; @@ -434,12 +436,14 @@ int main(int argc, String *argv) { &drm_hierarchy); MrmFetchWidget(drm_hierarchy, "scope", TopWidget, &MainWidget, &class); MrmCloseHierarchy(drm_hierarchy); - if (!MainWidget) { + if (!MainWidget) + { printf("Problem loading UID\n"); exit(1); } LockScalesWidget = XtNameToWidget(MainWidget, "*lockScales"); - if (appRes.icon_update) { + if (appRes.icon_update) + { XmToggleButtonGadgetSetState( XtNameToWidget(TopWidget, "*disable_icon_updates"), False, False); } @@ -450,14 +454,16 @@ int main(int argc, String *argv) { for (c = 1; c < NumPanes; c++) XtVaSetValues(Pane[c], XmNleftAttachment, XmATTACH_OPPOSITE_WIDGET, XmNleftWidget, Sash[c - 1], XmNleftOffset, 2, NULL); - if (printers) { + if (printers) + { Widget printers_pulldown = XtNameToWidget(MainWidget, "*printer_select_pulldown"); Arg arglist[] = {{XmNlabelString, 0}}; int num; Widget *children; char *printer; - for (printer = strtok(printers, "\n"); printer; printer = strtok(0, "\n")) { + for (printer = strtok(printers, "\n"); printer; printer = strtok(0, "\n")) + { arglist[0].value = (long)XmStringCreateSimple(printer); XmCreatePushButtonGadget(printers_pulldown, printer, arglist, XtNumber(arglist)); @@ -472,7 +478,8 @@ int main(int argc, String *argv) { for (i = 0; i < NumSashs; i++) XDefineCursor(XtDisplay(TopWidget), XtWindow(Sash[i]), cursor); for (c = 0; c < MaxCols; c++) - for (r = 0; r < MaxRows; r++) { + for (r = 0; r < MaxRows; r++) + { int p_r = (r + 1) % MaxRows; int p_c = p_r ? c : (c + 1) % MaxCols; XtVaSetValues(Wave[c][r].w, XmdsNpanWith, Wave[p_c][p_r].w, NULL); @@ -498,7 +505,8 @@ int main(int argc, String *argv) { #include #include -static void DoPrint(char *filename) { +static void DoPrint(char *filename) +{ char cmd[512]; int num = snprintf(cmd, sizeof(cmd), "dwscopePrint %s %s", filename, ScopePrinter); @@ -507,18 +515,24 @@ static void DoPrint(char *filename) { printf("Error invoking dwscopePrint\n"); } -static char *GetPrinterList() { +static char *GetPrinterList() +{ char *printers = 0; FILE *fp = popen("ScopePrinters", "r"); - if (fp != NULL) { + if (fp != NULL) + { char buff[256]; size_t bytes; - while ((bytes = fread(buff, 1, sizeof(buff) - 1, fp))) { + while ((bytes = fread(buff, 1, sizeof(buff) - 1, fp))) + { buff[bytes] = 0; - if (printers) { + if (printers) + { printers = realloc(printers, strlen(printers) + 1 + bytes); strcat(printers, buff); - } else { + } + else + { printers = strcpy(malloc(bytes + 1), buff); } } @@ -527,16 +541,19 @@ static char *GetPrinterList() { return printers; } -static void Shrink(Widget w, XEvent *event __attribute__((unused))) { +static void Shrink(Widget w, XEvent *event __attribute__((unused))) +{ if (XmToggleButtonGadgetGetState( - XtNameToWidget(w, "*disable_icon_updates"))) { + XtNameToWidget(w, "*disable_icon_updates"))) + { UpdateWhenExpand = XmToggleButtonGadgetGetState(XtNameToWidget(w, "*updates")); XmToggleButtonGadgetSetState(XtNameToWidget(w, "*updates"), FALSE, TRUE); } } -static void Expand(Widget w, XEvent *event __attribute__((unused))) { +static void Expand(Widget w, XEvent *event __attribute__((unused))) +{ if (XmToggleButtonGadgetGetState( XtNameToWidget(w, "*disable_icon_updates")) && UpdateWhenExpand) @@ -545,12 +562,14 @@ static void Expand(Widget w, XEvent *event __attribute__((unused))) { static void /*XtCallbackProc */ UpdatesMenuButton(Widget w, int *mode __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ XmToggleButtonGadgetSetState(XtNameToWidget(MainWidget, "*updates"), !XmToggleButtonGadgetGetState(w), TRUE); } -static String XYString(float x, float y) { +static String XYString(float x, float y) +{ static char label[42] = {'['}; int length; String ptr = (String)&label[1]; @@ -565,10 +584,12 @@ static String XYString(float x, float y) { return (String)label; } -void PositionMark() { +void PositionMark() +{ if (!MarkWidget) MarkWidget = XtNameToWidget(MainWidget, "*crosshairs_mark"); - if (DeltaWaveWidget && XtIsManaged(DeltaWaveWidget)) { + if (DeltaWaveWidget && XtIsManaged(DeltaWaveWidget)) + { float *xmin, *xmax, *ymin, *ymax; Position plots_rootx, plots_rooty; Position wave_rootx, wave_rooty; @@ -588,19 +609,22 @@ void PositionMark() { XtHeight(PlotsWidget) * 1000; if (xpos < 0 || ypos < 0 || xpos > 1000 || ypos > 1000) XtUnmanageChild(MarkWidget); - else { + else + { XtVaSetValues(MarkWidget, XmNleftPosition, xpos, XmNtopPosition, ypos, NULL); XtManageChild(MarkWidget); } - } else + } + else XtUnmanageChild(MarkWidget); } static void /*XtCallbackProc */ Crosshairs(Widget w, XtPointer client_data __attribute__((unused)), - XmdsWaveformCrosshairsCBStruct *cb) { + XmdsWaveformCrosshairsCBStruct *cb) +{ static Widget value_w = 0; int r; int c; @@ -609,10 +633,13 @@ static void /*XtCallbackProc */ Crosshairs(Widget w, String label; if (!value_w) value_w = XtNameToWidget(MainWidget, "*crosshairs_value"); - if (cb->event->xbutton.type == ButtonPress) { - if (cb->event->xbutton.state & ShiftMask) { + if (cb->event->xbutton.type == ButtonPress) + { + if (cb->event->xbutton.state & ShiftMask) + { DeltaWaveWidget = DeltaWaveWidget ? 0 : w; - if (DeltaWaveWidget) { + if (DeltaWaveWidget) + { DeltaX = cb->x; DeltaY = cb->y; } @@ -625,7 +652,8 @@ static void /*XtCallbackProc */ Crosshairs(Widget w, XmdsWaveformSetCrosshairs(Wave[c][r].w, &cb->x, &cb->y, 0); display_x = cb->x; display_y = cb->y; - if (DeltaWaveWidget) { + if (DeltaWaveWidget) + { display_x -= DeltaX; display_y -= DeltaY; } @@ -639,13 +667,16 @@ static void /*XtCallbackProc */ Exit(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *reason - __attribute__((unused))) { + __attribute__((unused))) +{ exit(1); } static void /*XtCallbackProc */ -SetPointerMode(Widget w, int *mode, int *reason __attribute__((unused))) { - if (XmToggleButtonGetState(w)) { +SetPointerMode(Widget w, int *mode, int *reason __attribute__((unused))) +{ + if (XmToggleButtonGetState(w)) + { int r; int c; pointermode = *mode; @@ -661,10 +692,12 @@ SetPointerMode(Widget w, int *mode, int *reason __attribute__((unused))) { static void /*XtCallbackProc */ SetPointerModeMenu(Widget w __attribute__((unused)), int *mode, - int *reason __attribute__((unused))) { + int *reason __attribute__((unused))) +{ int r; int c; - switch (*mode) { + switch (*mode) + { case XmdsPOINTER_MODE_POINT: XmToggleButtonSetState(XtNameToWidget(MainWidget, "*Point"), 1, 1); break; @@ -685,27 +718,35 @@ SetPointerModeMenu(Widget w __attribute__((unused)), int *mode, } } -static void RemoveZeros(String string, int *length) { +static void RemoveZeros(String string, int *length) +{ int i; int done = 0; - while (!done) { + while (!done) + { done = 1; - for (i = *length; i > 0; i--) { + for (i = *length; i > 0; i--) + { if (((string[i] == 'e') && (string[i + 1] == '0')) || ((string[i] == '-') && (string[i + 1] == '0')) || - ((string[i] == '+') && (string[i + 1] == '0'))) { + ((string[i] == '+') && (string[i + 1] == '0'))) + { int j; for (j = i + 1; j < *length; j++) string[j] = string[j + 1]; (*length)--; done = 0; - } else if ((string[i] == '0') && (string[i + 1] == 'e')) { + } + else if ((string[i] == '0') && (string[i + 1] == 'e')) + { int j; for (j = i; j < *length; j++) string[j] = string[j + 1]; (*length)--; done = 0; - } else if ((string[i] == '.') && (string[i + 1] == 'e')) { + } + else if ((string[i] == '.') && (string[i + 1] == 'e')) + { int j; for (j = i; j < *length; j++) string[j] = string[j + 1]; @@ -719,7 +760,8 @@ static void RemoveZeros(String string, int *length) { static void /*XtCallbackProc */ Align(int w __attribute__((unused)), XtPointer client_data __attribute__((unused)), - XmdsWaveformLimitsCBStruct *l) { + XmdsWaveformLimitsCBStruct *l) +{ int r; int c; for (c = 0; c < MaxCols; c++) @@ -732,7 +774,8 @@ static void /*XtCallbackProc */ GridStyle(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *cb - __attribute__((unused))) { + __attribute__((unused))) +{ int lines = XmToggleButtonGadgetGetState(w); int r; int c; @@ -744,12 +787,14 @@ static void /*XtCallbackProc */ GridStyle(Widget w __attribute__((unused)), static void /*XtCallbackProc */ Ok(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ if (ApplyStatus & 1) XtUnmanageChild(XtParent(w)); } -static String SetupTitle() { +static String SetupTitle() +{ int c; int r; static char title[80]; @@ -767,10 +812,12 @@ static String SetupTitle() { static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), String type, XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ int r; int c; - switch (type[0]) { + switch (type[0]) + { case 'y': XtVaSetValues(PendingWave->w, XmdsNyMin, NULL, XmdsNyMax, NULL, NULL); break; @@ -797,7 +844,8 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), XtVaSetValues(Wave[c][r].w, XmdsNxMin, NULL, XmdsNxMax, NULL, XmdsNyMin, NULL, XmdsNyMax, NULL, NULL); break; - case '0': { + case '0': + { float *xMin; float *xMax; float *yMin; @@ -811,7 +859,8 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), XmdsNyMin, yMin, XmdsNyMax, yMax, NULL); break; } - case '1': { + case '1': + { float *xMin; float *xMax; float *yMin; @@ -824,7 +873,8 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), XtVaSetValues(Wave[c][r].w, XmdsNxMin, xMin, XmdsNxMax, xMax, NULL); break; } - case '2': { + case '2': + { float *xMin; float *xMax; float *yMin; @@ -837,7 +887,8 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), XtVaSetValues(Wave[c][r].w, XmdsNyMin, yMin, XmdsNyMax, yMax, NULL); break; } - case '3': { + case '3': + { float *xMin; float *xMax; float *yMin; @@ -850,7 +901,8 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), NULL, XmdsNyMax, NULL, NULL); break; } - case '4': { + case '4': + { float *xMin; float *xMax; float *yMin; @@ -863,13 +915,15 @@ static void /*XtCallbackProc */ Autoscale(Widget w __attribute__((unused)), yMin, XmdsNyMax, yMax, NULL); break; } - case '5': { + case '5': + { float *xMin; float *xMax; float *yMin; float *yMax; for (c = 0; c < MaxCols; c++) - for (r = 0; r < MaxRows; r++) { + for (r = 0; r < MaxRows; r++) + { Boolean update = Wave[c][r].update; Wave[c][r].update = TRUE; GetNewLimits(&Wave[c][r], &xMin, &xMax, &yMin, &yMax); @@ -887,27 +941,35 @@ static void /*XtCallbackProc */ Refresh(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ UpdateWaveform(0, PendingWave, 0, -1, -1); } static void /*XtCallbackProc */ -Restore(Widget w, int *option, XmFileSelectionBoxCallbackStruct *reason) { +Restore(Widget w, int *option, XmFileSelectionBoxCallbackStruct *reason) +{ int opt = option ? *option : 0; - switch (opt) { - case 0: { - if (reason->length) { + switch (opt) + { + case 0: + { + if (reason->length) + { String filename; filename = XmStringUnparse(reason->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (filename) { + if (filename) + { int length = strlen(filename); - if (length) { + if (length) + { RestoreDatabase(filename, w); if (defaultfile) XtFree(defaultfile); defaultfile = filename; - } else + } + else XtFree(filename); } } @@ -916,7 +978,8 @@ Restore(Widget w, int *option, XmFileSelectionBoxCallbackStruct *reason) { case 1: RestoreDatabase(defaultfile, TopWidget); break; - case 2: { + case 2: + { Widget w = XtNameToWidget(TopWidget, "*file_dialog"); XmString title = XmStringCreateSimple("Restore Current Settings From"); XmString label = @@ -941,22 +1004,29 @@ Restore(Widget w, int *option, XmFileSelectionBoxCallbackStruct *reason) { static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), int *option, - XmFileSelectionBoxCallbackStruct *reason) { + XmFileSelectionBoxCallbackStruct *reason) +{ int opt = option ? *option : 0; - switch (opt) { - case 0: { - if (reason->length) { + switch (opt) + { + case 0: + { + if (reason->length) + { String filename; filename = XmStringUnparse(reason->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (filename) { + if (filename) + { int length = strlen(filename); - if (length) { + if (length) + { WriteDatabase(filename, FALSE); if (defaultfile) XtFree(defaultfile); defaultfile = filename; - } else + } + else XtFree(filename); } } @@ -965,7 +1035,8 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), case 1: WriteDatabase(defaultfile, FALSE); break; - case 2: { + case 2: + { Widget w = XtNameToWidget(TopWidget, "*file_dialog"); XmString title = XmStringCreateSimple("Save Current Settings As"); XmString label = @@ -984,19 +1055,24 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), XmStringFree(deffile); break; } - case 3: { - if (reason->length) { + case 3: + { + if (reason->length) + { String filename; filename = XmStringUnparse(reason->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (filename) { + if (filename) + { int length = strlen(filename); - if (length) { + if (length) + { WriteDatabase(filename, TRUE); if (defaultfile) XtFree(defaultfile); defaultfile = filename; - } else + } + else XtFree(filename); } } @@ -1005,7 +1081,8 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), case 4: WriteDatabase(defaultfile, TRUE); break; - case 5: { + case 5: + { Widget w = XtNameToWidget(TopWidget, "*file_dialog"); XmString title = XmStringCreateSimple("Save Current Settings As"); XmString label = @@ -1028,7 +1105,8 @@ static void /*XtCallbackProc */ Save(Widget w __attribute__((unused)), } } -static void ManageWaveforms() { +static void ManageWaveforms() +{ int row; int col; int max_rows = 0; @@ -1036,11 +1114,13 @@ static void ManageWaveforms() { if (!translations) translations = XtParseTranslationTable( "Shift:EqualPanes(H)\n :EqualPanes(H)"); - for (col = 0; col < Columns; col++) { + for (col = 0; col < Columns; col++) + { Widget w[MaxRows]; if (Rows[col] > max_rows) max_rows = Rows[col]; - for (row = Rows[col]; row < MaxRows; row++) { + for (row = Rows[col]; row < MaxRows; row++) + { if (&Wave[col][row] == SelectedWave) XtDisownSelection(SelectedWave->w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(SelectedWave->w))); @@ -1058,7 +1138,8 @@ static void ManageWaveforms() { if (Columns > 1) XtManageChildren(Sash, Columns - 1); XtManageChildren(Pane, Columns); - for (col = 0; col < Columns; col++) { + for (col = 0; col < Columns; col++) + { int i; int num; Widget *child; @@ -1072,7 +1153,8 @@ static void ManageWaveforms() { RaiseWindows(); } -static void RaiseWindows() { +static void RaiseWindows() +{ int col; for (col = 0; col < Columns - 1; col++) XRaiseWindow(XtDisplay(Sash[col]), XtWindow(Sash[col])); @@ -1082,7 +1164,8 @@ static void RaiseWindows() { static void /*XtCallbackProc */ ResetDataSetup(Widget w __attribute__((unused)), int *global, - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ if (*global == 1) PendingWave = &GlobalWave; CurrentWave = PendingWave; @@ -1099,7 +1182,8 @@ static void /*XtCallbackProc */ ResetCustomizeWindow(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ int i; XmTextSetString(XtNameToWidget(CustomizeWindowWidget, "window_title"), ScopeTitle); @@ -1107,7 +1191,8 @@ ResetCustomizeWindow(Widget w __attribute__((unused)), ScopeIcon); XmTextSetString(XtNameToWidget(CustomizeWindowWidget, "title_event"), ScopeTitleEvent); - for (i = 0; i < MaxCols; i++) { + for (i = 0; i < MaxCols; i++) + { char name[8]; sprintf(name, "rows_%d", i + 1); XmScaleSetValue(XtNameToWidget(CustomizeWindowWidget, name), Rows[i]); @@ -1120,7 +1205,8 @@ static void /*XtCallbackProc */ ResetCustomizePrint(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ Widget *children; int numchildren; int i; @@ -1138,18 +1224,21 @@ ResetCustomizePrint(Widget w __attribute__((unused)), XtVaGetValues( XtNameToWidget(CustomizePrintWidget, "*printer_select_pulldown"), XmNnumChildren, &numchildren, XmNchildren, &children, NULL); - for (i = 0; i < numchildren; i++) { + for (i = 0; i < numchildren; i++) + { XmString label; String label_string; XtVaGetValues(children[i], XmNlabelString, &label, NULL); label_string = XmStringUnparse(label, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (strcmp(label_string, ScopePrinter) == 0) { + if (strcmp(label_string, ScopePrinter) == 0) + { XtFree(label_string); XtVaSetValues(XtNameToWidget(CustomizePrintWidget, "*printer_select"), XmNmenuHistory, children[i], NULL); break; - } else + } + else XtFree(label_string); } if ((i > numchildren) && numchildren > 0) @@ -1164,7 +1253,8 @@ ResetCustomizePrint(Widget w __attribute__((unused)), static void /*XtCallbackProc */ CreateCustomizeFont(Widget w, XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ int c_count; String *courier_fonts = XListFonts( XtDisplay(w), "-*-courier-*-*-*--*-*-*-*-*-*-*-*", 1000, &c_count); @@ -1204,10 +1294,13 @@ CreateCustomizeFont(Widget w, XtPointer client_data __attribute__((unused)), static void Setup(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XButtonEvent *event, - Boolean *continue_to_dispatch __attribute__((unused))) { - if (event->button == Button3) { + Boolean *continue_to_dispatch __attribute__((unused))) +{ + if (event->button == Button3) + { if ((event->type == ButtonPress) && - !(event->state & (Button1Mask | Button2Mask))) { + !(event->state & (Button1Mask | Button2Mask))) + { int col; int row; for (col = 0; col < Columns - 1 && event->x > XtX(Sash[col]); col++) @@ -1220,7 +1313,9 @@ static void Setup(Widget w __attribute__((unused)), PendingWave = &Wave[col][row]; PositionPopupMenu(Button3Widget, event); XtManageChild(Button3Widget); - } else { + } + else + { XUngrabPointer(XtDisplay(Button3Widget), event->time); XtPopdown(XtParent(Button3Widget)); } @@ -1231,7 +1326,8 @@ static void /*XtCallbackProc */ ApplyCustomizeWindow(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ int c; int r; int old_columns = Columns; @@ -1255,7 +1351,8 @@ ApplyCustomizeWindow(Widget w __attribute__((unused)), XtUnmanageChildren(widgets, num); Columns = 1; memcpy(old_rows, Rows, sizeof(Rows)); - for (c = 0; c < MaxCols; c++) { + for (c = 0; c < MaxCols; c++) + { char name[8]; sprintf(name, "rows_%d", c + 1); XmScaleGetValue(XtNameToWidget(CustomizeWindowWidget, name), &Rows[c]); @@ -1264,19 +1361,26 @@ ApplyCustomizeWindow(Widget w __attribute__((unused)), else Rows[c] = 1; } - for (c = 0; c < MaxCols; c++) { - for (r = 0; r < MaxRows; r++) { - if (c >= Columns) { + for (c = 0; c < MaxCols; c++) + { + for (r = 0; r < MaxRows; r++) + { + if (c >= Columns) + { ClearWaveform(&Wave[c][r]); Rows[c] = 0; - } else if (r >= Rows[c]) + } + else if (r >= Rows[c]) ClearWaveform(&Wave[c][r]); - else { - if ((r < Rows[c]) && (Rows[c] != old_rows[c])) { + else + { + if ((r < Rows[c]) && (Rows[c] != old_rows[c])) + { int height = (pane_height - 2 * Rows[c] + (r % 2) * .4999) / Rows[c]; XtVaSetValues(Wave[c][r].w, XtNheight, height, NULL); } - if ((r >= old_rows[c]) && (r < Rows[c])) { + if ((r >= old_rows[c]) && (r < Rows[c])) + { WaveInfo *info = &Wave[c][r]; UpdateWaveform(0, info, 0, -1, -1); SetupEvent(info->_global.global.event ? GlobalWave.event @@ -1298,7 +1402,8 @@ static void /*XtCallbackProc */ ApplyCustomizePrint(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ Widget printer_select = XtNameToWidget(MainWidget, "*printer_select"); Widget option; XmString label; @@ -1325,16 +1430,20 @@ ApplyCustomizePrint(Widget w __attribute__((unused)), ApplyStatus = 1; } -static void SetFont(String font) { +static void SetFont(String font) +{ int c; int r; XFontStruct *font_struct = XLoadQueryFont(XtDisplay(TopWidget), font); - if (font_struct) { + if (font_struct) + { for (c = 0; c < MaxCols; c++) for (r = 0; r < MaxRows; r++) if (Wave[c][r].w) XtVaSetValues(Wave[c][r].w, XmdsNlabelFont, font_struct, NULL); - } else { + } + else + { static String prefix = "Unknown font selected: "; String error = XtMalloc(strlen(prefix) + strlen(font) + 1); sprintf(error, "%s%s", prefix, font); @@ -1346,7 +1455,8 @@ static void SetFont(String font) { static void ResetCustomizeFont(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ String font; XFontStruct *font_struct; unsigned long fontprop; @@ -1363,7 +1473,8 @@ static void ResetCustomizeFont(Widget w __attribute__((unused)), static void /*XtCallbackProc */ ApplyFont(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), - XmSelectionBoxCallbackStruct *callback_data) { + XmSelectionBoxCallbackStruct *callback_data) +{ String font; font = XmStringUnparse(callback_data->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); @@ -1375,28 +1486,34 @@ void /*XtInputCallbackProc */ EventUpdate(XtPointer client_data __attribute__((unused)), int *source __attribute__((unused)), XtInputId *id - __attribute__((unused))) { + __attribute__((unused))) +{ int r; int c; XAllowEvents(XtDisplay(Button3Widget), AsyncPointer, CurrentTime); pthread_mutex_lock(&event_mutex); - if (ScopeTitleEventReceived) { + if (ScopeTitleEventReceived) + { SetWindowTitles(); ScopeTitleEventReceived = 0; } - if (UpdatesOn) { + if (UpdatesOn) + { for (c = 0; c < MaxCols; c++) for (r = 0; r < MaxRows; r++) - if (Wave[c][r].received) { + if (Wave[c][r].received) + { UpdateWaveform(0, &Wave[c][r], 1, -1, -1); Wave[c][r].received = 0; } - if (ScopePrintEventReceived) { + if (ScopePrintEventReceived) + { PrintAll(0, 0, 0); ScopePrintEventReceived = 0; } } - if (CloseDataSourcesEventReceived) { + if (CloseDataSourcesEventReceived) + { CloseDataSourcesEventReceived = 0; CloseDataSources(); } @@ -1404,19 +1521,23 @@ void /*XtInputCallbackProc */ EventUpdate(XtPointer client_data return; } -struct _UpdateWaveformsInfo { +struct _UpdateWaveformsInfo +{ int r; int c; }; -static Boolean UpdateWaveformsWorkproc(XtPointer settings) { +static Boolean UpdateWaveformsWorkproc(XtPointer settings) +{ struct _UpdateWaveformsInfo *info = (struct _UpdateWaveformsInfo *)settings; UpdateWaveform(0, &Wave[info->c][info->r], 0, -1, -1); info->r++; - if (info->r >= Rows[info->c]) { + if (info->r >= Rows[info->c]) + { info->r = 0; info->c++; - if (info->c >= Columns) { + if (info->c >= Columns) + { XmString label = XmStringCreateSimple("Apply"); XtVaSetValues(XtNameToWidget(MainWidget, "*override_shot_apply"), XmNlabelString, label, XmNmarginWidth, 5, NULL); @@ -1434,16 +1555,20 @@ static Boolean UpdateWaveformsWorkproc(XtPointer settings) { static void /*XtCallbackProc */ ApplyOverride(Widget w __attribute__((unused)), int *mode __attribute__((unused)), XtPointer callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ static struct _UpdateWaveformsInfo info; - if (UpdateWaveformsWorkProcID != 0) { + if (UpdateWaveformsWorkProcID != 0) + { XmString label = XmStringCreateSimple("Apply"); XtRemoveWorkProc(UpdateWaveformsWorkProcID); XtVaSetValues(XtNameToWidget(MainWidget, "*override_shot_apply"), XmNlabelString, label, XmNmarginWidth, 5, NULL); UpdateWaveformsWorkProcID = 0; XmStringFree(label); - } else { + } + else + { XmString label = XmStringCreateSimple("Cancel"); XtVaSetValues(XtNameToWidget(MainWidget, "*override_shot_apply"), XmNlabelString, label, XmNmarginWidth, 2, NULL); @@ -1458,7 +1583,8 @@ static void /*XtCallbackProc */ ApplyOverride(Widget w __attribute__((unused)), static void /*XtCallbackProc */ Updates(Widget w, int *mode __attribute__((unused)), XtPointer callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ UpdatesOn = XmToggleButtonGadgetGetState(w); if (UpdatesOn) EventUpdate(0, 0, 0); @@ -1468,15 +1594,19 @@ static void /*XtCallbackProc */ Updates(Widget w, static void /*XtCallbackProc */ ApplyDataSetup(Widget w, int *mode, XtPointer callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ int change_mask; - if (CurrentWave != &GlobalWave) { - if (*mode) { + if (CurrentWave != &GlobalWave) + { + if (*mode) + { WaveInfo info; CopyWave(CurrentWave, &info); GetDataSetup(DataSetupWidget, &info, &change_mask); ApplyStatus = UpdateWaveform(*mode, &info, 0, 0, change_mask); - if (ApplyStatus & 1) { + if (ApplyStatus & 1) + { String event = info._global.global.event ? GlobalWave.event : info.event; FreeWave(CurrentWave); @@ -1485,19 +1615,25 @@ static void /*XtCallbackProc */ ApplyDataSetup(Widget w, int *mode, if (ApplyStatus & 1 && CurrentWave == SelectedWave) XtDisownSelection(SelectedWave->w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w))); - } else + } + else FreeWave(&info); - } else { + } + else + { GetDataSetup(DataSetupWidget, CurrentWave, &change_mask); XtUnmanageChild(DataSetupWidget); } - } else { + } + else + { int r; int c; GetDataSetup(DataSetupWidget, &GlobalWave, &change_mask); for (c = 0; c < Columns; c++) for (r = 0; r < Rows[c]; r++) - if (Wave[c][r]._global.global_defaults) { + if (Wave[c][r]._global.global_defaults) + { UpdateWaveform(0, &Wave[c][r], 0, change_mask, 0); if (Wave[c][r]._global.global.event) SetupEvent(GlobalWave.event, &Wave[c][r].received, @@ -1510,7 +1646,8 @@ static void /*XtCallbackProc */ ApplyDataSetup(Widget w, int *mode, return; } -static void CopyWave(WaveInfo *in, WaveInfo *out) { +static void CopyWave(WaveInfo *in, WaveInfo *out) +{ *out = *in; out->database = XtNewString(in->database); out->shot = XtNewString(in->shot); @@ -1523,7 +1660,8 @@ static void CopyWave(WaveInfo *in, WaveInfo *out) { out->pad_label = XtNewString(in->pad_label); } -static void FreeWave(WaveInfo *info) { +static void FreeWave(WaveInfo *info) +{ if (info->database) XtFree(info->database); if (info->shot) @@ -1548,7 +1686,8 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XEvent *event, String *params __attribute__((unused)), Cardinal *num_params - __attribute__((unused))) { + __attribute__((unused))) +{ Position main_x_root; Position main_y_root; static Position min_offset; @@ -1558,19 +1697,24 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XEvent *event, XtTranslateCoords(PlotsWidget, 0, 0, &main_x_root, &main_y_root); if (!separator) separator = XtNameToWidget(TopWidget, "*pane_separator"); - if (event->type == ButtonPress) { + if (event->type == ButtonPress) + { for (i = 0; i < NumSashs; i++) if (Sash[i] == w) break; - if (i) { + if (i) + { XtVaGetValues(Sash[i - 1], XmNx, &min_offset, NULL); min_offset += 10; - } else + } + else min_offset = 10; - if (i < (NumSashs - 1) && XtIsManaged(Sash[i + 1])) { + if (i < (NumSashs - 1) && XtIsManaged(Sash[i + 1])) + { XtVaGetValues(Sash[i + 1], XmNx, &max_offset, NULL); max_offset -= 10; - } else + } + else max_offset = XtWidth(MainWidget) - 10; separator->core.widget_class->core_class.compress_motion = 1; XtManageChild(separator); @@ -1579,7 +1723,8 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XEvent *event, separator, XmNleftOffset, min(max_offset, max(min_offset, event->xbutton.x_root - main_x_root)), NULL); - if (event->type == ButtonRelease) { + if (event->type == ButtonRelease) + { unsigned short position; XtVaGetValues(separator, XmNx, &position, NULL); position = position * 1000. / XtWidth(MainWidget) + .49999; @@ -1589,13 +1734,16 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XEvent *event, } } -static XrmDatabase MdsGetFileDatabase(String file_spec) { +static XrmDatabase MdsGetFileDatabase(String file_spec) +{ FILE *file = fopen(file_spec, "r"); XrmDatabase db = 0; - if (file) { + if (file) + { char line_text[8192]; char doubled[8192]; - while (fgets(line_text, 8192, file)) { + while (fgets(line_text, 8192, file)) + { size_t i; size_t j; int put_it = 0; @@ -1604,13 +1752,16 @@ static XrmDatabase MdsGetFileDatabase(String file_spec) { if (line_text[i] == ':') break; for (j = i + 1; j < size; j++) - if (line_text[j] != 9 && line_text[j] != 10 && line_text[j] != ' ') { + if (line_text[j] != 9 && line_text[j] != 10 && line_text[j] != ' ') + { put_it = 1; break; } - if (put_it) { + if (put_it) + { j = 0; - for (i = 0; (i < size) && (j < sizeof(doubled)); i++) { + for (i = 0; (i < size) && (j < sizeof(doubled)); i++) + { if (line_text[i] == '\\') doubled[j++] = line_text[i]; doubled[j++] = line_text[i]; @@ -1624,7 +1775,8 @@ static XrmDatabase MdsGetFileDatabase(String file_spec) { return db; } -static Window CreateBusyWindow(Widget toplevel) { +static Window CreateBusyWindow(Widget toplevel) +{ unsigned long valuemask; XSetWindowAttributes attributes; /* Ignore device events while the busy cursor is displayed. */ @@ -1642,10 +1794,12 @@ static Window CreateBusyWindow(Widget toplevel) { &attributes); } -static void Busy() { +static void Busy() +{ if (BusyLevel++) return; - if (BusyWindow) { + if (BusyWindow) + { XEvent event; XMapRaised(XtDisplay(MainWidget), BusyWindow); while (XCheckMaskEvent(XtDisplay(MainWidget), @@ -1658,7 +1812,8 @@ static void Busy() { } } -static void Unbusy() { +static void Unbusy() +{ if (--BusyLevel) return; if (BusyWindow) @@ -1669,7 +1824,8 @@ static void /*XtCallbackProc */ PrintAll(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ #ifndef _NO_DPS char filename[256]; @@ -1681,11 +1837,13 @@ static void /*XtCallbackProc */ PrintAll(Widget w __attribute__((unused)), if (ScopePrintToFile) printfid = fopen(ScopePrintFile, "w"); /*,"rop=RAH,WBH","mbc=8","mbf=2","deq=32"); */ - else { + else + { sprintf(filename, "/tmp/dwscope_tmp_%0x_%0x", getpid(), ScopeTempFileIdx++); printfid = fopen(filename, "w"); } - if (printfid) { + if (printfid) + { XmString filenames[1]; int orientation = ScopePrintPortrait ? 1 : 2; filenames[0] = XmStringCreateSimple(ScopePrintFile); @@ -1697,22 +1855,26 @@ static void /*XtCallbackProc */ PrintAll(Widget w __attribute__((unused)), Busy(); for (c = 0; c < Columns; c++) for (r = 0; r < Rows[c]; r++) - if (ScopePrintWindowTitle) { + if (ScopePrintWindowTitle) + { String title; String title_error; Boolean title_status = EvaluateText(ScopeTitle, " ", &title, &title_error); - if (!title_status) { + if (!title_status) + { XtFree(title_error); XmdsWaveformPrint(Wave[c][r].w, printfid, width, height, orientation, Wave[c][r].print_title_evaluated, 0, 0); - } else + } + else XmdsWaveformPrint(Wave[c][r].w, printfid, width, height, orientation, Wave[c][r].print_title_evaluated, title, 0); XtFree(title); - } else + } + else XmdsWaveformPrint(Wave[c][r].w, printfid, width, height, orientation, Wave[c][r].print_title_evaluated, 0, 0); fclose(printfid); @@ -1724,7 +1886,9 @@ static void /*XtCallbackProc */ PrintAll(Widget w __attribute__((unused)), #endif /* DXmNorientation */ XmStringFree(filenames[0]); Unbusy(); - } else { + } + else + { static String prefix = "Error creating printfile, "; String error = XtMalloc(strlen(prefix) + strlen(ScopePrintFile) + 1); sprintf(error, "%s%s", prefix, ScopePrintFile); @@ -1739,22 +1903,26 @@ static void /*XtCallbackProc */ Print(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), XmAnyCallbackStruct *callback_data - __attribute__((unused))) { + __attribute__((unused))) +{ #ifndef _NO_DPS int count; XtVaGetValues(PendingWave->w, XmdsNcount, &count, NULL); - if (count) { + if (count) + { char filename[256]; FILE *printfid; if (ScopePrintToFile) printfid = fopen(ScopePrintFile, "w"); /*,"rop=RAH,WBH","mbc=8","mbf=2","deq=32"); */ - else { + else + { sprintf(filename, "/tmp/dwscope_tmp_%0x_%0x", getpid(), ScopeTempFileIdx++); printfid = fopen(filename, "w"); } - if (printfid) { + if (printfid) + { XmString filenames[1]; int orientation = ScopePrintPortrait ? 1 : 2; filenames[0] = XmStringCreateSimple(ScopePrintFile); @@ -1762,20 +1930,24 @@ static void /*XtCallbackProc */ Print(Widget w __attribute__((unused)), XtVaGetValues(CustomizePrintWidget, DXmNorientation, &orientation, NULL); #endif Busy(); - if (ScopePrintWindowTitle) { + if (ScopePrintWindowTitle) + { String title; String title_error; Boolean title_status = EvaluateText(ScopeTitle, " ", &title, &title_error); - if (!title_status) { + if (!title_status) + { XtFree(title_error); XmdsWaveformPrint(PendingWave->w, printfid, 0, 0, orientation, PendingWave->print_title_evaluated, 0, 0); - } else + } + else XmdsWaveformPrint(PendingWave->w, printfid, 0, 0, orientation, PendingWave->print_title_evaluated, title, 0); XtFree(title); - } else + } + else XmdsWaveformPrint(PendingWave->w, printfid, 0, 0, orientation, PendingWave->print_title_evaluated, 0, 0); fclose(printfid); @@ -1787,14 +1959,17 @@ static void /*XtCallbackProc */ Print(Widget w __attribute__((unused)), #endif XmStringFree(filenames[0]); Unbusy(); - } else { + } + else + { static String prefix = "Error creating printfile, "; String error = XtMalloc(strlen(prefix) + strlen(ScopePrintFile) + 1); sprintf(error, "%s%s", prefix, ScopePrintFile); PopupComplaint(TopWidget, error); XtFree(error); } - } else + } + else PopupComplaint(TopWidget, "No data to print"); #endif /* _NO_DPS */ return; @@ -1802,13 +1977,15 @@ static void /*XtCallbackProc */ Print(Widget w __attribute__((unused)), static void /*XtCallbackProc */ Clear(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ if (SelectedWave && SelectedWave == GetPending(w)) XtDisownSelection(SelectedWave->w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w))); } -static WaveInfo *GetPending(Widget w) { +static WaveInfo *GetPending(Widget w) +{ int r; int c; for (c = 0; c < MaxCols; c++) @@ -1823,14 +2000,16 @@ static WaveInfo *GetPending(Widget w) { static void /*XtCallbackProc */ Cut(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_struct) { + XmAnyCallbackStruct *callback_struct) +{ WaveInfo *pending = GetPending(w); if (pending == SelectedWave) XtDisownSelection(SelectedWave->w, XA_PRIMARY, callback_struct->event->xbutton.time); else if (XtOwnSelection( pending->w, XA_PRIMARY, callback_struct->event->xbutton.time, - (XtConvertSelectionProc)ConvertSelection, LoseSelection, NULL)) { + (XtConvertSelectionProc)ConvertSelection, LoseSelection, NULL)) + { SelectedWave = pending; XmdsWaveformReverse(SelectedWave->w, 1); } @@ -1839,7 +2018,8 @@ static void /*XtCallbackProc */ Cut(Widget w, static Boolean /*XtConvertSelectionProc */ ConvertSelection(Widget w, Atom *selection __attribute__((unused)), Atom *target, Atom *type, XtPointer *value, - unsigned long *length, int *format) { + unsigned long *length, int *format) +{ int r = 0; int c = 0; char prefix[36]; @@ -1855,7 +2035,8 @@ ConvertSelection(Widget w, Atom *selection __attribute__((unused)), } static void /*XtLoseSelectionProc */ LoseSelection(Widget w, Atom *selection - __attribute__((unused))) { + __attribute__((unused))) +{ XmdsWaveformReverse(w, 0); if (SelectedWave && (SelectedWave->w == w)) SelectedWave = 0; @@ -1865,7 +2046,8 @@ static void /*XtActionProc */ Paste(Widget w, XEvent *event __attribute__((unused)), String *params __attribute__((unused)), Cardinal *num_params - __attribute__((unused))) { + __attribute__((unused))) +{ WaveInfo *pending = GetPending(w); if (pending) XtGetSelectionValue(pending->w, XA_PRIMARY, XA_TARGETS, @@ -1877,12 +2059,14 @@ static void /*XtSelectionCallbackProc */ PasteTypesComplete(Widget w, XtPointer cdata, Atom *selection __attribute__((unused)), Atom *type __attribute__((unused)), XtPointer value, - unsigned long *length, int *format __attribute__((unused))) { + unsigned long *length, int *format __attribute__((unused))) +{ unsigned long i; Atom req_type = XA_STRING; Atom *values = (Atom *)value; for (i = 0; i < *length; i++) - if (values[i] == XA_DWSCOPE_PANEL) { + if (values[i] == XA_DWSCOPE_PANEL) + { req_type = XA_DWSCOPE_PANEL; break; } @@ -1896,8 +2080,10 @@ PasteTypesComplete(Widget w, XtPointer cdata, static void /*XtSelectionCallbackProc */ PasteComplete(Widget w, WaveInfo *info, Atom *selection __attribute__((unused)), Atom *type, XtPointer value, unsigned long *length, - int *format __attribute__((unused))) { - if (ConvertSelectionToWave(w, *type, *length, value, info)) { + int *format __attribute__((unused))) +{ + if (ConvertSelectionToWave(w, *type, *length, value, info)) + { UpdateWaveform(0, info, 0, -1, -1); SetupEvent(info->_global.global.event ? GlobalWave.event : info->event, &info->received, &info->eventid); @@ -1908,34 +2094,39 @@ PasteComplete(Widget w, WaveInfo *info, Atom *selection __attribute__((unused)), static void /*XtCallbackProc */ RegisterPane(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ Pane[NumPanes++] = w; NumWaves = 0; } static void /*XtCallbackProc */ RegisterWave(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ Wave[NumPanes - 1][NumWaves].w = w; ResetWave(&Wave[NumPanes - 1][NumWaves++]); } static void /*XtCallbackProc */ RegisterSash(Widget w, XtPointer client_data __attribute__((unused)), - XmAnyCallbackStruct *callback_data __attribute__((unused))) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ Sash[NumSashs++] = w; } -static String GlobalShot() { +static String GlobalShot() +{ String override_shot = XmTextFieldGetString(XtNameToWidget(TopWidget, "*override_shot")); return strlen(override_shot) ? override_shot : GlobalWave.shot; } static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, - int global_change_mask, int change_mask) { + int global_change_mask, int change_mask) +{ -#define changed(field) \ +#define changed(field) \ ((info->_global.global.field ? global_change_mask : change_mask) & M_##field) Boolean new_grid = changed(x_grid_lines) || changed(y_grid_lines) || @@ -1944,7 +2135,8 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, info->received = 0; Busy(); if (changed(shot) || changed(database) || changed(default_node) || - changed(x) || changed(y) || changed(title) || changed(print_title)) { + changed(x) || changed(y) || changed(title) || changed(print_title)) + { XmdsWaveformValStruct x_wave; XmdsWaveformValStruct y_wave; String title_evaluated = 0; @@ -1978,12 +2170,14 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, found: if (!EvaluateData(brief, r, c, idx, event ? &update : (Boolean *)0, database, shot, default_node, x, y, &x_wave, &y_wave, - &error)) { + &error)) + { String terror = 0; if (!complain && EvaluateText(title, "Error evaluating title", &title_evaluated, &terror) && - title_evaluated) { + title_evaluated) + { String save = error; int len = strlen(title_evaluated) + 2 + strlen(save); error = XtMalloc(len + 1); @@ -1991,7 +2185,8 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, strcat(error, "\n"); strcat(error, save); error[len] = 0; - } else if (terror) + } + else if (terror) XtFree(terror); if (title_evaluated) XtFree(title_evaluated); @@ -2001,23 +2196,27 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, Unbusy(); return 0; } - if (event & !update) { + if (event & !update) + { Unbusy(); return 1; } if (!EvaluateText(title, "Error evaluating title", &title_evaluated, - &error)) { + &error)) + { if (complain) PopupComplaint(DataSetupWidget, error); if (error) XtFree(error); } - if (info->print_title_evaluated) { + if (info->print_title_evaluated) + { XtFree(info->print_title_evaluated); info->print_title_evaluated = 0; } if (!EvaluateText(print_title, "Error evaluating print title", - &info->print_title_evaluated, &error)) { + &info->print_title_evaluated, &error)) + { if (complain) PopupComplaint(DataSetupWidget, error); if (error) @@ -2029,7 +2228,9 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, XmdsWaveformUpdate(info->w, &x_wave, &y_wave, title_evaluated, xmin, xmax, ymin, ymax, new_grid); XtFree(title_evaluated); - } else if (changed(xmin) || changed(ymin) || changed(xmax) || changed(ymax)) { + } + else if (changed(xmin) || changed(ymin) || changed(xmax) || changed(ymax)) + { float *xmin; float *xmax; float *ymin; @@ -2038,7 +2239,8 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, XtVaSetValues(info->w, XmdsNxMin, xmin, XmdsNxMax, xmax, XmdsNyMin, ymin, XmdsNyMax, ymax, NULL); } - if (new_grid) { + if (new_grid) + { int x_grid_lines = info->_global.global.x_grid_lines ? GlobalWave.x_grid_lines : info->x_grid_lines; @@ -2064,12 +2266,15 @@ static int UpdateWaveform(Boolean complain, WaveInfo *info, Boolean event, return 1; } -static void Complain(WaveInfo *info, char mode, String error) { - switch (mode) { +static void Complain(WaveInfo *info, char mode, String error) +{ + switch (mode) + { case 0: XtVaSetValues(info->w, XmdsNcount, 0, XmdsNtitle, error, NULL); break; - case 1: { + case 1: + { Widget w = XtNameToWidget(DataSetupWidget, "*data_setup_error"); XmString error_string = XmStringCreateLtoR(error, XmSTRING_DEFAULT_CHARSET); XtVaSetValues(w, XmNmessageString, error_string, NULL); @@ -2084,7 +2289,8 @@ static void Complain(WaveInfo *info, char mode, String error) { } } -static void ClearWaveform(WaveInfo *info) { +static void ClearWaveform(WaveInfo *info) +{ ResetWave(info); SetupEvent("", &info->received, &info->eventid); if (info->w) @@ -2095,7 +2301,8 @@ static void ClearWaveform(WaveInfo *info) { 0, XmdsNtitle, "", NULL); } -static void RestoreDatabase(String dbname, Widget w) { +static void RestoreDatabase(String dbname, Widget w) +{ int c; int r; int x; @@ -2153,7 +2360,8 @@ static void RestoreDatabase(String dbname, Widget w) { &ScopeTitleEventReceived, &ScopeTitleEventId); SetupEvent(ScopePrintEvent, &ScopePrintEventReceived, &ScopePrintEventId); XtVaSetValues(TopWidget, XtNx, x, XtNy, y, NULL); - if (XtWidth(MainWidget) != width || XtHeight(MainWidget) != height) { + if (XtWidth(MainWidget) != width || XtHeight(MainWidget) != height) + { PreventResize = TRUE; /* XtVaSetValues(MainWidget, XtNwidth, width, XtNheight, height, NULL); */ XtVaSetValues(TopWidget, XtNwidth, width, XtNheight, height, NULL); @@ -2163,7 +2371,8 @@ static void RestoreDatabase(String dbname, Widget w) { Columns = min(max(strtol(GetResource(scopedb, "Scope.columns", "1"), NULL, 0), 1), MaxCols); - for (c = 0; c < MaxCols; c++) { + for (c = 0; c < MaxCols; c++) + { char resource[50]; sprintf(resource, "Scope.rows_in_column_%d", c + 1); resource[strlen(resource) - 1] = '1' + c; @@ -2174,10 +2383,12 @@ static void RestoreDatabase(String dbname, Widget w) { : 0; if (Rows[c]) XtVaSetValues(Pane[c], XtNheight, height, NULL); - for (r = 0; r < MaxRows; r++) { + for (r = 0; r < MaxRows; r++) + { WaveInfo *info = &Wave[c][r]; Dimension pheight; - if (r < Rows[c]) { + if (r < Rows[c]) + { float zoom[4]; int old_update; GetWaveFromDb(scopedb, "Scope.plot", r, c, info); @@ -2196,11 +2407,13 @@ static void RestoreDatabase(String dbname, Widget w) { XmdsNyMin, &zoom[2], XmdsNyMax, &zoom[3], NULL); SetupEvent(info->_global.global.event ? GlobalWave.event : info->event, &info->received, &info->eventid); - } else + } + else ClearWaveform(info); } } - for (c = 0; c < Columns - 1; c++) { + for (c = 0; c < Columns - 1; c++) + { static char resource[] = "Scope.vpane_n"; int position; resource[12] = '1' + c; @@ -2210,7 +2423,8 @@ static void RestoreDatabase(String dbname, Widget w) { XtVaSetValues(Sash[c], XmNleftPosition, position, NULL); } ManageWaveforms(); - if (!XtIsRealized(TopWidget)) { + if (!XtIsRealized(TopWidget)) + { XtRealizeWidget(TopWidget); RaiseWindows(); /* PreventResize = FALSE; */ @@ -2220,7 +2434,8 @@ static void RestoreDatabase(String dbname, Widget w) { XrmDestroyDatabase(scopedb); } -static void WriteDatabase(String dbname, Boolean zoom) { +static void WriteDatabase(String dbname, Boolean zoom) +{ int r; int c; Position x; @@ -2240,7 +2455,8 @@ static void WriteDatabase(String dbname, Boolean zoom) { filename[i] = 0; file = fopen(filename, "w"); XtFree(filename); - if (file) { + if (file) + { XtVaGetValues(TopWidget, XtNx, &x, XtNy, &y, NULL); XtVaGetValues(MainWidget, XtNwidth, &width, XtNheight, &height, NULL); fprintf(file, "Scope.geometry: %dx%d+%d+%d\n", width, height, x, y); @@ -2265,39 +2481,46 @@ static void WriteDatabase(String dbname, Boolean zoom) { fprintf(file, "Scope.font: %s\n", font); XFree(font); fprintf(file, "Scope.columns: %d\n", Columns); - while ((text = WaveToText("Scope.global_1_1", &GlobalWave, 0, &ctx))) { + while ((text = WaveToText("Scope.global_1_1", &GlobalWave, 0, &ctx))) + { fprintf(file, "%s", text); XtFree(text); } - for (c = 0; c < Columns; c++) { + for (c = 0; c < Columns; c++) + { fprintf(file, "Scope.rows_in_column_%d: %d\n", c + 1, Rows[c]); - for (r = 0; r < Rows[c]; r++) { + for (r = 0; r < Rows[c]; r++) + { char prefix[36]; int ctx = zoom ? -4 : 0; int height; XtVaGetValues(Wave[c][r].w, XtNheight, &height, NULL); fprintf(file, "\n"); sprintf(prefix, "Scope.plot_%d_%d", r + 1, c + 1); - while ((text = WaveToText(prefix, &Wave[c][r], height, &ctx))) { + while ((text = WaveToText(prefix, &Wave[c][r], height, &ctx))) + { fprintf(file, "%s", text); XtFree(text); } } } - for (c = 0; c < Columns - 1; c++) { + for (c = 0; c < Columns - 1; c++) + { int position; XtVaGetValues(Sash[c], XmNleftPosition, &position, NULL); fprintf(file, "Scope.vpane_%d: %d\n", c + 1, position); } fclose(file); - } else + } + else PopupComplaint(MainWidget, "Error writing setup file"); } static void /*XtActionProc */ Resize(Widget w, XEvent *event, String *params __attribute__((unused)), Cardinal *num_params - __attribute__((unused))) { + __attribute__((unused))) +{ int c; int r; double orig_height = XtHeight(Pane[0]); @@ -2307,7 +2530,8 @@ static void /*XtActionProc */ Resize(Widget w, XEvent *event, /* flush the event que for resize events */ while (XCheckTypedWindowEvent(XtDisplay(w), XtWindow(w), event->type, &ev)) event = &ev; - if (!PreventResize) { + if (!PreventResize) + { for (c = 0; c < Columns; c++) for (r = 0; r < Rows[c]; r++) Wave[c][r].height = XtHeight(Wave[c][r].w); @@ -2317,11 +2541,13 @@ static void /*XtActionProc */ Resize(Widget w, XEvent *event, event->xresizerequest.height, NULL); { new_height = XtHeight(Pane[0]); - if (PreventResize) { + if (PreventResize) + { orig_height = new_height; PreventResize = FALSE; } - for (c = 0; c < Columns; c++) { + for (c = 0; c < Columns; c++) + { XtUnmanageChild(Pane[c]); for (r = 0; r < Rows[c]; r++) XtVaSetValues(Wave[c][r].w, XtNheight, @@ -2338,15 +2564,20 @@ static void /*XtActionProc */ Resize(Widget w, XEvent *event, static void /*XtActionProc */ EqualPanes(Widget w, XEvent *event __attribute__((unused)), String *string, - Cardinal *num_strings) { + Cardinal *num_strings) +{ int c; int r; - if ((*num_strings == 1) && (string[0][0] == 'V')) { - for (c = 0; c < Columns - 1; c++) { + if ((*num_strings == 1) && (string[0][0] == 'V')) + { + for (c = 0; c < Columns - 1; c++) + { int position = (c + 1) * 1000 / Columns; XtVaSetValues(Sash[c], XmNleftPosition, position, NULL); } - } else if ((*num_strings == 1) && (string[0][0] == 'H')) { + } + else if ((*num_strings == 1) && (string[0][0] == 'H')) + { Widget p = XtParent(w); int height; for (c = 0; c < Columns; c++) @@ -2362,10 +2593,12 @@ static void /*XtActionProc */ EqualPanes(Widget w, } static void GetNewLimits(WaveInfo *info, float **xmin, float **xmax, - float **ymin, float **ymax) { + float **ymin, float **ymax) +{ int lockScales = LockScalesWidget ? XmToggleButtonGetState(LockScalesWidget) : 0; - if (info->update && !lockScales) { + if (info->update && !lockScales) + { static float xminval; static float xmaxval; static float yminval; @@ -2390,7 +2623,9 @@ static void GetNewLimits(WaveInfo *info, float **xmin, float **xmax, if (strlen(ymax_s)) if (sscanf(ymax_s, "%f", &ymaxval)) *ymax = &ymaxval; - } else { + } + else + { *xmin = (float *)-1; *xmax = (float *)-1; *ymin = (float *)-1; @@ -2398,7 +2633,8 @@ static void GetNewLimits(WaveInfo *info, float **xmin, float **xmax, } } -static void SetWindowTitles() { +static void SetWindowTitles() +{ String title; String title_error; XmdsWaveformValStruct x_wave; diff --git a/dwscope/dwscope.h b/dwscope/dwscope.h index 6748c738c8..9393420d07 100644 --- a/dwscope/dwscope.h +++ b/dwscope/dwscope.h @@ -4,7 +4,8 @@ /* *2 25-NOV-1991 10:32:07 TWF "add show mode" */ /* *1 12-NOV-1991 14:55:30 TWF "Data structures for DWSCOPE" */ /* VAX/DEC CMS REPLACEMENT HISTORY, Element DWSCOPE.H */ -typedef struct _WaveInfo { +typedef struct _WaveInfo +{ Boolean update; Boolean x_grid_labels; Boolean y_grid_labels; @@ -27,7 +28,8 @@ typedef struct _WaveInfo { String pad_label; union { int global_defaults; - struct { + struct + { unsigned update : 1; #define B_update 0 #define M_update (1 << B_update) @@ -97,12 +99,13 @@ typedef struct _WaveInfo { String print_title_evaluated; } WaveInfo; -#define DefaultDefaults \ - (M_update | M_x_grid_labels | M_y_grid_labels | M_show_mode | M_step_plot | \ - M_x_grid_lines | M_y_grid_lines | M_database | M_shot | M_default_node | \ +#define DefaultDefaults \ + (M_update | M_x_grid_labels | M_y_grid_labels | M_show_mode | M_step_plot | \ + M_x_grid_lines | M_y_grid_lines | M_database | M_shot | M_default_node | \ M_xmin | M_xmax | M_ymin | M_ymax) -typedef struct _CutHeader { +typedef struct _CutHeader +{ Boolean update; Boolean x_grid_labels; Boolean y_grid_labels; diff --git a/dwscope/dwscopesubs.c b/dwscope/dwscopesubs.c index 965ec582e8..10d349055f 100644 --- a/dwscope/dwscopesubs.c +++ b/dwscope/dwscopesubs.c @@ -142,14 +142,16 @@ static String FixupBARS(String in); #define XA_X_AXIS XInternAtom(XtDisplay(w), "DWSCOPE_X_AXIS", 0) #define XA_Y_AXIS XInternAtom(XtDisplay(w), "DWSCOPE_Y_AXIS", 0) -static int FlipBitsIfNecessary(int in) { +static int FlipBitsIfNecessary(int in) +{ static union { int i; unsigned bit : 1; } test = {1}; if (test.bit) return in; - else { + else + { int out = 0; int i; for (i = 0; i < 32; i++) @@ -159,9 +161,11 @@ static int FlipBitsIfNecessary(int in) { } Boolean ConvertSelectionToWave(Widget w, Atom type, unsigned long length, - CutHeader *header, WaveInfo *wave) { + CutHeader *header, WaveInfo *wave) +{ int status = 0; - if (type == XA_DWSCOPE_PANEL) { + if (type == XA_DWSCOPE_PANEL) + { String text = (String)(header + 1); if ((length >= sizeof(CutHeader)) && (length == @@ -169,7 +173,8 @@ Boolean ConvertSelectionToWave(Widget w, Atom type, unsigned long length, header->default_node_length + header->x_length + header->y_length + header->xmin_length + header->xmax_length + header->ymin_length + header->ymax_length + header->title_length + header->event_length + - header->print_title_length + header->pad_label_length))) { + header->print_title_length + header->pad_label_length))) + { wave->update = header->update; wave->x_grid_labels = header->x_grid_labels; wave->y_grid_labels = header->y_grid_labels; @@ -197,11 +202,14 @@ Boolean ConvertSelectionToWave(Widget w, Atom type, unsigned long length, text); } status = 1; - } else if (type == XA_STRING) { + } + else if (type == XA_STRING) + { String text = (String)header; text = ReplaceCountedString(&wave->y, strlen(text), text); wave->_global.global.y = 0; - if (strlen(wave->pad_label) == 0) { + if (strlen(wave->pad_label) == 0) + { int i; for (i = strlen(wave->y) - 1; i; i--) if (wave->y[i] == '.' || wave->y[i] == ':') @@ -217,7 +225,8 @@ Boolean ConvertSelectionToWave(Widget w, Atom type, unsigned long length, return status; } -static String ReplaceCountedString(String *old, short length, String new) { +static String ReplaceCountedString(String *old, short length, String new) +{ if (*old) XtFree(*old); *old = strncpy(XtMalloc(length + 1), new, length); @@ -225,49 +234,58 @@ static String ReplaceCountedString(String *old, short length, String new) { return new + length; } -String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { +String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) +{ String answer = 0; int prefix_length = strlen(prefix); Boolean done = 0; float *fptr; - while (answer == 0 && !done) { - switch ((*ctx)++) { + while (answer == 0 && !done) + { + switch ((*ctx)++) + { case -4: XtVaGetValues(wave->w, XmdsNxMin, &fptr, NULL); - if (fptr != NULL) { + if (fptr != NULL) + { answer = XtMalloc(prefix_length + sizeof(".xmin_zoom: \n") + 12); sprintf(answer, "%s.%s: %g\n", prefix, "xmin_zoom", *fptr); } break; case -3: XtVaGetValues(wave->w, XmdsNxMax, &fptr, NULL); - if (fptr != NULL) { + if (fptr != NULL) + { answer = XtMalloc(prefix_length + sizeof(".xmax_zoom: \n") + 12); sprintf(answer, "%s.%s: %g\n", prefix, "xmax_zoom", *fptr); } break; case -2: XtVaGetValues(wave->w, XmdsNyMin, &fptr, NULL); - if (fptr != NULL) { + if (fptr != NULL) + { answer = XtMalloc(prefix_length + sizeof(".ymin_zoom: \n") + 12); sprintf(answer, "%s.%s: %g\n", prefix, "ymin_zoom", *fptr); } break; case -1: XtVaGetValues(wave->w, XmdsNyMax, &fptr, NULL); - if (fptr != NULL) { + if (fptr != NULL) + { answer = XtMalloc(prefix_length + sizeof(".ymax_zoom: \n") + 12); sprintf(answer, "%s.%s: %g\n", prefix, "ymax_zoom", *fptr); } break; case 0: - if (height) { + if (height) + { answer = XtMalloc(prefix_length + sizeof(".height: \n") + 16); sprintf(answer, "%s.%s: %d\n", prefix, "height", height); } MDS_ATTR_FALLTHROUGH case 1: - if (!wave->update) { + if (!wave->update) + { answer = XtMalloc(prefix_length + sizeof(".update: 0\n") + 1); strcpy(answer, prefix); strcat(answer, ".update: 0\n"); @@ -289,35 +307,40 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { answer = wave->step_plot ? Concat(prefix, ".step_plot: 1\n") : 0; break; case 6: - if (wave->x_grid_lines != 4) { + if (wave->x_grid_lines != 4) + { answer = XtMalloc(prefix_length + sizeof(".x.grid_lines: \n") + 16); sprintf(answer, "%s.%s: %d\n", prefix, "x.grid_lines", wave->x_grid_lines); } break; case 7: - if (wave->y_grid_lines != 4) { + if (wave->y_grid_lines != 4) + { answer = XtMalloc(prefix_length + sizeof(".y.grid_lines: \n") + 16); sprintf(answer, "%s.%s: %d\n", prefix, "y.grid_lines", wave->y_grid_lines); } break; case 8: - if (strlen(wave->database)) { + if (strlen(wave->database)) + { answer = XtMalloc(prefix_length + sizeof(".experiment: \n") + strlen(wave->database) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "experiment", wave->database); } break; case 9: - if (strlen(wave->shot)) { + if (strlen(wave->shot)) + { answer = XtMalloc(prefix_length + sizeof(".shot: \n") + strlen(wave->shot) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "shot", wave->shot); } break; case 10: - if (strlen(wave->default_node)) { + if (strlen(wave->default_node)) + { answer = XtMalloc(prefix_length + sizeof(".default_node: \n") + strlen(wave->default_node) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "default_node", @@ -325,7 +348,8 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { } break; case 11: - if (strlen(wave->x)) { + if (strlen(wave->x)) + { String out = FixupLFS(wave->x); answer = XtMalloc(prefix_length + sizeof(".x: \n") + strlen(out) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "x", out); @@ -333,7 +357,8 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { } break; case 12: - if (strlen(wave->y)) { + if (strlen(wave->y)) + { String out = FixupLFS(wave->y); answer = XtMalloc(prefix_length + sizeof(".y: \n") + strlen(out) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "y", out); @@ -341,49 +366,56 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { } break; case 13: - if (strlen(wave->xmin)) { + if (strlen(wave->xmin)) + { answer = XtMalloc(prefix_length + sizeof(".xmin: \n") + strlen(wave->xmin) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "xmin", wave->xmin); } break; case 14: - if (strlen(wave->xmax)) { + if (strlen(wave->xmax)) + { answer = XtMalloc(prefix_length + sizeof(".xmax: \n") + strlen(wave->xmax) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "xmax", wave->xmax); } break; case 15: - if (strlen(wave->ymin)) { + if (strlen(wave->ymin)) + { answer = XtMalloc(prefix_length + sizeof(".ymin: \n") + strlen(wave->ymin) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "ymin", wave->ymin); } break; case 16: - if (strlen(wave->ymax)) { + if (strlen(wave->ymax)) + { answer = XtMalloc(prefix_length + sizeof(".ymax: \n") + strlen(wave->ymax) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "ymax", wave->ymax); } break; case 17: - if (strlen(wave->event)) { + if (strlen(wave->event)) + { answer = XtMalloc(prefix_length + sizeof(".event: \n") + strlen(wave->event) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "event", wave->event); } break; case 18: - if (strlen(wave->title)) { + if (strlen(wave->title)) + { answer = XtMalloc(prefix_length + sizeof(".title: \n") + strlen(wave->title) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "title", wave->title); } break; case 19: - if (strlen(wave->print_title)) { + if (strlen(wave->print_title)) + { answer = XtMalloc(prefix_length + sizeof(".print_title: \n") + strlen(wave->print_title) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "print_title", @@ -391,14 +423,16 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { } break; case 20: - if (strlen(wave->pad_label)) { + if (strlen(wave->pad_label)) + { answer = XtMalloc(prefix_length + sizeof(".label: \n") + strlen(wave->pad_label) + 1); sprintf(answer, "%s.%s: %s\n", prefix, "label", wave->pad_label); } break; case 21: - if (wave->_global.global_defaults != (strlen(wave->y) ? 0 : -1)) { + if (wave->_global.global_defaults != (strlen(wave->y) ? 0 : -1)) + { answer = XtMalloc(prefix_length + sizeof(".global_defaults: \n") + 16); sprintf(answer, "%s.%s: %d\n", prefix, "global_defaults", FlipBitsIfNecessary(wave->_global.global_defaults)); @@ -416,9 +450,11 @@ String WaveToText(String prefix, WaveInfo *wave, Dimension height, int *ctx) { Boolean ConvertWaveToSelection(Widget w, String prefix, WaveInfo *wave, Atom target, Atom *type, String *value, - unsigned long *length, int *format) { + unsigned long *length, int *format) +{ int status = 0; - if (target == XA_DWSCOPE_PANEL) { + if (target == XA_DWSCOPE_PANEL) + { CutHeader *header; String text; *type = target; @@ -478,27 +514,34 @@ Boolean ConvertWaveToSelection(Widget w, String prefix, WaveInfo *wave, memcpy(text, wave->pad_label, strlen(wave->pad_label)); text += strlen(wave->pad_label); status = 1; - } else if (target == XA_STRING) { + } + else if (target == XA_STRING) + { int ctx = 0; String text; String all_text = WaveToText(prefix, wave, 0, &ctx); - while (all_text && (text = WaveToText(prefix, wave, 0, &ctx))) { + while (all_text && (text = WaveToText(prefix, wave, 0, &ctx))) + { all_text = XtRealloc(all_text, strlen(all_text) + strlen(text) + 1); strcat(all_text, text); XtFree(text); } - if (all_text && strlen(all_text)) { + if (all_text && strlen(all_text)) + { *type = target; *value = (String)all_text; *length = strlen(all_text); *format = 8; status = 1; } - } else if (target == XA_X_AXIS) { + } + else if (target == XA_X_AXIS) + { XmdsWaveformValStruct *x; int count = 0; XtVaGetValues(w, XmdsNxValStruct, &x, XmdsNcount, &count, NULL); - if (x && count) { + if (x && count) + { *format = 8; *type = target; *value = (String)memcpy(XtMalloc(count * sizeof(float)), x->addr, @@ -506,11 +549,14 @@ Boolean ConvertWaveToSelection(Widget w, String prefix, WaveInfo *wave, *length = count * 32 / (*format); status = 1; } - } else if (target == XA_Y_AXIS) { + } + else if (target == XA_Y_AXIS) + { XmdsWaveformValStruct *y; int count = 0; XtVaGetValues(w, XmdsNyValStruct, &y, XmdsNcount, &count, NULL); - if (y && count) { + if (y && count) + { *format = 8; *type = target; *value = (String)memcpy(XtMalloc(count * sizeof(float)), y->addr, @@ -518,7 +564,9 @@ Boolean ConvertWaveToSelection(Widget w, String prefix, WaveInfo *wave, *length = count * 32 / (*format); status = 1; } - } else if (target == XA_TARGETS) { + } + else if (target == XA_TARGETS) + { *type = target; *value = (String)XtMalloc(sizeof(Atom) * 4); ((Atom *)*value)[0] = XA_STRING; @@ -532,13 +580,16 @@ Boolean ConvertWaveToSelection(Widget w, String prefix, WaveInfo *wave, return status; } -XrmDatabase GetFileDatabase(String file_spec) { +XrmDatabase GetFileDatabase(String file_spec) +{ FILE *file = fopen(file_spec, "r"); XrmDatabase db = 0; - if (file) { + if (file) + { char line_text[32768]; char doubled[32768]; - while (fgets(line_text, 32768, file)) { + while (fgets(line_text, 32768, file)) + { int i; int j; int put_it = 0; @@ -547,13 +598,16 @@ XrmDatabase GetFileDatabase(String file_spec) { if (line_text[i] == ':') break; for (j = i + 1; j < size; j++) - if (line_text[j] != 9 && line_text[j] != 10 && line_text[j] != ' ') { + if (line_text[j] != 9 && line_text[j] != 10 && line_text[j] != ' ') + { put_it = 1; break; } - if (put_it) { + if (put_it) + { j = 0; - for (i = 0; i < size; i++) { + for (i = 0; i < size; i++) + { if (line_text[i] == '\\') doubled[j++] = line_text[i]; doubled[j++] = line_text[i]; @@ -567,7 +621,8 @@ XrmDatabase GetFileDatabase(String file_spec) { return db; } -void LoadDataSetup(Widget w, String title, WaveInfo *info) { +void LoadDataSetup(Widget w, String title, WaveInfo *info) +{ Widget top; Widget tw; XmString title_s = XmStringCreateSimple(title); @@ -601,7 +656,8 @@ void LoadDataSetup(Widget w, String title, WaveInfo *info) { LoadGlobalDefaults(XtNameToWidget(top, "*defaults_setup_db"), info); } -static void LoadGlobalDefaults(Widget w, WaveInfo *info) { +static void LoadGlobalDefaults(Widget w, WaveInfo *info) +{ XmToggleButtonGadgetSetState(XtNameToWidget(w, "def_exp_text"), info->_global.global.database, 1); XmToggleButtonGadgetSetState(XtNameToWidget(w, "def_shot_text"), @@ -644,7 +700,8 @@ static void LoadGlobalDefaults(Widget w, WaveInfo *info) { info->_global.global.y_grid_lines, 1); } -String GetResource(XrmDatabase db, String resource, String default_answer) { +String GetResource(XrmDatabase db, String resource, String default_answer) +{ XrmValue value = {0, (String)0}; XrmString type; if (XrmGetResource(db, resource, 0, &type, &value) && value.size && @@ -656,7 +713,8 @@ String GetResource(XrmDatabase db, String resource, String default_answer) { static String GetPlotResource(XrmDatabase db, String prefix, int row, int column, String plot_resource, - String default_answer) { + String default_answer) +{ static char resource[256]; resource[0] = 0; sprintf(resource, "%s_%d_%d.%s", prefix, row + 1, column + 1, plot_resource); @@ -664,7 +722,8 @@ static String GetPlotResource(XrmDatabase db, String prefix, int row, } void GetWaveFromDb(XrmDatabase db, String prefix, int row, int col, - WaveInfo *info) { + WaveInfo *info) +{ ReplaceString(&info->database, GetPlotResource(db, prefix, row, col, "experiment", ""), 0); ReplaceString(&info->shot, GetPlotResource(db, prefix, row, col, "shot", ""), @@ -712,7 +771,8 @@ void GetWaveFromDb(XrmDatabase db, String prefix, int row, int col, } Boolean GetWaveZoomFromDb(XrmDatabase db, String prefix, int row, int col, - float *zoom) { + float *zoom) +{ String limit; limit = GetPlotResource(db, prefix, row, col, "xmin_zoom", ""); if (limit && strlen(limit) > 0) @@ -737,7 +797,8 @@ Boolean GetWaveZoomFromDb(XrmDatabase db, String prefix, int row, int col, return TRUE; } -void GetDataSetup(Widget w, WaveInfo *info, int *change_mask) { +void GetDataSetup(Widget w, WaveInfo *info, int *change_mask) +{ int value; int mask = 0; int global_defaults = info->_global.global_defaults; @@ -746,12 +807,12 @@ void GetDataSetup(Widget w, WaveInfo *info, int *change_mask) { for (tw = w; tw; top = tw, tw = XtParent(tw)) ; GetGlobalDefaults(XtNameToWidget(top, "*defaults_setup_db"), info); -#define changed(field, test) \ - ((test) || ((global_defaults & M_##field) != \ - (info->_global.global_defaults & M_##field))) \ +#define changed(field, test) \ + ((test) || ((global_defaults & M_##field) != \ + (info->_global.global_defaults & M_##field))) \ << B_##field -#define changed_string(field, name) \ - changed(field, ReplaceString(&info->field, \ +#define changed_string(field, name) \ + changed(field, ReplaceString(&info->field, \ XmTextGetString(XtNameToWidget(w, name)), 0)) mask |= changed_string(database, "exp_text"); mask |= changed_string(shot, "shot_text"); @@ -792,7 +853,8 @@ void GetDataSetup(Widget w, WaveInfo *info, int *change_mask) { #undef changed_string } -static void GetGlobalDefaults(Widget w, WaveInfo *info) { +static void GetGlobalDefaults(Widget w, WaveInfo *info) +{ info->_global.global.database = XmToggleButtonGadgetGetState(XtNameToWidget(w, "def_exp_text")); info->_global.global.shot = @@ -835,9 +897,11 @@ static void GetGlobalDefaults(Widget w, WaveInfo *info) { XmToggleButtonGadgetGetState(XtNameToWidget(w, "def_y_grid_lines")); } -Boolean ReplaceString(String *old, String new, Boolean free) { +Boolean ReplaceString(String *old, String new, Boolean free) +{ Boolean changed = TRUE; - if (*old) { + if (*old) + { changed = strcmp(*old, new); XtFree(*old); } @@ -848,20 +912,24 @@ Boolean ReplaceString(String *old, String new, Boolean free) { } void SetDirMask(Widget w, String *file, - XmAnyCallbackStruct *callback_data __attribute__((unused))) { - if (*file) { + XmAnyCallbackStruct *callback_data __attribute__((unused))) +{ + if (*file) + { XmString mask; char *tmpfile = strcpy(malloc(strlen(*file) + 10), *file); char *typpos = strrchr(tmpfile, '.'); char *dirpos = strrchr(tmpfile, '/'); - if (dirpos) { + if (dirpos) + { dirpos[1] = 0; strcat(tmpfile, "*"); if (typpos && typpos > dirpos) strcat(tmpfile, typpos); else strcat(tmpfile, ".dat"); - } else + } + else strcpy(tmpfile, "*.dat"); mask = XmStringCreateSimple(tmpfile); XtVaSetValues(w, XmNdirMask, mask, NULL); @@ -874,7 +942,8 @@ void DisplayHelp(Widget w_in __attribute__((unused)), String tag __attribute__((unused)), XtPointer callback_data __attribute__((unused))) {} -void ResetWave(WaveInfo *info) { +void ResetWave(WaveInfo *info) +{ ReplaceString(&info->database, "", 0); ReplaceString(&info->shot, "", 0); ReplaceString(&info->default_node, "", 0); @@ -899,7 +968,8 @@ void ResetWave(WaveInfo *info) { } void DisableGlobalDefault(Widget w, String tag, - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ Widget top = w; Widget tw; Widget defaults_widget; @@ -916,9 +986,11 @@ void DisableGlobalDefault(Widget w, String tag, } void InitDefaultsSetupWidget(Widget w, int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ static int default_db_inited = 0; - if (!default_db_inited) { + if (!default_db_inited) + { Widget top = w; Widget tw; Widget defaults_widget; @@ -936,9 +1008,11 @@ void InitDefaultsSetupWidget(Widget w, int *tag __attribute__((unused)), NULL); XtVaGetValues(setup_widget, XtNwidth, &width, XtNheight, &height, NULL); XtVaSetValues(defaults_widget, XtNwidth, width, XtNheight, height, NULL); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { Widget w = XtNameToWidget(setup_widget, &XtName(child[i])[4]); - if (w) { + if (w) + { Position x; Position y; XtVaGetValues(w, XtNx, &x, XtNy, &y, NULL); @@ -949,7 +1023,8 @@ void InitDefaultsSetupWidget(Widget w, int *tag __attribute__((unused)), } } -static String Concat(String prefix, String postfix) { +static String Concat(String prefix, String postfix) +{ String answer = XtMalloc(strlen(prefix) + strlen(postfix) + 1); strcpy(answer, prefix); strcat(answer, postfix); @@ -957,7 +1032,8 @@ static String Concat(String prefix, String postfix) { } void ExpandReset(Widget w, int *tag, - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ Widget dsw; Widget exw; String exp; @@ -972,14 +1048,16 @@ void ExpandReset(Widget w, int *tag, exp = XmTextGetString(XtNameToWidget(dsw, "*x_expression")); XmTextSetString(XtNameToWidget(exw, "*expanded_x"), exp); XtFree(exp); - if (!XtIsManaged(exw)) { + if (!XtIsManaged(exw)) + { XtVaSetValues(exw, XmNuserData, dsw, NULL); XtManageChild(exw); } } void ExpandCancel(Widget w, int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ Widget dsw; for (dsw = w; XtParent(dsw); dsw = XtParent(dsw)) ; @@ -987,7 +1065,8 @@ void ExpandCancel(Widget w, int *tag __attribute__((unused)), } void ExpandOk(Widget w, int *tag __attribute__((unused)), - XtPointer callback_data __attribute__((unused))) { + XtPointer callback_data __attribute__((unused))) +{ Widget dsw; Widget exw; String exp; @@ -1005,7 +1084,8 @@ void ExpandOk(Widget w, int *tag __attribute__((unused)), ExpandCancel(exw, 0, 0); } -static String FixupLFS(String in) { +static String FixupLFS(String in) +{ int i; int j; int lfs = 0; @@ -1014,45 +1094,55 @@ static String FixupLFS(String in) { if (in[i] == '\n') lfs++; out = XtMalloc(strlen(in) + lfs * 2 + 1); - for (i = 0, j = 0; in[i]; i++) { - if (in[i] == '\n') { + for (i = 0, j = 0; in[i]; i++) + { + if (in[i] == '\n') + { out[j++] = '|'; out[j++] = '|'; out[j++] = '|'; - } else + } + else out[j++] = in[i]; } out[j] = 0; return out; } -static String FixupBARS(String in) { +static String FixupBARS(String in) +{ int i; int j; int lfs = 0; String out; for (i = 0; in[i] && in[i + 1] && in[i + 2]; i++) - if (in[i] == '|' && in[i + 1] == '|' && in[i + 2] == '|') { + if (in[i] == '|' && in[i + 1] == '|' && in[i + 2] == '|') + { lfs++; i += 2; } out = XtMalloc(strlen(in) - lfs * 2 + 1); - for (i = 0, j = 0; in[i]; i++) { - if (lfs && in[i] == '|' && in[i + 1] == '|' && in[i + 2] == '|') { + for (i = 0, j = 0; in[i]; i++) + { + if (lfs && in[i] == '|' && in[i + 1] == '|' && in[i + 2] == '|') + { out[j++] = '\n'; lfs--; i += 2; - } else + } + else out[j++] = in[i]; } out[j] = 0; return out; } -static void SetOptionIdx(Widget w, int idx) { +static void SetOptionIdx(Widget w, int idx) +{ static Widget pulldown; XtVaGetValues(w, XmNsubMenuId, &pulldown, NULL); - if (pulldown) { + if (pulldown) + { static Widget *options; static Cardinal num_options; XtVaGetValues(pulldown, XmNchildren, &options, XmNnumChildren, &num_options, @@ -1062,19 +1152,22 @@ static void SetOptionIdx(Widget w, int idx) { } } -static int GetOptionIdx(Widget w) { +static int GetOptionIdx(Widget w) +{ int idx = -1; static Widget pulldown; static Widget option; XtVaGetValues(w, XmNsubMenuId, &pulldown, XmNmenuHistory, &option, NULL); - if (pulldown && option) { + if (pulldown && option) + { static Widget *options; static Cardinal num_options; int i; XtVaGetValues(pulldown, XmNchildren, &options, XmNnumChildren, &num_options, NULL); for (i = 0; i < (int)num_options; i++) - if (options[i] == option) { + if (options[i] == option) + { idx = i; break; } @@ -1082,7 +1175,8 @@ static int GetOptionIdx(Widget w) { return idx; } -void PositionPopupMenu(XmRowColumnWidget w, XButtonEvent *event) { +void PositionPopupMenu(XmRowColumnWidget w, XButtonEvent *event) +{ Widget option = w->row_column.memory_subwidget; XtX(w) = event->x_root - (option ? XtX(option) + XtWidth(option) / 2 : 0); XtY(w) = event->y_root - (option ? XtY(option) + XtHeight(option) / 2 : 0); @@ -1090,14 +1184,16 @@ void PositionPopupMenu(XmRowColumnWidget w, XButtonEvent *event) { RC_CascadeBtn(w) = XtWindowToWidget(XtDisplay(w), event->window); } -void PopupComplaint(Widget parent, String string) { +void PopupComplaint(Widget parent, String string) +{ Widget new_parent; Widget w; int i; for (new_parent = parent; new_parent && !XtIsWidget(new_parent); new_parent = XtParent(new_parent)) ; - if (new_parent) { + if (new_parent) + { static XtCallbackRec ok_callback_list[] = { {(XtCallbackProc)XtDestroyWidget, 0}, {0, 0}}; Arg args[] = {{XmNmessageString, (XtArgVal)0}, @@ -1117,7 +1213,8 @@ void PopupComplaint(Widget parent, String string) { XtDestroyWidget(XmMessageBoxGetChild(w, XmDIALOG_CANCEL_BUTTON)); XtDestroyWidget(XmMessageBoxGetChild(w, XmDIALOG_HELP_BUTTON)); XtManageChild(w); - } else + } + else printf("Error displaying dialog box\nCould not find widget to 'parent' " "box\nError message was:\n\t%s\n", string); diff --git a/dwscope/evaluate.c b/dwscope/evaluate.c index b38ff9d516..d14cb1628a 100644 --- a/dwscope/evaluate.c +++ b/dwscope/evaluate.c @@ -132,7 +132,8 @@ extern int TdiCompile(); extern int TdiDimOf(); extern int TdiDebug(); -static void ResetErrors() { +static void ResetErrors() +{ static int const four = 4; static struct descriptor const clear_messages = {4, DTYPE_L, CLASS_S, (char *)&four}; @@ -142,10 +143,12 @@ static void ResetErrors() { } static Boolean Error(Boolean brief, String topic, String *error, - struct descriptor_xd *xd1, struct descriptor_xd *xd2) { + struct descriptor_xd *xd1, struct descriptor_xd *xd2) +{ if (brief) *error = XtNewString(topic); - else { + else + { static struct descriptor_d messages = {0, DTYPE_T, CLASS_D, 0}; static int const one = 1; static struct descriptor const get_messages = {4, DTYPE_L, CLASS_S, @@ -170,7 +173,8 @@ static Boolean Error(Boolean brief, String topic, String *error, } static void DestroyXd(Widget w __attribute__((unused)), - struct descriptor_xd *xd) { + struct descriptor_xd *xd) +{ MdsFree1Dx(xd, 0); free(xd); } @@ -180,7 +184,8 @@ static inline int minInt(int a, int b) { return a < b ? a : b; } Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, String database, String shot, String default_node, String x, String y, XmdsWaveformValStruct *x_ret, - XmdsWaveformValStruct *y_ret, String *error) { + XmdsWaveformValStruct *y_ret, String *error) +{ static DESCRIPTOR(rowv, "_ROW=$"); static DESCRIPTOR(colv, "_COLUMN=$"); @@ -193,10 +198,12 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, TdiExecute(&colv, &ival_d, &ival_d MDS_END_ARG); ival = idx; TdiExecute(&idxv, &ival_d, &ival_d MDS_END_ARG); - if (strlen(database)) { + if (strlen(database)) + { static int shotnum; shotnum = 0; - if (strlen(shot)) { + if (strlen(shot)) + { struct descriptor shot_dsc = {0, DTYPE_T, CLASS_S, 0}; static DESCRIPTOR_LONG(shotnum_dsc, &shotnum); shot_dsc.length = strlen(shot); @@ -204,7 +211,8 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, ResetErrors(); if (!(TdiExecute(&shot_dsc, &shotnum_dsc MDS_END_ARG) & 1)) return Error(brief, "Error evaluating shot number", error, 0, 0); - if (event) { + if (event) + { int i; String upper_shot = XtNewString(shot); int len = strlen(shot); @@ -220,14 +228,17 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, if (!(TreeOpen(database, shotnum, 1) & 1)) return Error(1, "Error opening database", error, 0, 0); } - if (strlen(default_node)) { + if (strlen(default_node)) + { int nid; TreeSetDefaultNid(0); if (!(TreeSetDefault(default_node, &nid) & 1)) return Error(1, "Default node not found", error, 0, 0); - } else + } + else TreeSetDefaultNid(0); - if (strlen(y)) { + if (strlen(y)) + { struct descriptor y_dsc = {0, DTYPE_T, CLASS_S, 0}; static EMPTYXD(sig); static float zero = 0.0; @@ -239,36 +250,43 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, ResetErrors(); if ((TdiExecute(&y_dsc, &sig MDS_END_ARG) & 1) && (TdiData(sig.pointer, &y_xd MDS_END_ARG) & 1) && - (TdiCvt(&y_xd, &float_dsc, &y_xd MDS_END_ARG) & 1)) { + (TdiCvt(&y_xd, &float_dsc, &y_xd MDS_END_ARG) & 1)) + { struct descriptor_a *y_a = (struct descriptor_a *)y_xd.pointer; int count = (y_a->class == CLASS_A) ? y_a->arsize / sizeof(float) : 1; - if (count >= 1) { + if (count >= 1) + { EMPTYXD(x_xd); int status; ResetErrors(); - if (strlen(x)) { + if (strlen(x)) + { struct descriptor x_dsc = {0, DTYPE_T, CLASS_S, 0}; x_dsc.length = strlen(x); x_dsc.pointer = x; status = (TdiCompile(&x_dsc, &sig MDS_END_ARG) & 1) && (TdiData(&sig, &x_xd MDS_END_ARG) & 1) && (TdiCvt(&x_xd, &float_dsc, &x_xd MDS_END_ARG) & 1); - } else + } + else status = (TdiDimOf(&sig, &x_xd MDS_END_ARG) & 1) && (TdiData(&x_xd, &x_xd MDS_END_ARG) & 1) && (TdiCvt(&x_xd, &float_dsc, &x_xd MDS_END_ARG) & 1); - if (!(status & 1) && (y_a->class == CLASS_S)) { + if (!(status & 1) && (y_a->class == CLASS_S)) + { static int zero = 0; static DESCRIPTOR_LONG(zero_d, &zero); status = MdsCopyDxXd(&zero_d, &x_xd); } MdsFree1Dx(&sig, 0); - if (status) { + if (status) + { struct descriptor_a *x_a = (struct descriptor_a *)x_xd.pointer; count = (x_a->class == CLASS_A) ? minInt(x_a->arsize / sizeof(float), count) : 1; - if (count >= 1) { + if (count >= 1) + { x_ret->size = (x_a->class == CLASS_A) ? x_a->arsize : sizeof(float); x_ret->addr = x_a->pointer; x_ret->destroy = DestroyXd; @@ -279,23 +297,30 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, y_ret->destroy = DestroyXd; y_ret->destroy_arg = memcpy(malloc(sizeof(y_xd)), &y_xd, sizeof(y_xd)); - } else + } + else return Error(1, "X-axis contains no points", error, &y_xd, &x_xd); - } else + } + else return Error(brief, "Error evaluating X-axis", error, &y_xd, &x_xd); - } else + } + else return Error(1, "Y-axis contains no points", error, &y_xd, 0); - } else + } + else return Error(brief, "Error evaluating Y-axis", error, &y_xd, 0); - } else + } + else return Error(1, "", error, 0, 0); return 1; } Boolean EvaluateText(String text, String error_prefix, String *text_ret, - String *error) { + String *error) +{ Boolean status = 1; - if (strlen(text)) { + if (strlen(text)) + { struct descriptor text_dsc = {0, DTYPE_T, CLASS_S, 0}; static EMPTYXD(string_xd); static struct descriptor_d string_d = {0, DTYPE_T, CLASS_D, 0}; @@ -304,24 +329,29 @@ Boolean EvaluateText(String text, String error_prefix, String *text_ret, ResetErrors(); if ((TdiExecute(&text_dsc, &string_xd MDS_END_ARG) & 1) && (TdiData(&string_xd, &string_xd MDS_END_ARG) & 1) && - (TdiAdjustl(&string_xd, &string_d MDS_END_ARG) & 1)) { + (TdiAdjustl(&string_xd, &string_d MDS_END_ARG) & 1)) + { StrTrim((struct descriptor *)&string_d, (struct descriptor *)&string_d, 0); *text_ret = memcpy(XtMalloc(string_d.length + 1), string_d.pointer, string_d.length); (*text_ret)[string_d.length] = '\0'; - } else { + } + else + { *text_ret = XtNewString(""); status = Error(0, error_prefix, error, &string_xd, 0); } StrFree1Dx(&string_d); MdsFree1Dx(&string_xd, 0); - } else + } + else *text_ret = XtNewString(""); return status; } -void CloseDataSources() { +void CloseDataSources() +{ while (TreeClose(NULL, 0) & 1) ; } @@ -329,7 +359,8 @@ void CloseDataSources() { #ifdef OLD_WAY static XtAppContext this_app_context; static Widget this_widget; -static void EventAst(void *astparam, int dlen, char *data) { +static void EventAst(void *astparam, int dlen, char *data) +{ Boolean *received = (Boolean *)astparam; *received = 1; XtAppAddTimeOut(this_app_context, 1, (XtTimerCallbackProc)EventUpdate, 0); @@ -342,19 +373,23 @@ static void EventAst(void *astparam, int dlen, char *data) { XFlush(XtDisplay(this_widget)); } -void SetupEvent(String event, Boolean *received, int *id) { - if (*id) { +void SetupEvent(String event, Boolean *received, int *id) +{ + if (*id) + { MDSEventCan(*id); *id = 0; } - if (strlen(event)) { + if (strlen(event)) + { pthread_mutex_lock(&event_mutex); MDSEventAst(event, EventAst, received, id); pthread_mutex_unlock(&event_mutex); } } -void SetupEventInput(XtAppContext app_context, Widget w) { +void SetupEventInput(XtAppContext app_context, Widget w) +{ this_app_context = app_context; this_widget = w; } @@ -362,7 +397,8 @@ void SetupEventInput(XtAppContext app_context, Widget w) { static int event_pipe[2]; static void EventAst(void *astparam, int dlen __attribute__((unused)), - char *data __attribute__((unused))) { + char *data __attribute__((unused))) +{ Boolean *received = (Boolean *)astparam; char buf[1]; pthread_mutex_lock(&event_mutex); @@ -372,19 +408,23 @@ static void EventAst(void *astparam, int dlen __attribute__((unused)), perror("Error writing to event pipe\n"); } -void SetupEvent(String event, Boolean *received, int *id) { - if (*id) { +void SetupEvent(String event, Boolean *received, int *id) +{ + if (*id) + { MDSEventCan(*id); *id = 0; } - if (strlen(event)) { + if (strlen(event)) + { pthread_mutex_lock(&event_mutex); MDSEventAst(event, EventAst, received, id); pthread_mutex_unlock(&event_mutex); } } -static void DoEventUpdate(XtPointer client_data, int *source, XtInputId *id) { +static void DoEventUpdate(XtPointer client_data, int *source, XtInputId *id) +{ char buf[1]; if (read(event_pipe[0], buf, 1) == -1) perror("Error reading from event pipe\n"); @@ -392,7 +432,8 @@ static void DoEventUpdate(XtPointer client_data, int *source, XtInputId *id) { } void SetupEventInput(XtAppContext app_context, - Widget w __attribute__((unused))) { + Widget w __attribute__((unused))) +{ if (pipe(event_pipe) == -1) perror("Error creating event pipes"); XtAppAddInput(app_context, event_pipe[0], (XtPointer)XtInputReadMask, @@ -404,12 +445,16 @@ void SetupEventInput(XtAppContext app_context, #include #include #include -static void Destroy_xy(Widget w, float *ptr) { free(ptr); } +static void Destroy_xy(Widget w, float *ptr) +{ + free(ptr); +} Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, String database, String shot, String default_node, String x, String y, XmdsWaveformValStruct *x_ret, - XmdsWaveformValStruct *y_ret, String *error) { + XmdsWaveformValStruct *y_ret, String *error) +{ CLIENT *cl; char *rpc_server = getenv("mds_rpc_server"); @@ -426,18 +471,21 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, rpc_input.default_node = default_node; cl = clnt_create(rpc_server, MDSPLUS, MDSPLUSVERS, "tcp"); - if (cl == NULL) { + if (cl == NULL) + { *error = clnt_spcreateerror(rpc_server); return (0); } result = mds_scope_xy_value_1(&rpc_input, cl); - if (result == NULL) { + if (result == NULL) + { *error = clnt_sperror(cl, rpc_server); return (0); } - switch (result->errno) { + switch (result->errno) + { case 0: x_ptr = malloc(result->mds_scope_xy_res_u.results->x_value.len * sizeof(float)); @@ -465,11 +513,13 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, status = 1; break; case 1: - if (result->mds_scope_xy_res_u.results_error->error_len) { + if (result->mds_scope_xy_res_u.results_error->error_len) + { *error = XtCalloc(1, result->mds_scope_xy_res_u.results_error->error_len + 1); strcpy(*error, result->mds_scope_xy_res_u.results_error->error); - } else + } + else *error = XtNewString(""); xdr_free(xdr_mds_scope_xy_res, result); status = 0; @@ -482,7 +532,8 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, } Boolean EvaluateText(String text, String error_prefix, String *text_ret, - String *error) { + String *error) +{ CLIENT *cl; char *rpc_server = getenv("mds_rpc_server"); mds_scope_text_res *result; @@ -493,38 +544,45 @@ Boolean EvaluateText(String text, String error_prefix, String *text_ret, rpc_input.error_prefix = error_prefix; cl = clnt_create(rpc_server, MDSPLUS, MDSPLUSVERS, "tcp"); - if (cl == NULL) { + if (cl == NULL) + { *error = clnt_spcreateerror(rpc_server); *text_ret = XtNewString(""); return (0); } result = mds_scope_text_value_1(&rpc_input, cl); - if (result == NULL) { + if (result == NULL) + { *error = clnt_sperror(cl, rpc_server); *text_ret = XtNewString(""); return (0); } - switch (result->errno) { + switch (result->errno) + { case 0: - if (result->mds_scope_text_res_u.results->len) { + if (result->mds_scope_text_res_u.results->len) + { *text_ret = XtCalloc(1, result->mds_scope_text_res_u.results->len + 1); strcpy(*text_ret, result->mds_scope_text_res_u.results->ptr); (*text_ret)[result->mds_scope_text_res_u.results->len] = 0; - } else + } + else *text_ret = XtNewString(""); xdr_free(xdr_mds_scope_text_res, result); status = 1; break; case 1: - if (result->mds_scope_text_res_u.results_error->len) { + if (result->mds_scope_text_res_u.results_error->len) + { *error = XtCalloc(1, result->mds_scope_text_res_u.results_error->len + 1); strcpy(*error, result->mds_scope_text_res_u.results_error->ptr); (*error)[result->mds_scope_text_res_u.results_error->len] = 0; *text_ret = XtNewString(""); - } else + } + else *error = XtNewString(""); xdr_free(xdr_mds_scope_text_res, result); @@ -546,17 +604,21 @@ void SetupEventInput(XtAppContext app_context, Widget w) {} #elif defined(_DUMMY_) #include static Boolean Error(Boolean brief, String topic, String *error, String text, - int *dummy) { + int *dummy) +{ /* if (brief) *error = XtNewString(topic); else { */ - if (text) { + if (text) + { String message = XtMalloc(strlen(topic) + strlen(text) + 5); sprintf(message, "%s\n\n%s", topic, text); *error = message; - } else { + } + else + { String message = XtMalloc(strlen(topic) + 5); sprintf(message, "%s\n\n", topic); *error = message; @@ -572,13 +634,16 @@ static void Destroy(Widget w, String ptr) { free(ptr); } Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, String database, String shot, String default_node, String x, String y, XmdsWaveformValStruct *x_ret, - XmdsWaveformValStruct *y_ret, String *error) { - if (strlen(y)) { + XmdsWaveformValStruct *y_ret, String *error) +{ + if (strlen(y)) + { int count = 10000; int i; float *xv = (float *)malloc(count * sizeof(float)); float *yv = (float *)malloc(count * sizeof(float)); - for (i = 0; i < count; i++) { + for (i = 0; i < count; i++) + { xv[i] = i; yv[i] = sin(i / 1000. * 3.14); } @@ -590,17 +655,21 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, y_ret->addr = (caddr_t)yv; y_ret->destroy = Destroy; y_ret->destroy_arg = (caddr_t)yv; - } else + } + else return Error(1, "", error, NULL, NULL); return 1; } Boolean EvaluateText(String text, String error_prefix, String *text_ret, - String *error) { + String *error) +{ Boolean status = 1; - if (strlen(text)) { + if (strlen(text)) + { *text_ret = XtNewString(text); - } else + } + else *text_ret = XtNewString(""); return status; } @@ -618,11 +687,14 @@ void SetupEventInput(XtAppContext app_context, Widget w) {} #else #include -static long Connect() { +static long Connect() +{ static long sock; - if (!sock) { + if (!sock) + { char *host = getenv("MDS_HOST"); - if (host == 0) { + if (host == 0) + { printf("set environment variable MDS_HOST to remote server name\n"); exit(1); } @@ -633,7 +705,8 @@ static long Connect() { return sock; } -static long ConnectToMdsEvents(char *event_host) { +static long ConnectToMdsEvents(char *event_host) +{ char hostpart[256] = {0}; char portpart[256] = {0}; char host[256]; @@ -649,9 +722,11 @@ static long ConnectToMdsEvents(char *event_host) { return ConnectToMds(host); } -static long ConnectEvents() { +static long ConnectEvents() +{ static long sock = -1; - if (sock == -1) { + if (sock == -1) + { char *event_host = getenv("MDS_EVENT_HOST"); if (event_host) sock = ConnectToMdsEvents(event_host); @@ -659,26 +734,31 @@ static long ConnectEvents() { return sock; } -#define FreeDescrip(x) \ - if (x.ptr != NULL) { \ - free(x.ptr); \ - x.ptr = NULL; \ +#define FreeDescrip(x) \ + if (x.ptr != NULL) \ + { \ + free(x.ptr); \ + x.ptr = NULL; \ } -#define Descrip(name, type, ptr) \ +#define Descrip(name, type, ptr) \ struct descrip name = {type, 0, {0, 0, 0, 0, 0, 0, 0}, 0, ptr} static Boolean Error(Boolean brief __attribute__((unused)), String topic, - String *error, String text, struct descrip *dsc) { + String *error, String text, struct descrip *dsc) +{ /* if (brief) *error = XtNewString(topic); else { */ - if (text) { + if (text) + { String message = XtMalloc(strlen(topic) + strlen(text) + 5); sprintf(message, "%s\n\n%s", topic, text); *error = message; - } else { + } + else + { String message = XtMalloc(strlen(topic) + 5); sprintf(message, "%s\n\n", topic); *error = message; @@ -687,21 +767,25 @@ static Boolean Error(Boolean brief __attribute__((unused)), String topic, } */ if (dsc != NULL) - if (dsc->ptr != NULL) { + if (dsc->ptr != NULL) + { free(dsc->ptr); dsc->ptr = NULL; } return 0; } -static int Nelements(struct descrip *in) { - if (in->ndims) { +static int Nelements(struct descrip *in) +{ + if (in->ndims) + { int num = 1; int i; for (i = 0; i < in->ndims; i++) num *= in->dims[i]; return num; - } else + } + else return 1; } @@ -710,7 +794,8 @@ static void Destroy(Widget w __attribute__((unused)), String ptr) { free(ptr); } Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, String database, String shot, String default_node, String x, String y, XmdsWaveformValStruct *x_ret, - XmdsWaveformValStruct *y_ret, String *error) { + XmdsWaveformValStruct *y_ret, String *error) +{ int shotnum = 0; static int ival; static Descrip(id, DTYPE_LONG, &ival); @@ -723,8 +808,10 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, status = MdsValue(sock, "_COLUMN=$", &id, &ans, NULL); FreeDescrip(ans) ival = idx; status = MdsValue(sock, "_INDEX=$", &id, &ans, NULL); - FreeDescrip(ans) if (strlen(database)) { - if (strlen(shot)) { + FreeDescrip(ans) if (strlen(database)) + { + if (strlen(shot)) + { Descrip(ans, 0, NULL); Descrip(tmp, 0, NULL); if (!(MdsValue(sock, "long(execute($))", @@ -734,7 +821,8 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, return Error(brief, "Error evaluating shot number", error, ans.ptr, &ans); shotnum = *(int *)ans.ptr; - if (event) { + if (event) + { int i; String upper_shot = XtNewString(shot); int len = strlen(shot); @@ -750,36 +838,46 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, if (!(MdsOpen(sock, database, shotnum) & 1)) return Error(1, "Error opening database", error, NULL, NULL); } - if (strlen(default_node)) { + if (strlen(default_node)) + { MdsValue(sock, "TreeShr->TreeSetDefaultNid(val(0))", &ans, NULL); FreeDescrip(ans); if (!(MdsSetDefault(sock, default_node) & 1)) return Error(1, "Default node not found", error, NULL, NULL); - } else { + } + else + { MdsValue(sock, "TreeShr->TreeSetDefaultNid(val(0))", &ans, NULL); FreeDescrip(ans); } - if (strlen(y)) { + if (strlen(y)) + { Descrip(yans, 0, NULL); String yexp = XtMalloc(strlen(y) + 100); sprintf(yexp, "_y$$dwscope = (%s),f_float(data(_y$$dwscope))", y); - if (MdsValue(sock, yexp, &yans, NULL) & 1) { + if (MdsValue(sock, yexp, &yans, NULL) & 1) + { int count = Nelements(&yans); - if (count >= 1) { + if (count >= 1) + { Descrip(xans, 0, NULL); - if (strlen(x)) { + if (strlen(x)) + { String xexp = XtMalloc(strlen(x) + 100); sprintf(xexp, "f_float(data(%s))", x); status = MdsValue(sock, xexp, &xans, NULL); XtFree(xexp); - } else + } + else status = MdsValue(sock, "f_float(data(dim_of(_y$$dwscope)))", &xans, NULL); - if (status & 1) { + if (status & 1) + { int xcount = Nelements(&xans); if (xcount < count) count = xcount; - if (count >= 1) { + if (count >= 1) + { x_ret->size = count * sizeof(float); x_ret->addr = xans.ptr; x_ret->destroy = Destroy; @@ -788,49 +886,63 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, y_ret->addr = yans.ptr; y_ret->destroy = Destroy; y_ret->destroy_arg = yans.ptr; - } else { + } + else + { FreeDescrip(xans); FreeDescrip(yans); return Error(1, "X-axis contains no points", error, NULL, NULL); } - } else { + } + else + { FreeDescrip(yans); return Error(brief, "Error evaluating X-axis", error, xans.ptr, &xans); } - } else + } + else return Error(1, "Y-axis contains no points", error, NULL, &yans); - } else + } + else return Error(brief, "Error evaluating Y-axis", error, yans.ptr, &yans); - } else + } + else return Error(1, "", error, NULL, NULL); return 1; } Boolean EvaluateText(String text, String error_prefix, String *text_ret, - String *error) { + String *error) +{ Boolean status = 1; long sock = Connect(); *text_ret = NULL; - if (strlen(text) && sock) { + if (strlen(text) && sock) + { Descrip(ans, 0, NULL); Descrip(tmp, 0, NULL); if (MdsValue(sock, "trim(adjustl(execute($)))", MakeDescrip(&tmp, DTYPE_CSTRING, 0, NULL, text), &ans, NULL) & - 1) { + 1) + { *text_ret = XtNewString(ans.ptr); FreeDescrip(ans); - } else { + } + else + { *text_ret = XtNewString(""); status = Error(0, error_prefix, error, ans.ptr, &ans); } - } else + } + else *text_ret = XtNewString(""); return status; } -void CloseDataSources() { +void CloseDataSources() +{ long sock = Connect(); if (sock) MdsClose(sock); @@ -838,14 +950,18 @@ void CloseDataSources() { static void EventReceived(Boolean *received) { *received = True; } -void SetupEvent(String event, Boolean *received, int *id) { +void SetupEvent(String event, Boolean *received, int *id) +{ int sock = ConnectEvents(); - if (sock != -1) { - if (*id) { + if (sock != -1) + { + if (*id) + { MdsEventCan(sock, *id); *id = 0; } - if (strlen(event)) { + if (strlen(event)) + { MdsEventAst(sock, event, EventReceived, received, id); } } @@ -853,13 +969,15 @@ void SetupEvent(String event, Boolean *received, int *id) { extern void MdsDispatchEvent(); -static void DoEventUpdate(XtPointer client_data, int *source, XtInputId *id) { +static void DoEventUpdate(XtPointer client_data, int *source, XtInputId *id) +{ MdsDispatchEvent(ConnectEvents()); EventUpdate(client_data, source, id); } void SetupEventInput(XtAppContext app_context, - Widget w __attribute__((unused))) { + Widget w __attribute__((unused))) +{ int sock = ConnectEvents(); if (sock != -1) XtAppAddInput(app_context, sock, (XtPointer)XtInputExceptMask, diff --git a/epics/cas/mdsServer.h b/epics/cas/mdsServer.h index 1d65b30123..ab20308f85 100644 --- a/epics/cas/mdsServer.h +++ b/epics/cas/mdsServer.h @@ -28,7 +28,8 @@ class mdsServer; // with several of this class all referencing // the same pv info class // -class pvEntry : public stringId, public tsSLNode { +class pvEntry : public stringId, public tsSLNode +{ public: pvEntry(mdsPV &pvIn, mdsServer &casIn, const char *pAliasName); ~pvEntry(); @@ -45,7 +46,8 @@ class pvEntry : public stringId, public tsSLNode { // // mdsPV // -class mdsPV : public casPV, public tsSLNode { +class mdsPV : public casPV, public tsSLNode +{ public: mdsPV(mdsServer &cas, char *name, Tree *tree, TreeNode *topNode, bool append); virtual ~mdsPV(); @@ -143,7 +145,8 @@ class mdsPV : public casPV, public tsSLNode { // // mdsServer // -class mdsServer : private caServer { +class mdsServer : private caServer +{ public: mdsServer(Tree *tree, bool append); ~mdsServer(); @@ -167,7 +170,8 @@ class mdsServer : private caServer { // // mdsChannel // -class mdsChannel : public casChannel { +class mdsChannel : public casChannel +{ public: mdsChannel(const casCtx &ctxIn); void setOwner(const char *const pUserName, const char *const pHostName); diff --git a/epics/mdsrecords/devExprSoft.c b/epics/mdsrecords/devExprSoft.c index 75c83bbd89..aaab8a102a 100644 --- a/epics/mdsrecords/devExprSoft.c +++ b/epics/mdsrecords/devExprSoft.c @@ -62,7 +62,8 @@ extern int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, int retType, void *retBuf, int *retElements, char *errMsg, int isLocal); -struct { +struct +{ long number; DEVSUPFUN report; DEVSUPFUN init; @@ -72,7 +73,8 @@ struct { } devExprSoft = {5, NULL, NULL, init_record, NULL, read_mp}; epicsExportAddress(dset, devExprSoft); -static void callbackFunc(CALLBACK *pcallback) { +static void callbackFunc(CALLBACK *pcallback) +{ struct dbCommon *precord; rset *prset; @@ -83,7 +85,8 @@ static void callbackFunc(CALLBACK *pcallback) { dbScanUnlock(precord); } -static long init_record(mdsexprRecord *prec) { +static long init_record(mdsexprRecord *prec) +{ CALLBACK *pcallback; pcallback = (CALLBACK *)(calloc(1, sizeof(CALLBACK))); callbackSetCallback(callbackFunc, pcallback); @@ -119,7 +122,8 @@ static long init_record(mdsexprRecord *prec) { return 0; } -static long asynchRead(CALLBACK *pcallback) { +static long asynchRead(CALLBACK *pcallback) +{ struct dbCommon *precord; struct rset *prset; mdsexprRecord *prec; @@ -136,7 +140,8 @@ static long asynchRead(CALLBACK *pcallback) { prec = (mdsexprRecord *)precord; nRequest = prec->nelm; - for (i = 0; i < 8; i++) { + for (i = 0; i < 8; i++) + { buffers[i] = malloc(8 * prec->nelm); // Allocate maximum memory bufDims[i] = prec->nelm; } @@ -203,10 +208,12 @@ static long asynchRead(CALLBACK *pcallback) { return 0; } -static long read_mp(mdsexprRecord *prec) { +static long read_mp(mdsexprRecord *prec) +{ long nRequest = prec->nelm; CALLBACK *pcallback = (CALLBACK *)prec->dpvt; - if (prec->pact) { + if (prec->pact) + { prec->udf = FALSE; return 0; } @@ -214,7 +221,8 @@ static long read_mp(mdsexprRecord *prec) { /*************************Set Intermediate result to 0 UNTIL SET BY * asyncRead*********************************/ - switch (prec->ftvl) { + switch (prec->ftvl) + { case DBF_CHAR: case DBF_UCHAR: *((char *)prec->bptr) = 0; diff --git a/epics/mdsrecords/devMeSoft.c b/epics/mdsrecords/devMeSoft.c index 3a630ca2c6..7aa4792a68 100644 --- a/epics/mdsrecords/devMeSoft.c +++ b/epics/mdsrecords/devMeSoft.c @@ -57,7 +57,8 @@ static long init_record(waveformRecord *prec); static long read_me(waveformRecord *prec); extern int registerMdsEvent(char *eventName); extern int waitMdsEvent(char *eventName, char *buf, int maxLen, int *retLen); -struct { +struct +{ long number; DEVSUPFUN report; DEVSUPFUN init; @@ -67,7 +68,8 @@ struct { } devMeSoft = {5, NULL, NULL, init_record, NULL, read_me}; epicsExportAddress(dset, devMeSoft); -static void callbackFunc(CALLBACK *pcallback) { +static void callbackFunc(CALLBACK *pcallback) +{ struct dbCommon *precord; rset *prset; @@ -78,7 +80,8 @@ static void callbackFunc(CALLBACK *pcallback) { dbScanUnlock(precord); } -static long init_record(waveformRecord *prec) { +static long init_record(waveformRecord *prec) +{ CALLBACK *pcallback; pcallback = (CALLBACK *)(calloc(1, sizeof(CALLBACK))); callbackSetCallback(callbackFunc, pcallback); @@ -89,14 +92,16 @@ static long init_record(waveformRecord *prec) { return 0; } -static long asynchRead(CALLBACK *pcallback) { +static long asynchRead(CALLBACK *pcallback) +{ struct dbCommon *precord; waveformRecord *prec; int retLen, maxLen, elSize = 1; callbackGetUser(precord, pcallback); prec = (waveformRecord *)precord; - switch (prec->ftvl) { + switch (prec->ftvl) + { case DBF_UCHAR: case DBF_CHAR: elSize = 1; @@ -127,9 +132,11 @@ static long asynchRead(CALLBACK *pcallback) { return 0; } -static long read_me(waveformRecord *prec) { +static long read_me(waveformRecord *prec) +{ CALLBACK *pcallback = (CALLBACK *)prec->dpvt; - if (prec->pact) { + if (prec->pact) + { prec->udf = FALSE; return 0; } diff --git a/epics/mdsrecords/mdsexprRecord.c b/epics/mdsrecords/mdsexprRecord.c index 694d6b623a..afee3b1303 100644 --- a/epics/mdsrecords/mdsexprRecord.c +++ b/epics/mdsrecords/mdsexprRecord.c @@ -92,7 +92,8 @@ rset mdsexprRSET = {RSETNUMBER, get_control_double, get_alarm_double}; epicsExportAddress(rset, mdsexprRSET); -struct mpdset { /* mdsexpr dset */ +struct mpdset +{ /* mdsexpr dset */ long number; DEVSUPFUN dev_report; DEVSUPFUN init; @@ -105,36 +106,44 @@ static void monitor(mdsexprRecord *); static long readValue(mdsexprRecord *); static void checkAlarms(mdsexprRecord *prec); -static long init_record(mdsexprRecord *prec, int pass) { +static long init_record(mdsexprRecord *prec, int pass) +{ struct mpdset *pdset; long status; - if (pass == 0) { + if (pass == 0) + { if (prec->nelm <= 0) prec->nelm = 1; if (prec->ftvl > DBF_ENUM) prec->ftvl = DBF_UCHAR; prec->bptr = callocMustSucceed(prec->nelm, dbValueSize(prec->ftvl), "mdsexpr calloc failed"); - if (prec->nelm == 1) { + if (prec->nelm == 1) + { prec->nord = 1; - } else { + } + else + { prec->nord = 0; } return 0; } /* wf.siml must be a CONSTANT or a PV_LINK or a DB_LINK */ - if (prec->siml.type == CONSTANT) { + if (prec->siml.type == CONSTANT) + { recGblInitConstantLink(&prec->siml, DBF_USHORT, &prec->simm); } /* must have dset defined */ - if (!(pdset = (struct mpdset *)(prec->dset))) { + if (!(pdset = (struct mpdset *)(prec->dset))) + { recGblRecordError(S_dev_noDSET, (void *)prec, "mp: init_record"); return S_dev_noDSET; } /* must have read_wf function defined */ - if ((pdset->number < 5) || (pdset->read_mp == NULL)) { + if ((pdset->number < 5) || (pdset->read_mp == NULL)) + { recGblRecordError(S_dev_missingSup, (void *)prec, "mp: init_record"); return S_dev_missingSup; } @@ -146,12 +155,14 @@ static long init_record(mdsexprRecord *prec, int pass) { return status; } -static long process(mdsexprRecord *prec) { +static long process(mdsexprRecord *prec) +{ struct mpdset *pdset = (struct mpdset *)(prec->dset); long status; unsigned char pact = prec->pact; - if ((pdset == NULL) || (pdset->read_mp == NULL)) { + if ((pdset == NULL) || (pdset->read_mp == NULL)) + { prec->pact = TRUE; recGblRecordError(S_dev_missingSup, (void *)prec, "read_mp"); return S_dev_missingSup; @@ -179,7 +190,8 @@ static long process(mdsexprRecord *prec) { return 0; } -static long cvt_dbaddr(DBADDR *paddr) { +static long cvt_dbaddr(DBADDR *paddr) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; paddr->pfield = prec->bptr; @@ -191,7 +203,8 @@ static long cvt_dbaddr(DBADDR *paddr) { return 0; } -static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) { +static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; *no_elements = prec->nord; @@ -200,7 +213,8 @@ static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) { return 0; } -static long put_array_info(DBADDR *paddr, long nNew) { +static long put_array_info(DBADDR *paddr, long nNew) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; prec->nord = nNew; @@ -210,7 +224,8 @@ static long put_array_info(DBADDR *paddr, long nNew) { return 0; } -static long get_units(DBADDR *paddr, char *units) { +static long get_units(DBADDR *paddr, char *units) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; strncpy(units, prec->egu, DB_UNITS_SIZE); @@ -218,7 +233,8 @@ static long get_units(DBADDR *paddr, char *units) { return 0; } -static long get_precision(DBADDR *paddr, long *precision) { +static long get_precision(DBADDR *paddr, long *precision) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; int fieldIndex = dbGetFieldIndex(paddr); @@ -230,29 +246,36 @@ static long get_precision(DBADDR *paddr, long *precision) { return 0; } -static long get_graphic_double(DBADDR *paddr, struct dbr_grDouble *pgd) { +static long get_graphic_double(DBADDR *paddr, struct dbr_grDouble *pgd) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; - if (dbGetFieldIndex(paddr) == mdsexprRecordVAL) { + if (dbGetFieldIndex(paddr) == mdsexprRecordVAL) + { pgd->upper_disp_limit = prec->hopr; pgd->lower_disp_limit = prec->lopr; - } else + } + else recGblGetGraphicDouble(paddr, pgd); return 0; } -static long get_control_double(DBADDR *paddr, struct dbr_ctrlDouble *pcd) { +static long get_control_double(DBADDR *paddr, struct dbr_ctrlDouble *pcd) +{ mdsexprRecord *prec = (mdsexprRecord *)paddr->precord; - if (dbGetFieldIndex(paddr) == mdsexprRecordVAL) { + if (dbGetFieldIndex(paddr) == mdsexprRecordVAL) + { pcd->upper_ctrl_limit = prec->hopr; pcd->lower_ctrl_limit = prec->lopr; - } else + } + else recGblGetControlDouble(paddr, pcd); return 0; } -static void monitor(mdsexprRecord *prec) { +static void monitor(mdsexprRecord *prec) +{ unsigned short monitor_mask = 0; unsigned int hash = 0; @@ -265,12 +288,14 @@ static void monitor(mdsexprRecord *prec) { /* Calculate hash if we are interested in OnChange events. */ if ((prec->mpst == mdsexprPOST_OnChange) || - (prec->apst == mdsexprPOST_OnChange)) { + (prec->apst == mdsexprPOST_OnChange)) + { hash = epicsMemHash((char *)prec->bptr, prec->nord * dbValueSize(prec->ftvl), 0); /* Only post OnChange values if the hash is different. */ - if (hash != prec->hash) { + if (hash != prec->hash) + { if (prec->mpst == mdsexprPOST_OnChange) monitor_mask |= DBE_VALUE; if (prec->apst == mdsexprPOST_OnChange) @@ -283,16 +308,19 @@ static void monitor(mdsexprRecord *prec) { } } - if (monitor_mask) { + if (monitor_mask) + { db_post_events(prec, prec->bptr, monitor_mask); } } -static long readValue(mdsexprRecord *prec) { +static long readValue(mdsexprRecord *prec) +{ long status; struct mpdset *pdset = (struct mpdset *)prec->dset; - if (prec->pact == TRUE) { + if (prec->pact == TRUE) + { return (*pdset->read_mp)(prec); } @@ -300,20 +328,25 @@ static long readValue(mdsexprRecord *prec) { if (status) return status; - if (prec->simm == menuYesNoNO) { + if (prec->simm == menuYesNoNO) + { return (*pdset->read_mp)(prec); } - if (prec->simm == menuYesNoYES) { + if (prec->simm == menuYesNoYES) + { long nRequest = prec->nelm; status = dbGetLink(&(prec->siol), prec->ftvl, prec->bptr, 0, &nRequest); /* nord set only for db links: needed for old db_access */ - if (prec->siol.type != CONSTANT) { + if (prec->siol.type != CONSTANT) + { prec->nord = nRequest; if (status == 0) prec->udf = FALSE; } - } else { + } + else + { recGblSetSevr(prec, SOFT_ALARM, INVALID_ALARM); return -1; } @@ -321,10 +354,12 @@ static long readValue(mdsexprRecord *prec) { return status; } -static void checkAlarms(mdsexprRecord *prec) { +static void checkAlarms(mdsexprRecord *prec) +{ int status = prec->errs; - if (prec->udf == TRUE) { + if (prec->udf == TRUE) + { recGblSetSevr(prec, UDF_ALARM, INVALID_ALARM); return; } diff --git a/epics/mdsrecords/mdsplusSupMain.cpp b/epics/mdsrecords/mdsplusSupMain.cpp index ec863b7c3d..d33728751f 100644 --- a/epics/mdsrecords/mdsplusSupMain.cpp +++ b/epics/mdsrecords/mdsplusSupMain.cpp @@ -35,8 +35,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "epicsThread.h" #include "iocsh.h" -int main(int argc, char *argv[]) { - if (argc >= 2) { +int main(int argc, char *argv[]) +{ + if (argc >= 2) + { iocsh(argv[1]); epicsThreadSleep(.2); } diff --git a/epics/mdsrecords/mdsplusSupUtilities.cpp b/epics/mdsrecords/mdsplusSupUtilities.cpp index b555451e8e..b2ea90f638 100644 --- a/epics/mdsrecords/mdsplusSupUtilities.cpp +++ b/epics/mdsrecords/mdsplusSupUtilities.cpp @@ -58,8 +58,10 @@ using namespace MDSplus; static sem_t semStruct; static bool semInitialized = false; -static void lock() { - if (!semInitialized) { +static void lock() +{ + if (!semInitialized) + { semInitialized = true; int status = sem_init(&semStruct, 0, 1); if (status != 0) @@ -69,7 +71,8 @@ static void lock() { } static void unlock() { sem_post(&semStruct); } -struct EventDescriptor { +struct EventDescriptor +{ char *evName; Event *event; }; @@ -79,7 +82,8 @@ static EventDescriptor eventDescrs[MAX_EVENTS]; // return 0 if it is a new event // return -1 if the same name has already been declared: this is an error // condition since only one record per event must be defined per IOC -static int addEvent(char *evInName) { +static int addEvent(char *evInName) +{ int i; lock(); std::string evStr(evInName); @@ -90,7 +94,8 @@ static int addEvent(char *evInName) { evNameStr = evStr.substr(0, colPos); } char *evName = (char *)evNameStr.c_str(); - for (i = 0; i < MAX_EVENTS; i++) { + for (i = 0; i < MAX_EVENTS; i++) + { if (eventDescrs[i].evName && !strcmp(evName, eventDescrs[i].evName)) return -1; if (!eventDescrs[i].evName) @@ -106,10 +111,12 @@ static int addEvent(char *evInName) { return 0; } -static Event *getEvent(char *evName) { +static Event *getEvent(char *evName) +{ int i; lock(); - for (i = 0; i < MAX_EVENTS; i++) { + for (i = 0; i < MAX_EVENTS; i++) + { if (eventDescrs[i].evName && !strcmp(evName, eventDescrs[i].evName)) break; } @@ -125,7 +132,8 @@ static Event *getEvent(char *evName) { // For local connection it is the corresponding TreeNode instance // For Remote connection it is the experiment name and the path (used by // connection) -struct nodeDescr { +struct nodeDescr +{ Tree *tree; TreeNode *node; char *path; @@ -133,7 +141,8 @@ struct nodeDescr { // Connection table }; -struct connectionDescr { +struct connectionDescr +{ Connection *connection; char *ipAddr; // IP address for thei connection char *experiment; // Currently open experiment @@ -146,12 +155,14 @@ static connectionDescr connectionTable[MAX_CONNECTIONS]; // When called, a new TreeNode instance is added to nodeTable. Note this is // called in record initialization -static int getNodeId(TreeNode *node, char *path, Tree *tree, int connectionId) { +static int getNodeId(TreeNode *node, char *path, Tree *tree, int connectionId) +{ int i; lock(); for (i = 0; i < MAX_NODES && nodeTable[i].path != NULL; i++) ; - if (i == MAX_NODES) { + if (i == MAX_NODES) + { unlock(); printf("NODE TABLE OVERFLOW in mdsput Record initialization!!!!!\n"); return -1; @@ -159,7 +170,8 @@ static int getNodeId(TreeNode *node, char *path, Tree *tree, int connectionId) { nodeTable[i].node = node; nodeTable[i].tree = tree; nodeTable[i].connectionId = connectionId; - if (path) { + if (path) + { nodeTable[i].path = (char *)malloc(strlen(path) + 1); strcpy(nodeTable[i].path, path); } @@ -168,14 +180,16 @@ static int getNodeId(TreeNode *node, char *path, Tree *tree, int connectionId) { } // Note: no dynamic reconnection currently supported -static int getConnectionId(char *ipAddr, char *exp, int shot) { +static int getConnectionId(char *ipAddr, char *exp, int shot) +{ int i; lock(); for (i = 0; i < MAX_CONNECTIONS && connectionTable[i].ipAddr && strcmp(connectionTable[i].ipAddr, ipAddr); i++) ; - if (i == MAX_CONNECTIONS) { + if (i == MAX_CONNECTIONS) + { unlock(); printf("CONNECTION TABLE OVERFLOW in mdsput Record initialization!!!!!\n"); return -1; @@ -186,25 +200,31 @@ static int getConnectionId(char *ipAddr, char *exp, int shot) { strcpy(connectionTable[i].ipAddr, ipAddr); unlock(); // Let the lengthy connection establishment be done outsize lock - try { + try + { connectionTable[i].connection = new Connection(ipAddr); if (exp && *exp) // May be NULL or empty string if only the connection is // required connectionTable[i].connection->openTree(exp, shot); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Cannot establish mdsip connection: %s\n", exc.what()); connectionTable[i].connection = 0; } - } else // A Connection to this address already exists + } + else // A Connection to this address already exists unlock(); return i; } static void updateNode(int id, int *isLocal, TreeNode **node, Connection **conn, - char **path, Tree **tree) { + char **path, Tree **tree) +{ *node = NULL; lock(); - if (id < MAX_NODES) { + if (id < MAX_NODES) + { *node = nodeTable[id].node; if (nodeTable[id].connectionId != -1) *conn = connectionTable[nodeTable[id].connectionId].connection; @@ -218,42 +238,51 @@ static void updateNode(int id, int *isLocal, TreeNode **node, Connection **conn, } int openMds(char *expName, int shot, int isLocal, char *ipAddr, char *path, - unsigned int *nodeId, char *errMsg) { + unsigned int *nodeId, char *errMsg) +{ int connId; int id; Tree *tree; // printf("OpenMds: %s %d %s %s %s\n", expName, shot, // (isLocal)?"Local":"Remote", ipAddr, path); - if (isLocal) { + if (isLocal) + { TreeNode *node; - try { + try + { tree = new Tree(expName, shot); if (path) // path == 0 means that the tree must be only open, no nid // searched node = tree->getNode(path); else node = 0; - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("Cannot Open tree or find node: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); return 0; } id = getNodeId(node, path, tree, -1); - if (id == -1) { + if (id == -1) + { strcpy(errMsg, "NODE TABLE OVERFLOW"); return 0; } *nodeId = id; - } else // Remote connection + } + else // Remote connection { connId = getConnectionId(ipAddr, expName, shot); - if (connId == -1) { + if (connId == -1) + { strcpy(errMsg, "CANNOT CONNECT TO REMOTE TREE"); return 0; } id = getNodeId(0, path, 0, connId); - if (id == -1) { + if (id == -1) + { strcpy(errMsg, "NODE TABLE OVERFLOW"); return 0; } @@ -266,7 +295,8 @@ int openMds(char *expName, int shot, int isLocal, char *ipAddr, char *path, // *epicsTime, double *timing, char *errMsg) int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, int nVals, int dim1, int dim2, int dataIdx, double period, - double trigger, long epicsTime, char *errMsg, int debug) { + double trigger, long epicsTime, char *errMsg, int debug) +{ if (debug) printf("WriteMds: NodeId: %d, dtype: %d, nVals: %d, dim1: %d, dim2: %d\n, " "dataIdx: %d, epicsTime: %lX, period: %f, trigger: %f preTrigger " @@ -279,7 +309,8 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, char *path; int isLocal; updateNode(nodeId, &isLocal, &node, &conn, &path, &tree); - if (!node && !conn) { + if (!node && !conn) + { strcpy(errMsg, "Internal error: node ID not found"); return 0; } @@ -288,8 +319,10 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, // time is considered { Data *data; - if (dim1 == 0 && dim2 == 0) { - switch (dtype) { + if (dim1 == 0 && dim2 == 0) + { + switch (dtype) + { case DBF_CHAR: data = (Data *)new Int8(((char *)vals)[0]); break; @@ -321,8 +354,11 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, strcpy(errMsg, "Unsupported data type"); return 0; } - } else if (dim2 == 0) { - switch (dtype) { + } + else if (dim2 == 0) + { + switch (dtype) + { case DBF_CHAR: data = (Data *)new Int8Array((const char *)vals, dim1); break; @@ -351,11 +387,14 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, strcpy(errMsg, "Unsupported data type"); return 0; } - } else { + } + else + { int dims[2]; dims[0] = dim1; dims[1] = dim2; - switch (dtype) { + switch (dtype) + { case DBF_CHAR: data = (Data *)new Int8Array((char *)vals, 2, dims); break; @@ -385,52 +424,66 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, return 0; } } - if (isLocal) { - try { + if (isLocal) + { + try + { node->putRow(data, (int64_t *)&epicsTime); deleteData(data); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { strncpy(errMsg, exc.what(), 40); return 0; } - } else { + } + else + { char expr[256]; Int64 *timeData = new Int64((int64_t)epicsTime); sprintf(expr, "PutRow(\'%s\', 1000, $, $)", path); Data *args[2]; args[0] = timeData; args[1] = data; - try { + try + { Data *retData = conn->get(expr, args, 2); if (retData) deleteData(retData); deleteData(data); deleteData(timeData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { if (debug) printf("ERROR WRITING REMOTE TREE: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); return 0; } } - } else // Multiple samples: time is now derived from trigger, dataIds and - // period + } + else // Multiple samples: time is now derived from trigger, dataIds and + // period { int dims[3]; int nDims; dims[0] = nVals; if (dim1 == 0 && dim2 == 0) nDims = 1; - else if (dim2 == 0) { + else if (dim2 == 0) + { dims[1] = dim1; nDims = 2; - } else { + } + else + { dims[1] = dim1; dims[2] = dim2; nDims = 3; } Array *data; - switch (dtype) { + switch (dtype) + { case DBF_CHAR: data = new Int8Array((char *)vals, nDims, dims); break; @@ -463,17 +516,22 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, new Range(new Float64(trigger + period * dataIdx), new Float64(trigger + period * (dataIdx + nVals) - 0.05), new Float64(period)); - if (isLocal) { - try { + if (isLocal) + { + try + { node->makeSegment(start, end, times, data); deleteData(data); deleteData(times); deleteData(end); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { strncpy(errMsg, exc.what(), 40); return 0; } - } else // Remote connection + } + else // Remote connection { char expr[256]; sprintf(expr, "MakeSegment(\'%s\', $, $, MAKE_RANGE($, $, $), $, -1, %d)", @@ -486,7 +544,8 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, new Float64(trigger + period * (dataIdx + nVals) - 0.1 * period); args[4] = new Float64(period); args[5] = data; - try { + try + { Data *retData = conn->get(expr, args, 6); if (retData) deleteData(retData); @@ -496,7 +555,9 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, deleteData(args[3]); deleteData(args[4]); deleteData(end); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { if (debug) printf("ERROR WRITING REMOTE TREE: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); @@ -509,7 +570,8 @@ int writeMds(int nodeId, double *vals, int dtype, int preTriggerSamples, int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, int *bufDims, int *bufTypes, int maxRetElements, int retType, - void *retBuf, int *outElements, char *errMsg, int isLocal) { + void *retBuf, int *outElements, char *errMsg, int isLocal) +{ int i, retElSize, retElements, dummyLocal; TreeNode *node; Tree *tree; @@ -523,10 +585,14 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, // %d dim2: %d type2: %d\n", expr, treeIdx, nBuffers, maxRetElements, // bufDims[0], bufDims[1], bufTypes[0]); - try { - for (i = 0; i < nBuffers; i++) { - if (bufDims[i] > 1) { - switch (bufTypes[i]) { + try + { + for (i = 0; i < nBuffers; i++) + { + if (bufDims[i] > 1) + { + switch (bufTypes[i]) + { case DBF_CHAR: args[i] = new Int8Array((char *)buffers[i], bufDims[i]); break; @@ -552,8 +618,11 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, args[i] = new Float64Array((double *)buffers[i], bufDims[i]); break; } - } else { - switch (bufTypes[i]) { + } + else + { + switch (bufTypes[i]) + { case DBF_CHAR: args[i] = new Int8(*((char *)buffers[0])); break; @@ -584,12 +653,15 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, } } } - if (isLocal) { + if (isLocal) + { if (treeIdx != -1) // A Tree was defined, it must be restored { updateNode(treeIdx, &isLocal, &node, &conn, &currPath, &tree); - if (nBuffers > 0) { - switch (nBuffers) { + if (nBuffers > 0) + { + switch (nBuffers) + { case 1: evaluated = executeWithArgs(expr, tree, nBuffers, args[0]); break; @@ -623,12 +695,16 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, args[3], args[4], args[5], args[6], args[7]); break; } - } else + } + else evaluated = execute(expr, tree); - } else // no tree open + } + else // no tree open { - if (nBuffers > 0) { - switch (nBuffers) { + if (nBuffers > 0) + { + switch (nBuffers) + { case 1: evaluated = executeWithArgs(expr, nBuffers, args[0]); break; @@ -662,30 +738,36 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, args[3], args[4], args[5], args[6], args[7]); break; } - } else + } + else evaluated = execute(expr); } - } else // remote + } + else // remote { updateNode(treeIdx, &dummyLocal, &node, &conn, &currPath, &tree); // Retrieve connection - if (!conn) { + if (!conn) + { printf("Remote connection not established\n"); strcpy(errMsg, "Remote connection not established"); return 0; } - if (nBuffers > 0) { + if (nBuffers > 0) + { evaluated = conn->get(expr, args, nBuffers); // printf("Valuto : %s %s %d Risultato %s\n", expr, // args[0]->decompile(), nBuffers, evaluated->decompile()); - } else + } + else evaluated = conn->get(expr); } if (evaluated->getSize() == 1) // If scalar { retElements = 1; - switch (retType) { + switch (retType) + { case DBF_CHAR: case DBF_UCHAR: *((char *)retBuf) = evaluated->getByte(); @@ -704,16 +786,19 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, case DBF_DOUBLE: *((double *)retBuf) = evaluated->getDouble(); break; - case DBF_STRING: { + case DBF_STRING: + { char *retStr = evaluated->getString(); strcpy((char *)retBuf, retStr); delete[] retStr; break; } } - } else // Array + } + else // Array { - switch (retType) { + switch (retType) + { case DBF_CHAR: case DBF_UCHAR: currBuf = evaluated->getByteArray(&retElements); @@ -758,8 +843,9 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, deleteData(evaluated); for (i = 0; i < nBuffers; i++) deleteData(args[i]); - - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("ERROR WRITING REMOTE TREE: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); return 0; @@ -768,7 +854,8 @@ int evaluateExpr(char *expr, int treeIdx, int nBuffers, void **buffers, } int registerMdsEvent(char *eventName) { return addEvent(eventName); } -void waitMdsEvent(char *eventName, char *buf, int maxLen, int *retLen) { +void waitMdsEvent(char *eventName, char *buf, int maxLen, int *retLen) +{ size_t size; char *evBuf; @@ -783,18 +870,23 @@ void waitMdsEvent(char *eventName, char *buf, int maxLen, int *retLen) { sscanf(evStr.substr(colPos + 1).c_str(), "%d", &timeoutMs); } Event *event = getEvent((char *)evNameStr.c_str()); - if (!event) { + if (!event) + { printf("EVENT NOT FOUND!!!: %s\n", eventName); *retLen = 0; return; } - try { + try + { evBuf = (char *)event->waitRaw(&size, timeoutMs); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { size = 0; } - if (size > maxLen) { + if (size > maxLen) + { printf("Event buffer truncated from %d to %d bytes\n", size, maxLen); size = maxLen; } @@ -803,7 +895,8 @@ void waitMdsEvent(char *eventName, char *buf, int maxLen, int *retLen) { // delete[] evBuf; } -int doMdsAction(char *path, int nodeId, char *errMsg) { +int doMdsAction(char *path, int nodeId, char *errMsg) +{ TreeNode *node; Tree *tree; Connection *conn; @@ -813,31 +906,41 @@ int doMdsAction(char *path, int nodeId, char *errMsg) { sprintf(expr, "tcl(\'do %s\')", path); updateNode(nodeId, &isLocal, &node, &conn, &currPath, &tree); - if (!node && !conn) { + if (!node && !conn) + { strcpy(errMsg, "Internal error: node ID not found"); return 0; } // Build the data objects - if (isLocal) { - try { + if (isLocal) + { + try + { Data *data = compile(expr, node->getTree()); Data *resData = data->data(); // deleteData(data); // printf("Returned Data: %s\n", (resData)?resData->decompile():""); // if(resData) deleteData(resData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("ERROR EXECUTING ACTION: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); return 0; } - } else { - try { + } + else + { + try + { Data *resData = conn->get(expr); // printf("Returned Data: %s\n", (resData)?resData->decompile():""); if (resData) deleteData(resData); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { printf("ERROR EXECUTING REMOTE ACTION: %s\n", exc.what()); strncpy(errMsg, exc.what(), 40); return 0; diff --git a/epics/mdsrecords/mdsputRecord.c b/epics/mdsrecords/mdsputRecord.c index 3045b8d0db..c408a362cf 100644 --- a/epics/mdsrecords/mdsputRecord.c +++ b/epics/mdsrecords/mdsputRecord.c @@ -93,7 +93,8 @@ rset mdsputRSET = {RSETNUMBER, get_alarm_double}; epicsExportAddress(rset, mdsputRSET); -struct mpdset { /* mdsput dset */ +struct mpdset +{ /* mdsput dset */ long number; DEVSUPFUN dev_report; DEVSUPFUN init; @@ -106,36 +107,44 @@ static void monitor(mdsputRecord *); static long readValue(mdsputRecord *); static void checkAlarms(mdsputRecord *prec); -static long init_record(mdsputRecord *prec, int pass) { +static long init_record(mdsputRecord *prec, int pass) +{ struct mpdset *pdset; long status; - if (pass == 0) { + if (pass == 0) + { if (prec->nelm <= 0) prec->nelm = 1; if (prec->ftvl > DBF_ENUM) prec->ftvl = DBF_UCHAR; prec->bptr = callocMustSucceed(prec->nelm, dbValueSize(prec->ftvl), "mdsput calloc failed"); - if (prec->nelm == 1) { + if (prec->nelm == 1) + { prec->nord = 1; - } else { + } + else + { prec->nord = 0; } return 0; } /* wf.siml must be a CONSTANT or a PV_LINK or a DB_LINK */ - if (prec->siml.type == CONSTANT) { + if (prec->siml.type == CONSTANT) + { recGblInitConstantLink(&prec->siml, DBF_USHORT, &prec->simm); } /* must have dset defined */ - if (!(pdset = (struct mpdset *)(prec->dset))) { + if (!(pdset = (struct mpdset *)(prec->dset))) + { recGblRecordError(S_dev_noDSET, (void *)prec, "mp: init_record"); return S_dev_noDSET; } /* must have read_wf function defined */ - if ((pdset->number < 5) || (pdset->read_mp == NULL)) { + if ((pdset->number < 5) || (pdset->read_mp == NULL)) + { recGblRecordError(S_dev_missingSup, (void *)prec, "mp: init_record"); return S_dev_missingSup; } @@ -147,12 +156,14 @@ static long init_record(mdsputRecord *prec, int pass) { return status; } -static long process(mdsputRecord *prec) { +static long process(mdsputRecord *prec) +{ struct mpdset *pdset = (struct mpdset *)(prec->dset); long status; unsigned char pact = prec->pact; - if ((pdset == NULL) || (pdset->read_mp == NULL)) { + if ((pdset == NULL) || (pdset->read_mp == NULL)) + { prec->pact = TRUE; recGblRecordError(S_dev_missingSup, (void *)prec, "read_mp"); return S_dev_missingSup; @@ -180,7 +191,8 @@ static long process(mdsputRecord *prec) { return 0; } -static long cvt_dbaddr(DBADDR *paddr) { +static long cvt_dbaddr(DBADDR *paddr) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; paddr->pfield = prec->bptr; @@ -192,7 +204,8 @@ static long cvt_dbaddr(DBADDR *paddr) { return 0; } -static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) { +static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; *no_elements = prec->nord; @@ -201,7 +214,8 @@ static long get_array_info(DBADDR *paddr, long *no_elements, long *offset) { return 0; } -static long put_array_info(DBADDR *paddr, long nNew) { +static long put_array_info(DBADDR *paddr, long nNew) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; prec->nord = nNew; @@ -211,7 +225,8 @@ static long put_array_info(DBADDR *paddr, long nNew) { return 0; } -static long get_units(DBADDR *paddr, char *units) { +static long get_units(DBADDR *paddr, char *units) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; strncpy(units, prec->egu, DB_UNITS_SIZE); @@ -219,7 +234,8 @@ static long get_units(DBADDR *paddr, char *units) { return 0; } -static long get_precision(DBADDR *paddr, long *precision) { +static long get_precision(DBADDR *paddr, long *precision) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; int fieldIndex = dbGetFieldIndex(paddr); @@ -231,29 +247,36 @@ static long get_precision(DBADDR *paddr, long *precision) { return 0; } -static long get_graphic_double(DBADDR *paddr, struct dbr_grDouble *pgd) { +static long get_graphic_double(DBADDR *paddr, struct dbr_grDouble *pgd) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; - if (dbGetFieldIndex(paddr) == mdsputRecordVAL) { + if (dbGetFieldIndex(paddr) == mdsputRecordVAL) + { pgd->upper_disp_limit = prec->hopr; pgd->lower_disp_limit = prec->lopr; - } else + } + else recGblGetGraphicDouble(paddr, pgd); return 0; } -static long get_control_double(DBADDR *paddr, struct dbr_ctrlDouble *pcd) { +static long get_control_double(DBADDR *paddr, struct dbr_ctrlDouble *pcd) +{ mdsputRecord *prec = (mdsputRecord *)paddr->precord; - if (dbGetFieldIndex(paddr) == mdsputRecordVAL) { + if (dbGetFieldIndex(paddr) == mdsputRecordVAL) + { pcd->upper_ctrl_limit = prec->hopr; pcd->lower_ctrl_limit = prec->lopr; - } else + } + else recGblGetControlDouble(paddr, pcd); return 0; } -static void monitor(mdsputRecord *prec) { +static void monitor(mdsputRecord *prec) +{ unsigned short monitor_mask = 0; unsigned int hash = 0; @@ -266,12 +289,14 @@ static void monitor(mdsputRecord *prec) { /* Calculate hash if we are interested in OnChange events. */ if ((prec->mpst == mdsputPOST_OnChange) || - (prec->apst == mdsputPOST_OnChange)) { + (prec->apst == mdsputPOST_OnChange)) + { hash = epicsMemHash((char *)prec->bptr, prec->nord * dbValueSize(prec->ftvl), 0); /* Only post OnChange values if the hash is different. */ - if (hash != prec->hash) { + if (hash != prec->hash) + { if (prec->mpst == mdsputPOST_OnChange) monitor_mask |= DBE_VALUE; if (prec->apst == mdsputPOST_OnChange) @@ -284,16 +309,19 @@ static void monitor(mdsputRecord *prec) { } } - if (monitor_mask) { + if (monitor_mask) + { db_post_events(prec, prec->bptr, monitor_mask); } } -static long readValue(mdsputRecord *prec) { +static long readValue(mdsputRecord *prec) +{ long status; struct mpdset *pdset = (struct mpdset *)prec->dset; - if (prec->pact == TRUE) { + if (prec->pact == TRUE) + { return (*pdset->read_mp)(prec); } @@ -301,20 +329,25 @@ static long readValue(mdsputRecord *prec) { if (status) return status; - if (prec->simm == menuYesNoNO) { + if (prec->simm == menuYesNoNO) + { return (*pdset->read_mp)(prec); } - if (prec->simm == menuYesNoYES) { + if (prec->simm == menuYesNoYES) + { long nRequest = prec->nelm; status = dbGetLink(&(prec->siol), prec->ftvl, prec->bptr, 0, &nRequest); /* nord set only for db links: needed for old db_access */ - if (prec->siol.type != CONSTANT) { + if (prec->siol.type != CONSTANT) + { prec->nord = nRequest; if (status == 0) prec->udf = FALSE; } - } else { + } + else + { recGblSetSevr(prec, SOFT_ALARM, INVALID_ALARM); return -1; } @@ -323,10 +356,12 @@ static long readValue(mdsputRecord *prec) { return status; } -static void checkAlarms(mdsputRecord *prec) { +static void checkAlarms(mdsputRecord *prec) +{ int status = prec->errs; - if (prec->udf == TRUE) { + if (prec->udf == TRUE) + { recGblSetSevr(prec, UDF_ALARM, INVALID_ALARM); return; } diff --git a/examples/demoadc/DemoAdc.c b/examples/demoadc/DemoAdc.c index bb1314b47c..2b37aa97fb 100644 --- a/examples/demoadc/DemoAdc.c +++ b/examples/demoadc/DemoAdc.c @@ -55,13 +55,16 @@ static double frequency; static int pts; static int confOk; // Return 0 if succesful, -1 if any argument is not correct -int initialize(char *name, int clockFreq, int postTriggerSamples) { +int initialize(char *name, int clockFreq, int postTriggerSamples) +{ printf("INITIALIZE: %s\t%d\t%d\n", name, clockFreq, postTriggerSamples); - if (postTriggerSamples < 0 || postTriggerSamples >= totSamples) { + if (postTriggerSamples < 0 || postTriggerSamples >= totSamples) + { confOk = 0; return -1; } - switch (clockFreq) { + switch (clockFreq) + { case 1: frequency = 1000; break; @@ -85,12 +88,14 @@ int initialize(char *name, int clockFreq, int postTriggerSamples) { return 1; } -int acquire(char *name, short *c1, short *c2, short *c3, short *c4) { +int acquire(char *name, short *c1, short *c2, short *c3, short *c4) +{ int i; // it is assumed that c1,c2,c3,c4 arrays have totSamples elements if (!confOk) return -1; - for (i = 0; i < totSamples; i++) { + for (i = 0; i < totSamples; i++) + { c1[i] = (short)(sin(2 * PI * 10 * i / frequency) * 32767); c2[i] = (short)(sin(2 * PI * 50 * i / frequency) * 32767); c3[i] = (short)(sin(2 * PI * 100 * i / frequency) * 32767); diff --git a/hdf5/MDSplus2HDF5.c b/hdf5/MDSplus2HDF5.c index 62a3e069ee..d3a9e11143 100644 --- a/hdf5/MDSplus2HDF5.c +++ b/hdf5/MDSplus2HDF5.c @@ -72,7 +72,8 @@ static int shot; trouble reading in files with an attribute called _name in them. Hence the descision to put the '_' at the end. */ -static char *MemberMangle(char *name) { +static char *MemberMangle(char *name) +{ static char ans[MAX_TREENAME + 2]; ans[0] = 0; strcpy(ans, name); @@ -89,7 +90,8 @@ static char *MemberMangle(char *name) { case of MDSplus complex data structures we are adding a group, so a '.' is more appropriate. */ -static char *ChildMangle(char *name) { +static char *ChildMangle(char *name) +{ static char ans[MAX_TREENAME + 2]; ans[0] = '.'; ans[1] = 0; @@ -107,19 +109,22 @@ static char *ChildMangle(char *name) { Will return any integer answer, and zero for all other cases. */ -static int GetNidNCI(int nid, char *expr) { +static int GetNidNCI(int nid, char *expr) +{ int status; int ans = 0; static EMPTYXD(ans_xd); DESCRIPTOR_NID(nid_dsc, &nid); DESCRIPTOR_FROM_CSTRING(getnci, expr); status = TdiExecute(&getnci, &nid_dsc, &ans_xd MDS_END_ARG); - if (status & 1) { + if (status & 1) + { struct descriptor *d_ptr; for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; d_ptr = (struct descriptor *)d_ptr->pointer) ; - switch (d_ptr->dtype) { + switch (d_ptr->dtype) + { case DTYPE_NID: case DTYPE_L: ans = *(int *)d_ptr->pointer; @@ -143,7 +148,8 @@ static int GetNidNCI(int nid, char *expr) { ans = 0; break; } - } else + } + else ans = 0; return (ans); } @@ -153,11 +159,13 @@ static int GetNidNCI(int nid, char *expr) { */ static int FirstChild(int nid) { return (GetNidNCI(nid, "GETNCI($,'child')")); } -static int FirstMember(int nid) { +static int FirstMember(int nid) +{ return (GetNidNCI(nid, "GETNCI($,'member')")); } -static int NextSibling(int nid) { +static int NextSibling(int nid) +{ return (GetNidNCI(nid, "GETNCI($,'brother')")); } @@ -183,55 +191,70 @@ static int GetNidInt(int nid, char *expr) { return (GetNidNCI(nid, expr)); } String answer from expression or "" if error or non string type. */ -static char *GetNidString(int nid, char *expr) { +static char *GetNidString(int nid, char *expr) +{ DESCRIPTOR_NID(nid_dsc, &nid); DESCRIPTOR_FROM_CSTRING(expr_d, expr); static EMPTYXD(ans_xd); int status; status = TdiExecute(&expr_d, &nid_dsc, &ans_xd MDS_END_ARG); - if (status & 1) { + if (status & 1) + { struct descriptor *d_ptr; for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; d_ptr = (struct descriptor *)d_ptr->pointer) ; - if (d_ptr->dtype == DTYPE_T) { + if (d_ptr->dtype == DTYPE_T) + { d_ptr->pointer[d_ptr->length] = 0; return (char *)d_ptr->pointer; - } else + } + else return (""); - } else + } + else return (""); } -static int has_descendants(int nid) { +static int has_descendants(int nid) +{ return (GetNidInt(nid, "GETNCI($, 'NUMBER_OF_CHILDREN')") + GetNidInt(nid, "GETNCI($, 'NUMBER_OF_MEMBERS')") != 0); } -static int is_child(int nid) { +static int is_child(int nid) +{ int ans; - if (nid == 0) { + if (nid == 0) + { ans = 1; - } else { + } + else + { ans = GetNidInt(nid, "GETNCI($, 'is_child')"); } return ans; } -void ExitOnMDSError(int status, const char *msg) { - if (!(status & 1)) { +void ExitOnMDSError(int status, const char *msg) +{ + if (!(status & 1)) + { fprintf(stderr, "MDS Error\n%s\n%s\n", msg, MdsGetMsg(status)); exit(0); } } -static void usage(const char *cmd) { +static void usage(const char *cmd) +{ fprintf(stderr, "Usage %s tree shot\n", cmd); } -static void parse_cmdline(int argc, const char *argv[]) { - if (argc < 3) { +static void parse_cmdline(int argc, const char *argv[]) +{ + if (argc < 3) + { usage(argv[0]); exit(0); } @@ -239,21 +262,25 @@ static void parse_cmdline(int argc, const char *argv[]) { shot = strtol(argv[2], NULL, 0); } -static hid_t CreateHDF5(char *tree, int shot) { +static hid_t CreateHDF5(char *tree, int shot) +{ hid_t file_id; char filename[MAX_FILENAME]; sprintf(filename, "%s_%d.h5", tree, shot); file_id = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); - if (file_id < 0) { + if (file_id < 0) + { fprintf(stderr, "error creating HDF5 file %s\n", filename); exit(0); } return (file_id); } -hid_t MdsType2HDF5Type(unsigned char type) { - switch (type) { +hid_t MdsType2HDF5Type(unsigned char type) +{ + switch (type) + { case DTYPE_FS: return (H5T_NATIVE_FLOAT); case DTYPE_FT: @@ -276,24 +303,29 @@ hid_t MdsType2HDF5Type(unsigned char type) { return (0); } -static void PutNumeric(hid_t parent, char *name, struct descriptor *dsc) { +static void PutNumeric(hid_t parent, char *name, struct descriptor *dsc) +{ // herr_t status; hid_t type = MdsType2HDF5Type(dsc->dtype); - if (type != 0) { + if (type != 0) + { hid_t ds_id = H5Screate(H5S_SCALAR); hid_t a_id = H5Acreate(parent, name, MdsType2HDF5Type(dsc->dtype), ds_id, H5P_DEFAULT); - if (a_id < 0) { + if (a_id < 0) + { char *new_name = MemberMangle(name); a_id = H5Acreate(parent, new_name, MdsType2HDF5Type(dsc->dtype), ds_id, H5P_DEFAULT); } - if (a_id > 0) { + if (a_id > 0) + { // status = H5Awrite(a_id, MdsType2HDF5Type(dsc->dtype), // dsc->pointer); H5Awrite(a_id, MdsType2HDF5Type(dsc->dtype), dsc->pointer); H5Aclose(a_id); - } else + } + else fprintf(stderr, "could not create attribute to store scalar in %s\n", name); } @@ -301,7 +333,8 @@ static void PutNumeric(hid_t parent, char *name, struct descriptor *dsc) { typedef ARRAY_COEFF(char, MAX_DIMS) ARRAY_AC; -static void PutArray(hid_t parent, char *name, struct descriptor *dsc) { +static void PutArray(hid_t parent, char *name, struct descriptor *dsc) +{ int j; // herr_t status; struct descriptor_a *adsc = (struct descriptor_a *)dsc; @@ -311,54 +344,69 @@ static void PutArray(hid_t parent, char *name, struct descriptor *dsc) { int rank = adsc->dimct; hsize_t dim[MAX_DIMS]; hid_t dtype = MdsType2HDF5Type(dsc->dtype); - if (dtype > 0) { - if (adsc->aflags.coeff) { - for (j = 0; j < rank; j++) { + if (dtype > 0) + { + if (adsc->aflags.coeff) + { + for (j = 0; j < rank; j++) + { dim[j] = ac_dsc->m[adsc->dimct - j - 1]; } - } else { + } + else + { rank = 1; dim[0] = adsc->arsize / adsc->length; } space_id = H5Screate_simple(rank, dim, NULL); ds_id = H5Dcreate(parent, name, dtype, space_id, H5P_DEFAULT); - if (ds_id < 0) { + if (ds_id < 0) + { char *new_name = MemberMangle(name); ds_id = H5Acreate(parent, new_name, MdsType2HDF5Type(dsc->dtype), ds_id, H5P_DEFAULT); } - if (ds_id > 0) { + if (ds_id > 0) + { // status = H5Dwrite(ds_id, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, // dsc->pointer); H5Dwrite(ds_id, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, dsc->pointer); H5Dclose(ds_id); H5Sclose(space_id); - } else + } + else fprintf(stderr, "could not create atribute to store array in %s\n", name); } } -static void PutScalar(hid_t parent, char *name, struct descriptor *dsc) { - switch (dsc->dtype) { +static void PutScalar(hid_t parent, char *name, struct descriptor *dsc) +{ + switch (dsc->dtype) + { case DTYPE_T: - if (dsc->length > 0) { + if (dsc->length > 0) + { // herr_t status; hid_t ds_id = H5Screate(H5S_SCALAR); hsize_t size = dsc->length; hid_t type = H5Tcopy(H5T_C_S1); H5Tset_size(type, size); hid_t a_id = H5Acreate(parent, name, type, ds_id, H5P_DEFAULT); - if (a_id < 0) { + if (a_id < 0) + { char *new_name = MemberMangle(name); a_id = H5Acreate(parent, new_name, MdsType2HDF5Type(dsc->dtype), ds_id, H5P_DEFAULT); } - if (a_id > 0) { + if (a_id > 0) + { // status = H5Awrite(a_id, type, dsc->pointer); // status = H5Aclose(a_id); H5Awrite(a_id, type, dsc->pointer); H5Aclose(a_id); - } else { + } + else + { fprintf(stderr, "could not create attribute called %s\n", name); } // status = H5Sclose(ds_id); @@ -375,7 +423,8 @@ static void PutScalar(hid_t parent, char *name, struct descriptor *dsc) { typedef RECORD(MAX_DESCRS) RDSC; -static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { +static void WriteData(hid_t parent, char *name, struct descriptor *dsc) +{ struct descriptor_xd *xd = (struct descriptor_xd *)dsc; int status; @@ -392,7 +441,8 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { for (d_ptr = (struct descriptor *)xd; d_ptr->dtype == DTYPE_DSC; d_ptr = (struct descriptor *)d_ptr->pointer) ; - switch (d_ptr->class) { + switch (d_ptr->class) + { case CLASS_S: case CLASS_D: PutScalar(parent, name, d_ptr); @@ -400,12 +450,15 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { case CLASS_A: PutArray(parent, name, d_ptr); break; - case CLASS_CA: { + case CLASS_CA: + { static EMPTYXD(xd3); status = TdiEvaluate(d_ptr, &xd3 MDS_END_ARG); - if (status & 1) { + if (status & 1) + { status = TdiData((struct descriptor *)&xd3, &xd3 MDS_END_ARG); - if (status & 1) { + if (status & 1) + { for (d_ptr = (struct descriptor *)&xd3; d_ptr->dtype == DTYPE_DSC; d_ptr = (struct descriptor *)d_ptr->pointer) ; @@ -413,48 +466,61 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { PutArray(parent, name, d_ptr); } } - } break; - case CLASS_R: { + } + break; + case CLASS_R: + { RDSC *r_ptr = (RDSC *)d_ptr; - switch (d_ptr->dtype) { - case DTYPE_SIGNAL: { + switch (d_ptr->dtype) + { + case DTYPE_SIGNAL: + { int i; hid_t g_id; g_id = H5Gcreate(parent, name, 0); - if (g_id < 0) { + if (g_id < 0) + { char *new_name = ChildMangle(name); g_id = H5Gcreate(parent, new_name, 0); } - if (g_id > 0) { + if (g_id > 0) + { WriteData(g_id, "data", r_ptr->dscptrs[0]); WriteData(g_id, "raw", r_ptr->dscptrs[1]); - for (i = 2; i < r_ptr->ndesc; i++) { + for (i = 2; i < r_ptr->ndesc; i++) + { char name[8]; sprintf(name, "dim%1.1d", i - 2); WriteData(g_id, name, r_ptr->dscptrs[i]); } - } else + } + else fprintf(stderr, "could not create group for signal components of %s \n", name); break; } - case DTYPE_WITH_UNITS: { + case DTYPE_WITH_UNITS: + { hid_t g_id; g_id = H5Gcreate(parent, name, 0); - if (g_id < 0) { + if (g_id < 0) + { char *new_name = ChildMangle(name); g_id = H5Gcreate(parent, new_name, 0); } - if (g_id > 0) { + if (g_id > 0) + { WriteData(g_id, "data", r_ptr->dscptrs[0]); WriteData(g_id, "units", r_ptr->dscptrs[1]); - } else + } + else fprintf(stderr, "could not create group for with_units components of %s \n", name); break; } - default: { + default: + { // static EMPTYXD(xd2); // status = TdiData(d_ptr, &xd2); // if (status & 1) @@ -484,12 +550,14 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { recursively expanded into the HDF5 file as small groups. (Signals and With_units) */ -static void WriteDataNID(hid_t parent, char *name, int nid) { +static void WriteDataNID(hid_t parent, char *name, int nid) +{ static EMPTYXD(xd); DESCRIPTOR_NID(nid_dsc, &nid); int status; status = TdiEvaluate(&nid_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (status & 1) + { WriteData(parent, name, (struct descriptor *)&xd); } } @@ -511,7 +579,8 @@ static void WriteDataNID(hid_t parent, char *name, int nid) { the end, this may prove akward, and could be replaced by a name mangling which is only done when needed. */ -static void AddBranch(int nid, hid_t parent_id) { +static void AddBranch(int nid, hid_t parent_id) +{ int mem_nid; int child_nid; hid_t g_id = 0; @@ -526,42 +595,53 @@ static void AddBranch(int nid, hid_t parent_id) { _is_child = is_child(nid); _has_descendants = has_descendants(nid); - if (_is_child || _has_descendants) { + if (_is_child || _has_descendants) + { g_id = H5Gcreate(parent_id, name, 0); /* if it fails assume it was because the name was already taken. Since the members are added first, tack a '.' in the front. */ - if (g_id < 0) { + if (g_id < 0) + { char *child_name = ChildMangle(name); g_id = H5Gcreate(parent_id, child_name, 0); } - if (g_id >= 0) { + if (g_id >= 0) + { for (mem_nid = FirstMember(nid); mem_nid; - mem_nid = NextSibling(mem_nid)) { + mem_nid = NextSibling(mem_nid)) + { AddBranch(mem_nid, g_id); } for (child_nid = FirstChild(nid); child_nid; - child_nid = NextSibling(child_nid)) { + child_nid = NextSibling(child_nid)) + { AddBranch(child_nid, g_id); } - } else { + } + else + { fprintf(stderr, "Error adding HDF5 Group for %s\n", name); } } - if (!_is_child) { - if (_has_descendants) { + if (!_is_child) + { + if (_has_descendants) + { char *member_name = MemberMangle(name); WriteDataNID(parent_id, member_name, nid); - } else + } + else WriteDataNID(parent_id, name, nid); } if (_is_child || _has_descendants) H5Gclose(g_id); } -int main(int argc, const char *argv[]) { +int main(int argc, const char *argv[]) +{ hid_t file_id; parse_cmdline(argc, argv); ExitOnMDSError(TreeOpen(tree, shot, 0), "Error opening tree"); diff --git a/hdf5/dynhdf5.c b/hdf5/dynhdf5.c index a531b4e3f5..d94eaadcbb 100644 --- a/hdf5/dynhdf5.c +++ b/hdf5/dynhdf5.c @@ -73,18 +73,22 @@ static int Initialized = 0; #define Find(name) name##_dyn = FindSymbol(#name) #define FindGlobal(name) name = (hid_t)FindSymbol(#name) -static void *FindSymbol(char *name) { +static void *FindSymbol(char *name) +{ void *rtn = NULL; int status = LibFindImageSymbol_C("hdf5", name, &rtn); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Error activating hdf5 shared library\n"); exit(1); } return rtn; } -static void Initialize() { - if (!Initialized) { +static void Initialize() +{ + if (!Initialized) + { Find(H5Aclose); Find(H5Aget_space); Find(H5Aget_type); @@ -132,15 +136,18 @@ hid_t H5Aget_space(hid_t attr_id) { return (H5Aget_space_dyn)(attr_id); } hid_t H5Aget_type(hid_t attr_id) { return (H5Aget_type_dyn)(attr_id); } herr_t H5Aiterate(hid_t loc_id, unsigned *attr_num, H5A_operator_t op, - void *op_data) { + void *op_data) +{ return (H5Aiterate_dyn)(loc_id, attr_num, op, op_data); } -hid_t H5Aopen_name(hid_t loc_id, const char *name) { +hid_t H5Aopen_name(hid_t loc_id, const char *name) +{ return (H5Aopen_name_dyn)(loc_id, name); } -herr_t H5Aread(hid_t attr_id, hid_t type_id, void *buf) { +herr_t H5Aread(hid_t attr_id, hid_t type_id, void *buf) +{ Initialize(); return (H5Aread_dyn)(attr_id, type_id, buf); } @@ -151,43 +158,51 @@ hid_t H5Dget_space(hid_t dset_id) { return (H5Dget_space_dyn)(dset_id); } hid_t H5Dget_type(hid_t dset_id) { return (H5Dget_type_dyn)(dset_id); } -hid_t H5Dopen(hid_t file_id, const char *name) { +hid_t H5Dopen(hid_t file_id, const char *name) +{ return (H5Dopen_dyn)(file_id, name); } herr_t H5Dread(hid_t dset_id, hid_t mem_type, hid_t mem_space_id, - hid_t file_space_id, hid_t plist_id, void *buf) { + hid_t file_space_id, hid_t plist_id, void *buf) +{ return (H5Dread_dyn)(dset_id, mem_type, mem_space_id, file_space_id, plist_id, buf); } -herr_t H5Eget_auto(H5E_auto_t *func, void **client_data) { +herr_t H5Eget_auto(H5E_auto_t *func, void **client_data) +{ Initialize(); return (H5Eget_auto_dyn)(func, client_data); } -herr_t H5Eset_auto(H5E_auto_t func, void *client_data) { +herr_t H5Eset_auto(H5E_auto_t func, void *client_data) +{ Initialize(); return (H5Eset_auto_dyn)(func, client_data); } herr_t H5Gget_objinfo(hid_t loc_id, const char *name, hbool_t follow_link, - H5G_stat_t *statbuf) { + H5G_stat_t *statbuf) +{ return (H5Gget_objinfo_dyn)(loc_id, name, follow_link, statbuf); } -hid_t H5Gopen(hid_t loc_id, const char *name) { +hid_t H5Gopen(hid_t loc_id, const char *name) +{ return (H5Gopen_dyn)(loc_id, name); } herr_t H5Gclose(hid_t group) { return (H5Gclose_dyn)(group); } herr_t H5Giterate(hid_t loc_id, const char *name, int *idx, H5G_iterate_t op, - void *op_data) { + void *op_data) +{ return (H5Giterate_dyn)(loc_id, name, idx, op, op_data); } -hid_t H5Fopen(const char *filename, unsigned flags, hid_t access_plist) { +hid_t H5Fopen(const char *filename, unsigned flags, hid_t access_plist) +{ Initialize(); return (H5Fopen_dyn)(filename, flags, access_plist); } @@ -197,7 +212,8 @@ hid_t H5Fclose(hid_t fid) { return (H5Fclose_dyn)(fid); } herr_t H5Sclose(hid_t attr_id) { return (H5Sclose_dyn)(attr_id); } int H5Sget_simple_extent_dims(hid_t space_id, hsize_t dims[], - hsize_t maxdims[]) { + hsize_t maxdims[]) +{ return (H5Sget_simple_extent_dims_dyn)(space_id, dims, maxdims); } @@ -205,13 +221,15 @@ hid_t H5Tclose(hid_t type_id) { return (H5Tclose_dyn)(type_id); } H5T_class_t H5Tget_class(hid_t type_id) { return (H5Tget_class_dyn)(type_id); } -size_t H5Tget_precision(hid_t type_id) { +size_t H5Tget_precision(hid_t type_id) +{ return (H5Tget_precision_dyn)(type_id); } H5T_sign_t H5Tget_sign(hid_t type_id) { return (H5Tget_sign_dyn)(type_id); } -herr_t H5open(void) { +herr_t H5open(void) +{ Initialize(); return (H5open_dyn)(); } diff --git a/hdf5/hdf5ToMds.c b/hdf5/hdf5ToMds.c index d20e27c726..b5d44d045a 100644 --- a/hdf5/hdf5ToMds.c +++ b/hdf5/hdf5ToMds.c @@ -37,13 +37,16 @@ static int d_status = EXIT_SUCCESS; static const char *tree = 0; static const char *shot = 0; -static void usage(const char *prog) { +static void usage(const char *prog) +{ fflush(stdout); fprintf(stdout, "usage: %s file tree shot\n", prog); } -static void parse_command_line(int argc, const char *argv[]) { - if (argc < 4) { +static void parse_command_line(int argc, const char *argv[]) +{ + if (argc < 4) + { usage(argv[0]); exit(1); } @@ -52,7 +55,8 @@ static void parse_command_line(int argc, const char *argv[]) { shot = argv[3]; } -static int AddNode(const char *h5name, int usage) { +static int AddNode(const char *h5name, int usage) +{ /******************************************************** HDF5 datasets do not have restrictions on names whereas @@ -85,38 +89,53 @@ static int AddNode(const char *h5name, int usage) { else strcat(name, &h5name[i]); len = strlen(name); - if (len > 13) { + if (len > 13) + { name[13] = 0; len = 13; } - for (i = 1; i < len; i++) { + for (i = 1; i < len; i++) + { name[i] = toupper(name[i]); if ((name[i] < 'A' || name[i] > 'Z') && (name[i] < '0' || name[i] > '9') && (name[i] != '_')) name[i] = '_'; } status = TreeAddNode(name, &nid, usage); - while (status == TreeALREADY_THERE) { - if (len < 13) { + while (status == TreeALREADY_THERE) + { + if (len < 13) + { for (; len < 13; len++) name[len] = '0'; name[len - 1] = '1'; name[len] = 0; - } else if (idx < 10) { + } + else if (idx < 10) + { name[len - 1] = '0' + idx++; - } else if (idx < 100) { + } + else if (idx < 100) + { sprintf(&name[len - 2], "%2d", idx++); - } else if (idx < 1000) { + } + else if (idx < 1000) + { sprintf(&name[len - 3], "%3d", idx++); - } else if (idx < 10000) { + } + else if (idx < 10000) + { sprintf(&name[len - 4], "%4d", idx++); - } else { + } + else + { printf("Can't make unique node name\n"); exit(EXIT_FAILURE); } status = TreeAddNode(name, &nid, usage); } - if (status & 1) { + if (status & 1) + { int old; int name_nid; int set_flags = NciM_COMPRESS_ON_PUT; @@ -137,21 +156,25 @@ static int AddNode(const char *h5name, int usage) { } static void PutArray(int nid, char dtype, int size, int n_dims, hsize_t *dims, - void *ptr) { + void *ptr) +{ /*************************************************** Store array of data into MDSplus node. Use simple array descriptor for one dimensional arrays and a coefficient array descriptor for multi-dimensional arrays. ***************************************************/ - if (n_dims == 1) { + if (n_dims == 1) + { DESCRIPTOR_A(dsc, 0, 0, 0, 0); dsc.length = size; dsc.dtype = dtype; dsc.pointer = ptr; dsc.arsize = (int)dims[0] * size; TreePutRecord(nid, (struct descriptor *)&dsc, 0); - } else { + } + else + { int i; DESCRIPTOR_A_COEFF(dsc, 0, 0, 0, 8, 0); dsc.length = size; @@ -160,7 +183,8 @@ static void PutArray(int nid, char dtype, int size, int n_dims, hsize_t *dims, dsc.arsize = size; dsc.dimct = n_dims; dsc.a0 = ptr; - for (i = 0; i < n_dims; i++) { + for (i = 0; i < n_dims; i++) + { dsc.m[i] = (int)dims[i]; dsc.arsize *= (int)dims[i]; } @@ -168,7 +192,8 @@ static void PutArray(int nid, char dtype, int size, int n_dims, hsize_t *dims, } } -static void PutScalar(int nid, char dtype, int size, void *ptr) { +static void PutScalar(int nid, char dtype, int size, void *ptr) +{ /********************************************** Store scalar data in MDSplus node **********************************************/ @@ -180,13 +205,15 @@ static void PutScalar(int nid, char dtype, int size, void *ptr) { } static void PutData(hid_t obj, int nid, char dtype, int htype, int size, - int n_dims, hsize_t *dims, int is_attr) { + int n_dims, hsize_t *dims, int is_attr) +{ /********************************************* Read data from HDF5 file using H5Aread for attributes and H5Dread for datasets. Load the data into MDSplus nodes. *********************************************/ - if (dtype) { + if (dtype) + { char *mem; int array_size = 1; int i; @@ -206,13 +233,15 @@ static void PutData(hid_t obj, int nid, char dtype, int htype, int size, } static int mds_find_attr(hid_t attr_id, const char *name, - void *op_data __attribute__((unused))) { + void *op_data __attribute__((unused))) +{ hid_t obj, type; int nid; int oldnid; printf("\tmds_find_attr - %s\n", name); TreeGetDefaultNid(&oldnid); - if ((obj = H5Aopen_name(attr_id, name)) >= 0) { + if ((obj = H5Aopen_name(attr_id, name)) >= 0) + { int size; char dtype; int htype; @@ -223,8 +252,10 @@ static int mds_find_attr(hid_t attr_id, const char *name, size_t precision; H5Sclose(space); type = H5Aget_type(obj); - switch (H5Tget_class(type)) { - case H5T_COMPOUND: { + switch (H5Tget_class(type)) + { + case H5T_COMPOUND: + { printf("Compound data is not supported, skipping\n"); break; } @@ -233,7 +264,8 @@ static int mds_find_attr(hid_t attr_id, const char *name, precision = H5Tget_precision(type); is_signed = (H5Tget_sign(type) != H5T_SGN_NONE); size = precision / 8; - switch (precision) { + switch (precision) + { case 8: dtype = is_signed ? DTYPE_B : DTYPE_BU; htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR; @@ -261,7 +293,8 @@ static int mds_find_attr(hid_t attr_id, const char *name, nid = AddNode(name, TreeUSAGE_NUMERIC); precision = H5Tget_precision(type); size = precision / 8; - switch (precision) { + switch (precision) + { case 32: dtype = DTYPE_NATIVE_FLOAT; htype = H5T_NATIVE_FLOAT; @@ -285,23 +318,30 @@ static int mds_find_attr(hid_t attr_id, const char *name, { int slen = H5Tget_size(type); // int siz = slen; - if (slen < 0) { + if (slen < 0) + { printf("Badly formed string attribute\n"); - } else { + } + else + { hid_t st_id; #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 - if (H5Tis_variable_str(type)) { + if (H5Tis_variable_str(type)) + { st_id = H5Tcopy(H5T_C_S1); H5Tset_size(st_id, H5T_VARIABLE); - } else { + } + else + { #endif st_id = H5Tcopy(type); H5Tset_cset(st_id, H5T_CSET_ASCII); #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 } #endif - if ((int)H5Tget_size(st_id) > slen) { + if ((int)H5Tget_size(st_id) > slen) + { slen = H5Tget_size(st_id); } H5Tset_size(st_id, slen); @@ -344,22 +384,26 @@ static int mds_find_attr(hid_t attr_id, const char *name, return 0; } -static int mds_find_objs(hid_t group, const char *name, void *op_data) { +static int mds_find_objs(hid_t group, const char *name, void *op_data) +{ hid_t obj, type; H5G_stat_t statbuf; int nid; int defnid; int *first_time = (int *)op_data; TreeGetDefaultNid(&defnid); - if (*first_time) { + if (*first_time) + { // H5Aiterate(group,&idx,mds_find_attr,(void *)0); H5Aiterate(group, NULL, mds_find_attr, (void *)0); *first_time = 0; } H5Gget_objinfo(group, name, 1, &statbuf); - switch (statbuf.type) { + switch (statbuf.type) + { case H5G_GROUP: - if ((obj = H5Gopen(group, name)) >= 0) { + if ((obj = H5Gopen(group, name)) >= 0) + { int first_time = 1; nid = AddNode(name, TreeUSAGE_STRUCTURE); H5Giterate(obj, ".", NULL, mds_find_objs, (void *)&first_time); @@ -367,7 +411,8 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { } break; case H5G_DATASET: - if ((obj = H5Dopen(group, name)) >= 0) { + if ((obj = H5Dopen(group, name)) >= 0) + { int size; char dtype; int htype; @@ -382,8 +427,10 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { // H5Aiterate(obj,&idx,mds_find_attr,(void *)0); H5Aiterate(obj, NULL, mds_find_attr, (void *)0); type = H5Dget_type(obj); - switch (H5Tget_class(type)) { - case H5T_COMPOUND: { + switch (H5Tget_class(type)) + { + case H5T_COMPOUND: + { printf("Compound data is not supported, skipping\n"); break; } @@ -391,7 +438,8 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { precision = H5Tget_precision(type); is_signed = (H5Tget_sign(type) != H5T_SGN_NONE); size = precision / 8; - switch (precision) { + switch (precision) + { case 8: dtype = is_signed ? DTYPE_B : DTYPE_BU; htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR; @@ -418,7 +466,8 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { case H5T_FLOAT: precision = H5Tget_precision(type); size = precision / 8; - switch (precision) { + switch (precision) + { case 32: dtype = DTYPE_NATIVE_FLOAT; htype = H5T_NATIVE_FLOAT; @@ -437,30 +486,37 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { case H5T_TIME: printf("dataset is time ---- UNSUPPORTED\n"); break; - case H5T_STRING: { + case H5T_STRING: + { int slen = H5Tget_size(type); hid_t st_id; - if (slen < 0) { + if (slen < 0) + { printf("Badly formed string attribute\n"); return 0; } #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 - if (H5Tis_variable_str(type)) { + if (H5Tis_variable_str(type)) + { st_id = H5Tcopy(H5T_C_S1); H5Tset_size(st_id, H5T_VARIABLE); - } else { + } + else + { #endif st_id = H5Tcopy(type); H5Tset_cset(st_id, H5T_CSET_ASCII); #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 } #endif - if ((int)H5Tget_size(st_id) > slen) { + if ((int)H5Tget_size(st_id) > slen) + { slen = H5Tget_size(st_id); } H5Tset_size(st_id, slen); PutData(obj, nid, DTYPE_T, st_id, slen, n_ds_dims, ds_dims, 0); - } break; + } + break; case H5T_BITFIELD: printf("dataset is bitfield ---- UNSUPPORTED\n"); break; @@ -520,7 +576,8 @@ static int mds_find_objs(hid_t group, const char *name, void *op_data) { * *------------------------------------------------------------------------- */ -int main(int argc, const char *argv[]) { +int main(int argc, const char *argv[]) +{ hid_t fid; const char *fname = NULL; int first_time = 1; @@ -541,13 +598,15 @@ int main(int argc, const char *argv[]) { fid = H5Fopen(fname, 0, H5P_DEFAULT); - if (fid < 0) { + if (fid < 0) + { fprintf(stderr, "h5toMds, unable to open file \"%s\"\n", fname); exit(EXIT_FAILURE); } status = TreeOpenNew((char *)tree, strtol(shot, NULL, 0)); - if (!status & 1) { + if (!status & 1) + { printf("Error creating new tree for treename /%s/, shot number /%s/\n", tree, shot); exit(EXIT_FAILURE); diff --git a/hdf5/hdf5tdi.c b/hdf5/hdf5tdi.c index e7032805c6..2dbae116ef 100644 --- a/hdf5/hdf5tdi.c +++ b/hdf5/hdf5tdi.c @@ -35,7 +35,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -typedef struct _h5item { +typedef struct _h5item +{ int item_type; char *name; hid_t obj; @@ -48,21 +49,25 @@ typedef struct _h5item { static h5item *current = 0; static void PutArray(char dtype, int size, int n_dims, hsize_t *dims, void *ptr, - struct descriptor_xd *xd) { + struct descriptor_xd *xd) +{ /*************************************************** Store array of data into MDSplus descriptor. Use simple array descriptor for one dimensional arrays and a coefficient array descriptor for multi-dimensional arrays. ***************************************************/ - if (n_dims == 1) { + if (n_dims == 1) + { DESCRIPTOR_A(dsc, 0, 0, 0, 0); dsc.length = size; dsc.dtype = dtype; dsc.pointer = ptr; dsc.arsize = (int)dims[0] * size; MdsCopyDxXd((struct descriptor const *)&dsc, xd); - } else { + } + else + { int i; DESCRIPTOR_A_COEFF(dsc, 0, 0, 0, 8, 0); dsc.length = size; @@ -71,7 +76,8 @@ static void PutArray(char dtype, int size, int n_dims, hsize_t *dims, void *ptr, dsc.arsize = size; dsc.dimct = n_dims; dsc.a0 = ptr; - for (i = 0; i < n_dims; i++) { + for (i = 0; i < n_dims; i++) + { dsc.m[i] = (int)dims[i]; dsc.arsize *= (int)dims[i]; } @@ -80,7 +86,8 @@ static void PutArray(char dtype, int size, int n_dims, hsize_t *dims, void *ptr, } static void PutScalar(char dtype, int size, void *ptr, - struct descriptor_xd *xd) { + struct descriptor_xd *xd) +{ /********************************************** Store scalar data in MDSplus descriptor **********************************************/ @@ -92,13 +99,15 @@ static void PutScalar(char dtype, int size, void *ptr, } static void PutData(hid_t obj, char dtype, int htype, int size, int n_dims, - hsize_t *dims, int is_attr, struct descriptor_xd *xd) { + hsize_t *dims, int is_attr, struct descriptor_xd *xd) +{ /********************************************* Read data from HDF5 file using H5Aread for attributes and H5Dread for datasets. Load the data into MDSplus nodes. *********************************************/ - if (dtype) { + if (dtype) + { char *mem; /* if (dtype == DTYPE_T) { */ /* hid_t type = H5Aget_type(obj); */ @@ -136,7 +145,8 @@ static void PutData(hid_t obj, char dtype, int htype, int size, int n_dims, } } -static int find_attr(hid_t attr_id, const char *name, void *op_data) { +static int find_attr(hid_t attr_id, const char *name, void *op_data) +{ hid_t obj; h5item *parent = (h5item *)op_data; h5item *item = (h5item *)malloc(sizeof(h5item)); @@ -148,16 +158,21 @@ static int find_attr(hid_t attr_id, const char *name, void *op_data) { item->parent = parent; item->obj = 0; item->attribute = 0; - if (parent) { - if (parent->attribute == NULL) { + if (parent) + { + if (parent->attribute == NULL) + { parent->attribute = item; - } else { + } + else + { for (itm = parent->attribute; itm->brother; itm = itm->brother) ; itm->brother = item; } } - if ((obj = H5Aopen_name(attr_id, name)) >= 0) { + if ((obj = H5Aopen_name(attr_id, name)) >= 0) + { hid_t space = H5Aget_space(obj); H5Sclose(space); item->obj = obj; @@ -165,7 +180,8 @@ static int find_attr(hid_t attr_id, const char *name, void *op_data) { return 0; } -static int find_objs(hid_t group, const char *name, void *op_data) { +static int find_objs(hid_t group, const char *name, void *op_data) +{ hid_t obj; H5G_stat_t statbuf; unsigned int idx = 0; @@ -179,9 +195,12 @@ static int find_objs(hid_t group, const char *name, void *op_data) { item->parent = parent; item->obj = 0; item->attribute = 0; - if (parent->child == NULL) { + if (parent->child == NULL) + { parent->child = item; - } else { + } + else + { for (itm = parent->child; itm->brother; itm = itm->brother) ; itm->brother = item; @@ -192,15 +211,18 @@ static int find_objs(hid_t group, const char *name, void *op_data) { // H5Aiterate(group,&idx,find_attr,(void *)0); H5Gget_objinfo(group, name, 1, &statbuf); item->item_type = statbuf.type; - switch (statbuf.type) { + switch (statbuf.type) + { case H5G_GROUP: - if ((obj = H5Gopen(group, name)) >= 0) { + if ((obj = H5Gopen(group, name)) >= 0) + { H5Giterate(obj, ".", NULL, find_objs, (void *)item); H5Gclose(obj); } break; case H5G_DATASET: - if ((obj = H5Dopen(group, name)) >= 0) { + if ((obj = H5Dopen(group, name)) >= 0) + { item->obj = obj; /* H5Aiterate(obj,&idx,find_attr,(void *)item); */ H5Aiterate(obj, &idx, find_attr, (void *)item); @@ -234,11 +256,13 @@ static void ListItem(h5item * item) ListItem(item->brother); } */ -static void list_one(h5item *item, struct descriptor *xd) { +static void list_one(h5item *item, struct descriptor *xd) +{ char *name = strcpy(malloc(strlen(item->name) + 1), item->name); char *tmp; h5item *itm; - for (itm = item->parent; itm; itm = itm->parent) { + for (itm = item->parent; itm; itm = itm->parent) + { tmp = malloc(strlen(name) + strlen(itm->name) + 2); strcpy(tmp, itm->name); strcat(tmp, "/"); @@ -246,7 +270,8 @@ static void list_one(h5item *item, struct descriptor *xd) { free(name); name = tmp; } - if (item->item_type == H5G_DATASET || item->item_type == -1) { + if (item->item_type == H5G_DATASET || item->item_type == -1) + { struct descriptor name_d = {0, DTYPE_T, CLASS_S, 0}; name_d.length = strlen(name); name_d.pointer = name; @@ -261,18 +286,21 @@ static void list_one(h5item *item, struct descriptor *xd) { list_one(item->brother, xd); } -EXPORT void hdf5list(struct descriptor *xd) { +EXPORT void hdf5list(struct descriptor *xd) +{ MdsFree1Dx((struct descriptor_xd *)xd, 0); if (current) list_one(current, xd); } -static int find_one(h5item *item, char *findname, hid_t *obj, int *item_type) { +static int find_one(h5item *item, char *findname, hid_t *obj, int *item_type) +{ int status = 0; char *name = strcpy(malloc(strlen(item->name) + 1), item->name); char *tmp; h5item *itm; - for (itm = item->parent; itm; itm = itm->parent) { + for (itm = item->parent; itm; itm = itm->parent) + { tmp = malloc(strlen(name) + strlen(itm->name) + 2); strcpy(tmp, itm->name); strcat(tmp, "/"); @@ -280,8 +308,10 @@ static int find_one(h5item *item, char *findname, hid_t *obj, int *item_type) { free(name); name = tmp; } - if (item->item_type == H5G_DATASET || item->item_type == -1) { - if (strcmp(findname, name) == 0) { + if (item->item_type == H5G_DATASET || item->item_type == -1) + { + if (strcmp(findname, name) == 0) + { *obj = item->obj; *item_type = item->item_type; status = 1; @@ -297,7 +327,8 @@ static int find_one(h5item *item, char *findname, hid_t *obj, int *item_type) { return status; } -static int FindItem(char *namein, hid_t *obj, int *item_type) { +static int FindItem(char *namein, hid_t *obj, int *item_type) +{ int status; int i; char *name = strcpy(malloc(strlen(namein) + 1), namein); @@ -311,12 +342,15 @@ static int FindItem(char *namein, hid_t *obj, int *item_type) { return status; } -EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { +EXPORT int hdf5read(char *name, struct descriptor_xd *xd) +{ hid_t obj, type; int item_type; int status = FindItem(name, &obj, &item_type); - if (status & 1) { - if (item_type == H5G_DATASET) { + if (status & 1) + { + if (item_type == H5G_DATASET) + { int size; char dtype; int htype = 42; @@ -327,8 +361,10 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { size_t precision; H5Sclose(space); type = H5Dget_type(obj); - switch (H5Tget_class(type)) { - case H5T_COMPOUND: { + switch (H5Tget_class(type)) + { + case H5T_COMPOUND: + { printf("Compound data is not supported, skipping\n"); break; } @@ -336,7 +372,8 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { precision = H5Tget_precision(type); is_signed = (H5Tget_sign(type) != H5T_SGN_NONE); size = precision / 8; - switch (precision) { + switch (precision) + { case 8: dtype = is_signed ? DTYPE_B : DTYPE_BU; htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR; @@ -362,7 +399,8 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { case H5T_FLOAT: precision = H5Tget_precision(type); size = precision / 8; - switch (precision) { + switch (precision) + { case 32: dtype = DTYPE_NATIVE_FLOAT; htype = H5T_NATIVE_FLOAT; @@ -380,25 +418,31 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { case H5T_TIME: printf("dataset is time ---- UNSUPPORTED\n"); break; - case H5T_STRING: { + case H5T_STRING: + { int slen = H5Tget_size(type); hid_t st_id; - if (slen < 0) { + if (slen < 0) + { printf("Badly formed string attribute\n"); return 0; } #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 - if (H5Tis_variable_str(type)) { + if (H5Tis_variable_str(type)) + { st_id = H5Tcopy(H5T_C_S1); H5Tset_size(st_id, H5T_VARIABLE); - } else { + } + else + { #endif st_id = H5Tcopy(type); H5Tset_cset(st_id, H5T_CSET_ASCII); #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 } #endif - if ((int)H5Tget_size(st_id) > slen) { + if ((int)H5Tget_size(st_id) > slen) + { slen = H5Tget_size(st_id); } H5Tset_size(st_id, slen); @@ -425,7 +469,9 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { break; } H5Tclose(type); - } else { + } + else + { int size; char dtype; int htype = 42; @@ -436,8 +482,10 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { size_t precision; H5Sclose(space); type = H5Aget_type(obj); - switch (H5Tget_class(type)) { - case H5T_COMPOUND: { + switch (H5Tget_class(type)) + { + case H5T_COMPOUND: + { printf("Compound data is not supported, skipping\n"); break; } @@ -445,7 +493,8 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { precision = H5Tget_precision(type); is_signed = (H5Tget_sign(type) != H5T_SGN_NONE); size = precision / 8; - switch (precision) { + switch (precision) + { case 8: dtype = is_signed ? DTYPE_B : DTYPE_BU; htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR; @@ -471,7 +520,8 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { case H5T_FLOAT: precision = H5Tget_precision(type); size = precision / 8; - switch (precision) { + switch (precision) + { case 32: dtype = DTYPE_NATIVE_FLOAT; htype = H5T_NATIVE_FLOAT; @@ -489,25 +539,31 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { case H5T_TIME: printf("dataset is time ---- UNSUPPORTED\n"); break; - case H5T_STRING: { + case H5T_STRING: + { int slen = H5Tget_size(type); hid_t st_id; - if (slen < 0) { + if (slen < 0) + { printf("Badly formed string attribute\n"); return 0; } #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 - if (H5Tis_variable_str(type)) { + if (H5Tis_variable_str(type)) + { st_id = H5Tcopy(H5T_C_S1); H5Tset_size(st_id, H5T_VARIABLE); - } else { + } + else + { #endif st_id = H5Tcopy(type); H5Tset_cset(st_id, H5T_CSET_ASCII); #if H5_VERS_MAJOR >= 1 && H5_VERS_MINOR >= 6 && H5_VERS_RELEASE >= 1 } #endif - if ((int)H5Tget_size(st_id) > slen) { + if ((int)H5Tget_size(st_id) > slen) + { slen = H5Tget_size(st_id); } H5Tset_size(st_id, slen); @@ -538,7 +594,8 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) { return status; } -static void FreeObj(h5item *item) { +static void FreeObj(h5item *item) +{ free(item->name); if (item->item_type == H5G_DATASET && item->obj != 0) H5Dclose(item->obj); @@ -555,13 +612,15 @@ static void FreeObj(h5item *item) { free(item); } -EXPORT void hdf5close() { +EXPORT void hdf5close() +{ if (current) FreeObj(current); current = 0; } -EXPORT int hdf5open(char *fname) { +EXPORT int hdf5open(char *fname) +{ hid_t fid; /* Disable error reporting */ @@ -571,7 +630,8 @@ EXPORT int hdf5open(char *fname) { */ fid = H5Fopen(fname, 0, H5P_DEFAULT); - if (fid < 0) { + if (fid < 0) + { fprintf(stderr, "hdf5open, unable to open file \"%s\"\n", fname); return (-1); } diff --git a/idlmdsevent/mdsevent.c b/idlmdsevent/mdsevent.c index d89d012268..32f9ec020f 100644 --- a/idlmdsevent/mdsevent.c +++ b/idlmdsevent/mdsevent.c @@ -59,7 +59,8 @@ Invoked from MDSEVENT.PRO #include #include -typedef struct _event_struct { +typedef struct _event_struct +{ int stub_id; int base_id; int event_id; @@ -96,14 +97,16 @@ static void EventAst(void *e, int eventid, char *data); #define BlockSig(arg) #define UnBlockSig(arg) #else -static int BlockSig(int sig_number) { +static int BlockSig(int sig_number) +{ sigset_t newsigset; sigemptyset(&newsigset); sigaddset(&newsigset, sig_number); return sigprocmask(SIG_BLOCK, &newsigset, NULL); } -static int UnBlockSig(int sig_number) { +static int UnBlockSig(int sig_number) +{ sigset_t newsigset; sigemptyset(&newsigset); sigaddset(&newsigset, sig_number); @@ -111,9 +114,11 @@ static int UnBlockSig(int sig_number) { } #endif -EXPORT int IDLMdsEventCan(int argc, void **argv) { +EXPORT int IDLMdsEventCan(int argc, void **argv) +{ int status = 0; - if (argc == 2) { + if (argc == 2) + { EventStruct *e, *p; SOCKET sock = (SOCKET)((char *)argv[0] - (char *)0); int eventid = (unsigned int)((char *)argv[1] - (char *)0); @@ -123,7 +128,8 @@ EXPORT int IDLMdsEventCan(int argc, void **argv) { for (e = EventList, p = 0; e && e->loc_event_id != eventid; p = e, e = e->next) ; - if (e) { + if (e) + { #ifdef _WIN32 if (e->thread_handle) TerminateThread(e->thread_handle, 0); @@ -138,8 +144,10 @@ EXPORT int IDLMdsEventCan(int argc, void **argv) { return status; } -EXPORT int IDLMdsGetevi(int argc, void **argv) { - if (argc == 2) { +EXPORT int IDLMdsGetevi(int argc, void **argv) +{ + if (argc == 2) + { int eventid = (unsigned int)((char *)argv[0] - (char *)0); EventStruct *e; for (e = EventList; e && e->loc_event_id != eventid; e = e->next) @@ -147,7 +155,8 @@ EXPORT int IDLMdsGetevi(int argc, void **argv) { if (e) memcpy(argv[1], e, 52); return (e != 0); - } else + } + else return 0; } @@ -156,7 +165,8 @@ static int event_pipe[2]; static void DoEventUpdate(XtPointer client_data __attribute__((unused)), int *source __attribute__((unused)), - XtInputId *id __attribute__((unused))) { + XtInputId *id __attribute__((unused))) +{ char *stub_rec; char *base_rec; EventStruct *e; @@ -164,7 +174,8 @@ static void DoEventUpdate(XtPointer client_data __attribute__((unused)), if (read(event_pipe[0], &e, sizeof(EventStruct *)) == -1) perror("Error reading from event pipe\n"); if ((stub_rec = IDL_WidgetStubLookup(e->stub_id)) && - (base_rec = IDL_WidgetStubLookup(e->base_id))) { + (base_rec = IDL_WidgetStubLookup(e->base_id))) + { #ifdef _WIN32 HWND wid1, wid2; #endif @@ -178,7 +189,8 @@ static void DoEventUpdate(XtPointer client_data __attribute__((unused)), Widget w; IDL_WidgetGetStubIds(base_rec, (unsigned long *)&top, (unsigned long *)&w); - if (w) { + if (w) + { XClientMessageEvent event; event.type = ClientMessage; event.display = XtDisplay(top); @@ -193,7 +205,8 @@ static void DoEventUpdate(XtPointer client_data __attribute__((unused)), } } -static void EventAst(void *e_in, int len, char *data) { +static void EventAst(void *e_in, int len, char *data) +{ EventStruct *e = (EventStruct *)e_in; if (len > 0) memcpy(e->value, data, len > 12 ? 12 : len); @@ -201,8 +214,10 @@ static void EventAst(void *e_in, int len, char *data) { perror("Error writing to event pipe\n"); } #endif -EXPORT int IDLMdsEvent(int argc, void **argv) { - if (argc == 4) { +EXPORT int IDLMdsEvent(int argc, void **argv) +{ + if (argc == 4) + { SOCKET sock = (SOCKET)((char *)argv[0] - (char *)0); int *base_id = (int *)argv[1]; int *stub_id = (int *)argv[2]; @@ -214,22 +229,27 @@ EXPORT int IDLMdsEvent(int argc, void **argv) { char *stub_rec; IDL_WidgetStubLock(TRUE); if ((parent_rec = IDL_WidgetStubLookup(*base_id)) && - (stub_rec = IDL_WidgetStubLookup(*stub_id))) { + (stub_rec = IDL_WidgetStubLookup(*stub_id))) + { /* IDL_WidgetSetStubIds(stub_rec, parent_rec, parent_rec); */ #ifdef _WIN32 - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { e->thread_handle = CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)MdsDispatchEvent, (LPVOID)sock, (DWORD)NULL, &e->thread_id); - } else + } + else e->thread_handle = 0; #else - if (!XTINPUTID) { + if (!XTINPUTID) + { Widget w1, w2; IDL_WidgetGetStubIds(parent_rec, (unsigned long *)&w1, (unsigned long *)&w2); - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { XtAppAddInput(XtWidgetToApplicationContext(w1), sock, (XtPointer)XtInputExceptMask, MdsDispatchEvent, (char *)0 + sock); @@ -252,9 +272,12 @@ EXPORT int IDLMdsEvent(int argc, void **argv) { #pragma GCC diagnostic pop e->next = EventList; EventList = e; - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { MdsEventAst(sock, name, EventAst, e, &e->event_id); - } else { + } + else + { MDSEventAst(name, EventAst, e, &e->event_id); } IDL_WidgetStubLock(FALSE); @@ -268,7 +291,8 @@ EXPORT int IDLMdsEvent(int argc, void **argv) { } #ifdef _WIN32 -static void EventAst(void *e_in, int len, char *data) { +static void EventAst(void *e_in, int len, char *data) +{ EventStruct *e = (EventStruct *)e_in; char *stub_rec; char *base_rec; @@ -276,7 +300,8 @@ static void EventAst(void *e_in, int len, char *data) { if (len > 0) memcpy(e->value, data, len > 12 ? 12 : len); if ((stub_rec = IDL_WidgetStubLookup(e->stub_id)) && - (base_rec = IDL_WidgetStubLookup(e->base_id))) { + (base_rec = IDL_WidgetStubLookup(e->base_id))) + { HWND wid1, wid2; IDL_WidgetIssueStubEvent(stub_rec, (IDL_LONG)e); IDL_WidgetGetStubIds(stub_rec, (IDL_LONG *)&wid1, (IDL_LONG *)&wid2); diff --git a/idlmdswidgets/cw_wveditv5.c b/idlmdswidgets/cw_wveditv5.c index d186f2cbec..fa83051eab 100644 --- a/idlmdswidgets/cw_wveditv5.c +++ b/idlmdswidgets/cw_wveditv5.c @@ -62,7 +62,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") CB_USER }; -typedef struct _EventInfo { +typedef struct _EventInfo +{ int wave_idx; int reason; enum callback_id callback_id; @@ -75,7 +76,8 @@ typedef struct _EventInfo { struct _EventInfo *next; } EventInfo; -typedef struct _IdlEventRec { +typedef struct _IdlEventRec +{ char fill[24]; EventInfo *event; } IdlEventRec; @@ -91,8 +93,8 @@ static Atom XA_Y_AXIS; #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) -#define interp(x1, y1, x2, y2, x) \ - (((y2) - (y1)) / ((x2) - (x1)) * (x) + \ +#define interp(x1, y1, x2, y2, x) \ + (((y2) - (y1)) / ((x2) - (x1)) * (x) + \ (((y1) * (x2)) - ((y2) * (x1))) / ((x2) - (x1))) static void Align(Widget w, int stub, XmdsWaveformLimitsCBStruct *cb); @@ -133,7 +135,8 @@ static Widget CustomizePrintWidget = 0; // static int BusyLevel = 0; static String PrintFile = "WVEDIT.PS"; -static void Init(XtAppContext app_context) { +static void Init(XtAppContext app_context) +{ static XtActionsRec actions[] = { {"MoveVerticalPane", (XtActionProc)MoveVerticalPane}, {"EqualPanes", (XtActionProc)EqualPanes}}; @@ -144,7 +147,8 @@ static void Init(XtAppContext app_context) { Initialized = 1; } -static char *IndexedName(char *name_in, int idx) { +static char *IndexedName(char *name_in, int idx) +{ static char name[20]; int i; for (i = 0; name_in[i]; i++) @@ -154,43 +158,55 @@ static char *IndexedName(char *name_in, int idx) { return name; } -static Widget PaneIdxToWidget(Widget w, int idx) { +static Widget PaneIdxToWidget(Widget w, int idx) +{ return XtNameToWidget(w, IndexedName("*pane", idx)); } -static Widget SashIdxToWidget(Widget w, int idx) { +static Widget SashIdxToWidget(Widget w, int idx) +{ return XtNameToWidget(w, IndexedName("*sash", idx)); } -static Widget WaveIdxToWidget(Widget w, int idx) { +static Widget WaveIdxToWidget(Widget w, int idx) +{ return XtNameToWidget(w, IndexedName("*wave", idx)); } static void Align(Widget w, int stub __attribute__((unused)), - XmdsWaveformLimitsCBStruct *cb) { + XmdsWaveformLimitsCBStruct *cb) +{ Widget plots = XtNameToWidget(TopWidget(w), "*cw_wvedit"); int i; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget pane = PaneIdxToWidget(plots, i); - if (pane) { + if (pane) + { int i; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget wave = WaveIdxToWidget(pane, i); - if (wave) { + if (wave) + { if (wave != w) XtVaSetValues(wave, XmdsNxMin, cb->xminval, XmdsNxMax, cb->xmaxval, NULL); - } else + } + else break; } - } else + } + else break; } } -static void UserButton(Widget w, int stub, XmPushButtonCallbackStruct *cb) { +static void UserButton(Widget w, int stub, XmPushButtonCallbackStruct *cb) +{ Widget wave = setup_wave; - if (wave) { + if (wave) + { EventInfo *e = NewEvent(wave, stub, cb->event, 19, CB_USER); char *string = 0; XtVaGetValues(w, XmNuserData, &string, NULL); @@ -199,14 +215,16 @@ static void UserButton(Widget w, int stub, XmPushButtonCallbackStruct *cb) { } } -static void cw_wvedit_size_func(IDL_ULONG stub, int width, int height) { +static void cw_wvedit_size_func(IDL_ULONG stub, int width, int height) +{ char *stub_rec; unsigned long t_id, b_id; IDL_WidgetStubLock(TRUE); stub_rec = IDL_WidgetStubLookup(stub); - if (stub_rec) { + if (stub_rec) + { IDL_WidgetGetStubIds(stub_rec, &t_id, &b_id); XtVaSetValues((Widget)b_id, XmNwidth, width, XmNheight, height, NULL); } @@ -216,7 +234,8 @@ static void cw_wvedit_size_func(IDL_ULONG stub, int width, int height) { EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, int *cols, int *rows, Widget *plots, Widget *wavedraw_w, - struct descriptor *extra_buttons, int num_extra) { + struct descriptor *extra_buttons, int num_extra) +{ short class; static String hierarchy_name[] = {"cw_wvedit.uid"}; MrmHierarchy hierarchy; @@ -255,7 +274,8 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, return 1; IDL_WidgetStubLock(TRUE); if ((parent_rec = IDL_WidgetStubLookup(*parent_id)) && - (stub_rec = IDL_WidgetStubLookup(*stub_id))) { + (stub_rec = IDL_WidgetStubLookup(*stub_id))) + { IDL_WidgetGetStubIds(parent_rec, (unsigned long *)&t_id, (unsigned long *)&parent_w); if (Initialized == 0) @@ -269,8 +289,10 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, arglist[0].value = (char *)*stub_id; MrmRegisterNamesInHierarchy(hierarchy, arglist, XtNumber(arglist)); MrmFetchWidget(hierarchy, "waveform_popup", *plots, &pw, &class); - if (num_extra > 0) { - for (i = 0; i < num_extra; i++) { + if (num_extra > 0) + { + for (i = 0; i < num_extra; i++) + { Widget b; static XtCallbackRec user_button_callback_list[] = { {(XtCallbackProc)UserButton, (XtPointer)0}, {0, 0}}; @@ -294,13 +316,15 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, MrmFetchWidget(hierarchy, "customize_print_db", *plots, &pw, &class); MrmFetchWidget(hierarchy, "pane_separator", *plots, &pw, &class); XtAddEventHandler(*plots, ButtonPressMask, False, (XtEventHandler)Setup, 0); - for (i = 0; i < (*cols - 1); i++) { + for (i = 0; i < (*cols - 1); i++) + { Arg arglist[] = {{XmNleftPosition, 0}}; arglist[0].value = (int)(((i + 1) * 1000.) / *cols); MrmFetchWidgetOverride(hierarchy, "sash", *plots, IndexedName("sash", i), arglist, XtNumber(arglist), &sash, &class); } - for (i = 0; i < *cols; i++) { + for (i = 0; i < *cols; i++) + { Widget pane; Widget lsash = SashIdxToWidget(*plots, i - 1); Widget rsash = SashIdxToWidget(*plots, i); @@ -332,7 +356,8 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, args3[1].value = args4[1].value = (long)lsash; MrmFetchWidgetOverride(hierarchy, "pane", *plots, IndexedName("pane", i), arglist, numargs, &pane, &class); - for (j = 0; j < rows[i]; j++) { + for (j = 0; j < rows[i]; j++) + { Arg arglist[] = {{XmdsNpanWith, 0}}; arglist[0].value = (long)waveform; MrmFetchWidgetOverride(hierarchy, "wave", pane, IndexedName("wave", j), @@ -344,9 +369,11 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, XtVaSetValues(first_waveform, XmdsNpanWith, waveform, NULL); XtVaGetValues(pane, XmNnumChildren, &numchildren, XmNchildren, &child, NULL); - for (j = 0; j < numchildren; j++) { + for (j = 0; j < numchildren; j++) + { String name = XtName(child[j]); - if (name && !strcmp(name, "Sash")) { + if (name && !strcmp(name, "Sash")) + { XtTranslations translations = XtParseTranslationTable("Shift:EqualPanes(H)"); XtAugmentTranslations(child[j], translations); @@ -359,7 +386,8 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, NULL); XtManageChildren(child, numchildren); XtManageChild(*plots); - for (i = 0; i < *cols; i++) { + for (i = 0; i < *cols; i++) + { int r; Widget pane = PaneIdxToWidget(*plots, i); int height; @@ -374,7 +402,8 @@ EXPORT int CW_WVEDIT(unsigned long *parent_id, unsigned long *stub_id, return *stub_id; } -static Widget TopWidget(Widget w) { +static Widget TopWidget(Widget w) +{ Widget top; for (top = w; XtParent(top); top = XtParent(top)) ; @@ -383,8 +412,10 @@ static Widget TopWidget(Widget w) { static void Setup(Widget w, int stub __attribute__((unused)), XButtonEvent *event, - Boolean *continue_to_dispatch __attribute__((unused))) { - if (event->button == Button3) { + Boolean *continue_to_dispatch __attribute__((unused))) +{ + if (event->button == Button3) + { Widget popup = XtNameToWidget(TopWidget(w), "*waveform_popup"); setup_wave = FindWave(w, event); XmdsPopupMenuPosition(popup, event); @@ -396,7 +427,8 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XButtonEvent *event, String *params __attribute__((unused)), Cardinal *num_params - __attribute__((unused))) { + __attribute__((unused))) +{ Position main_x_root; Position main_y_root; int min_offset = 0; @@ -405,14 +437,16 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XButtonEvent *event, Widget separator = XtNameToWidget(TopWidget(w), "*pane_separator"); XtTranslateCoords(XtNameToWidget(TopWidget(w), "*cw_wvedit"), 0, 0, &main_x_root, &main_y_root); - if (event->type == ButtonPress) { + if (event->type == ButtonPress) + { separator->core.widget_class->core_class.compress_motion = 1; XtManageChild(separator); } XtVaSetValues(separator, XmNleftOffset, min(max_offset, max(min_offset, event->x_root - main_x_root)), NULL); - if (event->type == ButtonRelease) { + if (event->type == ButtonRelease) + { unsigned short position; XtVaGetValues(separator, XmNx, &position, NULL); position = @@ -427,9 +461,11 @@ static void /*XtActionProc */ MoveVerticalPane(Widget w, XButtonEvent *event, static void /*XtActionProc */ EqualPanes(Widget w, XEvent *event __attribute__((unused)), String *string, - Cardinal *num_strings) { + Cardinal *num_strings) +{ Widget plots = XtNameToWidget(TopWidget(w), "*cw_wvedit"); - if ((*num_strings == 1) && (string[0][0] == 'V')) { + if ((*num_strings == 1) && (string[0][0] == 'V')) + { int c; int cols; for (cols = 1; SashIdxToWidget(plots, cols - 1); cols++) @@ -437,7 +473,9 @@ static void /*XtActionProc */ EqualPanes(Widget w, for (c = 0; c < cols - 1; c++) XtVaSetValues(SashIdxToWidget(plots, c), XmNleftPosition, (int)((c + 1) * 1000 / cols), NULL); - } else if ((*num_strings == 1) && (string[0][0] == 'H')) { + } + else if ((*num_strings == 1) && (string[0][0] == 'H')) + { int r; Widget pane = XtParent(w); int height; @@ -454,9 +492,11 @@ static void /*XtActionProc */ EqualPanes(Widget w, } static void Autoscale(Widget w __attribute__((unused)), int stub, - XmPushButtonCallbackStruct *cb) { + XmPushButtonCallbackStruct *cb) +{ Widget wave = setup_wave; - if (wave) { + if (wave) + { EventInfo *e = NewEvent(wave, stub, cb->event, XmdsCRZoomOut, CB_AUTOSCALE); float *xminval; float *xmaxval; @@ -473,32 +513,40 @@ static void Autoscale(Widget w __attribute__((unused)), int stub, } } -static Widget FindWave(Widget w, XButtonEvent *event) { +static Widget FindWave(Widget w, XButtonEvent *event) +{ Widget plots = XtNameToWidget(TopWidget(w), "*cw_wvedit"); int i; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget pane = PaneIdxToWidget(plots, i); - if (pane) { + if (pane) + { int i; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget wave = WaveIdxToWidget(pane, i); - if (wave) { + if (wave) + { Position x; Position y; XtTranslateCoords(wave, 0, 0, &x, &y); if (event->x_root >= x && event->x_root <= (x + XtWidth(wave)) && event->y_root >= y && event->y_root <= (y + XtHeight(wave))) return wave; - } else + } + else break; } - } else + } + else break; } return 0; } -static void Crosshairs(Widget w, int stub, XmdsWaveformCrosshairsCBStruct *cb) { +static void Crosshairs(Widget w, int stub, XmdsWaveformCrosshairsCBStruct *cb) +{ // Widget top = TopWidget(w); // Widget plots = XtNameToWidget(top, "*cw_wvedit"); EventInfo *e = NewEvent(w, stub, cb->event, cb->reason, CB_CROSSHAIRS); @@ -506,7 +554,8 @@ static void Crosshairs(Widget w, int stub, XmdsWaveformCrosshairsCBStruct *cb) { e->values[1] = cb->y; } -static void Limits(Widget w, int stub, XmdsWaveformLimitsCBStruct *cb) { +static void Limits(Widget w, int stub, XmdsWaveformLimitsCBStruct *cb) +{ EventInfo *e = NewEvent(w, stub, cb->event, cb->reason, CB_LIMITS); e->values[0] = *cb->xminval; e->values[1] = *cb->xmaxval; @@ -516,15 +565,18 @@ static void Limits(Widget w, int stub, XmdsWaveformLimitsCBStruct *cb) { static void /*XtSelectionCallbackProc */ PasteComplete(Widget w, int stub, Atom *selection __attribute__((unused)), - Atom *type, XtPointer value, unsigned long *length, int *format) { + Atom *type, XtPointer value, unsigned long *length, int *format) +{ static float *x; if (*type == XA_X_AXIS) x = (float *)value; - else if (*type == XA_Y_AXIS) { + else if (*type == XA_Y_AXIS) + { int num = (int)(*length * ((float)*format) / 32); int i; // float *y = (float *)value; - if (x) { + if (x) + { // EventInfo *e; Boolean *knots = (Boolean *)XtMalloc(num * sizeof(Boolean)); for (i = 0; i < num; i++) @@ -541,10 +593,14 @@ PasteComplete(Widget w, int stub, Atom *selection __attribute__((unused)), NewEvent(w, stub, 0, 0, CB_PASTE); NewEvent(w, stub, 0, 18, CB_FIT); } - } else if (*type == XA_STRING) { + } + else if (*type == XA_STRING) + { XtVaSetValues(w, XmdsNtitle, value, NULL); XtFree((String)value); - } else if (*type == XA_TARGETS) { + } + else if (*type == XA_TARGETS) + { unsigned long i; Atom *values = value; Boolean supports_data_paste = 0; @@ -554,7 +610,8 @@ PasteComplete(Widget w, int stub, Atom *selection __attribute__((unused)), supports_data_paste = 1; else if (values[i] == XA_STRING) supports_string_paste = 1; - if (supports_data_paste) { + if (supports_data_paste) + { // Atom targets[2]; // targets[0] = XA_X_AXIS; // targets[1] = XA_Y_AXIS; @@ -571,19 +628,23 @@ PasteComplete(Widget w, int stub, Atom *selection __attribute__((unused)), (XtSelectionCallbackProc)PasteComplete, (XtPointer)((char *)0 + stub), XtLastTimestampProcessed(XtDisplay(w))); - } else if (supports_string_paste) + } + else if (supports_string_paste) XtGetSelectionValue(w, XA_PRIMARY, XA_STRING, (XtSelectionCallbackProc)PasteComplete, (XtPointer)((char *)0 + stub), XtLastTimestampProcessed(XtDisplay(w))); XtFree((String)values); - } else if (value) + } + else if (value) XtFree((String)value); } static void Paste(Widget w, int stub, - XmAnyCallbackStruct *cb __attribute__((unused))) { - if (XA_X_AXIS == 0) { + XmAnyCallbackStruct *cb __attribute__((unused))) +{ + if (XA_X_AXIS == 0) + { XA_X_AXIS = XInternAtom(XtDisplay(w), "DWSCOPE_X_AXIS", 0); XA_Y_AXIS = XInternAtom(XtDisplay(w), "DWSCOPE_Y_AXIS", 0); XA_TARGETS = XInternAtom(XtDisplay(w), "TARGETS", 0); @@ -593,7 +654,8 @@ static void Paste(Widget w, int stub, (XtPointer)((char *)0 + stub), XtLastTimestampProcessed(XtDisplay(w))); } -static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) { +static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) +{ XmdsWaveformReverse(w, 0); SelectedWidget = 0; } @@ -601,18 +663,22 @@ static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) { static Boolean ConvertSelection(Widget w, Atom *selection __attribute__((unused)), Atom *target, Atom *type, XtPointer *value, - unsigned long *length, int *format) { + unsigned long *length, int *format) +{ int status = 0; - if (XA_X_AXIS == 0) { + if (XA_X_AXIS == 0) + { XA_X_AXIS = XInternAtom(XtDisplay(w), "DWSCOPE_X_AXIS", 0); XA_Y_AXIS = XInternAtom(XtDisplay(w), "DWSCOPE_Y_AXIS", 0); XA_TARGETS = XInternAtom(XtDisplay(w), "TARGETS", 0); } - if (*target == XA_X_AXIS) { + if (*target == XA_X_AXIS) + { float *x; int count = 0; XtVaGetValues(w, XmdsNxValue, &x, XmdsNcount, &count, NULL); - if (x && count) { + if (x && count) + { *type = *target; *value = (char *)memcpy(XtMalloc(count * sizeof(float)), x, count * sizeof(float)); @@ -620,11 +686,14 @@ static Boolean ConvertSelection(Widget w, *format = 8; status = 1; } - } else if (*target == XA_Y_AXIS) { + } + else if (*target == XA_Y_AXIS) + { float *y; int count = 0; XtVaGetValues(w, XmdsNyValue, &y, XmdsNcount, &count, NULL); - if (y && count) { + if (y && count) + { *type = *target; *value = (char *)memcpy(XtMalloc(count * sizeof(float)), y, count * sizeof(float)); @@ -632,7 +701,9 @@ static Boolean ConvertSelection(Widget w, *format = 8; status = 1; } - } else if (*target == XA_TARGETS) { + } + else if (*target == XA_TARGETS) + { *type = *target; *value = (char *)XtMalloc(sizeof(Atom) * 2); ((Atom *)*value)[0] = XA_X_AXIS; @@ -645,19 +716,22 @@ static Boolean ConvertSelection(Widget w, } static void Cut(Widget w, int stub __attribute__((unused)), - XmAnyCallbackStruct *callback_struct __attribute__((unused))) { + XmAnyCallbackStruct *callback_struct __attribute__((unused))) +{ if (SelectedWidget == w) XtDisownSelection(SelectedWidget, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w))); else if (XtOwnSelection(w, XA_PRIMARY, XtLastTimestampProcessed(XtDisplay(w)), (XtConvertSelectionProc)ConvertSelection, - LoseSelection, NULL)) { + LoseSelection, NULL)) + { SelectedWidget = w; XmdsWaveformReverse(w, 1); } } -static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { +static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) +{ Boolean xincreasing; Boolean yincreasing; Boolean closed; @@ -684,24 +758,31 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { /* lib$establish(lib$sig_to_ret); */ - while (point < cb->count) { + while (point < cb->count) + { spline_points = 0; for (point = end_point + 1; point < cb->count && cb->pen_down[point] != -1; - point++) { - if (cb->selected[point]) { + point++) + { + if (cb->selected[point]) + { spline_x[spline_points] = cb->x[point]; spline_y[spline_points] = cb->y[point]; knotidx[spline_points++] = point; } } end_point = point; - if (point < cb->count) { + if (point < cb->count) + { memcpy(&cb->x[point], &thirty_two_k, 4); memcpy(&cb->y[point], &thirty_two_k, 4); } - if (spline_points < cb->count) { - if (spline_points > 2) { - if (xincreasing) { + if (spline_points < cb->count) + { + if (spline_points > 2) + { + if (xincreasing) + { float *fbreak = (float *)XtMalloc(spline_points * sizeof(float)); float *cscoef = (float *)XtMalloc(spline_points * 4 * sizeof(float)); int breaks = spline_points - 1; @@ -711,7 +792,9 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { ymin, min(ymax, csval_(&cb->x[i], &breaks, fbreak, cscoef))); XtFree((String)fbreak); XtFree((String)cscoef); - } else if (yincreasing) { + } + else if (yincreasing) + { float *fbreak = (float *)XtMalloc(spline_points * sizeof(float)); float *cscoef = (float *)XtMalloc(spline_points * 4 * sizeof(float)); int breaks = spline_points - 1; @@ -721,10 +804,13 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { xmin, min(xmax, csval_(&cb->y[i], &breaks, fbreak, cscoef))); XtFree((String)fbreak); XtFree((String)cscoef); - } else { + } + else + { int knotid = 1; // int first_knot = 0; - if (closed) { + if (closed) + { int offset; spline_x = (float *)XtRealloc((String)spline_x, spline_points * 2 * sizeof(float)); @@ -763,9 +849,12 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { int ics = 0; mskrv1_(&spline_points, spline_x, spline_y, &zero, &zero, xp, yp, temp, s, &zero, &three); - for (i = knotidx[0]; i < end_point && knotid < spline_points; i++) { - if (i < knotidx[knotid]) { - if (!cb->selected[i]) { + for (i = knotidx[0]; i < end_point && knotid < spline_points; i++) + { + if (i < knotidx[knotid]) + { + if (!cb->selected[i]) + { float d = (float)(i - knotidx[knotid - 1]) / (float)(knotidx[knotid] - knotidx[knotid - 1]); float s1 = s[knotid - 1] + d * (s[knotid] - s[knotid - 1]); @@ -775,7 +864,8 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { cb->x[i] = max(xmin, min(xmax, cb->x[i])); cb->y[i] = max(ymin, min(ymax, cb->y[i])); } - } else + } + else knotid++; } XtFree((String)xp); @@ -784,9 +874,13 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { XtFree((String)s); } } - } else if (spline_points > 1) { - if (xincreasing || !yincreasing) { - for (i = knotidx[0] + 1; i < knotidx[spline_points - 1]; i++) { + } + else if (spline_points > 1) + { + if (xincreasing || !yincreasing) + { + for (i = knotidx[0] + 1; i < knotidx[spline_points - 1]; i++) + { if (cb->x[i] < spline_x[1]) cb->y[i] = interp(spline_x[0], spline_y[0], spline_x[1], spline_y[1], cb->x[i]); @@ -794,8 +888,11 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { cb->y[i] = interp(spline_x[1], spline_y[1], spline_x[2], spline_y[2], cb->x[i]); } - } else { - for (i = knotidx[0] + 1; i < knotidx[spline_points - 1]; i++) { + } + else + { + for (i = knotidx[0] + 1; i < knotidx[spline_points - 1]; i++) + { if (cb->y[i] < spline_y[1]) cb->x[i] = interp(spline_y[0], spline_x[0], spline_y[1], spline_x[1], cb->y[i]); @@ -812,8 +909,10 @@ static void Fit(Widget w, int stub, XmdsWavedrawFitCBStruct *cb) { XtFree((String)knotidx); } -static void Move(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { - if (cb->event) { +static void Move(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) +{ + if (cb->event) + { int pointermode; EventInfo *e; XtVaGetValues(w, XmdsNpointerMode, &pointermode, NULL); @@ -829,34 +928,43 @@ static void Move(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { return; } -static int WaveToIdx(Widget w) { +static int WaveToIdx(Widget w) +{ Widget plots = XtNameToWidget(TopWidget(w), "*cw_wvedit"); int i; int idx = 0; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget pane = PaneIdxToWidget(plots, i); - if (pane) { + if (pane) + { int i; - for (i = 0; 1; i++) { + for (i = 0; 1; i++) + { Widget wave = WaveIdxToWidget(pane, i); - if (wave) { + if (wave) + { if (wave == w) return idx; else idx++; - } else + } + else break; } - } else + } + else break; } return -1; } static void SetAtLimits(Widget w __attribute__((unused)), int stub, - XmPushButtonCallbackStruct *cb) { + XmPushButtonCallbackStruct *cb) +{ Widget wave = setup_wave; - if (wave) { + if (wave) + { EventInfo *e = NewEvent(wave, stub, cb->event, XmdsCRZoomOut, CB_SET_AT_LIMITS); float *xminval; @@ -876,7 +984,8 @@ static void SetAtLimits(Widget w __attribute__((unused)), int stub, } } -static void AddPoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { +static void AddPoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) +{ EventInfo *e = NewEvent(w, stub, cb->event, cb->reason, CB_ADD_POINT); e->moved_idx = cb->idx; e->values[0] = cb->oldx; @@ -886,7 +995,8 @@ static void AddPoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { e->values[3] = cb->newy; } -static void DeletePoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { +static void DeletePoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) +{ EventInfo *e = NewEvent(w, stub, cb->event, cb->reason, CB_DELETE_POINT); e->moved_idx = cb->idx; e->values[0] = cb->oldx; @@ -898,7 +1008,8 @@ static void DeletePoint(Widget w, int stub, XmdsWavedrawValueCBStruct *cb) { static void Print(Widget w __attribute__((unused)), int tag __attribute__((unused)), - XmdsWavedrawValueCBStruct *cb __attribute__((unused))) { + XmdsWavedrawValueCBStruct *cb __attribute__((unused))) +{ return; } @@ -909,7 +1020,8 @@ static void PrintAll(Widget w __attribute__((unused)), static void ResetCustomizePrint(Widget w __attribute__((unused)), int tag __attribute__((unused)), XmAnyCallbackStruct *cb - __attribute__((unused))) { + __attribute__((unused))) +{ XmTextSetString(XtNameToWidget(CustomizePrintWidget, "print_file"), PrintFile); } @@ -917,15 +1029,18 @@ static void ResetCustomizePrint(Widget w __attribute__((unused)), static void ApplyCustomizePrint(Widget w __attribute__((unused)), int tag __attribute__((unused)), XmAnyCallbackStruct *cb - __attribute__((unused))) { + __attribute__((unused))) +{ ReplaceString( &PrintFile, XmTextGetString(XtNameToWidget(CustomizePrintWidget, "print_file")), 1); } -Boolean ReplaceString(String *old, String new, Boolean free) { +Boolean ReplaceString(String *old, String new, Boolean free) +{ Boolean changed = TRUE; - if (*old) { + if (*old) + { changed = strcmp(*old, new); XtFree(*old); } @@ -936,12 +1051,15 @@ Boolean ReplaceString(String *old, String new, Boolean free) { } static EventInfo *EVENTLIST = 0; -EXPORT void GetEventInfo(int *eventid, int *info) { +EXPORT void GetEventInfo(int *eventid, int *info) +{ EventInfo *e, *prev; IDL_WidgetStubLock(TRUE); memset(info, 0, 40); - for (e = EVENTLIST, prev = NULL; e; prev = e, e = e->next) { - if (e->eventid == *eventid) { + for (e = EVENTLIST, prev = NULL; e; prev = e, e = e->next) + { + if (e->eventid == *eventid) + { memcpy(info, e, 40); if (prev == NULL) EVENTLIST = e->next; @@ -954,15 +1072,18 @@ EXPORT void GetEventInfo(int *eventid, int *info) { } static EventInfo *NewEvent(Widget w, unsigned long stub, XEvent *event, - int reason, enum callback_id callback_id) { + int reason, enum callback_id callback_id) +{ static int EVENTID = 0; static EventInfo *last_e = 0; if (!(last_e && last_e->w == w && last_e->reason == reason && - last_e->callback_id == callback_id)) { + last_e->callback_id == callback_id)) + { char *rec; IDL_WidgetStubLock(TRUE); rec = IDL_WidgetStubLookup(stub); - if (rec) { + if (rec) + { EventInfo *e = (EventInfo *)malloc(sizeof(EventInfo)); e->wave_idx = WaveToIdx(w); e->reason = reason; @@ -971,10 +1092,13 @@ static EventInfo *NewEvent(Widget w, unsigned long stub, XEvent *event, e->button = event ? ((XButtonEvent *)event)->button : 0; e->w = w; e->eventid = ++EVENTID; - if (EVENTLIST == NULL) { + if (EVENTLIST == NULL) + { e->next = 0; EVENTLIST = e; - } else { + } + else + { e->next = EVENTLIST; EVENTLIST = e; } @@ -986,6 +1110,7 @@ static EventInfo *NewEvent(Widget w, unsigned long stub, XEvent *event, return last_e; } -EXPORT void *memmoveext(void *dest, const void *src, size_t n) { +EXPORT void *memmoveext(void *dest, const void *src, size_t n) +{ return memmove(dest, src, n); } diff --git a/include/WindowsUnnamedSemaphore.h b/include/WindowsUnnamedSemaphore.h index c9c0df0fec..43ec045a73 100644 --- a/include/WindowsUnnamedSemaphore.h +++ b/include/WindowsUnnamedSemaphore.h @@ -3,12 +3,14 @@ #include "Timeout.h" #include #define MAX_SEM_COUNT 256 -class EXPORT UnnamedSemaphore { +class EXPORT UnnamedSemaphore +{ // LPSTR semName; char semName[256]; public: - void initialize(int initVal) { + void initialize(int initVal) + { SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); @@ -16,21 +18,25 @@ class EXPORT UnnamedSemaphore { sa.lpSecurityDescriptor = NULL; int64_t uniqueId = reinterpret_cast(this); - while (true) { + while (true) + { sprintf((char *)semName, "%x", uniqueId); HANDLE semHandle = CreateSemaphore(NULL, initVal, MAX_SEM_COUNT, (LPSTR)semName); if (semHandle == 0) throw new SystemException("Error initializing semaphore", GetLastError()); - if (GetLastError() == ERROR_ALREADY_EXISTS) { + if (GetLastError() == ERROR_ALREADY_EXISTS) + { CloseHandle(semHandle); uniqueId++; - } else + } + else break; } } - void wait() { + void wait() + { HANDLE semHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS, NULL, (LPSTR)semName); if (semHandle == 0) @@ -42,7 +48,8 @@ class EXPORT UnnamedSemaphore { // CloseHandle(semHandle); } - int timedWait(MdsTimeout &timeout) { + int timedWait(MdsTimeout &timeout) + { HANDLE semHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS, NULL, (LPSTR)semName); if (semHandle == 0) @@ -67,7 +74,8 @@ class EXPORT UnnamedSemaphore { // CloseHandle(semHandle); } - bool isZero() { + bool isZero() + { HANDLE semHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS, NULL, (LPSTR)semName); if (semHandle == 0) diff --git a/include/Xmds/ListTree.h b/include/Xmds/ListTree.h index d8cbec6e30..fd6470146f 100644 --- a/include/Xmds/ListTree.h +++ b/include/Xmds/ListTree.h @@ -55,60 +55,67 @@ #define XtDESTROY 4 #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -extern WidgetClass listtreeWidgetClass; - -typedef struct _ListTreeClassRec *ListTreeWidgetClass; -typedef struct _ListTreeRec *ListTreeWidget; - -typedef enum _ListTreeItemType { - ItemDetermineType = 0, - ItemBranchType = XtBRANCH, - ItemLeafType = XtLEAF -} ListTreeItemType; - -typedef struct _ListTreeItem { - Boolean open; - Boolean highlighted; - char *text; - int length; - int x, y, ytext; - int count; - Dimension height; - ListTreeItemType type; - struct _ListTreeItem *parent, *firstchild, *prevsibling, *nextsibling; - Pixmap openPixmap, closedPixmap; - XtPointer user_data; -} ListTreeItem; - -typedef struct _ListTreeReturnStruct { - int reason; - ListTreeItem *item; - ListTreeItem **path; - int count; - Boolean open; -} ListTreeReturnStruct; - -typedef struct _ListTreeMultiReturnStruct { - ListTreeItem **items; - int count; -} ListTreeMultiReturnStruct; - -typedef struct _ListTreeActivateStruct { - int reason; - ListTreeItem *item; - Boolean open; - ListTreeItem **path; - int count; -} ListTreeActivateStruct; - -typedef struct _ListTreeItemReturnStruct { - int reason; - ListTreeItem *item; - XEvent *event; -} ListTreeItemReturnStruct; + extern WidgetClass listtreeWidgetClass; + + typedef struct _ListTreeClassRec *ListTreeWidgetClass; + typedef struct _ListTreeRec *ListTreeWidget; + + typedef enum _ListTreeItemType + { + ItemDetermineType = 0, + ItemBranchType = XtBRANCH, + ItemLeafType = XtLEAF + } ListTreeItemType; + + typedef struct _ListTreeItem + { + Boolean open; + Boolean highlighted; + char *text; + int length; + int x, y, ytext; + int count; + Dimension height; + ListTreeItemType type; + struct _ListTreeItem *parent, *firstchild, *prevsibling, *nextsibling; + Pixmap openPixmap, closedPixmap; + XtPointer user_data; + } ListTreeItem; + + typedef struct _ListTreeReturnStruct + { + int reason; + ListTreeItem *item; + ListTreeItem **path; + int count; + Boolean open; + } ListTreeReturnStruct; + + typedef struct _ListTreeMultiReturnStruct + { + ListTreeItem **items; + int count; + } ListTreeMultiReturnStruct; + + typedef struct _ListTreeActivateStruct + { + int reason; + ListTreeItem *item; + Boolean open; + ListTreeItem **path; + int count; + } ListTreeActivateStruct; + + typedef struct _ListTreeItemReturnStruct + { + int reason; + ListTreeItem *item; + XEvent *event; + } ListTreeItemReturnStruct; #ifdef __cplusplus }; diff --git a/include/Xmds/ListTreeP.h b/include/Xmds/ListTreeP.h index 1bbfe42428..4327069ed8 100644 --- a/include/Xmds/ListTreeP.h +++ b/include/Xmds/ListTreeP.h @@ -36,12 +36,12 @@ /* LessTif definitions that are convenient for Motif */ #ifndef Prim_HighlightThickness -#define Prim_HighlightThickness(w) \ +#define Prim_HighlightThickness(w) \ (((XmPrimitiveWidget)(w))->primitive.highlight_thickness) #endif #ifndef Prim_ShadowThickness -#define Prim_ShadowThickness(w) \ +#define Prim_ShadowThickness(w) \ (((XmPrimitiveWidget)(w))->primitive.shadow_thickness) #endif @@ -50,7 +50,7 @@ #endif #ifndef Prim_BottomShadowGC -#define Prim_BottomShadowGC(w) \ +#define Prim_BottomShadowGC(w) \ (((XmPrimitiveWidget)(w))->primitive.bottom_shadow_GC) #endif @@ -61,11 +61,13 @@ #define TIMER_DOUBLE 2 #define TIMER_WAITING 3 -typedef struct { +typedef struct +{ int dummy; /* keep compiler happy with dummy field */ } ListTreeClassPart; -typedef struct _ListTreeClassRec { +typedef struct _ListTreeClassRec +{ CoreClassPart core_class; XmPrimitiveClassPart primitive_class; ListTreeClassPart ListTree_class; @@ -73,14 +75,16 @@ typedef struct _ListTreeClassRec { extern ListTreeClassRec listtreeClassRec; -typedef struct { +typedef struct +{ Pixmap bitmap; Pixmap pix; int width, height; int xoff; } Pixinfo; -typedef struct { +typedef struct +{ /* Public stuff ... */ long foreground_pixel; XFontStruct *font; @@ -155,7 +159,8 @@ typedef struct { } ListTreePart; -typedef struct _ListTreeRec { +typedef struct _ListTreeRec +{ CorePart core; XmPrimitivePart primitive; ListTreePart list; diff --git a/include/Xmds/XmdsCallbacks.h b/include/Xmds/XmdsCallbacks.h index 1913b14556..5fe48af2eb 100644 --- a/include/Xmds/XmdsCallbacks.h +++ b/include/Xmds/XmdsCallbacks.h @@ -29,14 +29,16 @@ #ifndef XmdsCallbacks_H #define XmdsCallbacks_H -typedef struct _XmdsButtonCallbackStruct { +typedef struct _XmdsButtonCallbackStruct +{ int reason; XEvent *event; struct descriptor_xd *xd; Boolean on_off; } XmdsButtonCallbackStruct; -typedef struct _XmdsMenuCallbackStruct { +typedef struct _XmdsMenuCallbackStruct +{ int reason; XEvent *event; int button; diff --git a/include/Xmds/XmdsDigChans.h b/include/Xmds/XmdsDigChans.h index 759af8de11..c6785c63e8 100644 --- a/include/Xmds/XmdsDigChans.h +++ b/include/Xmds/XmdsDigChans.h @@ -37,16 +37,16 @@ #define XmdsNchannels "channels" /* Number of digitizer channels */ #define XmdsNnid "nid" /* Nid of first channel */ #define XmdsNnidOffset "nidOffset" /* Nid offset */ -#define XmdsNdataNidOffset \ +#define XmdsNdataNidOffset \ "dataNidOffset" /* Offset from channel head to data */ -#define XmdsNstartIdxNidOffset \ +#define XmdsNstartIdxNidOffset \ "startIdxNidOffset" /* Offset from channel head to startidx */ -#define XmdsNendIdxNidOffset \ +#define XmdsNendIdxNidOffset \ "endIdxNidOffset" /* Offset from channel head to endidx */ -#define XmdsNnodesPerChannel \ +#define XmdsNnodesPerChannel \ "nodesPerChannel" /* Number of nodes per digitizer channel */ -#define XmdsNputOnApply \ - "putOnApply" /* Put when a XmdsApplyAllXds is called \ +#define XmdsNputOnApply \ + "putOnApply" /* Put when a XmdsApplyAllXds is called \ */ /* External creation routines: diff --git a/include/Xmds/XmdsExprP.h b/include/Xmds/XmdsExprP.h index f074ce41b2..041908d3df 100644 --- a/include/Xmds/XmdsExprP.h +++ b/include/Xmds/XmdsExprP.h @@ -37,7 +37,8 @@ /* New fields for the Expr Widget record */ -typedef struct _XmdsExprPart { +typedef struct _XmdsExprPart +{ struct descriptor_xd *xd; int nid; int nid_offset; @@ -59,7 +60,8 @@ typedef struct _XmdsExprPart { /* * now define the actual widget data struct */ -typedef struct _XmdsExprWidgetRec { +typedef struct _XmdsExprWidgetRec +{ CorePart core; /* basic widget */ CompositePart composite; ConstraintPart constraint; @@ -71,7 +73,8 @@ typedef struct _XmdsExprWidgetRec { * Expr Class part is empty. */ -typedef struct _XmdsExprClassPart { +typedef struct _XmdsExprClassPart +{ caddr_t extension; /* Pointer to extension record */ } XmdsExprClassPart; @@ -79,7 +82,8 @@ typedef struct _XmdsExprClassPart { * The Expr Class record is a Dialog box class record plus * the empty ExprClassPart */ -typedef struct _XmdsExprClassRec { +typedef struct _XmdsExprClassRec +{ CoreClassPart core_class; CompositeClassPart composite; ConstraintClassPart constraint; diff --git a/include/Xmds/XmdsInputs.h b/include/Xmds/XmdsInputs.h index 2f06ecd029..ce7be5368c 100644 --- a/include/Xmds/XmdsInputs.h +++ b/include/Xmds/XmdsInputs.h @@ -30,7 +30,8 @@ #ifndef _XmdsInputs_h #define _XmdsInputs_h -typedef struct _xmdsInputCtx { +typedef struct _xmdsInputCtx +{ int inputs_nid; int nodes_per_input; int data_offset; diff --git a/include/Xmds/XmdsNidOptionMenu.h b/include/Xmds/XmdsNidOptionMenu.h index cd8862957c..5ec44859d2 100644 --- a/include/Xmds/XmdsNidOptionMenu.h +++ b/include/Xmds/XmdsNidOptionMenu.h @@ -38,16 +38,16 @@ #define XmdsNnid "nid" /* Nid */ #define XmdsNnidOffset "nidOffset" /* Nid offset */ -#define XmdsNputOnApply \ - "putOnApply" /* Put when a XmdsApplyAllXds is called \ - */ +#define XmdsNputOnApply \ + "putOnApply" /* Put when a XmdsApplyAllXds is called \ + */ #define XmdsNlabelStrings "labelStrings" /* String table of button labels */ -#define XmdsNvalueStrings \ - "valueStrings" /* String table of value expressions \ +#define XmdsNvalueStrings \ + "valueStrings" /* String table of value expressions \ */ -#define XmdsNresetCallback \ +#define XmdsNresetCallback \ "resetCallback" /* User routine to call for resets (no nid) */ -#define XmdsNvalueChangedCallback \ +#define XmdsNvalueChangedCallback \ "valueChangedCallback" /* User routine to call when the value changes */ /* External creation routines: diff --git a/include/Xmds/XmdsOnOffToggleButton.h b/include/Xmds/XmdsOnOffToggleButton.h index 0f8dec1904..ec9784429a 100644 --- a/include/Xmds/XmdsOnOffToggleButton.h +++ b/include/Xmds/XmdsOnOffToggleButton.h @@ -36,8 +36,8 @@ #define XmdsNnid "nid" /* Nid */ #define XmdsNnidOffset "nidOffset" /* Nid offset */ #define XmdsNshowPath "showPath" /* Nid */ -#define XmdsNputOnApply \ - "putOnApply" /* Put when a XmdsApplyAllXds is called \ +#define XmdsNputOnApply \ + "putOnApply" /* Put when a XmdsApplyAllXds is called \ */ /* External creation routines: diff --git a/include/Xmds/XmdsPath.h b/include/Xmds/XmdsPath.h index b1e2135a38..36a99666ba 100644 --- a/include/Xmds/XmdsPath.h +++ b/include/Xmds/XmdsPath.h @@ -29,7 +29,11 @@ #include #endif -typedef enum pathType { NciABSOLUTE_PATH, NciRELATIVE_PATH } XmdsPathType; +typedef enum pathType +{ + NciABSOLUTE_PATH, + NciRELATIVE_PATH +} XmdsPathType; /* Resources */ #define XmdsNnid "nid" /* Nid of first channel */ diff --git a/include/Xmds/XmdsWavedraw.h b/include/Xmds/XmdsWavedraw.h index 1edca607e7..cf015e5bd7 100644 --- a/include/Xmds/XmdsWavedraw.h +++ b/include/Xmds/XmdsWavedraw.h @@ -71,7 +71,8 @@ /* Callback structures */ -typedef struct { +typedef struct +{ int reason; XEvent *event; int idx; @@ -85,7 +86,8 @@ typedef struct { Boolean *selected; } XmdsWavedrawValueCBStruct; -typedef struct { +typedef struct +{ int reason; XEvent *event; int count; diff --git a/include/Xmds/XmdsWavedrawP.h b/include/Xmds/XmdsWavedrawP.h index e3c241b659..4e9ed55799 100644 --- a/include/Xmds/XmdsWavedrawP.h +++ b/include/Xmds/XmdsWavedrawP.h @@ -33,7 +33,8 @@ #include #include -typedef struct _XmdsWavedrawClassPart { +typedef struct _XmdsWavedrawClassPart +{ XtTranslations draw1_trans; XtTranslations draw2_trans; XtTranslations setpen_trans; @@ -48,7 +49,8 @@ typedef struct _XmdsWavedrawClassPart { caddr_t extension; } XmdsWavedrawClassPart; -typedef struct _XmdsWavedrawClassRec { +typedef struct _XmdsWavedrawClassRec +{ CoreClassPart core_class; XmPrimitiveClassPart primitive_class; XmdsWaveformClassPart waveform_class; @@ -57,7 +59,8 @@ typedef struct _XmdsWavedrawClassRec { externalref XmdsWavedrawClassRec xmdsWavedrawClassRec; -typedef struct _XmdsWavedrawAxis { +typedef struct _XmdsWavedrawAxis +{ float *low; float *high; float *min_distance; @@ -67,7 +70,8 @@ typedef struct _XmdsWavedrawAxis { float *grid_snap; } XmdsWavedrawAxis; -typedef struct _XmdsWavedrawPart { +typedef struct _XmdsWavedrawPart +{ XtCallbackList move_callback; XtCallbackList select_callback; XtCallbackList deselect_callback; @@ -83,7 +87,8 @@ typedef struct _XmdsWavedrawPart { } XmdsWavedrawPart; /* Full instance record declaration */ -typedef struct _XmdsWavedrawRec { +typedef struct _XmdsWavedrawRec +{ CorePart core; XmPrimitivePart common; XmdsWaveformPart waveform; diff --git a/include/Xmds/XmdsWaveform.h b/include/Xmds/XmdsWaveform.h index 5a19135d3a..48ffb41744 100644 --- a/include/Xmds/XmdsWaveform.h +++ b/include/Xmds/XmdsWaveform.h @@ -50,36 +50,36 @@ /* Global Resources */ #define XmdsNtitle "title" /* Title string displayed at top of waveform */ -#define XmdsNpointerMode \ - "pointerMode" /* Selects pointer mode (i.e. zoom, crosshairs, drag) */ +#define XmdsNpointerMode \ + "pointerMode" /* Selects pointer mode (i.e. zoom, crosshairs, drag) */ #define XmdsNlabelFont "labelFont" /* Font used for title and axis labels */ -#define XmdsNshowMode \ - "showMode" /* Show lines, points, or both (box at data points) */ +#define XmdsNshowMode \ + "showMode" /* Show lines, points, or both (box at data points) */ #define XmdsNshowSelections "showSelections" /* Show selection points */ #define XmdsNstepPlot "stepPlot" /* Step plot mode */ #define XmdsNcount "count" /* Number of X,Y datapoints */ #define XmdsNselections "selections" /* Selections (char [count]) */ -#define XmdsNselectionsValStruct \ +#define XmdsNselectionsValStruct \ "selectionsValStruct" /* Selections (using value struct mechanism) */ #define XmdsNpenDown "penDown" /* Pen down (char [count]) */ -#define XmdsNpenDownValStruct \ +#define XmdsNpenDownValStruct \ "penDownValStruct" /* Pen down (using value struct mechanism) */ #define XmdsNpanWith "panWith" /* Pan with widget */ -#define XmdsNattachCrosshairs \ +#define XmdsNattachCrosshairs \ "attachCrosshairs" /* Attach crosshairs to curve - boolean */ -#define XmdsNdisabled \ +#define XmdsNdisabled \ "disabled" /* True = disable drawing until disabled cleared */ -#define XmdsNclosed \ - "closed" /* True = connect last point to first point - boolean */ +#define XmdsNclosed \ + "closed" /* True = connect last point to first point - boolean */ #define XmdsNgridStyle "gridStyle" /* Select type of grid */ /* X-axis Resources */ #define XmdsNxValue "xValue" /* float X-values[count] */ -#define XmdsNxValStruct \ - "xValStruct" /* X-values (using value struct mechanism) */ -#define XmdsNxMin "xMin" /* float *min_x */ -#define XmdsNxMax "xMax" /* float *max_x */ +#define XmdsNxValStruct \ + "xValStruct" /* X-values (using value struct mechanism) */ +#define XmdsNxMin "xMin" /* float *min_x */ +#define XmdsNxMax "xMax" /* float *max_x */ #define XmdsNxCrosshair "xCrosshair" /* float *x_crosshair */ #define XmdsNxGridLines "xGridLines" /* int number of grid lines */ #define XmdsNxLabels "xLabels" /* boolean display labels */ @@ -96,27 +96,28 @@ /* Callbacks */ -#define XmdsNbutton3Callback \ +#define XmdsNbutton3Callback \ "button3Callback" /* Callback when button 3 is pressed */ #define XmdsNcrosshairsCallback \ "crosshairsCallback" /* Callback when crosshairs change position in waveform \ window */ -#define XmdsNalignCallback \ - "alignCallback" /* Callback when right button is depressed in crosshairs \ +#define XmdsNalignCallback \ + "alignCallback" /* Callback when right button is depressed in crosshairs \ pointer mode */ #define XmdsNlimitsCallback \ "limitsCallback" /* Callback when change in max/min axis values (after zoom, \ pan, etc.) */ -#define XmdsNunderlayCallback \ +#define XmdsNunderlayCallback \ "underlayCallback" /* Callback to write to window before waveform */ -#define XmdsNoverlayCallback \ - "overlayCallback" /* Callback to write to window after waveform */ +#define XmdsNoverlayCallback \ + "overlayCallback" /* Callback to write to window after waveform */ #define XmdsNcutCallback "cutCallback" /* Callback when cut occurs */ #define XmdsNpasteCallback "pasteCallback" /* Callback when paste occurs */ /* Value Struct resource mechanism */ -typedef struct _XmdsWaveformValStruct { +typedef struct _XmdsWaveformValStruct +{ unsigned int size; caddr_t addr; void (*destroy)(); /* Destroy called with widget and destroy arg */ @@ -124,14 +125,16 @@ typedef struct _XmdsWaveformValStruct { } XmdsWaveformValStruct, *XmdsWaveformValStructPtr; /* Callback structures */ -typedef struct { +typedef struct +{ int reason; XEvent *event; float x; float y; } XmdsWaveformCrosshairsCBStruct; -typedef struct { +typedef struct +{ int reason; XEvent *event; float *xminval; @@ -162,7 +165,8 @@ typedef struct { #define XmdsSHOW_MODE_POINTS 1 #define XmdsSHOW_MODE_BOTH 2 -enum XmdsWaveformMotionRestriction { +enum XmdsWaveformMotionRestriction +{ XmdsMOTION_UNSELECTED, XmdsMOTION_BOTH, XmdsMOTION_XONLY, @@ -170,7 +174,11 @@ enum XmdsWaveformMotionRestriction { XmdsMOTION_NONE }; -enum XmdsWaveformGridStyle { XmdsGRID_STYLE_LINES, XmdsGRID_STYLE_TICKS }; +enum XmdsWaveformGridStyle +{ + XmdsGRID_STYLE_LINES, + XmdsGRID_STYLE_TICKS +}; /* Class record constants */ externalref WidgetClass xmdsWaveformWidgetClass; diff --git a/include/Xmds/XmdsWaveformP.h b/include/Xmds/XmdsWaveformP.h index e149d40a71..dafa5953ad 100644 --- a/include/Xmds/XmdsWaveformP.h +++ b/include/Xmds/XmdsWaveformP.h @@ -82,17 +82,18 @@ #define XmdsInheritUpdate \ ((void (*)(Widget, XmdsWaveformValStruct *, XmdsWaveformValStruct *, char *, \ float *, float *, float *, float *, Boolean))_XtInherit) -#define XmdsInheritSetCrosshairs \ +#define XmdsInheritSetCrosshairs \ ((void (*)(Widget, float *, float *, Boolean))_XtInherit) #define XmdsInheritSetPointerMode ((void (*)(Widget, int))_XtInherit) -#define XmdsInheritPrint \ +#define XmdsInheritPrint \ ((void (*)(Widget, FILE *, int, int, int, char *, char *, int))_XtInherit) #define XmdsInheritReverse ((void (*)(Widget, int))_XtInherit) -#define XmdsInheritSetWave \ - ((void (*)(Widget, int, float *, float *, Boolean *, Boolean *, Boolean, \ +#define XmdsInheritSetWave \ + ((void (*)(Widget, int, float *, float *, Boolean *, Boolean *, Boolean, \ Boolean))_XtInherit) -typedef struct _WaveformClassPart { +typedef struct _WaveformClassPart +{ XtTranslations default_trans; XtTranslations zoom_trans; XtTranslations drag_trans; @@ -120,7 +121,8 @@ typedef struct _WaveformClassPart { } XmdsWaveformClassPart; /* Full class record declaration */ -typedef struct _XmdsWaveformClassRec { +typedef struct _XmdsWaveformClassRec +{ CoreClassPart core_class; XmPrimitiveClassPart primitive_class; XmdsWaveformClassPart waveform_class; @@ -131,7 +133,8 @@ externalref XmdsWaveformClassRec xmdsWaveformClassRec; /* Fields describing each axis */ -typedef struct _XmdsWaveformAxis { +typedef struct _XmdsWaveformAxis +{ float *minval; float *maxval; double crosshair; @@ -147,7 +150,8 @@ typedef struct _XmdsWaveformAxis { } XmdsWaveformAxis; /* Fields global to widget */ -typedef struct _WaveformPart { +typedef struct _WaveformPart +{ char *title; int pointer_mode; int grid_style; @@ -196,7 +200,8 @@ typedef struct _WaveformPart { * ****************************************************************/ -typedef struct _XmdsWaveformRec { +typedef struct _XmdsWaveformRec +{ CorePart core; XmPrimitivePart primitive; XmdsWaveformPart waveform; diff --git a/include/Xmds/XmdsXdBoxDialogButton.h b/include/Xmds/XmdsXdBoxDialogButton.h index 9420105820..afeac1620b 100644 --- a/include/Xmds/XmdsXdBoxDialogButton.h +++ b/include/Xmds/XmdsXdBoxDialogButton.h @@ -35,8 +35,8 @@ #define XmdsNnid "nid" /* Nid */ #define XmdsNnidOffset "nidOffset" /* Nid offset */ -#define XmdsNputOnApply \ - "putOnApply" /* Put when a XmdsApplyAllXds is called \ +#define XmdsNputOnApply \ + "putOnApply" /* Put when a XmdsApplyAllXds is called \ */ /* External creation routines: diff --git a/include/Xmds/XmdsXdBoxOnOffButton.h b/include/Xmds/XmdsXdBoxOnOffButton.h index af151d8a7c..7354f54bc6 100644 --- a/include/Xmds/XmdsXdBoxOnOffButton.h +++ b/include/Xmds/XmdsXdBoxOnOffButton.h @@ -34,8 +34,8 @@ #define XmdsNnid "nid" /* Nid */ #define XmdsNnidOffset "nidOffset" /* Nid offset */ -#define XmdsNputOnApply \ - "putOnApply" /* Put when a XmdsApplyAllXds is called \ +#define XmdsNputOnApply \ + "putOnApply" /* Put when a XmdsApplyAllXds is called \ */ /* External creation routines: diff --git a/include/Xmds/XmdsXdBoxP.h b/include/Xmds/XmdsXdBoxP.h index 0758266f1f..3d2905924c 100644 --- a/include/Xmds/XmdsXdBoxP.h +++ b/include/Xmds/XmdsXdBoxP.h @@ -43,12 +43,14 @@ /* New fields for the Xd Widget record */ -typedef struct _XmdsXdUserPart { +typedef struct _XmdsXdUserPart +{ void (*load_dlog_proc)(); struct descriptor_xd *(*unload_dlog_proc)(); } XmdsXdUserPart; -typedef struct _XmdsXdBoxPart { +typedef struct _XmdsXdBoxPart +{ int nid; int nid_offset; int default_nid; @@ -81,7 +83,8 @@ typedef struct _XmdsXdBoxPart { /* * now define the actual widget data struct */ -typedef struct _XmdsXdBoxWidgetRec { +typedef struct _XmdsXdBoxWidgetRec +{ CorePart core; /* basic widget */ CompositePart composite; /* composite specific data */ ConstraintPart constraint; @@ -94,7 +97,8 @@ typedef struct _XmdsXdBoxWidgetRec { * dialog box. */ -typedef struct _XmdsXdBoxClassPart { +typedef struct _XmdsXdBoxClassPart +{ MrmHierarchy drm; caddr_t extension; /* Pointer to extension record */ } XmdsXdBoxClassPart; @@ -103,7 +107,8 @@ typedef struct _XmdsXdBoxClassPart { * The XdBox Class record is a composite class plus * the XdBoxClassPart */ -typedef struct _XmdsXdBoxClassRec { +typedef struct _XmdsXdBoxClassRec +{ CoreClassPart core_class; CompositeClassPart composite_class; ConstraintClassPart constraint_class; diff --git a/include/condition.h b/include/condition.h index c26262a946..bdd85fa940 100644 --- a/include/condition.h +++ b/include/condition.h @@ -2,83 +2,95 @@ #define CONDITION_H #include -typedef struct _Condition { +typedef struct _Condition +{ pthread_cond_t cond; pthread_mutex_t mutex; int value; } Condition; -typedef struct _Condition_p { +typedef struct _Condition_p +{ pthread_cond_t cond; pthread_mutex_t mutex; void *value; } Condition_p; -#define CONDITION_INITIALIZER \ - { PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, B_FALSE } +#define CONDITION_INITIALIZER \ + { \ + PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, B_FALSE \ + } -#define CONDITION_INIT(input) \ - do { \ - (input)->value = 0; \ - pthread_cond_init(&(input)->cond, pthread_condattr_default); \ - pthread_mutex_init(&(input)->mutex, pthread_mutexattr_default); \ +#define CONDITION_INIT(input) \ + do \ + { \ + (input)->value = 0; \ + pthread_cond_init(&(input)->cond, pthread_condattr_default); \ + pthread_mutex_init(&(input)->mutex, pthread_mutexattr_default); \ } while (0) #define _CONDITION_LOCK(input) pthread_mutex_lock(&(input)->mutex) #define _CONDITION_UNLOCK(input) pthread_mutex_unlock(&(input)->mutex) #define _CONDITION_SIGNAL(input) pthread_cond_signal(&(input)->cond) -#define _CONDITION_WAIT(input) \ +#define _CONDITION_WAIT(input) \ pthread_cond_wait(&(input)->cond, &(input)->mutex) -#define _CONDITION_WAIT_SET(input) \ - while (!(input)->value) \ +#define _CONDITION_WAIT_SET(input) \ + while (!(input)->value) \ _CONDITION_WAIT(input) -#define _CONDITION_WAIT_RESET(input) \ - while ((input)->value) \ +#define _CONDITION_WAIT_RESET(input) \ + while ((input)->value) \ _CONDITION_WAIT(input) -#define _CONDITION_WAIT_1SEC(input, status) \ - do { \ - struct timespec tp; \ - clock_gettime(CLOCK_REALTIME, &tp); \ - tp.tv_sec++; \ - status pthread_cond_timedwait(&(input)->cond, &(input)->mutex, &tp); \ +#define _CONDITION_WAIT_1SEC(input, status) \ + do \ + { \ + struct timespec tp; \ + clock_gettime(CLOCK_REALTIME, &tp); \ + tp.tv_sec++; \ + status pthread_cond_timedwait(&(input)->cond, &(input)->mutex, &tp); \ } while (0) -#define CONDITION_SET_TO(input, value_in) \ - do { \ - _CONDITION_LOCK(input); \ - (input)->value = value_in; \ - _CONDITION_SIGNAL(input); \ - _CONDITION_UNLOCK(input); \ +#define CONDITION_SET_TO(input, value_in) \ + do \ + { \ + _CONDITION_LOCK(input); \ + (input)->value = value_in; \ + _CONDITION_SIGNAL(input); \ + _CONDITION_UNLOCK(input); \ } while (0) #define CONDITION_SET(input) CONDITION_SET_TO(input, B_TRUE) #define CONDITION_RESET(input) CONDITION_SET_TO(input, 0) -#define CONDITION_WAIT_SET(input) \ - do { \ - _CONDITION_LOCK(input); \ - _CONDITION_WAIT_SET(input); \ - _CONDITION_UNLOCK(input); \ +#define CONDITION_WAIT_SET(input) \ + do \ + { \ + _CONDITION_LOCK(input); \ + _CONDITION_WAIT_SET(input); \ + _CONDITION_UNLOCK(input); \ } while (0) -#define CONDITION_WAIT_1SEC(input) \ - do { \ - _CONDITION_LOCK(input); \ - _CONDITION_WAIT_1SEC(input, ); \ - _CONDITION_UNLOCK(input); \ +#define CONDITION_WAIT_1SEC(input) \ + do \ + { \ + _CONDITION_LOCK(input); \ + _CONDITION_WAIT_1SEC(input, ); \ + _CONDITION_UNLOCK(input); \ } while (0) -#define CONDITION_DESTROY(input, destroy_lock) \ - do { \ - pthread_mutex_lock(destroy_lock); \ - pthread_cond_destroy(&(input)->cond); \ - pthread_mutex_destroy(&(input)->mutex); \ - pthread_mutex_unlock(destroy_lock); \ +#define CONDITION_DESTROY(input, destroy_lock) \ + do \ + { \ + pthread_mutex_lock(destroy_lock); \ + pthread_cond_destroy(&(input)->cond); \ + pthread_mutex_destroy(&(input)->mutex); \ + pthread_mutex_unlock(destroy_lock); \ } while (0) -#define CONDITION_DESTROY_PTR(input, destroy_lock) \ - do { \ - pthread_mutex_lock(destroy_lock); \ - if (input) { \ - pthread_cond_destroy(&(input)->cond); \ - pthread_mutex_destroy(&(input)->mutex); \ - free(input); \ - (input) = NULL; \ - } \ - pthread_mutex_unlock(destroy_lock); \ +#define CONDITION_DESTROY_PTR(input, destroy_lock) \ + do \ + { \ + pthread_mutex_lock(destroy_lock); \ + if (input) \ + { \ + pthread_cond_destroy(&(input)->cond); \ + pthread_mutex_destroy(&(input)->mutex); \ + free(input); \ + (input) = NULL; \ + } \ + pthread_mutex_unlock(destroy_lock); \ } while (0) #define CREATE_THREAD(thread, stacksize, target, args) \ pthread_attr_t attr; \ @@ -86,25 +98,30 @@ typedef struct _Condition_p { pthread_attr_setstacksize(&attr, DEFAULT_STACKSIZE stacksize); \ int c_status = pthread_create(&thread, &attr, (void *)target, (void *)args); \ pthread_attr_destroy(&attr) -#define CREATE_DETACHED_THREAD(thread, stacksize, target, args) \ - CREATE_THREAD(thread, stacksize, target, args); \ - if (!c_status) \ +#define CREATE_DETACHED_THREAD(thread, stacksize, target, args) \ + CREATE_THREAD(thread, stacksize, target, args); \ + if (!c_status) \ pthread_detach(thread); -#define CONDITION_START_THREAD(input, thread, stacksize, target, args) \ - do { \ - _CONDITION_LOCK(input); \ - if (!(input)->value) { \ - CREATE_DETACHED_THREAD(thread, stacksize, target, args); \ - if (c_status) { \ - perror("Error creating pthread"); \ - status = MDSplusERROR; \ - } else { \ - _CONDITION_WAIT_SET(input); \ - status = MDSplusSUCCESS; \ - } \ - } \ - _CONDITION_UNLOCK(input); \ +#define CONDITION_START_THREAD(input, thread, stacksize, target, args) \ + do \ + { \ + _CONDITION_LOCK(input); \ + if (!(input)->value) \ + { \ + CREATE_DETACHED_THREAD(thread, stacksize, target, args); \ + if (c_status) \ + { \ + perror("Error creating pthread"); \ + status = MDSplusERROR; \ + } \ + else \ + { \ + _CONDITION_WAIT_SET(input); \ + status = MDSplusSUCCESS; \ + } \ + } \ + _CONDITION_UNLOCK(input); \ } while (0) //" #endif // CONDITION_H diff --git a/include/coz.h b/include/coz.h index 0c156524c2..c73ed8a6a4 100644 --- a/include/coz.h +++ b/include/coz.h @@ -22,75 +22,83 @@ #include /* for memcpy hack below */ #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif #define COZ_COUNTER_TYPE_THROUGHPUT 1 #define COZ_COUNTER_TYPE_BEGIN 2 #define COZ_COUNTER_TYPE_END 3 -// Declare dlsym as a weak reference so libdl isn't required -void *dlsym(void *handle, const char *symbol) __attribute__((weak)); - -// Counter info struct, containing both a counter and backoff size -typedef struct { - size_t count; // The actual count - size_t - backoff; // Used to batch updates to the shared counter. Currently unused. -} coz_counter_t; - -// The type of the _coz_get_counter function -typedef coz_counter_t *(*coz_get_counter_t)(int, const char *); - -// Locate and invoke _coz_get_counter -static coz_counter_t *_call_coz_get_counter(int type, const char *name) { - static unsigned char _initialized = 0; - static coz_get_counter_t fn; // The pointer to _coz_get_counter - - if (!_initialized) { - if (dlsym) { - // Locate the _coz_get_counter method - void *p = dlsym(RTLD_DEFAULT, "_coz_get_counter"); - - // Use memcpy to avoid pedantic GCC complaint about storing function - // pointer in void* - memcpy(&fn, &p, sizeof(p)); + // Declare dlsym as a weak reference so libdl isn't required + void *dlsym(void *handle, const char *symbol) __attribute__((weak)); + + // Counter info struct, containing both a counter and backoff size + typedef struct + { + size_t count; // The actual count + size_t + backoff; // Used to batch updates to the shared counter. Currently unused. + } coz_counter_t; + + // The type of the _coz_get_counter function + typedef coz_counter_t *(*coz_get_counter_t)(int, const char *); + + // Locate and invoke _coz_get_counter + static coz_counter_t *_call_coz_get_counter(int type, const char *name) + { + static unsigned char _initialized = 0; + static coz_get_counter_t fn; // The pointer to _coz_get_counter + + if (!_initialized) + { + if (dlsym) + { + // Locate the _coz_get_counter method + void *p = dlsym(RTLD_DEFAULT, "_coz_get_counter"); + + // Use memcpy to avoid pedantic GCC complaint about storing function + // pointer in void* + memcpy(&fn, &p, sizeof(p)); + } + + _initialized = 1; } - _initialized = 1; + // Call the function, or return null if profiler is not found + if (fn) + return fn(type, name); + else + return 0; } - - // Call the function, or return null if profiler is not found - if (fn) - return fn(type, name); - else - return 0; -} #include -static pthread_mutex_t coz_lock = PTHREAD_MUTEX_INITIALIZER; + static pthread_mutex_t coz_lock = PTHREAD_MUTEX_INITIALIZER; // Macro to initialize and increment a counter -#define COZ_INCREMENT_COUNTER(type, name) \ - do { \ - pthread_mutex_lock(&coz_lock); \ - static unsigned char _initialized = 0; \ - static coz_counter_t *_counter = 0; \ - if (!_initialized) { \ - _counter = _call_coz_get_counter(type, name); \ - _initialized = 1; \ - } \ - if (_counter) { \ - __atomic_add_fetch(&_counter->count, 1, __ATOMIC_RELAXED); \ - } \ - pthread_mutex_unlock(&coz_lock); \ +#define COZ_INCREMENT_COUNTER(type, name) \ + do \ + { \ + pthread_mutex_lock(&coz_lock); \ + static unsigned char _initialized = 0; \ + static coz_counter_t *_counter = 0; \ + if (!_initialized) \ + { \ + _counter = _call_coz_get_counter(type, name); \ + _initialized = 1; \ + } \ + if (_counter) \ + { \ + __atomic_add_fetch(&_counter->count, 1, __ATOMIC_RELAXED); \ + } \ + pthread_mutex_unlock(&coz_lock); \ } while (0) #define STR2(x) #x #define STR(x) STR2(x) -#define COZ_PROGRESS_NAMED(name) \ +#define COZ_PROGRESS_NAMED(name) \ COZ_INCREMENT_COUNTER(COZ_COUNTER_TYPE_THROUGHPUT, name) -#define COZ_PROGRESS \ +#define COZ_PROGRESS \ COZ_INCREMENT_COUNTER(COZ_COUNTER_TYPE_THROUGHPUT, __FILE__ ":" STR(__LINE__)) #define COZ_BEGIN(name) COZ_INCREMENT_COUNTER(COZ_COUNTER_TYPE_BEGIN, name) #define COZ_END(name) COZ_INCREMENT_COUNTER(COZ_COUNTER_TYPE_END, name) diff --git a/include/dbidef.h b/include/dbidef.h index 069fa83ba9..8f3ffe03c0 100644 --- a/include/dbidef.h +++ b/include/dbidef.h @@ -11,22 +11,23 @@ #define DbiEND_OF_LIST 0 /* End of list */ #define DbiNAME 1 /* Experiment name used for open - text string */ #define DbiSHOTID 2 /* Shot identification - longword */ -#define DbiMODIFIED \ - 3 /* True if tree has been modified during edit - boolean \ - */ +#define DbiMODIFIED \ + 3 /* True if tree has been modified during edit - boolean \ + */ #define DbiOPEN_FOR_EDIT 4 /* True if tree is open for edit - boolean */ -#define DbiINDEX \ - 5 /* Index of tree to use for subsequent information requests */ -#define DbiNUMBER_OPENED 6 /* Number of trees currently open */ -#define DbiMAX_OPEN 7 /* Maximum number of tree allowed open at one time */ -#define DbiDEFAULT 8 /* NID of default node */ -#define DbiOPEN_READONLY 9 /* True if tree has been opened readonly */ +#define DbiINDEX \ + 5 /* Index of tree to use for subsequent information requests */ +#define DbiNUMBER_OPENED 6 /* Number of trees currently open */ +#define DbiMAX_OPEN 7 /* Maximum number of tree allowed open at one time */ +#define DbiDEFAULT 8 /* NID of default node */ +#define DbiOPEN_READONLY 9 /* True if tree has been opened readonly */ #define DbiVERSIONS_IN_MODEL 10 /* True if using versioning in model */ #define DbiVERSIONS_IN_PULSE 11 /* True if using versioning in pulse files */ #define DbiREADONLY 12 /* True if making tree readonly */ #define DbiDISPATCH_TABLE 13 /* Tree dispatch table */ -typedef struct dbi_itm { +typedef struct dbi_itm +{ short int buffer_length; short int code; void *pointer; diff --git a/include/dtypedef.h b/include/dtypedef.h index 74067a1d89..16a0947913 100644 --- a/include/dtypedef.h +++ b/include/dtypedef.h @@ -7,17 +7,17 @@ DEFINE(BU, 2) /* byte (unsigned); 8-bit unsigned quantity */ DEFINE(WU, 3) /* word (unsigned); 16-bit unsigned quantity */ DEFINE(LU, 4) /* longword (unsigned); 32-bit unsigned quantity */ DEFINE(QU, 5) /* quadword (unsigned); 64-bit unsigned quantity */ -DEFINE(B, 6) /* byte integer (signed); 8-bit signed 2's-complement integer */ -DEFINE(W, 7) /* word integer (signed); 16-bit signed 2's-complement integer */ +DEFINE(B, 6) /* byte integer (signed); 8-bit signed 2's-complement integer */ +DEFINE(W, 7) /* word integer (signed); 16-bit signed 2's-complement integer */ DEFINE(L, 8) /* longword integer (signed); 32-bit signed 2's-complement integer */ DEFINE(Q, - 9) /* quadword integer (signed); 64-bit signed 2's-complement integer */ -DEFINE(F, 10) /* F_floating; 32-bit single-precision floating point */ -DEFINE(D, 11) /* D_floating; 64-bit double-precision floating point */ -DEFINE(FC, 12) /* F_floating complex */ -DEFINE(DC, 13) /* D_floating complex */ -DEFINE(T, 14) /* character string; a single 8-bit character or a sequence of + 9) /* quadword integer (signed); 64-bit signed 2's-complement integer */ +DEFINE(F, 10) /* F_floating; 32-bit single-precision floating point */ +DEFINE(D, 11) /* D_floating; 64-bit double-precision floating point */ +DEFINE(FC, 12) /* F_floating complex */ +DEFINE(DC, 13) /* D_floating complex */ +DEFINE(T, 14) /* character string; a single 8-bit character or a sequence of characters */ DEFINE(NU_deprecated, 15) /* numeric string) unsigned */ DEFINE(NL_deprecated, 16) /* numeric string) left separate sign */ @@ -32,11 +32,11 @@ DEFINE(DSC, 24) /* descriptor */ DEFINE(OU, 25) /* octaword (unsigned); 128-bit unsigned quantity */ DEFINE( O, - 26) /* octaword integer (signed); 128-bit signed 2's-complement integer */ -DEFINE(G, 27) /* G_floating; 64-bit double-precision floating point */ -DEFINE(H, 28) /* H_floating; 128-bit quadruple-precision floating point */ -DEFINE(GC, 29) /* G_floating complex */ -DEFINE(HC, 30) /* H_floating complex */ + 26) /* octaword integer (signed); 128-bit signed 2's-complement integer */ +DEFINE(G, 27) /* G_floating; 64-bit double-precision floating point */ +DEFINE(H, 28) /* H_floating; 128-bit quadruple-precision floating point */ +DEFINE(GC, 29) /* G_floating complex */ +DEFINE(HC, 30) /* H_floating complex */ DEFINE(CIT_deprecated, 31) /* COBOL Intermediate Temporary */ DEFINE(BPV_deprecated, 32) /* bound procedure value */ DEFINE(BLV_deprecated, 33) /* bound label value */ diff --git a/include/getusername.h b/include/getusername.h index f9a7bb663d..111a71159d 100644 --- a/include/getusername.h +++ b/include/getusername.h @@ -10,22 +10,24 @@ #endif #include -#define GETUSERNAME(user_p) \ - GETUSERNAME_BEGIN(user_p); \ +#define GETUSERNAME(user_p) \ + GETUSERNAME_BEGIN(user_p); \ GETUSERNAME_END; -#define GETUSERNAME_BEGIN(user_p) \ - { \ - static pthread_mutex_t username_mutex = PTHREAD_MUTEX_INITIALIZER; \ - pthread_mutex_lock(&username_mutex); \ - if (!user_p) { \ - user_p = _getUserName() +#define GETUSERNAME_BEGIN(user_p) \ + { \ + static pthread_mutex_t username_mutex = PTHREAD_MUTEX_INITIALIZER; \ + pthread_mutex_lock(&username_mutex); \ + if (!user_p) \ + { \ + user_p = _getUserName() -#define GETUSERNAME_END \ - } \ - pthread_mutex_unlock(&username_mutex); \ +#define GETUSERNAME_END \ + } \ + pthread_mutex_unlock(&username_mutex); \ } -static char *_getUserName() { +static char *_getUserName() +{ char *user_p; #ifdef _WIN32 static char user[128]; @@ -36,19 +38,23 @@ static char *_getUserName() { #else static char user[256]; struct passwd *pwd = getpwuid(geteuid()); - if (pwd) { + if (pwd) + { strcpy(user, pwd->pw_name); user_p = user; - } else + } + else #ifdef __APPLE__ user_p = "Apple User"; #else { user_p = getlogin(); - if (user_p && strlen(user_p) > 0) { + if (user_p && strlen(user_p) > 0) + { strcpy(user, user_p); user_p = user; - } else + } + else user_p = "Linux User"; } #endif diff --git a/include/int128.h b/include/int128.h index 84e218c165..23d79d68af 100644 --- a/include/int128.h +++ b/include/int128.h @@ -11,20 +11,24 @@ #define int64_max 0x7fffffffffffffffLL #define int64_min 0x8000000000000000LL #ifdef WORDS_BIGENDIAN -typedef struct int128_s { +typedef struct int128_s +{ int64_t high; uint64_t low; } int128_t; -typedef struct uint128_s { +typedef struct uint128_s +{ uint64_t high; uint64_t low; } uint128_t; #else -typedef struct int128_s { +typedef struct int128_s +{ uint64_t low; int64_t high; } int128_t; -typedef struct uint128_s { +typedef struct uint128_s +{ uint64_t low; uint64_t high; } uint128_t; @@ -36,7 +40,8 @@ typedef struct uint128_s { #define uint128_max {.high = uint64_max, .low = uint64_max}; #define uint128_min {.high = uint64_min, .low = uint64_min}; -static inline void int128_minus(const int128_t *a, int128_t *ans) { +static inline void int128_minus(const int128_t *a, int128_t *ans) +{ ans->high = ~(a->high); ans->low = ~(a->low); ans->low++; @@ -44,8 +49,10 @@ static inline void int128_minus(const int128_t *a, int128_t *ans) { ans->high++; } -static inline int int128_abs(const int128_t *x, int128_t *r) { - if (x->high >= 0) { +static inline int int128_abs(const int128_t *x, int128_t *r) +{ + if (x->high >= 0) + { if (x != r) memcpy(r, x, sizeof(int128_t)); return 0; @@ -55,61 +62,78 @@ static inline int int128_abs(const int128_t *x, int128_t *r) { } static inline void uint128_lshft(const uint128_t *x, const int n, - uint128_t *r) { + uint128_t *r) +{ int nn = n % 128; if (nn < 0) nn += 128; - if (nn > 63) { + if (nn > 63) + { r->high = x->low << (nn - 64); r->low = 0; - } else { + } + else + { r->high = x->high << nn | x->low >> (64 - nn); r->low = x->low << nn; } } static inline void uint128_rshft(const uint128_t *x, const int n, - uint128_t *r) { + uint128_t *r) +{ int nn = n % 128; if (nn < 0) nn += 128; - if (nn > 63) { + if (nn > 63) + { r->low = x->high >> (nn - 64); r->high = 0; - } else { + } + else + { r->low = x->low >> nn | x->high << (64 - nn); r->high = x->high >> nn; } } -static inline void int128_lshft(const int128_t *x, const int n, int128_t *r) { +static inline void int128_lshft(const int128_t *x, const int n, int128_t *r) +{ int nn = n % 128; if (nn < 0) nn += 128; - if (nn > 63) { + if (nn > 63) + { r->high = x->low << (nn - 64); r->low = 0; - } else { + } + else + { r->high = x->high << nn | x->low >> (64 - nn); r->low = x->low << nn; } } -static inline void int128_rshft(const int128_t *x, const int n, int128_t *r) { +static inline void int128_rshft(const int128_t *x, const int n, int128_t *r) +{ int nn = n % 128; if (nn < 0) nn += 128; - if (nn > 63) { + if (nn > 63) + { r->low = x->high >> (nn - 64); r->high = 0; - } else { + } + else + { r->low = x->low >> nn | x->high << (64 - nn); r->high = x->high >> nn; } } static inline void uint128_ishft(const uint128_t *x, const int n, - uint128_t *r) { + uint128_t *r) +{ if (n < 0) return uint128_rshft(x, -n, r); return uint128_lshft(x, n, r); @@ -118,20 +142,23 @@ static inline void uint128_ishft(const uint128_t *x, const int n, #define INT128_BUFLEN 128 / 3 + 2 #define INT128_BUF(buf) char buf[INT128_BUFLEN] -static char *uint128_deco(const uint128_t *in, char *p) { +static char *uint128_deco(const uint128_t *in, char *p) +{ uint128_t n; int i; memset(p, '0', INT128_BUFLEN - 1); p[INT128_BUFLEN - 1] = '\0'; memcpy(&n, in, sizeof(n)); - for (i = 0; i < 128; i++) { + for (i = 0; i < 128; i++) + { int j, carry; carry = (n.high > int64_max); // Shift n[] left, doubling it n.high = (n.high << 1) + (n.low > int64_max); n.low = (n.low << 1); // Add s[] to itself in decimal, doubling it - for (j = INT128_BUFLEN - 1; j-- > 0;) { + for (j = INT128_BUFLEN - 1; j-- > 0;) + { p[j] += p[j] - '0' + carry; carry = (p[j] > '9'); if (carry) @@ -144,7 +171,8 @@ static char *uint128_deco(const uint128_t *in, char *p) { return p; } -static inline char *int128_deco(const int128_t *in, char *p) { +static inline char *int128_deco(const int128_t *in, char *p) +{ int128_t a; int s = int128_abs(in, &a); p = uint128_deco((uint128_t *)&a, p); @@ -153,32 +181,37 @@ static inline char *int128_deco(const int128_t *in, char *p) { return p; } -static inline int uint128_gt(const uint128_t *a, const uint128_t *b) { +static inline int uint128_gt(const uint128_t *a, const uint128_t *b) +{ if (a->high == b->high) return a->low > b->low; return a->high > b->high; } -static inline int int128_gt(const int128_t *a, const int128_t *b) { +static inline int int128_gt(const int128_t *a, const int128_t *b) +{ if (a->high == b->high) return a->low > b->low; return a->high > b->high; } -static inline int uint128_lt(const uint128_t *a, const uint128_t *b) { +static inline int uint128_lt(const uint128_t *a, const uint128_t *b) +{ if (a->high == b->high) return a->low < b->low; return a->high < b->high; } -static inline int int128_lt(const int128_t *a, const int128_t *b) { +static inline int int128_lt(const int128_t *a, const int128_t *b) +{ if (a->high == b->high) return a->low < b->low; return a->high < b->high; } static inline int uint128_add(const uint128_t *a, const uint128_t *b, - uint128_t *ans) { + uint128_t *ans) +{ uint128_t aa; memcpy(&aa, a, sizeof(uint128_t)); ans->low = a->low + b->low; @@ -189,7 +222,8 @@ static inline int uint128_add(const uint128_t *a, const uint128_t *b, } static inline int int128_add(const int128_t *a, const int128_t *b, - int128_t *ans) { + int128_t *ans) +{ int128_t aa; memcpy(&aa, a, sizeof(uint128_t)); ans->low = a->low + b->low; @@ -200,7 +234,8 @@ static inline int int128_add(const int128_t *a, const int128_t *b, } static inline int uint128_sub(const uint128_t *a, const uint128_t *b, - uint128_t *ans) { + uint128_t *ans) +{ uint128_t aa; memcpy(&aa, a, sizeof(uint128_t)); ans->low = a->low - b->low; @@ -211,7 +246,8 @@ static inline int uint128_sub(const uint128_t *a, const uint128_t *b, } static inline int int128_sub(const int128_t *a, const int128_t *b, - int128_t *ans) { + int128_t *ans) +{ int128_t aa; memcpy(&aa, a, sizeof(int128_t)); ans->low = a->low - b->low; @@ -224,7 +260,8 @@ static inline int int128_sub(const int128_t *a, const int128_t *b, #define HI_INT 0xFFFFFFFF00000000LL #define LO_INT 0x00000000FFFFFFFFLL static inline int uint128_mul(const uint128_t *x, const uint128_t *y, - uint128_t *ans) { + uint128_t *ans) +{ /* as by 128-bit integer arithmetic for C++, by Robert Munafo */ uint64_t a[4], b[4], A[4]; a[0] = (x->high & HI_INT) >> 32LL; @@ -238,9 +275,11 @@ static inline int uint128_mul(const uint128_t *x, const uint128_t *y, b[3] = y->low & LO_INT; int i, j; uint64_t carry, acc = 0; - for (j = 4; j-- > 0;) { + for (j = 4; j-- > 0;) + { carry = 0; - for (i = 4; i-- > j;) { + for (i = 4; i-- > j;) + { uint64_t ac2 = acc + a[i] * b[j - i + 3]; if (ac2 < acc) carry++; @@ -255,7 +294,8 @@ static inline int uint128_mul(const uint128_t *x, const uint128_t *y, } static inline int int128_mul(const int128_t *x, const int128_t *d, - int128_t *ans) { + int128_t *ans) +{ uint128_t ux, ud; int mns = (int128_abs(x, (int128_t *)&ux) ^ int128_abs(d, (int128_t *)&ud)); uint128_mul(&ux, &ud, (uint128_t *)ans); @@ -265,17 +305,21 @@ static inline int int128_mul(const int128_t *x, const int128_t *d, } static inline int uint128_div(const uint128_t *x, const uint128_t *y, - uint128_t *ans) { - if (y->low == 0 && y->high == 0) { + uint128_t *ans) +{ + if (y->low == 0 && y->high == 0) + { ans->low = 0; ans->high = 0; return 1; } - if (y->low == 1 && y->high == 0) { + if (y->low == 1 && y->high == 0) + { memcpy(ans, x, sizeof(uint128_t)); return 1; } - if (uint128_lt(x, y)) { + if (uint128_lt(x, y)) + { ans->low = 0; ans->high = 0; return 0; @@ -286,7 +330,8 @@ static inline int uint128_div(const uint128_t *x, const uint128_t *y, uint128_t d; memcpy(&d, y, sizeof(uint128_t)); uint128_sub(&n, &d, &n); - while (!uint128_lt(&n, &d)) { + while (!uint128_lt(&n, &d)) + { uint128_sub(&n, &d, &n); // shift left (*2) d.high = d.high << 1 | d.low >> 63; @@ -295,16 +340,20 @@ static inline int uint128_div(const uint128_t *x, const uint128_t *y, } uint128_add(&n, &d, &n); memset(ans, 0, sizeof(uint128_t)); - for (; p >= 64; p--) { - if (!uint128_lt(&n, &d)) { + for (; p >= 64; p--) + { + if (!uint128_lt(&n, &d)) + { uint128_sub(&n, &d, &n); ans->high |= 1LL << (p - 64); } // shift right (/2) d.low = d.low >> 1 | d.high << 63, d.high = d.high >> 1; } - for (; p >= 0; p--) { - if (!uint128_lt(&n, &d)) { + for (; p >= 0; p--) + { + if (!uint128_lt(&n, &d)) + { uint128_sub(&n, &d, &n); ans->low |= 1LL << p; } @@ -321,7 +370,8 @@ static inline int uint128_div(const uint128_t *x, const uint128_t *y, } static inline int int128_div(const int128_t *x, const int128_t *d, - int128_t *ans) { + int128_t *ans) +{ uint128_t ux, ud; int mns = (int128_abs(x, (int128_t *)&ux) ^ int128_abs(d, (int128_t *)&ud)); uint128_div(&ux, &ud, (uint128_t *)ans); diff --git a/include/ipdesc.h b/include/ipdesc.h index 930588a94f..0a53c0606e 100644 --- a/include/ipdesc.h +++ b/include/ipdesc.h @@ -32,7 +32,8 @@ typedef int SOCKET; #define DTYPE_EVENT_NOTIFY 99 #define DTYPE_SERIAL 24 -struct descrip { +struct descrip +{ char dtype; char ndims; int dims[MAX_DIMS]; @@ -42,32 +43,33 @@ struct descrip { #define EndOfArgs ((struct descrip *)0) #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #ifndef __MDSIP_H__ -extern int ConnectToMds(char *host); -extern int SendArg(int s, unsigned char i, char dtype, unsigned char nargs, - short len, char ndims, int *dims, char *ptr); -extern int GetAnswerInfo(int s, char *dtype, short *len, char *ndims, int *dims, - int *nbytes, void **dptr); -extern int DisconnectFromMds(int conid); -extern struct descrip *MakeDescrip(struct descrip *in_descrip, char dtype, - char ndims, int *dims, void *ptr); -extern struct descrip *MakeDescripWithLength(struct descrip *in_descrip, - char dtype, int length, char ndims, - int *dims, void *ptr); -extern int MdsEventAst(int conid, char *eventnam, void (*astadr)(), - void *astprm, int *eventid); -extern int MdsEventCan(int conid, int eventid); -extern int HostToIp(char *host, int *addr, short *port); + extern int ConnectToMds(char *host); + extern int SendArg(int s, unsigned char i, char dtype, unsigned char nargs, + short len, char ndims, int *dims, char *ptr); + extern int GetAnswerInfo(int s, char *dtype, short *len, char *ndims, int *dims, + int *nbytes, void **dptr); + extern int DisconnectFromMds(int conid); + extern struct descrip *MakeDescrip(struct descrip *in_descrip, char dtype, + char ndims, int *dims, void *ptr); + extern struct descrip *MakeDescripWithLength(struct descrip *in_descrip, + char dtype, int length, char ndims, + int *dims, void *ptr); + extern int MdsEventAst(int conid, char *eventnam, void (*astadr)(), + void *astprm, int *eventid); + extern int MdsEventCan(int conid, int eventid); + extern int HostToIp(char *host, int *addr, short *port); #ifndef MdsLib_H -extern int MdsValue(int conid, char *, ...); -extern int MdsPut(int conid, char *node, char *expression, ...); -extern int MdsOpen(int conid, char *tree, int shot); -extern int MdsSetDefault(int conid, char *node); -extern int MdsClose(int conid); -extern void FreeMessage(void *m); + extern int MdsValue(int conid, char *, ...); + extern int MdsPut(int conid, char *node, char *expression, ...); + extern int MdsOpen(int conid, char *tree, int shot); + extern int MdsSetDefault(int conid, char *node); + extern int MdsClose(int conid); + extern void FreeMessage(void *m); #endif #endif diff --git a/include/mds_gendevice.h b/include/mds_gendevice.h index e991932556..02c589f9a9 100644 --- a/include/mds_gendevice.h +++ b/include/mds_gendevice.h @@ -34,81 +34,83 @@ extern int GenDeviceHeadNid(); #endif -#define DEV$_BAD_ENDIDX \ +#define DEV$_BAD_ENDIDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_FILTER \ +#define DEV$_BAD_FILTER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 2 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_FREQ \ +#define DEV$_BAD_FREQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 3 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_GAIN \ +#define DEV$_BAD_GAIN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 4 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_HEADER \ +#define DEV$_BAD_HEADER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 5 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_HEADER_IDX \ +#define DEV$_BAD_HEADER_IDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 6 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_MEMORIES \ +#define DEV$_BAD_MEMORIES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 7 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_MODE \ +#define DEV$_BAD_MODE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 8 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_NAME \ +#define DEV$_BAD_NAME \ (MSG_MASK + 2015 * MSG_FACNUM_M + 9 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_OFFSET \ +#define DEV$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 10 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_STARTIDX \ +#define DEV$_BAD_STARTIDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 11 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_NOT_TRIGGERED \ +#define DEV$_NOT_TRIGGERED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 12 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_FREQ_TO_HIGH \ +#define DEV$_FREQ_TO_HIGH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 13 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_INVALID_NOC \ +#define DEV$_INVALID_NOC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 14 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_RANGE_MISMATCH \ +#define DEV$_RANGE_MISMATCH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 15 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAMACERR \ +#define DEV$_CAMACERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 16 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_VERBS \ +#define DEV$_BAD_VERBS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 17 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_COMMANDS \ +#define DEV$_BAD_COMMANDS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 18 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_ADNR \ +#define DEV$_CAM_ADNR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 19 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_ERR \ +#define DEV$_CAM_ERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 20 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_LOSYNC \ +#define DEV$_CAM_LOSYNC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 21 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_LPE \ +#define DEV$_CAM_LPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 22 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_TMO \ +#define DEV$_CAM_TMO \ (MSG_MASK + 2015 * MSG_FACNUM_M + 23 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_TPE \ +#define DEV$_CAM_TPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 24 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_STE \ +#define DEV$_CAM_STE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 25 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_DERR \ +#define DEV$_CAM_DERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 26 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_SQ \ +#define DEV$_CAM_SQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 27 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_NOSQ \ +#define DEV$_CAM_NOSQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 28 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_SX \ +#define DEV$_CAM_SX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 29 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_NOSX \ +#define DEV$_CAM_NOSX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 30 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_INV_SETUP \ +#define DEV$_INV_SETUP \ (MSG_MASK + 2015 * MSG_FACNUM_M + 31 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BADPARAM \ +#define DEV$_BADPARAM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 32 * MSG_MSGNUM_M + MSG_ERROR) -#define GEN_DEV$_NODATA \ +#define GEN_DEV$_NODATA \ (MSG_MASK + 2037 * MSG_FACNUM_M + 1 * MSG_MSGNUM_M + MSG_WARNING) -#define GEN_DEV$_INV_SETUP \ +#define GEN_DEV$_INV_SETUP \ (MSG_MASK + 2037 * MSG_FACNUM_M + 2 * MSG_MSGNUM_M + MSG_WARNING) -#define GEN_DEV$_X_IO_ERR \ +#define GEN_DEV$_X_IO_ERR \ (MSG_MASK + 2037 * MSG_FACNUM_M + 3 * MSG_MSGNUM_M + MSG_WARNING) #ifdef MSG_LIBRARY -int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { - static struct msg { +int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) +{ + static struct msg + { int sts; char *facnam; char *msgnam; @@ -167,8 +169,10 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { " Hardware Error: X response failed"}}; size_t i; int status = 0; - for (i = 0; i < sizeof(msgs) / sizeof(struct msg); i++) { - if (msgs[i].sts == sts) { + for (i = 0; i < sizeof(msgs) / sizeof(struct msg); i++) + { + if (msgs[i].sts == sts) + { *facnam = msgs[i].facnam; *msgnam = msgs[i].msgnam; *msgtext = msgs[i].msgtext; @@ -183,124 +187,132 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { #define STRING_LITERAL(string) "" #string "" -#define ADD_NODE(name, usage) \ - { \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, usage); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - flags = 0; \ +#define ADD_NODE(name, usage) \ + { \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, usage); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + flags = 0; \ } -#define ADD_NODE_INTEGER(name, value, usage) \ - { \ - int num = value, curr_usage = usage; \ - struct descriptor num_d = {4, DTYPE_L, CLASS_S, 0}; \ - num_d.pointer = (char *)# \ - if (curr_usage) \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ - else \ - status = \ - TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ - if (status & 1) \ - status = TreePutRecord(curr_nid, &num_d, 0); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - flags = 0; \ +#define ADD_NODE_INTEGER(name, value, usage) \ + { \ + int num = value, curr_usage = usage; \ + struct descriptor num_d = {4, DTYPE_L, CLASS_S, 0}; \ + num_d.pointer = (char *)# \ + if (curr_usage) \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ + else \ + status = \ + TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ + if (status & 1) \ + status = TreePutRecord(curr_nid, &num_d, 0); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + flags = 0; \ } -#define ADD_NODE_FLOAT(name, value, usage) \ - { \ - float num = value; \ - int curr_usage = usage; \ - struct descriptor num_d = {4, DTYPE_F, CLASS_S, 0}; \ - num_d.pointer = (char *)# \ - if (curr_usage) \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ - else \ - status = \ - TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ - if (status & 1) \ - status = TreePutRecord(curr_nid, &num_d, 0); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - flags = 0; \ +#define ADD_NODE_FLOAT(name, value, usage) \ + { \ + float num = value; \ + int curr_usage = usage; \ + struct descriptor num_d = {4, DTYPE_F, CLASS_S, 0}; \ + num_d.pointer = (char *)# \ + if (curr_usage) \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ + else \ + status = \ + TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ + if (status & 1) \ + status = TreePutRecord(curr_nid, &num_d, 0); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + flags = 0; \ } -#define ADD_NODE_STRING(name, string, usage) \ - { \ - DESCRIPTOR(string_d, string); \ - int curr_usage = usage; \ - if (curr_usage) \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ - else \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_TEXT); \ - if (status & 1) \ - status = TreePutRecord(curr_nid, (struct descriptor *)&string_d, 0); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - flags = 0; \ +#define ADD_NODE_STRING(name, string, usage) \ + { \ + DESCRIPTOR(string_d, string); \ + int curr_usage = usage; \ + if (curr_usage) \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ + else \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_TEXT); \ + if (status & 1) \ + status = TreePutRecord(curr_nid, (struct descriptor *)&string_d, 0); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + flags = 0; \ } -#define ADD_NODE_EXPR(name, usage) \ - { \ - DESCRIPTOR(expr_d, expr); \ - usage_t curr_usage = usage; \ - struct descriptor_xd comp_expr_xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; \ - status = \ - TdiCompile((struct descriptor *)&expr_d, &comp_expr_xd MDS_END_ARG); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - if (!curr_usage) { \ - switch (comp_expr_xd.pointer->dtype) { \ - case DTYPE_DISPATCH: \ - curr_usage = TreeUSAGE_DISPATCH; \ - break; \ - case DTYPE_ACTION: \ - curr_usage = TreeUSAGE_ACTION; \ - break; \ - case DTYPE_CONGLOM: \ - curr_usage = TreeUSAGE_DEVICE; \ - break; \ - case DTYPE_PROGRAM: \ - case DTYPE_METHOD: \ - case DTYPE_ROUTINE: \ - curr_usage = TreeUSAGE_TASK; \ - break; \ - case DTYPE_SIGNAL: \ - curr_usage = TreeUSAGE_SIGNAL; \ - break; \ - case DTYPE_RANGE: \ - curr_usage = TreeUSAGE_AXIS; \ - break; \ - case DTYPE_WINDOW: \ - curr_usage = TreeUSAGE_WINDOW; \ - break; \ - case DTYPE_T: \ - curr_usage = TreeUSAGE_TEXT; \ - break; \ - default: \ - curr_usage = TreeUSAGE_NUMERIC; \ - } \ - } \ - status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ - if (status & 1) \ - status = TreePutRecord(curr_nid, comp_expr_xd.pointer, 0); \ - if (!(status & 1)) { \ - TreeSetDefaultNid(old_nid); \ - return status; \ - } \ - MdsFree1Dx(&comp_expr_xd, 0); \ - flags = 0; \ +#define ADD_NODE_EXPR(name, usage) \ + { \ + DESCRIPTOR(expr_d, expr); \ + usage_t curr_usage = usage; \ + struct descriptor_xd comp_expr_xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; \ + status = \ + TdiCompile((struct descriptor *)&expr_d, &comp_expr_xd MDS_END_ARG); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + if (!curr_usage) \ + { \ + switch (comp_expr_xd.pointer->dtype) \ + { \ + case DTYPE_DISPATCH: \ + curr_usage = TreeUSAGE_DISPATCH; \ + break; \ + case DTYPE_ACTION: \ + curr_usage = TreeUSAGE_ACTION; \ + break; \ + case DTYPE_CONGLOM: \ + curr_usage = TreeUSAGE_DEVICE; \ + break; \ + case DTYPE_PROGRAM: \ + case DTYPE_METHOD: \ + case DTYPE_ROUTINE: \ + curr_usage = TreeUSAGE_TASK; \ + break; \ + case DTYPE_SIGNAL: \ + curr_usage = TreeUSAGE_SIGNAL; \ + break; \ + case DTYPE_RANGE: \ + curr_usage = TreeUSAGE_AXIS; \ + break; \ + case DTYPE_WINDOW: \ + curr_usage = TreeUSAGE_WINDOW; \ + break; \ + case DTYPE_T: \ + curr_usage = TreeUSAGE_TEXT; \ + break; \ + default: \ + curr_usage = TreeUSAGE_NUMERIC; \ + } \ + } \ + status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ + if (status & 1) \ + status = TreePutRecord(curr_nid, comp_expr_xd.pointer, 0); \ + if (!(status & 1)) \ + { \ + TreeSetDefaultNid(old_nid); \ + return status; \ + } \ + MdsFree1Dx(&comp_expr_xd, 0); \ + flags = 0; \ } #define ADD_NODE_ACTION(name, method_in, phase_in, sequence, completion_in, \ @@ -334,7 +346,8 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { action_d.task = (struct descriptor *)&task_d; \ if (tim) \ task_d.time_out = &timout_d; \ - if (compl) { \ + if (compl) \ + { \ completion_d.length = strlen(compl); \ dispatch_d.completion = &completion_d; \ } \ @@ -344,22 +357,26 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { status = TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_ACTION); \ if (status & 1) \ status = TreePutRecord(curr_nid, (struct descriptor *)&action_d, 0); \ - if (!(status & 1)) { \ + if (!(status & 1)) \ + { \ TreeSetDefaultNid(old_nid); \ return status; \ } \ flags = 0; \ } -#define COPY_PART_NAME(name) \ - { \ - DESCRIPTOR(return_d, STRING_LITERAL(name)); \ - if (out_d->class == CLASS_XD) { \ - status = MdsCopyDxXd(&return_d, (mdsdsc_xd_t *const)out_d); \ - } else { \ - status = StrCopyDx((struct descriptor *)out_d, \ - (struct descriptor *)&return_d); \ - } \ +#define COPY_PART_NAME(name) \ + { \ + DESCRIPTOR(return_d, STRING_LITERAL(name)); \ + if (out_d->class == CLASS_XD) \ + { \ + status = MdsCopyDxXd(&return_d, (mdsdsc_xd_t *const)out_d); \ + } \ + else \ + { \ + status = StrCopyDx((struct descriptor *)out_d, \ + (struct descriptor *)&return_d); \ + } \ } #define DevNODATA 2 @@ -371,162 +388,169 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { #define DevMODSEAR 6 #define DevMODRANLON 7 -#define declare_variables(in_struct_type) \ - int error_code __attribute__((unused)) = 1; \ - int head_nid = GenDeviceHeadNid(nid_d_ptr), status; \ - short code __attribute__((unused)); \ - struct descriptor_xd xd \ - __attribute__((unused)) = {0, DTYPE_DSC, CLASS_XD, 0, 0}; \ - struct descriptor_a *array_d_ptr __attribute__((unused)); \ - in_struct_type in_struct __attribute__((unused)); \ - static int curr_nid __attribute__((unused)); \ - static int curr_int __attribute__((unused)); \ - static float curr_float __attribute__((unused)); \ - static struct descriptor curr_nid_d __attribute__((unused)) = { \ - sizeof(int), DTYPE_NID, CLASS_S, (char *)&curr_nid}; \ - static struct descriptor curr_float_d __attribute__((unused)) = { \ - sizeof(float), DTYPE_FS, CLASS_S, (char *)&curr_float}; \ - static struct descriptor curr_int_d __attribute__((unused)) = { \ +#define declare_variables(in_struct_type) \ + int error_code __attribute__((unused)) = 1; \ + int head_nid = GenDeviceHeadNid(nid_d_ptr), status; \ + short code __attribute__((unused)); \ + struct descriptor_xd xd \ + __attribute__((unused)) = {0, DTYPE_DSC, CLASS_XD, 0, 0}; \ + struct descriptor_a *array_d_ptr __attribute__((unused)); \ + in_struct_type in_struct __attribute__((unused)); \ + static int curr_nid __attribute__((unused)); \ + static int curr_int __attribute__((unused)); \ + static float curr_float __attribute__((unused)); \ + static struct descriptor curr_nid_d __attribute__((unused)) = { \ + sizeof(int), DTYPE_NID, CLASS_S, (char *)&curr_nid}; \ + static struct descriptor curr_float_d __attribute__((unused)) = { \ + sizeof(float), DTYPE_FS, CLASS_S, (char *)&curr_float}; \ + static struct descriptor curr_int_d __attribute__((unused)) = { \ sizeof(int), DTYPE_L, CLASS_S, (char *)&curr_int}; -#define initialize_variables(in_struct_type) \ - memset((char *)&in_struct, '\0', sizeof(in_struct_type)); \ +#define initialize_variables(in_struct_type) \ + memset((char *)&in_struct, '\0', sizeof(in_struct_type)); \ in_struct.head_nid = head_nid; -#define next_xd \ - memcpy((char *)&work_xd[xd_count++], (char *)&xd, \ - sizeof(struct descriptor_xd)); \ - xd.pointer = 0; \ +#define next_xd \ + memcpy((char *)&work_xd[xd_count++], (char *)&xd, \ + sizeof(struct descriptor_xd)); \ + xd.pointer = 0; \ xd.l_length = 0; -#define read_descriptor(pos, field) \ - curr_nid = head_nid + pos; \ - status = TreeGetRecord(curr_nid, &xd); \ - if (status & 1) \ - in_struct.field = xd.pointer; \ +#define read_descriptor(pos, field) \ + curr_nid = head_nid + pos; \ + status = TreeGetRecord(curr_nid, &xd); \ + if (status & 1) \ + in_struct.field = xd.pointer; \ next_xd -#define read_descriptor_error(pos, field, err) \ - curr_nid = head_nid + pos; \ - status = TreeGetRecord(curr_nid, &xd); \ - if (!(status & 1)) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) in_struct.field = xd.pointer; \ +#define read_descriptor_error(pos, field, err) \ + curr_nid = head_nid + pos; \ + status = TreeGetRecord(curr_nid, &xd); \ + if (!(status & 1)) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) in_struct.field = xd.pointer; \ next_xd -#define read_integer(pos, field) \ - curr_nid = head_nid + pos; \ - status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ - if (status & 1) \ +#define read_integer(pos, field) \ + curr_nid = head_nid + pos; \ + status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ + if (status & 1) \ in_struct.field = curr_int; -#define read_integer_error(pos, field, err) \ - curr_nid = head_nid + pos; \ - status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ - if (!(status & 1)) \ +#define read_integer_error(pos, field, err) \ + curr_nid = head_nid + pos; \ + status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = curr_int; -#define check_range(field, min, max, err) \ - if ((in_struct.field < min) || (in_struct.field > max)) \ +#define check_range(field, min, max, err) \ + if ((in_struct.field < min) || (in_struct.field > max)) \ error(head_nid, GEN_DEV$_INV_SETUP, err); -#define check_integer_set(field, table, max_idx, err) \ - status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_integer_set(field, table, max_idx, err) \ + status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) -#define check_integer_conv_set(field, conv_field, table, max_idx, err) \ - status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_integer_conv_set(field, conv_field, table, max_idx, err) \ + status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; -#define read_integer_array_error(pos, field, field_count, err) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ - if (!(status & 1)) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) else { \ - array_d_ptr = (struct descriptor_a *)xd.pointer; \ - if (array_d_ptr->class != CLASS_A) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) else { \ - in_struct.field = (int *)array_d_ptr->pointer; \ - in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ - } \ - } \ +#define read_integer_array_error(pos, field, field_count, err) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ + if (!(status & 1)) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) else \ + { \ + array_d_ptr = (struct descriptor_a *)xd.pointer; \ + if (array_d_ptr->class != CLASS_A) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) else \ + { \ + in_struct.field = (int *)array_d_ptr->pointer; \ + in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ + } \ + } \ next_xd -#define read_integer_array(pos, field, field_count) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ - if (status & 1) { \ - array_d_ptr = (struct descriptor_a *)xd.pointer; \ - if (array_d_ptr->class == CLASS_A) { \ - in_struct.field = (int *)array_d_ptr->pointer; \ - in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ - } \ - } \ +#define read_integer_array(pos, field, field_count) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ + if (status & 1) \ + { \ + array_d_ptr = (struct descriptor_a *)xd.pointer; \ + if (array_d_ptr->class == CLASS_A) \ + { \ + in_struct.field = (int *)array_d_ptr->pointer; \ + in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ + } \ + } \ next_xd -#define read_float_array_error(pos, field, field_count, err) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ - if (!(status & 1)) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) array_d_ptr = \ - (struct descriptor_a *)xd.pointer; \ - if (array_d_ptr->class != CLASS_A) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) else { \ - in_struct.field = (float *)array_d_ptr->pointer; \ - in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ - } \ - } \ +#define read_float_array_error(pos, field, field_count, err) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ + if (!(status & 1)) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) array_d_ptr = \ + (struct descriptor_a *)xd.pointer; \ + if (array_d_ptr->class != CLASS_A) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) else \ + { \ + in_struct.field = (float *)array_d_ptr->pointer; \ + in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ + } \ + } \ next_xd -#define read_float_array(pos, field, field_count) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ - if (status & 1) { \ - array_d_ptr = (struct descriptor_a *)xd.pointer; \ - if (array_d_ptr->class == CLASS_A) { \ - in_struct.field = (float *)array_d_ptr->pointer; \ - in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ - } \ - } \ +#define read_float_array(pos, field, field_count) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ + if (status & 1) \ + { \ + array_d_ptr = (struct descriptor_a *)xd.pointer; \ + if (array_d_ptr->class == CLASS_A) \ + { \ + in_struct.field = (float *)array_d_ptr->pointer; \ + in_struct.field_count = array_d_ptr->arsize / array_d_ptr->length; \ + } \ + } \ next_xd -#define read_float(pos, field) \ - curr_nid = head_nid + pos; \ - status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ - if (status & 1) \ +#define read_float(pos, field) \ + curr_nid = head_nid + pos; \ + status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ + if (status & 1) \ in_struct.field = curr_float; -#define read_float_error(pos, field, err) \ - curr_nid = head_nid + pos; \ - status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ - if (!(status & 1)) \ +#define read_float_error(pos, field, err) \ + curr_nid = head_nid + pos; \ + status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = curr_float; -#define check_float_set(field, table, max_idx, err) \ - status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_float_set(field, table, max_idx, err) \ + status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) -#define check_float_conv_set(field, conv_field, table, max_idx, err) \ - status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_float_conv_set(field, conv_field, table, max_idx, err) \ + status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; -#define read_string(pos, field) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ - if (status & 1) \ - in_struct.field = xd.pointer->pointer; \ +#define read_string(pos, field) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ + if (status & 1) \ + in_struct.field = xd.pointer->pointer; \ next_xd -#define read_string_error(pos, field, err) \ - curr_nid = head_nid + pos; \ - status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ - if (!(status & 1)) \ - error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = \ - xd.pointer->pointer; \ +#define read_string_error(pos, field, err) \ + curr_nid = head_nid + pos; \ + status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ + if (!(status & 1)) \ + error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = \ + xd.pointer->pointer; \ next_xd -#define check_string_set(field, table, max_idx, err) \ - status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_string_set(field, table, max_idx, err) \ + status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) -#define check_string_conv_set(field, conv_field, table, max_idx, err) \ - status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ +#define check_string_conv_set(field, conv_field, table, max_idx, err) \ + status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ + if (!(status & 1)) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; -#define build_results_with_xd_and_return(num_xd) \ - in_struct.__xds = \ - (struct descriptor_xd *)malloc(num_xd * sizeof(struct descriptor_xd)); \ - in_struct.__num_xds = num_xd; \ - memcpy((char *)in_struct.__xds, (char *)work_xd, \ - num_xd * sizeof(struct descriptor_xd)); \ - *in_ptr = in_struct; \ +#define build_results_with_xd_and_return(num_xd) \ + in_struct.__xds = \ + (struct descriptor_xd *)malloc(num_xd * sizeof(struct descriptor_xd)); \ + in_struct.__num_xds = num_xd; \ + memcpy((char *)in_struct.__xds, (char *)work_xd, \ + num_xd * sizeof(struct descriptor_xd)); \ + *in_ptr = in_struct; \ return error_code -#define build_results_and_return \ - *in_ptr = in_struct; \ +#define build_results_and_return \ + *in_ptr = in_struct; \ return error_code diff --git a/include/mds_stdarg.h b/include/mds_stdarg.h index 68ef4d30a8..dc9231f698 100644 --- a/include/mds_stdarg.h +++ b/include/mds_stdarg.h @@ -43,22 +43,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * anchor: last fix argument just before ... end: * terminating value, e.g. NULL or MdsEND_ARG */ -#define VA_LIST_TO_ARGLIST(arglist, nargs, pre, post, anchor, end) \ - { \ - va_list args; \ - va_start(args, anchor); \ - for (nargs = pre; nargs < (int)(sizeof(arglist) / sizeof(arglist[0])); \ - nargs++) \ - if (end == (arglist[nargs] = va_arg(args, void *))) \ - break; \ - va_end(args); \ - nargs += post; \ +#define VA_LIST_TO_ARGLIST(arglist, nargs, pre, post, anchor, end) \ + { \ + va_list args; \ + va_start(args, anchor); \ + for (nargs = pre; nargs < (int)(sizeof(arglist) / sizeof(arglist[0])); \ + nargs++) \ + if (end == (arglist[nargs] = va_arg(args, void *))) \ + break; \ + va_end(args); \ + nargs += post; \ } // abbreviations for NULL and MdsEND_ARG terminated va_lists -#define VA_LIST_NULL(arglist, nargs, pre, post, anchor) \ +#define VA_LIST_NULL(arglist, nargs, pre, post, anchor) \ VA_LIST_TO_ARGLIST(arglist, nargs, pre, post, anchor, NULL) -#define VA_LIST_MDS_END_ARG(arglist, nargs, pre, post, anchor) \ +#define VA_LIST_MDS_END_ARG(arglist, nargs, pre, post, anchor) \ VA_LIST_TO_ARGLIST(arglist, nargs, pre, post, anchor, MdsEND_ARG) #endif /* MDS_STDARG */ diff --git a/include/mdsdescrip.h b/include/mdsdescrip.h index 71b19f8e0d..8122ab4cf8 100644 --- a/include/mdsdescrip.h +++ b/include/mdsdescrip.h @@ -19,8 +19,8 @@ #ifdef MDSOBJECTSCPPSHRVS_EXPORTS // visual studio uses int types for typedef #define TYPEDEF(bytes) enum -#define ENDDEF(type, name) \ - ; \ +#define ENDDEF(type, name) \ + ; \ typedef type name #else #define TYPEDEF(bytes) typedef enum __attribute__((__packed__)) @@ -64,39 +64,42 @@ TYPEDEF(2){ TdiFUNCTION_MAX} ENDDEF(uint16_t, opcode_t); #ifdef __cplusplus -#define MDSDSC_HEAD(ptr_type) \ - length_t length; /* specific to descriptor class; typically a 16-bit \ - (unsigned) length */ \ - dtype_t dtype; /* data type code */ \ - class_t class_; /* descriptor class code */ \ +#define MDSDSC_HEAD(ptr_type) \ + length_t length; /* specific to descriptor class; typically a 16-bit \ + (unsigned) length */ \ + dtype_t dtype; /* data type code */ \ + class_t class_; /* descriptor class code */ \ ptr_type *pointer; /* address of first byte of data element */ #else -#define MDSDSC_HEAD(ptr_type) \ - length_t length; /* specific to descriptor class; typically a 16-bit \ - (unsigned) length */ \ - dtype_t dtype; /* data type code */ \ - class_t class; /* descriptor class code */ \ +#define MDSDSC_HEAD(ptr_type) \ + length_t length; /* specific to descriptor class; typically a 16-bit \ + (unsigned) length */ \ + dtype_t dtype; /* data type code */ \ + class_t class; /* descriptor class code */ \ ptr_type *pointer; /* address of first byte of data element */ #endif /* * Descriptor Prototype - each class of descriptor consists of at least the *following fields: */ -typedef struct descriptor { +typedef struct descriptor +{ MDSDSC_HEAD(char) } mdsdsc_t; /* * Fixed-Length Descriptor: */ -typedef struct descriptor_s { +typedef struct descriptor_s +{ MDSDSC_HEAD(char) } mdsdsc_s_t; /* * Dynamic String Descriptor: */ -typedef struct descriptor_d { +typedef struct descriptor_d +{ MDSDSC_HEAD(char) } mdsdsc_d_t; @@ -104,7 +107,8 @@ typedef struct descriptor_d { * Array Descriptor: */ -typedef struct { +typedef struct +{ unsigned __char_align__ : 3; /* reserved; must be zero */ unsigned __char_align__ binscale : 1; /* if set, scale is a power-of-two, otherwise, -ten */ @@ -139,19 +143,20 @@ arsize total size of array in bytes, or if dtype is K_DTYPE_P, digits (4 bits each) */ -#define ARRAY_HEAD(ptr_type) \ - MDSDSC_HEAD(ptr_type) \ - scale_t scale; /* signed power-of-two or -ten multiplier, as specified by */ \ - digits_t digits; /* if nonzero, number of decimal digits in internal \ - representation */ \ - aflags_t aflags; \ - dimct_t dimct; \ +#define ARRAY_HEAD(ptr_type) \ + MDSDSC_HEAD(ptr_type) \ + scale_t scale; /* signed power-of-two or -ten multiplier, as specified by */ \ + digits_t digits; /* if nonzero, number of decimal digits in internal \ + representation */ \ + aflags_t aflags; \ + dimct_t dimct; \ arsize_t arsize; -#define IS_ARRAY_DSC(p) \ +#define IS_ARRAY_DSC(p) \ ((p)->class == CLASS_A || (p)->class == CLASS_CA || (p)->class == CLASS_APD) -typedef struct descriptor_a { +typedef struct descriptor_a +{ ARRAY_HEAD(char) /* * One or two optional blocks of information may follow contiguously at this @@ -181,58 +186,59 @@ typedef struct descriptor_a { Useful for classes A, CA, and APD. *************************************************/ -#define ARRAY(ptr_type) \ - struct { \ - ARRAY_HEAD(ptr_type) \ +#define ARRAY(ptr_type) \ + struct \ + { \ + ARRAY_HEAD(ptr_type) \ } -#define ARRAY_COEFF(ptr_type, dimct) \ - struct { \ - ARRAY_HEAD(ptr_type) \ - ptr_type *a0; \ - uint32_t m[dimct]; \ +#define ARRAY_COEFF(ptr_type, dimct) \ + struct \ + { \ + ARRAY_HEAD(ptr_type) \ + ptr_type *a0; \ + uint32_t m[dimct]; \ } typedef uint32_t dim_t; -typedef struct { +typedef struct +{ int l; int u; } bound_t; -#define ARRAY_BOUNDS(ptr_type, dimct) \ - struct { \ - ARRAY_HEAD(ptr_type) \ - ptr_type *a0; \ - dim_t m[dimct]; \ - bound_t bounds[dimct]; \ +#define ARRAY_BOUNDS(ptr_type, dimct) \ + struct \ + { \ + ARRAY_HEAD(ptr_type) \ + ptr_type *a0; \ + dim_t m[dimct]; \ + bound_t bounds[dimct]; \ } -#define DESCRIPTOR_A(name, len, type, ptr, arsize) \ - ARRAY(char) \ - name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, \ - {0, 1, 1, 0, 0}, 1, arsize} - -#define DESCRIPTOR_A_COEFF(name, len, type, ptr, dimct, arsize) \ - ARRAY_COEFF(char, dimct) \ - name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, \ - {0, 1, 1, 1, 0}, dimct, arsize, 0, {0}} - -#define DESCRIPTOR_A_COEFF_2(name, len, type, ptr, arsize, rows, columns) \ - ARRAY_COEFF(char, 2) \ - name = {(length_t)len, \ - type, \ - CLASS_A, \ - (char *)ptr, \ - 0, \ - 0, \ - {0, 1, 1, 1, 0}, \ - 2, \ - arsize, \ - (char *)ptr, \ +#define DESCRIPTOR_A(name, len, type, ptr, arsize) \ + ARRAY(char) \ + name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, {0, 1, 1, 0, 0}, 1, arsize} + +#define DESCRIPTOR_A_COEFF(name, len, type, ptr, dimct, arsize) \ + ARRAY_COEFF(char, dimct) \ + name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, {0, 1, 1, 1, 0}, dimct, arsize, 0, {0}} + +#define DESCRIPTOR_A_COEFF_2(name, len, type, ptr, arsize, rows, columns) \ + ARRAY_COEFF(char, 2) \ + name = {(length_t)len, \ + type, \ + CLASS_A, \ + (char *)ptr, \ + 0, \ + 0, \ + {0, 1, 1, 1, 0}, \ + 2, \ + arsize, \ + (char *)ptr, \ {rows, columns}} -#define DESCRIPTOR_A_BOUNDS(name, len, type, ptr, dimct, arsize) \ - ARRAY_BOUNDS(char, dimct) \ - name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, \ - {0, 1, 1, 1, 1}, dimct, arsize, 0, {0}, {{0, 0}}} +#define DESCRIPTOR_A_BOUNDS(name, len, type, ptr, dimct, arsize) \ + ARRAY_BOUNDS(char, dimct) \ + name = {(length_t)len, type, CLASS_A, (char *)ptr, 0, 0, {0, 1, 1, 1, 1}, dimct, arsize, 0, {0}, {{0, 0}}} /************************************************ CLASS_XD extended dynamic descriptor definition. @@ -242,7 +248,8 @@ typedef struct { The descriptor is usually on the stack. *************************************************/ typedef uint32_t l_length_t; -typedef struct descriptor_xd { +typedef struct descriptor_xd +{ MDSDSC_HEAD(mdsdsc_t) l_length_t l_length; } mdsdsc_xd_t; @@ -253,7 +260,8 @@ typedef struct descriptor_xd { CLASS_XS extended static descriptor definition. *************************************************/ -typedef struct descriptor_xs { +typedef struct descriptor_xs +{ MDSDSC_HEAD(mdsdsc_t) l_length_t l_length; } mdsdsc_xs_t; @@ -263,24 +271,26 @@ typedef struct descriptor_xs { *************************************************/ typedef uint8_t ndesc_t; typedef uint8_t rec_ptr_t; -#define RECORD_HEAD(ptr_type) \ - MDSDSC_HEAD(ptr_type) \ - ndesc_t ndesc; \ +#define RECORD_HEAD(ptr_type) \ + MDSDSC_HEAD(ptr_type) \ + ndesc_t ndesc; \ unsigned __fill_name__ : 24; -typedef struct descriptor_r { +typedef struct descriptor_r +{ RECORD_HEAD(uint8_t) mdsdsc_t *dscptrs[1]; } mdsdsc_r_t; -#define RECORD(ndesc) \ - struct { \ - RECORD_HEAD(uint8_t) \ - mdsdsc_t *dscptrs[ndesc]; \ +#define RECORD(ndesc) \ + struct \ + { \ + RECORD_HEAD(uint8_t) \ + mdsdsc_t *dscptrs[ndesc]; \ } -#define DESCRIPTOR_R(name, type, ndesc) \ - RECORD(ndesc) \ +#define DESCRIPTOR_R(name, type, ndesc) \ + RECORD(ndesc) \ name = {(length_t)0, type, CLASS_R, 0, ndesc, __fill_value__{0}} /************************************************ @@ -296,18 +306,15 @@ typedef struct descriptor_r { It must have all length and type info. *************************************************/ -#define DESCRIPTOR_CA(name, len, type, ptr, arsize) \ - ARRAY(mdsdsc_t) \ - name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, \ - {0, 1, 1, 0, 0}, 1, arsize} -#define DESCRIPTOR_CA_COEFF(name, len, type, ptr, dimct, arsize) \ - ARRAY_COEFF(mdsdsc_t, dimct) \ - name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, \ - {0, 1, 1, 1, 0}, dimct, arsize} -#define DESCRIPTOR_CA_BOUNDS(name, len, type, ptr, dimct, arsize) \ - ARRAY_BOUNDS(mdsdsc_t, dimct) \ - name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, \ - {0, 1, 1, 1, 1}, dimct, arsize} +#define DESCRIPTOR_CA(name, len, type, ptr, arsize) \ + ARRAY(mdsdsc_t) \ + name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, {0, 1, 1, 0, 0}, 1, arsize} +#define DESCRIPTOR_CA_COEFF(name, len, type, ptr, dimct, arsize) \ + ARRAY_COEFF(mdsdsc_t, dimct) \ + name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, {0, 1, 1, 1, 0}, dimct, arsize} +#define DESCRIPTOR_CA_BOUNDS(name, len, type, ptr, dimct, arsize) \ + ARRAY_BOUNDS(mdsdsc_t, dimct) \ + name = {(length_t)len, type, CLASS_CA, (mdsdsc_t *)ptr, 0, 0, {0, 1, 1, 1, 1}, dimct, arsize} /************************************************ CLASS_APD Array of pointers to descriptors. @@ -324,38 +331,38 @@ typedef struct descriptor_r { the list of pointers to descriptors. *************************************************/ -#define DESCRIPTOR_APD(name, type, ptr, ndesc) \ - ARRAY(mdsdsc_t *) \ - name = {(length_t)sizeof(mdsdsc_t *), \ - type, \ - CLASS_APD, \ - (mdsdsc_t **)ptr, \ - 0, \ - 0, \ - {0, 1, 1, 0, 0}, \ - 1, \ +#define DESCRIPTOR_APD(name, type, ptr, ndesc) \ + ARRAY(mdsdsc_t *) \ + name = {(length_t)sizeof(mdsdsc_t *), \ + type, \ + CLASS_APD, \ + (mdsdsc_t **)ptr, \ + 0, \ + 0, \ + {0, 1, 1, 0, 0}, \ + 1, \ ndesc * sizeof(mdsdsc_t *)} -#define DESCRIPTOR_APD_COEFF(name, type, ptr, dimct, ndesc) \ - ARRAY_COEFF(mdsdsc_t *, dimct) \ - name = {(length_t)sizeof(mdsdsc_t *), \ - type, \ - CLASS_APD, \ - (mdsdsc_t **)ptr, \ - 0, \ - 0, \ - {0, 1, 1, 1, 0}, \ - dimct, \ +#define DESCRIPTOR_APD_COEFF(name, type, ptr, dimct, ndesc) \ + ARRAY_COEFF(mdsdsc_t *, dimct) \ + name = {(length_t)sizeof(mdsdsc_t *), \ + type, \ + CLASS_APD, \ + (mdsdsc_t **)ptr, \ + 0, \ + 0, \ + {0, 1, 1, 1, 0}, \ + dimct, \ ndesc * sizeof(mdsdsc_t *)} -#define DESCRIPTOR_APD_BOUNDS(name, type, ptr, dimct, ndesc) \ - ARRAY_BOUNDS(mdsdsc_t *, dimct) \ - name = {(length_t)sizeof(mdsdsc_t *), \ - type, \ - CLASS_APD, \ - (mdsdsc_t **)ptr, \ - 0, \ - 0, \ - {0, 1, 1, 1, 1}, \ - dimct, \ +#define DESCRIPTOR_APD_BOUNDS(name, type, ptr, dimct, ndesc) \ + ARRAY_BOUNDS(mdsdsc_t *, dimct) \ + name = {(length_t)sizeof(mdsdsc_t *), \ + type, \ + CLASS_APD, \ + (mdsdsc_t **)ptr, \ + 0, \ + 0, \ + {0, 1, 1, 1, 1}, \ + dimct, \ ndesc * sizeof(mdsdsc_t *)} /***************************************************** @@ -366,165 +373,177 @@ typedef struct descriptor_r { Others are supported record data types. *****************************************************/ -typedef struct descriptor_param { +typedef struct descriptor_param +{ RECORD_HEAD(void) mdsdsc_t *value; mdsdsc_t *help; mdsdsc_t *validation; } mds_param_t; -#define DESCRIPTOR_PARAM(name, value, help, validation) \ - mds_param_t name = {(length_t)0, \ - DTYPE_PARAM, \ - CLASS_R, \ - 0, \ - 3, \ - __fill_value__(mdsdsc_t *) value, \ - (mdsdsc_t *)help, \ +#define DESCRIPTOR_PARAM(name, value, help, validation) \ + mds_param_t name = {(length_t)0, \ + DTYPE_PARAM, \ + CLASS_R, \ + 0, \ + 3, \ + __fill_value__(mdsdsc_t *) value, \ + (mdsdsc_t *)help, \ (mdsdsc_t *)validation} -typedef struct descriptor_signal { +typedef struct descriptor_signal +{ RECORD_HEAD(void) mdsdsc_t *data; mdsdsc_t *raw; mdsdsc_t *dimensions[1]; } mds_signal_t; -#define SIGNAL(ndims) \ - struct { \ - RECORD_HEAD(void) \ - mdsdsc_t *data; \ - mdsdsc_t *raw; \ - mdsdsc_t *dimensions[ndims]; \ +#define SIGNAL(ndims) \ + struct \ + { \ + RECORD_HEAD(void) \ + mdsdsc_t *data; \ + mdsdsc_t *raw; \ + mdsdsc_t *dimensions[ndims]; \ } -#define DESCRIPTOR_SIGNAL(name, ndims, data, raw) \ - SIGNAL(ndims) \ - name = {0, \ - DTYPE_SIGNAL, \ - CLASS_R, \ - 0, \ - ndims + 2, \ - __fill_value__(mdsdsc_t *) data, \ - (mdsdsc_t *)raw, \ +#define DESCRIPTOR_SIGNAL(name, ndims, data, raw) \ + SIGNAL(ndims) \ + name = {0, \ + DTYPE_SIGNAL, \ + CLASS_R, \ + 0, \ + ndims + 2, \ + __fill_value__(mdsdsc_t *) data, \ + (mdsdsc_t *)raw, \ {0}} -#define DESCRIPTOR_SIGNAL_1(name, data, raw, dimension) \ - SIGNAL(1) \ - name = {0, \ - DTYPE_SIGNAL, \ - CLASS_R, \ - 0, \ - 3, \ - __fill_value__(mdsdsc_t *) data, \ - (mdsdsc_t *)raw, \ +#define DESCRIPTOR_SIGNAL_1(name, data, raw, dimension) \ + SIGNAL(1) \ + name = {0, \ + DTYPE_SIGNAL, \ + CLASS_R, \ + 0, \ + 3, \ + __fill_value__(mdsdsc_t *) data, \ + (mdsdsc_t *)raw, \ {(mdsdsc_t *)dimension}} -#define DESCRIPTOR_SIGNAL_2(name, data, raw, dim_1, dim_2) \ - SIGNAL(2) \ - name = {0, \ - DTYPE_SIGNAL, \ - CLASS_R, \ - 0, \ - 4, \ - __fill_value__(mdsdsc_t *) data, \ - (mdsdsc_t *)raw, \ +#define DESCRIPTOR_SIGNAL_2(name, data, raw, dim_1, dim_2) \ + SIGNAL(2) \ + name = {0, \ + DTYPE_SIGNAL, \ + CLASS_R, \ + 0, \ + 4, \ + __fill_value__(mdsdsc_t *) data, \ + (mdsdsc_t *)raw, \ {(mdsdsc_t *)dim_1, (mdsdsc_t *)dim_2}} -typedef struct descriptor_dimension { +typedef struct descriptor_dimension +{ RECORD_HEAD(void) mdsdsc_t *window; mdsdsc_t *axis; } mds_dimension_t; -#define DESCRIPTOR_DIMENSION(name, window, axis) \ - mds_dimension_t name = {0, \ - DTYPE_DIMENSION, \ - CLASS_R, \ - 0, \ - 2, \ - __fill_value__(mdsdsc_t *) window, \ +#define DESCRIPTOR_DIMENSION(name, window, axis) \ + mds_dimension_t name = {0, \ + DTYPE_DIMENSION, \ + CLASS_R, \ + 0, \ + 2, \ + __fill_value__(mdsdsc_t *) window, \ (mdsdsc_t *)axis} -typedef struct descriptor_window { +typedef struct descriptor_window +{ RECORD_HEAD(void) mdsdsc_t *startidx; mdsdsc_t *endingidx; mdsdsc_t *value_at_idx0; } mds_window_t; -#define DESCRIPTOR_WINDOW(name, start, iend, xref) \ - mds_window_t name = {0, \ - DTYPE_WINDOW, \ - CLASS_R, \ - 0, \ - 3, \ - __fill_value__(mdsdsc_t *) start, \ - (mdsdsc_t *)iend, \ +#define DESCRIPTOR_WINDOW(name, start, iend, xref) \ + mds_window_t name = {0, \ + DTYPE_WINDOW, \ + CLASS_R, \ + 0, \ + 3, \ + __fill_value__(mdsdsc_t *) start, \ + (mdsdsc_t *)iend, \ (mdsdsc_t *)xref} -typedef struct descriptor_axis { +typedef struct descriptor_axis +{ RECORD_HEAD(void) mdsdsc_t *dscptrs[3]; } mds_axis_t; /* This is to be replaced by RANGEs of scalars or vectors */ -typedef struct { +typedef struct +{ mdsdsc_t *slope; mdsdsc_t *begin; mdsdsc_t *ending; } slope_segment_t; -typedef struct descriptor_slope { +typedef struct descriptor_slope +{ RECORD_HEAD(void) slope_segment_t segment[1]; } mds_slope_t; -#define SLOPE(nsegs) \ - struct { \ - RECORD_HEAD(void) \ - slope_segment_t segment[nsegs]; \ +#define SLOPE(nsegs) \ + struct \ + { \ + RECORD_HEAD(void) \ + slope_segment_t segment[nsegs]; \ } -typedef struct descriptor_function { +typedef struct descriptor_function +{ RECORD_HEAD(opcode_t) mdsdsc_t *arguments[1]; } mds_function_t; -#define FUNCTION(nargs) \ - struct { \ - RECORD_HEAD(opcode_t) \ - mdsdsc_t *arguments[nargs]; \ +#define FUNCTION(nargs) \ + struct \ + { \ + RECORD_HEAD(opcode_t) \ + mdsdsc_t *arguments[nargs]; \ } -#define DESCRIPTOR_FUNCTION(name, opcode_ptr, nargs) \ - FUNCTION(nargs) \ - name = {(length_t)sizeof(opcode_t), DTYPE_FUNCTION, CLASS_R, \ - (opcode_t *)opcode_ptr, nargs, __fill_value__{0}} - -#define DESCRIPTOR_FUNCTION_0(name, opcode_ptr) \ - mds_function_t name = {(length_t)sizeof(opcode_t), \ - DTYPE_FUNCTION, \ - CLASS_R, \ - (opcode_t *)opcode_ptr, \ - 0, \ +#define DESCRIPTOR_FUNCTION(name, opcode_ptr, nargs) \ + FUNCTION(nargs) \ + name = {(length_t)sizeof(opcode_t), DTYPE_FUNCTION, CLASS_R, \ + (opcode_t *)opcode_ptr, nargs, __fill_value__{0}} + +#define DESCRIPTOR_FUNCTION_0(name, opcode_ptr) \ + mds_function_t name = {(length_t)sizeof(opcode_t), \ + DTYPE_FUNCTION, \ + CLASS_R, \ + (opcode_t *)opcode_ptr, \ + 0, \ __fill_value__{0}} -#define DESCRIPTOR_FUNCTION_1(name, opcode_ptr, arg) \ - mds_function_t name = {(length_t)sizeof(opcode_t), \ - DTYPE_FUNCTION, \ - CLASS_R, \ - (opcode_t *)opcode_ptr, \ - 1, \ +#define DESCRIPTOR_FUNCTION_1(name, opcode_ptr, arg) \ + mds_function_t name = {(length_t)sizeof(opcode_t), \ + DTYPE_FUNCTION, \ + CLASS_R, \ + (opcode_t *)opcode_ptr, \ + 1, \ __fill_value__{(mdsdsc_t *)arg}} -#define DESCRIPTOR_FUNCTION_2(name, opcode_ptr, arg_1, arg_2) \ - FUNCTION(2) \ - name = {(length_t)sizeof(opcode_t), \ - DTYPE_FUNCTION, \ - CLASS_R, \ - (opcode_t *)opcode_ptr, \ - 2, \ +#define DESCRIPTOR_FUNCTION_2(name, opcode_ptr, arg_1, arg_2) \ + FUNCTION(2) \ + name = {(length_t)sizeof(opcode_t), \ + DTYPE_FUNCTION, \ + CLASS_R, \ + (opcode_t *)opcode_ptr, \ + 2, \ __fill_value__{(mdsdsc_t *)arg_1, (mdsdsc_t *)arg_2}} -typedef struct descriptor_conglom { +typedef struct descriptor_conglom +{ RECORD_HEAD(void) mdsdsc_t *image; mdsdsc_t *model; @@ -532,35 +551,37 @@ typedef struct descriptor_conglom { mdsdsc_t *qualifiers; } mds_conglom_t; -#define DESCRIPTOR_CONGLOM(sname, image, model, name, qualifiers) \ - mds_conglom_t sname = {0, \ - DTYPE_CONGLOM, \ - CLASS_R, \ - 0, \ - 4, \ - __fill_value__(mdsdsc_t *) image, \ - (mdsdsc_t *)model, \ - (mdsdsc_t *)name, \ +#define DESCRIPTOR_CONGLOM(sname, image, model, name, qualifiers) \ + mds_conglom_t sname = {0, \ + DTYPE_CONGLOM, \ + CLASS_R, \ + 0, \ + 4, \ + __fill_value__(mdsdsc_t *) image, \ + (mdsdsc_t *)model, \ + (mdsdsc_t *)name, \ (mdsdsc_t *)qualifiers} -typedef struct descriptor_range { +typedef struct descriptor_range +{ RECORD_HEAD(void) mdsdsc_t *begin; mdsdsc_t *ending; mdsdsc_t *deltaval; } mds_range_t; -#define DESCRIPTOR_RANGE(name, begin, ending, delta) \ - mds_range_t name = {0, \ - DTYPE_RANGE, \ - CLASS_R, \ - 0, \ - 3, \ - __fill_value__(mdsdsc_t *) begin, \ - (mdsdsc_t *)ending, \ +#define DESCRIPTOR_RANGE(name, begin, ending, delta) \ + mds_range_t name = {0, \ + DTYPE_RANGE, \ + CLASS_R, \ + 0, \ + 3, \ + __fill_value__(mdsdsc_t *) begin, \ + (mdsdsc_t *)ending, \ (mdsdsc_t *)delta} -typedef struct descriptor_action { +typedef struct descriptor_action +{ RECORD_HEAD(void) mdsdsc_t *dispatch; mdsdsc_t *task; @@ -569,16 +590,16 @@ typedef struct descriptor_action { mdsdsc_a_t *performance; } mds_action_t; -#define DESCRIPTOR_ACTION(name, dispatch, task, errorlogs) \ - mds_action_t name = {0, \ - DTYPE_ACTION, \ - CLASS_R, \ - 0, \ - 5, \ - __fill_value__(mdsdsc_t *) dispatch, \ - (mdsdsc_t *)task, \ - (mdsdsc_t *)errorlogs, \ - 0, \ +#define DESCRIPTOR_ACTION(name, dispatch, task, errorlogs) \ + mds_action_t name = {0, \ + DTYPE_ACTION, \ + CLASS_R, \ + 0, \ + 5, \ + __fill_value__(mdsdsc_t *) dispatch, \ + (mdsdsc_t *)task, \ + (mdsdsc_t *)errorlogs, \ + 0, \ 0} /***************************************************** @@ -587,7 +608,8 @@ typedef struct descriptor_action { TYPEDEF(1){TreeSCHED_NONE = 0, TreeSCHED_ASYNC = 1, TreeSCHED_SEQ = 2, TreeSCHED_COND = 3} ENDDEF(uint8_t, treesched_t); -typedef struct descriptor_dispatch { +typedef struct descriptor_dispatch +{ RECORD_HEAD(treesched_t) mdsdsc_t *ident; mdsdsc_t *phase; @@ -595,33 +617,35 @@ typedef struct descriptor_dispatch { mdsdsc_t *completion; } mds_dispatch_t; -#define DESCRIPTOR_DISPATCH(name, type, ident, phase, when, completion) \ - mds_dispatch_t name = {(length_t)sizeof(treesched_t), \ - DTYPE_DISPATCH, \ - CLASS_R, \ - (treesched_t *)type, \ - 4, \ - __fill_value__(mdsdsc_t *) ident, \ - (mdsdsc_t *)phase, \ - (mdsdsc_t *)when, \ +#define DESCRIPTOR_DISPATCH(name, type, ident, phase, when, completion) \ + mds_dispatch_t name = {(length_t)sizeof(treesched_t), \ + DTYPE_DISPATCH, \ + CLASS_R, \ + (treesched_t *)type, \ + 4, \ + __fill_value__(mdsdsc_t *) ident, \ + (mdsdsc_t *)phase, \ + (mdsdsc_t *)when, \ (mdsdsc_t *)completion} -typedef struct descriptor_program { +typedef struct descriptor_program +{ RECORD_HEAD(void) mdsdsc_t *time_out; mdsdsc_t *program; } mds_program_t; -#define DESCRIPTOR_PROGRAM(name, program, timeout) \ - mds_program_t name = {0, \ - DTYPE_PROGRAM, \ - CLASS_R, \ - 0, \ - 2, \ - __fill_value__(mdsdsc_t *) timeout, \ +#define DESCRIPTOR_PROGRAM(name, program, timeout) \ + mds_program_t name = {0, \ + DTYPE_PROGRAM, \ + CLASS_R, \ + 0, \ + 2, \ + __fill_value__(mdsdsc_t *) timeout, \ (mdsdsc_t *)program} -typedef struct descriptor_routine { +typedef struct descriptor_routine +{ RECORD_HEAD(void) mdsdsc_t *time_out; mdsdsc_t *image; @@ -629,27 +653,29 @@ typedef struct descriptor_routine { mdsdsc_t *arguments[1]; } mds_routine_t; -#define ROUTINE(nargs) \ - struct { \ - RECORD_HEAD(void) \ - mdsdsc_t *time_out; \ - mdsdsc_t *image; \ - mdsdsc_t *routine; \ - mdsdsc_t *arguments[nargs]; \ +#define ROUTINE(nargs) \ + struct \ + { \ + RECORD_HEAD(void) \ + mdsdsc_t *time_out; \ + mdsdsc_t *image; \ + mdsdsc_t *routine; \ + mdsdsc_t *arguments[nargs]; \ } -#define DESCRIPTOR_ROUTINE(name, image, routine, timeout, nargs) \ - ROUTINE(nargs) \ - name = {0, \ - DTYPE_ROUTINE, \ - CLASS_R, \ - 0, \ - nargs + 3, \ - __fill_value__(mdsdsc_t *) timeout, \ - (mdsdsc_t *)image, \ +#define DESCRIPTOR_ROUTINE(name, image, routine, timeout, nargs) \ + ROUTINE(nargs) \ + name = {0, \ + DTYPE_ROUTINE, \ + CLASS_R, \ + 0, \ + nargs + 3, \ + __fill_value__(mdsdsc_t *) timeout, \ + (mdsdsc_t *)image, \ (mdsdsc_t *)routine} -typedef struct descriptor_procedure { +typedef struct descriptor_procedure +{ RECORD_HEAD(void) mdsdsc_t *time_out; mdsdsc_t *language; @@ -657,27 +683,29 @@ typedef struct descriptor_procedure { mdsdsc_t *arguments[1]; } mds_procedure_t; -#define PROCEDURE(nargs) \ - struct { \ - RECORD_HEAD(void) \ - mdsdsc_t *time_out; \ - mdsdsc_t *language; \ - mdsdsc_t *procedure; \ - mdsdsc_t *arguments[nargs]; \ +#define PROCEDURE(nargs) \ + struct \ + { \ + RECORD_HEAD(void) \ + mdsdsc_t *time_out; \ + mdsdsc_t *language; \ + mdsdsc_t *procedure; \ + mdsdsc_t *arguments[nargs]; \ } -#define DESCRIPTOR_PROCEDURE(name, language, procedure, timeout, nargs) \ - PROCEDURE(nargs) \ - name = {0, \ - DTYPE_PROCEDURE, \ - CLASS_R, \ - 0, \ - nargs + 3, \ - __fill_value__(mdsdsc_t *) timeout, \ - (mdsdsc_t *)language, \ +#define DESCRIPTOR_PROCEDURE(name, language, procedure, timeout, nargs) \ + PROCEDURE(nargs) \ + name = {0, \ + DTYPE_PROCEDURE, \ + CLASS_R, \ + 0, \ + nargs + 3, \ + __fill_value__(mdsdsc_t *) timeout, \ + (mdsdsc_t *)language, \ (mdsdsc_t *)procedure} -typedef struct descriptor_method { +typedef struct descriptor_method +{ RECORD_HEAD(void) mdsdsc_t *time_out; mdsdsc_t *method; @@ -685,60 +713,63 @@ typedef struct descriptor_method { mdsdsc_t *arguments[1]; } mds_method_t; -#define METHOD(nargs) \ - struct { \ - RECORD_HEAD(void) \ - mdsdsc_t *time_out; \ - mdsdsc_t *method; \ - mdsdsc_t *object; \ - mdsdsc_t *arguments[nargs]; \ +#define METHOD(nargs) \ + struct \ + { \ + RECORD_HEAD(void) \ + mdsdsc_t *time_out; \ + mdsdsc_t *method; \ + mdsdsc_t *object; \ + mdsdsc_t *arguments[nargs]; \ } -#define METHOD_0 \ - struct { \ - RECORD_HEAD(void) \ - mdsdsc_t *time_out; \ - mdsdsc_t *method; \ - mdsdsc_t *object; \ +#define METHOD_0 \ + struct \ + { \ + RECORD_HEAD(void) \ + mdsdsc_t *time_out; \ + mdsdsc_t *method; \ + mdsdsc_t *object; \ } -#define DESCRIPTOR_METHOD(name, method, object, timeout, nargs) \ - METHOD(nargs) \ - name = {0, \ - DTYPE_METHOD, \ - CLASS_R, \ - 0, \ - nargs + 3, \ - __fill_value__(mdsdsc_t *) timeout, \ - (mdsdsc_t *)method, \ +#define DESCRIPTOR_METHOD(name, method, object, timeout, nargs) \ + METHOD(nargs) \ + name = {0, \ + DTYPE_METHOD, \ + CLASS_R, \ + 0, \ + nargs + 3, \ + __fill_value__(mdsdsc_t *) timeout, \ + (mdsdsc_t *)method, \ (mdsdsc_t *)object} -#define DESCRIPTOR_METHOD_0(name, method, object, timeout) \ - METHOD_0 \ - name = {0, \ - DTYPE_METHOD, \ - CLASS_R, \ - 0, \ - 3, \ - __fill_value__(mdsdsc_t *) timeout, \ - (mdsdsc_t *)method, \ +#define DESCRIPTOR_METHOD_0(name, method, object, timeout) \ + METHOD_0 \ + name = {0, \ + DTYPE_METHOD, \ + CLASS_R, \ + 0, \ + 3, \ + __fill_value__(mdsdsc_t *) timeout, \ + (mdsdsc_t *)method, \ (mdsdsc_t *)object} TYPEDEF(1){TreeDEPENDENCY_AND = 10, TreeDEPENDENCY_OR = 11} ENDDEF(uint8_t, treedep_t); -typedef struct descriptor_dependency { +typedef struct descriptor_dependency +{ RECORD_HEAD(treedep_t) mdsdsc_t *arguments[2]; } mds_dependency_t; -#define DESCRIPTOR_DEPENDENCY(name, mode_ptr, arg_1, arg_2) \ - mds_dependency_t name = {(length_t)sizeof(treedep_t), \ - DTYPE_DEPENDENCY, \ - CLASS_R, \ - (treedep_t *)mode_ptr, \ - 2, \ - __fill_value__(mdsdsc_t *) arg_1, \ +#define DESCRIPTOR_DEPENDENCY(name, mode_ptr, arg_1, arg_2) \ + mds_dependency_t name = {(length_t)sizeof(treedep_t), \ + DTYPE_DEPENDENCY, \ + CLASS_R, \ + (treedep_t *)mode_ptr, \ + 2, \ + __fill_value__(mdsdsc_t *) arg_1, \ (mdsdsc_t *)arg_2} TYPEDEF(1){ @@ -747,32 +778,34 @@ TYPEDEF(1){ TreeIGNORE_STATUS = 9, } ENDDEF(uint8_t, treecond_t); -typedef struct descriptor_condition { +typedef struct descriptor_condition +{ RECORD_HEAD(treecond_t) mdsdsc_t *condition; } mds_condition_t; -#define DESCRIPTOR_CONDITION(name, mode_ptr, condition) \ - mds_condition_t name = {(length_t)sizeof(treecond_t), \ - DTYPE_CONDITION, \ - CLASS_R, \ - (treecond_t *)mode_ptr, \ - 1, \ +#define DESCRIPTOR_CONDITION(name, mode_ptr, condition) \ + mds_condition_t name = {(length_t)sizeof(treecond_t), \ + DTYPE_CONDITION, \ + CLASS_R, \ + (treecond_t *)mode_ptr, \ + 1, \ __fill_value__(mdsdsc_t *) condition} -typedef struct descriptor_with_units { +typedef struct descriptor_with_units +{ RECORD_HEAD(void) mdsdsc_t *data; mdsdsc_t *units; } mds_with_units_t; -#define DESCRIPTOR_WITH_UNITS(name, value, units) \ - mds_with_units_t name = {0, \ - DTYPE_WITH_UNITS, \ - CLASS_R, \ - 0, \ - 2, \ - __fill_value__(mdsdsc_t *) value, \ +#define DESCRIPTOR_WITH_UNITS(name, value, units) \ + mds_with_units_t name = {0, \ + DTYPE_WITH_UNITS, \ + CLASS_R, \ + 0, \ + 2, \ + __fill_value__(mdsdsc_t *) value, \ (mdsdsc_t *)units} /********************************************* @@ -781,83 +814,87 @@ typedef struct descriptor_with_units { The result (R0,R1) is given dtype, def=L. *********************************************/ -typedef struct descriptor_call { +typedef struct descriptor_call +{ RECORD_HEAD(dtype_t) mdsdsc_t *image; mdsdsc_t *routine; mdsdsc_t *arguments[1]; } mds_call_t; -#define CALL(nargs) \ - struct { \ - RECORD_HEAD(dtype_t) \ - mdsdsc_t *image; \ - mdsdsc_t *routine; \ - mdsdsc_t *arguments[nargs]; \ +#define CALL(nargs) \ + struct \ + { \ + RECORD_HEAD(dtype_t) \ + mdsdsc_t *image; \ + mdsdsc_t *routine; \ + mdsdsc_t *arguments[nargs]; \ } -#define DESCRIPTOR_CALL(name, dtype_ptr, nargs, image, routine) \ - CALL(nargs) \ - name = {(length_t)sizeof(dtype_t), \ - DTYPE_CALL, \ - CLASS_R, \ - dtype_ptr, \ - nargs + 2, \ - __fill_value__(mdsdsc_t *) image, \ - (mdsdsc_t *)routine, \ +#define DESCRIPTOR_CALL(name, dtype_ptr, nargs, image, routine) \ + CALL(nargs) \ + name = {(length_t)sizeof(dtype_t), \ + DTYPE_CALL, \ + CLASS_R, \ + dtype_ptr, \ + nargs + 2, \ + __fill_value__(mdsdsc_t *) image, \ + (mdsdsc_t *)routine, \ {0}} -typedef struct descriptor_with_error { +typedef struct descriptor_with_error +{ RECORD_HEAD(void) mdsdsc_t *data; mdsdsc_t *error; } mds_with_error_t; -#define DESCRIPTOR_WITH_ERROR(name, data, error) \ - mds_with_error_t name = {0, \ - DTYPE_WITH_ERROR, \ - CLASS_R, \ - 0, \ - 2, \ - __fill_value__(mdsdsc_t *) data, \ +#define DESCRIPTOR_WITH_ERROR(name, data, error) \ + mds_with_error_t name = {0, \ + DTYPE_WITH_ERROR, \ + CLASS_R, \ + 0, \ + 2, \ + __fill_value__(mdsdsc_t *) data, \ (mdsdsc_t *)error} -typedef struct descriptor_opaque { +typedef struct descriptor_opaque +{ RECORD_HEAD(void) mdsdsc_t *data; mdsdsc_t *opaque_type; } mds_opaque_t; -#define DESCRIPTOR_OPAQUE(name, data, opaque_type) \ - mds_opaque_t name = {0, \ - DTYPE_OPAQUE, \ - CLASS_R, \ - 0, \ - 2, \ - __fill_value__(mdsdsc_t *) data, \ +#define DESCRIPTOR_OPAQUE(name, data, opaque_type) \ + mds_opaque_t name = {0, \ + DTYPE_OPAQUE, \ + CLASS_R, \ + 0, \ + 2, \ + __fill_value__(mdsdsc_t *) data, \ (mdsdsc_t *)opaque_type} -#define DESCRIPTOR_FLOAT(name, _float) \ - mdsdsc_t name = {(length_t)sizeof(float), DTYPE_NATIVE_FLOAT, CLASS_S, \ +#define DESCRIPTOR_FLOAT(name, _float) \ + mdsdsc_t name = {(length_t)sizeof(float), DTYPE_NATIVE_FLOAT, CLASS_S, \ (char *)_float} -#define DESCRIPTOR_LONG(name, _int32) \ +#define DESCRIPTOR_LONG(name, _int32) \ mdsdsc_t name = {(length_t)sizeof(int32_t), DTYPE_L, CLASS_S, (char *)_int32} -#define DESCRIPTOR_QUADWORD(name, _int64) \ +#define DESCRIPTOR_QUADWORD(name, _int64) \ mdsdsc_t name = {(length_t)sizeof(int64_t), DTYPE_Q, CLASS_S, (char *)_int64} -#define DESCRIPTOR_NID(name, _nid) \ +#define DESCRIPTOR_NID(name, _nid) \ mdsdsc_t name = {(length_t)sizeof(int), DTYPE_NID, CLASS_S, (char *)_nid} /* * A simple macro to construct a 32-bit string descriptor: */ -#define DESCRIPTOR(name, string) \ - mdsdsc_t name = {(length_t)(sizeof(string) - 1), DTYPE_T, CLASS_S, \ +#define DESCRIPTOR(name, string) \ + mdsdsc_t name = {(length_t)(sizeof(string) - 1), DTYPE_T, CLASS_S, \ (char *)(string)} -#define DESCRIPTOR_FROM_CSTRING(name, cstring) \ - mdsdsc_t name = {(length_t)strlen(cstring), DTYPE_T, CLASS_S, \ +#define DESCRIPTOR_FROM_CSTRING(name, cstring) \ + mdsdsc_t name = {(length_t)strlen(cstring), DTYPE_T, CLASS_S, \ (char *)(cstring)} /* diff --git a/include/mdsevents.h b/include/mdsevents.h index 0fe261776f..d7690f6632 100644 --- a/include/mdsevents.h +++ b/include/mdsevents.h @@ -2,7 +2,8 @@ #include #endif -struct _id { +struct _id +{ struct linkage link; long status; char *name; diff --git a/include/mdslib.h b/include/mdslib.h index ce2db70845..8f1f521fa1 100644 --- a/include/mdslib.h +++ b/include/mdslib.h @@ -9,31 +9,32 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #ifndef MDSLIB_NO_PROTOS -int MdsConnect(char *host); -int descr(int *dtype, void *data, int *dim1, ...); -int descr2(int *dtype, int *dim1, ...); -int MdsOpen(char *tree, int *shot); -int MdsClose(char *tree, int *shot); -int MdsSetDefault(char *node); -int MdsValue(char *expression, ...); -int MdsPut(char *node, char *expression, ...); -int MdsValue2(char *expression, ...); -int MdsPut2(char *node, char *expression, ...); -int MdsSetSocket(int *socket); -void MdsDisconnect(); -int MdsConnectR(char *host); -int MdsOpenR(int *conid, char *tree, int *shot); -int MdsCloseR(int *conid, char *tree, int *shot); -int MdsSetDefaultR(int *conid, char *node); -int MdsValueR(int *conid, char *expression, ...); -int MdsPutR(int *conid, char *node, char *expression, ...); -int MdsValue2R(int *conid, char *expression, ...); -int MdsPut2R(int *conid, char *node, char *expression, ...); -void MdsDisconnectR(int *conid); + int MdsConnect(char *host); + int descr(int *dtype, void *data, int *dim1, ...); + int descr2(int *dtype, int *dim1, ...); + int MdsOpen(char *tree, int *shot); + int MdsClose(char *tree, int *shot); + int MdsSetDefault(char *node); + int MdsValue(char *expression, ...); + int MdsPut(char *node, char *expression, ...); + int MdsValue2(char *expression, ...); + int MdsPut2(char *node, char *expression, ...); + int MdsSetSocket(int *socket); + void MdsDisconnect(); + int MdsConnectR(char *host); + int MdsOpenR(int *conid, char *tree, int *shot); + int MdsCloseR(int *conid, char *tree, int *shot); + int MdsSetDefaultR(int *conid, char *node); + int MdsValueR(int *conid, char *expression, ...); + int MdsPutR(int *conid, char *node, char *expression, ...); + int MdsValue2R(int *conid, char *expression, ...); + int MdsPut2R(int *conid, char *node, char *expression, ...); + void MdsDisconnectR(int *conid); #endif #ifdef __cplusplus } // extern "C" diff --git a/include/mdsobjects.h b/include/mdsobjects.h index be024ece7c..659f0610ab 100644 --- a/include/mdsobjects.h +++ b/include/mdsobjects.h @@ -77,4183 +77,4462 @@ void **descs); void *convertToApdDsc(int type, int ndescs, void **ptr); void } */ -namespace MDSplus { +namespace MDSplus +{ -// Required for handling dynamic memory allocated in a different DLL on windows -// in Debug configuration -// MUST revert to old version. Winodws VS crashes otherwise!! The code MUST be -// moved from include + // Required for handling dynamic memory allocated in a different DLL on windows + // in Debug configuration + // MUST revert to old version. Winodws VS crashes otherwise!! The code MUST be + // moved from include -class Connection; -class Tree; + class Connection; + class Tree; -EXPORT void setActiveTree(Tree *tree); -EXPORT Tree *getActiveTree(); + EXPORT void setActiveTree(Tree *tree); + EXPORT Tree *getActiveTree(); -//////////////////////////////////////////////////////////////////////////////// -// MDS EXCEPTION /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // MDS EXCEPTION /////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The MdsException class -/// Extends stl exception class and holds a message accessible via virtual -/// funciont what() -/// -class EXPORT MdsException : public std::exception { + /// + /// \brief The MdsException class + /// Extends stl exception class and holds a message accessible via virtual + /// funciont what() + /// + class EXPORT MdsException : public std::exception + { + + friend EXPORT std::ostream &operator<<(std::ostream &outStream, + MdsException &exc) + { + return outStream << exc.what(); + } + + public: + MdsException(const char *msg) : msg(msg) {} + MdsException(std::string msg) : msg(msg) {} + MdsException(int status); + + virtual ~MdsException() NOEXCEPT {} + + /// + /// \brief virtual function to get exception message + /// \return error message + virtual const char *what() const NOEXCEPT { return msg.c_str(); } + + protected: + const std::string msg; + }; + + //////////////////////////////////////////////////////////////////////////////// + // MDS DATA CLASS ////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + class Data; + + /// Decrements the data reference counter and if last ref is reached deletes + /// the data instance and free the allocated memory. This function must be + /// called each time the code is responsible for the object deletion. + /// + EXPORT void deleteData(Data *); + + /// + /// \brief Data objects abstract baseclass class + /// + /// Every data in a tree is also a subclass of the generic Data class. + /// Subinstances of units, error, help and validation Data are also managed. + /// + /// This class implements also a reference counting feature of Data objects + /// though the overloading of new and delete operators. + /// + /// + class EXPORT Data + { + public: + /// Default constructor,s reference counting is set to 1 and the data to + /// "changed" state. + /// + Data() + : refCount(1), units(nullptr), error(nullptr), help(nullptr), + validation(nullptr) {} + + virtual ~Data(); + + // void *operator new(size_t sz); + // void operator delete(void *p); + + static void incRefCount(Data *d); + static void decRefCount(Data *d); + void incRefCount(); + void decRefCount(); + + virtual Data *getUnits(); + virtual Data *getError(); + virtual Data *getHelp(); + virtual Data *getValidation(); + virtual void setUnits(Data *in); + virtual void setError(Data *in); + virtual void setHelp(Data *in); + virtual void setValidation(Data *in); + + private: + /// Protect the use of copy constructor not permitted for Data objects, use + /// \ref clone() function instead. + Data(const Data &) {} + + ///@{ + /// Friendship declaration for TDI expression compilation + friend EXPORT Data *compile(const char *expr); + friend EXPORT Data *compileWithArgs(const char *expr, int nArgs...); + friend EXPORT Data *compile(const char *expr, Tree *tree); + friend EXPORT Data *compileWithArgs(const char *expr, Tree *tree, + int nArgs...); + friend EXPORT Data *execute(const char *expr); + friend EXPORT Data *executeWithArgs(const char *expr, int nArgs...); + friend EXPORT Data *execute(const char *expr, Tree *tree); + friend EXPORT Data *executeWithArgs(const char *expr, Tree *tree, + int nArgs...); + friend EXPORT Data *deserialize(char const *serialized); + friend EXPORT Data *deserialize(Data *serialized); + ///@} + + virtual void propagateDeletion() {} + + public: + // NOTE: [andrea] why public? + int clazz; ///< data class member + int dtype; ///< data type member + int refCount; ///< reference counting member + + /// Pure virtual function matching data to a specific MDS descriptor + /// \return MDS descriptor structure + /// \ingroup Descrmap + virtual void *convertToDsc() = 0; + + /// Complete conversion to csc by condsidering help, units and error + /// implementations of convertToDsc() calls this completion function + /// \ingroup Descrmap + void *completeConversionToDsc(void *dsc); + + /// c style access to internal data members + virtual void getInfo(char *clazz, char *dtype, short *length = NULL, + char *nDims = NULL, int **dims = NULL, + void **ptr = NULL) + { + *clazz = this->clazz; + *dtype = this->dtype; + if (length) + *length = 0; + if (nDims) + *nDims = 0; + if (dims) + *dims = 0; + if (ptr) + *ptr = 0; + } + + /// \return true if this and data match, false otherwise and as default + virtual bool equals(Data *data __attribute__((unused))) { return false; } + + /// \return Return the result of TDI evaluate + Data *evaluate(); + Data *evaluate(Tree *tree); + + /// eports TDI data functionality, i.e. returns a native type + /// (scalar or array). + virtual Data *data(); + virtual Data *data(Tree *tree); + + /// Return the result of TDI decompile + char *decompile(); + + /// Make a dymanically allocated copy of the Data instance Tree + Data *clone(); + + /// serialize data into non terminated char array using serializeData + /// function, if serializeData fails MdsException is trown. + /// + /// \see serializeData(void *dsc, int *retSize, void **retDsc) + /// \param size set to serialized data length + /// \return c string representing serialized data + char *serialize(int *size); + + ///@{ \ingroup NativeTypes + /// + /// Access data as native type using getData() conversion function. This + /// function might be overloaded by derived data classes to improve + /// conversion. + /// + virtual char getByte(); + virtual short getShort(); + virtual int getInt(); + virtual int64_t getLong(); + virtual unsigned char getByteUnsigned(); + virtual unsigned short getShortUnsigned(); + virtual unsigned int getIntUnsigned(); + virtual uint64_t getLongUnsigned(); + virtual float getFloat(); + virtual double getDouble(); + virtual std::complex getComplex() + { + throw MdsException("getComplex() not supported for non Complex data types"); + } + virtual char *getString() { return decompile(); } + virtual int *getShape(int *numDim); + virtual char *getByteArray(int *numElements); + virtual std::vector getByteArray(); + virtual short *getShortArray(int *numElements); + virtual std::vector getShortArray(); + virtual int *getIntArray(int *numElements); + virtual std::vector getIntArray(); + virtual int64_t *getLongArray(int *numElements); + virtual std::vector getLongArray(); + virtual float *getFloatArray(int *numElements); + virtual std::vector getFloatArray(); + virtual unsigned char *getByteUnsignedArray(int *numElements); + virtual std::vector getByteUnsignedArray(); + virtual unsigned short *getShortUnsignedArray(int *numElements); + virtual std::vector getShortUnsignedArray(); + virtual unsigned int *getIntUnsignedArray(int *numElements); + virtual std::vector getIntUnsignedArray(); + virtual uint64_t *getLongUnsignedArray(int *numElements); + virtual std::vector getLongUnsignedArray(); + virtual double *getDoubleArray(int *numElements); + virtual std::vector getDoubleArray(); + virtual std::complex *getComplexArray(int *numElements + __attribute__((unused))) + { + throw MdsException( + "getComplexArray() not supported for non Complex data types"); + } + virtual std::vector > getComplexArray(); + virtual char **getStringArray(int *numElements) + { + *numElements = 0; + return NULL; + } + ///@} + + virtual Data *getDimensionAt(int dimIdx); + + virtual int getSize() { return 1; } + + /// Instantiate a Scope object and plot data into. + virtual void plot(); + + friend EXPORT std::ostream &operator<<(std::ostream &outStream, + MDSplus::Data *data); + + protected: + /// readonly access + virtual bool isImmutable() { return true; } + + /// Set accessory data (utits, error, help and validation) + void setAccessory(Data *units, Data *error, Data *help, Data *validation) + { + setUnits(units); + setError(error); + setHelp(help); + setValidation(validation); + } + + private: + /// Execute data conversion selecting proper descriptor conversion function. + /// If conversion fails a MdsException is thrown. + /// \param classType target class type + /// \param dataType target data type + Data *getData(int classType, int dataType); + + /// convert data to array type (CLASS_A) \see getData() + Data *getArrayData(int dataType); + + /// convert data to scalar type (CLASS_S) \see getData() + Data *getScalarData(int dataType); + + /// + /// @{ + /// Accessory information added on this data + friend void deleteData(Data *data); + Data *units; + Data *error; + Data *help; + Data *validation; + //// @} + }; + + //////////////////////////////////////////////////////////////////////////////// + // SCALAR DATA ///////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Scalar class + /// + /// Scalar is the common base class for all scalar data types + /// (descriptor class CLASS_S). + class EXPORT Scalar : public Data + { + friend class Array; + + protected: + int length; + char *ptr; + + public: + Scalar() : length(0), ptr(0) { clazz = CLASS_S; } + + virtual ~Scalar() { delete[] ptr; } + + /// convert data to scalar descriptor + virtual void *convertToDsc(); + + virtual void getInfo(char *clazz, char *dtype, short *length = NULL, + char *nDims = NULL, int **dims = NULL, + void **ptr = NULL) + { + *clazz = this->clazz; + *dtype = this->dtype; + if (length) + *length = this->length; + if (nDims) + *nDims = 0; + if (dims) + *dims = 0; + if (ptr) + *ptr = this->ptr; + } + + }; // ScalarData + + //////////////////////////////////////////////////////////////////////////////// + // INT8 SCALAR ///////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int8 class object description of DTYPE_B + /// + class EXPORT Int8 : public Scalar + { + public: + Int8(char val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_B; + length = 1; + ptr = new char[1]; + ptr[0] = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(ptr[0]); } + short getShort() { return numeric_cast(ptr[0]); } + int getInt() { return numeric_cast(ptr[0]); } + int64_t getLong() { return numeric_cast(ptr[0]); } + unsigned char getByteUnsigned() + { + return numeric_cast(ptr[0]); + } + unsigned short getShortUnsigned() + { + return numeric_cast(ptr[0]); + } + unsigned int getIntUnsigned() { return numeric_cast(ptr[0]); } + uint64_t getLongUnsigned() { return numeric_cast(ptr[0]); } + float getFloat() { return numeric_cast(ptr[0]); } + double getDouble() { return numeric_cast(ptr[0]); } + + ///@} + }; + + /// + /// \brief The Uint8 class object description of DTYPE_BU + /// + class EXPORT Uint8 : public Scalar + { + public: + Uint8(unsigned char val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_BU; + length = 1; + ptr = new char[1]; + ptr[0] = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(unsigned char *)ptr); } + short getShort() { return numeric_cast(*(unsigned char *)ptr); } + int getInt() { return numeric_cast(*(unsigned char *)ptr); } + int64_t getLong() { return numeric_cast(*(unsigned char *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(unsigned char *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(unsigned char *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(unsigned char *)ptr); + } + uint64_t getLongUnsigned() + { + return numeric_cast(*(unsigned char *)ptr); + } + float getFloat() { return numeric_cast(*(unsigned char *)ptr); } + double getDouble() { return numeric_cast(*(unsigned char *)ptr); } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT16 SCALAR //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int16 class object description of DTYPE_W + /// + class EXPORT Int16 : public Scalar + { + public: + Int16(short val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_W; + length = 2; + ptr = new char[2]; + *(short *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(short *)ptr); } + short getShort() { return numeric_cast(*(short *)ptr); } + int getInt() { return numeric_cast(*(short *)ptr); } + int64_t getLong() { return numeric_cast(*(short *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(short *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(short *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(short *)ptr); + } + uint64_t getLongUnsigned() { return numeric_cast(*(short *)ptr); } + float getFloat() { return numeric_cast(*(short *)ptr); } + double getDouble() { return numeric_cast(*(short *)ptr); } + + ///@} + }; + + /// + /// \brief The Uint16 class object description of DTYPE_WU + /// + class EXPORT Uint16 : public Scalar + { + public: + Uint16(unsigned short val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_WU; + length = 2; + ptr = new char[2]; + *(unsigned short *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(unsigned short *)ptr); } + short getShort() { return numeric_cast(*(unsigned short *)ptr); } + int getInt() { return numeric_cast(*(unsigned short *)ptr); } + int64_t getLong() { return numeric_cast(*(unsigned short *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(unsigned short *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(unsigned short *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(unsigned short *)ptr); + } + uint64_t getLongUnsigned() + { + return numeric_cast(*(unsigned short *)ptr); + } + float getFloat() { return numeric_cast(*(unsigned short *)ptr); } + double getDouble() { return numeric_cast(*(unsigned short *)ptr); } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT32 SCALAR //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int32 class object description of DTYPE_L + /// + class EXPORT Int32 : public Scalar + { + public: + Int32(int val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_L; + length = sizeof(int); + ptr = new char[sizeof(int)]; + *(int *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(int *)ptr); } + short getShort() { return numeric_cast(*(int *)ptr); } + int getInt() { return numeric_cast(*(int *)ptr); } + int64_t getLong() { return numeric_cast(*(int *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(int *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(int *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(int *)ptr); + } + uint64_t getLongUnsigned() { return numeric_cast(*(int *)ptr); } + float getFloat() { return numeric_cast(*(int *)ptr); } + double getDouble() { return numeric_cast(*(int *)ptr); } + + ///@} + }; + + /// + /// \brief The Uint32 class object description of DTYPE_LU + /// + class EXPORT Uint32 : public Scalar + { + public: + Uint32(unsigned int val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_LU; + length = sizeof(int); + ptr = new char[sizeof(int)]; + *(unsigned int *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(unsigned int *)ptr); } + short getShort() { return numeric_cast(*(unsigned int *)ptr); } + int getInt() { return numeric_cast(*(unsigned int *)ptr); } + int64_t getLong() { return numeric_cast(*(unsigned int *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(unsigned int *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(unsigned int *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(unsigned int *)ptr); + } + uint64_t getLongUnsigned() + { + return numeric_cast(*(unsigned int *)ptr); + } + float getFloat() { return numeric_cast(*(unsigned int *)ptr); } + double getDouble() { return numeric_cast(*(unsigned int *)ptr); } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT64 SCALAR //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int64 class object description of DTYPE_Q + /// + class EXPORT Int64 : public Scalar + { + public: + Int64(int64_t val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_Q; + length = sizeof(int64_t); + ptr = new char[sizeof(int64_t)]; + *(int64_t *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(int64_t *)ptr); } + short getShort() { return numeric_cast(*(int64_t *)ptr); } + int getInt() { return numeric_cast(*(int64_t *)ptr); } + int64_t getLong() { return numeric_cast(*(int64_t *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(int64_t *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(int64_t *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(int64_t *)ptr); + } + uint64_t getLongUnsigned() { return numeric_cast(*(int64_t *)ptr); } + float getFloat() { return numeric_cast(*(int64_t *)ptr); } + double getDouble() { return numeric_cast(*(int64_t *)ptr); } + + ///@} + }; + + /// + /// \brief The Uint64 class object description of DTYPE_QU + /// + class EXPORT Uint64 : public Scalar + { + public: + Uint64(uint64_t val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_QU; + length = sizeof(int64_t); + ptr = new char[sizeof(int64_t)]; + *(uint64_t *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + unsigned char getByteUnsigned() + { + return numeric_cast(*(uint64_t *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(uint64_t *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(uint64_t *)ptr); + } + uint64_t getLongUnsigned() + { + return numeric_cast(*(uint64_t *)ptr); + } + char getByte() { return numeric_cast(*(uint64_t *)ptr); } + short getShort() { return numeric_cast(*(uint64_t *)ptr); } + int getInt() { return numeric_cast(*(uint64_t *)ptr); } + int64_t getLong() { return numeric_cast(*(uint64_t *)ptr); } + float getFloat() { return numeric_cast(*(uint64_t *)ptr); } + double getDouble() { return numeric_cast(*(uint64_t *)ptr); } + char *getDate(); + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // FLOAT32 SCALAR ////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Float32 class object description of DTYPE_FLOAT + /// + class EXPORT Float32 : public Scalar + { + public: + Float32(float val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_FLOAT; + length = sizeof(float); + ptr = new char[sizeof(float)]; + *(float *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(float *)ptr); } + short getShort() { return numeric_cast(*(float *)ptr); } + int getInt() { return numeric_cast(*(float *)ptr); } + int64_t getLong() { return numeric_cast(*(float *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(float *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(float *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(float *)ptr); + } + uint64_t getLongUnsigned() { return numeric_cast(*(float *)ptr); } + float getFloat() { return numeric_cast(*(float *)ptr); } + double getDouble() { return numeric_cast(*(float *)ptr); } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // FLOAT64 SCALAR ////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Float64 class object description of DTYPE_DOUBLE + /// + class EXPORT Float64 : public Scalar + { + public: + Float64(double val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_DOUBLE; + length = sizeof(double); + ptr = new char[sizeof(double)]; + *(double *)ptr = val; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + char getByte() { return numeric_cast(*(double *)ptr); } + short getShort() { return numeric_cast(*(double *)ptr); } + int getInt() { return numeric_cast(*(double *)ptr); } + int64_t getLong() { return numeric_cast(*(double *)ptr); } + unsigned char getByteUnsigned() + { + return numeric_cast(*(double *)ptr); + } + unsigned short getShortUnsigned() + { + return numeric_cast(*(double *)ptr); + } + unsigned int getIntUnsigned() + { + return numeric_cast(*(double *)ptr); + } + uint64_t getLongUnsigned() { return numeric_cast(*(double *)ptr); } + float getFloat() { return numeric_cast(*(double *)ptr); } + double getDouble() { return numeric_cast(*(double *)ptr); } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // COMPLEX32 SCALAR //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Complex32 class object description of DTYPE_FSC + /// + class EXPORT Complex32 : public Scalar + { + public: + Complex32(float re, float im, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_FSC; + length = 2 * sizeof(float); + ptr = new char[2 * sizeof(float)]; + ((float *)ptr)[0] = re; + ((float *)ptr)[1] = im; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + float getReal() { return ((float *)ptr)[0]; } + float getImaginary() { return ((float *)ptr)[1]; } + std::complex getComplex() + { + return std::complex(((float *)ptr)[0], ((float *)ptr)[1]); + } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // COMPLEX64 SCALAR //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Complex64 class object description of DTYPE_FTC + /// + class EXPORT Complex64 : public Scalar + { + public: + Complex64(double re, double im, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_FTC; + length = 2 * sizeof(double); + ptr = new char[2 * sizeof(double)]; + ((double *)ptr)[0] = re; + ((double *)ptr)[1] = im; + setAccessory(units, error, help, validation); + } + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + double getReal() { return ((double *)ptr)[0]; } + double getImaginary() { return ((double *)ptr)[1]; } + std::complex getComplex() + { + return std::complex(((double *)ptr)[0], ((double *)ptr)[1]); + } + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // STRING SCALAR /////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The String class object description of DTYPE_T + /// + class EXPORT String : public Scalar + { + public: + String(const char *val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + init(val, std::string(val).size(), units, error, help, validation); + } + + String(unsigned char *uval, int len __attribute__((unused)), Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + // FIXME: Hack to handle broken LabView types that use unsigned char (as + // uint8) instead of char + // FIXME: Warning: Do not use this constructor in user code + char *val = reinterpret_cast(uval); + init(val, std::string(val).size(), units, error, help, validation); + } + + // GAB definition in order to avoid breaking LabVIEW + String(unsigned char *uval, int numDims __attribute__((unused)), + int *dims __attribute__((unused)), Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + char *val = reinterpret_cast(uval); + init(val, std::string(val).size(), units, error, help, validation); + } + + String(const char *val, int len, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + init(val, len, units, error, help, validation); + } + + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + char *getString() + { + char *res = new char[length + 1]; + std::copy(&ptr[0], &ptr[length + 1], res); + res[length] = 0; + return res; + } + + /// get a string array of a single element + char **getStringArray(int *numElements) + { + char **res = new char *[1]; + res[0] = new char[length + 1]; + std::copy(&ptr[0], &ptr[length + 1], res[0]); + res[0][length] = 0; + *numElements = 1; + return res; + } + + /// check if two strings have the same content. + bool equals(Data *data); + + private: + virtual void init(char const *val, int len, Data *units, Data *error, + Data *help, Data *validation) + { + dtype = DTYPE_T; + length = len; + ptr = new char[length + 1]; + std::copy(&val[0], &val[length], ptr); + ptr[length] = 0; + setAccessory(units, error, help, validation); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // IDENT SCALAR /////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Ident class is the object description of DTYPE_IDENT and is used + /// to describe TDI variables + /// + class EXPORT Ident : public String + { + public: + Ident(const char *val, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : String(val, units, error, help, validation) + { + dtype = DTYPE_IDENT; + } + + Ident(unsigned char *uval, int len, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + : String(uval, len, units, error, help, validation) + { + dtype = DTYPE_IDENT; + } + + // GAB definition in order to avoid breaking LabVIEW + Ident(unsigned char *uval, int numDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + : String(uval, numDims, dims, units, error, help, validation) + { + dtype = DTYPE_IDENT; + } + + Ident(const char *val, int len, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + : String(val, len, units, error, help, validation) + { + dtype = DTYPE_IDENT; + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // ARRAY DATA ////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Array class object description of DTYPE_A + /// + /// Common base class for arrays (CLASS_A). It contains dimension informationThe + /// contained data is assumed to be row-first ordered. + /// Array - derived classes will hold actual data in language-specific + /// structures. This allows for a direct implementation of operations such as + /// getElementAt() and setElementAt() which would be difficult or impossible to + /// implement via TDI. + /// + /// For the remaining Data methods, the generic mechanism of the base class' + /// implementation (conversion to MDSplus descriptor, TDI operation conversion + /// back to class instances) is retained. + + class EXPORT Array : public Data + { + protected: + int length; ///< individual size of stored data element + int arsize; ///< total array data storage size + int nDims; ///< number of dimensions of the array access tuple + int dims[MAX_DIMS]; ///< store each dimension size + char *ptr; + + void setSpecific(void const *data, int length, int dtype, int nData) + { + setSpecific(data, length, dtype, 1, &nData); + } + + void setSpecific(void const *data, int length, int dtype, int nDims, + int *dims) + { + this->dtype = dtype; + this->nDims = nDims; + this->length = length; + arsize = length; + for (int i = 0; i < nDims; i++) + { + arsize *= dims[i]; + this->dims[i] = dims[i]; + } + + char const *dataBytes = reinterpret_cast(data); + ptr = new char[arsize]; + std::copy(&dataBytes[0], &dataBytes[arsize], ptr); + } + + public: + Array() : length(0), arsize(0), nDims(0), ptr(0) { clazz = CLASS_A; } + + ~Array() + { + // deleteNativeArray(ptr); + delete[] ptr; + } + + /// returns total array storage size as product of dimensions + virtual int getSize() + { + int retSize = 1; + for (int i = 0; i < nDims; i++) + retSize *= dims[i]; + return retSize; + } + + virtual void getInfo(char *clazz, char *dtype, short *length = NULL, + char *nDims = NULL, int **dims = NULL, + void **ptr = NULL) + { + *clazz = this->clazz; + *dtype = this->dtype; + if (length) + *length = this->length; + if (nDims) + *nDims = this->nDims; + if (dims) + { + *dims = new int[this->nDims]; + for (int i = 0; i < this->nDims; i++) + (*dims)[i] = this->dims[i]; + } + if (ptr) + *ptr = this->ptr; + } + + /// Provides a method to get the array shape, i.e. the array of dimension + /// sizes and the total number of dimensions. + virtual int *getShape(int *numDims); + + /// Retrieve a single element from the array matrix at the getDims position, + /// if the passed number of dimension is equals to the dimension of dims + /// field. Otherwise it returns the reshaped array corresponding to the + /// passed dimension array. For example, if the array is bi-dimensional, a + /// single dimension i will specify the i-th row. + /// + /// If the position exceeds the array dimension boundaries an exception is + /// thrown + /// + /// \param getDims array of integers identifying the position tuple of the + /// array \param getNumDims the size of the position tuple + Data *getElementAt(int *getDims, int getNumDims); + + // TODO: [andrea] finire ... + /// + /// If the position exceeds the array dimension boundaries an exception is + /// thrown + /// + /// \param getDims array of integers identifying the position tuple of the + /// array \param getNumDims the size of the position tuple \param data the + /// data object to set + void setElementAt(int *getDims, int getNumDims, Data *data); + + /// Retrieve an element considering the array as one dimension shaped. + Data *getElementAt(int dim) { return getElementAt(&dim, 1); } + + /// Set an element considering the array as one dimension shaped. + void setElementAt(int dim, Data *data) { setElementAt(&dim, 1, data); } + + Array *getSubArray(int startDim, int nSamples); + + /// Convert data to array descriptor + void *convertToDsc(); + + ///@{ + /// inline overloaded conversion access returning result of cast operator of + /// the Scalar object data member + + void *getArray() { return ptr; } + char *getByteArray(int *numElements); + short *getShortArray(int *numElements); + int *getIntArray(int *numElements); + int64_t *getLongArray(int *numElements); + unsigned char *getByteUnsignedArray(int *numElements); + unsigned short *getShortUnsignedArray(int *numElements); + unsigned int *getIntUnsignedArray(int *numElements); + uint64_t *getLongUnsignedArray(int *numElements); + float *getFloatArray(int *numElements); + double *getDoubleArray(int *numElements); + std::complex *getComplexArray(int *numElements); + virtual char **getStringArray(int *numElements); + + ///@} + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT8 ARRAY DATA ///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int8Array class, array of objects of descriptor type DTYPE_B + /// + class Int8Array : public Array + { + public: + Int8Array(char const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, 1, DTYPE_B, nData); + setAccessory(units, error, help, validation); + } + Int8Array(char const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 1, DTYPE_B, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + /// + /// \brief The Uint8Array class, array of objects of descriptor type DTYPE_BU + /// + class EXPORT Uint8Array : public Array + { + friend Data *deserialize(Data *serializedData); + + public: + Uint8Array(unsigned char const *data, int nData, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 1, DTYPE_BU, nData); + setAccessory(units, error, help, validation); + } + Uint8Array(unsigned char const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 1, DTYPE_BU, nDims, dims); + setAccessory(units, error, help, validation); + } + Data *deserialize(); + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT16 ARRAY DATA //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int16Array class, array of objects of descriptor type DTYPE_W + /// + class Int16Array : public Array + { + public: + Int16Array(short const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, 2, DTYPE_W, nData); + setAccessory(units, error, help, validation); + } + Int16Array(short const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 2, DTYPE_W, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + /// + /// \brief The Uint16Array class, array of objects of descriptor type DTYPE_WU + /// + class Uint16Array : public Array + { + public: + Uint16Array(unsigned short const *data, int nData, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 2, DTYPE_WU, nData); + setAccessory(units, error, help, validation); + } + Uint16Array(unsigned short const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 2, DTYPE_WU, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT32 ARRAY DATA //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int32Array class, array of objects of descriptor type DTYPE_L + /// + class Int32Array : public Array + { + public: + Int32Array(int const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(int), DTYPE_L, nData); + setAccessory(units, error, help, validation); + } + Int32Array(int const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(int), DTYPE_L, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + /// + /// \brief The Uint32Array, array of objects of descriptor type DTYPE_LU + /// + class Uint32Array : public Array + { + public: + Uint32Array(unsigned int const *data, int nData, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(int), DTYPE_LU, nData); + setAccessory(units, error, help, validation); + } + Uint32Array(unsigned int const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(int), DTYPE_LU, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // INT64 ARRAY DATA //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Int64Array class, array of objects of descriptor type DTYPE_Q + /// + class Int64Array : public Array + { + public: + Int64Array(int64_t const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, 8, DTYPE_Q, nData); + setAccessory(units, error, help, validation); + } + Int64Array(int64_t const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 8, DTYPE_Q, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + /// + /// \brief The Uint64Array class object, array of objects of descriptor type + /// DTYPE_QU + /// + class Uint64Array : public Array + { + public: + Uint64Array(uint64_t const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, 8, DTYPE_QU, nData); + setAccessory(units, error, help, validation); + } + Uint64Array(uint64_t const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, 8, DTYPE_QU, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // FLOAT32 ARRAY DATA ////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Float32Array class object, array of objects of descriptor type + /// DTYPE_FLOAT + /// + class Float32Array : public Array + { + public: + Float32Array(float const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(float), DTYPE_FLOAT, nData); + setAccessory(units, error, help, validation); + } + Float32Array(float const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(float), DTYPE_FLOAT, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + /// + /// \brief The Float64Array class object, array of objects of descriptor type + /// DTYPE_DOUBLE + /// + class Float64Array : public Array + { + public: + Float64Array(double const *data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(double), DTYPE_DOUBLE, nData); + setAccessory(units, error, help, validation); + } + Float64Array(double const *data, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(data, sizeof(double), DTYPE_DOUBLE, nDims, dims); + setAccessory(units, error, help, validation); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // COMPLEX32 ARRAY DATA //////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// - friend EXPORT std::ostream &operator<<(std::ostream &outStream, - MdsException &exc) { - return outStream << exc.what(); - } + /// + /// \brief The Complex32Array class, array of objects of descriptor type + /// DTYPE_FSC + /// + class Complex32Array : public Array + { + public: + Complex32Array(float const *reIm, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + setSpecific(reIm, 2 * sizeof(float), DTYPE_FSC, nData); + setAccessory(units, error, help, validation); + } + Complex32Array(float const *reIm, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(reIm, 2 * sizeof(float), DTYPE_FSC, nDims, dims); + setAccessory(units, error, help, validation); + } + }; -public: - MdsException(const char *msg) : msg(msg) {} - MdsException(std::string msg) : msg(msg) {} - MdsException(int status); + /// + /// \brief The Complex64Array class, array of objects of descriptor type + /// DTYPE_FTC + /// + class Complex64Array : public Array + { + public: + Complex64Array(double const *reIm, int nData, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(reIm, 2 * sizeof(double), DTYPE_FTC, nData); + setAccessory(units, error, help, validation); + } + Complex64Array(double const *reIm, int nDims, int *dims, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + setSpecific(reIm, 2 * sizeof(double), DTYPE_FTC, nDims, dims); + setAccessory(units, error, help, validation); + } + }; - virtual ~MdsException() NOEXCEPT {} + //////////////////////////////////////////////////////////////////////////////// + // STRING ARRAY DATA /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// /// - /// \brief virtual function to get exception message - /// \return error message - virtual const char *what() const NOEXCEPT { return msg.c_str(); } + /// \brief The StringArray class, array of objects of descriptor type DTYPE_T + /// + class StringArray : public Array + { + public: + /// StringArray constructor from array of c strings + StringArray(char **data, int nData, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + // Pad all string to longest + int maxLen = 0; + for (int i = 0; i < nData; i++) + maxLen = std::max(std::string(data[i]).size(), (std::size_t)maxLen); + + char *padData = new char[nData * maxLen]; + for (int i = 0; i < nData; i++) + { + std::size_t currLen = std::string(data[i]).size(); + std::copy(&data[i][0], &data[i][currLen], &padData[i * maxLen]); + std::fill(&padData[i * maxLen + currLen], &padData[i * maxLen + maxLen], + ' '); + } + setSpecific(padData, maxLen, DTYPE_T, nData); + setAccessory(units, error, help, validation); + delete[] padData; + } + + /// StringArray constructor from single c string + StringArray(char const *data, int nStrings, int stringLen, Data *units = 0, + Data *error = 0, Data *help = 0, + Data *validation = 0) // For contiuguous + { + setSpecific(data, stringLen, DTYPE_T, nStrings); + setAccessory(units, error, help, validation); + } + }; -protected: - const std::string msg; -}; + //////////////////////////////////////////////////////////////////////////////// + // COMPOUND DATA //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Compound class object description of DTYPE_R + /// + /// Compound is the common base class for all CLASS_R types. Its fields contain + /// all the required information (Descriptor array, keyword). Its getter/setter + /// methods allow to read/replace descriptors, based on their index. Derived + /// classes will only define methods with appropriate names for reading/writing + /// descriptors (i.e. Data objects). + + class EXPORT Compound : public Data + { + public: + Compound() : opcode(0) { setClass(); } + + Compound(int dtype, int length, void *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + setClass(); + setAccessory(units, error, help, validation); + this->dtype = dtype; + + switch (length) + { + case 1: + opcode = *(static_cast(ptr)); + break; + case 2: + opcode = *(static_cast(ptr)); + break; + case 4: + opcode = *(static_cast(ptr)); + break; + default: + opcode = 0; + } + + for (int i = 0; i < nDescs; ++i) + { + this->descs.push_back((Data *)descs[i]); + if (this->descs[i]) + this->descs[i]->incRefCount(); + } + } + + virtual void propagateDeletion() + { + for (std::size_t i = 0; i < descs.size(); ++i) + if (descs[i]) + { + descs[i]->decRefCount(); + deleteData(descs[i]); + } + } + + void *convertToDsc(); + + virtual ~Compound() { propagateDeletion(); } + + protected: + short opcode; ///< used only by some derived classes. + std::vector descs; ///< descriptors storage member + + /// increment reference of each stored data + void incrementRefCounts() + { + for (std::size_t i = 0; i < descs.size(); ++i) + if (descs[i]) + descs[i]->refCount++; + } + + public: + /// set Data at idx element of contained descriptors + void assignDescAt(Data *data, int idx) + { + if (idx < 0 || idx >= (int)descs.size()) + { + if (data) + deleteData(data); + throw(MdsException("Index out of bounds accessing arguments")); + } + + if (descs.at(idx)) + { + descs.at(idx)->decRefCount(); + deleteData(descs[idx]); + } + + descs.at(idx) = data; + if (data) + data->refCount++; + } + + /// retrieve Data at the idx position of contained descriptors + Data *getDescAt(int idx) + { + if (idx < 0 || idx >= (int)descs.size()) + { + throw(MdsException("Index out of bounds accessing arguments")); + } + + if (descs.at(idx)) + descs[idx]->incRefCount(); + return descs[idx]; + } + int getNumDescs() { return descs.size(); } + + private: + void setClass() { clazz = CLASS_R; } + }; + + //////////////////////////////////////////////////////////////////////////////// + // SIGNAL COMPOUND /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Signal class object description of DTYPE_SIGNAL + /// + /// MDSplus provides a signal data type which combines dimension descriptions + /// with the data. While it was initially designed to be used for efficient + /// storage of data acquired from measurement devices attached to an experiment + /// it has been found to be a very useful way of storing additional information + /// such as results from data analysis or modeling data. A signal is a + /// structure of three or more fields. The first field is the "value" field of + /// the signal. This is followed by an optional raw data field (explained + /// later). These two fields can be followed by one or more dimension + /// descriptions. The number of dimension descriptions in general should match + /// the dimensionality of the value. MDSplus stores data from a transient + /// recorder which is a device which measures voltage as a function of time. + /// Typically a transient recorder uses a analog to digital converter and + /// records the data as a series of integer values. A linear conversion can be + /// done to convert these integer values into input voltages being measured. + /// When MDSplus stores the data for such a device it uses a signal datatype to + /// record the data. The signal structure is constructed by putting an + /// expression for converting the integer data to volts in the "value" portion, + /// the integer data in the raw data portion, and a representation of the + /// timebase in the single dimension portion. + /// + /// \note This class represents a data descriptor of a signal intended as an + /// ordered sequence of data. Nothing in common with software objects + /// signalling systems. + + class EXPORT Signal : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Signal(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + // Signal descriptor requires length = 0, so override the method + void *convertToDsc(); + +#endif // DOXYGEN end of hidden code + + Signal(Data *data, Data *raw, Data *dimension, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + descs.push_back(data); + descs.push_back(raw); + descs.push_back(dimension); + init(units, error, help, validation); + } + + Signal(Data *data, Data *raw, Data *dimension1, Data *dimension2, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + descs.push_back(data); + descs.push_back(raw); + descs.push_back(dimension1); + descs.push_back(dimension2); + init(units, error, help, validation); + } -//////////////////////////////////////////////////////////////////////////////// -// MDS DATA CLASS ////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Signal(Data *data, Data *raw, int nDims, Data **dimensions, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + descs.push_back(data); + descs.push_back(raw); + for (int i = 0; i < nDims; i++) + descs.push_back(dimensions[i]); + init(units, error, help, validation); + } -class Data; + Data *getData() { return getDescAt(0); } -/// Decrements the data reference counter and if last ref is reached deletes -/// the data instance and free the allocated memory. This function must be -/// called each time the code is responsible for the object deletion. -/// -EXPORT void deleteData(Data *); + Data *getRaw() { return getDescAt(1); } -/// -/// \brief Data objects abstract baseclass class -/// -/// Every data in a tree is also a subclass of the generic Data class. -/// Subinstances of units, error, help and validation Data are also managed. -/// -/// This class implements also a reference counting feature of Data objects -/// though the overloading of new and delete operators. -/// -/// -class EXPORT Data { -public: - /// Default constructor,s reference counting is set to 1 and the data to - /// "changed" state. - /// - Data() - : refCount(1), units(nullptr), error(nullptr), help(nullptr), - validation(nullptr) {} - - virtual ~Data(); - - // void *operator new(size_t sz); - // void operator delete(void *p); - - static void incRefCount(Data *d); - static void decRefCount(Data *d); - void incRefCount(); - void decRefCount(); - - virtual Data *getUnits(); - virtual Data *getError(); - virtual Data *getHelp(); - virtual Data *getValidation(); - virtual void setUnits(Data *in); - virtual void setError(Data *in); - virtual void setHelp(Data *in); - virtual void setValidation(Data *in); - -private: - /// Protect the use of copy constructor not permitted for Data objects, use - /// \ref clone() function instead. - Data(const Data &) {} - - ///@{ - /// Friendship declaration for TDI expression compilation - friend EXPORT Data *compile(const char *expr); - friend EXPORT Data *compileWithArgs(const char *expr, int nArgs...); - friend EXPORT Data *compile(const char *expr, Tree *tree); - friend EXPORT Data *compileWithArgs(const char *expr, Tree *tree, - int nArgs...); - friend EXPORT Data *execute(const char *expr); - friend EXPORT Data *executeWithArgs(const char *expr, int nArgs...); - friend EXPORT Data *execute(const char *expr, Tree *tree); - friend EXPORT Data *executeWithArgs(const char *expr, Tree *tree, - int nArgs...); - friend EXPORT Data *deserialize(char const *serialized); - friend EXPORT Data *deserialize(Data *serialized); - ///@} - - virtual void propagateDeletion() {} - -public: - // NOTE: [andrea] why public? - int clazz; ///< data class member - int dtype; ///< data type member - int refCount; ///< reference counting member - - /// Pure virtual function matching data to a specific MDS descriptor - /// \return MDS descriptor structure - /// \ingroup Descrmap - virtual void *convertToDsc() = 0; - - /// Complete conversion to csc by condsidering help, units and error - /// implementations of convertToDsc() calls this completion function - /// \ingroup Descrmap - void *completeConversionToDsc(void *dsc); - - /// c style access to internal data members - virtual void getInfo(char *clazz, char *dtype, short *length = NULL, - char *nDims = NULL, int **dims = NULL, - void **ptr = NULL) { - *clazz = this->clazz; - *dtype = this->dtype; - if (length) - *length = 0; - if (nDims) - *nDims = 0; - if (dims) - *dims = 0; - if (ptr) - *ptr = 0; - } - - /// \return true if this and data match, false otherwise and as default - virtual bool equals(Data *data __attribute__((unused))) { return false; } - - /// \return Return the result of TDI evaluate - Data *evaluate(); - Data *evaluate(Tree *tree); - - /// eports TDI data functionality, i.e. returns a native type - /// (scalar or array). - virtual Data *data(); - virtual Data *data(Tree *tree); - - /// Return the result of TDI decompile - char *decompile(); - - /// Make a dymanically allocated copy of the Data instance Tree - Data *clone(); - - /// serialize data into non terminated char array using serializeData - /// function, if serializeData fails MdsException is trown. - /// - /// \see serializeData(void *dsc, int *retSize, void **retDsc) - /// \param size set to serialized data length - /// \return c string representing serialized data - char *serialize(int *size); - - ///@{ \ingroup NativeTypes - /// - /// Access data as native type using getData() conversion function. This - /// function might be overloaded by derived data classes to improve - /// conversion. - /// - virtual char getByte(); - virtual short getShort(); - virtual int getInt(); - virtual int64_t getLong(); - virtual unsigned char getByteUnsigned(); - virtual unsigned short getShortUnsigned(); - virtual unsigned int getIntUnsigned(); - virtual uint64_t getLongUnsigned(); - virtual float getFloat(); - virtual double getDouble(); - virtual std::complex getComplex() { - throw MdsException("getComplex() not supported for non Complex data types"); - } - virtual char *getString() { return decompile(); } - virtual int *getShape(int *numDim); - virtual char *getByteArray(int *numElements); - virtual std::vector getByteArray(); - virtual short *getShortArray(int *numElements); - virtual std::vector getShortArray(); - virtual int *getIntArray(int *numElements); - virtual std::vector getIntArray(); - virtual int64_t *getLongArray(int *numElements); - virtual std::vector getLongArray(); - virtual float *getFloatArray(int *numElements); - virtual std::vector getFloatArray(); - virtual unsigned char *getByteUnsignedArray(int *numElements); - virtual std::vector getByteUnsignedArray(); - virtual unsigned short *getShortUnsignedArray(int *numElements); - virtual std::vector getShortUnsignedArray(); - virtual unsigned int *getIntUnsignedArray(int *numElements); - virtual std::vector getIntUnsignedArray(); - virtual uint64_t *getLongUnsignedArray(int *numElements); - virtual std::vector getLongUnsignedArray(); - virtual double *getDoubleArray(int *numElements); - virtual std::vector getDoubleArray(); - virtual std::complex *getComplexArray(int *numElements - __attribute__((unused))) { - throw MdsException( - "getComplexArray() not supported for non Complex data types"); - } - virtual std::vector > getComplexArray(); - virtual char **getStringArray(int *numElements) { - *numElements = 0; - return NULL; - } - ///@} - - virtual Data *getDimensionAt(int dimIdx); - - virtual int getSize() { return 1; } - - /// Instantiate a Scope object and plot data into. - virtual void plot(); - - friend EXPORT std::ostream &operator<<(std::ostream &outStream, - MDSplus::Data *data); - -protected: - /// readonly access - virtual bool isImmutable() { return true; } - - /// Set accessory data (utits, error, help and validation) - void setAccessory(Data *units, Data *error, Data *help, Data *validation) { - setUnits(units); - setError(error); - setHelp(help); - setValidation(validation); - } - -private: - /// Execute data conversion selecting proper descriptor conversion function. - /// If conversion fails a MdsException is thrown. - /// \param classType target class type - /// \param dataType target data type - Data *getData(int classType, int dataType); - - /// convert data to array type (CLASS_A) \see getData() - Data *getArrayData(int dataType); - - /// convert data to scalar type (CLASS_S) \see getData() - Data *getScalarData(int dataType); - - /// - /// @{ - /// Accessory information added on this data - friend void deleteData(Data *data); - Data *units; - Data *error; - Data *help; - Data *validation; - //// @} -}; - -//////////////////////////////////////////////////////////////////////////////// -// SCALAR DATA ///////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getDimension() { return getDescAt(2); } -/// -/// \brief The Scalar class -/// -/// Scalar is the common base class for all scalar data types -/// (descriptor class CLASS_S). -class EXPORT Scalar : public Data { - friend class Array; - -protected: - int length; - char *ptr; - -public: - Scalar() : length(0), ptr(0) { clazz = CLASS_S; } - - virtual ~Scalar() { delete[] ptr; } - - /// convert data to scalar descriptor - virtual void *convertToDsc(); - - virtual void getInfo(char *clazz, char *dtype, short *length = NULL, - char *nDims = NULL, int **dims = NULL, - void **ptr = NULL) { - *clazz = this->clazz; - *dtype = this->dtype; - if (length) - *length = this->length; - if (nDims) - *nDims = 0; - if (dims) - *dims = 0; - if (ptr) - *ptr = this->ptr; - } - -}; // ScalarData - -//////////////////////////////////////////////////////////////////////////////// -// INT8 SCALAR ///////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getDimensionAt(int idx) { return getDescAt(idx + 2); } -/// -/// \brief The Int8 class object description of DTYPE_B -/// -class EXPORT Int8 : public Scalar { -public: - Int8(char val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_B; - length = 1; - ptr = new char[1]; - ptr[0] = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(ptr[0]); } - short getShort() { return numeric_cast(ptr[0]); } - int getInt() { return numeric_cast(ptr[0]); } - int64_t getLong() { return numeric_cast(ptr[0]); } - unsigned char getByteUnsigned() { - return numeric_cast(ptr[0]); - } - unsigned short getShortUnsigned() { - return numeric_cast(ptr[0]); - } - unsigned int getIntUnsigned() { return numeric_cast(ptr[0]); } - uint64_t getLongUnsigned() { return numeric_cast(ptr[0]); } - float getFloat() { return numeric_cast(ptr[0]); } - double getDouble() { return numeric_cast(ptr[0]); } - - ///@} -}; + int getNumDimensions() { return descs.size() - 2; } -/// -/// \brief The Uint8 class object description of DTYPE_BU -/// -class EXPORT Uint8 : public Scalar { -public: - Uint8(unsigned char val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_BU; - length = 1; - ptr = new char[1]; - ptr[0] = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(unsigned char *)ptr); } - short getShort() { return numeric_cast(*(unsigned char *)ptr); } - int getInt() { return numeric_cast(*(unsigned char *)ptr); } - int64_t getLong() { return numeric_cast(*(unsigned char *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(unsigned char *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(unsigned char *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(unsigned char *)ptr); - } - uint64_t getLongUnsigned() { - return numeric_cast(*(unsigned char *)ptr); - } - float getFloat() { return numeric_cast(*(unsigned char *)ptr); } - double getDouble() { return numeric_cast(*(unsigned char *)ptr); } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT16 SCALAR //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setData(Data *data) { assignDescAt(data, 0); } + void setRaw(Data *raw) { assignDescAt(raw, 1); } + void setDimension(Data *dimension) { assignDescAt(dimension, 2); } + void setDimensionAt(Data *dimension, int idx) + { + assignDescAt(dimension, 2 + idx); + } -/// -/// \brief The Int16 class object description of DTYPE_W -/// -class EXPORT Int16 : public Scalar { -public: - Int16(short val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_W; - length = 2; - ptr = new char[2]; - *(short *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(short *)ptr); } - short getShort() { return numeric_cast(*(short *)ptr); } - int getInt() { return numeric_cast(*(short *)ptr); } - int64_t getLong() { return numeric_cast(*(short *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(short *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(short *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(short *)ptr); - } - uint64_t getLongUnsigned() { return numeric_cast(*(short *)ptr); } - float getFloat() { return numeric_cast(*(short *)ptr); } - double getDouble() { return numeric_cast(*(short *)ptr); } - - ///@} -}; + private: + void init(Data *units, Data *error, Data *help, Data *validation) + { + dtype = DTYPE_SIGNAL; + incrementRefCounts(); + setAccessory(units, error, help, validation); + } + }; -/// -/// \brief The Uint16 class object description of DTYPE_WU -/// -class EXPORT Uint16 : public Scalar { -public: - Uint16(unsigned short val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_WU; - length = 2; - ptr = new char[2]; - *(unsigned short *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(unsigned short *)ptr); } - short getShort() { return numeric_cast(*(unsigned short *)ptr); } - int getInt() { return numeric_cast(*(unsigned short *)ptr); } - int64_t getLong() { return numeric_cast(*(unsigned short *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(unsigned short *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(unsigned short *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(unsigned short *)ptr); - } - uint64_t getLongUnsigned() { - return numeric_cast(*(unsigned short *)ptr); - } - float getFloat() { return numeric_cast(*(unsigned short *)ptr); } - double getDouble() { return numeric_cast(*(unsigned short *)ptr); } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT32 SCALAR //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // DIMENSION COMPOUND //////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + /// + /// \brief The Dimension class object description of DTYPE_DIMENSION + /// + /// MDSplus provides a dimension data type which provides a compact mechanism + /// for expressing signal dimensions (See: DTYPE_SIGNAL). The dimension data + /// type was implemented as a way to represent data such as the timebase for + /// signals recorded by data acquisition equipment such as transient recorders. + /// + /// A dimension data type is a structure which has two parts, a window and an + /// axis. The axis part is a representation of a series of values (i.e. time + /// stamps) and is generally represented by a DTYPE_RANGE data item. If this + /// was a single speed clock, for example, the axis would be represented by a + /// range consisting or an optional start time, an optional end time and a + /// single delta time value. This range could represent a series of clock + /// pulses which began some time infinitely in the past and continuing to some + /// time infinitely in the future. The window portion of the dimention is used + /// to select a set of these infinite stream of clock pulses that represent + /// those clock pulses which match the samples that were recorded in the + /// digitizers internal memory. The window portion is usually represented by a + /// DTYPE_WINDOW data item. A window consists of a start index, and end index + /// and a value at index 0. For a transient digitizer, the samples in the + /// memory were recorded at a known number of clock pulses before the trigger + /// (the start index) and continuing a known number of clock pulses after the + /// trigger. The time the module was triggered is the value at index 0 part of + /// the window. + /// + /// > + /// > See \ref dt_dimension for further details. + /// > + /// -/// -/// \brief The Int32 class object description of DTYPE_L -/// -class EXPORT Int32 : public Scalar { -public: - Int32(int val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_L; - length = sizeof(int); - ptr = new char[sizeof(int)]; - *(int *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(int *)ptr); } - short getShort() { return numeric_cast(*(int *)ptr); } - int getInt() { return numeric_cast(*(int *)ptr); } - int64_t getLong() { return numeric_cast(*(int *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(int *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(int *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(int *)ptr); - } - uint64_t getLongUnsigned() { return numeric_cast(*(int *)ptr); } - float getFloat() { return numeric_cast(*(int *)ptr); } - double getDouble() { return numeric_cast(*(int *)ptr); } - - ///@} -}; + class Dimension : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Dimension(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } +#endif // DOXYGEN end of hidden code -/// -/// \brief The Uint32 class object description of DTYPE_LU -/// -class EXPORT Uint32 : public Scalar { -public: - Uint32(unsigned int val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_LU; - length = sizeof(int); - ptr = new char[sizeof(int)]; - *(unsigned int *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(unsigned int *)ptr); } - short getShort() { return numeric_cast(*(unsigned int *)ptr); } - int getInt() { return numeric_cast(*(unsigned int *)ptr); } - int64_t getLong() { return numeric_cast(*(unsigned int *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(unsigned int *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(unsigned int *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(unsigned int *)ptr); - } - uint64_t getLongUnsigned() { - return numeric_cast(*(unsigned int *)ptr); - } - float getFloat() { return numeric_cast(*(unsigned int *)ptr); } - double getDouble() { return numeric_cast(*(unsigned int *)ptr); } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT64 SCALAR //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Dimension(Data *window, Data *axis, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_DIMENSION; + descs.push_back(window); + descs.push_back(axis); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -/// -/// \brief The Int64 class object description of DTYPE_Q -/// -class EXPORT Int64 : public Scalar { -public: - Int64(int64_t val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_Q; - length = sizeof(int64_t); - ptr = new char[sizeof(int64_t)]; - *(int64_t *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(int64_t *)ptr); } - short getShort() { return numeric_cast(*(int64_t *)ptr); } - int getInt() { return numeric_cast(*(int64_t *)ptr); } - int64_t getLong() { return numeric_cast(*(int64_t *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(int64_t *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(int64_t *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(int64_t *)ptr); - } - uint64_t getLongUnsigned() { return numeric_cast(*(int64_t *)ptr); } - float getFloat() { return numeric_cast(*(int64_t *)ptr); } - double getDouble() { return numeric_cast(*(int64_t *)ptr); } - - ///@} -}; + /// Get the dimension window + Data *getWindow() { return getDescAt(0); } -/// -/// \brief The Uint64 class object description of DTYPE_QU -/// -class EXPORT Uint64 : public Scalar { -public: - Uint64(uint64_t val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_QU; - length = sizeof(int64_t); - ptr = new char[sizeof(int64_t)]; - *(uint64_t *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - unsigned char getByteUnsigned() { - return numeric_cast(*(uint64_t *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(uint64_t *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(uint64_t *)ptr); - } - uint64_t getLongUnsigned() { - return numeric_cast(*(uint64_t *)ptr); - } - char getByte() { return numeric_cast(*(uint64_t *)ptr); } - short getShort() { return numeric_cast(*(uint64_t *)ptr); } - int getInt() { return numeric_cast(*(uint64_t *)ptr); } - int64_t getLong() { return numeric_cast(*(uint64_t *)ptr); } - float getFloat() { return numeric_cast(*(uint64_t *)ptr); } - double getDouble() { return numeric_cast(*(uint64_t *)ptr); } - char *getDate(); - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// FLOAT32 SCALAR ////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Get the dimension axis + Data *getAxis() { return getDescAt(1); } -/// -/// \brief The Float32 class object description of DTYPE_FLOAT -/// -class EXPORT Float32 : public Scalar { -public: - Float32(float val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_FLOAT; - length = sizeof(float); - ptr = new char[sizeof(float)]; - *(float *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(float *)ptr); } - short getShort() { return numeric_cast(*(float *)ptr); } - int getInt() { return numeric_cast(*(float *)ptr); } - int64_t getLong() { return numeric_cast(*(float *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(float *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(float *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(float *)ptr); - } - uint64_t getLongUnsigned() { return numeric_cast(*(float *)ptr); } - float getFloat() { return numeric_cast(*(float *)ptr); } - double getDouble() { return numeric_cast(*(float *)ptr); } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// FLOAT64 SCALAR ////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Set the dimension window + void setWindow(Data *window) { assignDescAt(window, 0); } -/// -/// \brief The Float64 class object description of DTYPE_DOUBLE -/// -class EXPORT Float64 : public Scalar { -public: - Float64(double val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_DOUBLE; - length = sizeof(double); - ptr = new char[sizeof(double)]; - *(double *)ptr = val; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - char getByte() { return numeric_cast(*(double *)ptr); } - short getShort() { return numeric_cast(*(double *)ptr); } - int getInt() { return numeric_cast(*(double *)ptr); } - int64_t getLong() { return numeric_cast(*(double *)ptr); } - unsigned char getByteUnsigned() { - return numeric_cast(*(double *)ptr); - } - unsigned short getShortUnsigned() { - return numeric_cast(*(double *)ptr); - } - unsigned int getIntUnsigned() { - return numeric_cast(*(double *)ptr); - } - uint64_t getLongUnsigned() { return numeric_cast(*(double *)ptr); } - float getFloat() { return numeric_cast(*(double *)ptr); } - double getDouble() { return numeric_cast(*(double *)ptr); } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// COMPLEX32 SCALAR //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Set the dimension axis + void setAxis(Data *axis) { assignDescAt(axis, 1); } + }; -/// -/// \brief The Complex32 class object description of DTYPE_FSC -/// -class EXPORT Complex32 : public Scalar { -public: - Complex32(float re, float im, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - dtype = DTYPE_FSC; - length = 2 * sizeof(float); - ptr = new char[2 * sizeof(float)]; - ((float *)ptr)[0] = re; - ((float *)ptr)[1] = im; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - float getReal() { return ((float *)ptr)[0]; } - float getImaginary() { return ((float *)ptr)[1]; } - std::complex getComplex() { - return std::complex(((float *)ptr)[0], ((float *)ptr)[1]); - } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// COMPLEX64 SCALAR //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // WINDOW COMPOUND /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Complex64 class object description of DTYPE_FTC -/// -class EXPORT Complex64 : public Scalar { -public: - Complex64(double re, double im, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - dtype = DTYPE_FTC; - length = 2 * sizeof(double); - ptr = new char[2 * sizeof(double)]; - ((double *)ptr)[0] = re; - ((double *)ptr)[1] = im; - setAccessory(units, error, help, validation); - } - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - double getReal() { return ((double *)ptr)[0]; } - double getImaginary() { return ((double *)ptr)[1]; } - std::complex getComplex() { - return std::complex(((double *)ptr)[0], ((double *)ptr)[1]); - } - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// STRING SCALAR /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// + /// \brief The Window class object description of DTYPE_WINDOW + /// + /// MDSplus provides a window data type which is used exclusively in + /// conjunction with a dimension data item (\ref Dimension). The window + /// provides a means for bracketing a potentially infinite vector of values + /// generated by a range data item (\ref Range). A window data type is a + /// structure containing three fields: the start index, the end index and the + /// value at index 0. The window brackets the axis portion of a dimension item + /// by finding the nearest element in the axis to the "value at index 0" value. + /// The subset of the axis elements are selected using the start index and end + /// index using this starting element as the index 0. For example if the window + /// was BUILD_WINDOW(-5,10,42.), MDSplus would find the element in the axis + /// portion of the dimension closest to a value of 42 (assuming the axis is + /// always increasing) and call that element, element number 0. The subset + /// would be this element and the 5 elements before it and the 10 elements + /// after it. For a more detailed explanation see the description of the + /// dimension data type. + /// + /// > + /// > See \ref dt_window for further details. + /// > + /// -/// -/// \brief The String class object description of DTYPE_T -/// -class EXPORT String : public Scalar { -public: - String(const char *val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - init(val, std::string(val).size(), units, error, help, validation); - } - - String(unsigned char *uval, int len __attribute__((unused)), Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - // FIXME: Hack to handle broken LabView types that use unsigned char (as - // uint8) instead of char - // FIXME: Warning: Do not use this constructor in user code - char *val = reinterpret_cast(uval); - init(val, std::string(val).size(), units, error, help, validation); - } - - // GAB definition in order to avoid breaking LabVIEW - String(unsigned char *uval, int numDims __attribute__((unused)), - int *dims __attribute__((unused)), Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - char *val = reinterpret_cast(uval); - init(val, std::string(val).size(), units, error, help, validation); - } - - String(const char *val, int len, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - init(val, len, units, error, help, validation); - } - - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - char *getString() { - char *res = new char[length + 1]; - std::copy(&ptr[0], &ptr[length + 1], res); - res[length] = 0; - return res; - } - - /// get a string array of a single element - char **getStringArray(int *numElements) { - char **res = new char *[1]; - res[0] = new char[length + 1]; - std::copy(&ptr[0], &ptr[length + 1], res[0]); - res[0][length] = 0; - *numElements = 1; - return res; - } - - /// check if two strings have the same content. - bool equals(Data *data); - -private: - virtual void init(char const *val, int len, Data *units, Data *error, - Data *help, Data *validation) { - dtype = DTYPE_T; - length = len; - ptr = new char[length + 1]; - std::copy(&val[0], &val[length], ptr); - ptr[length] = 0; - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// IDENT SCALAR /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + class Window : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Window(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } +#endif // DOXYGEN end of hidden code -/// -/// \brief The Ident class is the object description of DTYPE_IDENT and is used -/// to describe TDI variables -/// -class EXPORT Ident : public String { -public: - Ident(const char *val, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : String(val, units, error, help, validation) { - dtype = DTYPE_IDENT; - } - - Ident(unsigned char *uval, int len, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) - : String(uval, len, units, error, help, validation) { - dtype = DTYPE_IDENT; - } - - // GAB definition in order to avoid breaking LabVIEW - Ident(unsigned char *uval, int numDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) - : String(uval, numDims, dims, units, error, help, validation) { - dtype = DTYPE_IDENT; - } - - Ident(const char *val, int len, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) - : String(val, len, units, error, help, validation) { - dtype = DTYPE_IDENT; - } -}; + Window(Data *startidx, Data *endidx, Data *value_at_idx0, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_WINDOW; + descs.push_back(startidx); + descs.push_back(endidx); + descs.push_back(value_at_idx0); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -//////////////////////////////////////////////////////////////////////////////// -// ARRAY DATA ////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getStartIdx() { return getDescAt(0); } -/// -/// \brief The Array class object description of DTYPE_A -/// -/// Common base class for arrays (CLASS_A). It contains dimension informationThe -/// contained data is assumed to be row-first ordered. -/// Array - derived classes will hold actual data in language-specific -/// structures. This allows for a direct implementation of operations such as -/// getElementAt() and setElementAt() which would be difficult or impossible to -/// implement via TDI. -/// -/// For the remaining Data methods, the generic mechanism of the base class' -/// implementation (conversion to MDSplus descriptor, TDI operation conversion -/// back to class instances) is retained. - -class EXPORT Array : public Data { -protected: - int length; ///< individual size of stored data element - int arsize; ///< total array data storage size - int nDims; ///< number of dimensions of the array access tuple - int dims[MAX_DIMS]; ///< store each dimension size - char *ptr; - - void setSpecific(void const *data, int length, int dtype, int nData) { - setSpecific(data, length, dtype, 1, &nData); - } - - void setSpecific(void const *data, int length, int dtype, int nDims, - int *dims) { - this->dtype = dtype; - this->nDims = nDims; - this->length = length; - arsize = length; - for (int i = 0; i < nDims; i++) { - arsize *= dims[i]; - this->dims[i] = dims[i]; - } - - char const *dataBytes = reinterpret_cast(data); - ptr = new char[arsize]; - std::copy(&dataBytes[0], &dataBytes[arsize], ptr); - } - -public: - Array() : length(0), arsize(0), nDims(0), ptr(0) { clazz = CLASS_A; } - - ~Array() { - // deleteNativeArray(ptr); - delete[] ptr; - } - - /// returns total array storage size as product of dimensions - virtual int getSize() { - int retSize = 1; - for (int i = 0; i < nDims; i++) - retSize *= dims[i]; - return retSize; - } - - virtual void getInfo(char *clazz, char *dtype, short *length = NULL, - char *nDims = NULL, int **dims = NULL, - void **ptr = NULL) { - *clazz = this->clazz; - *dtype = this->dtype; - if (length) - *length = this->length; - if (nDims) - *nDims = this->nDims; - if (dims) { - *dims = new int[this->nDims]; - for (int i = 0; i < this->nDims; i++) - (*dims)[i] = this->dims[i]; - } - if (ptr) - *ptr = this->ptr; - } - - /// Provides a method to get the array shape, i.e. the array of dimension - /// sizes and the total number of dimensions. - virtual int *getShape(int *numDims); - - /// Retrieve a single element from the array matrix at the getDims position, - /// if the passed number of dimension is equals to the dimension of dims - /// field. Otherwise it returns the reshaped array corresponding to the - /// passed dimension array. For example, if the array is bi-dimensional, a - /// single dimension i will specify the i-th row. - /// - /// If the position exceeds the array dimension boundaries an exception is - /// thrown - /// - /// \param getDims array of integers identifying the position tuple of the - /// array \param getNumDims the size of the position tuple - Data *getElementAt(int *getDims, int getNumDims); - - // TODO: [andrea] finire ... - /// - /// If the position exceeds the array dimension boundaries an exception is - /// thrown - /// - /// \param getDims array of integers identifying the position tuple of the - /// array \param getNumDims the size of the position tuple \param data the - /// data object to set - void setElementAt(int *getDims, int getNumDims, Data *data); - - /// Retrieve an element considering the array as one dimension shaped. - Data *getElementAt(int dim) { return getElementAt(&dim, 1); } - - /// Set an element considering the array as one dimension shaped. - void setElementAt(int dim, Data *data) { setElementAt(&dim, 1, data); } - - Array *getSubArray(int startDim, int nSamples); - - /// Convert data to array descriptor - void *convertToDsc(); - - ///@{ - /// inline overloaded conversion access returning result of cast operator of - /// the Scalar object data member - - void *getArray() { return ptr; } - char *getByteArray(int *numElements); - short *getShortArray(int *numElements); - int *getIntArray(int *numElements); - int64_t *getLongArray(int *numElements); - unsigned char *getByteUnsignedArray(int *numElements); - unsigned short *getShortUnsignedArray(int *numElements); - unsigned int *getIntUnsignedArray(int *numElements); - uint64_t *getLongUnsignedArray(int *numElements); - float *getFloatArray(int *numElements); - double *getDoubleArray(int *numElements); - std::complex *getComplexArray(int *numElements); - virtual char **getStringArray(int *numElements); - - ///@} -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT8 ARRAY DATA ///////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getEndIdx() { return getDescAt(1); } -/// -/// \brief The Int8Array class, array of objects of descriptor type DTYPE_B -/// -class Int8Array : public Array { -public: - Int8Array(char const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, 1, DTYPE_B, nData); - setAccessory(units, error, help, validation); - } - Int8Array(char const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 1, DTYPE_B, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + Data *getValueAt0() { return getDescAt(2); } -/// -/// \brief The Uint8Array class, array of objects of descriptor type DTYPE_BU -/// -class EXPORT Uint8Array : public Array { - friend Data *deserialize(Data *serializedData); - -public: - Uint8Array(unsigned char const *data, int nData, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 1, DTYPE_BU, nData); - setAccessory(units, error, help, validation); - } - Uint8Array(unsigned char const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 1, DTYPE_BU, nDims, dims); - setAccessory(units, error, help, validation); - } - Data *deserialize(); -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT16 ARRAY DATA //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setStartIdx(Data *startidx) { assignDescAt(startidx, 0); } + void setEndIdx(Data *endidx) { assignDescAt(endidx, 1); } + void setValueAt0(Data *value_at_idx0) { assignDescAt(value_at_idx0, 2); } + }; -/// -/// \brief The Int16Array class, array of objects of descriptor type DTYPE_W -/// -class Int16Array : public Array { -public: - Int16Array(short const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, 2, DTYPE_W, nData); - setAccessory(units, error, help, validation); - } - Int16Array(short const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 2, DTYPE_W, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + //////////////////////////////////////////////////////////////////////////////// + // FUNCTION COMPOUND ///////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Uint16Array class, array of objects of descriptor type DTYPE_WU -/// -class Uint16Array : public Array { -public: - Uint16Array(unsigned short const *data, int nData, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 2, DTYPE_WU, nData); - setAccessory(units, error, help, validation); - } - Uint16Array(unsigned short const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 2, DTYPE_WU, nDims, dims); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT32 ARRAY DATA //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// + /// \brief The Function class object description of DTYPE_FUNCTION + /// + /// MDSplus provides a function data type used for describing references to + /// built in native TDI functions. When you specify an expression such as "a+b", + /// MDSplus will compile this into a DTYPE_FUNCTION data item. The function + /// data type consists of a opcode and a list of operands. The opcode is stored + /// as a 16 bit code and the operands can be any MDSplus data type. + /// + /// > + /// > See \ref dt_function for further details. + /// > + /// -/// -/// \brief The Int32Array class, array of objects of descriptor type DTYPE_L -/// -class Int32Array : public Array { -public: - Int32Array(int const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(int), DTYPE_L, nData); - setAccessory(units, error, help, validation); - } - Int32Array(int const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(int), DTYPE_L, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + class Function : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Function(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } +#endif // DOXYGEN end of hidden code -/// -/// \brief The Uint32Array, array of objects of descriptor type DTYPE_LU -/// -class Uint32Array : public Array { -public: - Uint32Array(unsigned int const *data, int nData, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(int), DTYPE_LU, nData); - setAccessory(units, error, help, validation); - } - Uint32Array(unsigned int const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(int), DTYPE_LU, nDims, dims); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// INT64 ARRAY DATA //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Function(short opcode, int nargs, Data **args, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_FUNCTION; + this->opcode = opcode; + for (int i = 0; i < nargs; i++) + descs.push_back(args[i]); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -/// -/// \brief The Int64Array class, array of objects of descriptor type DTYPE_Q -/// -class Int64Array : public Array { -public: - Int64Array(int64_t const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, 8, DTYPE_Q, nData); - setAccessory(units, error, help, validation); - } - Int64Array(int64_t const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 8, DTYPE_Q, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + /// Get operation code from compiled TDI expression + short getOpcode() { return opcode; } -/// -/// \brief The Uint64Array class object, array of objects of descriptor type -/// DTYPE_QU -/// -class Uint64Array : public Array { -public: - Uint64Array(uint64_t const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, 8, DTYPE_QU, nData); - setAccessory(units, error, help, validation); - } - Uint64Array(uint64_t const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, 8, DTYPE_QU, nDims, dims); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// FLOAT32 ARRAY DATA ////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Get number of arguments for this expression. + int getNumArguments() { return descs.size(); } -/// -/// \brief The Float32Array class object, array of objects of descriptor type -/// DTYPE_FLOAT -/// -class Float32Array : public Array { -public: - Float32Array(float const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(float), DTYPE_FLOAT, nData); - setAccessory(units, error, help, validation); - } - Float32Array(float const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(float), DTYPE_FLOAT, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + /// Get data argument at position idx + Data *getArgumentAt(int idx) { return getDescAt(idx); } -/// -/// \brief The Float64Array class object, array of objects of descriptor type -/// DTYPE_DOUBLE -/// -class Float64Array : public Array { -public: - Float64Array(double const *data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(double), DTYPE_DOUBLE, nData); - setAccessory(units, error, help, validation); - } - Float64Array(double const *data, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(data, sizeof(double), DTYPE_DOUBLE, nDims, dims); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// COMPLEX32 ARRAY DATA //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Set idx data argument + void setArgAt(Data *arg, int idx) { assignDescAt(arg, idx); } + }; -/// -/// \brief The Complex32Array class, array of objects of descriptor type -/// DTYPE_FSC -/// -class Complex32Array : public Array { -public: - Complex32Array(float const *reIm, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - setSpecific(reIm, 2 * sizeof(float), DTYPE_FSC, nData); - setAccessory(units, error, help, validation); - } - Complex32Array(float const *reIm, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(reIm, 2 * sizeof(float), DTYPE_FSC, nDims, dims); - setAccessory(units, error, help, validation); - } -}; + //////////////////////////////////////////////////////////////////////////////// + // CONGLOM COMPOUND ////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Complex64Array class, array of objects of descriptor type -/// DTYPE_FTC -/// -class Complex64Array : public Array { -public: - Complex64Array(double const *reIm, int nData, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(reIm, 2 * sizeof(double), DTYPE_FTC, nData); - setAccessory(units, error, help, validation); - } - Complex64Array(double const *reIm, int nDims, int *dims, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - setSpecific(reIm, 2 * sizeof(double), DTYPE_FTC, nDims, dims); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// STRING ARRAY DATA /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// + /// \brief The Conglom class object description of DTYPE_CONGLOM + /// + /// MDSplus provides a conglomerate data type used for describing data + /// acquisition or analysis devices. A device in MDSplus is implemented as a + /// collection of adjacent tree nodes (or a conglomerate). The first node + /// (located at the top of the node structure of this collection) contains a + /// conglomerate data type. The conglomerate data type is a structure + /// containing an image part, a model part, a name part and a qualifiers part. + /// MDSplus implements device support by providing a mechanism for performing + /// "methods" on devices. When a device method is performed on a device in a + /// MDSplus tree either through an action or using the TCL command DO/METHOD, + /// MDSplus invokes a procedure determined by the information in the head node + /// of the device which contains a conglomerate data type. If there is an image + /// part of the conglomerate structure, MDSplus will attempt to call a routine + /// called "model-part"__"method" in the shared library specified by the image + /// part. If the routine can not be found, MDSplus will try to invoke the TDI + /// function called "model-part"__"method". Normally, the conglomerate data is + /// loaded into the head node of a device automatically when you add it to the + /// tree so you may not need to access this data type directly. + /// + /// The name part of the device is often a reference to a sub node of the + /// device which contains the data acquisition module identification such as + /// the CAMAC module name. This portion of the device is not used during method + /// invokation and was simply added as a convenience in building tools for + /// gathering information about device definitions in a tree. The qualifiers + /// part of the structure could be used by device support for making variant + /// device implementations. This field along with the name field are generally + /// not used any longer. + /// + /// > + /// > See \ref dt_conglom for further details. + /// > + /// -/// -/// \brief The StringArray class, array of objects of descriptor type DTYPE_T -/// -class StringArray : public Array { -public: - /// StringArray constructor from array of c strings - StringArray(char **data, int nData, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - // Pad all string to longest - int maxLen = 0; - for (int i = 0; i < nData; i++) - maxLen = std::max(std::string(data[i]).size(), (std::size_t)maxLen); - - char *padData = new char[nData * maxLen]; - for (int i = 0; i < nData; i++) { - std::size_t currLen = std::string(data[i]).size(); - std::copy(&data[i][0], &data[i][currLen], &padData[i * maxLen]); - std::fill(&padData[i * maxLen + currLen], &padData[i * maxLen + maxLen], - ' '); - } - setSpecific(padData, maxLen, DTYPE_T, nData); - setAccessory(units, error, help, validation); - delete[] padData; - } - - /// StringArray constructor from single c string - StringArray(char const *data, int nStrings, int stringLen, Data *units = 0, - Data *error = 0, Data *help = 0, - Data *validation = 0) // For contiuguous + class Conglom : public Compound { - setSpecific(data, stringLen, DTYPE_T, nStrings); - setAccessory(units, error, help, validation); - } -}; + public: +#ifndef DOXYGEN // hide this part from documentation + Conglom(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } +#endif // DOXYGEN end of hidden code -//////////////////////////////////////////////////////////////////////////////// -// COMPOUND DATA //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Conglom(Data *image, Data *model, Data *name, Data *qualifiers, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_CONGLOM; + descs.push_back(image); + descs.push_back(model); + descs.push_back(name); + descs.push_back(qualifiers); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -/// -/// \brief The Compound class object description of DTYPE_R -/// -/// Compound is the common base class for all CLASS_R types. Its fields contain -/// all the required information (Descriptor array, keyword). Its getter/setter -/// methods allow to read/replace descriptors, based on their index. Derived -/// classes will only define methods with appropriate names for reading/writing -/// descriptors (i.e. Data objects). + Data *getImage() { return getDescAt(0); } -class EXPORT Compound : public Data { -public: - Compound() : opcode(0) { setClass(); } + Data *getModel() { return getDescAt(1); } - Compound(int dtype, int length, void *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - setClass(); - setAccessory(units, error, help, validation); - this->dtype = dtype; - - switch (length) { - case 1: - opcode = *(static_cast(ptr)); - break; - case 2: - opcode = *(static_cast(ptr)); - break; - case 4: - opcode = *(static_cast(ptr)); - break; - default: - opcode = 0; - } - - for (int i = 0; i < nDescs; ++i) { - this->descs.push_back((Data *)descs[i]); - if (this->descs[i]) - this->descs[i]->incRefCount(); - } - } - - virtual void propagateDeletion() { - for (std::size_t i = 0; i < descs.size(); ++i) - if (descs[i]) { - descs[i]->decRefCount(); - deleteData(descs[i]); - } - } + Data *getName() { return getDescAt(2); } - void *convertToDsc(); + Data *getQualifiers() { return getDescAt(3); } - virtual ~Compound() { propagateDeletion(); } + void setImage(Data *image) { assignDescAt(image, 0); } + void setModel(Data *model) { assignDescAt(model, 1); } + void setName(Data *name) { assignDescAt(name, 2); } + void setQualifiers(Data *qualifiers) { assignDescAt(qualifiers, 3); } + }; -protected: - short opcode; ///< used only by some derived classes. - std::vector descs; ///< descriptors storage member + //////////////////////////////////////////////////////////////////////////////// + // RANGE COMPOUND //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// - /// increment reference of each stored data - void incrementRefCounts() { - for (std::size_t i = 0; i < descs.size(); ++i) - if (descs[i]) - descs[i]->refCount++; - } + /// + /// \brief The Range class, object description of DTYPE_RANGE + /// + /// MDSplus provides a range data type which provides a compact mechanism for + /// expressing series of values with fixed intervals. The range data type is a + /// structure consisting of three parts; begin, end, and delta. This data type + /// is used often in MDSplus for representing data such as the output of clock + /// devices used in data acquisition. The following example shows three simple + /// instances of ranges: + /// + /// \code{.cpp} + /// // _tdi_range1 = 1 : 10 + /// Data *range1 = new Range(new Int32(1),new Int32(10),NULL); + /// + /// // _tdi_range2 = 1 : 10 : .5 + /// Data *range2 = new Range(new Float32(1),new Float32(10),new + /// Float32(0.5)); + /// + /// // _range = * : * : 1E-6 + /// Data *range3 = new Range(NULL,NULL,new Float32(1E-6)); + /// \endcode + /// + /// In the above examples, we show two formats for creating ranges. The MDSplus + /// TDI expression evaluator has a built in syntax for specifying ranges which + /// is one of the following: + /// + /// \code{.cpp} + /// begin : end [: delta] + /// _range = build_range(begin,end,delta) + /// \endcode + /// + /// > + /// > See \ref dt_range for further details. + /// > + /// -public: - /// set Data at idx element of contained descriptors - void assignDescAt(Data *data, int idx) { - if (idx < 0 || idx >= (int)descs.size()) { - if (data) - deleteData(data); - throw(MdsException("Index out of bounds accessing arguments")); + class Range : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Range(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); } +#endif // DOXYGEN end of hidden code - if (descs.at(idx)) { - descs.at(idx)->decRefCount(); - deleteData(descs[idx]); + Range(Data *begin, Data *ending, Data *deltaval, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_RANGE; + descs.push_back(begin); + descs.push_back(ending); + descs.push_back(deltaval); + incrementRefCounts(); + setAccessory(units, error, help, validation); } - descs.at(idx) = data; - if (data) - data->refCount++; - } + /// Get range begin + Data *getBegin() { return getDescAt(0); } - /// retrieve Data at the idx position of contained descriptors - Data *getDescAt(int idx) { - if (idx < 0 || idx >= (int)descs.size()) { - throw(MdsException("Index out of bounds accessing arguments")); - } + /// Get range end + Data *getEnding() { return getDescAt(1); } - if (descs.at(idx)) - descs[idx]->incRefCount(); - return descs[idx]; - } - int getNumDescs() { return descs.size(); } + /// Get Range delta + Data *getDeltaVal() { return getDescAt(2); } -private: - void setClass() { clazz = CLASS_R; } -}; + void setBegin(Data *begin) { assignDescAt(begin, 0); } + void setEnding(Data *ending) { assignDescAt(ending, 1); } + void setDeltaVal(Data *deltaval) { assignDescAt(deltaval, 2); } + }; -//////////////////////////////////////////////////////////////////////////////// -// SIGNAL COMPOUND /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // ACTION COMPOUND /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Signal class object description of DTYPE_SIGNAL -/// -/// MDSplus provides a signal data type which combines dimension descriptions -/// with the data. While it was initially designed to be used for efficient -/// storage of data acquired from measurement devices attached to an experiment -/// it has been found to be a very useful way of storing additional information -/// such as results from data analysis or modeling data. A signal is a -/// structure of three or more fields. The first field is the "value" field of -/// the signal. This is followed by an optional raw data field (explained -/// later). These two fields can be followed by one or more dimension -/// descriptions. The number of dimension descriptions in general should match -/// the dimensionality of the value. MDSplus stores data from a transient -/// recorder which is a device which measures voltage as a function of time. -/// Typically a transient recorder uses a analog to digital converter and -/// records the data as a series of integer values. A linear conversion can be -/// done to convert these integer values into input voltages being measured. -/// When MDSplus stores the data for such a device it uses a signal datatype to -/// record the data. The signal structure is constructed by putting an -/// expression for converting the integer data to volts in the "value" portion, -/// the integer data in the raw data portion, and a representation of the -/// timebase in the single dimension portion. -/// -/// \note This class represents a data descriptor of a signal intended as an -/// ordered sequence of data. Nothing in common with software objects -/// signalling systems. + /// + /// \brief The Action class, object description of type DTYPE_ACTION + /// -class EXPORT Signal : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Signal(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - // Signal descriptor requires length = 0, so override the method - void *convertToDsc(); + /// MDSplus provides an action data type used for describing actions to be + /// dispatched to action servers during a normal experiment cycle. An action + /// consists of 5 parts but the current implementations of action dispatching + /// only refernce the first three parts, a dispatch part, a task part and an + /// errorlogs part (OpenVMS only). The dispatch part (See: DTYPE_DISPATCH) + /// includes information such as which server should perform the task, when + /// during the course of the shot cycle it should be executed, what MDSplus + /// event should be issued when the task completes. The task part describes + /// what is to be done when the action is executed. There are a couple + /// different types of task types currently support (See: DTYPE_METHOD and + /// DTYPE_ROUTINE). The errorlogs part is implemented only on OpenVMS. If this + /// part contains a string consisting of a comma delimited list of user + /// accounts, each user on the list will receive a OpenVMS cluster-wide + /// broadcast message if this action fails during execution. The remaining + /// parts were originally defined to hold statistics from the execution of the + /// action but since this would require rewriting the action data (which is + /// usually considered setup information and not writable in the pulse files) + /// this feature was never used. This unused parts are called + /// completion_message and performance. + /// + /// > + /// > See \ref dt_action for further details. + /// > + /// + class Action : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Action(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } #endif // DOXYGEN end of hidden code - Signal(Data *data, Data *raw, Data *dimension, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - descs.push_back(data); - descs.push_back(raw); - descs.push_back(dimension); - init(units, error, help, validation); - } - - Signal(Data *data, Data *raw, Data *dimension1, Data *dimension2, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - descs.push_back(data); - descs.push_back(raw); - descs.push_back(dimension1); - descs.push_back(dimension2); - init(units, error, help, validation); - } - - Signal(Data *data, Data *raw, int nDims, Data **dimensions, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - descs.push_back(data); - descs.push_back(raw); - for (int i = 0; i < nDims; i++) - descs.push_back(dimensions[i]); - init(units, error, help, validation); - } - - Data *getData() { return getDescAt(0); } - - Data *getRaw() { return getDescAt(1); } - - Data *getDimension() { return getDescAt(2); } - - Data *getDimensionAt(int idx) { return getDescAt(idx + 2); } - - int getNumDimensions() { return descs.size() - 2; } - - void setData(Data *data) { assignDescAt(data, 0); } - void setRaw(Data *raw) { assignDescAt(raw, 1); } - void setDimension(Data *dimension) { assignDescAt(dimension, 2); } - void setDimensionAt(Data *dimension, int idx) { - assignDescAt(dimension, 2 + idx); - } - -private: - void init(Data *units, Data *error, Data *help, Data *validation) { - dtype = DTYPE_SIGNAL; - incrementRefCounts(); - setAccessory(units, error, help, validation); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// DIMENSION COMPOUND //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Dimension class object description of DTYPE_DIMENSION -/// -/// MDSplus provides a dimension data type which provides a compact mechanism -/// for expressing signal dimensions (See: DTYPE_SIGNAL). The dimension data -/// type was implemented as a way to represent data such as the timebase for -/// signals recorded by data acquisition equipment such as transient recorders. -/// -/// A dimension data type is a structure which has two parts, a window and an -/// axis. The axis part is a representation of a series of values (i.e. time -/// stamps) and is generally represented by a DTYPE_RANGE data item. If this -/// was a single speed clock, for example, the axis would be represented by a -/// range consisting or an optional start time, an optional end time and a -/// single delta time value. This range could represent a series of clock -/// pulses which began some time infinitely in the past and continuing to some -/// time infinitely in the future. The window portion of the dimention is used -/// to select a set of these infinite stream of clock pulses that represent -/// those clock pulses which match the samples that were recorded in the -/// digitizers internal memory. The window portion is usually represented by a -/// DTYPE_WINDOW data item. A window consists of a start index, and end index -/// and a value at index 0. For a transient digitizer, the samples in the -/// memory were recorded at a known number of clock pulses before the trigger -/// (the start index) and continuing a known number of clock pulses after the -/// trigger. The time the module was triggered is the value at index 0 part of -/// the window. -/// -/// > -/// > See \ref dt_dimension for further details. -/// > -/// + Action(Data *dispatch, Data *task, Data *errorlogs, Data *completion_message, + Data *performance, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_ACTION; + descs.push_back(dispatch); + descs.push_back(task); + descs.push_back(errorlogs); + descs.push_back(completion_message); + descs.push_back(performance); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -class Dimension : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Dimension(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + Data *getDispatch() { return getDescAt(0); } - Dimension(Data *window, Data *axis, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - dtype = DTYPE_DIMENSION; - descs.push_back(window); - descs.push_back(axis); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + Data *getTask() { return getDescAt(1); } - /// Get the dimension window - Data *getWindow() { return getDescAt(0); } + Data *getErrorLogs() { return getDescAt(2); } - /// Get the dimension axis - Data *getAxis() { return getDescAt(1); } + Data *getCompletionMessage() { return getDescAt(3); } - /// Set the dimension window - void setWindow(Data *window) { assignDescAt(window, 0); } + Data *getPerformance() { return getDescAt(4); } - /// Set the dimension axis - void setAxis(Data *axis) { assignDescAt(axis, 1); } -}; + void setDispatch(Data *dispatch) { assignDescAt(dispatch, 0); } + void setTask(Data *task) { assignDescAt(task, 1); } + void setErrorLogs(Data *errorlogs) { assignDescAt(errorlogs, 2); } + void setCompletionMessage(Data *completion_message) + { + assignDescAt(completion_message, 3); + } + void setPerformance(Data *performance) { assignDescAt(performance, 4); } + }; -//////////////////////////////////////////////////////////////////////////////// -// WINDOW COMPOUND /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // DISPATCH COMPOUND ///////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Window class object description of DTYPE_WINDOW -/// -/// MDSplus provides a window data type which is used exclusively in -/// conjunction with a dimension data item (\ref Dimension). The window -/// provides a means for bracketing a potentially infinite vector of values -/// generated by a range data item (\ref Range). A window data type is a -/// structure containing three fields: the start index, the end index and the -/// value at index 0. The window brackets the axis portion of a dimension item -/// by finding the nearest element in the axis to the "value at index 0" value. -/// The subset of the axis elements are selected using the start index and end -/// index using this starting element as the index 0. For example if the window -/// was BUILD_WINDOW(-5,10,42.), MDSplus would find the element in the axis -/// portion of the dimension closest to a value of 42 (assuming the axis is -/// always increasing) and call that element, element number 0. The subset -/// would be this element and the 5 elements before it and the 10 elements -/// after it. For a more detailed explanation see the description of the -/// dimension data type. -/// -/// > -/// > See \ref dt_window for further details. -/// > -/// + /// + /// \brief The Dispatch class, object description of DTYPE_DISPATCH + /// + /// MDSplus provides a dispatch data type used for specifying the dispatching + /// information of an action. This determines where and when an automatic + /// action should be executed during the course of a experiment cycle. + /// + /// A dispatch item is a structure consisting of 5 parts; dispatch type, + /// server, phase, when, and completion. The dispatch type part specifies the + /// type of scheduling to be done. Currently only one type of dispatching is + /// supported in MDSplus and that is sequential scheduling (value=2). This + /// field should contain an integer value of 2. + /// + /// Server + /// ------ + /// The server part specifies the server that should execute the action. For + /// tcpip based action servers this field should contain a string such as + /// host:port where host is the tcpip hostname of the computer where the action + /// server is running and the port is the port number on which the action + /// server is listening for actions to perform. For DECNET based action servers + /// (OpenVMS only), this should be a string such as host::object where the host + /// is the DECNET node name and the object is the DECNET object name of the + /// action server. + /// + /// Phase + /// ----- + /// The phase part of a dispatch item is either the name or number + /// corresponding to the phase of the experiment cycle. These would normally be + /// phases such as "store", "init","analysis" etc. but the names and numbers of + /// the phases can be customized by the MDSplus system administrator by + /// modifying the TDI function phase_table(). + /// + /// When + /// ---- + /// The when part normally contains either an integer value or an expression + /// which evaluates to an integer value representing a sequence number. When + /// the dispatcher (implemented by a set of mdstcl dispatch commands) builds a + /// dispatching table, it finds all the actions defined in a tree and then + /// sorts these actions first by phase and then by sequence number. Actions are + /// then dispatched to servers during a phase in order of their sequence + /// numbers (except for actions with sequence numbers less than or equal to + /// zero which are not dispatched). There is a special case for the when part + /// which enables you to set up dependencies on other actions. If instead of + /// specifying a sequence number for the when part, you specify an expression + /// which references other action nodes in the tree, this action will not be + /// dispatched until all action nodes referenced in the expression have + /// completed. When all the actions referenced in the expression have + /// completed, the expression is then evaluated substituting the completion + /// status of the referenced actions instead of the action node itself. If the + /// result of the evaluation yields an odd number (low bit set) then this + /// action will be dispatched. If the result is an even value then this action + /// is not dispatched but instead assigned a failure completion status in case + /// other actions have when expressions refering to it. Using this mechanism + /// you can configure fairly complex conditional dispatching. + /// + /// Completion + /// ---------- + /// The completion part can hold a string defining the name of an MDSplus event + /// to be declared upon completion of this action. These events are often used + /// to trigger updates on visualization tools such as dwscope when this action + /// completes indicating availability of the data. + /// + /// > + /// > See \ref dt_dispatch for further details. + /// > + /// -class Window : public Compound { -public: + class Dispatch : public Compound + { + public: #ifndef DOXYGEN // hide this part from documentation - Window(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } + Dispatch(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } #endif // DOXYGEN end of hidden code - Window(Data *startidx, Data *endidx, Data *value_at_idx0, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - dtype = DTYPE_WINDOW; - descs.push_back(startidx); - descs.push_back(endidx); - descs.push_back(value_at_idx0); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } - - Data *getStartIdx() { return getDescAt(0); } + Dispatch(Data *ident, Data *phase, Data *when, Data *completion, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_DISPATCH; + descs.push_back(ident); + descs.push_back(phase); + descs.push_back(when); + descs.push_back(completion); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - Data *getEndIdx() { return getDescAt(1); } + Data *getIdent() { return getDescAt(0); } - Data *getValueAt0() { return getDescAt(2); } + Data *getPhase() { return getDescAt(1); } - void setStartIdx(Data *startidx) { assignDescAt(startidx, 0); } - void setEndIdx(Data *endidx) { assignDescAt(endidx, 1); } - void setValueAt0(Data *value_at_idx0) { assignDescAt(value_at_idx0, 2); } -}; + Data *getWhen() { return getDescAt(2); } -//////////////////////////////////////////////////////////////////////////////// -// FUNCTION COMPOUND ///////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getCompletion() { return getDescAt(3); } -/// -/// \brief The Function class object description of DTYPE_FUNCTION -/// -/// MDSplus provides a function data type used for describing references to -/// built in native TDI functions. When you specify an expression such as "a+b", -/// MDSplus will compile this into a DTYPE_FUNCTION data item. The function -/// data type consists of a opcode and a list of operands. The opcode is stored -/// as a 16 bit code and the operands can be any MDSplus data type. -/// -/// > -/// > See \ref dt_function for further details. -/// > -/// + void setIdent(Data *ident) { assignDescAt(ident, 0); } + void setPhase(Data *phase) { assignDescAt(phase, 1); } + void setWhen(Data *when) { assignDescAt(when, 2); } + void setCompletion(Data *completion) { assignDescAt(completion, 3); } + }; -class Function : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Function(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + //////////////////////////////////////////////////////////////////////////////// + // PROGRAM COMPOUND ///////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// - Function(short opcode, int nargs, Data **args, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - dtype = DTYPE_FUNCTION; - this->opcode = opcode; - for (int i = 0; i < nargs; i++) - descs.push_back(args[i]); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + /// + /// \brief The Program class object description of DTYPE_PROGRAM + /// - /// Get operation code from compiled TDI expression - short getOpcode() { return opcode; } + class Program : public Compound + { + protected: + bool isImmutable() { return false; } - /// Get number of arguments for this expression. - int getNumArguments() { return descs.size(); } + public: + Program(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + Program(Data *timeout, Data *program, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_PROGRAM; + descs.push_back(timeout); + descs.push_back(program); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - /// Get data argument at position idx - Data *getArgumentAt(int idx) { return getDescAt(idx); } + Data *getTimeout() { return getDescAt(0); } - /// Set idx data argument - void setArgAt(Data *arg, int idx) { assignDescAt(arg, idx); } -}; + Data *getProgram() { return getDescAt(1); } -//////////////////////////////////////////////////////////////////////////////// -// CONGLOM COMPOUND ////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } + void setProgram(Data *program) { assignDescAt(program, 1); } + }; -/// -/// \brief The Conglom class object description of DTYPE_CONGLOM -/// -/// MDSplus provides a conglomerate data type used for describing data -/// acquisition or analysis devices. A device in MDSplus is implemented as a -/// collection of adjacent tree nodes (or a conglomerate). The first node -/// (located at the top of the node structure of this collection) contains a -/// conglomerate data type. The conglomerate data type is a structure -/// containing an image part, a model part, a name part and a qualifiers part. -/// MDSplus implements device support by providing a mechanism for performing -/// "methods" on devices. When a device method is performed on a device in a -/// MDSplus tree either through an action or using the TCL command DO/METHOD, -/// MDSplus invokes a procedure determined by the information in the head node -/// of the device which contains a conglomerate data type. If there is an image -/// part of the conglomerate structure, MDSplus will attempt to call a routine -/// called "model-part"__"method" in the shared library specified by the image -/// part. If the routine can not be found, MDSplus will try to invoke the TDI -/// function called "model-part"__"method". Normally, the conglomerate data is -/// loaded into the head node of a device automatically when you add it to the -/// tree so you may not need to access this data type directly. -/// -/// The name part of the device is often a reference to a sub node of the -/// device which contains the data acquisition module identification such as -/// the CAMAC module name. This portion of the device is not used during method -/// invokation and was simply added as a convenience in building tools for -/// gathering information about device definitions in a tree. The qualifiers -/// part of the structure could be used by device support for making variant -/// device implementations. This field along with the name field are generally -/// not used any longer. -/// -/// > -/// > See \ref dt_conglom for further details. -/// > -/// + //////////////////////////////////////////////////////////////////////////////// + // ROUTINE COMPOUND ////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Conglom : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Conglom(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + /// + /// \brief The Routine class object description of DTYPE_ROUTINE + /// - Conglom(Data *image, Data *model, Data *name, Data *qualifiers, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_CONGLOM; - descs.push_back(image); - descs.push_back(model); - descs.push_back(name); - descs.push_back(qualifiers); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + class Routine : public Compound + { + protected: + bool isImmutable() { return false; } - Data *getImage() { return getDescAt(0); } + public: + Routine(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + Routine(Data *timeout, Data *image, Data *routine, int nargs, Data **args, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_ROUTINE; + descs.push_back(timeout); + descs.push_back(image); + descs.push_back(routine); + for (int i = 0; i < nargs; i++) + descs.push_back(args[i]); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - Data *getModel() { return getDescAt(1); } + Data *getTimeout() { return getDescAt(0); } - Data *getName() { return getDescAt(2); } + Data *getImage() { return getDescAt(1); } - Data *getQualifiers() { return getDescAt(3); } + Data *getRoutine() { return getDescAt(2); } - void setImage(Data *image) { assignDescAt(image, 0); } - void setModel(Data *model) { assignDescAt(model, 1); } - void setName(Data *name) { assignDescAt(name, 2); } - void setQualifiers(Data *qualifiers) { assignDescAt(qualifiers, 3); } -}; + Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } -//////////////////////////////////////////////////////////////////////////////// -// RANGE COMPOUND //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } + void setImage(Data *image) { assignDescAt(image, 1); } + void setRoutine(Data *routine) { assignDescAt(routine, 2); } + void setArgumentAt(Data *argument, int idx) + { + assignDescAt(argument, 3 + idx); + } + }; -/// -/// \brief The Range class, object description of DTYPE_RANGE -/// -/// MDSplus provides a range data type which provides a compact mechanism for -/// expressing series of values with fixed intervals. The range data type is a -/// structure consisting of three parts; begin, end, and delta. This data type -/// is used often in MDSplus for representing data such as the output of clock -/// devices used in data acquisition. The following example shows three simple -/// instances of ranges: -/// -/// \code{.cpp} -/// // _tdi_range1 = 1 : 10 -/// Data *range1 = new Range(new Int32(1),new Int32(10),NULL); -/// -/// // _tdi_range2 = 1 : 10 : .5 -/// Data *range2 = new Range(new Float32(1),new Float32(10),new -/// Float32(0.5)); -/// -/// // _range = * : * : 1E-6 -/// Data *range3 = new Range(NULL,NULL,new Float32(1E-6)); -/// \endcode -/// -/// In the above examples, we show two formats for creating ranges. The MDSplus -/// TDI expression evaluator has a built in syntax for specifying ranges which -/// is one of the following: -/// -/// \code{.cpp} -/// begin : end [: delta] -/// _range = build_range(begin,end,delta) -/// \endcode -/// -/// > -/// > See \ref dt_range for further details. -/// > -/// + //////////////////////////////////////////////////////////////////////////////// + // PROCEDURE COMPOUND //////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Range : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Range(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + /// + /// \brief The Procedure class object description of DTYPE_PROCEDURE + /// - Range(Data *begin, Data *ending, Data *deltaval, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - dtype = DTYPE_RANGE; - descs.push_back(begin); - descs.push_back(ending); - descs.push_back(deltaval); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + class Procedure : public Compound + { + protected: + bool isImmutable() { return false; } + + public: + Procedure(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + Procedure(Data *timeout, Data *language, Data *procedure, int nargs, + Data **args, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_PROCEDURE; + descs.push_back(timeout); + descs.push_back(language); + descs.push_back(procedure); + for (int i = 0; i < nargs; i++) + descs.push_back(args[i]); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - /// Get range begin - Data *getBegin() { return getDescAt(0); } + Data *getTimeout() { return getDescAt(0); } - /// Get range end - Data *getEnding() { return getDescAt(1); } + Data *getLanguage() { return getDescAt(1); } - /// Get Range delta - Data *getDeltaVal() { return getDescAt(2); } + Data *getProcedure() { return getDescAt(2); } - void setBegin(Data *begin) { assignDescAt(begin, 0); } - void setEnding(Data *ending) { assignDescAt(ending, 1); } - void setDeltaVal(Data *deltaval) { assignDescAt(deltaval, 2); } -}; + Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } -//////////////////////////////////////////////////////////////////////////////// -// ACTION COMPOUND /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } + void setLanguage(Data *language) { assignDescAt(language, 1); } + void seProcedure(Data *procedure) { assignDescAt(procedure, 2); } + void setArgumentAt(Data *argument, int idx) + { + assignDescAt(argument, 3 + idx); + } + }; -/// -/// \brief The Action class, object description of type DTYPE_ACTION -/// + //////////////////////////////////////////////////////////////////////////////// + // METHOD COMPOUND /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// MDSplus provides an action data type used for describing actions to be -/// dispatched to action servers during a normal experiment cycle. An action -/// consists of 5 parts but the current implementations of action dispatching -/// only refernce the first three parts, a dispatch part, a task part and an -/// errorlogs part (OpenVMS only). The dispatch part (See: DTYPE_DISPATCH) -/// includes information such as which server should perform the task, when -/// during the course of the shot cycle it should be executed, what MDSplus -/// event should be issued when the task completes. The task part describes -/// what is to be done when the action is executed. There are a couple -/// different types of task types currently support (See: DTYPE_METHOD and -/// DTYPE_ROUTINE). The errorlogs part is implemented only on OpenVMS. If this -/// part contains a string consisting of a comma delimited list of user -/// accounts, each user on the list will receive a OpenVMS cluster-wide -/// broadcast message if this action fails during execution. The remaining -/// parts were originally defined to hold statistics from the execution of the -/// action but since this would require rewriting the action data (which is -/// usually considered setup information and not writable in the pulse files) -/// this feature was never used. This unused parts are called -/// completion_message and performance. -/// -/// > -/// > See \ref dt_action for further details. -/// > -/// + /// + /// \brief The Method class object description of DTYPE_METHOD + /// + /// MDSplus provides a method data type for describing an operation to be + /// performed on an MDSplus device to be used as the task portion of an action + /// data item. MDSplus devices support various "methods" which can be performed + /// on the device. For example, transient digitizer device may support an + /// "INIT" method to prepare the device to acquire data and a "STORE" method + /// which would retrieve the data from the physical device and store it into + /// the device nodes in the MDSplus tree. + /// + /// The method data type is a structure consisting of three fields followed by + /// optional arguments to the method being performed. + /// + /// The first field is a timeout value specified in seconds. When the method is + /// being performed on the device and a timeout is specified, a timer is + /// started when the operation is started and if the operation is not completed + /// before the specified timeout, the operation will be aborted abruptly. This + /// field can either be omitted or should contain a value or expression which + /// when evaluated will result in a scalar numeric value. + /// + /// The next field in the method data type is the name of the method to be + /// performed. This should contain a value or expression which when evaluated + /// will result in a scalar text value representing a supported method for the + /// device being operated on (i.e. "INIT", "STORE","EXECUTE"). The set of + /// available methods is device specific. + /// + /// The next field is the object on which this operation is to be performed. + /// This should be a node reference to one of the nodes which make up the + /// device, usually the top node in the device node structure. + /// + /// These first three fields can be followed by optional parameters which will + /// be interpretted by the implementation of the method. These fields are + /// specific to the implementation of the various methods. + /// + /// > + /// > See \ref dt_method for further details. + /// > + /// -class Action : public Compound { -public: + class Method : public Compound + { + public: #ifndef DOXYGEN // hide this part from documentation - Action(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } + Method(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } #endif // DOXYGEN end of hidden code - Action(Data *dispatch, Data *task, Data *errorlogs, Data *completion_message, - Data *performance, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_ACTION; - descs.push_back(dispatch); - descs.push_back(task); - descs.push_back(errorlogs); - descs.push_back(completion_message); - descs.push_back(performance); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + Method(Data *timeout, Data *method, Data *object, int nargs, Data **args, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_METHOD; + descs.push_back(timeout); + descs.push_back(method); + descs.push_back(object); + for (int i = 0; i < nargs; i++) + descs.push_back(args[i]); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } + + Data *getTimeout() { return getDescAt(0); } - Data *getDispatch() { return getDescAt(0); } + Data *getMethod() { return getDescAt(1); } - Data *getTask() { return getDescAt(1); } + Data *getObject() { return getDescAt(2); } - Data *getErrorLogs() { return getDescAt(2); } + Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } - Data *getCompletionMessage() { return getDescAt(3); } + void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } + void setMethod(Data *method) { assignDescAt(method, 1); } + void setObject(Data *object) { assignDescAt(object, 2); } + void setArgumentAt(Data *argument, int idx) + { + assignDescAt(argument, 3 + idx); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // DEPENDENCY COMPOUND /////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// \brief The Dependency class object description of DTYPE_DEPENDENCY + /// + + class Dependency : public Compound + { + public: + Dependency(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + Dependency(short opcode, Data *arg1, Data *arg2, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_DEPENDENCY; + this->opcode = opcode; + descs.push_back(arg1); + descs.push_back(arg2); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - Data *getPerformance() { return getDescAt(4); } + short getOpcode() { return opcode; } - void setDispatch(Data *dispatch) { assignDescAt(dispatch, 0); } - void setTask(Data *task) { assignDescAt(task, 1); } - void setErrorLogs(Data *errorlogs) { assignDescAt(errorlogs, 2); } - void setCompletionMessage(Data *completion_message) { - assignDescAt(completion_message, 3); - } - void setPerformance(Data *performance) { assignDescAt(performance, 4); } -}; + Data *getArg1() { return getDescAt(0); } -//////////////////////////////////////////////////////////////////////////////// -// DISPATCH COMPOUND ///////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getArg2() { return getDescAt(1); } -/// -/// \brief The Dispatch class, object description of DTYPE_DISPATCH -/// -/// MDSplus provides a dispatch data type used for specifying the dispatching -/// information of an action. This determines where and when an automatic -/// action should be executed during the course of a experiment cycle. -/// -/// A dispatch item is a structure consisting of 5 parts; dispatch type, -/// server, phase, when, and completion. The dispatch type part specifies the -/// type of scheduling to be done. Currently only one type of dispatching is -/// supported in MDSplus and that is sequential scheduling (value=2). This -/// field should contain an integer value of 2. -/// -/// Server -/// ------ -/// The server part specifies the server that should execute the action. For -/// tcpip based action servers this field should contain a string such as -/// host:port where host is the tcpip hostname of the computer where the action -/// server is running and the port is the port number on which the action -/// server is listening for actions to perform. For DECNET based action servers -/// (OpenVMS only), this should be a string such as host::object where the host -/// is the DECNET node name and the object is the DECNET object name of the -/// action server. -/// -/// Phase -/// ----- -/// The phase part of a dispatch item is either the name or number -/// corresponding to the phase of the experiment cycle. These would normally be -/// phases such as "store", "init","analysis" etc. but the names and numbers of -/// the phases can be customized by the MDSplus system administrator by -/// modifying the TDI function phase_table(). -/// -/// When -/// ---- -/// The when part normally contains either an integer value or an expression -/// which evaluates to an integer value representing a sequence number. When -/// the dispatcher (implemented by a set of mdstcl dispatch commands) builds a -/// dispatching table, it finds all the actions defined in a tree and then -/// sorts these actions first by phase and then by sequence number. Actions are -/// then dispatched to servers during a phase in order of their sequence -/// numbers (except for actions with sequence numbers less than or equal to -/// zero which are not dispatched). There is a special case for the when part -/// which enables you to set up dependencies on other actions. If instead of -/// specifying a sequence number for the when part, you specify an expression -/// which references other action nodes in the tree, this action will not be -/// dispatched until all action nodes referenced in the expression have -/// completed. When all the actions referenced in the expression have -/// completed, the expression is then evaluated substituting the completion -/// status of the referenced actions instead of the action node itself. If the -/// result of the evaluation yields an odd number (low bit set) then this -/// action will be dispatched. If the result is an even value then this action -/// is not dispatched but instead assigned a failure completion status in case -/// other actions have when expressions refering to it. Using this mechanism -/// you can configure fairly complex conditional dispatching. -/// -/// Completion -/// ---------- -/// The completion part can hold a string defining the name of an MDSplus event -/// to be declared upon completion of this action. These events are often used -/// to trigger updates on visualization tools such as dwscope when this action -/// completes indicating availability of the data. -/// -/// > -/// > See \ref dt_dispatch for further details. -/// > -/// + void setOpcode(short opcode) { this->opcode = opcode; } -class Dispatch : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Dispatch(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + void setArg1(Data *arg1) { assignDescAt(arg1, 0); } + void setArg2(Data *arg2) { assignDescAt(arg2, 0); } + }; - Dispatch(Data *ident, Data *phase, Data *when, Data *completion, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_DISPATCH; - descs.push_back(ident); - descs.push_back(phase); - descs.push_back(when); - descs.push_back(completion); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + //////////////////////////////////////////////////////////////////////////////// + // CONDITION COMPOUND //////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// - Data *getIdent() { return getDescAt(0); } + /// + /// \brief The Condition class object description of DTYPE_CONDITION + /// - Data *getPhase() { return getDescAt(1); } + class Condition : public Compound + { + public: + Condition(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } + Condition(short opcode, Data *arg, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + dtype = DTYPE_CONDITION; + this->opcode = opcode; + descs.push_back(arg); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } - Data *getWhen() { return getDescAt(2); } + short getOpcode() { return opcode; } - Data *getCompletion() { return getDescAt(3); } + Data *getArg() { return getDescAt(0); } - void setIdent(Data *ident) { assignDescAt(ident, 0); } - void setPhase(Data *phase) { assignDescAt(phase, 1); } - void setWhen(Data *when) { assignDescAt(when, 2); } - void setCompletion(Data *completion) { assignDescAt(completion, 3); } -}; + void setOpcode(short opcode) { this->opcode = opcode; } -//////////////////////////////////////////////////////////////////////////////// -// PROGRAM COMPOUND ///////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + void setArg(Data *arg) { assignDescAt(arg, 0); } + }; -/// -/// \brief The Program class object description of DTYPE_PROGRAM -/// + //////////////////////////////////////////////////////////////////////////////// + // CALL COMPOUND ///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Program : public Compound { -protected: - bool isImmutable() { return false; } + /// + /// \brief The Call class object description of DTYPE_CALL + /// + /// MDSplus provides a call data type used for describing references to + /// external functions. The MDSplus expression evaluator has the ability to + /// call external functions in shared libararies or DLL's. The call datatype + /// describes the type of the return value of the function, the name of the + /// library or DLL where the function can be found, the name of the function + /// and the list of arguments to present to the function when calling it. The + /// expression evaluator in MDSplus has syntax for easily building instances of + /// this data type as will as builtin functions for constructing them. The call + /// to the external function occurs when the expression containing a call item + /// is evaluated. The following example shows an example of calling an external + /// function in TDI: + /// + /// mysharedlib->myfunction(42) + /// + /// The code above is the most common form of the function reference. When + /// evaluated, the function called "myfunction" found in the library + /// "mysharedlib" will be called with one argument, 42. The return value of the + /// function is assumed to be a 32-bit signed integer. The code following shows + /// how to instance a binary call, the actual function call is done when the + /// evaluation of the expression is triggered by the data() member. + /// + /// \code{.cpp} + /// #include + /// using namespace MDSplus; + /// { + /// // test for binary function call // + /// Data *args[2] = { new Int32(5552367), new Int32(1) }; + /// AutoData call2 = new Call(new + /// String("./testutils/libMdsTestDummy.so"), + /// new String("test_addint"), + /// 2, (Data**)args); + /// TEST1( AutoData(call2->data())->getInt() == 5552368 ); + /// deleteData(args[0]); + /// deleteData(args[1]); + /// } + /// \endcode + /// + /// \note MDSplus uses operating system specific rules to locate shared + /// libraries when the full file specification of the library is not given. On + /// OpenVMS, the system would first look for a logical name matching the name + /// of the library and if one is found it would activate the image defined by + /// the logical name. If their is no such logical name, the system would then + /// look in the directory search path defined by SYS$SHARE for the library. The + /// file type for shared libraries on OpenVMS is ".EXE". On Unix systems the + /// system looks for a library path environment variable such as + /// LD_LIBRARY_PATH or SHLIB_PATH and looks in these directories. If there is + /// no such environment variable, the system looks in system library + /// directories (usually /usr/lib or /usr/local/lib) for the shared library. + /// The file type for shared libraries on Unix is generally ".so",".sl" or + /// sometimes ".a". On Windows systems, the system looks for shared libraries + /// in the directory where the application was run or in the directory list + /// specified by the "PATH" environment variable. The file type of shared + /// libraries on Windows is ".dll". + /// -public: - Program(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - Program(Data *timeout, Data *program, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - dtype = DTYPE_PROGRAM; - descs.push_back(timeout); - descs.push_back(program); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } - - Data *getTimeout() { return getDescAt(0); } - - Data *getProgram() { return getDescAt(1); } - - void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } - void setProgram(Data *program) { assignDescAt(program, 1); } -}; - -//////////////////////////////////////////////////////////////////////////////// -// ROUTINE COMPOUND ////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + class Call : public Compound + { + public: +#ifndef DOXYGEN // hide this part from documentation + Call(int dtype, int length, char *ptr, int nDescs, char **descs, + Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Compound(dtype, length, ptr, nDescs, descs) + { + setAccessory(units, error, help, validation); + } +#endif // DOXYGEN end of hidden code -/// -/// \brief The Routine class object description of DTYPE_ROUTINE -/// + /// Build a call object secifying the image and routine entries, together + /// with the routine data arguments and return type. If no return type is + /// specified the DTYPE_L is assumed as default. + /// + /// \param image A new \ref String containing the routine to be called + /// \param routine A new \ref String of the called image symbol routine. + /// \param nargs The number of arguments that will be the routine input + /// arguments. \param args The array of the data arguments of the routine. + /// \param retType The data type (DTYPE_xxx) that the Call will return. + /// + Call(Data *image, Data *routine, int nargs, Data **args, + char retType = DTYPE_L, Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + { + dtype = DTYPE_CALL; + opcode = retType; + descs.push_back(image); + descs.push_back(routine); + for (int i = 0; i < nargs; i++) + descs.push_back(args[i]); + incrementRefCounts(); + setAccessory(units, error, help, validation); + } -class Routine : public Compound { -protected: - bool isImmutable() { return false; } + /// Get the code associated to the Call return type. This is the data type + /// that will be associated to the returned data descriptor. If no return + /// type was specified in the instance construction the DTYPE_L is assumed + /// as default. + /// + char getRetType() { return opcode; } + + /// Set the return type code as one of the DTYPE_xx codes defined. If no + /// return type was specified in the instance construction the DTYPE_L is + /// assumed as default. + /// + void setRetType(char retType) { opcode = retType; } + + /// Get the Call image as Data object. The image is usually a string that + /// specifies the current path to find the library that contains the symbol + /// to be called. + /// + Data *getImage() { return getDescAt(0); } + + /// Get the routine that the Call instance will look for in the image. This + /// is usually a string containing the symbol within the image library. + /// \note MDSplus does not manages the symbol mangling used by compilers to + /// identify class member functions, so that only C compiled function will + /// be reached by Call. + /// + Data *getRoutine() { return getDescAt(1); } + + /// Get the idx argument of the routine input argument list. + /// + Data *getArgumentAt(int idx) { return getDescAt(idx + 2); } + + /// Set the call image. The image is usually a string that specifies the + /// current path to find the library that contains the symbol to be called. + /// + void setImage(Data *image) { assignDescAt(image, 0); } + + /// Set the routine that the Call instance will look for in the image. This + /// is usually a string containing the symbol within the image library. + /// \note MDSplus does not manages the symbol mangling used by compilers to + /// identify class member functions, so that only C compiled function will + /// be reached by Call. + /// + void setRoutine(Data *routine) { assignDescAt(routine, 1); } + + /// Set the idx argument of the routine input argument list. + /// + void setArgumentAt(Data *argument, int idx) + { + assignDescAt(argument, 2 + idx); + } + }; -public: - Routine(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - Routine(Data *timeout, Data *image, Data *routine, int nargs, Data **args, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_ROUTINE; - descs.push_back(timeout); - descs.push_back(image); - descs.push_back(routine); - for (int i = 0; i < nargs; i++) - descs.push_back(args[i]); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } - - Data *getTimeout() { return getDescAt(0); } - - Data *getImage() { return getDescAt(1); } - - Data *getRoutine() { return getDescAt(2); } - - Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } - - void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } - void setImage(Data *image) { assignDescAt(image, 1); } - void setRoutine(Data *routine) { assignDescAt(routine, 2); } - void setArgumentAt(Data *argument, int idx) { - assignDescAt(argument, 3 + idx); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// PROCEDURE COMPOUND //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // APD DATA ////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -/// -/// \brief The Procedure class object description of DTYPE_PROCEDURE -/// + /// + /// \brief The Apd class object description of DTYPE_DSC + /// -class Procedure : public Compound { -protected: - bool isImmutable() { return false; } + class EXPORT Apd : public Data + { + public: + Apd(Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + { + clazz = CLASS_APD; + dtype = DTYPE_DSC; + setAccessory(units, error, help, validation); + } -public: - Procedure(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - Procedure(Data *timeout, Data *language, Data *procedure, int nargs, - Data **args, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_PROCEDURE; - descs.push_back(timeout); - descs.push_back(language); - descs.push_back(procedure); - for (int i = 0; i < nargs; i++) - descs.push_back(args[i]); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } - - Data *getTimeout() { return getDescAt(0); } - - Data *getLanguage() { return getDescAt(1); } - - Data *getProcedure() { return getDescAt(2); } - - Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } - - void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } - void setLanguage(Data *language) { assignDescAt(language, 1); } - void seProcedure(Data *procedure) { assignDescAt(procedure, 2); } - void setArgumentAt(Data *argument, int idx) { - assignDescAt(argument, 3 + idx); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// METHOD COMPOUND /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Apd(std::size_t nData, Data **descs, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + { + clazz = CLASS_APD; + dtype = DTYPE_DSC; + for (std::size_t i = 0; i < nData; ++i) + { + if (descs[i]) + descs[i]->incRefCount(); + this->descs.push_back(descs[i]); + } + setAccessory(units, error, help, validation); + } -/// -/// \brief The Method class object description of DTYPE_METHOD -/// -/// MDSplus provides a method data type for describing an operation to be -/// performed on an MDSplus device to be used as the task portion of an action -/// data item. MDSplus devices support various "methods" which can be performed -/// on the device. For example, transient digitizer device may support an -/// "INIT" method to prepare the device to acquire data and a "STORE" method -/// which would retrieve the data from the physical device and store it into -/// the device nodes in the MDSplus tree. -/// -/// The method data type is a structure consisting of three fields followed by -/// optional arguments to the method being performed. -/// -/// The first field is a timeout value specified in seconds. When the method is -/// being performed on the device and a timeout is specified, a timer is -/// started when the operation is started and if the operation is not completed -/// before the specified timeout, the operation will be aborted abruptly. This -/// field can either be omitted or should contain a value or expression which -/// when evaluated will result in a scalar numeric value. -/// -/// The next field in the method data type is the name of the method to be -/// performed. This should contain a value or expression which when evaluated -/// will result in a scalar text value representing a supported method for the -/// device being operated on (i.e. "INIT", "STORE","EXECUTE"). The set of -/// available methods is device specific. -/// -/// The next field is the object on which this operation is to be performed. -/// This should be a node reference to one of the nodes which make up the -/// device, usually the top node in the device node structure. -/// -/// These first three fields can be followed by optional parameters which will -/// be interpretted by the implementation of the method. These fields are -/// specific to the implementation of the various methods. -/// -/// > -/// > See \ref dt_method for further details. -/// > -/// + virtual void propagateDeletion() + { + for (std::size_t i = 0; i < descs.size(); ++i) + { + if (descs[i]) + { + descs[i]->decRefCount(); + deleteData(descs[i]); + } + } + } -class Method : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Method(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + virtual ~Apd() { propagateDeletion(); } - Method(Data *timeout, Data *method, Data *object, int nargs, Data **args, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_METHOD; - descs.push_back(timeout); - descs.push_back(method); - descs.push_back(object); - for (int i = 0; i < nargs; i++) - descs.push_back(args[i]); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + virtual std::size_t len() { return descs.size(); } - Data *getTimeout() { return getDescAt(0); } + Data **getDscs() { return &descs[0]; } - Data *getMethod() { return getDescAt(1); } + std::size_t getDimension() { return Apd::len(); } - Data *getObject() { return getDescAt(2); } + Data **getDscArray() { return getDscs(); } - Data *getArgumentAt(int idx) { return getDescAt(idx + 3); } + Data *getDescAt(std::size_t i) + { + // descs.at(i)->incRefCount(); + return descs.at(i); + } - void setTimeout(Data *timeout) { assignDescAt(timeout, 0); } - void setMethod(Data *method) { assignDescAt(method, 1); } - void setObject(Data *object) { assignDescAt(object, 2); } - void setArgumentAt(Data *argument, int idx) { - assignDescAt(argument, 3 + idx); - } -}; + bool hasDescAt(std::size_t i) { return descs.size() > i && descs[i] != NULL; } + void setDescAt(std::size_t i, Data *data) + { + if (descs.size() <= i) + { + for (size_t j = descs.size(); j < i; j++) + descs.push_back(NULL); + descs.push_back(data); + } + else + // INSERT AND BEGIN() WORK ONLY IF VECTOR NON EMPTY!! + descs.insert(descs.begin() + i, data); + // data->incRefCount(); + } + void appendDesc(Data *data) + { + descs.push_back(data); + // if(data) data->incRefCount(); + } + void *convertToDsc(); -//////////////////////////////////////////////////////////////////////////////// -// DEPENDENCY COMPOUND /////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + protected: + std::vector descs; + }; -/// -/// \brief The Dependency class object description of DTYPE_DEPENDENCY -/// + //////////////////////////////////////////////////////////////////////////////// + // LIST DATA ///////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Dependency : public Compound { -public: - Dependency(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - Dependency(short opcode, Data *arg1, Data *arg2, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0) { - dtype = DTYPE_DEPENDENCY; - this->opcode = opcode; - descs.push_back(arg1); - descs.push_back(arg2); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + class EXPORT List : public Apd + { + public: + List(Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) + : Apd(units, error, help, validation) + { + dtype = DTYPE_LIST; + } - short getOpcode() { return opcode; } + List(int nData, Data **descs, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + : Apd(nData, descs, units, error, help, validation) + { + dtype = DTYPE_LIST; + } - Data *getArg1() { return getDescAt(0); } + void append(Data *data) { appendDesc(data); } - Data *getArg2() { return getDescAt(1); } + void remove(Data *data) + { + descs.erase(std::remove(descs.begin(), descs.end(), data), descs.end()); + data->decRefCount(); + } - void setOpcode(short opcode) { this->opcode = opcode; } + void remove(std::size_t i) + { + descs.at(i)->decRefCount(); + descs.erase(descs.begin() + i); + } - void setArg1(Data *arg1) { assignDescAt(arg1, 0); } - void setArg2(Data *arg2) { assignDescAt(arg2, 0); } -}; + void insert(std::size_t i, Data *data) + { + descs.insert(descs.begin() + i, data); + data->incRefCount(); + } -//////////////////////////////////////////////////////////////////////////////// -// CONDITION COMPOUND //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + Data *getElementAt(std::size_t i) + { + descs.at(i)->incRefCount(); + return descs[i]; + } + }; -/// -/// \brief The Condition class object description of DTYPE_CONDITION -/// + //////////////////////////////////////////////////////////////////////////////// + // DICTIONARY DATA /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Condition : public Compound { -public: - Condition(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } - Condition(short opcode, Data *arg, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - dtype = DTYPE_CONDITION; - this->opcode = opcode; - descs.push_back(arg); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + class EXPORT Dictionary : public Apd + { + public: + Dictionary(Data *units = 0, Data *error = 0, Data *help = 0, + Data *validation = 0) + : Apd(units, error, help, validation) + { + dtype = DTYPE_DICTIONARY; + } - short getOpcode() { return opcode; } + Dictionary(int nData, Data **descs, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0) + : Apd(nData, descs, units, error, help, validation) + { + dtype = DTYPE_DICTIONARY; + } - Data *getArg() { return getDescAt(0); } + Data *getItem(String *strData) + { + for (std::size_t i = 0; i < descs.size(); i += 2) + { + if (strData->equals(descs[i])) + { + descs[i + 1]->incRefCount(); + return descs[i + 1]; + } + } + return 0; + } - void setOpcode(short opcode) { this->opcode = opcode; } + void setItem(String *strData, Data *data) + { + for (std::size_t i = 0; i < descs.size(); i += 2) + { + if (strData->equals(descs[i])) + { + descs[i]->decRefCount(); + descs[i] = strData; + strData->incRefCount(); + + descs[i + 1]->decRefCount(); + descs[i + 1] = data; + data->incRefCount(); + return; + } + } - void setArg(Data *arg) { assignDescAt(arg, 0); } -}; + descs.push_back(strData); + descs.push_back(data); + strData->incRefCount(); + data->incRefCount(); + } -//////////////////////////////////////////////////////////////////////////////// -// CALL COMPOUND ///////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + std::size_t len() { return Apd::len() / 2; } + }; -/// -/// \brief The Call class object description of DTYPE_CALL -/// -/// MDSplus provides a call data type used for describing references to -/// external functions. The MDSplus expression evaluator has the ability to -/// call external functions in shared libararies or DLL's. The call datatype -/// describes the type of the return value of the function, the name of the -/// library or DLL where the function can be found, the name of the function -/// and the list of arguments to present to the function when calling it. The -/// expression evaluator in MDSplus has syntax for easily building instances of -/// this data type as will as builtin functions for constructing them. The call -/// to the external function occurs when the expression containing a call item -/// is evaluated. The following example shows an example of calling an external -/// function in TDI: -/// -/// mysharedlib->myfunction(42) -/// -/// The code above is the most common form of the function reference. When -/// evaluated, the function called "myfunction" found in the library -/// "mysharedlib" will be called with one argument, 42. The return value of the -/// function is assumed to be a 32-bit signed integer. The code following shows -/// how to instance a binary call, the actual function call is done when the -/// evaluation of the expression is triggered by the data() member. -/// -/// \code{.cpp} -/// #include -/// using namespace MDSplus; -/// { -/// // test for binary function call // -/// Data *args[2] = { new Int32(5552367), new Int32(1) }; -/// AutoData call2 = new Call(new -/// String("./testutils/libMdsTestDummy.so"), -/// new String("test_addint"), -/// 2, (Data**)args); -/// TEST1( AutoData(call2->data())->getInt() == 5552368 ); -/// deleteData(args[0]); -/// deleteData(args[1]); -/// } -/// \endcode -/// -/// \note MDSplus uses operating system specific rules to locate shared -/// libraries when the full file specification of the library is not given. On -/// OpenVMS, the system would first look for a logical name matching the name -/// of the library and if one is found it would activate the image defined by -/// the logical name. If their is no such logical name, the system would then -/// look in the directory search path defined by SYS$SHARE for the library. The -/// file type for shared libraries on OpenVMS is ".EXE". On Unix systems the -/// system looks for a library path environment variable such as -/// LD_LIBRARY_PATH or SHLIB_PATH and looks in these directories. If there is -/// no such environment variable, the system looks in system library -/// directories (usually /usr/lib or /usr/local/lib) for the shared library. -/// The file type for shared libraries on Unix is generally ".so",".sl" or -/// sometimes ".a". On Windows systems, the system looks for shared libraries -/// in the directory where the application was run or in the directory list -/// specified by the "PATH" environment variable. The file type of shared -/// libraries on Windows is ".dll". -/// + //////////////////////////////////////////////////////////////////////////////// + // TREE DATA //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -class Call : public Compound { -public: -#ifndef DOXYGEN // hide this part from documentation - Call(int dtype, int length, char *ptr, int nDescs, char **descs, - Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Compound(dtype, length, ptr, nDescs, descs) { - setAccessory(units, error, help, validation); - } -#endif // DOXYGEN end of hidden code + class Tree; + class TreeNode; + class TreeNodeArray; - /// Build a call object secifying the image and routine entries, together - /// with the routine data arguments and return type. If no return type is - /// specified the DTYPE_L is assumed as default. /// - /// \param image A new \ref String containing the routine to be called - /// \param routine A new \ref String of the called image symbol routine. - /// \param nargs The number of arguments that will be the routine input - /// arguments. \param args The array of the data arguments of the routine. - /// \param retType The data type (DTYPE_xxx) that the Call will return. + /// \brief The TreeNode class object description of DTYPE_NID /// - Call(Data *image, Data *routine, int nargs, Data **args, - char retType = DTYPE_L, Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) { - dtype = DTYPE_CALL; - opcode = retType; - descs.push_back(image); - descs.push_back(routine); - for (int i = 0; i < nargs; i++) - descs.push_back(args[i]); - incrementRefCounts(); - setAccessory(units, error, help, validation); - } + class EXPORT TreeNode : public Data + { + friend EXPORT std::ostream &operator<<(std::ostream &stream, + TreeNode *treeNode) + { + stream << treeNode->getFullPathStr(); + return stream; + } - /// Get the code associated to the Call return type. This is the data type - /// that will be associated to the returned data descriptor. If no return - /// type was specified in the instance construction the DTYPE_L is assumed - /// as default. - /// - char getRetType() { return opcode; } + protected: + Tree *tree; + int nid; - /// Set the return type code as one of the DTYPE_xx codes defined. If no - /// return type was specified in the instance construction the DTYPE_L is - /// assumed as default. - /// - void setRetType(char retType) { opcode = retType; } + // From Data + virtual bool isImmutable() { return false; } + virtual void *convertToDsc(); + virtual bool getFlag(int flagOfs); + virtual void setFlag(int flagOfs, bool val); - /// Get the Call image as Data object. The image is usually a string that - /// specifies the current path to find the library that contains the symbol - /// to be called. - /// - Data *getImage() { return getDescAt(0); } + virtual char getNciChar(int itm); + virtual int getNciInt(int itm); + virtual int64_t getNciInt64(int itm); + virtual std::string getNciString(int itm); - /// Get the routine that the Call instance will look for in the image. This - /// is usually a string containing the symbol within the image library. - /// \note MDSplus does not manages the symbol mangling used by compilers to - /// identify class member functions, so that only C compiled function will - /// be reached by Call. - /// - Data *getRoutine() { return getDescAt(1); } + public: + virtual Data *data(); - /// Get the idx argument of the routine input argument list. - /// - Data *getArgumentAt(int idx) { return getDescAt(idx + 2); } + /// + /// \brief TreeNode constructor + /// \param nid node id (required) + /// \param tree the tree that this node belongs to + /// + TreeNode(int nid, Tree *tree, Data *units = 0, Data *error = 0, + Data *help = 0, Data *validation = 0); + TreeNode() { tree = 0; } + ~TreeNode(); + // Force new and delete in dll for windows + void *operator new(size_t sz); + void operator delete(void *p); - /// Set the call image. The image is usually a string that specifies the - /// current path to find the library that contains the symbol to be called. - /// - void setImage(Data *image) { assignDescAt(image, 0); } + /// Get the associated tree instance + virtual Tree *getTree() { return tree; } - /// Set the routine that the Call instance will look for in the image. This - /// is usually a string containing the symbol within the image library. - /// \note MDSplus does not manages the symbol mangling used by compilers to - /// identify class member functions, so that only C compiled function will - /// be reached by Call. - /// - void setRoutine(Data *routine) { assignDescAt(routine, 1); } + /// Set the associated Tree instance + virtual void setTree(Tree *tree); + + /// Get the path name for this node + virtual char *getPath(); + + /// Get the minimum path name for this node + /// \ref getNci() with Nci code NciMINPATH + virtual char *getMinPath(); + + /// Get the full path name for this node + /// \ref getNci() with code NciFULLPATH + virtual char *getFullPath(); + + /// Get the name of this node + /// \ref getNci() with code NciNODE_NAME + virtual char *getNodeName(); + + /// Get the original path within the conglomerate to which the node belongs + /// \ref getNci() with code NciORIGINAL_PART_NAME + virtual char *getOriginalPartName(); + + /// %String output version of getPath() + virtual std::string getPathStr(); + + /// %String output version of getMinPath() + virtual std::string getMinPathStr(); + + /// %String output version of getFullPath() + virtual std::string getFullPathStr(); + + /// %String output version of getNodeName() + virtual std::string getNodeNameStr(); + + /// %String output version of getOriginalPartName() + virtual std::string getOriginalPartNameStr(); + + /// Retrieve node from this tree by its realPath string + virtual TreeNode *getNode(char const *relPath); + + /// Retrieve node from this tree by its realPath string + virtual TreeNode *getNode(String *relPathStr); + + // Retrieve node from this tree by its realPath string with a wild card + virtual TreeNodeArray *getNodeWild(char const *path, int usageMask); + virtual TreeNodeArray *getNodeWild(char const *path); + + virtual Data *getData(); + virtual void putData(Data *data); + virtual void deleteData(); + + /// virtual function to resolve node id in the active tree. + /// This is called each time a path to nid conversion is needed. + virtual void resolveNid() {} + + virtual int getNid() { return nid; } + + /// Returns true if the node is On + virtual bool isOn(); + + /// Set on/off for that node + virtual void setOn(bool on); + + /// Return the length in bytes of the contained data. + /// \ref getNci() with code NciLENGTH + virtual int getLength(); + + /// Return the size in bytes of (possibly compressed) associated data. + /// \ref getNci() with code NciRLENGTH + virtual int getCompressedLength(); + + /// Return the Group/Id of the last writer for that node. + /// \ref getNci() with code NciOWNER_ID + virtual int getOwnerId(); + + /// Return the status of the completed action (if the node contains + /// ActionData). \ref getNci() with code NciSTATUSNciSTATUS + virtual int getStatus(); + + /// Get the time of the last data insertion + /// \ref getNci() with code NciTIME_INSERTED + virtual int64_t getTimeInserted(); + + /// Do specified method for this node (valid only if it belongs to a + /// conglomerate) + virtual void doMethod(char *method); + + /// Return true if this is setup data (i.e. present in the the model) + virtual bool isSetup(); + + ///@{ + /// Nci Flags access + virtual bool isWriteOnce(); + virtual void setWriteOnce(bool flag); + virtual bool isCompressOnPut(); + virtual void setCompressOnPut(bool flag); + virtual bool isNoWriteModel(); + virtual void setNoWriteModel(bool flag); + virtual bool isNoWriteShot(); + virtual void setNoWriteShot(bool flag); + virtual bool isEssential(); + virtual void setEssential(bool flag); + virtual bool isIncludedInPulse(); + virtual void setIncludedInPulse(bool flag); + virtual bool isIncludeInPulse(); + virtual void setIncludeInPulse(bool flag); + virtual bool isMember(); + virtual bool isChild(); + ///@} + + /// Extended attribute getter/setter + virtual Data *getExtendedAttribute(const char *name); + virtual Data *getExtendedAttribute(std::string name); + virtual void setExtendedAttribute(const char *name, Data *data); + virtual void setExtendedAttribute(std::string name, Data *data); + + /// Get the parent of this node. + /// Ref to \ref getNci() with code NciPARENT + virtual TreeNode *getParent(); + + /// Return next sibling. + /// Ref to \ref getNci() with code NciBROTHER + virtual TreeNode *getBrother(); + + /// Get the first child of this node. + /// Ref to \ref getNci() with code NciCHILD + virtual TreeNode *getChild(); + + /// Get the first member of this node. + /// Ref to \ref getNci() with code NciMEMBER + virtual TreeNode *getMember(); + + /// Get the number of members for this node. + /// Ref to \ref getNci() with code NciNUMBER_OF_MEMBERS + virtual int getNumMembers(); + + /// Get the number of children for this node. + /// Ref to \ref getNci() with code NciNUMBER_OF_CHILDREN + virtual int getNumChildren(); + + /// Get the number of all descendants (members + children)fir this node. + /// Ref to \ref getNci with codes NciNUMBER_OF_MEMBERS and + /// NciNUMBER_OF_MEMBERS + virtual int getNumDescendants(); + + // NOTE: [andrea] java implementation discrepancy (java uses TreeNodeArray + // instance) + /// Get all che child nodes for this node. + virtual TreeNode **getChildren(int *numChildren); + + /// Return all the members of this node + virtual TreeNode **getMembers(int *numChildren); + + /// Get all the descendant (members + children)for this node + virtual TreeNode **getDescendants(int *numChildren); + + /// Return Nci class name (NciCLASS) as c string + virtual const char *getClass(); + + /// Return Nci descriptor type (NciDTYPE) as c string + virtual const char *getDType(); + + /// Return Nci node usage (NciUSAGE) as c string + virtual const char *getUsage(); + + /// Get index of the node in the corresponding conglomerate. + /// Ref to \ref getNci() with code NciCONGLOMERATE_ELT + virtual int getConglomerateElt(); + + /// Return the number of the elements for the conglomerate to which the node + /// belongs + virtual int getNumElts(); + + /// Return the array of nodes corresponding to the elements of the + /// conglomeate to which the node belongs + virtual TreeNodeArray *getConglomerateNodes(); + + /// Return the depth of the node in the tree. + /// Ref to \ref getNci() with code NciDEPTH + virtual int getDepth(); + + /// Return true if the node contains versions (Nci flags) + virtual bool containsVersions(); + + // SEGMENTS // + + // NOTE: [andrea] there are missed members ( vs java impl ) + /// Begin a new data segment + virtual void beginSegment(Data *start, Data *end, Data *time, + Array *initialData); + /// Begin and fill a new data segment + virtual void makeSegment(Data *start, Data *end, Data *time, + Array *initialData); + + // Begin and fill a new data segment. At the same time make a resampled minmax + // version (two samples (min and max) every 100 original samples) + virtual void makeSegmentMinMax(Data *start, Data *end, Data *time, + Array *initialData, TreeNode *resampledNode, + int resFactor = 100); - /// Set the idx argument of the routine input argument list. - /// - void setArgumentAt(Data *argument, int idx) { - assignDescAt(argument, 2 + idx); - } -}; + // Begin and fill a new data segment. At the same time make a resampled + // version + virtual void makeSegmentResampled(Data *start, Data *end, Data *time, + Array *initialData, TreeNode *resampledNode, + int resFactor = 100); -//////////////////////////////////////////////////////////////////////////////// -// APD DATA ////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + // Begin and fill a new data segment. At the same time make a resampled minmax + // version (two samples (min and max) every 100 original samples) + virtual void beginSegmentMinMax(Data *start, Data *end, Data *time, + Array *initialData, TreeNode *resampledNode, + int resFactor = 100); -/// -/// \brief The Apd class object description of DTYPE_DSC -/// + // Begin and fill a new data segment. At the same time make a resampled + // version + virtual void beginSegmentResampled(Data *start, Data *end, Data *time, + Array *initialData, + TreeNode *resampledNode, + int resFactor = 100); -class EXPORT Apd : public Data { -public: - Apd(Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) { - clazz = CLASS_APD; - dtype = DTYPE_DSC; - setAccessory(units, error, help, validation); - } - - Apd(std::size_t nData, Data **descs, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) { - clazz = CLASS_APD; - dtype = DTYPE_DSC; - for (std::size_t i = 0; i < nData; ++i) { - if (descs[i]) - descs[i]->incRefCount(); - this->descs.push_back(descs[i]); - } - setAccessory(units, error, help, validation); - } - - virtual void propagateDeletion() { - for (std::size_t i = 0; i < descs.size(); ++i) { - if (descs[i]) { - descs[i]->decRefCount(); - deleteData(descs[i]); - } - } - } + /// Write (part of) data segment + virtual void putSegment(Array *data, int ofs); - virtual ~Apd() { propagateDeletion(); } + /// Write (part of) data segment + virtual void putSegmentResampled(Array *data, int ofs, + TreeNode *resampledNode, + int resFactor = 100); - virtual std::size_t len() { return descs.size(); } + /// Write (part of) data segment + virtual void putSegmentMinMax(Array *data, int ofs, TreeNode *resampledNode, + int resFactor = 100); - Data **getDscs() { return &descs[0]; } + /// Update start, end time and dimension for the last segment + virtual void updateSegment(Data *start, Data *end, Data *time); - std::size_t getDimension() { return Apd::len(); } + /// Update start, end time and dimension for the specified segment + virtual void updateSegment(int idx, Data *start, Data *end, Data *time); - Data **getDscArray() { return getDscs(); } + /// Get the number of segments + virtual int getNumSegments(); - Data *getDescAt(std::size_t i) { - // descs.at(i)->incRefCount(); - return descs.at(i); - } + /// Instantiate two arrays with Segments starts and ends + virtual void getSegmentLimits(int segmentIdx, Data **start, Data **end); - bool hasDescAt(std::size_t i) { return descs.size() > i && descs[i] != NULL; } - void setDescAt(std::size_t i, Data *data) { - if (descs.size() <= i) { - for (size_t j = descs.size(); j < i; j++) - descs.push_back(NULL); - descs.push_back(data); - } else - // INSERT AND BEGIN() WORK ONLY IF VECTOR NON EMPTY!! - descs.insert(descs.begin() + i, data); - // data->incRefCount(); - } - void appendDesc(Data *data) { - descs.push_back(data); - // if(data) data->incRefCount(); - } - void *convertToDsc(); - -protected: - std::vector descs; -}; - -//////////////////////////////////////////////////////////////////////////////// -// LIST DATA ///////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -class EXPORT List : public Apd { -public: - List(Data *units = 0, Data *error = 0, Data *help = 0, Data *validation = 0) - : Apd(units, error, help, validation) { - dtype = DTYPE_LIST; - } - - List(int nData, Data **descs, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) - : Apd(nData, descs, units, error, help, validation) { - dtype = DTYPE_LIST; - } - - void append(Data *data) { appendDesc(data); } - - void remove(Data *data) { - descs.erase(std::remove(descs.begin(), descs.end(), data), descs.end()); - data->decRefCount(); - } - - void remove(std::size_t i) { - descs.at(i)->decRefCount(); - descs.erase(descs.begin() + i); - } - - void insert(std::size_t i, Data *data) { - descs.insert(descs.begin() + i, data); - data->incRefCount(); - } - - Data *getElementAt(std::size_t i) { - descs.at(i)->incRefCount(); - return descs[i]; - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// DICTIONARY DATA /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -class EXPORT Dictionary : public Apd { -public: - Dictionary(Data *units = 0, Data *error = 0, Data *help = 0, - Data *validation = 0) - : Apd(units, error, help, validation) { - dtype = DTYPE_DICTIONARY; - } - - Dictionary(int nData, Data **descs, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0) - : Apd(nData, descs, units, error, help, validation) { - dtype = DTYPE_DICTIONARY; - } - - Data *getItem(String *strData) { - for (std::size_t i = 0; i < descs.size(); i += 2) { - if (strData->equals(descs[i])) { - descs[i + 1]->incRefCount(); - return descs[i + 1]; - } - } - return 0; - } + /// Get data form the selected segment + virtual Array *getSegment(int segIdx); - void setItem(String *strData, Data *data) { - for (std::size_t i = 0; i < descs.size(); i += 2) { - if (strData->equals(descs[i])) { - descs[i]->decRefCount(); - descs[i] = strData; - strData->incRefCount(); + /// Get the selected segment dimension + virtual Data *getSegmentDim(int segIdx); - descs[i + 1]->decRefCount(); - descs[i + 1] = data; - data->incRefCount(); - return; - } - } + /// Get both segment and segment dimension + virtual void getSegmentAndDimension(int segIdx, Array *&segment, + Data *&dimension); - descs.push_back(strData); - descs.push_back(data); - strData->incRefCount(); - data->incRefCount(); - } + /// Set scale for segmented Node + virtual void setSegmentScale(Data *scale); - std::size_t len() { return Apd::len() / 2; } -}; + /// Get scale of segmented Node + virtual Data *getSegmentScale(); -//////////////////////////////////////////////////////////////////////////////// -// TREE DATA //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + /// Begin a timestamted segment + virtual void beginTimestampedSegment(Array *initData); -class Tree; -class TreeNode; -class TreeNodeArray; + /// Make a timestamped segment + virtual void makeTimestampedSegment(Array *data, int64_t *times); -/// -/// \brief The TreeNode class object description of DTYPE_NID -/// -class EXPORT TreeNode : public Data { - friend EXPORT std::ostream &operator<<(std::ostream &stream, - TreeNode *treeNode) { - stream << treeNode->getFullPathStr(); - return stream; - } + /// Write (part of) data in a timestamped segment + virtual void putTimestampedSegment(Array *data, int64_t *times); -protected: - Tree *tree; - int nid; + /// Writre a single row of timestamped data + virtual void putRow(Data *data, int64_t *time, int size = 1024); - // From Data - virtual bool isImmutable() { return false; } - virtual void *convertToDsc(); - virtual bool getFlag(int flagOfs); - virtual void setFlag(int flagOfs, bool val); + /// Get info for the node identified by sefIdx, or the last node if -1 is + /// passed as segIdx argument. The function returns dtype of the contained + /// data and the row dimensions. The function provides: In dimct the number + /// of dimensions is stored, in dims the array of dimensions, in nextRow + /// the position of the next free row. The dims always reflects the segment + /// dimension passed by beginSegment while the next will get the current + /// position reached in this segment by the putSegment function. + /// + /// \note dtype, dimct and nextRow are pointer of size 1 array, while the + /// dims dimension must be allocated array of size 8 integers! Furthermore, + /// at the time of writing the returned dims are actually written int + /// reverse order for a mismatch in the row/column order within the treeshr + /// library + /// + virtual void getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, + int *nextRow); - virtual char getNciChar(int itm); - virtual int getNciInt(int itm); - virtual int64_t getNciInt64(int itm); - virtual std::string getNciString(int itm); + /// Retrieve node tags as array of strings + virtual StringArray *findTags(); -public: - virtual Data *data(); + // EDIT METHODS // - /// - /// \brief TreeNode constructor - /// \param nid node id (required) - /// \param tree the tree that this node belongs to - /// - TreeNode(int nid, Tree *tree, Data *units = 0, Data *error = 0, - Data *help = 0, Data *validation = 0); - TreeNode() { tree = 0; } - ~TreeNode(); - // Force new and delete in dll for windows - void *operator new(size_t sz); - void operator delete(void *p); + /// This method adds a new node to the tree that this instance belongs to. + /// The name specifies the relative or the full path of the new node and + /// the usage is a string that defines the type of the new node. See \ref + /// Tree::addNode for reference. If the relative path is chosen the new + /// node will be set as child/member of the current. + /// + virtual TreeNode *addNode(char const *name, char const *usage); - /// Get the associated tree instance - virtual Tree *getTree() { return tree; } + /// This removes a node indentified by its path from the tree that holds the + /// current node instance. See \ref Tree::remove() for reference. + /// + virtual void remove(char const *name); - /// Set the associated Tree instance - virtual void setTree(Tree *tree); - - /// Get the path name for this node - virtual char *getPath(); - - /// Get the minimum path name for this node - /// \ref getNci() with Nci code NciMINPATH - virtual char *getMinPath(); - - /// Get the full path name for this node - /// \ref getNci() with code NciFULLPATH - virtual char *getFullPath(); - - /// Get the name of this node - /// \ref getNci() with code NciNODE_NAME - virtual char *getNodeName(); - - /// Get the original path within the conglomerate to which the node belongs - /// \ref getNci() with code NciORIGINAL_PART_NAME - virtual char *getOriginalPartName(); - - /// %String output version of getPath() - virtual std::string getPathStr(); - - /// %String output version of getMinPath() - virtual std::string getMinPathStr(); - - /// %String output version of getFullPath() - virtual std::string getFullPathStr(); - - /// %String output version of getNodeName() - virtual std::string getNodeNameStr(); - - /// %String output version of getOriginalPartName() - virtual std::string getOriginalPartNameStr(); - - /// Retrieve node from this tree by its realPath string - virtual TreeNode *getNode(char const *relPath); - - /// Retrieve node from this tree by its realPath string - virtual TreeNode *getNode(String *relPathStr); - - // Retrieve node from this tree by its realPath string with a wild card - virtual TreeNodeArray *getNodeWild(char const *path, int usageMask); - virtual TreeNodeArray *getNodeWild(char const *path); - - virtual Data *getData(); - virtual void putData(Data *data); - virtual void deleteData(); - - /// virtual function to resolve node id in the active tree. - /// This is called each time a path to nid conversion is needed. - virtual void resolveNid() {} - - virtual int getNid() { return nid; } - - /// Returns true if the node is On - virtual bool isOn(); - - /// Set on/off for that node - virtual void setOn(bool on); - - /// Return the length in bytes of the contained data. - /// \ref getNci() with code NciLENGTH - virtual int getLength(); - - /// Return the size in bytes of (possibly compressed) associated data. - /// \ref getNci() with code NciRLENGTH - virtual int getCompressedLength(); - - /// Return the Group/Id of the last writer for that node. - /// \ref getNci() with code NciOWNER_ID - virtual int getOwnerId(); + /// Rename current node instance in tree setting a new path indentified by + /// the newName argument that must be in form of an absolute path string. + virtual void rename(std::string const &newName); - /// Return the status of the completed action (if the node contains - /// ActionData). \ref getNci() with code NciSTATUSNciSTATUS - virtual int getStatus(); + /// Move the node setting a new parent and changing the node name + virtual void move(TreeNode *parent, std::string const &newName); - /// Get the time of the last data insertion - /// \ref getNci() with code NciTIME_INSERTED - virtual int64_t getTimeInserted(); + /// Move the node setting a new parent. + virtual void move(TreeNode *parent); - /// Do specified method for this node (valid only if it belongs to a - /// conglomerate) - virtual void doMethod(char *method); + /// Add a device to the tree that holds current node instance. The argument + /// name will be the name of the new created device and the type will be + /// serched within the device library. See \ref Tree::addDevice for details. + /// + virtual TreeNode *addDevice(char const *name, char const *type); - /// Return true if this is setup data (i.e. present in the the model) - virtual bool isSetup(); - - ///@{ - /// Nci Flags access - virtual bool isWriteOnce(); - virtual void setWriteOnce(bool flag); - virtual bool isCompressOnPut(); - virtual void setCompressOnPut(bool flag); - virtual bool isNoWriteModel(); - virtual void setNoWriteModel(bool flag); - virtual bool isNoWriteShot(); - virtual void setNoWriteShot(bool flag); - virtual bool isEssential(); - virtual void setEssential(bool flag); - virtual bool isIncludedInPulse(); - virtual void setIncludedInPulse(bool flag); - virtual bool isIncludeInPulse(); - virtual void setIncludeInPulse(bool flag); - virtual bool isMember(); - virtual bool isChild(); - ///@} - - /// Extended attribute getter/setter - virtual Data *getExtendedAttribute(const char *name); - virtual Data *getExtendedAttribute(std::string name); - virtual void setExtendedAttribute(const char *name, Data *data); - virtual void setExtendedAttribute(std::string name, Data *data); - - /// Get the parent of this node. - /// Ref to \ref getNci() with code NciPARENT - virtual TreeNode *getParent(); - - /// Return next sibling. - /// Ref to \ref getNci() with code NciBROTHER - virtual TreeNode *getBrother(); - - /// Get the first child of this node. - /// Ref to \ref getNci() with code NciCHILD - virtual TreeNode *getChild(); - - /// Get the first member of this node. - /// Ref to \ref getNci() with code NciMEMBER - virtual TreeNode *getMember(); - - /// Get the number of members for this node. - /// Ref to \ref getNci() with code NciNUMBER_OF_MEMBERS - virtual int getNumMembers(); - - /// Get the number of children for this node. - /// Ref to \ref getNci() with code NciNUMBER_OF_CHILDREN - virtual int getNumChildren(); - - /// Get the number of all descendants (members + children)fir this node. - /// Ref to \ref getNci with codes NciNUMBER_OF_MEMBERS and - /// NciNUMBER_OF_MEMBERS - virtual int getNumDescendants(); - - // NOTE: [andrea] java implementation discrepancy (java uses TreeNodeArray - // instance) - /// Get all che child nodes for this node. - virtual TreeNode **getChildren(int *numChildren); - - /// Return all the members of this node - virtual TreeNode **getMembers(int *numChildren); - - /// Get all the descendant (members + children)for this node - virtual TreeNode **getDescendants(int *numChildren); - - /// Return Nci class name (NciCLASS) as c string - virtual const char *getClass(); - - /// Return Nci descriptor type (NciDTYPE) as c string - virtual const char *getDType(); - - /// Return Nci node usage (NciUSAGE) as c string - virtual const char *getUsage(); - - /// Get index of the node in the corresponding conglomerate. - /// Ref to \ref getNci() with code NciCONGLOMERATE_ELT - virtual int getConglomerateElt(); - - /// Return the number of the elements for the conglomerate to which the node - /// belongs - virtual int getNumElts(); - - /// Return the array of nodes corresponding to the elements of the - /// conglomeate to which the node belongs - virtual TreeNodeArray *getConglomerateNodes(); - - /// Return the depth of the node in the tree. - /// Ref to \ref getNci() with code NciDEPTH - virtual int getDepth(); - - /// Return true if the node contains versions (Nci flags) - virtual bool containsVersions(); - - // SEGMENTS // - - // NOTE: [andrea] there are missed members ( vs java impl ) - /// Begin a new data segment - virtual void beginSegment(Data *start, Data *end, Data *time, - Array *initialData); - /// Begin and fill a new data segment - virtual void makeSegment(Data *start, Data *end, Data *time, - Array *initialData); - - // Begin and fill a new data segment. At the same time make a resampled minmax - // version (two samples (min and max) every 100 original samples) - virtual void makeSegmentMinMax(Data *start, Data *end, Data *time, - Array *initialData, TreeNode *resampledNode, - int resFactor = 100); - - // Begin and fill a new data segment. At the same time make a resampled - // version - virtual void makeSegmentResampled(Data *start, Data *end, Data *time, - Array *initialData, TreeNode *resampledNode, - int resFactor = 100); + /// Add a tag to the current tree that hold this instance pointing to this + /// node. See \ref Tree::addTag() for reference. + /// + virtual void addTag(std::string const &tagName); - // Begin and fill a new data segment. At the same time make a resampled minmax - // version (two samples (min and max) every 100 original samples) - virtual void beginSegmentMinMax(Data *start, Data *end, Data *time, - Array *initialData, TreeNode *resampledNode, - int resFactor = 100); + /// Removes a tag added to the current tree and indentified by tagName. + virtual void removeTag(std::string const &tagName); - // Begin and fill a new data segment. At the same time make a resampled - // version - virtual void beginSegmentResampled(Data *start, Data *end, Data *time, - Array *initialData, - TreeNode *resampledNode, - int resFactor = 100); + /// Set this node to be a subtree of the tree that holds it. + virtual void setSubtree(bool isSubtree); + }; - /// Write (part of) data segment - virtual void putSegment(Array *data, int ofs); + /////////////////End Class TreeTreeNode/////////////// - /// Write (part of) data segment - virtual void putSegmentResampled(Array *data, int ofs, - TreeNode *resampledNode, - int resFactor = 100); + /// + /// \brief The TreeNodeThinClient class provides (a subset of) TreeNode + /// functionality using thin client mddip connection + /// - /// Write (part of) data segment - virtual void putSegmentMinMax(Array *data, int ofs, TreeNode *resampledNode, - int resFactor = 100); + class EXPORT TreeNodeThinClient : public TreeNode + { + friend EXPORT std::ostream &operator<<(std::ostream &stream, + TreeNodeThinClient *treeNode) + { + stream << treeNode->getFullPathStr(); + return stream; + } - /// Update start, end time and dimension for the last segment - virtual void updateSegment(Data *start, Data *end, Data *time); + protected: + Connection *connection; + + // From Data + virtual bool isImmutable() { return false; } + // virtual void *convertToDsc(); Use superclass implementation + // bool getFlag(int flagOfs); Use superclass implementation + // void setFlag(int flagOfs, bool val); Use superclass implementation + virtual char getNciChar(int itm); + virtual int getNciInt(int itm); + virtual int64_t getNciInt64(int itm); + virtual std::string getNciString(int itm); + + public: + // virtual Data *data(); Use superclass implementation + + /// + /// \brief TreeNodeThinClient constructor + /// \param nid node id (required) + /// \param Connection the Connection object used to communicate to mdsip + /// server + /// + TreeNodeThinClient(int nid, Connection *connection, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0); + + /// Get the associated tree instance + virtual Tree *getTree() + { + throw MdsException("getTree() not supported for TreeNodeThinClient object"); + return NULL; + } - /// Update start, end time and dimension for the specified segment - virtual void updateSegment(int idx, Data *start, Data *end, Data *time); + /// Set the associated Tree instance + virtual void setTree(Tree *tree) + { + (void)tree; + throw MdsException("setTree() not supported for TreeNodeThinClient object"); + } - /// Get the number of segments - virtual int getNumSegments(); + /// Get the path name for this node + virtual char *getPath(); - /// Instantiate two arrays with Segments starts and ends - virtual void getSegmentLimits(int segmentIdx, Data **start, Data **end); + /// Get the minimum path name for this node + /// \ref getNci() with Nci code NciMINPATH + // virtual char *getMinPath(); Use superclass implementation - /// Get data form the selected segment - virtual Array *getSegment(int segIdx); + /// Get the full path name for this node + /// \ref getNci() with code NciFULLPATH + // virtual char *getFullPath(); Use superclass implementation - /// Get the selected segment dimension - virtual Data *getSegmentDim(int segIdx); + /// Get the name of this node + /// \ref getNci() with code NciNODE_NAME + // virtual char *getNodeName(); Use superclass implementation - /// Get both segment and segment dimension - virtual void getSegmentAndDimension(int segIdx, Array *&segment, - Data *&dimension); + /// Get the original path within the conglomerate to which the node belongs + /// \ref getNci() with code NciORIGINAL_PART_NAME + // virtual char *getOriginalPartName(); Use superclass implementation - /// Set scale for segmented Node - virtual void setSegmentScale(Data *scale); + /// %String output version of getPath() + // virtual std::string getPathStr(); Use superclass implementation - /// Get scale of segmented Node - virtual Data *getSegmentScale(); + /// %String output version of getMinPath() + // virtual std::string getMinPathStr(); Use superclass implementation - /// Begin a timestamted segment - virtual void beginTimestampedSegment(Array *initData); + /// %String output version of getFullPath() + // virtual std::string getFullPathStr(); Use superclass implementation - /// Make a timestamped segment - virtual void makeTimestampedSegment(Array *data, int64_t *times); + /// %String output version of getNodeName() + // virtual std::string getNodeNameStr(); Use superclass implementation - /// Write (part of) data in a timestamped segment - virtual void putTimestampedSegment(Array *data, int64_t *times); + /// %String output version of getOriginalPartName() + // virtual std::string getOriginalPartNameStr(); Use superclass + // implementation - /// Writre a single row of timestamped data - virtual void putRow(Data *data, int64_t *time, int size = 1024); + /// Retrieve node from this tree by its realPath string + virtual TreeNode *getNode(char const *relPath) + { + (void)relPath; + throw MdsException("getNode() not supported for TreeNodeThinClient object"); + return NULL; + } + /// Retrieve node from this tree by its realPath string + virtual TreeNode *getNode(String *relPathStr) + { + (void)relPathStr; + throw MdsException("getNode() not supported for TreeNodeThinClient object"); + return NULL; + } - /// Get info for the node identified by sefIdx, or the last node if -1 is - /// passed as segIdx argument. The function returns dtype of the contained - /// data and the row dimensions. The function provides: In dimct the number - /// of dimensions is stored, in dims the array of dimensions, in nextRow - /// the position of the next free row. The dims always reflects the segment - /// dimension passed by beginSegment while the next will get the current - /// position reached in this segment by the putSegment function. - /// - /// \note dtype, dimct and nextRow are pointer of size 1 array, while the - /// dims dimension must be allocated array of size 8 integers! Furthermore, - /// at the time of writing the returned dims are actually written int - /// reverse order for a mismatch in the row/column order within the treeshr - /// library - /// - virtual void getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, - int *nextRow); + virtual Data *getData(); + virtual void putData(Data *data); + virtual void deleteData(); - /// Retrieve node tags as array of strings - virtual StringArray *findTags(); + /// virtual function to resolve node id in the active tree. + /// This is called each time a path to nid conversion is needed. + virtual void resolveNid() {} - // EDIT METHODS // + virtual int getNid() { return nid; } - /// This method adds a new node to the tree that this instance belongs to. - /// The name specifies the relative or the full path of the new node and - /// the usage is a string that defines the type of the new node. See \ref - /// Tree::addNode for reference. If the relative path is chosen the new - /// node will be set as child/member of the current. - /// - virtual TreeNode *addNode(char const *name, char const *usage); + /// Returns true if the node is On + virtual bool isOn(); - /// This removes a node indentified by its path from the tree that holds the - /// current node instance. See \ref Tree::remove() for reference. - /// - virtual void remove(char const *name); + /// Set on/off for that node + virtual void setOn(bool on); - /// Rename current node instance in tree setting a new path indentified by - /// the newName argument that must be in form of an absolute path string. - virtual void rename(std::string const &newName); + /// Return the length in bytes of the contained data. + /// \ref getNci() with code NciLENGTH + // virtual int getLength(); Use superclass implementation - /// Move the node setting a new parent and changing the node name - virtual void move(TreeNode *parent, std::string const &newName); + virtual int getCompressedLength() + { + throw MdsException( + "getCompressedLength() not supported for TreeNodeThinClient object"); + } - /// Move the node setting a new parent. - virtual void move(TreeNode *parent); + /// Return the Group/Id of the last writer for that node. + /// \ref getNci() with code NciOWNER_ID + // virtual int getOwnerId(); Use superclass implementation + + /// Return the status of the completed action (if the node contains + /// ActionData). \ref getNci() with code NciSTATUSNciSTATUS + // virtual int getStatus(); Use superclass implementation + + /// Get the time of the last data insertion + /// \ref getNci() with code NciTIME_INSERTED + // virtual int64_t getTimeInserted(); Use superclass implementation + + /// Do specified method for this node (valid only if it belongs to a + /// conglomerate) + virtual void doMethod(char *method) + { + (void)method; + throw MdsException( + "doMethod() not supported for TreeNodeThinClient object"); + } - /// Add a device to the tree that holds current node instance. The argument - /// name will be the name of the new created device and the type will be - /// serched within the device library. See \ref Tree::addDevice for details. - /// - virtual TreeNode *addDevice(char const *name, char const *type); + /// Return true if this is setup data (i.e. present in the the model) + // virtual bool isSetup(); Use superclass implementation + + ///@{ + /// Nci Flags access + // virtual bool isWriteOnce(); Use superclass implementation + // virtual void setWriteOnce(bool flag); Use superclass implementation + // virtual bool isCompressOnPut(); Use superclass implementation + // virtual void setCompressOnPut(bool flag); Use superclass implementation + // virtual bool isNoWriteModel(); Use superclass implementation + // virtual void setNoWriteModel(bool flag); Use superclass implementation + // virtual bool isNoWriteShot(); Use superclass implementation + // virtual void setNoWriteShot(bool flag); Use superclass implementation + // virtual bool isEssential(); Use superclass implementation + // virtual void setEssential(bool flag); + // virtual bool isIncludedInPulse(); Use superclass implementation + // virtual void setIncludedInPulse(bool flag); Use superclass implementation + // virtual bool isIncludeInPulse(); Use superclass implementation + // virtual void setIncludeInPulse(bool flag); Use superclass implementation + // virtual bool isMember(); Use superclass implementation + // virtual bool isChild(); Use superclass implementation + ///@} + + /// Get the parent of this node. + /// Ref to \ref getNci() with code NciPARENT + virtual TreeNode *getParent() + { + throw MdsException( + "getParent() not supported for TreeNodeThinClient object"); + } - /// Add a tag to the current tree that hold this instance pointing to this - /// node. See \ref Tree::addTag() for reference. - /// - virtual void addTag(std::string const &tagName); + /// Return next sibling. + /// Ref to \ref getNci() with code NciBROTHER + virtual TreeNode *getBrother() + { + throw MdsException( + "getBrother() not supported for TreeNodeThinClient object"); + } - /// Removes a tag added to the current tree and indentified by tagName. - virtual void removeTag(std::string const &tagName); + /// Get the first child of this node. + /// Ref to \ref getNci() with code NciCHILD + virtual TreeNode *getChild() + { + throw MdsException( + "getChild() not supported for TreeNodeThinClient object"); + } - /// Set this node to be a subtree of the tree that holds it. - virtual void setSubtree(bool isSubtree); -}; + /// Get the first member of this node. + /// Ref to \ref getNci() with code NciMEMBER + virtual TreeNode *getMember() + { + throw MdsException( + "getMember() not supported for TreeNodeThinClient object"); + } -/////////////////End Class TreeTreeNode/////////////// + /// Get the number of members for this node. + /// Ref to \ref getNci() with code NciNUMBER_OF_MEMBERS + // virtual int getNumMembers(); Use superclass implementation + + /// Get the number of children for this node. + /// Ref to \ref getNci() with code NciNUMBER_OF_CHILDREN + // virtual int getNumChildren(); Use superclass implementation + + /// Get the number of all descendants (members + children)fir this node. + /// Ref to \ref getNci with codes NciNUMBER_OF_MEMBERS and + /// NciNUMBER_OF_MEMBERS + // virtual int getNumDescendants(); Use superclass implementation + + // NOTE: [andrea] java implementation discrepancy (java uses TreeNodeArray + // instance) + /// Get all che child nodes for this node. + virtual TreeNode **getChildren(int *numChildren) + { + (void)numChildren; + throw MdsException( + "getChildren() not supported for TreeNodeThinClient object"); + } -/// -/// \brief The TreeNodeThinClient class provides (a subset of) TreeNode -/// functionality using thin client mddip connection -/// + /// Return all the members of this node + virtual TreeNode **getMembers(int *numChildren) + { + (void)numChildren; + throw MdsException( + "getMembers() not supported for TreeNodeThinClient object"); + } -class EXPORT TreeNodeThinClient : public TreeNode { - friend EXPORT std::ostream &operator<<(std::ostream &stream, - TreeNodeThinClient *treeNode) { - stream << treeNode->getFullPathStr(); - return stream; - } - -protected: - Connection *connection; - - // From Data - virtual bool isImmutable() { return false; } - // virtual void *convertToDsc(); Use superclass implementation - // bool getFlag(int flagOfs); Use superclass implementation - // void setFlag(int flagOfs, bool val); Use superclass implementation - virtual char getNciChar(int itm); - virtual int getNciInt(int itm); - virtual int64_t getNciInt64(int itm); - virtual std::string getNciString(int itm); - -public: - // virtual Data *data(); Use superclass implementation - - /// - /// \brief TreeNodeThinClient constructor - /// \param nid node id (required) - /// \param Connection the Connection object used to communicate to mdsip - /// server - /// - TreeNodeThinClient(int nid, Connection *connection, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0); - - /// Get the associated tree instance - virtual Tree *getTree() { - throw MdsException("getTree() not supported for TreeNodeThinClient object"); - return NULL; - } - - /// Set the associated Tree instance - virtual void setTree(Tree *tree) { - (void)tree; - throw MdsException("setTree() not supported for TreeNodeThinClient object"); - } - - /// Get the path name for this node - virtual char *getPath(); - - /// Get the minimum path name for this node - /// \ref getNci() with Nci code NciMINPATH - // virtual char *getMinPath(); Use superclass implementation - - /// Get the full path name for this node - /// \ref getNci() with code NciFULLPATH - // virtual char *getFullPath(); Use superclass implementation - - /// Get the name of this node - /// \ref getNci() with code NciNODE_NAME - // virtual char *getNodeName(); Use superclass implementation - - /// Get the original path within the conglomerate to which the node belongs - /// \ref getNci() with code NciORIGINAL_PART_NAME - // virtual char *getOriginalPartName(); Use superclass implementation - - /// %String output version of getPath() - // virtual std::string getPathStr(); Use superclass implementation - - /// %String output version of getMinPath() - // virtual std::string getMinPathStr(); Use superclass implementation - - /// %String output version of getFullPath() - // virtual std::string getFullPathStr(); Use superclass implementation - - /// %String output version of getNodeName() - // virtual std::string getNodeNameStr(); Use superclass implementation - - /// %String output version of getOriginalPartName() - // virtual std::string getOriginalPartNameStr(); Use superclass - // implementation - - /// Retrieve node from this tree by its realPath string - virtual TreeNode *getNode(char const *relPath) { - (void)relPath; - throw MdsException("getNode() not supported for TreeNodeThinClient object"); - return NULL; - } - /// Retrieve node from this tree by its realPath string - virtual TreeNode *getNode(String *relPathStr) { - (void)relPathStr; - throw MdsException("getNode() not supported for TreeNodeThinClient object"); - return NULL; - } - - virtual Data *getData(); - virtual void putData(Data *data); - virtual void deleteData(); - - /// virtual function to resolve node id in the active tree. - /// This is called each time a path to nid conversion is needed. - virtual void resolveNid() {} - - virtual int getNid() { return nid; } - - /// Returns true if the node is On - virtual bool isOn(); - - /// Set on/off for that node - virtual void setOn(bool on); - - /// Return the length in bytes of the contained data. - /// \ref getNci() with code NciLENGTH - // virtual int getLength(); Use superclass implementation - - virtual int getCompressedLength() { - throw MdsException( - "getCompressedLength() not supported for TreeNodeThinClient object"); - } - - /// Return the Group/Id of the last writer for that node. - /// \ref getNci() with code NciOWNER_ID - // virtual int getOwnerId(); Use superclass implementation - - /// Return the status of the completed action (if the node contains - /// ActionData). \ref getNci() with code NciSTATUSNciSTATUS - // virtual int getStatus(); Use superclass implementation - - /// Get the time of the last data insertion - /// \ref getNci() with code NciTIME_INSERTED - // virtual int64_t getTimeInserted(); Use superclass implementation - - /// Do specified method for this node (valid only if it belongs to a - /// conglomerate) - virtual void doMethod(char *method) { - (void)method; - throw MdsException( - "doMethod() not supported for TreeNodeThinClient object"); - } - - /// Return true if this is setup data (i.e. present in the the model) - // virtual bool isSetup(); Use superclass implementation - - ///@{ - /// Nci Flags access - // virtual bool isWriteOnce(); Use superclass implementation - // virtual void setWriteOnce(bool flag); Use superclass implementation - // virtual bool isCompressOnPut(); Use superclass implementation - // virtual void setCompressOnPut(bool flag); Use superclass implementation - // virtual bool isNoWriteModel(); Use superclass implementation - // virtual void setNoWriteModel(bool flag); Use superclass implementation - // virtual bool isNoWriteShot(); Use superclass implementation - // virtual void setNoWriteShot(bool flag); Use superclass implementation - // virtual bool isEssential(); Use superclass implementation - // virtual void setEssential(bool flag); - // virtual bool isIncludedInPulse(); Use superclass implementation - // virtual void setIncludedInPulse(bool flag); Use superclass implementation - // virtual bool isIncludeInPulse(); Use superclass implementation - // virtual void setIncludeInPulse(bool flag); Use superclass implementation - // virtual bool isMember(); Use superclass implementation - // virtual bool isChild(); Use superclass implementation - ///@} - - /// Get the parent of this node. - /// Ref to \ref getNci() with code NciPARENT - virtual TreeNode *getParent() { - throw MdsException( - "getParent() not supported for TreeNodeThinClient object"); - } - - /// Return next sibling. - /// Ref to \ref getNci() with code NciBROTHER - virtual TreeNode *getBrother() { - throw MdsException( - "getBrother() not supported for TreeNodeThinClient object"); - } - - /// Get the first child of this node. - /// Ref to \ref getNci() with code NciCHILD - virtual TreeNode *getChild() { - throw MdsException( - "getChild() not supported for TreeNodeThinClient object"); - } - - /// Get the first member of this node. - /// Ref to \ref getNci() with code NciMEMBER - virtual TreeNode *getMember() { - throw MdsException( - "getMember() not supported for TreeNodeThinClient object"); - } - - /// Get the number of members for this node. - /// Ref to \ref getNci() with code NciNUMBER_OF_MEMBERS - // virtual int getNumMembers(); Use superclass implementation - - /// Get the number of children for this node. - /// Ref to \ref getNci() with code NciNUMBER_OF_CHILDREN - // virtual int getNumChildren(); Use superclass implementation - - /// Get the number of all descendants (members + children)fir this node. - /// Ref to \ref getNci with codes NciNUMBER_OF_MEMBERS and - /// NciNUMBER_OF_MEMBERS - // virtual int getNumDescendants(); Use superclass implementation - - // NOTE: [andrea] java implementation discrepancy (java uses TreeNodeArray - // instance) - /// Get all che child nodes for this node. - virtual TreeNode **getChildren(int *numChildren) { - (void)numChildren; - throw MdsException( - "getChildren() not supported for TreeNodeThinClient object"); - } - - /// Return all the members of this node - virtual TreeNode **getMembers(int *numChildren) { - (void)numChildren; - throw MdsException( - "getMembers() not supported for TreeNodeThinClient object"); - } - - /// Get all the descendant (members + children)for this node - virtual TreeNode **getDescendants(int *numChildren) { - (void)numChildren; - throw MdsException( - "getDescendants() not supported for TreeNodeThinClient object"); - } - - /// Return Nci class name (NciCLASS) as c string - // virtual const char *getClass(); Use superclass implementation - - /// Return Nci descriptor type (NciDTYPE) as c string - // virtual const char *getDType(); Use superclass implementation - - /// Return Nci node usage (NciUSAGE) as c string - // virtual const char *getUsage(); Use superclass implementation - - /// Get index of the node in the corresponding conglomerate. - /// Ref to \ref getNci() with code NciCONGLOMERATE_ELT - // virtual int getConglomerateElt(); Use superclass implementation - - /// Return the number of the elements for the conglomerate to which the node - /// belongs - // virtual int getNumElts(); Use superclass implementation - - /// Return the array of nodes corresponding to the elements of the - /// conglomeate to which the node belongs - virtual TreeNodeArray *getConglomerateNodes() { - throw MdsException( - "getConglomerateNodes() not supported for TreeNodeThinClient object"); - } - - /// Return the depth of the node in the tree. - /// Ref to \ref getNci() with code NciDEPTH - // virtual int getDepth(); Use superclass implementation - - /// Return true if the node contains versions (Nci flags) - // virtual bool containsVersions(); Use superclass implementation - - // SEGMENTS // - - // NOTE: [andrea] there are missed members ( vs java impl ) - /// Begin a new data segment - virtual void beginSegment(Data *start, Data *end, Data *time, - Array *initialData); - /// Begin and fill a new data segment - virtual void makeSegment(Data *start, Data *end, Data *time, - Array *initialData); - - // Begin and fill a new data segment. At the same time make a resampled minmax - // version (two samples (min and max) every 100 original samples) - virtual void makeSegmentMinMax(Data *start, Data *end, Data *time, - Array *initialData, TreeNode *resampledNode, - int resFactor = 100) { - (void)start; - (void)end; - (void)time; - (void)initialData; - (void)resampledNode; - (void)resFactor; - throw MdsException( - "makeSegmentMinMax() not supported for TreeNodeThinClient object"); - } - // Begin and fill a new data segment. At the same time make a resampled - // version - virtual void makeSegmentResampled(Data *start, Data *end, Data *time, - Array *initialData, - TreeNode *resampledNode) { - (void)start; - (void)end; - (void)initialData; - (void)time; - (void)resampledNode; - throw MdsException( - "makeSegmentResampled() not supported for TreeNodeThinClient object"); - } - - /// Write (part of) data segment - virtual void putSegment(Array *data, int ofs); - - /// Update start, end time and dimension for the last segment - virtual void updateSegment(Data *start, Data *end, Data *time) { - (void)start; - (void)end; - (void)time; - throw MdsException( - "updateSegment() not supported for TreeNodeThinClient object"); - } - - /// Update start, end time and dimension for the specified segment - virtual void updateSegment(int idx, Data *start, Data *end, Data *time) { - (void)idx; - (void)start; - (void)end; - (void)time; - throw MdsException( - "updateSegment() not supported for TreeNodeThinClient object"); - } - - /// Get the number of segments - virtual int getNumSegments(); - - /// Instantiate two arrays with Segments starts and ends - virtual void getSegmentLimits(int segmentIdx, Data **start, Data **end); - - /// Get data form the selected segment - virtual Array *getSegment(int segIdx); - - /// Get the selected segment dimension - virtual Data *getSegmentDim(int segIdx); - - /// Get both segment and segment dimension - virtual void getSegmentAndDimension(int segIdx, Array *&segment, - Data *&dimension); - - /// Begin a timestamted segment - virtual void beginTimestampedSegment(Array *initData); - - /// Make a timestamped segment - virtual void makeTimestampedSegment(Array *data, int64_t *times); - - /// Write (part of) data in a timestamped segment - virtual void putTimestampedSegment(Array *data, int64_t *times); - - /// Writre a single row of timestamped data - virtual void putRow(Data *data, int64_t *time, int size = 1024); - - /// Get info for the node identified by sefIdx, or the last node if -1 is - /// passed as segIdx argument. The function returns dtype of the contained - /// data and the row dimensions. The function provides: In dimct the number - /// of dimensions is stored, in dims the array of dimensions, in nextRow - /// the position of the next free row. The dims always reflects the segment - /// dimension passed by beginSegment while the next will get the current - /// position reached in this segment by the putSegment function. - /// - /// \note dtype, dimct and nextRow are pointer of size 1 array, while the - /// dims dimension must be allocated array of size 8 integers! Furthermore, - /// at the time of writing the returned dims are actually written int - /// reverse order for a mismatch in the row/column order within the treeshr - /// library - /// - virtual void getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, - int *nextRow) { - (void)segIdx; - (void)dtype; - (void)dimct; - (void)dims; - (void)nextRow; - throw MdsException( - "getSegmentInfo() not supported for TreeNodeThinClient object"); - } - - /// Retrieve node tags as array of strings - virtual StringArray *findTags(); - - // EDIT METHODS // - - /// This method adds a new node to the tree that this instance belongs to. - /// The name specifies the relative or the full path of the new node and - /// the usage is a string that defines the type of the new node. See \ref - /// Tree::addNode for reference. If the relative path is chosen the new - /// node will be set as child/member of the current. - /// - virtual TreeNode *addNode(char const *name, char const *usage) { - (void)name; - (void)usage; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// This removes a node indentified by its path from the tree that holds the - /// current node instance. See \ref Tree::remove() for reference. - /// - virtual void remove(char const *name) { - (void)name; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Rename current node instance in tree setting a new path indentified by - /// the newName argument that must be in form of an absolute path string. - virtual void rename(std::string const &newName) { - (void)newName; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Move the node setting a new parent and changing the node name - virtual void move(TreeNode *parent, std::string const &newName) { - (void)parent; - (void)newName; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Move the node setting a new parent. - virtual void move(TreeNode *parent) { - (void)parent; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Add a device to the tree that holds current node instance. The argument - /// name will be the name of the new created device and the type will be - /// serched within the device library. See \ref Tree::addDevice for details. - /// - virtual TreeNode *addDevice(char const *name, char const *type) { - (void)name; - (void)type; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Add a tag to the current tree that hold this instance pointing to this - /// node. See \ref Tree::addTag() for reference. - /// - virtual void addTag(std::string const &tagName) { - (void)tagName; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Removes a tag added to the current tree and indentified by tagName. - virtual void removeTag(std::string const &tagName) { - (void)tagName; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } - - /// Set this node to be a subtree of the tree that holds it. - virtual void setSubtree(bool isSubtree) { - (void)isSubtree; - throw MdsException( - "edit operations not supported for TreeNodeThinClient object"); - } -}; - -/////////////////End Class TreeNodeThinClient/////////////// - -class EXPORT TreePath : public TreeNode { -public: - TreePath(std::string const &path, Tree *tree, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0); - TreePath(char const *path, int len, Tree *tree, Data *units = 0, - Data *error = 0, Data *help = 0, Data *validation = 0); - void *convertToDsc(); - void resolveNid(); - -private: - std::string path; -}; - -////////////////Class TreeNodeArray/////////////////////// -class EXPORT TreeNodeArray { - TreeNode **nodes; - int numNodes; - -public: - void *operator new(size_t sz); - void operator delete(void *p); - TreeNodeArray(TreeNode **nodes, int numNodes); - TreeNodeArray(int *nids, int numNodes, Tree *tree); - ~TreeNodeArray(); - StringArray *getPath(); - StringArray *getFullPath(); - Int32Array *getNid(); - Int8Array *isOn(); - void setOn(Int8Array *info); - Int8Array *isSetup(); - Int8Array *isWriteOnce(); - void setWriteOnce(Int8Array *info); - Int8Array *isCompressOnPut(); - void setCompressOnPut(Int8Array *info); - Int8Array *isNoWriteModel(); - void setNoWriteModel(Int8Array *info); - Int8Array *isNoWriteShot(); - void setNoWriteShot(Int8Array *info); - Int32Array *getLength(); - Int32Array *getCompressedLength(); - StringArray *getUsage(); - int getNumNodes() { return numNodes; } - TreeNode *operator[](int idx) { - if (idx >= 0 && idx < numNodes) - return nodes[idx]; - else - return 0; - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// Tree ////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// MDSplus provides a data storage mechanism for recording a wide variety of -/// information pertaining to experiments or simulations including, but not -/// limited to, data acquisition settings, comments, physical measurements, -/// data acquisition and analysis task information and analysis results. -/// Keeping all this information organized can be difficult especially with -/// large experiments or codes where there may be many thousands of data items. -/// MDSplus provides a hierarchical tree structure in its data storage so that -/// users can organize their data much like one would organize files in a file -/// system with directories and subdirectories. -/// -/// A tree is a collection of nodes which describe something. All data in -/// MDSplus are stored in trees. There are two different kinds of nodes in the -/// MDSplus tree structure called members and children. One could consider -/// members to be similar to files in a file system while children are similar -/// to directories. Members normally contain data, (i.e. a measurement, a -/// calibration coefficient, a comment) while a child node, used for structure -/// only, cannot contain data. However, unlike a file system, both members and -/// children nodes can have subnodes of either members or children. -/// -/// Tree shots -/// ---------- -/// -/// The trees which contain the data pertaining to an experiment or simulation -/// are stored on an MDSplus server as files. Each tree consists of a model -/// (shot # -1) and one or more pulse files with positive shot numbers. Special -/// shot numbers: -/// -/// -1 - model -/// 0 - current shot -/// >1 - pulse files -/// + /// Get all the descendant (members + children)for this node + virtual TreeNode **getDescendants(int *numChildren) + { + (void)numChildren; + throw MdsException( + "getDescendants() not supported for TreeNodeThinClient object"); + } -class EXPORT Tree { - friend void setActiveTree(Tree *tree); - friend Tree *getActiveTree(); + /// Return Nci class name (NciCLASS) as c string + // virtual const char *getClass(); Use superclass implementation -protected: - std::string name; - int shot; - void *ctx; - bool fromActiveTree; + /// Return Nci descriptor type (NciDTYPE) as c string + // virtual const char *getDType(); Use superclass implementation -public: - /// Builds a new Tree object instance creating or attaching to the named - /// tree. The tree name has to match the path envoronment variable - /// xxx_path, and the shot is the shot number the Tree instance will point - /// to. - /// - Tree(char const *name, int shot); - Tree(char const *name, int shot, void *ctx); + /// Return Nci node usage (NciUSAGE) as c string + // virtual const char *getUsage(); Use superclass implementation - /// Builds a new Tree object instance creating or attaching to the named - /// tree. The tree name has to match the path envoronment variable - /// xxx_path, and the shot is the shot number the Tree instance will point - /// to. Four opening mode are availabe: - /// - /// | opening mode | description | - /// |--------------|-----------------------------------------------------------------| - /// | NEW | create new tree with target parse files if not present | - /// | EDIT | open tree in edit mode to access the tree structure for - /// writing | | READONLY | open tree in read only mode | | NORMAL | - /// set the tree for normal operations reading and writing data | - /// - Tree(char const *name, int shot, char const *mode); - Tree(Tree *tree); - ~Tree(); + /// Get index of the node in the corresponding conglomerate. + /// Ref to \ref getNci() with code NciCONGLOMERATE_ELT + // virtual int getConglomerateElt(); Use superclass implementation - void *operator new(size_t sz); - void operator delete(void *p); + /// Return the number of the elements for the conglomerate to which the node + /// belongs + // virtual int getNumElts(); Use superclass implementation - /// Set current shot number - static void setCurrent(char const *treeName, int shot); + /// Return the array of nodes corresponding to the elements of the + /// conglomeate to which the node belongs + virtual TreeNodeArray *getConglomerateNodes() + { + throw MdsException( + "getConglomerateNodes() not supported for TreeNodeThinClient object"); + } - /// Get current shot number - static int getCurrent(char const *treeName); + /// Return the depth of the node in the tree. + /// Ref to \ref getNci() with code NciDEPTH + // virtual int getDepth(); Use superclass implementation + + /// Return true if the node contains versions (Nci flags) + // virtual bool containsVersions(); Use superclass implementation + + // SEGMENTS // + + // NOTE: [andrea] there are missed members ( vs java impl ) + /// Begin a new data segment + virtual void beginSegment(Data *start, Data *end, Data *time, + Array *initialData); + /// Begin and fill a new data segment + virtual void makeSegment(Data *start, Data *end, Data *time, + Array *initialData); + + // Begin and fill a new data segment. At the same time make a resampled minmax + // version (two samples (min and max) every 100 original samples) + virtual void makeSegmentMinMax(Data *start, Data *end, Data *time, + Array *initialData, TreeNode *resampledNode, + int resFactor = 100) + { + (void)start; + (void)end; + (void)time; + (void)initialData; + (void)resampledNode; + (void)resFactor; + throw MdsException( + "makeSegmentMinMax() not supported for TreeNodeThinClient object"); + } + // Begin and fill a new data segment. At the same time make a resampled + // version + virtual void makeSegmentResampled(Data *start, Data *end, Data *time, + Array *initialData, + TreeNode *resampledNode) + { + (void)start; + (void)end; + (void)initialData; + (void)time; + (void)resampledNode; + throw MdsException( + "makeSegmentResampled() not supported for TreeNodeThinClient object"); + } - /// Return current tree context (see treeshr library) - void *getCtx() { return ctx; } + /// Write (part of) data segment + virtual void putSegment(Array *data, int ofs); + + /// Update start, end time and dimension for the last segment + virtual void updateSegment(Data *start, Data *end, Data *time) + { + (void)start; + (void)end; + (void)time; + throw MdsException( + "updateSegment() not supported for TreeNodeThinClient object"); + } - /// Reopen target tree in edit mode or in normal mode according to the - /// value passed as argument. The default behavior is to reopen for edit. - /// - void edit(const bool st = true); + /// Update start, end time and dimension for the specified segment + virtual void updateSegment(int idx, Data *start, Data *end, Data *time) + { + (void)idx; + (void)start; + (void)end; + (void)time; + throw MdsException( + "updateSegment() not supported for TreeNodeThinClient object"); + } - /// \note This function has been discontinued and the TreeQuit is now - /// handled by destructor only. Anyway the declaration is maintained here - /// to keep the labview compatibility. - /// - void quit() {} + /// Get the number of segments + virtual int getNumSegments(); + + /// Instantiate two arrays with Segments starts and ends + virtual void getSegmentLimits(int segmentIdx, Data **start, Data **end); + + /// Get data form the selected segment + virtual Array *getSegment(int segIdx); + + /// Get the selected segment dimension + virtual Data *getSegmentDim(int segIdx); + + /// Get both segment and segment dimension + virtual void getSegmentAndDimension(int segIdx, Array *&segment, + Data *&dimension); + + /// Begin a timestamted segment + virtual void beginTimestampedSegment(Array *initData); + + /// Make a timestamped segment + virtual void makeTimestampedSegment(Array *data, int64_t *times); + + /// Write (part of) data in a timestamped segment + virtual void putTimestampedSegment(Array *data, int64_t *times); + + /// Writre a single row of timestamped data + virtual void putRow(Data *data, int64_t *time, int size = 1024); + + /// Get info for the node identified by sefIdx, or the last node if -1 is + /// passed as segIdx argument. The function returns dtype of the contained + /// data and the row dimensions. The function provides: In dimct the number + /// of dimensions is stored, in dims the array of dimensions, in nextRow + /// the position of the next free row. The dims always reflects the segment + /// dimension passed by beginSegment while the next will get the current + /// position reached in this segment by the putSegment function. + /// + /// \note dtype, dimct and nextRow are pointer of size 1 array, while the + /// dims dimension must be allocated array of size 8 integers! Furthermore, + /// at the time of writing the returned dims are actually written int + /// reverse order for a mismatch in the row/column order within the treeshr + /// library + /// + virtual void getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, + int *nextRow) + { + (void)segIdx; + (void)dtype; + (void)dimct; + (void)dims; + (void)nextRow; + throw MdsException( + "getSegmentInfo() not supported for TreeNodeThinClient object"); + } - /// writes tree changes to the target storage - void write(); + /// Retrieve node tags as array of strings + virtual StringArray *findTags(); + + // EDIT METHODS // + + /// This method adds a new node to the tree that this instance belongs to. + /// The name specifies the relative or the full path of the new node and + /// the usage is a string that defines the type of the new node. See \ref + /// Tree::addNode for reference. If the relative path is chosen the new + /// node will be set as child/member of the current. + /// + virtual TreeNode *addNode(char const *name, char const *usage) + { + (void)name; + (void)usage; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Access treenode by path using const char string - TreeNode *getNode(char const *path); + /// This removes a node indentified by its path from the tree that holds the + /// current node instance. See \ref Tree::remove() for reference. + /// + virtual void remove(char const *name) + { + (void)name; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Access treenode by path using a \ref TreePath mdsplus object - TreeNode *getNode(TreePath *path); + /// Rename current node instance in tree setting a new path indentified by + /// the newName argument that must be in form of an absolute path string. + virtual void rename(std::string const &newName) + { + (void)newName; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Access treenode by path using a \ref String mdsplus object - TreeNode *getNode(String *path); + /// Move the node setting a new parent and changing the node name + virtual void move(TreeNode *parent, std::string const &newName) + { + (void)parent; + (void)newName; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Get the name of the tree as c string - const char *getName() const { return name.c_str(); } + /// Move the node setting a new parent. + virtual void move(TreeNode *parent) + { + (void)parent; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Get shot number - int getShot() const { return shot; } + /// Add a device to the tree that holds current node instance. The argument + /// name will be the name of the new created device and the type will be + /// serched within the device library. See \ref Tree::addDevice for details. + /// + virtual TreeNode *addDevice(char const *name, char const *type) + { + (void)name; + (void)type; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Get the name of this tree as a std::string - std::string getNameStr() const { return name; } + /// Add a tag to the current tree that hold this instance pointing to this + /// node. See \ref Tree::addTag() for reference. + /// + virtual void addTag(std::string const &tagName) + { + (void)tagName; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// Adds a node by path and usage. To each node we assign here a USAGE. - /// This node characteristic defines and limits how a particular node can - /// be used. Usage must be a strig matching one of the following: - /// - /// | usage | description | - /// |----------|-----------------------------------------------------------| - /// | ACTION | node that describes an \ref Action object | - /// | ANY | node scope not defined and it left here set for any use | - /// | AXIS | node represent an axis object | - /// | COMPOUND_DATA | node represents a \ref Compound object | - /// | DEVICE | node is a device composite data used for acquisition | - /// | DISPATCH | node is a dispach of an action | - /// | STRUCTURE | used for tree structure - a "child" node definition | - /// | NUMERIC | node contains simple numbers or arrays | - /// | SIGNAL | node is a signal object | - /// | SUBTREE | node links to another tree | - /// | TASK | node represents a Task of a \ref Action | - /// | TEXT | node will contain a text string | - /// | WINDOW | node is a window definition | - /// - TreeNode *addNode(char const *name, char const *usage); + /// Removes a tag added to the current tree and indentified by tagName. + virtual void removeTag(std::string const &tagName) + { + (void)tagName; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } - /// add device node to tree with name and device type - TreeNode *addDevice(char const *name, char const *type); + /// Set this node to be a subtree of the tree that holds it. + virtual void setSubtree(bool isSubtree) + { + (void)isSubtree; + throw MdsException( + "edit operations not supported for TreeNodeThinClient object"); + } + }; - /// remove tree node by path - void remove(char const *name); + /////////////////End Class TreeNodeThinClient/////////////// - /// Get a new array of nodes in this tree or subtrees mathing the path name - /// and usages given as arguments. Asterisk is available as a wildcard to - /// set the search pattern while usages are found as a ordered bitmask. + class EXPORT TreePath : public TreeNode + { + public: + TreePath(std::string const &path, Tree *tree, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0); + TreePath(char const *path, int len, Tree *tree, Data *units = 0, + Data *error = 0, Data *help = 0, Data *validation = 0); + void *convertToDsc(); + void resolveNid(); + + private: + std::string path; + }; + + ////////////////Class TreeNodeArray/////////////////////// + class EXPORT TreeNodeArray + { + TreeNode **nodes; + int numNodes; + + public: + void *operator new(size_t sz); + void operator delete(void *p); + TreeNodeArray(TreeNode **nodes, int numNodes); + TreeNodeArray(int *nids, int numNodes, Tree *tree); + ~TreeNodeArray(); + StringArray *getPath(); + StringArray *getFullPath(); + Int32Array *getNid(); + Int8Array *isOn(); + void setOn(Int8Array *info); + Int8Array *isSetup(); + Int8Array *isWriteOnce(); + void setWriteOnce(Int8Array *info); + Int8Array *isCompressOnPut(); + void setCompressOnPut(Int8Array *info); + Int8Array *isNoWriteModel(); + void setNoWriteModel(Int8Array *info); + Int8Array *isNoWriteShot(); + void setNoWriteShot(Int8Array *info); + Int32Array *getLength(); + Int32Array *getCompressedLength(); + StringArray *getUsage(); + int getNumNodes() { return numNodes; } + TreeNode *operator[](int idx) + { + if (idx >= 0 && idx < numNodes) + return nodes[idx]; + else + return 0; + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // Tree ////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// MDSplus provides a data storage mechanism for recording a wide variety of + /// information pertaining to experiments or simulations including, but not + /// limited to, data acquisition settings, comments, physical measurements, + /// data acquisition and analysis task information and analysis results. + /// Keeping all this information organized can be difficult especially with + /// large experiments or codes where there may be many thousands of data items. + /// MDSplus provides a hierarchical tree structure in its data storage so that + /// users can organize their data much like one would organize files in a file + /// system with directories and subdirectories. /// - /// the usage codes are listed in \ref usagedef.h and the mask has to be - /// compiled activating the related bit. For example to set all numeric and - /// signals nodes in a tree: + /// A tree is a collection of nodes which describe something. All data in + /// MDSplus are stored in trees. There are two different kinds of nodes in the + /// MDSplus tree structure called members and children. One could consider + /// members to be similar to files in a file system while children are similar + /// to directories. Members normally contain data, (i.e. a measurement, a + /// calibration coefficient, a comment) while a child node, used for structure + /// only, cannot contain data. However, unlike a file system, both members and + /// children nodes can have subnodes of either members or children. /// - /// AutoPointer nodes = tree->getNodeWild("***", - /// 1<1 - pulse files /// - void setDefault(TreeNode *treeNode); - /// Get the node that is the default base for all the relative paths - /// specified using \ref SetDefault function. As a new tree is open the - /// fist set default node is TOP (i.e the root of the tree). - /// - TreeNode *getDefault(); + class EXPORT Tree + { + friend void setActiveTree(Tree *tree); + friend Tree *getActiveTree(); + + protected: + std::string name; + int shot; + void *ctx; + bool fromActiveTree; + + public: + /// Builds a new Tree object instance creating or attaching to the named + /// tree. The tree name has to match the path envoronment variable + /// xxx_path, and the shot is the shot number the Tree instance will point + /// to. + /// + Tree(char const *name, int shot); + Tree(char const *name, int shot, void *ctx); + + /// Builds a new Tree object instance creating or attaching to the named + /// tree. The tree name has to match the path envoronment variable + /// xxx_path, and the shot is the shot number the Tree instance will point + /// to. Four opening mode are availabe: + /// + /// | opening mode | description | + /// |--------------|-----------------------------------------------------------------| + /// | NEW | create new tree with target parse files if not present | + /// | EDIT | open tree in edit mode to access the tree structure for + /// writing | | READONLY | open tree in read only mode | | NORMAL | + /// set the tree for normal operations reading and writing data | + /// + Tree(char const *name, int shot, char const *mode); + Tree(Tree *tree); + ~Tree(); + + void *operator new(size_t sz); + void operator delete(void *p); + + /// Set current shot number + static void setCurrent(char const *treeName, int shot); + + /// Get current shot number + static int getCurrent(char const *treeName); + + /// Return current tree context (see treeshr library) + void *getCtx() { return ctx; } + + /// Reopen target tree in edit mode or in normal mode according to the + /// value passed as argument. The default behavior is to reopen for edit. + /// + void edit(const bool st = true); + + /// \note This function has been discontinued and the TreeQuit is now + /// handled by destructor only. Anyway the declaration is maintained here + /// to keep the labview compatibility. + /// + void quit() {} + + /// writes tree changes to the target storage + void write(); + + /// Access treenode by path using const char string + TreeNode *getNode(char const *path); + + /// Access treenode by path using a \ref TreePath mdsplus object + TreeNode *getNode(TreePath *path); + + /// Access treenode by path using a \ref String mdsplus object + TreeNode *getNode(String *path); + + /// Get the name of the tree as c string + const char *getName() const { return name.c_str(); } + + /// Get shot number + int getShot() const { return shot; } + + /// Get the name of this tree as a std::string + std::string getNameStr() const { return name; } + + /// Adds a node by path and usage. To each node we assign here a USAGE. + /// This node characteristic defines and limits how a particular node can + /// be used. Usage must be a strig matching one of the following: + /// + /// | usage | description | + /// |----------|-----------------------------------------------------------| + /// | ACTION | node that describes an \ref Action object | + /// | ANY | node scope not defined and it left here set for any use | + /// | AXIS | node represent an axis object | + /// | COMPOUND_DATA | node represents a \ref Compound object | + /// | DEVICE | node is a device composite data used for acquisition | + /// | DISPATCH | node is a dispach of an action | + /// | STRUCTURE | used for tree structure - a "child" node definition | + /// | NUMERIC | node contains simple numbers or arrays | + /// | SIGNAL | node is a signal object | + /// | SUBTREE | node links to another tree | + /// | TASK | node represents a Task of a \ref Action | + /// | TEXT | node will contain a text string | + /// | WINDOW | node is a window definition | + /// + TreeNode *addNode(char const *name, char const *usage); + + /// add device node to tree with name and device type + TreeNode *addDevice(char const *name, char const *type); + + /// remove tree node by path + void remove(char const *name); + + /// Get a new array of nodes in this tree or subtrees mathing the path name + /// and usages given as arguments. Asterisk is available as a wildcard to + /// set the search pattern while usages are found as a ordered bitmask. + /// + /// the usage codes are listed in \ref usagedef.h and the mask has to be + /// compiled activating the related bit. For example to set all numeric and + /// signals nodes in a tree: + /// + /// AutoPointer nodes = tree->getNodeWild("***", + /// 1<createPulse(1); + /// delete tree; + /// tree = new Tree("test_tree",1); + /// + /// Please note that as the createPulse makes a copy of the model file a + /// plenty tree with all model nodes is written into the new shot. Another + /// correct method to create a pulse file would be also to call constructor + /// using "NEW" mode: + /// + /// Tree * tree = new Tree("test_tree",1,"NEW"); + /// + /// but in this case an empty tree will be written to file without any + /// node defined form model. + /// + void createPulse(int shot); + + /// Delete pulse file identified by shot id. After this function is called + /// all tree instance opened with delete shot number are no more valid and + /// will throw exception for any content access. Note that the model file + /// can not be deleted. + /// + void deletePulse(int shot); + + // Evaluate an expression in the context of the tree - Thread Safe, provided + // setActiveTree is not used + Data *tdiEvaluate(Data *data); + + // Compute an expression in the context of the tree - Thread Safe, provided + // setActiveTree is not used + Data *tdiData(Data *data); + + // Compile an expression in the context of the tree - Thread Safe, provided + // setActiveTree is not used + Data *tdiCompile(const char *expr); + Data *tdiCompile(const char *expr, Data *arg1); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6, Data *arg7); + Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6, Data *arg7, Data *arg8); + + // Compile an expression with arguments in the context of the tree - + // ThreaSafe, provided setActiveTree is not used + Data *tdiCompile(const char *expr, int nArgs...); + + // Execute an expression in the context of the tree - Thread Safe, provided + // setActiveTree is not used + Data *tdiExecute(const char *expr); + Data *tdiExecute(const char *expr, Data *arg1); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6, Data *arg7); + Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, + Data *arg4, Data *arg5, Data *arg6, Data *arg7, Data *arg8); + + // Execute an expression with arguments in the context of the tree - Thread + // Safe, provided setActiveTree is not used + Data *tdiExecute(const char *expr, int nArgs...); + + StringArray *findTags(char *wild); + void removeTag(char const *tagName); + int64_t getDatafileSize(); + }; + + //////////////////////////////////////////////////////////////////////////////// + // Event ///////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// - /// This function returns true if the tree has been modified from the - /// version written in the pulse file. See treeshr function \ref - /// TreeGetDbi() called with code DbiMODIFIED. /// - bool isModified(); - - /// This function returns true if the tree has been opened in edit mode. - /// See treeshr function \ref TreeGetDbi() called with code - /// DbiOPEN_FOR_EDIT. + /// Asynchronous events in MDSplus + /// ------------------------------ + /// In MDSplus it is possible to generate asynchronous events as well as + /// waiting for them. Events are often used to synchronize data visualization + /// (for instance an update event name can be defined in the jScope Setup Data + /// pop-up window, forcing an update of the displayed signal whenever such an + /// event is received). Data acquisition events in this case are generated by + /// the data acquisition routines (usually the methods of the devices involved + /// in data acquisition). /// - bool isOpenForEdit(); - - /// This function returns true if the tree has been opened for read only. - /// See treeshr function \ref TreeGetDbi() called with code - /// DbiOPEN_READONLY. + /// MDSplus defines this Event class, for event generation and reception. In + /// addition to notification, MDSplus events can bring data, either raw or + /// "packed" into Data instances. The event issuer can then optionally + /// associate data top the event, which will be received by every listener for + /// that event. Events can be generated by the following methods: /// - bool isReadOnly(); - - /// This function returns true if the tree has been created to keep stored - /// data versioning. See treeshr function \ref TreeGetDbi() called with - /// code DbiVERSIONS_IN_MODEL. \note This versioning feature will be not - /// avaiable for segmented data. + /// * setevent(name) to generate an event with no associated data /// - bool versionsInModelEnabled(); - - /// This function returns true if the tree has been created to keep stored - /// data versioning in the current pulse file. See treeshr function \ref - /// TreeGetDbi() called with code DbiVERSIONS_IN_PULSE. \note The - /// Versioning feature is not avaiable for segmented data. - /// - bool versionsInPulseEnabled(); - - /// Activates the versioning feature in the tree model so each pulse that - /// is created will have the versioning active. \note The Versioning - /// feature is not avaiable for segmented data. - /// - void setVersionsInModel(bool enable); - - /// Activates the versioning feature for the current pulse so all data that - /// is stored over the preexisting ones will be always accessible trhough a - /// growing version id. \note This versioning feature will be not avaiable - /// for segmented data. - /// - void setVersionsInPulse(bool enable); - - /// View data stored in tree from given start date when version control is - /// enabled. - /// - void setViewDate(char *date); - - void setTimeContext(Data *start, Data *end, Data *delta); - - /// Create pulse makes a copy of the tree model file into a new pulse file - /// ready to be filled with new acquired data. When this function is called - /// MDSplus asks that the model file is not opened for edit so do not - /// create pulses if you opened the tree in EDIT mode. For example a - /// correct usage would be: + /// * seteventRaw(name, buffer) to generate an event carrying a buffer of bytes /// - /// Tree * tree = new Tree("test_tree",-1); - /// tree->createPulse(1); - /// delete tree; - /// tree = new Tree("test_tree",1); + /// * setevent(name, Data) to generate an event carrying a Data instance /// - /// Please note that as the createPulse makes a copy of the model file a - /// plenty tree with all model nodes is written into the new shot. Another - /// correct method to create a pulse file would be also to call constructor - /// using "NEW" mode: + /// To handle event reception it is necessary to extend Event class by + /// associating the actions to be executed upon event reception. Class Event in + /// fact defines the virtual function \ref run(), which is called after the + /// class instantiation whenever the event with the specified name has been + /// received. The overriden run() method can then retrieve received data by + /// calling superclass \ref getData() or \ref getRaw() methods. /// - /// Tree * tree = new Tree("test_tree",1,"NEW"); + /// The following example code shows how to define a new Event class called + /// MyEvent whose action is to print the content of the received buffer (it is + /// possible to test the programs using the command: setevent event string). /// - /// but in this case an empty tree will be written to file without any - /// node defined form model. + /// \code{.cpp} + /// class MyEvent : public Event + /// { + /// public: + /// MyEvent(char *name) : Event(name) {} /// - void createPulse(int shot); - - /// Delete pulse file identified by shot id. After this function is called - /// all tree instance opened with delete shot number are no more valid and - /// will throw exception for any content access. Note that the model file - /// can not be deleted. + /// void run() + /// { + /// size_t bufSize; + /// char *name = getName(); //Get the name of the event + /// char *date = getTime()->getDate(); //Get the event reception time + /// const char *buf = getRaw(&bufSize); //Get raw data + /// char *str = new char[bufSize+1]; //Make it a string + /// memcpy(str, buf, bufSize); + /// str[bufSize] = 0; + /// std::cout << "RECEIVED EVENT " << name + /// << " AT " << date + /// << " WITH DATA " << str << "\n"; + /// } + /// }; + /// \endcode + /// + /// + /// \note There are also two MDSplus executables which can be called from a + /// console: wfevent Event_name and setevent event_name string + /// . The former suspends until an event with that name has been received; + /// the latter generates such an event. /// - void deletePulse(int shot); - - // Evaluate an expression in the context of the tree - Thread Safe, provided - // setActiveTree is not used - Data *tdiEvaluate(Data *data); - - // Compute an expression in the context of the tree - Thread Safe, provided - // setActiveTree is not used - Data *tdiData(Data *data); - - // Compile an expression in the context of the tree - Thread Safe, provided - // setActiveTree is not used - Data *tdiCompile(const char *expr); - Data *tdiCompile(const char *expr, Data *arg1); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7); - Data *tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7, Data *arg8); - - // Compile an expression with arguments in the context of the tree - - // ThreaSafe, provided setActiveTree is not used - Data *tdiCompile(const char *expr, int nArgs...); - - // Execute an expression in the context of the tree - Thread Safe, provided - // setActiveTree is not used - Data *tdiExecute(const char *expr); - Data *tdiExecute(const char *expr, Data *arg1); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7); - Data *tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7, Data *arg8); - - // Execute an expression with arguments in the context of the tree - Thread - // Safe, provided setActiveTree is not used - Data *tdiExecute(const char *expr, int nArgs...); - - StringArray *findTags(char *wild); - void removeTag(char const *tagName); - int64_t getDatafileSize(); -}; - -//////////////////////////////////////////////////////////////////////////////// -// Event ///////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// -/// Asynchronous events in MDSplus -/// ------------------------------ -/// In MDSplus it is possible to generate asynchronous events as well as -/// waiting for them. Events are often used to synchronize data visualization -/// (for instance an update event name can be defined in the jScope Setup Data -/// pop-up window, forcing an update of the displayed signal whenever such an -/// event is received). Data acquisition events in this case are generated by -/// the data acquisition routines (usually the methods of the devices involved -/// in data acquisition). -/// -/// MDSplus defines this Event class, for event generation and reception. In -/// addition to notification, MDSplus events can bring data, either raw or -/// "packed" into Data instances. The event issuer can then optionally -/// associate data top the event, which will be received by every listener for -/// that event. Events can be generated by the following methods: -/// -/// * setevent(name) to generate an event with no associated data -/// -/// * seteventRaw(name, buffer) to generate an event carrying a buffer of bytes -/// -/// * setevent(name, Data) to generate an event carrying a Data instance -/// -/// To handle event reception it is necessary to extend Event class by -/// associating the actions to be executed upon event reception. Class Event in -/// fact defines the virtual function \ref run(), which is called after the -/// class instantiation whenever the event with the specified name has been -/// received. The overriden run() method can then retrieve received data by -/// calling superclass \ref getData() or \ref getRaw() methods. -/// -/// The following example code shows how to define a new Event class called -/// MyEvent whose action is to print the content of the received buffer (it is -/// possible to test the programs using the command: setevent event string). -/// -/// \code{.cpp} -/// class MyEvent : public Event -/// { -/// public: -/// MyEvent(char *name) : Event(name) {} -/// -/// void run() -/// { -/// size_t bufSize; -/// char *name = getName(); //Get the name of the event -/// char *date = getTime()->getDate(); //Get the event reception time -/// const char *buf = getRaw(&bufSize); //Get raw data -/// char *str = new char[bufSize+1]; //Make it a string -/// memcpy(str, buf, bufSize); -/// str[bufSize] = 0; -/// std::cout << "RECEIVED EVENT " << name -/// << " AT " << date -/// << " WITH DATA " << str << "\n"; -/// } -/// }; -/// \endcode -/// -/// -/// \note There are also two MDSplus executables which can be called from a -/// console: wfevent Event_name and setevent event_name string -/// . The former suspends until an event with that name has been received; -/// the latter generates such an event. -/// - -class EXPORT Event { -public: - Event(const char *name); - Event(const char *name, unsigned int cpuMask); - virtual ~Event(); + class EXPORT Event + { + public: + Event(const char *name); + Event(const char *name, unsigned int cpuMask); - const char *getRaw(std::size_t *size) const; + virtual ~Event(); - Data *getData() const; + const char *getRaw(std::size_t *size) const; - Uint64 *getTime() const; + Data *getData() const; - const char *getName() const; + Uint64 *getTime() const; - void start(); + const char *getName() const; - void stop(); + void start(); - bool isStarted() const; + void stop(); - void wait(std::size_t secs = 0); + bool isStarted() const; - Data *waitData(std::size_t secs = 0) { - wait(secs); - return getData(); - } + void wait(std::size_t secs = 0); - char const *waitRaw(std::size_t *size, std::size_t secs = 0) { - wait(secs); - return getRaw(size); - } + Data *waitData(std::size_t secs = 0) + { + wait(secs); + return getData(); + } - virtual void run(); + char const *waitRaw(std::size_t *size, std::size_t secs = 0) + { + wait(secs); + return getRaw(size); + } - static void setEvent(const char *evName) { setEventRaw(evName, 0, NULL); } - static void setEventRaw(const char *evName, int bufLen, char *buf); - static void setEvent(const char *evName, Data *evData); + virtual void run(); - // To keep them compatible with python - static void setevent(char *evName) { setEvent(evName); } - static void seteventRaw(char *evName, int bufLen, char *buf) { - setEventRaw(evName, bufLen, buf); - } - static void setevent(char *evName, Data *evData); + static void setEvent(const char *evName) { setEventRaw(evName, 0, NULL); } + static void setEventRaw(const char *evName, int bufLen, char *buf); + static void setEvent(const char *evName, Data *evData); -protected: - void notify(); - virtual void connectToEvents(); - virtual void disconnectFromEvents(); + // To keep them compatible with python + static void setevent(char *evName) { setEvent(evName); } + static void seteventRaw(char *evName, int bufLen, char *buf) + { + setEventRaw(evName, bufLen, buf); + } + static void setevent(char *evName, Data *evData); + + protected: + void notify(); + virtual void connectToEvents(); + virtual void disconnectFromEvents(); + + private: + Event() {} + Event(const Event &) {} + friend void eventAst(void *arg, int len, char *buf); + std::string eventName; + std::string eventBuf; + int eventId; + unsigned int cpuMask; + int64_t eventTime; + ConditionVar condition; + }; + + ///////////////remote data access classes //////////////// + // + /// mdsip Connection in MDSplus + /// ------------------------------ + /// + /// Connection objects are used to establish a remote connection to a mdsip + /// server. Connection is carried out by the object constructor and then it is + /// possible to evaluate remote expressions The basic methods of Conneciton + /// class are: + /// + /// * openTree(char *tree, int shot) Open a tree at the mdsip server side + /// * closeTree(char *tree, int shot) Close the remote tree + /// * setDefault(char *path) Set default position in remote tree + /// * Data *get(const char *expr) Remote expression evaluation + /// * Data *get(const char *expr, Data **args, int nArgs) Remote expression + /// evaluation with arguments + /// * put(const char *path, char *expr, Data **args, int nArgs) Put an + /// expression (with arguments) in remote tree + /// + /// Class connection allows also the remote evaluation and put of multiple + /// expressions. Support classes GetMany and PutMany are used for this + /// purpose. GetMany and PutMany provide methods for inserting expressions to + /// be evaluated and stored, respectively. In addition both classes provide + /// method execute() that executes remote evaluation/store of the set of + /// associated expressions. GetMany and PutMany are not instantiated directly, + /// but are obtained by Connection Facotry methods getMany() and putMany() + /// Class connection provides also support for remote data streaming using + /// publish - subscribe pattern Clients can register to a connection instance + /// specifying a remote tree, shot and expression containing at least a + /// reference to a segmented node. Whenever new data are appended to the + /// segmented node at the server side registered listeners are notified and + /// receive the (chunk of) newly evaluated data and times A listener will + /// inherit abstract class DataStreamListener that defines a single method: + /// + /// * void dataReceived(Data samples, Data times). + /// + /// This method is asynchronously called by the connection frameworkwhen new + /// data are available. It is possible to register multiple listeners to the + /// same connection object. Once all listeners are registered, Connection + /// method startStreaming will start the streaming process. NOTE: when + /// streaming is started, the Connection instance is fully devoted to streaming + /// management. Therefore methods get and put cannot be called afterwards for + /// that Connection instance (they will freeze). + /// + class Connection; -private: - Event() {} - Event(const Event &) {} - friend void eventAst(void *arg, int len, char *buf); - std::string eventName; - std::string eventBuf; - int eventId; - unsigned int cpuMask; - int64_t eventTime; - ConditionVar condition; -}; + class EXPORT GetMany : public List + { + Connection *conn; + Dictionary *evalRes; + + public: + GetMany(Connection *conn) + { + this->conn = conn; + evalRes = 0; + } + ~GetMany() + { + if (evalRes) + delete evalRes; + } + void append(char *name, char *expr, Data **args, int nArgs); + void insert(int idx, char *name, char *expr, Data **args, int nArgs); + void insert(char *beforeName, char *name, char *expr, Data **args, int nArgs); + void remove(char *name); + void execute(); + Data *get(char *name); + }; + class EXPORT PutMany : public List + { + Connection *conn; + Dictionary *evalRes; + + public: + PutMany(Connection *conn) + { + this->conn = conn; + evalRes = 0; + } + ~PutMany() + { + if (evalRes) + delete evalRes; + } + void append(char *name, char *expr, Data **args, int nArgs); + void insert(int idx, char *name, char *expr, Data **args, int nArgs); + void insert(char *beforeName, char *name, char *expr, Data **args, int nArgs); + void remove(char *name); + void execute(); + void checkStatus(char *name); + }; + + class EXPORT DataStreamListener + { + public: + virtual void dataReceived(Data *samples, Data *times, int shot = 0) = 0; + }; -///////////////remote data access classes //////////////// -// -/// mdsip Connection in MDSplus -/// ------------------------------ -/// -/// Connection objects are used to establish a remote connection to a mdsip -/// server. Connection is carried out by the object constructor and then it is -/// possible to evaluate remote expressions The basic methods of Conneciton -/// class are: -/// -/// * openTree(char *tree, int shot) Open a tree at the mdsip server side -/// * closeTree(char *tree, int shot) Close the remote tree -/// * setDefault(char *path) Set default position in remote tree -/// * Data *get(const char *expr) Remote expression evaluation -/// * Data *get(const char *expr, Data **args, int nArgs) Remote expression -/// evaluation with arguments -/// * put(const char *path, char *expr, Data **args, int nArgs) Put an -/// expression (with arguments) in remote tree -/// -/// Class connection allows also the remote evaluation and put of multiple -/// expressions. Support classes GetMany and PutMany are used for this -/// purpose. GetMany and PutMany provide methods for inserting expressions to -/// be evaluated and stored, respectively. In addition both classes provide -/// method execute() that executes remote evaluation/store of the set of -/// associated expressions. GetMany and PutMany are not instantiated directly, -/// but are obtained by Connection Facotry methods getMany() and putMany() -/// Class connection provides also support for remote data streaming using -/// publish - subscribe pattern Clients can register to a connection instance -/// specifying a remote tree, shot and expression containing at least a -/// reference to a segmented node. Whenever new data are appended to the -/// segmented node at the server side registered listeners are notified and -/// receive the (chunk of) newly evaluated data and times A listener will -/// inherit abstract class DataStreamListener that defines a single method: -/// -/// * void dataReceived(Data samples, Data times). -/// -/// This method is asynchronously called by the connection frameworkwhen new -/// data are available. It is possible to register multiple listeners to the -/// same connection object. Once all listeners are registered, Connection -/// method startStreaming will start the streaming process. NOTE: when -/// streaming is started, the Connection instance is fully devoted to streaming -/// management. Therefore methods get and put cannot be called afterwards for -/// that Connection instance (they will freeze). -/// -class Connection; - -class EXPORT GetMany : public List { - Connection *conn; - Dictionary *evalRes; - -public: - GetMany(Connection *conn) { - this->conn = conn; - evalRes = 0; - } - ~GetMany() { - if (evalRes) - delete evalRes; - } - void append(char *name, char *expr, Data **args, int nArgs); - void insert(int idx, char *name, char *expr, Data **args, int nArgs); - void insert(char *beforeName, char *name, char *expr, Data **args, int nArgs); - void remove(char *name); - void execute(); - Data *get(char *name); -}; -class EXPORT PutMany : public List { - Connection *conn; - Dictionary *evalRes; - -public: - PutMany(Connection *conn) { - this->conn = conn; - evalRes = 0; - } - ~PutMany() { - if (evalRes) - delete evalRes; - } - void append(char *name, char *expr, Data **args, int nArgs); - void insert(int idx, char *name, char *expr, Data **args, int nArgs); - void insert(char *beforeName, char *name, char *expr, Data **args, int nArgs); - void remove(char *name); - void execute(); - void checkStatus(char *name); -}; - -class EXPORT DataStreamListener { -public: - virtual void dataReceived(Data *samples, Data *times, int shot = 0) = 0; -}; - -class EXPORT Connection { -public: - Connection(char *mdsipAddr, int clevel = 0); - ~Connection(); - void openTree(char *tree, int shot); - void closeAllTrees(); - void closeTree(char *tree __attribute__((unused)), - int shot __attribute__((unused))) { - closeAllTrees(); - } - void setDefault(char *path); - Data *get(const char *expr, Data **args, int nArgs); - Data *get(const char *expr) { return get(expr, 0, 0); } - void put(const char *path, char *expr, Data **args, int nArgs); - PutMany *putMany() { return new PutMany(this); } - GetMany *getMany() { return new GetMany(this); } - // Get TreeNode instance for (a subset of) TreeNode functionality in thin - // client configuration - TreeNodeThinClient *getNode(char *path); - // Streaming stuff - void registerStreamListener(DataStreamListener *listener, char *expr, - char *tree, int shot); - void unregisterStreamListener(DataStreamListener *listener); - void startStreaming(); - void resetConnection(); - void checkDataAvailability(); - -private: - MDS_DEBUG_ACCESS - void lockLocal(); - void unlockLocal(); - void lockGlobal(); - void unlockGlobal(); - - std::string mdsipAddrStr; - int clevel; - int sockId; - Mutex mutex; - static Mutex globalMutex; - std::vector listenerV; - std::vector listenerIdV; -}; - -class EXPORT Scope { - int x, y, width, height; - int idx; - -public: - Scope(const char *name, int x = 100, int y = 100, int width = 400, - int height = 400); - void plot(Data *x, Data *y, int row = 1, int col = 1, - const char *color = "black"); - void oplot(Data *x, Data *y, int row = 1, int col = 1, - const char *color = "black"); - void show(); -}; + class EXPORT Connection + { + public: + Connection(char *mdsipAddr, int clevel = 0); + ~Connection(); + void openTree(char *tree, int shot); + void closeAllTrees(); + void closeTree(char *tree __attribute__((unused)), + int shot __attribute__((unused))) + { + closeAllTrees(); + } + void setDefault(char *path); + Data *get(const char *expr, Data **args, int nArgs); + Data *get(const char *expr) { return get(expr, 0, 0); } + void put(const char *path, char *expr, Data **args, int nArgs); + PutMany *putMany() { return new PutMany(this); } + GetMany *getMany() { return new GetMany(this); } + // Get TreeNode instance for (a subset of) TreeNode functionality in thin + // client configuration + TreeNodeThinClient *getNode(char *path); + // Streaming stuff + void registerStreamListener(DataStreamListener *listener, char *expr, + char *tree, int shot); + void unregisterStreamListener(DataStreamListener *listener); + void startStreaming(); + void resetConnection(); + void checkDataAvailability(); + + private: + MDS_DEBUG_ACCESS + void lockLocal(); + void unlockLocal(); + void lockGlobal(); + void unlockGlobal(); + + std::string mdsipAddrStr; + int clevel; + int sockId; + Mutex mutex; + static Mutex globalMutex; + std::vector listenerV; + std::vector listenerIdV; + }; + + class EXPORT Scope + { + int x, y, width, height; + int idx; + + public: + Scope(const char *name, int x = 100, int y = 100, int width = 400, + int height = 400); + void plot(Data *x, Data *y, int row = 1, int col = 1, + const char *color = "black"); + void oplot(Data *x, Data *y, int row = 1, int col = 1, + const char *color = "black"); + void show(); + }; #ifdef HAVE_PTHREAD_H -class EXPORT EventStream : public Event { - std::vector listeners; - std::vector names; - std::string name; - void handleJSONPayload(char *); -public: - virtual void run(); - EventStream() : Event("STREAMING") { - listeners.clear(); - names.clear(); - name = "STREAMING"; - } - EventStream(const char *streamName) : Event(streamName) { - listeners.clear(); - names.clear(); - name = streamName; - } - EventStream(const char *streamName, unsigned int cpuMask) : Event(streamName, cpuMask) { - listeners.clear(); - names.clear(); - name = streamName; - } - static void send(int shot, const char *name, bool isAbsTime, int nTimes, void *times, - int nDims, int *dims, float *samples); - static void send(int shot, const char *name, float time, float sample); - static void send(int shot, const char *name, uint64_t time, float sample); - static void send(int shot, const char *name, int numSamples, float *times, - float *samples); - static void send(int shot, const char *name, int numSamples, uint64_t *times, - float *samples); - static void send(int shot, const char *name, int numTimes, uint64_t *times, - int numSamples, float *samples); - static void send(int shot, const char *name, Data *timesD, Data *samplesD); - void registerListener(DataStreamListener *listener, const char *name); - void registerListener(DataStreamListener *listener); -}; + class EXPORT EventStream : public Event + { + std::vector listeners; + std::vector names; + std::string name; + void handleJSONPayload(char *); + + public: + virtual void run(); + EventStream() : Event("STREAMING") + { + listeners.clear(); + names.clear(); + name = "STREAMING"; + } + EventStream(const char *streamName) : Event(streamName) + { + listeners.clear(); + names.clear(); + name = streamName; + } + EventStream(const char *streamName, unsigned int cpuMask) : Event(streamName, cpuMask) + { + listeners.clear(); + names.clear(); + name = streamName; + } + static void send(int shot, const char *name, bool isAbsTime, int nTimes, void *times, + int nDims, int *dims, float *samples); + static void send(int shot, const char *name, float time, float sample); + static void send(int shot, const char *name, uint64_t time, float sample); + static void send(int shot, const char *name, int numSamples, float *times, + float *samples); + static void send(int shot, const char *name, int numSamples, uint64_t *times, + float *samples); + static void send(int shot, const char *name, int numTimes, uint64_t *times, + int numSamples, float *samples); + static void send(int shot, const char *name, Data *timesD, Data *samplesD); + void registerListener(DataStreamListener *listener, const char *name); + void registerListener(DataStreamListener *listener); + }; #endif -//////////////Support functions//////// -EXPORT Data *deserialize(char const *serialized); -EXPORT Data *deserialize(Data *serializedData); -EXPORT Data *compile(const char *expr); -EXPORT Data *compileWithArgs(const char *expr, int nArgs...); -EXPORT Data *compile(const char *expr, Tree *tree); -EXPORT Data *compileWithArgs(const char *expr, Tree *tree, int nArgs...); -EXPORT Data *execute(const char *expr); -EXPORT Data *executeWithArgs(const char *expr, int nArgs...); -EXPORT Data *execute(const char *expr, Tree *tree); -EXPORT Data *executeWithArgs(const char *expr, Tree *tree, int nArgs...); -// EXPORT Tree *getActiveTree(); -// EXPORT void setActiveTree(Tree *tree); -// Required for handling dynamic memory allocated in a different DLL on windows -// in Debug configuration -EXPORT void deleteTreeNode(TreeNode *node); -EXPORT void deleteTree(Tree *tree); -EXPORT void deleteTreeNodeArray(TreeNodeArray *nodeArray); -EXPORT std::ostream &operator<<(std::ostream &stream, MDSplus::Data *data); - -EXPORT void deleteNativeArray(char *array); -EXPORT void deleteNativeArray(unsigned char *array); -EXPORT void deleteNativeArray(short *array); -EXPORT void deleteNativeArray(unsigned short *array); -EXPORT void deleteNativeArray(int *array); -EXPORT void deleteNativeArray(unsigned int *array); -EXPORT void deleteNativeArray(int64_t *array); -EXPORT void deleteNativeArray(uint64_t *array); -EXPORT void deleteNativeArray(float *array); -EXPORT void deleteNativeArray(double *array); -EXPORT void deleteNativeArray(char **array); -EXPORT void deleteNativeArray(Data **array); + //////////////Support functions//////// + EXPORT Data *deserialize(char const *serialized); + EXPORT Data *deserialize(Data *serializedData); + EXPORT Data *compile(const char *expr); + EXPORT Data *compileWithArgs(const char *expr, int nArgs...); + EXPORT Data *compile(const char *expr, Tree *tree); + EXPORT Data *compileWithArgs(const char *expr, Tree *tree, int nArgs...); + EXPORT Data *execute(const char *expr); + EXPORT Data *executeWithArgs(const char *expr, int nArgs...); + EXPORT Data *execute(const char *expr, Tree *tree); + EXPORT Data *executeWithArgs(const char *expr, Tree *tree, int nArgs...); + // EXPORT Tree *getActiveTree(); + // EXPORT void setActiveTree(Tree *tree); + // Required for handling dynamic memory allocated in a different DLL on windows + // in Debug configuration + EXPORT void deleteTreeNode(TreeNode *node); + EXPORT void deleteTree(Tree *tree); + EXPORT void deleteTreeNodeArray(TreeNodeArray *nodeArray); + EXPORT std::ostream &operator<<(std::ostream &stream, MDSplus::Data *data); + + EXPORT void deleteNativeArray(char *array); + EXPORT void deleteNativeArray(unsigned char *array); + EXPORT void deleteNativeArray(short *array); + EXPORT void deleteNativeArray(unsigned short *array); + EXPORT void deleteNativeArray(int *array); + EXPORT void deleteNativeArray(unsigned int *array); + EXPORT void deleteNativeArray(int64_t *array); + EXPORT void deleteNativeArray(uint64_t *array); + EXPORT void deleteNativeArray(float *array); + EXPORT void deleteNativeArray(double *array); + EXPORT void deleteNativeArray(char **array); + EXPORT void deleteNativeArray(Data **array); } // namespace MDSplus diff --git a/include/mdsplus/AutoPointer.hpp b/include/mdsplus/AutoPointer.hpp index ba2118ef23..e97a6b5ef1 100644 --- a/include/mdsplus/AutoPointer.hpp +++ b/include/mdsplus/AutoPointer.hpp @@ -11,80 +11,96 @@ #include #include -namespace MDSplus { +namespace MDSplus +{ -template -struct AutoPointerBase { - AutoPointerBase(T * t): ptr(t) { - } + template + struct AutoPointerBase + { + AutoPointerBase(T *t) : ptr(t) + { + } - virtual ~AutoPointerBase() = 0; + virtual ~AutoPointerBase() = 0; - T * get() { - return ptr; - } + T *get() + { + return ptr; + } - T * operator->() { - return ptr; - } + T *operator->() + { + return ptr; + } - T & operator*() { - return *ptr; - } + T &operator*() + { + return *ptr; + } operator T *() { return ptr; } operator const T *() const { return ptr; } - T * ptr; -}; - -template -AutoPointerBase::~AutoPointerBase() {} - -template -struct AutoPointer: public AutoPointerBase { - AutoPointer(T * t): AutoPointerBase(t) { - } - - virtual ~AutoPointer() { - delete AutoPointerBase::ptr; - } -}; - -// FIXME: AutoData can't be a specialization of AutoPointer -// FIXME: until we use a more recent version of VS that supports -// FIXME: the TR1 type traits. -template -struct AutoData: public AutoPointerBase { - AutoData(T * t): AutoPointerBase(t) { - } - - virtual ~AutoData() { - deleteData(AutoPointerBase::ptr); - } -}; - -template -struct AutoArray: public AutoPointerBase { - AutoArray(T * t): AutoPointerBase(t) { - } - - virtual ~AutoArray() { - delete[] AutoPointerBase::ptr; - } -}; - -template -struct AutoVector: public AutoArray { - AutoVector(T * vBeg, T* vEnd): AutoArray(vBeg), vector(vBeg, vEnd) {} - std::vector vector; -}; - -struct AutoString: public AutoArray { - AutoString(char * cstr): AutoArray(cstr), string(cstr) {} - std::string string; -}; - + T *ptr; + }; + + template + AutoPointerBase::~AutoPointerBase() {} + + template + struct AutoPointer : public AutoPointerBase + { + AutoPointer(T *t) : AutoPointerBase(t) + { + } + + virtual ~AutoPointer() + { + delete AutoPointerBase::ptr; + } + }; + + // FIXME: AutoData can't be a specialization of AutoPointer + // FIXME: until we use a more recent version of VS that supports + // FIXME: the TR1 type traits. + template + struct AutoData : public AutoPointerBase + { + AutoData(T *t) : AutoPointerBase(t) + { + } + + virtual ~AutoData() + { + deleteData(AutoPointerBase::ptr); + } + }; + + template + struct AutoArray : public AutoPointerBase + { + AutoArray(T *t) : AutoPointerBase(t) + { + } + + virtual ~AutoArray() + { + delete[] AutoPointerBase::ptr; + } + }; + + template + struct AutoVector : public AutoArray + { + AutoVector(T *vBeg, T *vEnd) : AutoArray(vBeg), vector(vBeg, vEnd) {} + std::vector vector; + }; + + struct AutoString : public AutoArray + { + AutoString(char *cstr) : AutoArray(cstr), string(cstr) {} + std::string string; + }; } #endif /* MDS_AUTOPOINTER_HPP_ */ diff --git a/include/mdsplus/ConditionVar.hpp b/include/mdsplus/ConditionVar.hpp index 0ad26ee37d..4fc5741a39 100644 --- a/include/mdsplus/ConditionVar.hpp +++ b/include/mdsplus/ConditionVar.hpp @@ -12,9 +12,9 @@ #include -#if defined (MDS_WINDOWS) +#if defined(MDS_WINDOWS) #include -#elif defined (MDS_PTHREAD) +#elif defined(MDS_PTHREAD) #include #endif @@ -24,105 +24,121 @@ #ifndef CLOCK_REALTIME #define CLOCK_REALTIME 0 #endif -static void clock_gettime(int dummyClock __attribute__ ((unused)), timespec * ts) { - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - - ts->tv_sec = mts.tv_sec; - ts->tv_nsec = mts.tv_nsec; +static void clock_gettime(int dummyClock __attribute__((unused)), timespec *ts) +{ + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + + ts->tv_sec = mts.tv_sec; + ts->tv_nsec = mts.tv_nsec; } #endif -namespace MDSplus { - -class ConditionVar { -public: - ConditionVar() { - _create(); - } - - ~ConditionVar() { - _destroy(); - } - - void wait() { - _wait(); - } - - bool waitTimeout(std::size_t msec) { - return _waitTimeout(msec); - } - - void notify() { - _notify(); - } - -private: -#if defined (MDS_PTHREAD) - pthread_mutex_t mutex; - pthread_cond_t condition; - - void _create() { - //FIXME: Use PTHREAD_MUTEX_INITIALIZER when FC15 goes away - pthread_mutex_init(&mutex, NULL); - pthread_cond_init(&condition, NULL); - } - - void _wait() { - pthread_mutex_lock(&mutex); - pthread_cond_wait(&condition, &mutex); - pthread_mutex_unlock(&mutex); - } - - bool _waitTimeout(std::size_t msec) { - timespec t; - clock_gettime(CLOCK_REALTIME, &t); - t.tv_sec += msec / 1000L; - t.tv_nsec += msec % 1000L * 1000000L; - pthread_mutex_lock(&mutex); - bool res = pthread_cond_timedwait(&condition, &mutex, &t) == 0 ? true:false; - pthread_mutex_unlock(&mutex); - return res; - } - - void _notify() { - pthread_mutex_lock(&mutex); - pthread_cond_broadcast(&condition); - pthread_mutex_unlock(&mutex); - } - - void _destroy() { - pthread_cond_destroy(&condition); - } -#elif defined (MDS_WINDOWS) - HANDLE condition; - - void _create() { - condition = CreateEvent(NULL, FALSE, FALSE, NULL); - } - - void _wait() { - WaitForSingleObject(condition, INFINITE); - } - - bool _waitTimeout(std::size_t msec) { - return WaitForSingleObject(condition, msec) == WAIT_OBJECT_0 ? true:false; - } - - void _notify() { - SetEvent(condition); - } - - void _destroy() { - CloseHandle(condition); - } +namespace MDSplus +{ + + class ConditionVar + { + public: + ConditionVar() + { + _create(); + } + + ~ConditionVar() + { + _destroy(); + } + + void wait() + { + _wait(); + } + + bool waitTimeout(std::size_t msec) + { + return _waitTimeout(msec); + } + + void notify() + { + _notify(); + } + + private: +#if defined(MDS_PTHREAD) + pthread_mutex_t mutex; + pthread_cond_t condition; + + void _create() + { + //FIXME: Use PTHREAD_MUTEX_INITIALIZER when FC15 goes away + pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&condition, NULL); + } + + void _wait() + { + pthread_mutex_lock(&mutex); + pthread_cond_wait(&condition, &mutex); + pthread_mutex_unlock(&mutex); + } + + bool _waitTimeout(std::size_t msec) + { + timespec t; + clock_gettime(CLOCK_REALTIME, &t); + t.tv_sec += msec / 1000L; + t.tv_nsec += msec % 1000L * 1000000L; + pthread_mutex_lock(&mutex); + bool res = pthread_cond_timedwait(&condition, &mutex, &t) == 0 ? true : false; + pthread_mutex_unlock(&mutex); + return res; + } + + void _notify() + { + pthread_mutex_lock(&mutex); + pthread_cond_broadcast(&condition); + pthread_mutex_unlock(&mutex); + } + + void _destroy() + { + pthread_cond_destroy(&condition); + } +#elif defined(MDS_WINDOWS) + HANDLE condition; + + void _create() + { + condition = CreateEvent(NULL, FALSE, FALSE, NULL); + } + + void _wait() + { + WaitForSingleObject(condition, INFINITE); + } + + bool _waitTimeout(std::size_t msec) + { + return WaitForSingleObject(condition, msec) == WAIT_OBJECT_0 ? true : false; + } + + void _notify() + { + SetEvent(condition); + } + + void _destroy() + { + CloseHandle(condition); + } #endif - -}; - + }; } #endif /* MDS_CONDITIONVAR_HPP_ */ diff --git a/include/mdsplus/Mutex.hpp b/include/mdsplus/Mutex.hpp index 367c9330b5..cb6276a800 100644 --- a/include/mdsplus/Mutex.hpp +++ b/include/mdsplus/Mutex.hpp @@ -9,70 +9,77 @@ #define MDS_MUTEX_HPP_ #include -#if defined (MDS_WINDOWS) +#if defined(MDS_WINDOWS) #include -#elif defined (MDS_PTHREAD) +#elif defined(MDS_PTHREAD) #include #endif -namespace MDSplus { +namespace MDSplus +{ -class Mutex { -public: - Mutex() { - _create(); - } + class Mutex + { + public: + Mutex() + { + _create(); + } - ~Mutex() { -// unlock(); Unlocking a POSIX mutex which is already unlocked leads to undefinite behavior!! - _destroy(); - } + ~Mutex() + { + // unlock(); Unlocking a POSIX mutex which is already unlocked leads to undefinite behavior!! + _destroy(); + } - void lock() { - _lock(); - } + void lock() + { + _lock(); + } - void unlock() { - _unlock(); - } + void unlock() + { + _unlock(); + } -private: -#if defined (MDS_PTHREAD) - pthread_mutex_t mutex; - void _create() - { - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&mutex, &attr); - } - void _lock() { pthread_mutex_lock(&mutex); } - void _unlock() { pthread_mutex_unlock(&mutex); } - void _destroy() { pthread_mutex_destroy(&mutex); } -#elif defined (MDS_WINDOWS) - HANDLE mutex; - void _create() { mutex = CreateMutex(NULL, FALSE, NULL); } - void _lock() { WaitForSingleObject(mutex, INFINITE); } - void _unlock() { ReleaseMutex(mutex); } - void _destroy() { CloseHandle(mutex); } + private: +#if defined(MDS_PTHREAD) + pthread_mutex_t mutex; + void _create() + { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&mutex, &attr); + } + void _lock() { pthread_mutex_lock(&mutex); } + void _unlock() { pthread_mutex_unlock(&mutex); } + void _destroy() { pthread_mutex_destroy(&mutex); } +#elif defined(MDS_WINDOWS) + HANDLE mutex; + void _create() { mutex = CreateMutex(NULL, FALSE, NULL); } + void _lock() { WaitForSingleObject(mutex, INFINITE); } + void _unlock() { ReleaseMutex(mutex); } + void _destroy() { CloseHandle(mutex); } #endif -}; + }; -class AutoLock { -public: - AutoLock(Mutex & mutex): mutex(mutex) { - mutex.lock(); - } + class AutoLock + { + public: + AutoLock(Mutex &mutex) : mutex(mutex) + { + mutex.lock(); + } - ~AutoLock() { - mutex.unlock(); - } - -private: - Mutex & mutex; - -}; + ~AutoLock() + { + mutex.unlock(); + } + private: + Mutex &mutex; + }; } #endif /* MDS_MUTEX_HPP_ */ diff --git a/include/mdsplus/Traits.hpp b/include/mdsplus/Traits.hpp index cb880ee2f7..da9d74ee16 100644 --- a/include/mdsplus/Traits.hpp +++ b/include/mdsplus/Traits.hpp @@ -6,19 +6,21 @@ // ENABLE IF ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace MDSplus { +namespace MDSplus +{ -template -struct enable_if { + template + struct enable_if + { typedef T type; -}; + }; -template -struct enable_if {}; + template + struct enable_if + { + }; } // MDSplus - #endif // DOXYGEN end of hidden code #endif // TRAITS_HPP - diff --git a/include/mdsplus/mdsplus.h b/include/mdsplus/mdsplus.h index f82a9c6658..81ef644240 100644 --- a/include/mdsplus/mdsplus.h +++ b/include/mdsplus/mdsplus.h @@ -53,8 +53,7 @@ #ifdef MDS_SHARED // defined if MDS is compiled as a shared library #define MDS_API_LOCAL MDS_API_HIDDEN -#ifdef MDS_API_BUILD // defined if we are building the MDS library instead of - // using it +#ifdef MDS_API_BUILD // defined if we are building the MDS library instead of using it #define MDS_API MDS_API_EXPORT #else #define MDS_API MDS_API_IMPORT diff --git a/include/mdsplus/numeric_cast.hpp b/include/mdsplus/numeric_cast.hpp index a5cb9d443e..bcc2e299cf 100644 --- a/include/mdsplus/numeric_cast.hpp +++ b/include/mdsplus/numeric_cast.hpp @@ -9,293 +9,281 @@ #include "mdsplus/Traits.hpp" - - //////////////////////////////////////////////////////////////////////////////// // Numeric Limits //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace MDSplus { +namespace MDSplus +{ #ifndef DOXYGEN // hide this part from documentation -/// Numeric Limits for Integer types -template < typename T, typename EnableIf = void > -class numeric_limits : - public std::numeric_limits -{ -public: + /// Numeric Limits for Integer types + template + class numeric_limits : public std::numeric_limits + { + public: typedef std::numeric_limits BaseClass; static inline T highest() { return BaseClass::max(); } static inline T lowest() { return BaseClass::min(); } -}; - -/// Numeric Limits for Floating types -template < typename T > -class numeric_limits::is_integer && - std::numeric_limits::is_signed - >::type > : - public std::numeric_limits -{ -public: + }; + + /// Numeric Limits for Floating types + template + class numeric_limits::is_integer && + std::numeric_limits::is_signed>::type> : public std::numeric_limits + { + public: typedef std::numeric_limits BaseClass; static inline T highest() { return BaseClass::max(); } static inline T lowest() { return -BaseClass::max(); } -}; + }; #endif // DOXYGEN end of hidden code } // MDSplus - - - // YOU REALLY SHOULD PREFER BOOST CONVERSION // // #include - // THIS IS BASED ON STD LIMITS // //////////////////////////////////////////////////////////////////////////////// // numeric_cast_traits /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - -namespace MDSplus { -namespace detail { - -template < typename Target, typename Source > -struct numeric_cast_trait { - typedef numeric_limits Slimits; - typedef numeric_limits Tlimits; - static const bool is_coercion = Slimits::digits > Tlimits::digits; - static const bool is_u2s = !Slimits::is_signed && Tlimits::is_signed; - static const bool is_s2u = Slimits::is_signed && !Tlimits::is_signed; -}; - - - -template < typename Target, typename Source, typename EnableIf = void > -struct numeric_cast_max_rule { - static inline void apply(Source value) { - if( value > static_cast( numeric_limits::highest() ) ) - throw ( std::overflow_error("scalar cast overflow")); - } -}; - -template < typename Target, typename Source, typename EnableIf = void > -struct numeric_cast_min_rule { - static inline void apply(Source value) { - if( value < static_cast( numeric_limits::lowest() ) ) - throw ( std::underflow_error("scalar cast underflow")); - } -}; - -template < typename Target, typename Source, typename EnableIf = void > -struct numeric_cast_precision_rule { - typedef numeric_cast_trait trait; - static inline void apply(Source value __attribute__ ((unused))) { - // if( trait::is_coercion ) { - // if( value > (Source)(1<::digits) ) - // throw(std::range_error("scalar loss of precision for digit overflow") ); - // if( trait::Slimits::is_signed && value < -static_cast(1<::digits) ) - // throw(std::range_error("scalar loss of precision for digit underflow") ); - // } - // if(value != static_cast(static_cast(value)) ) - // throw(std::range_error("scalar loss of precision") ); - } -}; - -template < typename Target, typename Source, typename EnableIf = void > -struct numeric_cast_nan_rule { - typedef numeric_cast_trait trait; - static inline void apply(Source value) { - if( std::isnan(value) ) throw(std::range_error("Trying to convert Nan to an Integer type")); - } -}; - -template < typename Target, typename Source, typename EnableIf = void > -struct numeric_cast_inf_rule { - typedef numeric_cast_trait trait; - static inline void apply(Source value) { - if( std::isinf(value) ) throw(std::range_error("Trying to convert Inf to an Integer type")); - } -}; - - - -//////////////////////////////////////////////////////////////////////////////// -// NumericCastImpl /////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - - -template -struct NumericCastImpl { - static Target numeric_cast(Source value __attribute__ ((unused))) {} -}; - -// Integer -> Integer -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - numeric_limits::is_integer && - numeric_limits::is_integer && - numeric_cast_trait::is_coercion - > - ::type > +namespace MDSplus { - static Target numeric_cast(Source value ) { - if( !numeric_cast_trait::is_u2s ) - numeric_cast_min_rule::apply(value); - numeric_cast_max_rule::apply(value); + namespace detail + { + + template + struct numeric_cast_trait + { + typedef numeric_limits Slimits; + typedef numeric_limits Tlimits; + static const bool is_coercion = Slimits::digits > Tlimits::digits; + static const bool is_u2s = !Slimits::is_signed && Tlimits::is_signed; + static const bool is_s2u = Slimits::is_signed && !Tlimits::is_signed; + }; + + template + struct numeric_cast_max_rule + { + static inline void apply(Source value) + { + if (value > static_cast(numeric_limits::highest())) + throw(std::overflow_error("scalar cast overflow")); + } + }; + + template + struct numeric_cast_min_rule + { + static inline void apply(Source value) + { + if (value < static_cast(numeric_limits::lowest())) + throw(std::underflow_error("scalar cast underflow")); + } + }; + + template + struct numeric_cast_precision_rule + { + typedef numeric_cast_trait trait; + static inline void apply(Source value __attribute__((unused))) + { + // if( trait::is_coercion ) { + // if( value > (Source)(1<::digits) ) + // throw(std::range_error("scalar loss of precision for digit overflow") ); + // if( trait::Slimits::is_signed && value < -static_cast(1<::digits) ) + // throw(std::range_error("scalar loss of precision for digit underflow") ); + // } + // if(value != static_cast(static_cast(value)) ) + // throw(std::range_error("scalar loss of precision") ); + } + }; + + template + struct numeric_cast_nan_rule + { + typedef numeric_cast_trait trait; + static inline void apply(Source value) + { + if (std::isnan(value)) + throw(std::range_error("Trying to convert Nan to an Integer type")); + } + }; + + template + struct numeric_cast_inf_rule + { + typedef numeric_cast_trait trait; + static inline void apply(Source value) + { + if (std::isinf(value)) + throw(std::range_error("Trying to convert Inf to an Integer type")); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + // NumericCastImpl /////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + template + struct NumericCastImpl + { + static Target numeric_cast(Source value __attribute__((unused))) {} + }; + + // Integer -> Integer + template + struct NumericCastImpl::is_integer && + numeric_limits::is_integer && + numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { + if (!numeric_cast_trait::is_u2s) + numeric_cast_min_rule::apply(value); + numeric_cast_max_rule::apply(value); return static_cast(value); - } -}; - -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - numeric_limits::is_integer && - numeric_limits::is_integer && - !numeric_cast_trait::is_coercion - > - ::type > -{ - static Target numeric_cast(Source value ) { - if( numeric_cast_trait::is_s2u ) - numeric_cast_min_rule::apply(value); + } + }; + + template + struct NumericCastImpl::is_integer && + numeric_limits::is_integer && + !numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { + if (numeric_cast_trait::is_s2u) + numeric_cast_min_rule::apply(value); return static_cast(value); - } -}; - -// Integer -> Float -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - numeric_limits::is_integer && - !numeric_limits::is_integer && - numeric_cast_trait::is_coercion - > - ::type > -{ - static Target numeric_cast(Source value ) { - numeric_cast_precision_rule::apply(value); + } + }; + + // Integer -> Float + template + struct NumericCastImpl::is_integer && + !numeric_limits::is_integer && + numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { + numeric_cast_precision_rule::apply(value); return static_cast(value); - } -}; - -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - numeric_limits::is_integer && - !numeric_limits::is_integer && - !numeric_cast_trait::is_coercion - > - ::type > -{ - static Target numeric_cast(Source value ) { + } + }; + + template + struct NumericCastImpl::is_integer && + !numeric_limits::is_integer && + !numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { return static_cast(value); - } -}; - -// Float -> Integer -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - !numeric_limits::is_integer && - numeric_limits::is_integer - > - ::type > -{ - static Target numeric_cast(Source value ) { - numeric_cast_nan_rule::apply(value); - numeric_cast_inf_rule::apply(value); - numeric_cast_min_rule::apply(value); - numeric_cast_max_rule::apply(value); - numeric_cast_precision_rule::apply(value); + } + }; + + // Float -> Integer + template + struct NumericCastImpl::is_integer && + numeric_limits::is_integer>::type> + { + static Target numeric_cast(Source value) + { + numeric_cast_nan_rule::apply(value); + numeric_cast_inf_rule::apply(value); + numeric_cast_min_rule::apply(value); + numeric_cast_max_rule::apply(value); + numeric_cast_precision_rule::apply(value); return static_cast(value); - - } -}; - - -// Float -> Float -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - !numeric_limits::is_integer && - !numeric_limits::is_integer && - numeric_cast_trait::is_coercion - > - ::type > -{ - static Target numeric_cast(Source value ) { - numeric_cast_min_rule::apply(value); - numeric_cast_max_rule::apply(value); - numeric_cast_precision_rule::apply(value); + } + }; + + // Float -> Float + template + struct NumericCastImpl::is_integer && + !numeric_limits::is_integer && + numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { + numeric_cast_min_rule::apply(value); + numeric_cast_max_rule::apply(value); + numeric_cast_precision_rule::apply(value); return static_cast(value); - } -}; - -template < typename Target, typename Source > -struct NumericCastImpl < Target, Source, - typename enable_if< - !numeric_limits::is_integer && - !numeric_limits::is_integer && - !numeric_cast_trait::is_coercion - > - ::type > -{ - static Target numeric_cast(Source value ) { + } + }; + + template + struct NumericCastImpl::is_integer && + !numeric_limits::is_integer && + !numeric_cast_trait::is_coercion>::type> + { + static Target numeric_cast(Source value) + { return static_cast(value); - } -}; - - -} // detail - - -//////////////////////////////////////////////////////////////////////////////// -// numeric_cast ////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// For each possible scalar conversion, from one native type to another one, a -/// specific cast function was implemented to check if the conversion is not -/// meaningless. If no accepted conversion was found the library throws an -/// exception identifying the error status. For instance a Int8 n = -1 casted -/// to Uint32 will throw a std::underflow_error. -/// -/// All conversion checks is managed by a template specialization of the -/// MDSplus::numeric_cast() function. This function uses the -/// std::numeric_limits to get boundaries for the source and target numeric -/// domains of the specific cast, so at the end the test is done using the -/// standard template library numeric traits. The implementation was done using -/// very few type traits and the standard std::numeric_limits class. -/// -/// Four checks are selected by traits to be performed on values: -/// -/// - numeric_cast_max_rule -/// - numeric_cast_min_rule -/// - numeric_cast_precision_rule (disabled at the moment) -/// - numeric_cast_nan_rule -/// -/// The possible exception that the function can throw are: -/// -/// | Exception | Description | -/// |-----------------------|------------------------------------------| -/// | std::overflow_error | exceeded the upper limitof target domain | -/// | std::underflow_error | exceeded the lower limitof target domain | -/// | std::range_error | nan or inf converted to integer domain | -/// | std::range_error | loss of precision (disabled) | -/// - -template -inline Target numeric_cast(Source value) { - return detail::NumericCastImpl::numeric_cast(value); -} + } + }; + + } // detail + + //////////////////////////////////////////////////////////////////////////////// + // numeric_cast ////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// For each possible scalar conversion, from one native type to another one, a + /// specific cast function was implemented to check if the conversion is not + /// meaningless. If no accepted conversion was found the library throws an + /// exception identifying the error status. For instance a Int8 n = -1 casted + /// to Uint32 will throw a std::underflow_error. + /// + /// All conversion checks is managed by a template specialization of the + /// MDSplus::numeric_cast() function. This function uses the + /// std::numeric_limits to get boundaries for the source and target numeric + /// domains of the specific cast, so at the end the test is done using the + /// standard template library numeric traits. The implementation was done using + /// very few type traits and the standard std::numeric_limits class. + /// + /// Four checks are selected by traits to be performed on values: + /// + /// - numeric_cast_max_rule + /// - numeric_cast_min_rule + /// - numeric_cast_precision_rule (disabled at the moment) + /// - numeric_cast_nan_rule + /// + /// The possible exception that the function can throw are: + /// + /// | Exception | Description | + /// |-----------------------|------------------------------------------| + /// | std::overflow_error | exceeded the upper limitof target domain | + /// | std::underflow_error | exceeded the lower limitof target domain | + /// | std::range_error | nan or inf converted to integer domain | + /// | std::range_error | loss of precision (disabled) | + /// + + template + inline Target numeric_cast(Source value) + { + return detail::NumericCastImpl::numeric_cast(value); + } } // MDSplus - - - #endif // NUMERIC_CAST_HPP - diff --git a/include/mdsserver.h b/include/mdsserver.h index befe200af7..544ba8c92f 100644 --- a/include/mdsserver.h +++ b/include/mdsserver.h @@ -2,7 +2,8 @@ #define _MDSSERVER #include -typedef enum { +typedef enum +{ doabort, /**** Abort current action or mdsdcl command ***/ action, /**** Execute an action nid in a tree ***/ close_tree, /**** Close open trees ***/ @@ -15,9 +16,15 @@ typedef enum { noop /**** Noop used to start server ***/ } MsgType; -typedef enum { none, log, statistics } LoggingType; +typedef enum +{ + none, + log, + statistics +} LoggingType; -typedef enum { +typedef enum +{ build_table_begin = 1, build_table, build_table_end, @@ -27,27 +34,33 @@ typedef enum { done } MonitorMode; -typedef struct { +typedef struct +{ char flush; } DoAbortMsg; -typedef struct { +typedef struct +{ char treename[12]; int shot; int nid; } ActionMsg; /* close message has no data */ -typedef struct { +typedef struct +{ char treename[12]; int shot; } CreatePulseMsg; -typedef struct { +typedef struct +{ LoggingType type; } LoggingMsg; -typedef struct { +typedef struct +{ char cli[12]; char command[1]; } MdsDclCommandMsg; -typedef struct { +typedef struct +{ char treename[12]; int shot; int phase; @@ -57,12 +70,14 @@ typedef struct { char server[32]; int status; } MonitorMsg; -typedef struct { +typedef struct +{ char full; } ShowMsg; /* stop message has no data */ -typedef struct { +typedef struct +{ char opcode; char now; char fill1; @@ -73,7 +88,8 @@ typedef struct { #define MsgOffset(field) ((int)&((Msg *)0)->field) -typedef struct { +typedef struct +{ char server[32]; int nid; int phase; @@ -91,7 +107,8 @@ typedef struct { unsigned recorded : 1; } ActionInfo; -typedef struct { +typedef struct +{ int num; char tree[12]; int shot; @@ -99,7 +116,8 @@ typedef struct { ActionInfo actions[1]; } DispatchTable; -typedef struct { +typedef struct +{ int shot; union { int nid; diff --git a/include/mdsshr.h b/include/mdsshr.h index 886cefc3c3..056ff96159 100644 --- a/include/mdsshr.h +++ b/include/mdsshr.h @@ -6,150 +6,152 @@ #include #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -//////////////////////////////////////////////////////////////////////////////// -/// -/// USED INTERNALLY BY MDSplus kernel libraries. -/// Compress data by passing the data to the compression routine specified -/// or the default routine, MdsCmprs. -/// -/// An algorithm to compress data with small differences. -/// Only data less than 32 bits can be packed. -/// The run length may be varied up to the maximum by repeated calls. -/// -/// Each block of information has a header and two data blocks. -/// Each block is independent, it has its own starting value. -/// The header has the number of bits (y) and the count (x) of each data -/// block. Think of the data histogrammed by its significance (y) vs. index -/// (x). Header block: yn & xn-1 & ye-1 & xe Normal block: xn fields of yn each. -/// Exception block: xe fields of ye each. -/// The exception block is absent if there are no exceptions. -/// The normal block is absent if all items are zero. -/// -/// The input is differenced and these numbers are checked -/// for the number of bits in their representation. -/// The data is optimally divided into normal points and exceptions. -/// The normal points have the differences except those points that -/// are exceptions are marked with the most negative twos complement -/// number for the size of the normal point. -/// Thus non-exceptional points are in a symmetric range about 0. -/// The exception list can approach 31/32 as long as the difference list. -/// -/// Numerical example: items = NINT(256.*SIN(LOG(1..10))) -/// items = [0,164,228,252,256,250,238,224,207,190] -/// diff = [0,164, 64, 24, 4, -6,-12,-14,-17,-17] -/// i = [0, 9, 8, 6, 4, 4, 5, 5, 6, 6] -/// y = [1,2,3,4,5,6,7,8,9] -/// tally = [1,0,0,2,2,3,0,1,1] -/// xsum = [1,1,1,3,5,8,8,9,10] -/// ye = 9; yn = 6; xe = 2; xn = 10 -/// for MAXX 1024: -/// pack = [0x00880246, 0x84620800, 0x4befcb4e, 0x080a] 110 bits -/// .0...8...0...a...4...b...e...f...c...b...4...e...8...4...6...2...0...8...0...0...0...0...8...8...0...2...4...6 -/// 00100000001010010010111110111111001011010011101000010001100010000010000000000000000000100010000000001001000110 -/// .......64......164...-17...-17...-14...-12....-6.....4....24....ex....ex.....0......xe=2.....8....xn-1=9..yn=6 -/// -/// Ken Klare, LANL P-4 (c)1990 -/// Based on ideas of Thomas W. Fredian, MIT (c)1985, the DELTA method. -/// Assumes: 8-bit bytes, 32-bit long, 2's complement -/// MdsPk/MdsUnpk do right-to-left packing/unpacking, not assumed here. -/// -/// \param cimage the name of the shared library where the compression routine -/// is to be found. -/// If Null then the default compression will be used. -/// \param centry the name of the compression image to use for compressing the -/// data. -/// If Null then the default compression will be used. -/// \param in the data to be compressed. -/// \param out the compressed data. -/// \return status value. Either 1 for success or LibSTRTRU status code if data -/// is not compressible -/// + //////////////////////////////////////////////////////////////////////////////// + /// + /// USED INTERNALLY BY MDSplus kernel libraries. + /// Compress data by passing the data to the compression routine specified + /// or the default routine, MdsCmprs. + /// + /// An algorithm to compress data with small differences. + /// Only data less than 32 bits can be packed. + /// The run length may be varied up to the maximum by repeated calls. + /// + /// Each block of information has a header and two data blocks. + /// Each block is independent, it has its own starting value. + /// The header has the number of bits (y) and the count (x) of each data + /// block. Think of the data histogrammed by its significance (y) vs. index + /// (x). Header block: yn & xn-1 & ye-1 & xe Normal block: xn fields of yn each. + /// Exception block: xe fields of ye each. + /// The exception block is absent if there are no exceptions. + /// The normal block is absent if all items are zero. + /// + /// The input is differenced and these numbers are checked + /// for the number of bits in their representation. + /// The data is optimally divided into normal points and exceptions. + /// The normal points have the differences except those points that + /// are exceptions are marked with the most negative twos complement + /// number for the size of the normal point. + /// Thus non-exceptional points are in a symmetric range about 0. + /// The exception list can approach 31/32 as long as the difference list. + /// + /// Numerical example: items = NINT(256.*SIN(LOG(1..10))) + /// items = [0,164,228,252,256,250,238,224,207,190] + /// diff = [0,164, 64, 24, 4, -6,-12,-14,-17,-17] + /// i = [0, 9, 8, 6, 4, 4, 5, 5, 6, 6] + /// y = [1,2,3,4,5,6,7,8,9] + /// tally = [1,0,0,2,2,3,0,1,1] + /// xsum = [1,1,1,3,5,8,8,9,10] + /// ye = 9; yn = 6; xe = 2; xn = 10 + /// for MAXX 1024: + /// pack = [0x00880246, 0x84620800, 0x4befcb4e, 0x080a] 110 bits + /// .0...8...0...a...4...b...e...f...c...b...4...e...8...4...6...2...0...8...0...0...0...0...8...8...0...2...4...6 + /// 00100000001010010010111110111111001011010011101000010001100010000010000000000000000000100010000000001001000110 + /// .......64......164...-17...-17...-14...-12....-6.....4....24....ex....ex.....0......xe=2.....8....xn-1=9..yn=6 + /// + /// Ken Klare, LANL P-4 (c)1990 + /// Based on ideas of Thomas W. Fredian, MIT (c)1985, the DELTA method. + /// Assumes: 8-bit bytes, 32-bit long, 2's complement + /// MdsPk/MdsUnpk do right-to-left packing/unpacking, not assumed here. + /// + /// \param cimage the name of the shared library where the compression routine + /// is to be found. + /// If Null then the default compression will be used. + /// \param centry the name of the compression image to use for compressing the + /// data. + /// If Null then the default compression will be used. + /// \param in the data to be compressed. + /// \param out the compressed data. + /// \return status value. Either 1 for success or LibSTRTRU status code if data + /// is not compressible + /// -extern int MdsCompress(const mdsdsc_t *const cimage, - const mdsdsc_t *const centry, const mdsdsc_t *const in, - mdsdsc_xd_t *const out); -extern int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, - const mdsdsc_t *const dsc2_ptr); -extern int MdsDecompress(const mdsdsc_r_t *const rec_ptr, - mdsdsc_xd_t *const out_ptr); -extern int MdsCopyDxXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out); -extern int MdsCopyDxXdZ(const mdsdsc_t *const in, mdsdsc_xd_t *const out, - void **const zone, int (*const fixup_nid)(), - void *const fixup_nid_arg, int (*const fixup_path)(), - void *const fixup_path_arg); -extern char *MdsDescrToCstring(const mdsdsc_t *const string_dsc); -extern void MdsEnableSandbox(); -extern int MDSfprintf(FILE *const fp, const char *const fmt, ...); -extern void MdsFree(void *const ptr); -extern int MdsGet1Dx(const l_length_t *const len, const dtype_t *const dtype, - mdsdsc_xd_t *const dsc, void **const zone); -extern int MdsGet1DxA(const mdsdsc_a_t *const in, const length_t *const len, - const dtype_t *const dtype, mdsdsc_xd_t *const out); -extern int MdsGet1DxS(const length_t *const len, const dtype_t *const dtype, - mdsdsc_xd_t *const out); -extern char *MdsGetMsg(const int status); -extern void MdsGetMsgDsc(const int status, mdsdsc_t *const out); -extern int MdsGetStdMsg(const int status, const char **fac_out, - const char **msgnam_out, const char **text_out); -extern int MdsFree1Dx(mdsdsc_xd_t *const dsc, void **const zone); -extern int MdsMsg(const int status, const char *const fmt, ...); -extern int MDSQueueEvent(const char *const event, int *const eventid); -extern int MDSGetEventQueue(const int eventid, const int timeout, - int *const data_len, char **const data); -extern int MdsSandboxEnabled(); -extern int MdsSerializeDscIn(const char *const in, mdsdsc_xd_t *const out); -extern int MdsSerializeDscOutZ( - const mdsdsc_t *const in, mdsdsc_xd_t *const out, int (*const fixupNid)(), - void *const fixupNidArg, int (*const fixupPath)(), void *const fixupPathArg, - const int compress, int *const compressible, l_length_t *const length, - l_length_t *const reclen, dtype_t *const dtype, class_t *const classType, - const int altbuflen, void *const altbuf, int *const data_in_altbuf); -extern int MdsSerializeDscOut(const mdsdsc_t *const in, mdsdsc_xd_t *const out); -extern int MDSSetEventTimeout(const int seconds); -extern int MDSEvent(const char *eventName, int num_bytes, char *data); -extern int MDSEventAst(const char *eventName, - void (*astadr)(void *, int, char *), void *astprm, - int *eventid); -extern int MDSEventAstMask(const char *eventName, - void (*astadr)(void *, int, char *), void *astprm, - int *eventid, unsigned int cpuMask); -extern int MDSEventCan(const int eventid); -extern int MDSWfevent(const char *const evname, const int buflen, - char *const data, int *const datlen); -extern int MDSWfeventTimed(const char *const evname, const int buflen, - char *const data, int *const datlen, - const int timeout); -extern char *MdsDtypeString(const dtype_t id); -extern char *MdsClassString(const class_t id); -extern char *MdsUsageString(const usage_t id); -extern int MDSprintf(const char *fmt, ...); -extern char *TranslateLogical(const char *name); -extern void TranslateLogicalFree(char *const value); -extern int TranslateLogicalXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out); -extern const char *MdsRelease(); -extern const mdsdsc_t *MdsReleaseDsc(); -extern int MdsPutEnv(const char *const cmd); -extern void MdsGlobalLock(); -extern void MdsGlobalUnlock(); -extern int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, - mdsdsc_a_t *const items_dsc_ptr, int *const bit_ptr); -extern char *Now32(char *buf); + extern int MdsCompress(const mdsdsc_t *const cimage, + const mdsdsc_t *const centry, const mdsdsc_t *const in, + mdsdsc_xd_t *const out); + extern int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, + const mdsdsc_t *const dsc2_ptr); + extern int MdsDecompress(const mdsdsc_r_t *const rec_ptr, + mdsdsc_xd_t *const out_ptr); + extern int MdsCopyDxXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out); + extern int MdsCopyDxXdZ(const mdsdsc_t *const in, mdsdsc_xd_t *const out, + void **const zone, int (*const fixup_nid)(), + void *const fixup_nid_arg, int (*const fixup_path)(), + void *const fixup_path_arg); + extern char *MdsDescrToCstring(const mdsdsc_t *const string_dsc); + extern void MdsEnableSandbox(); + extern int MDSfprintf(FILE *const fp, const char *const fmt, ...); + extern void MdsFree(void *const ptr); + extern int MdsGet1Dx(const l_length_t *const len, const dtype_t *const dtype, + mdsdsc_xd_t *const dsc, void **const zone); + extern int MdsGet1DxA(const mdsdsc_a_t *const in, const length_t *const len, + const dtype_t *const dtype, mdsdsc_xd_t *const out); + extern int MdsGet1DxS(const length_t *const len, const dtype_t *const dtype, + mdsdsc_xd_t *const out); + extern char *MdsGetMsg(const int status); + extern void MdsGetMsgDsc(const int status, mdsdsc_t *const out); + extern int MdsGetStdMsg(const int status, const char **fac_out, + const char **msgnam_out, const char **text_out); + extern int MdsFree1Dx(mdsdsc_xd_t *const dsc, void **const zone); + extern int MdsMsg(const int status, const char *const fmt, ...); + extern int MDSQueueEvent(const char *const event, int *const eventid); + extern int MDSGetEventQueue(const int eventid, const int timeout, + int *const data_len, char **const data); + extern int MdsSandboxEnabled(); + extern int MdsSerializeDscIn(const char *const in, mdsdsc_xd_t *const out); + extern int MdsSerializeDscOutZ( + const mdsdsc_t *const in, mdsdsc_xd_t *const out, int (*const fixupNid)(), + void *const fixupNidArg, int (*const fixupPath)(), void *const fixupPathArg, + const int compress, int *const compressible, l_length_t *const length, + l_length_t *const reclen, dtype_t *const dtype, class_t *const classType, + const int altbuflen, void *const altbuf, int *const data_in_altbuf); + extern int MdsSerializeDscOut(const mdsdsc_t *const in, mdsdsc_xd_t *const out); + extern int MDSSetEventTimeout(const int seconds); + extern int MDSEvent(const char *eventName, int num_bytes, char *data); + extern int MDSEventAst(const char *eventName, + void (*astadr)(void *, int, char *), void *astprm, + int *eventid); + extern int MDSEventAstMask(const char *eventName, + void (*astadr)(void *, int, char *), void *astprm, + int *eventid, unsigned int cpuMask); + extern int MDSEventCan(const int eventid); + extern int MDSWfevent(const char *const evname, const int buflen, + char *const data, int *const datlen); + extern int MDSWfeventTimed(const char *const evname, const int buflen, + char *const data, int *const datlen, + const int timeout); + extern char *MdsDtypeString(const dtype_t id); + extern char *MdsClassString(const class_t id); + extern char *MdsUsageString(const usage_t id); + extern int MDSprintf(const char *fmt, ...); + extern char *TranslateLogical(const char *name); + extern void TranslateLogicalFree(char *const value); + extern int TranslateLogicalXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out); + extern const char *MdsRelease(); + extern const mdsdsc_t *MdsReleaseDsc(); + extern int MdsPutEnv(const char *const cmd); + extern void MdsGlobalLock(); + extern void MdsGlobalUnlock(); + extern int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, + mdsdsc_a_t *const items_dsc_ptr, int *const bit_ptr); + extern char *Now32(char *buf); #ifdef HAVE_PTHREAD_H #include -// FREEXD -static void __attribute__((unused)) free_xd(void *ptr) { - MdsFree1Dx((mdsdsc_xd_t *)ptr, NULL); -} + // FREEXD + static void __attribute__((unused)) free_xd(void *ptr) + { + MdsFree1Dx((mdsdsc_xd_t *)ptr, NULL); + } #define FREEXD_ON_EXIT(ptr) pthread_cleanup_push(free_xd, ptr) #define FREEXD_IF(ptr, c) pthread_cleanup_pop(c) #define FREEXD_NOW(ptr) FREEXD_IF(ptr, 1) #define FREEXD_CANCEL(ptr) FREEXD_IF(ptr, 0) -#define INIT_AND_FREEXD_ON_EXIT(xd) \ - EMPTYXD(xd); \ +#define INIT_AND_FREEXD_ON_EXIT(xd) \ + EMPTYXD(xd); \ FREEXD_ON_EXIT(&xd) #endif diff --git a/include/mdsversion.h b/include/mdsversion.h index 2ff9529142..35f574c2d4 100644 --- a/include/mdsversion.h +++ b/include/mdsversion.h @@ -1,7 +1,8 @@ #include #pragma pack(push) -typedef struct { +typedef struct +{ const int MAJOR; const int MINOR; const int MICRO; diff --git a/include/mitdevices_msg.h b/include/mitdevices_msg.h index a6eca15bef..1accf3c857 100644 --- a/include/mitdevices_msg.h +++ b/include/mitdevices_msg.h @@ -12,331 +12,333 @@ #endif -#define DEV$_BAD_ENDIDX \ +#define DEV$_BAD_ENDIDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_FILTER \ +#define DEV$_BAD_FILTER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 2 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_FREQ \ +#define DEV$_BAD_FREQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 3 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_GAIN \ +#define DEV$_BAD_GAIN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 4 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_HEADER \ +#define DEV$_BAD_HEADER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 5 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_HEADER_IDX \ +#define DEV$_BAD_HEADER_IDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 6 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_MEMORIES \ +#define DEV$_BAD_MEMORIES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 7 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_MODE \ +#define DEV$_BAD_MODE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 8 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_NAME \ +#define DEV$_BAD_NAME \ (MSG_MASK + 2015 * MSG_FACNUM_M + 9 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_OFFSET \ +#define DEV$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 10 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_STARTIDX \ +#define DEV$_BAD_STARTIDX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 11 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_NOT_TRIGGERED \ +#define DEV$_NOT_TRIGGERED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 12 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_FREQ_TO_HIGH \ +#define DEV$_FREQ_TO_HIGH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 13 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_INVALID_NOC \ +#define DEV$_INVALID_NOC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 14 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_RANGE_MISMATCH \ +#define DEV$_RANGE_MISMATCH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 15 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAMACERR \ +#define DEV$_CAMACERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 16 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_VERBS \ +#define DEV$_BAD_VERBS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 17 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_BAD_COMMANDS \ +#define DEV$_BAD_COMMANDS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 18 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_ADNR \ +#define DEV$_CAM_ADNR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 19 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_ERR \ +#define DEV$_CAM_ERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 20 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_LOSYNC \ +#define DEV$_CAM_LOSYNC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 21 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_LPE \ +#define DEV$_CAM_LPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 22 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_TMO \ +#define DEV$_CAM_TMO \ (MSG_MASK + 2015 * MSG_FACNUM_M + 23 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_TPE \ +#define DEV$_CAM_TPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 24 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_STE \ +#define DEV$_CAM_STE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 25 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_DERR \ +#define DEV$_CAM_DERR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 26 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_SQ \ +#define DEV$_CAM_SQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 27 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_NOSQ \ +#define DEV$_CAM_NOSQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 28 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_SX \ +#define DEV$_CAM_SX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 29 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_CAM_NOSX \ +#define DEV$_CAM_NOSX \ (MSG_MASK + 2015 * MSG_FACNUM_M + 30 * MSG_MSGNUM_M + MSG_ERROR) -#define DEV$_INV_SETUP \ +#define DEV$_INV_SETUP \ (MSG_MASK + 2015 * MSG_FACNUM_M + 31 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_NORMAL \ +#define RETICON$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 51 * MSG_MSGNUM_M + MSG_SUCCESS) -#define RETICON$_BAD_FRAMES \ +#define RETICON$_BAD_FRAMES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 52 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_BAD_FRAME_SELECT \ +#define RETICON$_BAD_FRAME_SELECT \ (MSG_MASK + 2015 * MSG_FACNUM_M + 53 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_BAD_NUM_STATES \ +#define RETICON$_BAD_NUM_STATES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 54 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_BAD_PERIOD \ +#define RETICON$_BAD_PERIOD \ (MSG_MASK + 2015 * MSG_FACNUM_M + 55 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_BAD_PIXEL_SELECT \ +#define RETICON$_BAD_PIXEL_SELECT \ (MSG_MASK + 2015 * MSG_FACNUM_M + 56 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_DATA_CORRUPTED \ +#define RETICON$_DATA_CORRUPTED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 57 * MSG_MSGNUM_M + MSG_ERROR) -#define RETICON$_TOO_MANY_FRAMES \ +#define RETICON$_TOO_MANY_FRAMES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 58 * MSG_MSGNUM_M + MSG_ERROR) -#define J221$_NORMAL \ +#define J221$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 101 * MSG_MSGNUM_M + MSG_SUCCESS) -#define J221$_INVALID_DATA \ +#define J221$_INVALID_DATA \ (MSG_MASK + 2015 * MSG_FACNUM_M + 102 * MSG_MSGNUM_M + MSG_WARNING) -#define J221$_NO_DATA \ +#define J221$_NO_DATA \ (MSG_MASK + 2015 * MSG_FACNUM_M + 103 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVCLKFRQ \ +#define TIMING$_INVCLKFRQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 151 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVDELDUR \ +#define TIMING$_INVDELDUR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 152 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVOUTCTR \ +#define TIMING$_INVOUTCTR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 153 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVPSEUDODEV \ +#define TIMING$_INVPSEUDODEV \ (MSG_MASK + 2015 * MSG_FACNUM_M + 154 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVTRGMOD \ +#define TIMING$_INVTRGMOD \ (MSG_MASK + 2015 * MSG_FACNUM_M + 155 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_NOPSEUDODEV \ +#define TIMING$_NOPSEUDODEV \ (MSG_MASK + 2015 * MSG_FACNUM_M + 156 * MSG_MSGNUM_M + MSG_INFO) -#define TIMING$_TOO_MANY_EVENTS \ +#define TIMING$_TOO_MANY_EVENTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 157 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_INVDUTY \ +#define TIMING$_INVDUTY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 158 * MSG_MSGNUM_M + MSG_ERROR) -#define TIMING$_ \ +#define TIMING$_ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 159 * MSG_MSGNUM_M + MSG_ERROR) -#define B2408$_NORMAL \ +#define B2408$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 201 * MSG_MSGNUM_M + MSG_SUCCESS) -#define B2408$_OVERFLOW \ +#define B2408$_OVERFLOW \ (MSG_MASK + 2015 * MSG_FACNUM_M + 202 * MSG_MSGNUM_M + MSG_INFO) -#define B2408$_TRIG_LIM \ +#define B2408$_TRIG_LIM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 203 * MSG_MSGNUM_M + MSG_WARNING) -#define FERA$_NORMAL \ +#define FERA$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 251 * MSG_MSGNUM_M + MSG_SUCCESS) -#define FERA$_DIGNOTSTRARRAY \ +#define FERA$_DIGNOTSTRARRAY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 252 * MSG_MSGNUM_M + MSG_ERROR) -#define FERA$_NODIG \ +#define FERA$_NODIG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 253 * MSG_MSGNUM_M + MSG_ERROR) -#define FERA$_MEMNOTSTRARRAY \ +#define FERA$_MEMNOTSTRARRAY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 254 * MSG_MSGNUM_M + MSG_ERROR) -#define FERA$_NOMEM \ +#define FERA$_NOMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 255 * MSG_MSGNUM_M + MSG_ERROR) -#define FERA$_PHASE_LOST \ +#define FERA$_PHASE_LOST \ (MSG_MASK + 2015 * MSG_FACNUM_M + 256 * MSG_MSGNUM_M + MSG_ERROR) -#define FERA$_CONFUSED \ +#define FERA$_CONFUSED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 257 * MSG_MSGNUM_M + MSG_WARNING) -#define FERA$_OVER_RUN \ +#define FERA$_OVER_RUN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 258 * MSG_MSGNUM_M + MSG_WARNING) -#define FERA$_OVERFLOW \ +#define FERA$_OVERFLOW \ (MSG_MASK + 2015 * MSG_FACNUM_M + 259 * MSG_MSGNUM_M + MSG_INFO) -#define HM650$_NORMAL \ +#define HM650$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 301 * MSG_MSGNUM_M + MSG_SUCCESS) -#define HM650$_DLYCHNG \ +#define HM650$_DLYCHNG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 302 * MSG_MSGNUM_M + MSG_WARNING) -#define HV4032$_NORMAL \ +#define HV4032$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 351 * MSG_MSGNUM_M + MSG_SUCCESS) -#define HV4032$_WRONG_POD_TYPE \ +#define HV4032$_WRONG_POD_TYPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 352 * MSG_MSGNUM_M + MSG_ERROR) -#define HV1440$_NORMAL \ +#define HV1440$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 401 * MSG_MSGNUM_M + MSG_SUCCESS) -#define HV1440$_WRONG_POD_TYPE \ +#define HV1440$_WRONG_POD_TYPE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 402 * MSG_MSGNUM_M + MSG_ERROR) -#define HV1440$_BAD_FRAME \ +#define HV1440$_BAD_FRAME \ (MSG_MASK + 2015 * MSG_FACNUM_M + 403 * MSG_MSGNUM_M + MSG_ERROR) -#define HV1440$_BAD_RANGE \ +#define HV1440$_BAD_RANGE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 404 * MSG_MSGNUM_M + MSG_ERROR) -#define HV1440$_OUTRNG \ +#define HV1440$_OUTRNG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 405 * MSG_MSGNUM_M + MSG_ERROR) -#define HV1440$_STUCK \ +#define HV1440$_STUCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 406 * MSG_MSGNUM_M + MSG_ERROR) -#define JOERGER$_BAD_PRE_TRIGGER \ +#define JOERGER$_BAD_PRE_TRIGGER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 451 * MSG_MSGNUM_M + MSG_ERROR) -#define JOERGER$_BAD_ACT_MEMORY \ +#define JOERGER$_BAD_ACT_MEMORY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 452 * MSG_MSGNUM_M + MSG_ERROR) -#define JOERGER$_BAD_GAIN \ +#define JOERGER$_BAD_GAIN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 453 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_WAVE_LENGTH \ +#define U_OF_M$_BAD_WAVE_LENGTH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 501 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_SLIT_WIDTH \ +#define U_OF_M$_BAD_SLIT_WIDTH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 502 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_NUM_SPECTRA \ +#define U_OF_M$_BAD_NUM_SPECTRA \ (MSG_MASK + 2015 * MSG_FACNUM_M + 503 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_GRATING \ +#define U_OF_M$_BAD_GRATING \ (MSG_MASK + 2015 * MSG_FACNUM_M + 504 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_EXPOSURE \ +#define U_OF_M$_BAD_EXPOSURE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 505 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_BAD_FILTER \ +#define U_OF_M$_BAD_FILTER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 506 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_GO_FILE_ERROR \ +#define U_OF_M$_GO_FILE_ERROR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 507 * MSG_MSGNUM_M + MSG_ERROR) -#define U_OF_M$_DATA_FILE_ERROR \ +#define U_OF_M$_DATA_FILE_ERROR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 508 * MSG_MSGNUM_M + MSG_ERROR) -#define IDL$_NORMAL \ +#define IDL$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 551 * MSG_MSGNUM_M + MSG_SUCCESS) -#define IDL$_ERROR \ +#define IDL$_ERROR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 552 * MSG_MSGNUM_M + MSG_ERROR) -#define B5910A$_BAD_CHAN \ +#define B5910A$_BAD_CHAN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 601 * MSG_MSGNUM_M + MSG_ERROR) -#define B5910A$_BAD_CLOCK \ +#define B5910A$_BAD_CLOCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 602 * MSG_MSGNUM_M + MSG_ERROR) -#define B5910A$_BAD_ITERATIONS \ +#define B5910A$_BAD_ITERATIONS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 603 * MSG_MSGNUM_M + MSG_ERROR) -#define B5910A$_BAD_NOC \ +#define B5910A$_BAD_NOC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 604 * MSG_MSGNUM_M + MSG_ERROR) -#define B5910A$_BAD_SAMPS \ +#define B5910A$_BAD_SAMPS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 605 * MSG_MSGNUM_M + MSG_ERROR) -#define J412$_NOT_SORTED \ +#define J412$_NOT_SORTED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 651 * MSG_MSGNUM_M + MSG_ERROR) -#define J412$_NO_DATA \ +#define J412$_NO_DATA \ (MSG_MASK + 2015 * MSG_FACNUM_M + 652 * MSG_MSGNUM_M + MSG_ERROR) -#define J412$_BADCYCLES \ +#define J412$_BADCYCLES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 653 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_NORMAL \ +#define TR16$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 701 * MSG_MSGNUM_M + MSG_SUCCESS) -#define TR16$_BAD_MEMSIZE \ +#define TR16$_BAD_MEMSIZE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 702 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_ACTIVEMEM \ +#define TR16$_BAD_ACTIVEMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 703 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_ACTIVECHAN \ +#define TR16$_BAD_ACTIVECHAN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 704 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_PTS \ +#define TR16$_BAD_PTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 705 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_FREQUENCY \ +#define TR16$_BAD_FREQUENCY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 706 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_MASTER \ +#define TR16$_BAD_MASTER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 707 * MSG_MSGNUM_M + MSG_ERROR) -#define TR16$_BAD_GAIN \ +#define TR16$_BAD_GAIN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 708 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_NORMAL \ +#define A14$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 751 * MSG_MSGNUM_M + MSG_SUCCESS) -#define A14$_BAD_CLK_DIVIDE \ +#define A14$_BAD_CLK_DIVIDE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 752 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_BAD_MODE \ +#define A14$_BAD_MODE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 753 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_BAD_CLK_POLARITY \ +#define A14$_BAD_CLK_POLARITY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 754 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_BAD_STR_POLARITY \ +#define A14$_BAD_STR_POLARITY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 755 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_BAD_STP_POLARITY \ +#define A14$_BAD_STP_POLARITY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 756 * MSG_MSGNUM_M + MSG_ERROR) -#define A14$_BAD_GATED \ +#define A14$_BAD_GATED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 757 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_NORMAL \ +#define L6810$_NORMAL \ (MSG_MASK + 2015 * MSG_FACNUM_M + 801 * MSG_MSGNUM_M + MSG_SUCCESS) -#define L6810$_BAD_ACTIVECHAN \ +#define L6810$_BAD_ACTIVECHAN \ (MSG_MASK + 2015 * MSG_FACNUM_M + 802 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_ACTIVEMEM \ +#define L6810$_BAD_ACTIVEMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 803 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_FREQUENCY \ +#define L6810$_BAD_FREQUENCY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 804 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_FULL_SCALE \ +#define L6810$_BAD_FULL_SCALE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 805 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_MEMORIES \ +#define L6810$_BAD_MEMORIES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 806 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_COUPLING \ +#define L6810$_BAD_COUPLING \ (MSG_MASK + 2015 * MSG_FACNUM_M + 807 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_OFFSET \ +#define L6810$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 808 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_SEGMENTS \ +#define L6810$_BAD_SEGMENTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 809 * MSG_MSGNUM_M + MSG_ERROR) -#define L6810$_BAD_TRIG_DELAY \ +#define L6810$_BAD_TRIG_DELAY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 810 * MSG_MSGNUM_M + MSG_ERROR) -#define J_DAC$_OUTRNG \ +#define J_DAC$_OUTRNG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 851 * MSG_MSGNUM_M + MSG_ERROR) -#define INCAA$_BAD_ACTIVE_CHANS \ +#define INCAA$_BAD_ACTIVE_CHANS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 901 * MSG_MSGNUM_M + MSG_ERROR) -#define INCAA$_BAD_MASTER \ +#define INCAA$_BAD_MASTER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 902 * MSG_MSGNUM_M + MSG_ERROR) -#define INCAA$_BAD_EXT_1MHZ \ +#define INCAA$_BAD_EXT_1MHZ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 903 * MSG_MSGNUM_M + MSG_ERROR) -#define INCAA$_BAD_PTSC \ +#define INCAA$_BAD_PTSC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 904 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_BAD_HEADER \ +#define L8212$_BAD_HEADER \ (MSG_MASK + 2015 * MSG_FACNUM_M + 951 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_BAD_MEMORIES \ +#define L8212$_BAD_MEMORIES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 952 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_BAD_NOC \ +#define L8212$_BAD_NOC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 953 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_BAD_OFFSET \ +#define L8212$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 954 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_BAD_PTS \ +#define L8212$_BAD_PTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 955 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_FREQ_TO_HIGH \ +#define L8212$_FREQ_TO_HIGH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 956 * MSG_MSGNUM_M + MSG_ERROR) -#define L8212$_INVALID_NOC \ +#define L8212$_INVALID_NOC \ (MSG_MASK + 2015 * MSG_FACNUM_M + 957 * MSG_MSGNUM_M + MSG_ERROR) -#define MPB$_BADTIME \ +#define MPB$_BADTIME \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1001 * MSG_MSGNUM_M + MSG_ERROR) -#define MPB$_BADFREQ \ +#define MPB$_BADFREQ \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1002 * MSG_MSGNUM_M + MSG_ERROR) -#define L8828$_BAD_OFFSET \ +#define L8828$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1051 * MSG_MSGNUM_M + MSG_ERROR) -#define L8828$_BAD_PRETRIG \ +#define L8828$_BAD_PRETRIG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1052 * MSG_MSGNUM_M + MSG_ERROR) -#define L8828$_BAD_ACTIVEMEM \ +#define L8828$_BAD_ACTIVEMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1053 * MSG_MSGNUM_M + MSG_ERROR) -#define L8828$_BAD_CLOCK \ +#define L8828$_BAD_CLOCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1054 * MSG_MSGNUM_M + MSG_ERROR) -#define L8818$_BAD_OFFSET \ +#define L8818$_BAD_OFFSET \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1101 * MSG_MSGNUM_M + MSG_ERROR) -#define L8818$_BAD_PRETRIG \ +#define L8818$_BAD_PRETRIG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1102 * MSG_MSGNUM_M + MSG_ERROR) -#define L8818$_BAD_ACTIVEMEM \ +#define L8818$_BAD_ACTIVEMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1103 * MSG_MSGNUM_M + MSG_ERROR) -#define L8818$_BAD_CLOCK \ +#define L8818$_BAD_CLOCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1104 * MSG_MSGNUM_M + MSG_ERROR) -#define J_TR612$_BAD_ACTMEM \ +#define J_TR612$_BAD_ACTMEM \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1111 * MSG_MSGNUM_M + MSG_ERROR) -#define J_TR612$_BAD_PRETRIG \ +#define J_TR612$_BAD_PRETRIG \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1112 * MSG_MSGNUM_M + MSG_ERROR) -#define J_TR612$_BAD_MODE \ +#define J_TR612$_BAD_MODE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1113 * MSG_MSGNUM_M + MSG_ERROR) -#define J_TR612$_BAD_FREQUENCY \ +#define J_TR612$_BAD_FREQUENCY \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1114 * MSG_MSGNUM_M + MSG_ERROR) -#define L8206$_NODATA \ +#define L8206$_NODATA \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1151 * MSG_MSGNUM_M + MSG_WARNING) -#define H912$_BAD_CLOCK \ +#define H912$_BAD_CLOCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1161 * MSG_MSGNUM_M + MSG_ERROR) -#define H912$_BAD_BLOCKS \ +#define H912$_BAD_BLOCKS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1162 * MSG_MSGNUM_M + MSG_ERROR) -#define H912$_BAD_PTS \ +#define H912$_BAD_PTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1163 * MSG_MSGNUM_M + MSG_ERROR) -#define H908$_BAD_CLOCK \ +#define H908$_BAD_CLOCK \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1171 * MSG_MSGNUM_M + MSG_ERROR) -#define H908$_BAD_ACTIVE_CHANS \ +#define H908$_BAD_ACTIVE_CHANS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1172 * MSG_MSGNUM_M + MSG_ERROR) -#define H908$_BAD_PTS \ +#define H908$_BAD_PTS \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1173 * MSG_MSGNUM_M + MSG_ERROR) -#define DSP2904$_CHANNEL_READ_ERROR \ +#define DSP2904$_CHANNEL_READ_ERROR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1181 * MSG_MSGNUM_M + MSG_ERROR) -#define PY$_UNHANDLED_EXCEPTION \ +#define PY$_UNHANDLED_EXCEPTION \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1191 * MSG_MSGNUM_M + MSG_ERROR) -#define DT196B$_NO_SAMPLES \ +#define DT196B$_NO_SAMPLES \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1201 * MSG_MSGNUM_M + MSG_ERROR) -#define ACQ$_INITIALIZATION_ERROR \ +#define ACQ$_INITIALIZATION_ERROR \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1202 * MSG_MSGNUM_M + MSG_ERROR) -#define ACQ$_SETTINGS_NOT_LOADED \ +#define ACQ$_SETTINGS_NOT_LOADED \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1203 * MSG_MSGNUM_M + MSG_ERROR) -#define ACQ$_WRONG_TREE \ +#define ACQ$_WRONG_TREE \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1204 * MSG_MSGNUM_M + MSG_ERROR) -#define ACQ$_WRONG_PATH \ +#define ACQ$_WRONG_PATH \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1205 * MSG_MSGNUM_M + MSG_ERROR) -#define ACQ$_WRONG_SHOT \ +#define ACQ$_WRONG_SHOT \ (MSG_MASK + 2015 * MSG_FACNUM_M + 1206 * MSG_MSGNUM_M + MSG_ERROR) #ifdef MSG_LIBRARY #include -EXPORT int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { - static struct msg { +EXPORT int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) +{ + static struct msg + { int sts; char *facnam; char *msgnam; @@ -626,8 +628,10 @@ EXPORT int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) { "with"}}; size_t i; int status = 0; - for (i = 0; i < sizeof(msgs) / sizeof(struct msg); i++) { - if (msgs[i].sts == sts) { + for (i = 0; i < sizeof(msgs) / sizeof(struct msg); i++) + { + if (msgs[i].sts == sts) + { *facnam = msgs[i].facnam; *msgnam = msgs[i].msgnam; *msgtext = msgs[i].msgtext; diff --git a/include/msc_stdint.h b/include/msc_stdint.h index a055e3c496..83ab3e9d11 100644 --- a/include/msc_stdint.h +++ b/include/msc_stdint.h @@ -52,7 +52,8 @@ // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include #ifdef __cplusplus @@ -122,9 +123,8 @@ typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types -#if !defined(__cplusplus) || \ - defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and - // footnote 221 at page 259 +#if !defined(__cplusplus) || \ + defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) @@ -220,7 +220,7 @@ typedef uint64_t uintmax_t; // 7.18.4 Limits of other integer types -#if !defined(__cplusplus) || \ +#if !defined(__cplusplus) || \ defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants diff --git a/include/ncidef.h b/include/ncidef.h index 0f6aac2ac6..2bd136c45a 100644 --- a/include/ncidef.h +++ b/include/ncidef.h @@ -11,8 +11,8 @@ #ifdef MDSOBJECTSCPPSHRVS_EXPORTS // visual studio uses int types for typedef #define TYPEDEF(bytes) enum -#define ENDDEF(type, name) \ - ; \ +#define ENDDEF(type, name) \ + ; \ typedef type name #else #define TYPEDEF(bytes) typedef enum __attribute__((__packed__)) @@ -86,7 +86,8 @@ TYPEDEF(4){ } ENDDEF(int16_t, nci_t); #undef TYPEDEF #undef ENDDEF -typedef struct nci_itm { +typedef struct nci_itm +{ int16_t buffer_length; nci_t code; void *pointer; diff --git a/include/pthread_port.h b/include/pthread_port.h index 63f132bb47..56bbf19e42 100644 --- a/include/pthread_port.h +++ b/include/pthread_port.h @@ -19,28 +19,29 @@ #endif #ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP -#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER \ +#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER \ PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #endif #endif #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER -#define STATIC_PTHREAD_RECURSIVE_MUTEX_DEF(name) \ +#define STATIC_PTHREAD_RECURSIVE_MUTEX_DEF(name) \ static pthread_mutex_t name = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; #define STATIC_PTHREAD_RECURSIVE_MUTEX_INIT(name) #else -#define STATIC_PTHREAD_RECURSIVE_MUTEX_DEF(name) \ - static pthread_mutex_t name; \ - static pthread_once_t __##name##__once = PTHREAD_ONCE_INIT; \ - static void init__##name##__once() { \ - pthread_mutexattr_t attr; \ - if (pthread_mutexattr_init(&attr)) \ - abort(); \ - if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) \ - abort(); \ - pthread_mutex_init(&name, &attr); \ - pthread_mutexattr_destroy(&attr); \ +#define STATIC_PTHREAD_RECURSIVE_MUTEX_DEF(name) \ + static pthread_mutex_t name; \ + static pthread_once_t __##name##__once = PTHREAD_ONCE_INIT; \ + static void init__##name##__once() \ + { \ + pthread_mutexattr_t attr; \ + if (pthread_mutexattr_init(&attr)) \ + abort(); \ + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) \ + abort(); \ + pthread_mutex_init(&name, &attr); \ + pthread_mutexattr_destroy(&attr); \ } -#define STATIC_PTHREAD_RECURSIVE_MUTEX_INIT(name) \ +#define STATIC_PTHREAD_RECURSIVE_MUTEX_INIT(name) \ pthread_once(&__##name##__once, init__##name##__once); #endif @@ -57,12 +58,12 @@ #define CLOCK_REALTIME 0 // clock_gettime is not implemented on older versions of OS X (< 10.12). // If implemented, CLOCK_REALTIME will have already been defined. -#define clock_gettime(clk_id_unused, timespec) \ - { \ - struct timeval now; \ - int rv = gettimeofday(&now, NULL); \ - (timespec)->tv_sec = rv ? 0 : now.tv_sec; \ - (timespec)->tv_nsec = rv ? 0 : now.tv_usec * 1000; \ +#define clock_gettime(clk_id_unused, timespec) \ + { \ + struct timeval now; \ + int rv = gettimeofday(&now, NULL); \ + (timespec)->tv_sec = rv ? 0 : now.tv_sec; \ + (timespec)->tv_nsec = rv ? 0 : now.tv_usec * 1000; \ } #endif @@ -72,15 +73,16 @@ static void __attribute__((unused)) free_if(void *ptr) { free(*(void **)ptr); } #define FREE_IF(ptr, c) pthread_cleanup_pop(c); #define FREE_NOW(ptr) FREE_IF(ptr, 1) #define FREE_CANCEL(ptr) FREE_IF(ptr, 0) -#define INIT_AS_AND_FREE_ON_EXIT(type, ptr, value) \ - type ptr = value; \ +#define INIT_AS_AND_FREE_ON_EXIT(type, ptr, value) \ + type ptr = value; \ FREE_ON_EXIT(ptr) -#define INIT_AND_FREE_ON_EXIT(type, ptr) \ +#define INIT_AND_FREE_ON_EXIT(type, ptr) \ INIT_AS_AND_FREE_ON_EXIT(type, ptr, NULL) // FCLOSE #include -static void __attribute__((unused)) fclose_if(void *ptr) { +static void __attribute__((unused)) fclose_if(void *ptr) +{ if (*(FILE **)ptr) fclose(*(FILE **)ptr); } @@ -88,19 +90,20 @@ static void __attribute__((unused)) fclose_if(void *ptr) { #define FCLOSE_IF(ptr, c) pthread_cleanup_pop(c) #define FCLOSE_NOW(ptr) FCLOSE_IF(ptr, 1) #define FCLOSE_CANCEL(ptr) FCLOSE_IF(ptr, 0) -#define INIT_AS_AND_FCLOSE_ON_EXIT(ptr, value) \ - FILE *ptr = value; \ +#define INIT_AS_AND_FCLOSE_ON_EXIT(ptr, value) \ + FILE *ptr = value; \ FCLOSE_ON_EXIT(ptr) #define INIT_AND_FCLOSE_ON_EXIT(ptr) INIT_AS_AND_FCLOSE_ON_EXIT(ptr, NULL) -#define INIT_SHARED_FUNCTION_ONCE(fun) \ +#define INIT_SHARED_FUNCTION_ONCE(fun) \ static pthread_once_t __##fun##__once = PTHREAD_ONCE_INIT -#define RUN_SHARED_FUNCTION_ONCE(fun) \ +#define RUN_SHARED_FUNCTION_ONCE(fun) \ pthread_once(&__##fun##__once, (void *)fun) -#define RUN_FUNCTION_ONCE(fun) \ - do { \ - INIT_SHARED_FUNCTION_ONCE(fun); \ - RUN_SHARED_FUNCTION_ONCE(fun); \ +#define RUN_FUNCTION_ONCE(fun) \ + do \ + { \ + INIT_SHARED_FUNCTION_ONCE(fun); \ + RUN_SHARED_FUNCTION_ONCE(fun); \ } while (0) #endif // PTHREAD_PORT_H diff --git a/include/socket_port.h b/include/socket_port.h index 9ecfc85eb0..ae759a9e07 100644 --- a/include/socket_port.h +++ b/include/socket_port.h @@ -43,13 +43,14 @@ typedef int SOCKET; #define RECV_BUF_SIZE 32768 #ifdef _WIN32 -#define DEFINE_INITIALIZESOCKETS \ - static void InitializeSockets() { \ - WSADATA wsaData; \ - WORD wVersionRequested; \ - wVersionRequested = MAKEWORD(1, 1); \ - WSAStartup(wVersionRequested, &wsaData); \ - } \ +#define DEFINE_INITIALIZESOCKETS \ + static void InitializeSockets() \ + { \ + WSADATA wsaData; \ + WORD wVersionRequested; \ + wVersionRequested = MAKEWORD(1, 1); \ + WSAStartup(wVersionRequested, &wsaData); \ + } \ INIT_SHARED_FUNCTION_ONCE(InitializeSockets) #define INITIALIZESOCKETS RUN_SHARED_FUNCTION_ONCE(InitializeSockets) #else diff --git a/include/sqldb.h b/include/sqldb.h index f283e783d2..371612d4be 100644 --- a/include/sqldb.h +++ b/include/sqldb.h @@ -2,7 +2,8 @@ #define _INC_SQLDB #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /***************************************************************************** @@ -26,16 +27,16 @@ extern "C" { #define DBSETLTIME(a, b) dbsetlname((a), (LPCSTR)(ULONG)(b), DBSETLOGINTIME) #define DBSETLFALLBACK(a, b) dbsetlname((a), (b), DBSETFALLBACK) -/***************************************************************************** + /***************************************************************************** * Windows 3.x and Non-Windows 3.x differences. * *****************************************************************************/ #ifdef DBMSWIN -extern void SQLAPI dbwinexit(void); + extern void SQLAPI dbwinexit(void); -void SQLAPI dblocklib(void); -void SQLAPI dbunlocklib(void); + void SQLAPI dblocklib(void); + void SQLAPI dbunlocklib(void); #define DBLOCKLIB() dblocklib() #define DBUNLOCKLIB() dbunlocklib() @@ -43,8 +44,8 @@ void SQLAPI dbunlocklib(void); #define DBERRHANDLE_PROC FARPROC #define DBMSGHANDLE_PROC FARPROC -extern DBERRHANDLE_PROC dberrhandle(DBERRHANDLE_PROC); -extern DBMSGHANDLE_PROC dbmsghandle(DBMSGHANDLE_PROC); + extern DBERRHANDLE_PROC dberrhandle(DBERRHANDLE_PROC); + extern DBMSGHANDLE_PROC dbmsghandle(DBMSGHANDLE_PROC); #else @@ -87,176 +88,176 @@ extern DBMSGHANDLE_PROC SQLAPI dbprocmsghandle(PDBHANDLE, DBMSGHANDLE_PROC); #define DBROWS(a) dbrows(a) #define DBROWTYPE(a) dbrowtype(a) -// Two-phase commit functions -extern RETCODE SQLAPI abort_xact(PDBPROCESS, DBINT); -extern void SQLAPI build_xact_string(LPCSTR, LPCSTR, DBINT, LPSTR); -extern void SQLAPI close_commit(PDBPROCESS); -extern RETCODE SQLAPI commit_xact(PDBPROCESS, DBINT); -extern PDBPROCESS SQLAPI open_commit(PLOGINREC, LPCSTR); -extern RETCODE SQLAPI remove_xact(PDBPROCESS, DBINT, INT); -extern RETCODE SQLAPI scan_xact(PDBPROCESS, DBINT); -extern DBINT SQLAPI start_xact(PDBPROCESS, LPCSTR, LPCSTR, INT); -extern INT SQLAPI stat_xact(PDBPROCESS, DBINT); + // Two-phase commit functions + extern RETCODE SQLAPI abort_xact(PDBPROCESS, DBINT); + extern void SQLAPI build_xact_string(LPCSTR, LPCSTR, DBINT, LPSTR); + extern void SQLAPI close_commit(PDBPROCESS); + extern RETCODE SQLAPI commit_xact(PDBPROCESS, DBINT); + extern PDBPROCESS SQLAPI open_commit(PLOGINREC, LPCSTR); + extern RETCODE SQLAPI remove_xact(PDBPROCESS, DBINT, INT); + extern RETCODE SQLAPI scan_xact(PDBPROCESS, DBINT); + extern DBINT SQLAPI start_xact(PDBPROCESS, LPCSTR, LPCSTR, INT); + extern INT SQLAPI stat_xact(PDBPROCESS, DBINT); -// BCP functions -extern DBINT SQLAPI bcp_batch(PDBPROCESS); -extern RETCODE SQLAPI bcp_bind(PDBPROCESS, LPCBYTE, INT, DBINT, LPCBYTE, INT, - INT, INT); -extern RETCODE SQLAPI bcp_colfmt(PDBPROCESS, INT, BYTE, INT, DBINT, LPCBYTE, + // BCP functions + extern DBINT SQLAPI bcp_batch(PDBPROCESS); + extern RETCODE SQLAPI bcp_bind(PDBPROCESS, LPCBYTE, INT, DBINT, LPCBYTE, INT, INT, INT); -extern RETCODE SQLAPI bcp_collen(PDBPROCESS, DBINT, INT); -extern RETCODE SQLAPI bcp_colptr(PDBPROCESS, LPCBYTE, INT); -extern RETCODE SQLAPI bcp_columns(PDBPROCESS, INT); -extern RETCODE SQLAPI bcp_control(PDBPROCESS, INT, DBINT); -extern DBINT SQLAPI bcp_done(PDBPROCESS); -extern RETCODE SQLAPI bcp_exec(PDBPROCESS, LPDBINT); -extern RETCODE SQLAPI bcp_init(PDBPROCESS, LPCSTR, LPCSTR, LPCSTR, INT); -extern RETCODE SQLAPI bcp_moretext(PDBPROCESS, DBINT, LPCBYTE); -extern RETCODE SQLAPI bcp_readfmt(PDBPROCESS, LPCSTR); -extern RETCODE SQLAPI bcp_sendrow(PDBPROCESS); -extern RETCODE SQLAPI bcp_setl(PLOGINREC, BOOL); -extern RETCODE SQLAPI bcp_writefmt(PDBPROCESS, LPCSTR); + extern RETCODE SQLAPI bcp_colfmt(PDBPROCESS, INT, BYTE, INT, DBINT, LPCBYTE, + INT, INT); + extern RETCODE SQLAPI bcp_collen(PDBPROCESS, DBINT, INT); + extern RETCODE SQLAPI bcp_colptr(PDBPROCESS, LPCBYTE, INT); + extern RETCODE SQLAPI bcp_columns(PDBPROCESS, INT); + extern RETCODE SQLAPI bcp_control(PDBPROCESS, INT, DBINT); + extern DBINT SQLAPI bcp_done(PDBPROCESS); + extern RETCODE SQLAPI bcp_exec(PDBPROCESS, LPDBINT); + extern RETCODE SQLAPI bcp_init(PDBPROCESS, LPCSTR, LPCSTR, LPCSTR, INT); + extern RETCODE SQLAPI bcp_moretext(PDBPROCESS, DBINT, LPCBYTE); + extern RETCODE SQLAPI bcp_readfmt(PDBPROCESS, LPCSTR); + extern RETCODE SQLAPI bcp_sendrow(PDBPROCESS); + extern RETCODE SQLAPI bcp_setl(PLOGINREC, BOOL); + extern RETCODE SQLAPI bcp_writefmt(PDBPROCESS, LPCSTR); -// Standard DB-Library functions -extern LPCBYTE SQLAPI dbadata(PDBPROCESS, INT, INT); -extern DBINT SQLAPI dbadlen(PDBPROCESS, INT, INT); -extern RETCODE SQLAPI dbaltbind(PDBPROCESS, INT, INT, INT, DBINT, LPCBYTE); -extern INT SQLAPI dbaltcolid(PDBPROCESS, INT, INT); -extern DBINT SQLAPI dbaltlen(PDBPROCESS, INT, INT); -extern INT SQLAPI dbaltop(PDBPROCESS, INT, INT); -extern INT SQLAPI dbalttype(PDBPROCESS, INT, INT); -extern DBINT SQLAPI dbaltutype(PDBPROCESS, INT, INT); -extern RETCODE SQLAPI dbanullbind(PDBPROCESS, INT, INT, LPCDBINT); -extern RETCODE SQLAPI dbbind(PDBPROCESS, INT, INT, DBINT, LPBYTE); -extern LPCBYTE SQLAPI dbbylist(PDBPROCESS, INT, LPINT); -extern RETCODE SQLAPI dbcancel(PDBPROCESS); -extern RETCODE SQLAPI dbcanquery(PDBPROCESS); -extern LPCSTR SQLAPI dbchange(PDBPROCESS); -extern RETCODE SQLAPI dbclose(PDBPROCESS); -extern void SQLAPI dbclrbuf(PDBPROCESS, DBINT); -extern RETCODE SQLAPI dbclropt(PDBPROCESS, INT, LPCSTR); -extern RETCODE SQLAPI dbcmd(PDBPROCESS, LPCSTR); -extern RETCODE SQLAPI dbcmdrow(PDBPROCESS); -extern BOOL SQLAPI dbcolbrowse(PDBPROCESS, INT); -extern RETCODE SQLAPI dbcolinfo(PDBHANDLE, INT, INT, INT, LPDBCOL); -extern DBINT SQLAPI dbcollen(PDBPROCESS, INT); -extern LPCSTR SQLAPI dbcolname(PDBPROCESS, INT); -extern LPCSTR SQLAPI dbcolsource(PDBPROCESS, INT); -extern INT SQLAPI dbcoltype(PDBPROCESS, INT); -extern DBINT SQLAPI dbcolutype(PDBPROCESS, INT); -extern INT SQLAPI dbconvert(PDBPROCESS, INT, LPCBYTE, DBINT, INT, LPBYTE, - DBINT); -extern DBINT SQLAPI dbcount(PDBPROCESS); -extern INT SQLAPI dbcurcmd(PDBPROCESS); -extern DBINT SQLAPI dbcurrow(PDBPROCESS); -extern RETCODE SQLAPI dbcursor(PDBCURSOR, INT, INT, LPCSTR, LPCSTR); -extern RETCODE SQLAPI dbcursorbind(PDBCURSOR, INT, INT, DBINT, LPDBINT, LPBYTE); -extern RETCODE SQLAPI dbcursorclose(PDBHANDLE); -extern RETCODE SQLAPI dbcursorcolinfo(PDBCURSOR, INT, LPSTR, LPINT, LPDBINT, - LPINT); -extern RETCODE SQLAPI dbcursorfetch(PDBCURSOR, INT, INT); -extern RETCODE SQLAPI dbcursorfetchex(PDBCURSOR, INT, DBINT, DBINT, DBINT); -extern RETCODE SQLAPI dbcursorinfo(PDBCURSOR, LPINT, LPDBINT); -extern RETCODE SQLAPI dbcursorinfoex(PDBCURSOR, LPDBCURSORINFO); -extern PDBCURSOR SQLAPI dbcursoropen(PDBPROCESS, LPCSTR, INT, INT, UINT, - LPDBINT); -extern LPCBYTE SQLAPI dbdata(PDBPROCESS, INT); -extern BOOL SQLAPI dbdataready(PDBPROCESS); -extern RETCODE SQLAPI dbdatecrack(PDBPROCESS, LPDBDATEREC, LPCDBDATETIME); -extern DBINT SQLAPI dbdatlen(PDBPROCESS, INT); -extern BOOL SQLAPI dbdead(PDBPROCESS); -extern void SQLAPI dbexit(void); -extern RETCODE SQLAPI dbenlisttrans(PDBPROCESS, LPVOID); -extern RETCODE SQLAPI dbenlistxatrans(PDBPROCESS, BOOL); -extern RETCODE SQLAPI dbfcmd(PDBPROCESS, LPCSTR, ...); -extern DBINT SQLAPI dbfirstrow(PDBPROCESS); -extern void SQLAPI dbfreebuf(PDBPROCESS); -extern void SQLAPI dbfreelogin(PLOGINREC); -extern void SQLAPI dbfreequal(LPCSTR); -extern LPSTR SQLAPI dbgetchar(PDBPROCESS, INT); -extern SHORT SQLAPI dbgetmaxprocs(void); -extern INT SQLAPI dbgetoff(PDBPROCESS, DBUSMALLINT, INT); -extern UINT SQLAPI dbgetpacket(PDBPROCESS); -extern STATUS SQLAPI dbgetrow(PDBPROCESS, DBINT); -extern INT SQLAPI dbgettime(void); -extern LPVOID SQLAPI dbgetuserdata(PDBPROCESS); -extern BOOL SQLAPI dbhasretstat(PDBPROCESS); -extern LPCSTR SQLAPI dbinit(void); -extern BOOL SQLAPI dbisavail(PDBPROCESS); -extern BOOL SQLAPI dbiscount(PDBPROCESS); -extern BOOL SQLAPI dbisopt(PDBPROCESS, INT, LPCSTR); -extern DBINT SQLAPI dblastrow(PDBPROCESS); -extern PLOGINREC SQLAPI dblogin(void); -extern RETCODE SQLAPI dbmorecmds(PDBPROCESS); -extern RETCODE SQLAPI dbmoretext(PDBPROCESS, DBINT, LPCBYTE); -extern LPCSTR SQLAPI dbname(PDBPROCESS); -extern STATUS SQLAPI dbnextrow(PDBPROCESS); -extern RETCODE SQLAPI dbnullbind(PDBPROCESS, INT, LPCDBINT); -extern INT SQLAPI dbnumalts(PDBPROCESS, INT); -extern INT SQLAPI dbnumcols(PDBPROCESS); -extern INT SQLAPI dbnumcompute(PDBPROCESS); -extern INT SQLAPI dbnumorders(PDBPROCESS); -extern INT SQLAPI dbnumrets(PDBPROCESS); -extern PDBPROCESS SQLAPI dbopen(PLOGINREC, LPCSTR); -extern INT SQLAPI dbordercol(PDBPROCESS, INT); -extern RETCODE SQLAPI dbprocinfo(PDBPROCESS, LPDBPROCINFO); -extern void SQLAPI dbprhead(PDBPROCESS); -extern RETCODE SQLAPI dbprrow(PDBPROCESS); -extern LPCSTR SQLAPI dbprtype(INT); -extern LPCSTR SQLAPI dbqual(PDBPROCESS, INT, LPCSTR); -extern DBINT SQLAPI dbreadpage(PDBPROCESS, LPCSTR, DBINT, DBINT, LPBYTE); -extern DBINT SQLAPI dbreadtext(PDBPROCESS, LPVOID, DBINT); -extern RETCODE SQLAPI dbresults(PDBPROCESS); -extern LPCBYTE SQLAPI dbretdata(PDBPROCESS, INT); -extern DBINT SQLAPI dbretlen(PDBPROCESS, INT); -extern LPCSTR SQLAPI dbretname(PDBPROCESS, INT); -extern DBINT SQLAPI dbretstatus(PDBPROCESS); -extern INT SQLAPI dbrettype(PDBPROCESS, INT); -extern RETCODE SQLAPI dbrows(PDBPROCESS); -extern STATUS SQLAPI dbrowtype(PDBPROCESS); -extern RETCODE SQLAPI dbrpcinit(PDBPROCESS, LPCSTR, DBSMALLINT); -extern RETCODE SQLAPI dbrpcparam(PDBPROCESS, LPCSTR, BYTE, INT, DBINT, DBINT, - LPCBYTE); -extern RETCODE SQLAPI dbrpcsend(PDBPROCESS); -extern RETCODE SQLAPI dbrpcexec(PDBPROCESS); -extern void SQLAPI dbrpwclr(PLOGINREC); -extern RETCODE SQLAPI dbrpwset(PLOGINREC, LPCSTR, LPCSTR, INT); -extern INT SQLAPI dbserverenum(USHORT, LPSTR, USHORT, LPUSHORT); -extern void SQLAPI dbsetavail(PDBPROCESS); -extern RETCODE SQLAPI dbsetmaxprocs(SHORT); -extern RETCODE SQLAPI dbsetlname(PLOGINREC, LPCSTR, INT); -extern RETCODE SQLAPI dbsetlogintime(INT); -extern RETCODE SQLAPI dbsetlpacket(PLOGINREC, USHORT); -extern RETCODE SQLAPI dbsetnull(PDBPROCESS, INT, INT, LPCBYTE); -extern RETCODE SQLAPI dbsetopt(PDBPROCESS, INT, LPCSTR); -extern RETCODE SQLAPI dbsettime(INT); -extern void SQLAPI dbsetuserdata(PDBPROCESS, LPVOID); -extern RETCODE SQLAPI dbsqlexec(PDBPROCESS); -extern RETCODE SQLAPI dbsqlok(PDBPROCESS); -extern RETCODE SQLAPI dbsqlsend(PDBPROCESS); -extern RETCODE SQLAPI dbstrcpy(PDBPROCESS, INT, INT, LPSTR); -extern INT SQLAPI dbstrlen(PDBPROCESS); -extern BOOL SQLAPI dbtabbrowse(PDBPROCESS, INT); -extern INT SQLAPI dbtabcount(PDBPROCESS); -extern LPCSTR SQLAPI dbtabname(PDBPROCESS, INT); -extern LPCSTR SQLAPI dbtabsource(PDBPROCESS, INT, LPINT); -extern INT SQLAPI dbtsnewlen(PDBPROCESS); -extern LPCDBBINARY SQLAPI dbtsnewval(PDBPROCESS); -extern RETCODE SQLAPI dbtsput(PDBPROCESS, LPCDBBINARY, INT, INT, LPCSTR); -extern LPCDBBINARY SQLAPI dbtxptr(PDBPROCESS, INT); -extern LPCDBBINARY SQLAPI dbtxtimestamp(PDBPROCESS, INT); -extern LPCDBBINARY SQLAPI dbtxtsnewval(PDBPROCESS); -extern RETCODE SQLAPI dbtxtsput(PDBPROCESS, LPCDBBINARY, INT); -extern RETCODE SQLAPI dbuse(PDBPROCESS, LPCSTR); -extern BOOL SQLAPI dbvarylen(PDBPROCESS, INT); -extern BOOL SQLAPI dbwillconvert(INT, INT); -extern RETCODE SQLAPI dbwritepage(PDBPROCESS, LPCSTR, DBINT, DBINT, DBINT, - LPBYTE); -extern RETCODE SQLAPI dbwritetext(PDBPROCESS, LPCSTR, LPCDBBINARY, DBTINYINT, - LPCDBBINARY, BOOL, DBINT, LPCBYTE); -extern RETCODE SQLAPI dbupdatetext(PDBPROCESS, LPCSTR, LPCDBBINARY, LPCDBBINARY, - INT, DBINT, DBINT, LPCSTR, DBINT, - LPCDBBINARY); + // Standard DB-Library functions + extern LPCBYTE SQLAPI dbadata(PDBPROCESS, INT, INT); + extern DBINT SQLAPI dbadlen(PDBPROCESS, INT, INT); + extern RETCODE SQLAPI dbaltbind(PDBPROCESS, INT, INT, INT, DBINT, LPCBYTE); + extern INT SQLAPI dbaltcolid(PDBPROCESS, INT, INT); + extern DBINT SQLAPI dbaltlen(PDBPROCESS, INT, INT); + extern INT SQLAPI dbaltop(PDBPROCESS, INT, INT); + extern INT SQLAPI dbalttype(PDBPROCESS, INT, INT); + extern DBINT SQLAPI dbaltutype(PDBPROCESS, INT, INT); + extern RETCODE SQLAPI dbanullbind(PDBPROCESS, INT, INT, LPCDBINT); + extern RETCODE SQLAPI dbbind(PDBPROCESS, INT, INT, DBINT, LPBYTE); + extern LPCBYTE SQLAPI dbbylist(PDBPROCESS, INT, LPINT); + extern RETCODE SQLAPI dbcancel(PDBPROCESS); + extern RETCODE SQLAPI dbcanquery(PDBPROCESS); + extern LPCSTR SQLAPI dbchange(PDBPROCESS); + extern RETCODE SQLAPI dbclose(PDBPROCESS); + extern void SQLAPI dbclrbuf(PDBPROCESS, DBINT); + extern RETCODE SQLAPI dbclropt(PDBPROCESS, INT, LPCSTR); + extern RETCODE SQLAPI dbcmd(PDBPROCESS, LPCSTR); + extern RETCODE SQLAPI dbcmdrow(PDBPROCESS); + extern BOOL SQLAPI dbcolbrowse(PDBPROCESS, INT); + extern RETCODE SQLAPI dbcolinfo(PDBHANDLE, INT, INT, INT, LPDBCOL); + extern DBINT SQLAPI dbcollen(PDBPROCESS, INT); + extern LPCSTR SQLAPI dbcolname(PDBPROCESS, INT); + extern LPCSTR SQLAPI dbcolsource(PDBPROCESS, INT); + extern INT SQLAPI dbcoltype(PDBPROCESS, INT); + extern DBINT SQLAPI dbcolutype(PDBPROCESS, INT); + extern INT SQLAPI dbconvert(PDBPROCESS, INT, LPCBYTE, DBINT, INT, LPBYTE, + DBINT); + extern DBINT SQLAPI dbcount(PDBPROCESS); + extern INT SQLAPI dbcurcmd(PDBPROCESS); + extern DBINT SQLAPI dbcurrow(PDBPROCESS); + extern RETCODE SQLAPI dbcursor(PDBCURSOR, INT, INT, LPCSTR, LPCSTR); + extern RETCODE SQLAPI dbcursorbind(PDBCURSOR, INT, INT, DBINT, LPDBINT, LPBYTE); + extern RETCODE SQLAPI dbcursorclose(PDBHANDLE); + extern RETCODE SQLAPI dbcursorcolinfo(PDBCURSOR, INT, LPSTR, LPINT, LPDBINT, + LPINT); + extern RETCODE SQLAPI dbcursorfetch(PDBCURSOR, INT, INT); + extern RETCODE SQLAPI dbcursorfetchex(PDBCURSOR, INT, DBINT, DBINT, DBINT); + extern RETCODE SQLAPI dbcursorinfo(PDBCURSOR, LPINT, LPDBINT); + extern RETCODE SQLAPI dbcursorinfoex(PDBCURSOR, LPDBCURSORINFO); + extern PDBCURSOR SQLAPI dbcursoropen(PDBPROCESS, LPCSTR, INT, INT, UINT, + LPDBINT); + extern LPCBYTE SQLAPI dbdata(PDBPROCESS, INT); + extern BOOL SQLAPI dbdataready(PDBPROCESS); + extern RETCODE SQLAPI dbdatecrack(PDBPROCESS, LPDBDATEREC, LPCDBDATETIME); + extern DBINT SQLAPI dbdatlen(PDBPROCESS, INT); + extern BOOL SQLAPI dbdead(PDBPROCESS); + extern void SQLAPI dbexit(void); + extern RETCODE SQLAPI dbenlisttrans(PDBPROCESS, LPVOID); + extern RETCODE SQLAPI dbenlistxatrans(PDBPROCESS, BOOL); + extern RETCODE SQLAPI dbfcmd(PDBPROCESS, LPCSTR, ...); + extern DBINT SQLAPI dbfirstrow(PDBPROCESS); + extern void SQLAPI dbfreebuf(PDBPROCESS); + extern void SQLAPI dbfreelogin(PLOGINREC); + extern void SQLAPI dbfreequal(LPCSTR); + extern LPSTR SQLAPI dbgetchar(PDBPROCESS, INT); + extern SHORT SQLAPI dbgetmaxprocs(void); + extern INT SQLAPI dbgetoff(PDBPROCESS, DBUSMALLINT, INT); + extern UINT SQLAPI dbgetpacket(PDBPROCESS); + extern STATUS SQLAPI dbgetrow(PDBPROCESS, DBINT); + extern INT SQLAPI dbgettime(void); + extern LPVOID SQLAPI dbgetuserdata(PDBPROCESS); + extern BOOL SQLAPI dbhasretstat(PDBPROCESS); + extern LPCSTR SQLAPI dbinit(void); + extern BOOL SQLAPI dbisavail(PDBPROCESS); + extern BOOL SQLAPI dbiscount(PDBPROCESS); + extern BOOL SQLAPI dbisopt(PDBPROCESS, INT, LPCSTR); + extern DBINT SQLAPI dblastrow(PDBPROCESS); + extern PLOGINREC SQLAPI dblogin(void); + extern RETCODE SQLAPI dbmorecmds(PDBPROCESS); + extern RETCODE SQLAPI dbmoretext(PDBPROCESS, DBINT, LPCBYTE); + extern LPCSTR SQLAPI dbname(PDBPROCESS); + extern STATUS SQLAPI dbnextrow(PDBPROCESS); + extern RETCODE SQLAPI dbnullbind(PDBPROCESS, INT, LPCDBINT); + extern INT SQLAPI dbnumalts(PDBPROCESS, INT); + extern INT SQLAPI dbnumcols(PDBPROCESS); + extern INT SQLAPI dbnumcompute(PDBPROCESS); + extern INT SQLAPI dbnumorders(PDBPROCESS); + extern INT SQLAPI dbnumrets(PDBPROCESS); + extern PDBPROCESS SQLAPI dbopen(PLOGINREC, LPCSTR); + extern INT SQLAPI dbordercol(PDBPROCESS, INT); + extern RETCODE SQLAPI dbprocinfo(PDBPROCESS, LPDBPROCINFO); + extern void SQLAPI dbprhead(PDBPROCESS); + extern RETCODE SQLAPI dbprrow(PDBPROCESS); + extern LPCSTR SQLAPI dbprtype(INT); + extern LPCSTR SQLAPI dbqual(PDBPROCESS, INT, LPCSTR); + extern DBINT SQLAPI dbreadpage(PDBPROCESS, LPCSTR, DBINT, DBINT, LPBYTE); + extern DBINT SQLAPI dbreadtext(PDBPROCESS, LPVOID, DBINT); + extern RETCODE SQLAPI dbresults(PDBPROCESS); + extern LPCBYTE SQLAPI dbretdata(PDBPROCESS, INT); + extern DBINT SQLAPI dbretlen(PDBPROCESS, INT); + extern LPCSTR SQLAPI dbretname(PDBPROCESS, INT); + extern DBINT SQLAPI dbretstatus(PDBPROCESS); + extern INT SQLAPI dbrettype(PDBPROCESS, INT); + extern RETCODE SQLAPI dbrows(PDBPROCESS); + extern STATUS SQLAPI dbrowtype(PDBPROCESS); + extern RETCODE SQLAPI dbrpcinit(PDBPROCESS, LPCSTR, DBSMALLINT); + extern RETCODE SQLAPI dbrpcparam(PDBPROCESS, LPCSTR, BYTE, INT, DBINT, DBINT, + LPCBYTE); + extern RETCODE SQLAPI dbrpcsend(PDBPROCESS); + extern RETCODE SQLAPI dbrpcexec(PDBPROCESS); + extern void SQLAPI dbrpwclr(PLOGINREC); + extern RETCODE SQLAPI dbrpwset(PLOGINREC, LPCSTR, LPCSTR, INT); + extern INT SQLAPI dbserverenum(USHORT, LPSTR, USHORT, LPUSHORT); + extern void SQLAPI dbsetavail(PDBPROCESS); + extern RETCODE SQLAPI dbsetmaxprocs(SHORT); + extern RETCODE SQLAPI dbsetlname(PLOGINREC, LPCSTR, INT); + extern RETCODE SQLAPI dbsetlogintime(INT); + extern RETCODE SQLAPI dbsetlpacket(PLOGINREC, USHORT); + extern RETCODE SQLAPI dbsetnull(PDBPROCESS, INT, INT, LPCBYTE); + extern RETCODE SQLAPI dbsetopt(PDBPROCESS, INT, LPCSTR); + extern RETCODE SQLAPI dbsettime(INT); + extern void SQLAPI dbsetuserdata(PDBPROCESS, LPVOID); + extern RETCODE SQLAPI dbsqlexec(PDBPROCESS); + extern RETCODE SQLAPI dbsqlok(PDBPROCESS); + extern RETCODE SQLAPI dbsqlsend(PDBPROCESS); + extern RETCODE SQLAPI dbstrcpy(PDBPROCESS, INT, INT, LPSTR); + extern INT SQLAPI dbstrlen(PDBPROCESS); + extern BOOL SQLAPI dbtabbrowse(PDBPROCESS, INT); + extern INT SQLAPI dbtabcount(PDBPROCESS); + extern LPCSTR SQLAPI dbtabname(PDBPROCESS, INT); + extern LPCSTR SQLAPI dbtabsource(PDBPROCESS, INT, LPINT); + extern INT SQLAPI dbtsnewlen(PDBPROCESS); + extern LPCDBBINARY SQLAPI dbtsnewval(PDBPROCESS); + extern RETCODE SQLAPI dbtsput(PDBPROCESS, LPCDBBINARY, INT, INT, LPCSTR); + extern LPCDBBINARY SQLAPI dbtxptr(PDBPROCESS, INT); + extern LPCDBBINARY SQLAPI dbtxtimestamp(PDBPROCESS, INT); + extern LPCDBBINARY SQLAPI dbtxtsnewval(PDBPROCESS); + extern RETCODE SQLAPI dbtxtsput(PDBPROCESS, LPCDBBINARY, INT); + extern RETCODE SQLAPI dbuse(PDBPROCESS, LPCSTR); + extern BOOL SQLAPI dbvarylen(PDBPROCESS, INT); + extern BOOL SQLAPI dbwillconvert(INT, INT); + extern RETCODE SQLAPI dbwritepage(PDBPROCESS, LPCSTR, DBINT, DBINT, DBINT, + LPBYTE); + extern RETCODE SQLAPI dbwritetext(PDBPROCESS, LPCSTR, LPCDBBINARY, DBTINYINT, + LPCDBBINARY, BOOL, DBINT, LPCBYTE); + extern RETCODE SQLAPI dbupdatetext(PDBPROCESS, LPCSTR, LPCDBBINARY, LPCDBBINARY, + INT, DBINT, DBINT, LPCSTR, DBINT, + LPCDBBINARY); #ifdef __cplusplus } diff --git a/include/sqlfront.h b/include/sqlfront.h index 914638c666..84d2076298 100644 --- a/include/sqlfront.h +++ b/include/sqlfront.h @@ -4,17 +4,18 @@ #define DBNTWIN32 #ifdef DBNTWIN32 #ifndef _WINDOWS_ -#pragma message( \ - __FILE__ \ +#pragma message( \ + __FILE__ \ " : db-library error: windows.h must be included before sqlfront.h.") #endif #endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/***************************************************************************** + /***************************************************************************** * * * SQLFRONT.H - DB-Library header file for the Microsoft SQL Server. * * * @@ -27,11 +28,11 @@ extern "C" { * * *****************************************************************************/ -/***************************************************************************** + /***************************************************************************** * Datatype definitions * *****************************************************************************/ -// Note this has changed because Windows 3.1 defines API as 'pascal far' + // Note this has changed because Windows 3.1 defines API as 'pascal far' #if !defined(M_I86SM) && !defined(DBNTWIN32) #define SQLAPI cdecl far @@ -44,10 +45,10 @@ extern "C" { #endif #ifndef DOUBLE -typedef double DOUBLE; + typedef double DOUBLE; #endif -/***************************************************************************** + /***************************************************************************** * DBPROCESS, LOGINREC and DBCURSOR * *****************************************************************************/ @@ -58,35 +59,35 @@ typedef double DOUBLE; // DOS Specific #ifdef DBMSDOS -typedef DBPROCESS *PDBPROCESS; -typedef LOGINREC *PLOGINREC; -typedef DBCURSOR *PDBCURSOR; -typedef DBHANDLE *PDBHANDLE; + typedef DBPROCESS *PDBPROCESS; + typedef LOGINREC *PLOGINREC; + typedef DBCURSOR *PDBCURSOR; + typedef DBHANDLE *PDBHANDLE; #define PTR * #endif // WIN 3.x Specific. The handle pointers are near for Windows 3.x #ifdef DBMSWIN -typedef DBPROCESS near *PDBPROCESS; -typedef LOGINREC near *PLOGINREC; -typedef DBCURSOR near *PDBCURSOR; -typedef DBHANDLE near *PDBHANDLE; + typedef DBPROCESS near *PDBPROCESS; + typedef LOGINREC near *PLOGINREC; + typedef DBCURSOR near *PDBCURSOR; + typedef DBHANDLE near *PDBHANDLE; #define PTR far * #endif // Windows NT Specific #ifdef DBNTWIN32 -typedef DBPROCESS *PDBPROCESS; -typedef LOGINREC *PLOGINREC; -typedef DBCURSOR *PDBCURSOR; -typedef DBHANDLE *PDBHANDLE; + typedef DBPROCESS *PDBPROCESS; + typedef LOGINREC *PLOGINREC; + typedef DBCURSOR *PDBCURSOR; + typedef DBHANDLE *PDBHANDLE; #define PTR * -typedef int(SQLAPI *SQLFARPROC)(); + typedef int(SQLAPI *SQLFARPROC)(); #else typedef long(far pascal *LGFARPROC)(); // Windows loadable driver fp #endif -/***************************************************************************** + /***************************************************************************** * Win32 compatibility datatype definitions * * Note: The following datatypes are provided for Win32 compatibility. * * Since some of the datatypes are already defined in unrelated include files * @@ -97,45 +98,45 @@ typedef long(far pascal *LGFARPROC)(); // Windows loadable driver fp #ifndef DBNTWIN32 #ifndef SHORT -typedef short SHORT; + typedef short SHORT; #endif #ifndef INT -typedef int INT; + typedef int INT; #endif #ifndef UINT -typedef unsigned int UINT; + typedef unsigned int UINT; #endif #ifndef USHORT -typedef unsigned short USHORT; + typedef unsigned short USHORT; #endif #ifndef ULONG -typedef unsigned long ULONG; + typedef unsigned long ULONG; #endif #ifndef CHAR -typedef char CHAR; + typedef char CHAR; #endif #ifndef LPINT -typedef INT PTR LPINT; + typedef INT PTR LPINT; #endif -typedef unsigned char BYTE; + typedef unsigned char BYTE; -typedef CHAR PTR LPSTR; -typedef BYTE PTR LPBYTE; -typedef void PTR LPVOID; -typedef const CHAR PTR LPCSTR; + typedef CHAR PTR LPSTR; + typedef BYTE PTR LPBYTE; + typedef void PTR LPVOID; + typedef const CHAR PTR LPCSTR; -typedef int BOOL; + typedef int BOOL; #endif -/***************************************************************************** + /***************************************************************************** * DB-Library datatype definitions * *****************************************************************************/ @@ -148,61 +149,67 @@ typedef int BOOL; #define RETCODE INT #define STATUS INT -// DB-Library datatypes -typedef char DBCHAR; -typedef unsigned char DBBINARY; -typedef unsigned char DBTINYINT; -typedef short DBSMALLINT; -typedef unsigned short DBUSMALLINT; -typedef long DBINT; -typedef double DBFLT8; -typedef unsigned char DBBIT; -typedef unsigned char DBBOOL; -typedef float DBFLT4; -typedef long DBMONEY4; - -typedef DBFLT4 DBREAL; -typedef UINT DBUBOOL; - -typedef struct dbdatetime4 { - USHORT numdays; // No of days since Jan-1-1900 - USHORT nummins; // No. of minutes since midnight -} DBDATETIM4; - -typedef struct dbvarychar { - DBSMALLINT len; - DBCHAR str[DBMAXCHAR]; -} DBVARYCHAR; - -typedef struct dbvarybin { - DBSMALLINT len; - BYTE array[DBMAXCHAR]; -} DBVARYBIN; - -typedef struct dbmoney { - DBINT mnyhigh; - ULONG mnylow; -} DBMONEY; - -typedef struct dbdatetime { - DBINT dtdays; - ULONG dttime; -} DBDATETIME; - -// DBDATEREC structure used by dbdatecrack -typedef struct dbdaterec { - INT year; // 1753 - 9999 - INT quarter; // 1 - 4 - INT month; // 1 - 12 - INT dayofyear; // 1 - 366 - INT day; // 1 - 31 - INT week; // 1 - 54 (for leap years) - INT weekday; // 1 - 7 (Mon - Sun) - INT hour; // 0 - 23 - INT minute; // 0 - 59 - INT second; // 0 - 59 - INT millisecond; // 0 - 999 -} DBDATEREC; + // DB-Library datatypes + typedef char DBCHAR; + typedef unsigned char DBBINARY; + typedef unsigned char DBTINYINT; + typedef short DBSMALLINT; + typedef unsigned short DBUSMALLINT; + typedef long DBINT; + typedef double DBFLT8; + typedef unsigned char DBBIT; + typedef unsigned char DBBOOL; + typedef float DBFLT4; + typedef long DBMONEY4; + + typedef DBFLT4 DBREAL; + typedef UINT DBUBOOL; + + typedef struct dbdatetime4 + { + USHORT numdays; // No of days since Jan-1-1900 + USHORT nummins; // No. of minutes since midnight + } DBDATETIM4; + + typedef struct dbvarychar + { + DBSMALLINT len; + DBCHAR str[DBMAXCHAR]; + } DBVARYCHAR; + + typedef struct dbvarybin + { + DBSMALLINT len; + BYTE array[DBMAXCHAR]; + } DBVARYBIN; + + typedef struct dbmoney + { + DBINT mnyhigh; + ULONG mnylow; + } DBMONEY; + + typedef struct dbdatetime + { + DBINT dtdays; + ULONG dttime; + } DBDATETIME; + + // DBDATEREC structure used by dbdatecrack + typedef struct dbdaterec + { + INT year; // 1753 - 9999 + INT quarter; // 1 - 4 + INT month; // 1 - 12 + INT dayofyear; // 1 - 366 + INT day; // 1 - 31 + INT week; // 1 - 54 (for leap years) + INT weekday; // 1 - 7 (Mon - Sun) + INT hour; // 0 - 23 + INT minute; // 0 - 59 + INT second; // 0 - 59 + INT millisecond; // 0 - 999 + } DBDATEREC; #define MAXNUMERICLEN 16 #define MAXNUMERICDIG 38 @@ -210,21 +217,21 @@ typedef struct dbdaterec { #define DEFAULTPRECISION 18 #define DEFAULTSCALE 0 -typedef struct dbnumeric { - BYTE precision; - BYTE scale; - BYTE sign; // 1 = Positive, 0 = Negative - BYTE val[MAXNUMERICLEN]; -} DBNUMERIC; + typedef struct dbnumeric + { + BYTE precision; + BYTE scale; + BYTE sign; // 1 = Positive, 0 = Negative + BYTE val[MAXNUMERICLEN]; + } DBNUMERIC; -typedef DBNUMERIC DBDECIMAL; + typedef DBNUMERIC DBDECIMAL; // Pack the following structures on a word boundary #ifdef __BORLANDC__ #pragma option -a+ #else -#ifndef DBLIB_SKIP_PRAGMA_PACK // Define this if your compiler does not support - // #pragma pack() +#ifndef DBLIB_SKIP_PRAGMA_PACK // Define this if your compiler does not support #pragma pack() #pragma pack(2) #endif #endif @@ -232,47 +239,50 @@ typedef DBNUMERIC DBDECIMAL; #define MAXCOLNAMELEN 30 #define MAXTABLENAME 30 -typedef struct { - DBINT SizeOfStruct; - CHAR Name[MAXCOLNAMELEN + 1]; - CHAR ActualName[MAXCOLNAMELEN + 1]; - CHAR TableName[MAXTABLENAME + 1]; - SHORT Type; - DBINT UserType; - DBINT MaxLength; - BYTE Precision; - BYTE Scale; - BOOL VarLength; // TRUE, FALSE - BYTE Null; // TRUE, FALSE or DBUNKNOWN - BYTE CaseSensitive; // TRUE, FALSE or DBUNKNOWN - BYTE Updatable; // TRUE, FALSE or DBUNKNOWN - BOOL Identity; // TRUE, FALSE -} DBCOL, PTR LPDBCOL; + typedef struct + { + DBINT SizeOfStruct; + CHAR Name[MAXCOLNAMELEN + 1]; + CHAR ActualName[MAXCOLNAMELEN + 1]; + CHAR TableName[MAXTABLENAME + 1]; + SHORT Type; + DBINT UserType; + DBINT MaxLength; + BYTE Precision; + BYTE Scale; + BOOL VarLength; // TRUE, FALSE + BYTE Null; // TRUE, FALSE or DBUNKNOWN + BYTE CaseSensitive; // TRUE, FALSE or DBUNKNOWN + BYTE Updatable; // TRUE, FALSE or DBUNKNOWN + BOOL Identity; // TRUE, FALSE + } DBCOL, PTR LPDBCOL; #define MAXSERVERNAME 30 #define MAXNETLIBNAME 255 #define MAXNETLIBCONNSTR 255 -typedef struct { - DBINT SizeOfStruct; - BYTE ServerType; - USHORT ServerMajor; - USHORT ServerMinor; - USHORT ServerRevision; - CHAR ServerName[MAXSERVERNAME + 1]; - CHAR NetLibName[MAXNETLIBNAME + 1]; - CHAR NetLibConnStr[MAXNETLIBCONNSTR + 1]; -} DBPROCINFO, PTR LPDBPROCINFO; - -typedef struct { - DBINT SizeOfStruct; // Use sizeof(DBCURSORINFO) - ULONG TotCols; // Total Columns in cursor - ULONG TotRows; // Total Rows in cursor - ULONG CurRow; // Current actual row in server - ULONG TotRowsFetched; // Total rows actually fetched - ULONG Type; // See CU_... - ULONG Status; // See CU_... -} DBCURSORINFO, PTR LPDBCURSORINFO; + typedef struct + { + DBINT SizeOfStruct; + BYTE ServerType; + USHORT ServerMajor; + USHORT ServerMinor; + USHORT ServerRevision; + CHAR ServerName[MAXSERVERNAME + 1]; + CHAR NetLibName[MAXNETLIBNAME + 1]; + CHAR NetLibConnStr[MAXNETLIBCONNSTR + 1]; + } DBPROCINFO, PTR LPDBPROCINFO; + + typedef struct + { + DBINT SizeOfStruct; // Use sizeof(DBCURSORINFO) + ULONG TotCols; // Total Columns in cursor + ULONG TotRows; // Total Rows in cursor + ULONG CurRow; // Current actual row in server + ULONG TotRowsFetched; // Total rows actually fetched + ULONG Type; // See CU_... + ULONG Status; // See CU_... + } DBCURSORINFO, PTR LPDBCURSORINFO; #define INVALID_UROWNUM ((ULONG)(-1)) @@ -280,32 +290,31 @@ typedef struct { #ifdef __BORLANDC__ #pragma option -a- #else -#ifndef DBLIB_SKIP_PRAGMA_PACK // Define this if your compiler does not support - // #pragma pack() +#ifndef DBLIB_SKIP_PRAGMA_PACK // Define this if your compiler does not support #pragma pack() #pragma pack() #endif #endif #endif // End DBTYPEDEFS -/***************************************************************************** + /***************************************************************************** * Pointer Datatypes * *****************************************************************************/ -typedef const LPINT LPCINT; -typedef const LPBYTE LPCBYTE; -typedef USHORT PTR LPUSHORT; -typedef const LPUSHORT LPCUSHORT; -typedef DBINT PTR LPDBINT; -typedef const LPDBINT LPCDBINT; -typedef DBBINARY PTR LPDBBINARY; -typedef const LPDBBINARY LPCDBBINARY; -typedef DBDATEREC PTR LPDBDATEREC; -typedef const LPDBDATEREC LPCDBDATEREC; -typedef DBDATETIME PTR LPDBDATETIME; -typedef const LPDBDATETIME LPCDBDATETIME; - -/***************************************************************************** + typedef const LPINT LPCINT; + typedef const LPBYTE LPCBYTE; + typedef USHORT PTR LPUSHORT; + typedef const LPUSHORT LPCUSHORT; + typedef DBINT PTR LPDBINT; + typedef const LPDBINT LPCDBINT; + typedef DBBINARY PTR LPDBBINARY; + typedef const LPDBBINARY LPCDBBINARY; + typedef DBDATEREC PTR LPDBDATEREC; + typedef const LPDBDATEREC LPCDBDATEREC; + typedef DBDATETIME PTR LPDBDATETIME; + typedef const LPDBDATETIME LPCDBDATETIME; + + /***************************************************************************** * General #defines * *****************************************************************************/ @@ -317,8 +326,13 @@ typedef const LPDBDATETIME LPCDBDATETIME; #define SERVTYPE_UNKNOWN 0 #define SERVTYPE_MICROSOFT 1 -// Used by dbcolinfo -enum CI_TYPES { CI_REGULAR = 1, CI_ALTERNATE = 2, CI_CURSOR = 3 }; + // Used by dbcolinfo + enum CI_TYPES + { + CI_REGULAR = 1, + CI_ALTERNATE = 2, + CI_CURSOR = 3 + }; // Bulk Copy Definitions (bcp) #define DB_IN 1 // Transfer from client to server @@ -591,9 +605,9 @@ enum CI_TYPES { CI_REGULAR = 1, CI_ALTERNATE = 2, CI_CURSOR = 3 }; // DBPROCESS is still alive #define EXPROGRAM 7 // Coding error in user program #define EXRESOURCE 8 // Running out of resources - the DBPROCESS may be dead -#define EXCOMM 9 // Failure in communication with Server - the DBPROCESS is dead -#define EXFATAL 10 // Fatal error - the DBPROCESS is dead -#define EXCONSISTENCY \ +#define EXCOMM 9 // Failure in communication with Server - the DBPROCESS is dead +#define EXFATAL 10 // Fatal error - the DBPROCESS is dead +#define EXCONSISTENCY \ 11 // Internal software error - notify MS Technical Supprt // Offset identifiers @@ -670,7 +684,7 @@ enum CI_TYPES { CI_REGULAR = 1, CI_ALTERNATE = 2, CI_CURSOR = 3 }; #define CUR_OPTCC 3 // Optimistic concurrency control, data modifications // succeed only if the row hasn't been updated since // the last fetch. -#define CUR_OPTCCVAL \ +#define CUR_OPTCCVAL \ 4 // Optimistic concurrency control based on selected column values // Following flags are used in the scrollopt parameter in dbcursoropen @@ -741,10 +755,10 @@ enum CI_TYPES { CI_REGULAR = 1, CI_ALTERNATE = 2, CI_CURSOR = 3 }; #define NOT_SUPPORTED 0x0008 #define ENUM_INVALID_PARAM 0x0010 -// Netlib Error problem codes. ConnectionError() should return one of -// these as the dblib-mapped problem code, so the corresponding string -// is sent to the dblib app's error handler as dberrstr. Return NE_E_NOMAP -// for a generic DB-Library error string (as in prior versions of dblib). + // Netlib Error problem codes. ConnectionError() should return one of + // these as the dblib-mapped problem code, so the corresponding string + // is sent to the dblib app's error handler as dberrstr. Return NE_E_NOMAP + // for a generic DB-Library error string (as in prior versions of dblib). #define NE_E_NOMAP 0 // No string; uses dblib default. #define NE_E_NOMEMORY 1 // Insufficient memory. @@ -757,16 +771,16 @@ enum CI_TYPES { CI_REGULAR = 1, CI_ALTERNATE = 2, CI_CURSOR = 3 }; #define NE_E_NORESOURCE 8 // Insufficient network resources. #define NE_E_NETBUSY 9 // Network is busy. #define NE_E_NONETACCESS 10 // Network access denied. -#define NE_E_GENERAL 11 // General network error. Check your documentation. -#define NE_E_CONNMODE 12 // Incorrect connection mode. -#define NE_E_NAMENOTFOUND 13 // Name not found in directory service. -#define NE_E_INVALIDCONN 14 // Invalid connection. -#define NE_E_NETDATAERR 15 // Error reading or writing network data. -#define NE_E_TOOMANYFILES 16 // Too many open file handles. -#define NE_E_CANTCONNECT 17 // SQL Server does not exist or access denied. -#define NE_E_SSLSEC 18 // SSL Security error -#define NE_E_ENCRYPT_REQ 19 // Server requires encryption -#define NE_ENCRPYT_NOTSUP 20 // Encryption not supported on SQL Server +#define NE_E_GENERAL 11 // General network error. Check your documentation. +#define NE_E_CONNMODE 12 // Incorrect connection mode. +#define NE_E_NAMENOTFOUND 13 // Name not found in directory service. +#define NE_E_INVALIDCONN 14 // Invalid connection. +#define NE_E_NETDATAERR 15 // Error reading or writing network data. +#define NE_E_TOOMANYFILES 16 // Too many open file handles. +#define NE_E_CANTCONNECT 17 // SQL Server does not exist or access denied. +#define NE_E_SSLSEC 18 // SSL Security error +#define NE_E_ENCRYPT_REQ 19 // Server requires encryption +#define NE_ENCRPYT_NOTSUP 20 // Encryption not supported on SQL Server #define NE_MAX_NETERROR 20 diff --git a/include/status.h b/include/status.h index cb47af718c..f20435a561 100644 --- a/include/status.h +++ b/include/status.h @@ -1,35 +1,34 @@ #pragma once #include +#define STATUS_H(x) x #define FALSE 0 #define TRUE 1 #define B_TRUE TRUE #define B_FALSE FALSE #define C_OK 0 #define C_ERROR -1 -#define IS_OK(status) ((status)&1) -#define STATUS_OK IS_OK(status) -#define IS_NOT_OK(status) (!IS_OK(status)) -#define STATUS_NOT_OK (!STATUS_OK) +#define IS_OK(status) !!((status)&1) +#define STATUS_OK !!IS_OK(status) +#define IS_NOT_OK(status) !IS_OK(status) +#define STATUS_NOT_OK !STATUS_OK #define INIT_STATUS_AS int status = #define INIT_STATUS INIT_STATUS_AS MDSplusSUCCESS #define INIT_STATUS_ERROR INIT_STATUS_AS MDSplusERROR -#define TO_CODE(status) (status & (-8)) +#define TO_CODE(status) !!(status & (-8)) #define STATUS_TO_CODE TO_CODE(status) -#define RETURN_IF_STATUS_NOT_OK \ - if \ - STATUS_NOT_OK return status; -#define BREAK_IF_STATUS_NOT_OK \ - if \ - STATUS_NOT_OK break; -#define GOTO_IF_STATUS_NOT_OK(MARK) \ - if \ - STATUS_NOT_OK goto MARK; -#define RETURN_IF_NOT_OK(CHECK) \ - if \ - IS_NOT_OK((status = (CHECK))) return status; -#define BREAK_IF_NOT_OK(CHECK) \ - if \ - IS_NOT_OK((status = (CHECK))) break; -#define GOTO_IF_NOT_OK(MARK, CHECK) \ - if \ - IS_NOT_OK((status = (CHECK))) goto MARK; +#define RETURN_IF_STATUS_NOT_OK \ + if (STATUS_NOT_OK) \ + return status; \ +#define BREAK_IF_STATUS_NOT_OK if (STATUS_NOT_OK) break; +#define GOTO_IF_STATUS_NOT_OK(MARK) \ + if (STATUS_NOT_OK) \ + goto MARK; +#define RETURN_IF_NOT_OK(CHECK) \ + if (IS_NOT_OK((status = (CHECK)))) \ + return status; +#define BREAK_IF_NOT_OK(CHECK) \ + if (IS_NOT_OK((status = (CHECK)))) \ + break; +#define GOTO_IF_NOT_OK(MARK, CHECK) \ + if (IS_NOT_OK((status = (CHECK)))) \ + goto MARK; diff --git a/include/strroutines.h b/include/strroutines.h index e48163b4cf..514bb26d1b 100644 --- a/include/strroutines.h +++ b/include/strroutines.h @@ -37,16 +37,17 @@ extern int StrPosition(const mdsdsc_t *const source, #ifdef HAVE_PTHREAD_H #include -static void __attribute__((unused)) free_d(void *ptr) { +static void __attribute__((unused)) free_d(void *ptr) +{ StrFree1Dx((mdsdsc_d_t *)ptr); } #define FREED_ON_EXIT(ptr) pthread_cleanup_push(free_d, ptr) #define FREED_IF(ptr, c) pthread_cleanup_pop(c) #define FREED_NOW(ptr) FREED_IF(ptr, 1) #define FREED_CANCEL(ptr) FREED_IF(ptr, 0) -#define INIT_AS_AND_FREED_ON_EXIT(var, value) \ - mdsdsc_d_t var = value; \ +#define INIT_AS_AND_FREED_ON_EXIT(var, value) \ + mdsdsc_d_t var = value; \ FREED_ON_EXIT(&var) -#define INIT_AND_FREED_ON_EXIT(var, dtype) \ +#define INIT_AND_FREED_ON_EXIT(var, dtype) \ INIT_AS_AND_FREED_ON_EXIT(var, ((mdsdsc_d_t){0, dtype, CLASS_D, NULL})) #endif diff --git a/include/tdishr.h b/include/tdishr.h index 5cd33a6135..004f16dc3e 100644 --- a/include/tdishr.h +++ b/include/tdishr.h @@ -14,7 +14,7 @@ #include #undef OPC -#define OPC(name, ...) \ +#define OPC(name, ...) \ extern int _Tdi##name(void **ctx, struct descriptor *first, ...); #include #undef OPC diff --git a/include/treeioperf.h b/include/treeioperf.h index fb8a285869..3d8300baf3 100644 --- a/include/treeioperf.h +++ b/include/treeioperf.h @@ -4,7 +4,8 @@ #include -typedef struct _TREE_IO_PERF { +typedef struct _TREE_IO_PERF +{ int num_writes_10_0_to_10_1; int num_writes_10_1_to_10_2; diff --git a/include/treeshr.h b/include/treeshr.h index 0a33799d30..a908fb9bfa 100644 --- a/include/treeshr.h +++ b/include/treeshr.h @@ -5,372 +5,373 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include #include #define TreeBLOCKID 0x3ade68b1 -extern int treeshr_errno; -extern int TREE_BLOCKID; + extern int treeshr_errno; + extern int TREE_BLOCKID; #include #ifndef DBIDEF_H -struct dbi_itm; + struct dbi_itm; #endif #ifndef NCIDEF_H -struct nci_itm; + struct nci_itm; #endif -extern EXPORT void *TreeSavePrivateCtx(void *dbid); -extern EXPORT void *TreeRestorePrivateCtx(void *pctx); -extern EXPORT char * -TreeAbsPath(char const *in); /********** Use TreeFree(result) *****/ -extern EXPORT char * -_TreeAbsPath(void *dbid, - char const *in); /********** Use TreeFree(result) *****/ -extern EXPORT int TreeAbsPathDsc(char const *in, mdsdsc_t *out_ptr); -extern EXPORT int _TreeAbsPathDsc(void *dbid, char const *in, - mdsdsc_t *out_ptr); -extern EXPORT int TreeAddConglom(char const *path, char const *congtype, - int *nid); -extern EXPORT int _TreeAddConglom(void *dbid, char const *path, - char const *congtype, int *nid); -extern EXPORT int TreeAddNode(char const *name, int *nid_ret, char usage); -extern EXPORT int _TreeAddNode(void *dbid, char const *name, int *nid_ret, - char usage); -extern EXPORT int TreeAddTag(int nid, char const *tagnam); -extern EXPORT int _TreeAddTag(void *dbid, int nid, char const *tagnam); -extern EXPORT int TreeCleanDatafile(char const *tree, int shot); -extern EXPORT int _TreeCleanDatafile(void **dbid, char const *tree, int shot); -extern EXPORT int TreeClose(char const *tree, int shot); -extern EXPORT int _TreeClose(void **dbid, char const *tree, int shot); -extern EXPORT int TreeCompressDatafile(char const *tree, int shot); -extern EXPORT int _TreeCompressDatafile(void **dbid, char const *tree, - int shot); -extern EXPORT int TreeCreatePulseFile(int shot, int numnids, int *nids); -extern EXPORT int _TreeCreatePulseFile(void *dbid, int shot, int numnids, - int *nids); -extern EXPORT int TreeCreateTreeFiles(char const *tree, int shot, - int source_shot); -extern EXPORT void **TreeCtx(); -extern EXPORT void *TreeDbid(); -extern EXPORT void *_TreeDbid(void **dbid); -extern EXPORT void TreeDeleteNodeExecute(void); -extern EXPORT void _TreeDeleteNodeExecute(void *dbid); -extern EXPORT int TreeDeleteNodeGetNid(int *nid); -extern EXPORT int _TreeDeleteNodeGetNid(void *dbid, int *nid); -extern EXPORT int TreeDeleteNodeInitialize(int nid, int *count, int reset); -extern EXPORT int _TreeDeleteNodeInitialize(void *dbid, int nid, int *count, - int reset); -extern EXPORT int TreeDeletePulseFile(int shotid, int all_versions); -extern EXPORT int _TreeDeletePulseFile(void *dbid, int shotid, - int all_versions); -extern EXPORT int TreeDoMethod(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...); -extern EXPORT int _TreeDoMethod(void *dbid, mdsdsc_t *nid_dsc, - mdsdsc_t *method_ptr, ...); -extern EXPORT int TreeDoMethodA(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, - int nargs_in, mdsdsc_t **arglist_in, - mdsdsc_xd_t *out_ptr); -extern EXPORT int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, - mdsdsc_t *method_ptr, int nargs_in, - mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr); -extern EXPORT int TreeDoMethod_HANDLER(int *sig_args, int *mech_args); -extern EXPORT int TreeEditing(); -extern EXPORT int _TreeEditing(void *dbid); -extern EXPORT int TreeEndConglomerate(); -extern EXPORT int _TreeEndConglomerate(void *dbid); + extern EXPORT void *TreeSavePrivateCtx(void *dbid); + extern EXPORT void *TreeRestorePrivateCtx(void *pctx); + extern EXPORT char * + TreeAbsPath(char const *in); /********** Use TreeFree(result) *****/ + extern EXPORT char * + _TreeAbsPath(void *dbid, + char const *in); /********** Use TreeFree(result) *****/ + extern EXPORT int TreeAbsPathDsc(char const *in, mdsdsc_t *out_ptr); + extern EXPORT int _TreeAbsPathDsc(void *dbid, char const *in, + mdsdsc_t *out_ptr); + extern EXPORT int TreeAddConglom(char const *path, char const *congtype, + int *nid); + extern EXPORT int _TreeAddConglom(void *dbid, char const *path, + char const *congtype, int *nid); + extern EXPORT int TreeAddNode(char const *name, int *nid_ret, char usage); + extern EXPORT int _TreeAddNode(void *dbid, char const *name, int *nid_ret, + char usage); + extern EXPORT int TreeAddTag(int nid, char const *tagnam); + extern EXPORT int _TreeAddTag(void *dbid, int nid, char const *tagnam); + extern EXPORT int TreeCleanDatafile(char const *tree, int shot); + extern EXPORT int _TreeCleanDatafile(void **dbid, char const *tree, int shot); + extern EXPORT int TreeClose(char const *tree, int shot); + extern EXPORT int _TreeClose(void **dbid, char const *tree, int shot); + extern EXPORT int TreeCompressDatafile(char const *tree, int shot); + extern EXPORT int _TreeCompressDatafile(void **dbid, char const *tree, + int shot); + extern EXPORT int TreeCreatePulseFile(int shot, int numnids, int *nids); + extern EXPORT int _TreeCreatePulseFile(void *dbid, int shot, int numnids, + int *nids); + extern EXPORT int TreeCreateTreeFiles(char const *tree, int shot, + int source_shot); + extern EXPORT void **TreeCtx(); + extern EXPORT void *TreeDbid(); + extern EXPORT void *_TreeDbid(void **dbid); + extern EXPORT void TreeDeleteNodeExecute(void); + extern EXPORT void _TreeDeleteNodeExecute(void *dbid); + extern EXPORT int TreeDeleteNodeGetNid(int *nid); + extern EXPORT int _TreeDeleteNodeGetNid(void *dbid, int *nid); + extern EXPORT int TreeDeleteNodeInitialize(int nid, int *count, int reset); + extern EXPORT int _TreeDeleteNodeInitialize(void *dbid, int nid, int *count, + int reset); + extern EXPORT int TreeDeletePulseFile(int shotid, int all_versions); + extern EXPORT int _TreeDeletePulseFile(void *dbid, int shotid, + int all_versions); + extern EXPORT int TreeDoMethod(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...); + extern EXPORT int _TreeDoMethod(void *dbid, mdsdsc_t *nid_dsc, + mdsdsc_t *method_ptr, ...); + extern EXPORT int TreeDoMethodA(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, + int nargs_in, mdsdsc_t **arglist_in, + mdsdsc_xd_t *out_ptr); + extern EXPORT int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, + mdsdsc_t *method_ptr, int nargs_in, + mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr); + extern EXPORT int TreeDoMethod_HANDLER(int *sig_args, int *mech_args); + extern EXPORT int TreeEditing(); + extern EXPORT int _TreeEditing(void *dbid); + extern EXPORT int TreeEndConglomerate(); + extern EXPORT int _TreeEndConglomerate(void *dbid); -extern EXPORT int TreeFindNode(char const *path, int *nid); -extern EXPORT int _TreeFindNode(void *dbid, char const *path, int *nid); -extern EXPORT int TreeFindNodeRelative(char const *path, int startnid, - int *nid); -extern EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, - int startnid, int *nid); + extern EXPORT int TreeFindNode(char const *path, int *nid); + extern EXPORT int _TreeFindNode(void *dbid, char const *path, int *nid); + extern EXPORT int TreeFindNodeRelative(char const *path, int startnid, + int *nid); + extern EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, + int startnid, int *nid); -extern EXPORT int TreeFindNodeEnd(void **ctx); -extern EXPORT int _TreeFindNodeEnd(void *dbid, void **ctx); -extern EXPORT char * -TreeFindNodeTags(int nid, void **ctx); /********** Use TreeFree(result) *****/ -extern EXPORT char * -_TreeFindNodeTags(void *dbid, int nid, - void **ctx); /********** Use TreeFree(result) *****/ + extern EXPORT int TreeFindNodeEnd(void **ctx); + extern EXPORT int _TreeFindNodeEnd(void *dbid, void **ctx); + extern EXPORT char * + TreeFindNodeTags(int nid, void **ctx); /********** Use TreeFree(result) *****/ + extern EXPORT char * + _TreeFindNodeTags(void *dbid, int nid, + void **ctx); /********** Use TreeFree(result) *****/ -extern EXPORT int TreeFindNodeWild(char const *path, int *nid, void **ctx, - int usage_mask); -extern EXPORT int _TreeFindNodeWild(void *dbid, char const *path, int *nid, - void **ctx, int usage_mask); -extern EXPORT int TreeFindNodeWildRelative(char const *path, int startnid, - int *nid, void **ctx, - int usage_mask); -extern EXPORT int _TreeFindNodeWildRelative(void *dbid, char const *path, - int startnid, int *nid, void **ctx, - int usage_mask); + extern EXPORT int TreeFindNodeWild(char const *path, int *nid, void **ctx, + int usage_mask); + extern EXPORT int _TreeFindNodeWild(void *dbid, char const *path, int *nid, + void **ctx, int usage_mask); + extern EXPORT int TreeFindNodeWildRelative(char const *path, int startnid, + int *nid, void **ctx, + int usage_mask); + extern EXPORT int _TreeFindNodeWildRelative(void *dbid, char const *path, + int startnid, int *nid, void **ctx, + int usage_mask); -extern EXPORT void TreeFindTagEnd(void **ctx); -extern EXPORT char *TreeFindTagWild(char *wild, int *nidout, void **search_ctx); -extern EXPORT char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, - void **ctx); -extern EXPORT int TreeFlushOff(int nid); -extern EXPORT int _TreeFlushOff(void *dbid, int nid); -extern EXPORT int TreeFlushReset(int nid); -extern EXPORT int _TreeFlushReset(void *dbid, int nid); -extern EXPORT void TreeFree(void *); -extern EXPORT void TreeFreeDbid(void *); -extern EXPORT int _TreeNewDbid(void **dbid); -extern EXPORT int TreeGetDbi(struct dbi_itm *itmlst); -extern EXPORT int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst); -extern EXPORT int TreeGetNci(int nid, struct nci_itm *itmlst); -extern EXPORT int _TreeGetNci(void *dbid, int nid, struct nci_itm *itmlst); -extern EXPORT int TreeGetDefaultNid(int *nid); -extern EXPORT int _TreeGetDefaultNid(void *dbid, int *nid); -extern EXPORT char *TreeGetMinimumPath(int *def_nid, int nid); -/********** Use TreeFree(result) *****/ -extern EXPORT char *_TreeGetMinimumPath(void *dbid, int *def_nid, int nid); -/********** Use TreeFree(result) *****/ -extern EXPORT char *TreeGetPath(int nid); -/********** Use TreeFree(result) *****/ -extern EXPORT char *_TreeGetPath(void *dbid, int nid); -/********** Use TreeFree(result) *****/ -extern EXPORT int TreeGetMinimumPathDsc(int *def_nid, int nid, - mdsdsc_xd_t *out_ptr); -extern EXPORT int _TreeGetMinimumPathDsc(void *dbid, int *def_nid, int nid, - mdsdsc_xd_t *out_ptr); -extern EXPORT int TreeGetPathDsc(int nid, mdsdsc_xd_t *out_ptr); -extern EXPORT int _TreeGetPathDsc(void *dbid, int nid, mdsdsc_xd_t *out_ptr); -extern EXPORT int TreeGetRecord(int nid, mdsdsc_xd_t *dsc_ptr); -extern EXPORT int _TreeGetRecord(void *dbid, int nid, mdsdsc_xd_t *dsc_ptr); -extern EXPORT int TreeGetStackSize(); -extern EXPORT int _TreeGetStackSize(void *dbid); -extern EXPORT int TreeGetViewDate(int64_t *date); -extern EXPORT int TreeIsOn(int nid); -extern EXPORT int _TreeIsOn(void *dbid, int nid); -extern EXPORT int TreeIsOpen(); -extern EXPORT int _TreeIsOpen(void *dbid); -extern EXPORT int TreeLink(mdsdsc_t *intree, mdsdsc_t *outtree); -extern EXPORT int TreeMarkIncludes(); -extern EXPORT int TreeNodePresent(int *nid); -extern EXPORT int TreeOpen(char const *tree, int shot, int flags); -extern EXPORT int _TreeOpen(void **dbid, char const *tree, int shot, int flags); -extern EXPORT int TreeOpenEdit(char const *tree, int shot); -extern EXPORT int _TreeOpenEdit(void **dbid, char const *tree, int shot); -extern EXPORT int TreeOpenNew(char const *tree, int shot); -extern EXPORT int _TreeOpenNew(void **dbid, char const *tree, int shot); -extern EXPORT int TreePutRecord(int nid, mdsdsc_t *descriptor_ptr, - int utility_update); -extern EXPORT int _TreePutRecord(void *dbid, int nid, mdsdsc_t *descriptor, - int utility_update); -extern EXPORT int TreeQuitTree(char const *tree, int shot); -extern EXPORT int _TreeQuitTree(void **dbid, char const *tree, int shot); -extern EXPORT int TreeRemoveNodesTags(int nid); -extern EXPORT int _TreeRemoveNodesTags(void *dbid, int nid); -extern EXPORT int TreeRemoveTag(char const *tagname); -extern EXPORT int _TreeRemoveTag(void *dbid, char const *tagname); -extern EXPORT int TreeRenameNode(int nid, char const *newname); -extern EXPORT int _TreeRenameNode(void *dbid, int nid, char const *newname); -extern EXPORT void TreeRestoreContext(void *ctx); -extern EXPORT void _TreeRestoreContext(void **dbid, void *ctx); -extern EXPORT int TreeRundownTree(mdsdsc_t *treenam, int *shotid, - int single_tree, int force_exit); -extern EXPORT void *TreeSaveContext(); -extern EXPORT void *_TreeSaveContext(void *dbid); -extern EXPORT int TreeSetDbi(struct dbi_itm *itmlst); -extern EXPORT int _TreeSetDbi(void *dbid, struct dbi_itm *itmlst); -extern EXPORT int TreeSetNci(int nid, struct nci_itm *itmlst); -extern EXPORT int _TreeSetNci(void *dbid, int nid, struct nci_itm *itmlst); -extern EXPORT int TreeSetDefault(char *path, int *nid); -extern EXPORT int _TreeSetDefault(void *dbid, char *path, int *nid); -extern EXPORT int TreeSetDefaultNid(int nid); -extern EXPORT int _TreeSetDefaultNid(void *dbid, int nid); -extern EXPORT int TreeSetNoSubtree(int nid); -extern EXPORT int _TreeSetNoSubtree(void *dbid, int nid); -extern EXPORT int TreeSetStackSize(int new_size); -extern EXPORT int _TreeSetStackSize(void **dbid, int new_size); -extern EXPORT int TreeSetSubtree(int nid); -extern EXPORT int _TreeSetSubtree(void *dbid, int nid); -extern EXPORT int TreeSetUsage(int nid, unsigned char usage); -extern EXPORT int _TreeSetUsage(void *dbid, int nid, unsigned char usage); -extern EXPORT int TreeStartConglomerate(int numnodes); -extern EXPORT int _TreeStartConglomerate(void *dbid, int numnodes); -extern EXPORT void *TreeSwitchDbid(void *dbid); -extern EXPORT int TreeTurnOff(int nid); -extern EXPORT int _TreeTurnOff(void *dbid, int nid); -extern EXPORT int TreeTurnOn(int nid); -extern EXPORT int _TreeTurnOn(void *dbid, int nid); -extern EXPORT int TreeUsePrivateCtx(int onoff); -extern EXPORT int TreeUsingPrivateCtx(); -extern EXPORT int TreeVerify(); -extern EXPORT int _TreeVerify(void *dbid); -extern EXPORT int TreeWait(); -extern EXPORT int TreeWriteTree(char const *tree, int shot); -extern EXPORT int _TreeWriteTree(void **dbid, char const *tree, int shot); + extern EXPORT void TreeFindTagEnd(void **ctx); + extern EXPORT char *TreeFindTagWild(char *wild, int *nidout, void **search_ctx); + extern EXPORT char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, + void **ctx); + extern EXPORT int TreeFlushOff(int nid); + extern EXPORT int _TreeFlushOff(void *dbid, int nid); + extern EXPORT int TreeFlushReset(int nid); + extern EXPORT int _TreeFlushReset(void *dbid, int nid); + extern EXPORT void TreeFree(void *); + extern EXPORT void TreeFreeDbid(void *); + extern EXPORT int _TreeNewDbid(void **dbid); + extern EXPORT int TreeGetDbi(struct dbi_itm *itmlst); + extern EXPORT int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst); + extern EXPORT int TreeGetNci(int nid, struct nci_itm *itmlst); + extern EXPORT int _TreeGetNci(void *dbid, int nid, struct nci_itm *itmlst); + extern EXPORT int TreeGetDefaultNid(int *nid); + extern EXPORT int _TreeGetDefaultNid(void *dbid, int *nid); + extern EXPORT char *TreeGetMinimumPath(int *def_nid, int nid); + /********** Use TreeFree(result) *****/ + extern EXPORT char *_TreeGetMinimumPath(void *dbid, int *def_nid, int nid); + /********** Use TreeFree(result) *****/ + extern EXPORT char *TreeGetPath(int nid); + /********** Use TreeFree(result) *****/ + extern EXPORT char *_TreeGetPath(void *dbid, int nid); + /********** Use TreeFree(result) *****/ + extern EXPORT int TreeGetMinimumPathDsc(int *def_nid, int nid, + mdsdsc_xd_t *out_ptr); + extern EXPORT int _TreeGetMinimumPathDsc(void *dbid, int *def_nid, int nid, + mdsdsc_xd_t *out_ptr); + extern EXPORT int TreeGetPathDsc(int nid, mdsdsc_xd_t *out_ptr); + extern EXPORT int _TreeGetPathDsc(void *dbid, int nid, mdsdsc_xd_t *out_ptr); + extern EXPORT int TreeGetRecord(int nid, mdsdsc_xd_t *dsc_ptr); + extern EXPORT int _TreeGetRecord(void *dbid, int nid, mdsdsc_xd_t *dsc_ptr); + extern EXPORT int TreeGetStackSize(); + extern EXPORT int _TreeGetStackSize(void *dbid); + extern EXPORT int TreeGetViewDate(int64_t *date); + extern EXPORT int TreeIsOn(int nid); + extern EXPORT int _TreeIsOn(void *dbid, int nid); + extern EXPORT int TreeIsOpen(); + extern EXPORT int _TreeIsOpen(void *dbid); + extern EXPORT int TreeLink(mdsdsc_t *intree, mdsdsc_t *outtree); + extern EXPORT int TreeMarkIncludes(); + extern EXPORT int TreeNodePresent(int *nid); + extern EXPORT int TreeOpen(char const *tree, int shot, int flags); + extern EXPORT int _TreeOpen(void **dbid, char const *tree, int shot, int flags); + extern EXPORT int TreeOpenEdit(char const *tree, int shot); + extern EXPORT int _TreeOpenEdit(void **dbid, char const *tree, int shot); + extern EXPORT int TreeOpenNew(char const *tree, int shot); + extern EXPORT int _TreeOpenNew(void **dbid, char const *tree, int shot); + extern EXPORT int TreePutRecord(int nid, mdsdsc_t *descriptor_ptr, + int utility_update); + extern EXPORT int _TreePutRecord(void *dbid, int nid, mdsdsc_t *descriptor, + int utility_update); + extern EXPORT int TreeQuitTree(char const *tree, int shot); + extern EXPORT int _TreeQuitTree(void **dbid, char const *tree, int shot); + extern EXPORT int TreeRemoveNodesTags(int nid); + extern EXPORT int _TreeRemoveNodesTags(void *dbid, int nid); + extern EXPORT int TreeRemoveTag(char const *tagname); + extern EXPORT int _TreeRemoveTag(void *dbid, char const *tagname); + extern EXPORT int TreeRenameNode(int nid, char const *newname); + extern EXPORT int _TreeRenameNode(void *dbid, int nid, char const *newname); + extern EXPORT void TreeRestoreContext(void *ctx); + extern EXPORT void _TreeRestoreContext(void **dbid, void *ctx); + extern EXPORT int TreeRundownTree(mdsdsc_t *treenam, int *shotid, + int single_tree, int force_exit); + extern EXPORT void *TreeSaveContext(); + extern EXPORT void *_TreeSaveContext(void *dbid); + extern EXPORT int TreeSetDbi(struct dbi_itm *itmlst); + extern EXPORT int _TreeSetDbi(void *dbid, struct dbi_itm *itmlst); + extern EXPORT int TreeSetNci(int nid, struct nci_itm *itmlst); + extern EXPORT int _TreeSetNci(void *dbid, int nid, struct nci_itm *itmlst); + extern EXPORT int TreeSetDefault(char *path, int *nid); + extern EXPORT int _TreeSetDefault(void *dbid, char *path, int *nid); + extern EXPORT int TreeSetDefaultNid(int nid); + extern EXPORT int _TreeSetDefaultNid(void *dbid, int nid); + extern EXPORT int TreeSetNoSubtree(int nid); + extern EXPORT int _TreeSetNoSubtree(void *dbid, int nid); + extern EXPORT int TreeSetStackSize(int new_size); + extern EXPORT int _TreeSetStackSize(void **dbid, int new_size); + extern EXPORT int TreeSetSubtree(int nid); + extern EXPORT int _TreeSetSubtree(void *dbid, int nid); + extern EXPORT int TreeSetUsage(int nid, unsigned char usage); + extern EXPORT int _TreeSetUsage(void *dbid, int nid, unsigned char usage); + extern EXPORT int TreeStartConglomerate(int numnodes); + extern EXPORT int _TreeStartConglomerate(void *dbid, int numnodes); + extern EXPORT void *TreeSwitchDbid(void *dbid); + extern EXPORT int TreeTurnOff(int nid); + extern EXPORT int _TreeTurnOff(void *dbid, int nid); + extern EXPORT int TreeTurnOn(int nid); + extern EXPORT int _TreeTurnOn(void *dbid, int nid); + extern EXPORT int TreeUsePrivateCtx(int onoff); + extern EXPORT int TreeUsingPrivateCtx(); + extern EXPORT int TreeVerify(); + extern EXPORT int _TreeVerify(void *dbid); + extern EXPORT int TreeWait(); + extern EXPORT int TreeWriteTree(char const *tree, int shot); + extern EXPORT int _TreeWriteTree(void **dbid, char const *tree, int shot); -// Segments -extern EXPORT int TreeBeginSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, - int idx); -extern EXPORT int _TreeBeginSegment(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, - mdsdsc_a_t *initialData, int idx); -extern EXPORT int TreeBeginSegmentResampled(int nid, mdsdsc_t *start, + // Segments + extern EXPORT int TreeBeginSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, mdsdsc_a_t *initialData, + int idx); + extern EXPORT int _TreeBeginSegment(void *dbid, int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, + mdsdsc_a_t *initialData, int idx); + extern EXPORT int TreeBeginSegmentResampled(int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, + mdsdsc_a_t *initialData, int idx, + int resNid, int resFactor); + extern EXPORT int _TreeBeginSegmentResampled(void *dbid, int nid, + mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, + mdsdsc_a_t *initialData, int idx, + int resNid, int resFactor); + extern EXPORT int TreeBeginSegmentMinMax(int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, + mdsdsc_a_t *initialData, int idx, + int resNid, int resFactor); + extern EXPORT int _TreeBeginSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dim, mdsdsc_a_t *initialData, int idx, int resNid, int resFactor); -extern EXPORT int _TreeBeginSegmentResampled(void *dbid, int nid, - mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, + extern EXPORT int TreeMakeSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, mdsdsc_a_t *initialData, + int idx, int filled); + extern EXPORT int _TreeMakeSegment(void *dbid, int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, + mdsdsc_a_t *initialData, int idx, + int filled); + extern EXPORT int TreeMakeSegmentResampled(int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, mdsdsc_a_t *initialData, int idx, - int resNid, int resFactor); -extern EXPORT int TreeBeginSegmentMinMax(int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, - mdsdsc_a_t *initialData, int idx, - int resNid, int resFactor); -extern EXPORT int _TreeBeginSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, - mdsdsc_a_t *initialData, int idx, - int resNid, int resFactor); -extern EXPORT int TreeMakeSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, - int idx, int filled); -extern EXPORT int _TreeMakeSegment(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, - mdsdsc_a_t *initialData, int idx, - int filled); -extern EXPORT int TreeMakeSegmentResampled(int nid, mdsdsc_t *start, + int filled, int resNid, + int resFactor); + extern EXPORT int + _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, mdsdsc_a_t *initialData, int idx, + int filled, int resNid, int resFactor); + extern EXPORT int TreeMakeSegmentMinMax(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, mdsdsc_a_t *initialData, + int idx, int filled, int resNid, + int resFactor); + extern EXPORT int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dim, mdsdsc_a_t *initialData, int idx, - int filled, int resNid, - int resFactor); -extern EXPORT int -_TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, int idx, - int filled, int resNid, int resFactor); -extern EXPORT int TreeMakeSegmentMinMax(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, - int idx, int filled, int resNid, - int resFactor); -extern EXPORT int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, - mdsdsc_a_t *initialData, int idx, - int filled, int resNid, int resFactor); -extern EXPORT int TreePutSegment(int nid, const int rowidx, mdsdsc_a_t *data); -extern EXPORT int _TreePutSegment(void *dbid, int nid, const int rowidx, - mdsdsc_a_t *data); -extern EXPORT int TreePutSegmentResampled(int nid, const int rowidx, + int filled, int resNid, int resFactor); + extern EXPORT int TreePutSegment(int nid, const int rowidx, mdsdsc_a_t *data); + extern EXPORT int _TreePutSegment(void *dbid, int nid, const int rowidx, + mdsdsc_a_t *data); + extern EXPORT int TreePutSegmentResampled(int nid, const int rowidx, + mdsdsc_a_t *data, int resNid, + int resFactor); + extern EXPORT int _TreePutSegmentResampled(void *dbid, int nid, + const int rowidx, mdsdsc_a_t *data, + int resNid, int resFactor); + extern EXPORT int TreePutSegmentMinMax(int nid, const int rowidx, + mdsdsc_a_t *data, int resNid, + int resFactor); + extern EXPORT int _TreePutSegmentMinMax(void *dbid, int nid, const int rowidx, mdsdsc_a_t *data, int resNid, int resFactor); -extern EXPORT int _TreePutSegmentResampled(void *dbid, int nid, - const int rowidx, mdsdsc_a_t *data, - int resNid, int resFactor); -extern EXPORT int TreePutSegmentMinMax(int nid, const int rowidx, - mdsdsc_a_t *data, int resNid, - int resFactor); -extern EXPORT int _TreePutSegmentMinMax(void *dbid, int nid, const int rowidx, - mdsdsc_a_t *data, int resNid, - int resFactor); -extern EXPORT int TreeSetRowsFilled(int nid, int rows_filled); -extern EXPORT int _TreeSetRowsFilled(void *dbid, int nid, int rows_filled); -extern EXPORT int TreeUpdateSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, int idx); -extern EXPORT int _TreeUpdateSegment(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *dim, int idx); -extern EXPORT int TreeBeginTimestampedSegment(int nid, mdsdsc_a_t *initialValue, - int idx); -extern EXPORT int _TreeBeginTimestampedSegment(void *dbid, int nid, - mdsdsc_a_t *initialValue, - int idx); -extern EXPORT int TreePutTimestampedSegment(int nid, int64_t *timestamp, - mdsdsc_a_t *rowdata); -extern EXPORT int _TreePutTimestampedSegment(void *dbid, int nid, - int64_t *timestamp, - mdsdsc_a_t *rowdata); -extern EXPORT int TreeMakeTimestampedSegment(int nid, int64_t *timestamp, - mdsdsc_a_t *rowdata, int idx, - int filled); -extern EXPORT int _TreeMakeTimestampedSegment(void *dbid, int nid, - int64_t *timestamp, - mdsdsc_a_t *rowdata, int idx, - int filled); -extern EXPORT int TreePutRow(int nid, int bufsize, int64_t *timestamp, - mdsdsc_a_t *rowdata); -extern EXPORT int _TreePutRow(void *dbid, int nid, int bufsize, - int64_t *timestamp, mdsdsc_a_t *rowdata); -extern EXPORT int TreeSetTimeContext(mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *delta); -extern EXPORT int _TreeSetTimeContext(void *dbid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_t *delta); -extern EXPORT int TreeGetTimeContext(mdsdsc_xd_t *start, mdsdsc_xd_t *end, - mdsdsc_xd_t *delta); -extern EXPORT int _TreeGetTimeContext(void *dbid, mdsdsc_xd_t *start, - mdsdsc_xd_t *end, mdsdsc_xd_t *delta); -extern EXPORT int TreeGetNumSegments(int nid, int *num); -extern EXPORT int _TreeGetNumSegments(void *dbid, int nid, int *num); -extern EXPORT int TreeGetSegmentLimits(int nid, int segidx, mdsdsc_xd_t *start, - mdsdsc_xd_t *end); -extern EXPORT int _TreeGetSegmentLimits(void *dbid, int nid, int segidx, - mdsdsc_xd_t *start, mdsdsc_xd_t *end); -extern EXPORT int TreeGetSegment(int nid, int segidx, mdsdsc_xd_t *data, - mdsdsc_xd_t *dim); -extern EXPORT int _TreeGetSegment(void *dbid, int nid, int segidx, - mdsdsc_xd_t *data, mdsdsc_xd_t *dim); -extern EXPORT int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_xd_t *retSegments); -extern EXPORT int _TreeGetSegments(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_xd_t *retSegments); -extern EXPORT int TreeGetSegmentInfo(int nid, int idx, char *dtype, char *dimct, - int *dims, int *next_row); -extern EXPORT int _TreeGetSegmentInfo(void *dbid, int nid, int idx, char *dtype, - char *dimct, int *dims, int *next_row); -extern EXPORT int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_xd_t *out); -extern EXPORT int _TreeGetSegments(void *dbid, int nid, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_xd_t *out); -extern EXPORT int TreeGetSegmentTimes(int nid, int *numsegs, int64_t **times); -extern EXPORT int _TreeGetSegmentTimes(void *dbid, int nid, int *numsegs, - int64_t **times); -extern EXPORT int TreeGetSegmentTimesXd(int nid, int *numsegs, - mdsdsc_xd_t *start_list, - mdsdsc_xd_t *end_list); -extern EXPORT int _TreeGetSegmentTimesXd(void *dbid, int nid, int *numsegs, - mdsdsc_xd_t *start_list, - mdsdsc_xd_t *end_list); + extern EXPORT int TreeSetRowsFilled(int nid, int rows_filled); + extern EXPORT int _TreeSetRowsFilled(void *dbid, int nid, int rows_filled); + extern EXPORT int TreeUpdateSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, int idx); + extern EXPORT int _TreeUpdateSegment(void *dbid, int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *dim, int idx); + extern EXPORT int TreeBeginTimestampedSegment(int nid, mdsdsc_a_t *initialValue, + int idx); + extern EXPORT int _TreeBeginTimestampedSegment(void *dbid, int nid, + mdsdsc_a_t *initialValue, + int idx); + extern EXPORT int TreePutTimestampedSegment(int nid, int64_t *timestamp, + mdsdsc_a_t *rowdata); + extern EXPORT int _TreePutTimestampedSegment(void *dbid, int nid, + int64_t *timestamp, + mdsdsc_a_t *rowdata); + extern EXPORT int TreeMakeTimestampedSegment(int nid, int64_t *timestamp, + mdsdsc_a_t *rowdata, int idx, + int filled); + extern EXPORT int _TreeMakeTimestampedSegment(void *dbid, int nid, + int64_t *timestamp, + mdsdsc_a_t *rowdata, int idx, + int filled); + extern EXPORT int TreePutRow(int nid, int bufsize, int64_t *timestamp, + mdsdsc_a_t *rowdata); + extern EXPORT int _TreePutRow(void *dbid, int nid, int bufsize, + int64_t *timestamp, mdsdsc_a_t *rowdata); + extern EXPORT int TreeSetTimeContext(mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *delta); + extern EXPORT int _TreeSetTimeContext(void *dbid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_t *delta); + extern EXPORT int TreeGetTimeContext(mdsdsc_xd_t *start, mdsdsc_xd_t *end, + mdsdsc_xd_t *delta); + extern EXPORT int _TreeGetTimeContext(void *dbid, mdsdsc_xd_t *start, + mdsdsc_xd_t *end, mdsdsc_xd_t *delta); + extern EXPORT int TreeGetNumSegments(int nid, int *num); + extern EXPORT int _TreeGetNumSegments(void *dbid, int nid, int *num); + extern EXPORT int TreeGetSegmentLimits(int nid, int segidx, mdsdsc_xd_t *start, + mdsdsc_xd_t *end); + extern EXPORT int _TreeGetSegmentLimits(void *dbid, int nid, int segidx, + mdsdsc_xd_t *start, mdsdsc_xd_t *end); + extern EXPORT int TreeGetSegment(int nid, int segidx, mdsdsc_xd_t *data, + mdsdsc_xd_t *dim); + extern EXPORT int _TreeGetSegment(void *dbid, int nid, int segidx, + mdsdsc_xd_t *data, mdsdsc_xd_t *dim); + extern EXPORT int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_xd_t *retSegments); + extern EXPORT int _TreeGetSegments(void *dbid, int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_xd_t *retSegments); + extern EXPORT int TreeGetSegmentInfo(int nid, int idx, char *dtype, char *dimct, + int *dims, int *next_row); + extern EXPORT int _TreeGetSegmentInfo(void *dbid, int nid, int idx, char *dtype, + char *dimct, int *dims, int *next_row); + extern EXPORT int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_xd_t *out); + extern EXPORT int _TreeGetSegments(void *dbid, int nid, mdsdsc_t *start, + mdsdsc_t *end, mdsdsc_xd_t *out); + extern EXPORT int TreeGetSegmentTimes(int nid, int *numsegs, int64_t **times); + extern EXPORT int _TreeGetSegmentTimes(void *dbid, int nid, int *numsegs, + int64_t **times); + extern EXPORT int TreeGetSegmentTimesXd(int nid, int *numsegs, + mdsdsc_xd_t *start_list, + mdsdsc_xd_t *end_list); + extern EXPORT int _TreeGetSegmentTimesXd(void *dbid, int nid, int *numsegs, + mdsdsc_xd_t *start_list, + mdsdsc_xd_t *end_list); -extern EXPORT int TreeGetXNci(int nid, const char *xnciname, - mdsdsc_xd_t *value); -extern EXPORT int _TreeGetXNci(void *dbid, int nid, const char *xnciname, - mdsdsc_xd_t *value); -extern EXPORT int TreeSetXNci(int nid, const char *xnciname, mdsdsc_t *value); -extern EXPORT int _TreeSetXNci(void *dbid, int nid, const char *xnciname, - mdsdsc_t *value); -extern EXPORT int TreeSetViewDate(int64_t *date); -extern EXPORT int TreeSetCurrentShotId(char const *experiment, int shot); -extern EXPORT int TreeGetCurrentShotId(char const *experiment); -extern EXPORT int TreeSetDbiItm(int code, int value); -extern EXPORT int64_t TreeGetDatafileSize(); -extern EXPORT int64_t _TreeGetDatafileSize(void *dbid); + extern EXPORT int TreeGetXNci(int nid, const char *xnciname, + mdsdsc_xd_t *value); + extern EXPORT int _TreeGetXNci(void *dbid, int nid, const char *xnciname, + mdsdsc_xd_t *value); + extern EXPORT int TreeSetXNci(int nid, const char *xnciname, mdsdsc_t *value); + extern EXPORT int _TreeSetXNci(void *dbid, int nid, const char *xnciname, + mdsdsc_t *value); + extern EXPORT int TreeSetViewDate(int64_t *date); + extern EXPORT int TreeSetCurrentShotId(char const *experiment, int shot); + extern EXPORT int TreeGetCurrentShotId(char const *experiment); + extern EXPORT int TreeSetDbiItm(int code, int value); + extern EXPORT int64_t TreeGetDatafileSize(); + extern EXPORT int64_t _TreeGetDatafileSize(void *dbid); -extern EXPORT int TreeFindNodeTagsDsc(int nid_in, void **ctx_ptr, - mdsdsc_t *tag); -extern EXPORT int TreeFindTagWildDsc(char *wild, int *nidout, void **ctx_inout, - mdsdsc_xd_t *name); + extern EXPORT int TreeFindNodeTagsDsc(int nid_in, void **ctx_ptr, + mdsdsc_t *tag); + extern EXPORT int TreeFindTagWildDsc(char *wild, int *nidout, void **ctx_inout, + mdsdsc_xd_t *name); -extern EXPORT int _TreeGetSegmentScale(void *dbid, int nid, mdsdsc_xd_t *value); -extern EXPORT int TreeGetSegmentScale(int nid, mdsdsc_xd_t *value); -extern EXPORT int _TreeSetSegmentScale(void *dbid, int nid, mdsdsc_t *value); -extern EXPORT int TreeSetSegmentScale(int nid, mdsdsc_t *value); + extern EXPORT int _TreeGetSegmentScale(void *dbid, int nid, mdsdsc_xd_t *value); + extern EXPORT int TreeGetSegmentScale(int nid, mdsdsc_xd_t *value); + extern EXPORT int _TreeSetSegmentScale(void *dbid, int nid, mdsdsc_t *value); + extern EXPORT int TreeSetSegmentScale(int nid, mdsdsc_t *value); -extern EXPORT int _TreeExecute(void *dbid, ...); -extern EXPORT int _TreeEvaluate(void *dbid, ...); -extern EXPORT int _TreeDecompile(void *dbid, ...); -extern EXPORT int _TreeCompile(void *dbid, ...); + extern EXPORT int _TreeExecute(void *dbid, ...); + extern EXPORT int _TreeEvaluate(void *dbid, ...); + extern EXPORT int _TreeDecompile(void *dbid, ...); + extern EXPORT int _TreeCompile(void *dbid, ...); -extern EXPORT void *TreeCtxPush(void **ctx); -extern EXPORT void TreeCtxPop(void *ps); -extern EXPORT void *TreeDbidPush(void *dbid); -extern EXPORT void *TreeDbidPop(void *ps); + extern EXPORT void *TreeCtxPush(void **ctx); + extern EXPORT void TreeCtxPop(void *ps); + extern EXPORT void *TreeDbidPush(void *dbid); + extern EXPORT void *TreeDbidPop(void *ps); #define CTX_PUSH(ctx) pthread_cleanup_push(TreeCtxPop, TreeCtxPush(ctx)) #define CTX_POP(ctx) pthread_cleanup_pop(1) diff --git a/include/treeshr_hooks.h b/include/treeshr_hooks.h index bf3a1b9296..0b881b590c 100644 --- a/include/treeshr_hooks.h +++ b/include/treeshr_hooks.h @@ -1,7 +1,8 @@ #ifndef _TREESHR_HOOKS_H #define _TREESHR_HOOKS_H -typedef enum { +typedef enum +{ OpenTree, OpenTreeEdit, RetrieveTree, diff --git a/include/usagedef.h b/include/usagedef.h index 94064339aa..5e1620eae3 100644 --- a/include/usagedef.h +++ b/include/usagedef.h @@ -8,8 +8,8 @@ Node Usage definitions #ifdef MDSOBJECTSCPPSHRVS_EXPORTS // visual studio uses int types for typedef #define TYPEDEF(bytes) enum -#define ENDDEF(type, name) \ - ; \ +#define ENDDEF(type, name) \ + ; \ typedef type name #else #define TYPEDEF(bytes) typedef enum __attribute__((__packed__)) diff --git a/javamds/MDSplus_Connection.h b/javamds/MDSplus_Connection.h index 858658590b..55a6905648 100644 --- a/javamds/MDSplus_Connection.h +++ b/javamds/MDSplus_Connection.h @@ -5,64 +5,65 @@ #ifndef _Included_MDSplus_Connection #define _Included_MDSplus_Connection #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* + /* * Class: MDSplus_Connection * Method: connectToMds * Signature: (LMDSplus/String;)I */ -JNIEXPORT jint JNICALL Java_MDSplus_Connection_connectToMds(JNIEnv *, jobject, - jstring); + JNIEXPORT jint JNICALL Java_MDSplus_Connection_connectToMds(JNIEnv *, jobject, + jstring); -/* + /* * Class: MDSplus_Connection * Method: disconnectFromMds * Signature: (I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Connection_disconnectFromMds(JNIEnv *, - jobject, jint); + JNIEXPORT void JNICALL Java_MDSplus_Connection_disconnectFromMds(JNIEnv *, + jobject, jint); -/* + /* * Class: MDSplus_Connection * Method: openTree * Signature: (ILjava/lang/String;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Connection_openTree(JNIEnv *, jobject, jint, - jstring, jint); + JNIEXPORT void JNICALL Java_MDSplus_Connection_openTree(JNIEnv *, jobject, jint, + jstring, jint); -/* + /* * Class: MDSplus_Connection * Method: closeTree * Signature: (I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Connection_closeTree(JNIEnv *, jobject, - jint); + JNIEXPORT void JNICALL Java_MDSplus_Connection_closeTree(JNIEnv *, jobject, + jint); -/* + /* * Class: MDSplus_Connection * Method: setDefault * Signature: (ILjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Connection_setDefault(JNIEnv *, jobject, - jint, jstring); + JNIEXPORT void JNICALL Java_MDSplus_Connection_setDefault(JNIEnv *, jobject, + jint, jstring); -/* + /* * Class: MDSplus_Connection * Method: get * Signature: (ILjava/lang/String;[LMDSplus/Data;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Connection_get(JNIEnv *, jobject, jint, - jstring, jobjectArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Connection_get(JNIEnv *, jobject, jint, + jstring, jobjectArray); -/* + /* * Class: MDSplus_Connection * Method: put * Signature: (ILjava/lang/String;Ljava/lang/String;[LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Connection_put(JNIEnv *, jobject, jint, - jstring, jstring, - jobjectArray); + JNIEXPORT void JNICALL Java_MDSplus_Connection_put(JNIEnv *, jobject, jint, + jstring, jstring, + jobjectArray); #ifdef __cplusplus } diff --git a/javamds/MDSplus_Data.h b/javamds/MDSplus_Data.h index 57322a2129..5f2fa5496d 100644 --- a/javamds/MDSplus_Data.h +++ b/javamds/MDSplus_Data.h @@ -5,7 +5,8 @@ #ifndef _Included_MDSplus_Data #define _Included_MDSplus_Data #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #undef MDSplus_Data_DTYPE_BU #define MDSplus_Data_DTYPE_BU 2L @@ -107,80 +108,80 @@ extern "C" { #define MDSplus_Data_CLASS_R 194L #undef MDSplus_Data_CLASS_APD #define MDSplus_Data_CLASS_APD 196L -/* + /* * Class: MDSplus_Data * Method: compile * Signature: (Ljava/lang/String;[LMDSplus/Data;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *, jclass, jstring, - jobjectArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *, jclass, jstring, + jobjectArray); -/* + /* * Class: MDSplus_Data * Method: execute * Signature: (Ljava/lang/String;[LMDSplus/Data;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *, jclass, jstring, - jobjectArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *, jclass, jstring, + jobjectArray); -/* + /* * Class: MDSplus_Data * Method: decompile * Signature: (J)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *, jobject, jlong); + JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *, jobject, jlong); -/* + /* * Class: MDSplus_Data * Method: cloneData * Signature: ()LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_cloneData(JNIEnv *, jobject); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_cloneData(JNIEnv *, jobject); -/* + /* * Class: MDSplus_Data * Method: dataData * Signature: ()LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *, jobject, jlong); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *, jobject, jlong); -/* + /* * Class: MDSplus_Data * Method: evaluateData * Signature: (J)LMDSplus/String; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *, jobject, - jlong); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *, jobject, + jlong); -/* + /* * Class: MDSplus_Data * Method: serialize * Signature: ()[B */ -JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *, jobject); + JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *, jobject); -/* + /* * Class: MDSplus_Data * Method: deserialize * Signature: ([B)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Data_deserialize(JNIEnv *, jclass, - jbyteArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Data_deserialize(JNIEnv *, jclass, + jbyteArray); -/* + /* * Class: MDSplus_Data * Method: convertToDate * Signature: (J)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_MDSplus_Data_convertToDate(JNIEnv *, jclass, - jlong); + JNIEXPORT jstring JNICALL Java_MDSplus_Data_convertToDate(JNIEnv *, jclass, + jlong); -/* + /* * Class: MDSplus_Data * Method: getTime * Signature: ()J */ -JNIEXPORT jlong JNICALL Java_MDSplus_Data_getTime(JNIEnv *, jclass); + JNIEXPORT jlong JNICALL Java_MDSplus_Data_getTime(JNIEnv *, jclass); #ifdef __cplusplus } diff --git a/javamds/MDSplus_Event.h b/javamds/MDSplus_Event.h index bb9edbccbf..0db16f9bfb 100644 --- a/javamds/MDSplus_Event.h +++ b/javamds/MDSplus_Event.h @@ -5,31 +5,32 @@ #ifndef _Included_MDSplus_Event #define _Included_MDSplus_Event #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* + /* * Class: MDSplus_Event * Method: setEventRaw * Signature: (Ljava/lang/String;[B)V */ -JNIEXPORT void JNICALL Java_MDSplus_Event_setEventRaw(JNIEnv *, jclass, jstring, - jbyteArray); + JNIEXPORT void JNICALL Java_MDSplus_Event_setEventRaw(JNIEnv *, jclass, jstring, + jbyteArray); -/* + /* * Class: MDSplus_Event * Method: registerEvent * Signature: (Ljava/lang/String;)J */ -JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *, jobject, - jstring); + JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *, jobject, + jstring); -/* + /* * Class: MDSplus_Event * Method: unregisterEvent * Signature: (J)V */ -JNIEXPORT void JNICALL Java_MDSplus_Event_unregisterEvent(JNIEnv *, jobject, - jlong); + JNIEXPORT void JNICALL Java_MDSplus_Event_unregisterEvent(JNIEnv *, jobject, + jlong); #ifdef __cplusplus } diff --git a/javamds/MDSplus_REvent.h b/javamds/MDSplus_REvent.h index 82caafe2c1..6cd5549b84 100644 --- a/javamds/MDSplus_REvent.h +++ b/javamds/MDSplus_REvent.h @@ -5,40 +5,41 @@ #ifndef _Included_MDSplus_REvent #define _Included_MDSplus_REvent #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* + /* * Class: MDSplus_REvent * Method: setEventRaw * Signature: (Ljava/lang/String;[B)V */ -JNIEXPORT void JNICALL Java_MDSplus_REvent_setEventRaw(JNIEnv *, jclass, - jstring, jbyteArray); + JNIEXPORT void JNICALL Java_MDSplus_REvent_setEventRaw(JNIEnv *, jclass, + jstring, jbyteArray); -/* + /* * Class: MDSplus_REvent * Method: setEventRawAndWait * Signature: (Ljava/lang/String;[B)V */ -JNIEXPORT void JNICALL Java_MDSplus_REvent_setEventRawAndWait(JNIEnv *, jclass, - jstring, - jbyteArray); + JNIEXPORT void JNICALL Java_MDSplus_REvent_setEventRawAndWait(JNIEnv *, jclass, + jstring, + jbyteArray); -/* + /* * Class: MDSplus_REvent * Method: registerEvent * Signature: (Ljava/lang/String;)J */ -JNIEXPORT jlong JNICALL Java_MDSplus_REvent_registerEvent(JNIEnv *, jobject, - jstring); + JNIEXPORT jlong JNICALL Java_MDSplus_REvent_registerEvent(JNIEnv *, jobject, + jstring); -/* + /* * Class: MDSplus_REvent * Method: unregisterEvent * Signature: (J)V */ -JNIEXPORT void JNICALL Java_MDSplus_REvent_unregisterEvent(JNIEnv *, jobject, - jlong); + JNIEXPORT void JNICALL Java_MDSplus_REvent_unregisterEvent(JNIEnv *, jobject, + jlong); #ifdef __cplusplus } diff --git a/javamds/MDSplus_Tree.h b/javamds/MDSplus_Tree.h index 4410f4dbe3..2682768160 100644 --- a/javamds/MDSplus_Tree.h +++ b/javamds/MDSplus_Tree.h @@ -5,7 +5,8 @@ #ifndef _Included_MDSplus_Tree #define _Included_MDSplus_Tree #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #undef MDSplus_Tree_DbiNAME #define MDSplus_Tree_DbiNAME 1L @@ -57,204 +58,204 @@ extern "C" { #define MDSplus_Tree_TreeUSAGE_SUBTREE 11L #undef MDSplus_Tree_TreeUSAGE_COMPOUND_DATA #define MDSplus_Tree_TreeUSAGE_COMPOUND_DATA 1L -/* + /* * Class: MDSplus_Tree * Method: openTree * Signature: (JLjava/lang/String;IZ)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_openTree(JNIEnv *, jobject, jlong, - jstring, jint, jboolean); + JNIEXPORT void JNICALL Java_MDSplus_Tree_openTree(JNIEnv *, jobject, jlong, + jstring, jint, jboolean); -/* + /* * Class: MDSplus_Tree * Method: closeTree * Signature: (JLjava/lang/String;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_closeTree(JNIEnv *, jobject, jlong, - jstring, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_closeTree(JNIEnv *, jobject, jlong, + jstring, jint); -/* + /* * Class: MDSplus_Tree * Method: editTree * Signature: (JLjava/lang/String;IZ)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_editTree(JNIEnv *, jobject, jlong, - jstring, jint, jboolean); + JNIEXPORT void JNICALL Java_MDSplus_Tree_editTree(JNIEnv *, jobject, jlong, + jstring, jint, jboolean); -/* + /* * Class: MDSplus_Tree * Method: writeTree * Signature: (JLjava/lang/String;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_writeTree(JNIEnv *, jclass, jlong, - jstring, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_writeTree(JNIEnv *, jclass, jlong, + jstring, jint); -/* + /* * Class: MDSplus_Tree * Method: quitTree * Signature: (JLjava/lang/String;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_quitTree(JNIEnv *, jclass, jlong, - jstring, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_quitTree(JNIEnv *, jclass, jlong, + jstring, jint); -/* + /* * Class: MDSplus_Tree * Method: findNode * Signature: (JLjava/lang/String;)I */ -JNIEXPORT jint JNICALL Java_MDSplus_Tree_findNode(JNIEnv *, jclass, jlong, - jstring); + JNIEXPORT jint JNICALL Java_MDSplus_Tree_findNode(JNIEnv *, jclass, jlong, + jstring); -/* + /* * Class: MDSplus_Tree * Method: getWild * Signature: (JLjava/lang/String;I)[I */ -JNIEXPORT jintArray JNICALL Java_MDSplus_Tree_getWild(JNIEnv *, jclass, jlong, - jstring, jint); + JNIEXPORT jintArray JNICALL Java_MDSplus_Tree_getWild(JNIEnv *, jclass, jlong, + jstring, jint); -/* + /* * Class: MDSplus_Tree * Method: getDefaultNid * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_MDSplus_Tree_getDefaultNid(JNIEnv *, jclass, jlong); + JNIEXPORT jint JNICALL Java_MDSplus_Tree_getDefaultNid(JNIEnv *, jclass, jlong); -/* + /* * Class: MDSplus_Tree * Method: setDefaultNid * Signature: (JI)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_setDefaultNid(JNIEnv *, jclass, jlong, - jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_setDefaultNid(JNIEnv *, jclass, jlong, + jint); -/* + /* * Class: MDSplus_Tree * Method: getDbiFlag * Signature: (JI)Z */ -JNIEXPORT jboolean JNICALL Java_MDSplus_Tree_getDbiFlag(JNIEnv *, jclass, jlong, - jint); + JNIEXPORT jboolean JNICALL Java_MDSplus_Tree_getDbiFlag(JNIEnv *, jclass, jlong, + jint); -/* + /* * Class: MDSplus_Tree * Method: setDbiFlag * Signature: (JZI)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_setDbiFlag(JNIEnv *, jclass, jlong, - jboolean, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_setDbiFlag(JNIEnv *, jclass, jlong, + jboolean, jint); -/* + /* * Class: MDSplus_Tree * Method: setTreeViewDate * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeViewDate(JNIEnv *, jclass, - jstring); + JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeViewDate(JNIEnv *, jclass, + jstring); -/* + /* * Class: MDSplus_Tree * Method: setTreeTimeContext * Signature: (JLMDSplus/Data;LMDSplus/Data;LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext(JNIEnv *, jclass, - jlong, jobject, - jobject, jobject); + JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext(JNIEnv *, jclass, + jlong, jobject, + jobject, jobject); -/* + /* * Class: MDSplus_Tree * Method: setCurrent * Signature: (Ljava/lang/String;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_setCurrent(JNIEnv *, jclass, jstring, - jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_setCurrent(JNIEnv *, jclass, jstring, + jint); -/* + /* * Class: MDSplus_Tree * Method: getCurrent * Signature: (Ljava/lang/String;)I */ -JNIEXPORT jint JNICALL Java_MDSplus_Tree_getCurrent(JNIEnv *, jclass, jstring); + JNIEXPORT jint JNICALL Java_MDSplus_Tree_getCurrent(JNIEnv *, jclass, jstring); -/* + /* * Class: MDSplus_Tree * Method: createPulseFile * Signature: (JI)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_createPulseFile(JNIEnv *, jclass, - jlong, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_createPulseFile(JNIEnv *, jclass, + jlong, jint); -/* + /* * Class: MDSplus_Tree * Method: deletePulseFile * Signature: (JI)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_deletePulseFile(JNIEnv *, jclass, - jlong, jint); + JNIEXPORT void JNICALL Java_MDSplus_Tree_deletePulseFile(JNIEnv *, jclass, + jlong, jint); -/* + /* * Class: MDSplus_Tree * Method: findTreeTags * Signature: (JLjava/lang/String;)[Ljava/lang/String; */ -JNIEXPORT jobjectArray JNICALL Java_MDSplus_Tree_findTreeTags(JNIEnv *, jclass, - jlong, jstring); + JNIEXPORT jobjectArray JNICALL Java_MDSplus_Tree_findTreeTags(JNIEnv *, jclass, + jlong, jstring); -/* + /* * Class: MDSplus_Tree * Method: addTreeNode * Signature: (JLjava/lang/String;I)I */ -JNIEXPORT jint JNICALL Java_MDSplus_Tree_addTreeNode(JNIEnv *, jclass, jlong, - jstring, jint); + JNIEXPORT jint JNICALL Java_MDSplus_Tree_addTreeNode(JNIEnv *, jclass, jlong, + jstring, jint); -/* + /* * Class: MDSplus_Tree * Method: addTreeDevice * Signature: (JLjava/lang/String;Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_addTreeDevice(JNIEnv *, jclass, jlong, - jstring, jstring); + JNIEXPORT void JNICALL Java_MDSplus_Tree_addTreeDevice(JNIEnv *, jclass, jlong, + jstring, jstring); -/* + /* * Class: MDSplus_Tree * Method: deleteTreeNode * Signature: (JLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_deleteTreeNode(JNIEnv *, jclass, jlong, - jstring); + JNIEXPORT void JNICALL Java_MDSplus_Tree_deleteTreeNode(JNIEnv *, jclass, jlong, + jstring); -/* + /* * Class: MDSplus_Tree * Method: removeTreeTag * Signature: (JLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_Tree_removeTreeTag(JNIEnv *, jclass, jlong, - jstring); + JNIEXPORT void JNICALL Java_MDSplus_Tree_removeTreeTag(JNIEnv *, jclass, jlong, + jstring); -/* + /* * Class: MDSplus_Tree * Method: getDatafileSize * Signature: (J)J */ -JNIEXPORT jlong JNICALL Java_MDSplus_Tree_getDatafileSize(JNIEnv *, jclass, - jlong); + JNIEXPORT jlong JNICALL Java_MDSplus_Tree_getDatafileSize(JNIEnv *, jclass, + jlong); -/* + /* * Class: MDSplus_Tree * Method: execute * Signature: (JLjava/lang/String;[LMDSplus/Data;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *, jclass, jlong, - jstring, jobjectArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *, jclass, jlong, + jstring, jobjectArray); -/* + /* * Class: MDSplus_Tree * Method: compile * Signature: (JLjava/lang/String;[LMDSplus/Data;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_Tree_compile(JNIEnv *, jclass, jlong, - jstring, jobjectArray); + JNIEXPORT jobject JNICALL Java_MDSplus_Tree_compile(JNIEnv *, jclass, jlong, + jstring, jobjectArray); #ifdef __cplusplus } diff --git a/javamds/MDSplus_TreeNode.h b/javamds/MDSplus_TreeNode.h index f733910e3b..43ab7eb965 100644 --- a/javamds/MDSplus_TreeNode.h +++ b/javamds/MDSplus_TreeNode.h @@ -5,7 +5,8 @@ #ifndef _Included_MDSplus_TreeNode #define _Included_MDSplus_TreeNode #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #undef MDSplus_TreeNode_DTYPE_BU #define MDSplus_TreeNode_DTYPE_BU 2L @@ -245,353 +246,353 @@ extern "C" { #define MDSplus_TreeNode_TreeUSAGE_SUBTREE 11L #undef MDSplus_TreeNode_TreeUSAGE_COMPOUND_DATA #define MDSplus_TreeNode_TreeUSAGE_COMPOUND_DATA 12L -/* + /* * Class: MDSplus_TreeNode * Method: getNci * Signature: (IJI)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNci(JNIEnv *, jclass, jint, - jlong, jint); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNci(JNIEnv *, jclass, jint, + jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: getNciLong * Signature: (IJI)J */ -JNIEXPORT jlong JNICALL Java_MDSplus_TreeNode_getNciLong(JNIEnv *, jclass, jint, - jlong, jint); + JNIEXPORT jlong JNICALL Java_MDSplus_TreeNode_getNciLong(JNIEnv *, jclass, jint, + jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: getNciString * Signature: (IJI)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_MDSplus_TreeNode_getNciString(JNIEnv *, jclass, - jint, jlong, jint); + JNIEXPORT jstring JNICALL Java_MDSplus_TreeNode_getNciString(JNIEnv *, jclass, + jint, jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: setNciFlag * Signature: (IJIZ)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlag(JNIEnv *, jclass, jint, - jlong, jint, jboolean); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlag(JNIEnv *, jclass, jint, + jlong, jint, jboolean); -/* + /* * Class: MDSplus_TreeNode * Method: setNciFlags * Signature: (IJI)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlags(JNIEnv *, jclass, jint, - jlong, jint); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlags(JNIEnv *, jclass, jint, + jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: getNciFlag * Signature: (IJI)Z */ -JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_getNciFlag(JNIEnv *, jclass, - jint, jlong, jint); + JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_getNciFlag(JNIEnv *, jclass, + jint, jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: getNciFlags * Signature: (IJ)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNciFlags(JNIEnv *, jclass, jint, - jlong); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNciFlags(JNIEnv *, jclass, jint, + jlong); -/* + /* * Class: MDSplus_TreeNode * Method: getNciNids * Signature: (IJII)[I */ -JNIEXPORT jintArray JNICALL Java_MDSplus_TreeNode_getNciNids(JNIEnv *, jclass, - jint, jlong, jint, - jint); + JNIEXPORT jintArray JNICALL Java_MDSplus_TreeNode_getNciNids(JNIEnv *, jclass, + jint, jlong, jint, + jint); -/* + /* * Class: MDSplus_TreeNode * Method: turnOn * Signature: (IJZ)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_turnOn(JNIEnv *, jclass, jint, - jlong, jboolean); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_turnOn(JNIEnv *, jclass, jint, + jlong, jboolean); -/* + /* * Class: MDSplus_TreeNode * Method: isOn * Signature: (IJ)Z */ -JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isOn(JNIEnv *, jclass, jint, - jlong); + JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isOn(JNIEnv *, jclass, jint, + jlong); -/* + /* * Class: MDSplus_TreeNode * Method: isParentOff * Signature: (IJ)Z */ -JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isParentOff(JNIEnv *, jclass, - jint, jlong); + JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isParentOff(JNIEnv *, jclass, + jint, jlong); -/* + /* * Class: MDSplus_TreeNode * Method: getExtendedAttribute * Signature: (IJLjava/lang/String;)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getExtendedAttribute( - JNIEnv *, jclass, jint, jlong, jstring); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getExtendedAttribute( + JNIEnv *, jclass, jint, jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: setExtendedAttribute * Signature: (IJLjava/lang/String;LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( - JNIEnv *, jclass, jint, jlong, jstring, jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( + JNIEnv *, jclass, jint, jlong, jstring, jobject); -/* + /* * Class: MDSplus_TreeNode * Method: getData * Signature: (IJ)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getData(JNIEnv *, jclass, jint, - jlong); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getData(JNIEnv *, jclass, jint, + jlong); -/* + /* * Class: MDSplus_TreeNode * Method: putData * Signature: (IJLMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putData(JNIEnv *, jclass, jint, - jlong, jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putData(JNIEnv *, jclass, jint, + jlong, jobject); -/* + /* * Class: MDSplus_TreeNode * Method: deleteData * Signature: (IJ)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteData(JNIEnv *, jclass, jint, - jlong); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteData(JNIEnv *, jclass, jint, + jlong); -/* + /* * Class: MDSplus_TreeNode * Method: doMethod * Signature: (IJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *, jclass, jint, - jlong, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *, jclass, jint, + jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: getTags * Signature: (IJ)[Ljava/lang/String; */ -JNIEXPORT jobjectArray JNICALL Java_MDSplus_TreeNode_getTags(JNIEnv *, jclass, - jint, jlong); + JNIEXPORT jobjectArray JNICALL Java_MDSplus_TreeNode_getTags(JNIEnv *, jclass, + jint, jlong); -/* + /* * Class: MDSplus_TreeNode * Method: beginSegment * Signature: (IJLMDSplus/Data;LMDSplus/Data;LMDSplus/Data;LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment(JNIEnv *, jclass, - jint, jlong, jobject, - jobject, jobject, - jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment(JNIEnv *, jclass, + jint, jlong, jobject, + jobject, jobject, + jobject); -/* + /* * Class: MDSplus_TreeNode * Method: makeSegment * Signature: (IJLMDSplus/Data;LMDSplus/Data;LMDSplus/Data;LMDSplus/Data;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment(JNIEnv *, jclass, jint, - jlong, jobject, - jobject, jobject, - jobject, jint); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment(JNIEnv *, jclass, jint, + jlong, jobject, + jobject, jobject, + jobject, jint); -/* + /* * Class: MDSplus_TreeNode * Method: putSegment * Signature: (IJLMDSplus/Data;I)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment(JNIEnv *, jclass, jint, - jlong, jobject, jint); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment(JNIEnv *, jclass, jint, + jlong, jobject, jint); -/* + /* * Class: MDSplus_TreeNode * Method: updateSegment * Signature: (IJILMDSplus/Data;LMDSplus/Data;LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment(JNIEnv *, jclass, - jint, jlong, jint, - jobject, jobject, - jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment(JNIEnv *, jclass, + jint, jlong, jint, + jobject, jobject, + jobject); -/* + /* * Class: MDSplus_TreeNode * Method: beginTimestampedSegment * Signature: (IJLMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( - JNIEnv *, jclass, jint, jlong, jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( + JNIEnv *, jclass, jint, jlong, jobject); -/* + /* * Class: MDSplus_TreeNode * Method: putTimestampedSegment * Signature: (IJLMDSplus/Data;[J)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( - JNIEnv *, jclass, jint, jlong, jobject, jlongArray); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( + JNIEnv *, jclass, jint, jlong, jobject, jlongArray); -/* + /* * Class: MDSplus_TreeNode * Method: makeTimestampedSegment * Signature: (IJLMDSplus/Data;[J)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( - JNIEnv *, jclass, jint, jlong, jobject, jlongArray); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( + JNIEnv *, jclass, jint, jlong, jobject, jlongArray); -/* + /* * Class: MDSplus_TreeNode * Method: putRow * Signature: (IJLMDSplus/Data;JI)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow(JNIEnv *, jclass, jint, - jlong, jobject, jlong, - jint); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow(JNIEnv *, jclass, jint, + jlong, jobject, jlong, + jint); -/* + /* * Class: MDSplus_TreeNode * Method: getNumSegments * Signature: (IJ)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNumSegments(JNIEnv *, jclass, - jint, jlong); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNumSegments(JNIEnv *, jclass, + jint, jlong); -/* + /* * Class: MDSplus_TreeNode * Method: acceptSegment * Signature: (IJLMDSplus/Data;LMDSplus/Data;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_acceptSegment(JNIEnv *, jclass, - jint, jlong, jobject, - jobject); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_acceptSegment(JNIEnv *, jclass, + jint, jlong, jobject, + jobject); -/* + /* * Class: MDSplus_TreeNode * Method: acceptRow * Signature: (IJLMDSplus/Data;J)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_acceptRow(JNIEnv *, jclass, jint, - jlong, jobject, jlong); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_acceptRow(JNIEnv *, jclass, jint, + jlong, jobject, jlong); -/* + /* * Class: MDSplus_TreeNode * Method: getSegmentStart * Signature: (IJI)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentStart(JNIEnv *, - jclass, jint, - jlong, jint); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentStart(JNIEnv *, + jclass, jint, + jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: getSegmentEnd * Signature: (IJI)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentEnd(JNIEnv *, jclass, - jint, jlong, - jint); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentEnd(JNIEnv *, jclass, + jint, jlong, + jint); -/* + /* * Class: MDSplus_TreeNode * Method: getSegmentDim * Signature: (IJI)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentDim(JNIEnv *, jclass, - jint, jlong, - jint); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentDim(JNIEnv *, jclass, + jint, jlong, + jint); -/* + /* * Class: MDSplus_TreeNode * Method: getSegment * Signature: (IJI)LMDSplus/Data; */ -JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegment(JNIEnv *, jclass, - jint, jlong, jint); + JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegment(JNIEnv *, jclass, + jint, jlong, jint); -/* + /* * Class: MDSplus_TreeNode * Method: addNode * Signature: (IJLjava/lang/String;I)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addNode(JNIEnv *, jclass, jint, - jlong, jstring, jint); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addNode(JNIEnv *, jclass, jint, + jlong, jstring, jint); -/* + /* * Class: MDSplus_TreeNode * Method: deleteNode * Signature: (IJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteNode(JNIEnv *, jclass, jint, - jlong, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteNode(JNIEnv *, jclass, jint, + jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: renameNode * Signature: (IJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_renameNode(JNIEnv *, jclass, jint, - jlong, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_renameNode(JNIEnv *, jclass, jint, + jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: addTag * Signature: (IJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_addTag(JNIEnv *, jclass, jint, - jlong, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_addTag(JNIEnv *, jclass, jint, + jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: removeTag * Signature: (IJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_removeTag(JNIEnv *, jclass, jint, - jlong, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_removeTag(JNIEnv *, jclass, jint, + jlong, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: addDevice * Signature: (IJLjava/lang/String;Ljava/lang/String;)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addDevice(JNIEnv *, jclass, jint, - jlong, jstring, jstring); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addDevice(JNIEnv *, jclass, jint, + jlong, jstring, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: setSubtree * Signature: (IJZ)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setSubtree(JNIEnv *, jclass, jint, - jlong, jboolean); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setSubtree(JNIEnv *, jclass, jint, + jlong, jboolean); -/* + /* * Class: MDSplus_TreeNode * Method: moveNode * Signature: (IJILjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_MDSplus_TreeNode_moveNode(JNIEnv *, jclass, jint, - jlong, jint, jstring); + JNIEXPORT void JNICALL Java_MDSplus_TreeNode_moveNode(JNIEnv *, jclass, jint, + jlong, jint, jstring); -/* + /* * Class: MDSplus_TreeNode * Method: doAction * Signature: (IJ)I */ -JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_doAction(JNIEnv *, jclass, jint, - jlong); + JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_doAction(JNIEnv *, jclass, jint, + jlong); #ifdef __cplusplus } diff --git a/javamds/MdsHelper.h b/javamds/MdsHelper.h index cf20d83e89..ada1f4c645 100644 --- a/javamds/MdsHelper.h +++ b/javamds/MdsHelper.h @@ -10,11 +10,12 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* + /* * Class: MdsHelper @@ -24,7 +25,7 @@ extern "C" { */ -JNIEXPORT jstring JNICALL Java_MdsHelper_getErrorString(JNIEnv *, jclass, jint); + JNIEXPORT jstring JNICALL Java_MdsHelper_getErrorString(JNIEnv *, jclass, jint); #ifdef __cplusplus } diff --git a/javamds/ServerSupport.c b/javamds/ServerSupport.c index d01fde0484..01cb77d04a 100644 --- a/javamds/ServerSupport.c +++ b/javamds/ServerSupport.c @@ -80,7 +80,8 @@ extern int TdiCompile(); #define MAX_POINTS 1000 EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, - float *dt) { + float *dt) +{ static EMPTYXD(xd); static EMPTYXD(emptyXd); EMPTYXD(startXd); @@ -100,7 +101,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, DESCRIPTOR_SIGNAL_1(retSigDsc, &dataDsc, NULL, ×Dsc); printf("JavaResample %d %f %f %f\n", nid, *xmin, *xmax, *dt); status = TreeGetNumSegments(nid, &numSegments); - if (!(status & 1) || numSegments < 1) { + if (!(status & 1) || numSegments < 1) + { printf("JavaResample: Unexpected Non Segmented Item!!\n"); return &emptyXd; } @@ -109,14 +111,16 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, actMax = *xmax; actDelta = *dt; maxSegment = numSegments - 1; - for (currSegment = 0; currSegment < numSegments; currSegment++) { + for (currSegment = 0; currSegment < numSegments; currSegment++) + { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); if (status & 1) status = TdiData(&startXd, &startXd MDS_END_ARG); if (status & 1) status = TdiFloat(&startXd, &startXd MDS_END_ARG); if (!(status & 1) || startXd.pointer == NULL || - startXd.pointer->class != CLASS_S) { + startXd.pointer->class != CLASS_S) + { printf("Cannot get segment start!!\n"); return &xd; } @@ -125,7 +129,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, if (status & 1) status = TdiFloat(&endXd, &endXd MDS_END_ARG); if (!(status & 1) || endXd.pointer == NULL || - endXd.pointer->class != CLASS_S) { + endXd.pointer->class != CLASS_S) + { printf("Cannot get segment end!!\n"); return &xd; } @@ -149,7 +154,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, actMax = segEnd; if (actMin <= segEnd && actMin >= segStart) minSegment = currSegment; - if (actMax >= segStart && actMax <= segEnd) { + if (actMax >= segStart && actMax <= segEnd) + { maxSegment = currSegment; break; } @@ -161,7 +167,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, outTimes = malloc(outSamples * sizeof(float)); outIdx = 0; - for (currSegment = minSegment; currSegment <= maxSegment; currSegment++) { + for (currSegment = minSegment; currSegment <= maxSegment; currSegment++) + { status = TreeGetSegment(nid, currSegment, &segDataXd, &segTimesXd); if (status & 1) status = TdiData(&segDataXd, &segDataXd MDS_END_ARG); @@ -172,7 +179,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, if (status & 1) status = TdiFloat(&segTimesXd, &segTimesXd MDS_END_ARG); if (!(status & 1) || segDataXd.pointer->class != CLASS_A || - segTimesXd.pointer->class != CLASS_A) { + segTimesXd.pointer->class != CLASS_A) + { printf("Cannot Get segment %d\n", currSegment); return &emptyXd; } @@ -187,36 +195,45 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, currTimes = (float *)arrDsc->pointer; currTimesDouble = (double *)arrDsc->pointer; isTimeDouble = (arrDsc->length == sizeof(double)); - if (currSegment == minSegment) { + if (currSegment == minSegment) + { for (currIdx = 0; currIdx < currSamples && currTimes[currIdx] < actMin; currIdx++) ; - if (currIdx == currSamples) { + if (currIdx == currSamples) + { printf("INTERNAL ERROR in JavaResample\n"); return &emptyXd; } - } else + } + else currIdx = 0; - while (currIdx < currSamples) { + while (currIdx < currSamples) + { if (isTimeDouble) currTime = currTimesDouble[currIdx]; else currTime = currTimes[currIdx]; - if (isDouble) { + if (isDouble) + { currMin = currMax = currDataDouble[currIdx]; while (currIdx < currSamples && - currTime < actMin + (outIdx + 1) * actDelta) { + currTime < actMin + (outIdx + 1) * actDelta) + { if (currDataDouble[currIdx] > currMax) currMax = currDataDouble[currIdx]; if (currDataDouble[currIdx] < currMin) currMin = currDataDouble[currIdx]; currIdx++; } - } else { + } + else + { currMin = currMax = currData[currIdx]; while (currIdx < currSamples && - currTime < actMin + (outIdx + 1) * actDelta) { + currTime < actMin + (outIdx + 1) * actDelta) + { if (currData[currIdx] > currMax) currMax = currData[currIdx]; if (currData[currIdx] < currMin) @@ -248,7 +265,8 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, #define QUITE_SIMILAR(x, y) ((x) > (y) * (1 - 1E-10) && (x) < (y) * (1 + 1E-10)) EXPORT struct descriptor_xd *JavaDim(float *x, int *in_xsamples, float *in_xmin, - float *in_xmax) { + float *in_xmax) +{ static struct descriptor_xd xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; DESCRIPTOR_A(a_d, sizeof(float), DTYPE_FLOAT, 0, 0); int x_points, act_points, start_idx, end_idx, curr_idx, out_idx; @@ -268,10 +286,12 @@ EXPORT struct descriptor_xd *JavaDim(float *x, int *in_xsamples, float *in_xmin, for (end_idx = 0; x[end_idx] < xmax; end_idx++) ; act_points = end_idx - start_idx + 1; - if (act_points < MAX_POINTS) { /*Code time axis */ + if (act_points < MAX_POINTS) + { /*Code time axis */ curr_idx = start_idx + 1; out_idx = 1; - while (curr_idx <= end_idx) { + while (curr_idx <= end_idx) + { out_array[out_idx++] = x[curr_idx - 1]; delta = x[curr_idx + 1] - x[curr_idx]; for (; curr_idx <= end_idx && @@ -283,7 +303,9 @@ EXPORT struct descriptor_xd *JavaDim(float *x, int *in_xsamples, float *in_xmin, curr_idx++; } out_array[0] = 1; - } else { /*Resample */ + } + else + { /*Resample */ out_idx = 1; out_array[out_idx++] = x[start_idx]; @@ -291,7 +313,8 @@ EXPORT struct descriptor_xd *JavaDim(float *x, int *in_xsamples, float *in_xmin, out_array[out_idx++] = (x[end_idx] - x[start_idx]) / (MAX_POINTS - 1); out_array[0] = 1; } - if (out_idx >= act_points) { /* Coding is not convenient */ + if (out_idx >= act_points) + { /* Coding is not convenient */ out_array[0] = -1; out_idx = 1; for (curr_idx = start_idx; curr_idx <= end_idx; curr_idx++) @@ -306,7 +329,8 @@ EXPORT struct descriptor_xd *JavaDim(float *x, int *in_xsamples, float *in_xmin, static int traverseNodeMinMax(int nid, float *xMin, float *xMax); static int traverseExprMinMax(struct descriptor *dsc, float *xMin, - float *xMax) { + float *xMax) +{ int status, nid, size, i, isUpdated; struct descriptor_a *arrD; struct descriptor_r *recD; @@ -316,13 +340,15 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, if (!dsc) return 0; - switch (dsc->class) { + switch (dsc->class) + { case CLASS_XD: return traverseExprMinMax(((struct descriptor_xd *)dsc)->pointer, xMin, xMax); case CLASS_S: case CLASS_D: - switch (dsc->dtype) { + switch (dsc->dtype) + { case DTYPE_PATH: currName = malloc(dsc->length + 1); memcpy(currName, dsc->pointer, dsc->length); @@ -341,7 +367,8 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, case CLASS_A: arrD = (struct descriptor_a *)dsc; size = arrD->arsize / arrD->length; - switch (arrD->dtype) { + switch (arrD->dtype) + { case DTYPE_B: *xMin = ((char *)arrD->pointer)[0]; *xMax = ((char *)arrD->pointer)[size - 1]; @@ -394,7 +421,8 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, min = -1E30; max = 1E30; isUpdated = 0; - switch (recD->dtype) { + switch (recD->dtype) + { case DTYPE_PARAM: case DTYPE_WITH_UNITS: case DTYPE_WITH_ERROR: @@ -411,7 +439,8 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, MdsFree1Dx(&xd, 0); return status; case DTYPE_FUNCTION: - for (i = 0; i < size; i++) { + for (i = 0; i < size; i++) + { status = traverseExprMinMax(recD->dscptrs[i], &currMin, &currMax); if (status) // something meaningful has been returned { @@ -436,7 +465,8 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, return 0; } -static int traverseNodeMinMax(int nid, float *xMin, float *xMax) { +static int traverseNodeMinMax(int nid, float *xMin, float *xMax) +{ EMPTYXD(xd); EMPTYXD(startXd); EMPTYXD(endXd); @@ -445,7 +475,8 @@ static int traverseNodeMinMax(int nid, float *xMin, float *xMax) { status = TreeGetNumSegments(nid, &numSegments); if (!(status & 1)) return 0; - if (numSegments == 0) { + if (numSegments == 0) + { status = TreeGetRecord(nid, &xd); if (!(status & 1)) return 0; @@ -485,7 +516,8 @@ static int traverseNodeMinMax(int nid, float *xMin, float *xMax) { } // Find minimum and maximum time for an expression involving signals -EXPORT int JavaGetMinMax(char *sigExpr, float *xMin, float *xMax) { +EXPORT int JavaGetMinMax(char *sigExpr, float *xMin, float *xMax) +{ EMPTYXD(xd); int status; struct descriptor sigD = {strlen(sigExpr), DTYPE_T, CLASS_S, sigExpr}; @@ -502,7 +534,8 @@ EXPORT int JavaGetMinMax(char *sigExpr, float *xMin, float *xMax) { // Find estimated (by defect) number of points for segmented and not segmented // signal EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, - int *nLimit) { + int *nLimit) +{ EMPTYXD(xd); EMPTYXD(startXd); EMPTYXD(endXd); @@ -516,7 +549,8 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, status = TdiCompile(&sigD, &xd MDS_END_ARG); if (!(status & 1)) return 0; - if (xd.pointer->dtype != DTYPE_NID) { + if (xd.pointer->dtype != DTYPE_NID) + { printf("JavaGetNumPoints: Not a NID\n"); return 0; } @@ -524,18 +558,21 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, status = TreeGetNumSegments(nid, &numSegments); if (!(status & 1)) return 0; - if (numSegments == 0) { + if (numSegments == 0) + { status = TdiData(&xd, &xd MDS_END_ARG); if (!(status & 1) || !xd.pointer || xd.pointer->class != CLASS_A) numPoints = 0; - else { + else + { arrayPtr = (struct descriptor_a *)xd.pointer; numPoints = arrayPtr->arsize / arrayPtr->length; } MdsFree1Dx(&xd, 0); return numPoints; } - for (currSegment = 0; currSegment < numSegments; currSegment++) { + for (currSegment = 0; currSegment < numSegments; currSegment++) + { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); if (!(status & 1)) return 0; @@ -553,7 +590,8 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, if (currStart >= *xMin) break; } - for (numPoints = 0; currSegment < numSegments; currSegment++) { + for (numPoints = 0; currSegment < numSegments; currSegment++) + { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); if (!(status & 1)) return 0; diff --git a/javamds/mdsobjects.c b/javamds/mdsobjects.c index 4c710c9981..070f41ee57 100644 --- a/javamds/mdsobjects.c +++ b/javamds/mdsobjects.c @@ -65,7 +65,8 @@ static CRITICAL_SECTION critSect; static pthread_mutex_t evMutex = PTHREAD_MUTEX_INITIALIZER; #endif -static void set_ctx_field(JNIEnv *env, jobject jobj, void *ctx) { +static void set_ctx_field(JNIEnv *env, jobject jobj, void *ctx) +{ jclass cls = (*env)->GetObjectClass(env, jobj); if (!cls) return; // be safe during finalize @@ -75,24 +76,23 @@ static void set_ctx_field(JNIEnv *env, jobject jobj, void *ctx) { (*env)->SetLongField(env, jobj, ctxFid, PTR2JLONG(ctx)); } -static int doAction(void *ctx, int nid) { +static int doAction(void *ctx, int nid) +{ // EXPORT int doAction(int nid) int rstatus = 0; DESCRIPTOR_NID(nid_d, &nid); DESCRIPTOR_LONG(status_d, &rstatus); int status = CTXCALLR(TdiDoTask, &nid_d, &status_d MDS_END_ARG); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; NCI_ITM setnci[] = { {sizeof(int), NciSTATUS, 0, 0}, {0, NciEND_OF_LIST, 0, 0}, }; setnci[0].pointer = (unsigned char *)&rstatus; status = _TreeSetNci(ctx, nid, setnci); - if - STATUS_OK - return rstatus; + if (STATUS_OK) + return rstatus; return status; } @@ -100,7 +100,8 @@ extern int GetAnswerInfoTS(int sock, char *dtype, short *length, char *ndims, int *dims, int *numbytes, void **dptr, void **m); #ifdef DEBUG -static void printDecompiled(struct descriptor *dsc) { +static void printDecompiled(struct descriptor *dsc) +{ EMPTYXD(out_xd); static char decompiled[1024]; @@ -112,7 +113,8 @@ static void printDecompiled(struct descriptor *dsc) { printf("%s\n", decompiled); MdsFree1Dx(&out_xd, 0); } -static void printDecompiled1(void *ctx, struct descriptor *dsc) { +static void printDecompiled1(void *ctx, struct descriptor *dsc) +{ EMPTYXD(out_xd); static char decompiled[1024]; @@ -128,12 +130,14 @@ static void printDecompiled1(void *ctx, struct descriptor *dsc) { static void FreeDescrip(struct descriptor *desc); -static jintArray getDimensions(JNIEnv *env, void *dsc) { +static jintArray getDimensions(JNIEnv *env, void *dsc) +{ ARRAY_COEFF(char *, 256) *arrD = dsc; jintArray jdims; int dim = (arrD->length > 0) ? arrD->arsize / arrD->length : 0; jdims = (*env)->NewIntArray(env, arrD->dimct); - if (jdims) { + if (jdims) + { if (arrD->dimct == 1) (*env)->SetIntArrayRegion(env, jdims, 0, 1, (const jint *)&dim); else @@ -145,7 +149,8 @@ static jintArray getDimensions(JNIEnv *env, void *dsc) { static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, jobject helpObj, jobject unitsObj, - jobject errorObj, jobject validationObj) { + jobject errorObj, jobject validationObj) +{ jclass cls, data_cls; jmethodID constr; int i, length, count, status; @@ -171,7 +176,8 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, EMPTYXD(ca_xd); int is_ca = 0; - if (!desc) { + if (!desc) + { return NULL; } // printf("DescripToObject dtype = %d class = %d\n", desc->dtype, @@ -181,14 +187,16 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, return DescripToObject(env, ctx, ((struct descriptor_xd *)desc)->pointer, helpObj, unitsObj, errorObj, validationObj); memset(&args, 0, sizeof(args)); - switch (desc->class) { + switch (desc->class) + { case CLASS_S: // printf("CLASS_S\n"); args[1].l = helpObj; args[2].l = unitsObj; args[3].l = errorObj; args[4].l = validationObj; - switch (desc->dtype) { + switch (desc->dtype) + { case DTYPE_BU: cls = (*env)->FindClass(env, "MDSplus/Uint8"); constr = @@ -357,11 +365,11 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, } case CLASS_CA: status = CTXCALLN(TdiData, desc, &ca_xd MDS_END_ARG); - if - STATUS_NOT_OK { - printf("Cannot evaluate CA descriptor\n"); - return NULL; - } + if (STATUS_NOT_OK) + { + printf("Cannot evaluate CA descriptor\n"); + return NULL; + } is_ca = 1; MDS_ATTR_FALLTHROUGH @@ -378,7 +386,8 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, args[1].l = getDimensions(env, array_d); length = (array_d->length != 0) ? array_d->arsize / array_d->length : 0; - switch (array_d->dtype) { + switch (array_d->dtype) + { case DTYPE_MISSING: return NULL; case DTYPE_BU: @@ -578,10 +587,12 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, "Data;LMDSplus/Data;)LMDSplus/Data;"); data_cls = (*env)->FindClass(env, "java/lang/String"); jobjects = (*env)->NewObjectArray(env, length, data_cls, 0); - if (jobjects) { + if (jobjects) + { buf = malloc(array_d->length + 1); buf[array_d->length] = 0; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { memcpy(buf, &array_d->pointer[i * array_d->length], array_d->length); (*env)->SetObjectArrayElement( env, jobjects, i, (jobject)(*env)->NewStringUTF(env, buf)); @@ -609,7 +620,8 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, record_d = (struct descriptor_r *)desc; // printf("CLASS_R %d\n", record_d->dtype); - switch (record_d->dtype) { + switch (record_d->dtype) + { case DTYPE_PARAM: return DescripToObject( env, ctx, record_d->dscptrs[0], @@ -742,8 +754,10 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, obj = (*env)->CallStaticObjectMethodA(env, cls, constr, args); data_cls = (*env)->FindClass(env, "MDSplus/Data"); jobjects = (*env)->NewObjectArray(env, record_d->ndesc, data_cls, 0); - if (jobjects) { - for (i = count = 0; count < record_d->ndesc; i++, count++) { + if (jobjects) + { + for (i = count = 0; count < record_d->ndesc; i++, count++) + { (*env)->SetObjectArrayElement( env, jobjects, i, DescripToObject(env, ctx, record_d->dscptrs[i], 0, 0, 0, 0)); @@ -755,10 +769,12 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, (record_d->dtype == DTYPE_FUNCTION || record_d->dtype == DTYPE_DEPENDENCY || record_d->dtype == DTYPE_CONDITION || record_d->dtype == DTYPE_CALL || - record_d->dtype == DTYPE_DISPATCH)) { + record_d->dtype == DTYPE_DISPATCH)) + { opcode_fid = (*env)->GetFieldID(env, cls, "opcode", "I"); opcode = 0; - switch (record_d->length) { + switch (record_d->length) + { case 1: opcode = *(unsigned char *)record_d->pointer; break; @@ -779,7 +795,8 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, args[4].l = validationObj; array_d = (struct descriptor_a *)desc; length = array_d->arsize / array_d->length; - switch (desc->dtype) { + switch (desc->dtype) + { case DTYPE_LIST: cls = (*env)->FindClass(env, "MDSplus/List"); break; @@ -796,8 +813,10 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, "([LMDSplus/Data;LMDSplus/Data;LMDSplus/Data;LMDSplus/Data;LMDSplus/" "Data;)LMDSplus/Data;"); jobjects = (*env)->NewObjectArray(env, length, data_cls, 0); - if (jobjects) { - for (i = 0; i < length; i++) { + if (jobjects) + { + for (i = 0; i < length; i++) + { if ((curr_obj = DescripToObject( env, ctx, ((struct descriptor **)array_d->pointer)[i], 0, 0, 0, 0))) @@ -819,7 +838,8 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, struct descriptor *helpDscPtr, struct descriptor *unitsDscPtr, struct descriptor *errorDscPtr, - struct descriptor *validationDscPtr) { + struct descriptor *validationDscPtr) +{ DESCRIPTOR_PARAM(templateParam, 0, 0, 0); DESCRIPTOR_WITH_UNITS(templateWithUnits, 0, 0); DESCRIPTOR_WITH_ERROR(templateWithError, 0, 0); @@ -827,7 +847,8 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, struct descriptor_with_units *currWithUnitsDsc; struct descriptor_with_error *currWithErrorDsc; - if (errorDscPtr) { + if (errorDscPtr) + { currWithErrorDsc = (struct descriptor_with_error *)malloc( sizeof(struct descriptor_with_error)); memcpy(currWithErrorDsc, &templateWithError, @@ -837,7 +858,8 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, completeDescr(dataDscPtr, helpDscPtr, unitsDscPtr, 0, validationDscPtr); return (struct descriptor *)currWithErrorDsc; } - if (unitsDscPtr) { + if (unitsDscPtr) + { currWithUnitsDsc = (struct descriptor_with_units *)malloc( sizeof(struct descriptor_with_units)); memcpy(currWithUnitsDsc, &templateWithUnits, @@ -847,7 +869,8 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, completeDescr(dataDscPtr, helpDscPtr, 0, errorDscPtr, validationDscPtr); return (struct descriptor *)currWithUnitsDsc; } - if (helpDscPtr || validationDscPtr) { + if (helpDscPtr || validationDscPtr) + { currParamDsc = (struct descriptor_param *)malloc(sizeof(struct descriptor_param)); memcpy(currParamDsc, &templateParam, sizeof(struct descriptor_param)); @@ -860,7 +883,8 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, return dataDscPtr; } -static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { +static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) +{ jclass cls; jfieldID datum_fid, descs_fid, ndescs_fid, opcode_fid, dtype_fid, dclass_fid, dims_fid; @@ -899,7 +923,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { // printf("ObjectTodescrip %x\n", obj); - if (!obj) { + if (!obj) + { return NULL; } cls = (*env)->GetObjectClass(env, obj); @@ -929,7 +954,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { errorDscPtr = ObjectToDescrip(env, (*env)->GetObjectField(env, obj, getErrorFid)); - switch (dclass) { + switch (dclass) + { case CLASS_S: desc = (struct descriptor *)malloc(sizeof(struct descriptor)); desc->class = dclass; @@ -937,7 +963,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { // printf("DTYPE: %d\n", dtype); - switch (dtype) { + switch (dtype) + { case DTYPE_B: case DTYPE_BU: datum_fid = (*env)->GetFieldID(env, cls, "datum", "B"); @@ -994,10 +1021,12 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { java_string = (*env)->GetObjectField(env, obj, datum_fid); string = (*env)->GetStringUTFChars(env, java_string, 0); desc->length = strlen(string); - if (desc->length > 0) { + if (desc->length > 0) + { desc->pointer = (char *)malloc(desc->length); memcpy(desc->pointer, string, desc->length); - } else + } + else desc->pointer = 0; (*env)->ReleaseStringUTFChars(env, java_string, string); return completeDescr(desc, helpDscPtr, unitsDscPtr, errorDscPtr, @@ -1007,10 +1036,12 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { java_string = (*env)->GetObjectField(env, obj, datum_fid); string = (*env)->GetStringUTFChars(env, java_string, 0); desc->length = strlen(string); - if (desc->length > 0) { + if (desc->length > 0) + { desc->pointer = (char *)malloc(desc->length); memcpy(desc->pointer, string, desc->length); - } else + } + else desc->pointer = 0; (*env)->ReleaseStringUTFChars(env, java_string, string); return completeDescr(desc, helpDscPtr, unitsDscPtr, errorDscPtr, @@ -1020,10 +1051,12 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { java_string = (*env)->GetObjectField(env, obj, datum_fid); string = (*env)->GetStringUTFChars(env, java_string, 0); desc->length = strlen(string); - if (desc->length > 0) { + if (desc->length > 0) + { desc->pointer = (char *)malloc(desc->length); memcpy(desc->pointer, string, desc->length); - } else + } + else desc->pointer = 0; (*env)->ReleaseStringUTFChars(env, java_string, string); return completeDescr(desc, helpDscPtr, unitsDscPtr, errorDscPtr, @@ -1065,7 +1098,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { array_d->m[i] = dims[i]; (*env)->ReleaseIntArrayElements(env, jDims, dims, 0); - switch (dtype) { + switch (dtype) + { case DTYPE_B: case DTYPE_BU: datum_fid = (*env)->GetFieldID(env, cls, "datum", "[B"); @@ -1168,7 +1202,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { strings = malloc(length * sizeof(char *)); jstrings = malloc(length * sizeof(jstring)); maxlen = 0; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { jstrings[i] = (*env)->GetObjectArrayElement(env, jobjects, i); strings[i] = (char *)(*env)->GetStringUTFChars(env, jstrings[i], 0); if (maxlen < (int)strlen(strings[i])) @@ -1176,7 +1211,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { } array_d->pointer = (char *)malloc(length * maxlen); memset(array_d->pointer, ' ', length * maxlen); - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { memcpy(&array_d->pointer[i * maxlen], strings[i], maxlen); (*env)->ReleaseStringUTFChars(env, jstrings[i], strings[i]); } @@ -1209,18 +1245,21 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { record_d->pointer = 0; if (dtype == DTYPE_FUNCTION || dtype == DTYPE_DEPENDENCY || dtype == DTYPE_CONDITION || dtype == DTYPE_CALL || - dtype == DTYPE_DISPATCH) { + dtype == DTYPE_DISPATCH) + { record_d->length = sizeof(short); record_d->pointer = (unsigned char *)malloc(sizeof(short)); *(short *)record_d->pointer = opcode; } - if (dtype == DTYPE_CALL) { + if (dtype == DTYPE_CALL) + { record_d->length = sizeof(char); record_d->pointer = (unsigned char *)malloc(sizeof(char)); *(char *)record_d->pointer = opcode; } record_d->ndesc = ndescs; - for (i = 0; i < ndescs; i++) { + for (i = 0; i < ndescs; i++) + { record_d->dscptrs[i] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jdescs, i)); } @@ -1250,7 +1289,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { return 0; } -static void FreeDescrip(struct descriptor *desc) { +static void FreeDescrip(struct descriptor *desc) +{ struct descriptor_r *record_d; struct descriptor_a *array_d; int i; @@ -1260,7 +1300,8 @@ static void FreeDescrip(struct descriptor *desc) { /*printf("FreeDescrip class %d dtype %d\n", desc->class, desc->dtype);*/ - switch (desc->class) { + switch (desc->class) + { default: break; case CLASS_S: @@ -1292,7 +1333,8 @@ static void FreeDescrip(struct descriptor *desc) { * Signature: ()[B */ JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *env, - jobject obj) { + jobject obj) +{ EMPTYXD(xd); jclass exc; @@ -1302,15 +1344,16 @@ JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *env, struct descriptor *dscPtr = ObjectToDescrip(env, obj); jbyteArray jserialized; status = MdsSerializeDscOut(dscPtr, &xd); - if - STATUS_NOT_OK { - errorMsg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, errorMsg); - return NULL; - } + if (STATUS_NOT_OK) + { + errorMsg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, errorMsg); + return NULL; + } arrPtr = (struct descriptor_a *)xd.pointer; - if (arrPtr->dtype != DTYPE_B && arrPtr->dtype != DTYPE_BU) { + if (arrPtr->dtype != DTYPE_B && arrPtr->dtype != DTYPE_BU) + { printf("FATAL ERROR: MdsSerializeDscOut returned a wrong type"); exit(0); } @@ -1329,7 +1372,8 @@ JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *env, * Signature: ([B)LMDSplus/Data; */ JNIEXPORT jobject JNICALL Java_MDSplus_Data_deserialize( - JNIEnv *env, jclass cls __attribute__((unused)), jbyteArray jserialized) { + JNIEnv *env, jclass cls __attribute__((unused)), jbyteArray jserialized) +{ EMPTYXD(xd); jclass exc; char *errorMsg; @@ -1337,13 +1381,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_deserialize( char *serialized = (char *)(*env)->GetByteArrayElements(env, jserialized, JNI_FALSE); int status = MdsSerializeDscIn(serialized, &xd); - if - STATUS_NOT_OK { - errorMsg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, errorMsg); - return NULL; - } + if (STATUS_NOT_OK) + { + errorMsg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, errorMsg); + return NULL; + } retObj = DescripToObject(env, NULL, xd.pointer, 0, 0, 0, 0); MdsFree1Dx(&xd, 0); @@ -1360,7 +1404,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *env, jclass cls __attribute__((unused)), jstring jexpr, - jobjectArray jargs) { + jobjectArray jargs) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status, i, varIdx; @@ -1391,13 +1436,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *env, (*env)->ReleaseStringUTFChars(env, jexpr, expr); for (i = 0; i < numArgs; i++) FreeDescrip(arglist[2 + i]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, NULL, outXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&outXd, NULL); return ris; @@ -1409,7 +1454,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *env, * Signature: ()LMDSplus/String; */ JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *env, jobject jobj, - jlong jctx) { + jlong jctx) +{ EMPTYXD(outXd); jstring ris; jclass exc; @@ -1429,13 +1475,13 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *env, jobject jobj, // status = CTXCALLR(TdiDecompile, dataD, &outXd MDS_END_ARG); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } FreeDescrip(dataD); decD = outXd.pointer; buf = (char *)malloc(decD->length + 1); @@ -1453,7 +1499,8 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *env, jobject jobj, * Signature: ()LMDSplus/Data; */ JNIEXPORT jobject JNICALL Java_MDSplus_Data_cloneData(JNIEnv *env, - jobject jobj) { + jobject jobj) +{ struct descriptor *descr; jobject retObj; @@ -1472,7 +1519,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *env, jclass cls __attribute__((unused)), jstring jexpr, - jobjectArray jargs) { + jobjectArray jargs) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status, i, varIdx; @@ -1500,21 +1548,21 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *env, (*env)->ReleaseStringUTFChars(env, jexpr, expr); for (i = 0; i < numArgs; i++) FreeDescrip(arglist[2 + i]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } status = TdiData((struct descriptor *)&outXd, &outXd MDS_END_ARG); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, NULL, outXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&outXd, NULL); return ris; @@ -1526,7 +1574,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *env, * Signature: ()LMDSplus/Data; */ JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *env, jobject jobj, - jlong jctx) { + jlong jctx) +{ void *ctx = JLONG2PTR(jctx); EMPTYXD(xd); char *error_msg; @@ -1537,13 +1586,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *env, jobject jobj, struct descriptor *descr; descr = ObjectToDescrip(env, jobj); status = CTXCALLR(TdiData, descr, &xd MDS_END_ARG); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } retObj = DescripToObject(env, ctx, xd.pointer, 0, 0, 0, 0); MdsFree1Dx(&xd, 0); FreeDescrip(descr); @@ -1557,7 +1606,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *env, jobject jobj, */ JNIEXPORT jstring JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *env, jobject jobj, - jlong jctx) { + jlong jctx) +{ void *ctx = JLONG2PTR(jctx); EMPTYXD(xd); char *error_msg; @@ -1565,13 +1615,13 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *env, jclass exc; struct descriptor *descr = ObjectToDescrip(env, jobj); int status = CTXCALLR(TdiEvaluate, descr, &xd MDS_END_ARG); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } FreeDescrip(descr); retObj = DescripToObject(env, ctx, descr, 0, 0, 0, 0); MdsFree1Dx(&xd, 0); @@ -1580,14 +1630,16 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *env, //////////////////////////////Class Tree Stuff/////////////////////////// -static void throwMdsExceptionStr(JNIEnv *env, char *errorMsg) { +static void throwMdsExceptionStr(JNIEnv *env, char *errorMsg) +{ jclass exc; exc = (*env)->FindClass(env, "MDSplus/MdsException"); (*env)->ThrowNew(env, exc, errorMsg); } -static void throwMdsException(JNIEnv *env, int status) { +static void throwMdsException(JNIEnv *env, int status) +{ jclass exc; exc = (*env)->FindClass(env, "MDSplus/MdsException"); @@ -1602,20 +1654,22 @@ static void throwMdsException(JNIEnv *env, int status) { JNIEXPORT void JNICALL Java_MDSplus_Tree_openTree(JNIEnv *env, jobject jobj, jlong jctx, jstring jname, jint shot, - jboolean readonly) { + jboolean readonly) +{ int status; const char *name; void *ctx = JLONG2PTR(jctx); name = (*env)->GetStringUTFChars(env, jname, 0); - if (strlen(name) > 0) { + if (strlen(name) > 0) + { status = _TreeOpen(&ctx, (char *)name, shot, readonly ? 1 : 0); set_ctx_field(env, jobj, ctx); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK { - throwMdsException(env, status); - return; - } + if (STATUS_NOT_OK) + { + throwMdsException(env, status); + return; + } } } @@ -1626,7 +1680,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_openTree(JNIEnv *env, jobject jobj, */ JNIEXPORT void JNICALL Java_MDSplus_Tree_closeTree(JNIEnv *env, jobject jobj, jlong jctx, jstring jname, - jint shot) { + jint shot) +{ int status; const char *name; void *ctx = JLONG2PTR(jctx); @@ -1634,12 +1689,13 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_closeTree(JNIEnv *env, jobject jobj, name = (*env)->GetStringUTFChars(env, jname, 0); status = CTXCALLR(TreeClose, name, shot); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK { - set_ctx_field(env, jobj, ctx); - throwMdsException(env, status); - } - else { + if (STATUS_NOT_OK) + { + set_ctx_field(env, jobj, ctx); + throwMdsException(env, status); + } + else + { TreeFreeDbid(ctx); set_ctx_field(env, jobj, NULL); } @@ -1652,7 +1708,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_closeTree(JNIEnv *env, jobject jobj, */ JNIEXPORT void JNICALL Java_MDSplus_Tree_editTree(JNIEnv *env, jobject jobj, jlong jctx, jstring jname, - jint shot, jboolean isNew) { + jint shot, jboolean isNew) +{ int status; const char *name; void *ctx = JLONG2PTR(jctx); @@ -1663,11 +1720,11 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_editTree(JNIEnv *env, jobject jobj, status = _TreeOpenEdit(&ctx, name, shot); set_ctx_field(env, jobj, ctx); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK { - throwMdsException(env, status); - return; - } + if (STATUS_NOT_OK) + { + throwMdsException(env, status); + return; + } } /* @@ -1677,7 +1734,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_editTree(JNIEnv *env, jobject jobj, */ JNIEXPORT void JNICALL Java_MDSplus_Tree_writeTree(JNIEnv *env, jobject jobj, jlong jctx, jstring jname, - jint shot) { + jint shot) +{ const char *name; void *ctx = JLONG2PTR(jctx); @@ -1686,9 +1744,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_writeTree(JNIEnv *env, jobject jobj, status = CTXCALLR(TreeWriteTree, name, shot); set_ctx_field(env, jobj, ctx); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1698,19 +1755,21 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_writeTree(JNIEnv *env, jobject jobj, */ JNIEXPORT void JNICALL Java_MDSplus_Tree_quitTree(JNIEnv *env, jobject jobj, jlong jctx, jstring jname, - jint shot) { + jint shot) +{ const char *name; void *ctx = JLONG2PTR(jctx); int status; name = (*env)->GetStringUTFChars(env, jname, 0); status = CTXCALLR(TreeQuitTree, name, shot); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK { - set_ctx_field(env, jobj, ctx); - throwMdsException(env, status); - } - else { + if (STATUS_NOT_OK) + { + set_ctx_field(env, jobj, ctx); + throwMdsException(env, status); + } + else + { TreeFreeDbid(ctx); set_ctx_field(env, jobj, NULL); } @@ -1724,7 +1783,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_quitTree(JNIEnv *env, jobject jobj, JNIEXPORT jint JNICALL Java_MDSplus_Tree_findNode(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jstring jpath) { + jlong jctx, jstring jpath) +{ int status, nid; const char *path; void *ctx = JLONG2PTR(jctx); @@ -1732,9 +1792,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_findNode(JNIEnv *env, path = (*env)->GetStringUTFChars(env, jpath, 0); status = CTXCALLN(TreeFindNode, path, &nid); (*env)->ReleaseStringUTFChars(env, jpath, path); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return nid; } @@ -1747,7 +1806,8 @@ JNIEXPORT jintArray JNICALL Java_MDSplus_Tree_getWild(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jpath, - jint usage) { + jint usage) +{ int currNid, status, i; int numNids = 0; const char *path; @@ -1764,7 +1824,8 @@ JNIEXPORT jintArray JNICALL Java_MDSplus_Tree_getWild(JNIEnv *env, CTXCALLN(TreeFindNodeEnd, &wildCtx); nids = malloc(numNids * sizeof(int)); wildCtx = 0; - for (i = 0; i < numNids; i++) { + for (i = 0; i < numNids; i++) + { CTXCALLN(TreeFindNodeWild, (char *)path, &nids[i], &wildCtx, usage); //_TreeFindNodeWild, (char *)path, &nids[i], &wildCtx, (1 << usage)); } @@ -1786,13 +1847,13 @@ JNIEXPORT jintArray JNICALL Java_MDSplus_Tree_getWild(JNIEnv *env, JNIEXPORT jint JNICALL Java_MDSplus_Tree_getDefaultNid(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx) { + jlong jctx) +{ void *ctx = JLONG2PTR(jctx); int nid; int status = CTXCALLN(TreeGetDefaultNid, &nid); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return nid; } @@ -1804,12 +1865,12 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_getDefaultNid(JNIEnv *env, JNIEXPORT void JNICALL Java_MDSplus_Tree_setDefaultNid(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jint nid) { + jlong jctx, jint nid) +{ void *ctx = JLONG2PTR(jctx); int status = CTXCALLN(TreeSetDefaultNid, nid); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1820,7 +1881,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setDefaultNid(JNIEnv *env, JNIEXPORT jboolean JNICALL Java_MDSplus_Tree_getDbiFlag(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jint code) { + jlong jctx, jint code) +{ int flag = 0, len = sizeof(jboolean), status; void *ctx = JLONG2PTR(jctx); struct dbi_itm dbiList[] = {{sizeof(int), 0, &flag, &len}, @@ -1828,9 +1890,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_Tree_getDbiFlag(JNIEnv *env, dbiList[0].code = (short)code; status = CTXCALLN(TreeGetDbi, dbiList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return flag; } @@ -1843,7 +1904,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setDbiFlag(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jboolean jflag, - jint code) { + jint code) +{ int len = sizeof(jboolean), status, flag; void *ctx = JLONG2PTR(jctx); struct dbi_itm dbiList[] = {{sizeof(int), 0, &flag, &len}, @@ -1853,9 +1915,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setDbiFlag(JNIEnv *env, dbiList[0].code = (short)code; dbiList[0].pointer = &flag; status = CTXCALLN(TreeSetDbi, dbiList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1864,21 +1925,20 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setDbiFlag(JNIEnv *env, * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeViewDate( - JNIEnv *env, jclass cls __attribute__((unused)), jstring jdate) { + JNIEnv *env, jclass cls __attribute__((unused)), jstring jdate) +{ int64_t qtime; const char *date; int status; date = (*env)->GetStringUTFChars(env, jdate, 0); qtime = 0; status = LibConvertDateString(date, &qtime); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); status = TreeSetViewDate(&qtime); (*env)->ReleaseStringUTFChars(env, jdate, date); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1888,7 +1948,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeViewDate( */ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext( JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jobject jstart, - jobject jend, jobject jdelta) { + jobject jend, jobject jdelta) +{ struct descriptor *start, *end, *delta; int status; void *ctx = JLONG2PTR(jctx); @@ -1899,9 +1960,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext( FreeDescrip(start); FreeDescrip(end); FreeDescrip(delta); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1912,16 +1972,16 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext( JNIEXPORT void JNICALL Java_MDSplus_Tree_setCurrent(JNIEnv *env, jclass cls __attribute__((unused)), - jstring jname, jint shot) { + jstring jname, jint shot) +{ int status; const char *name; name = (*env)->GetStringUTFChars(env, jname, 0); status = TreeSetCurrentShotId((char *)name, shot); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1932,7 +1992,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setCurrent(JNIEnv *env, JNIEXPORT jint JNICALL Java_MDSplus_Tree_getCurrent(JNIEnv *env, jclass cls __attribute__((unused)), - jstring jname) { + jstring jname) +{ int current = 0; const char *name; @@ -1948,13 +2009,13 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_getCurrent(JNIEnv *env, * Signature: (JI)V */ JNIEXPORT void JNICALL Java_MDSplus_Tree_createPulseFile( - JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jint shot) { + JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jint shot) +{ int status; void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeCreatePulseFile, shot, 0, NULL); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1963,13 +2024,13 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_createPulseFile( * Signature: (JI)V */ JNIEXPORT void JNICALL Java_MDSplus_Tree_deletePulseFile( - JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jint shot) { + JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jint shot) +{ int status; void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeDeletePulseFile, shot, 1); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -1981,7 +2042,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_deletePulseFile( JNIEXPORT jobjectArray JNICALL Java_MDSplus_Tree_findTreeTags(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jstring jwild) { + jlong jctx, jstring jwild) +{ const char *wild; char *tagNames[MAX_TAGS]; void *wildCtx = 0; @@ -2004,8 +2066,10 @@ Java_MDSplus_Tree_findTreeTags(JNIEnv *env, jclass cls __attribute__((unused)), stringCls = (*env)->FindClass(env, "java/lang/String"); jtags = (*env)->NewObjectArray(env, nTags, stringCls, 0); - if (jtags) { - for (i = 0; i < nTags; i++) { + if (jtags) + { + for (i = 0; i < nTags; i++) + { (*env)->SetObjectArrayElement( env, jtags, i, (jobject)(*env)->NewStringUTF(env, tagNames[i])); } @@ -2022,7 +2086,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_addTreeNode(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jpath, - jint usage) { + jint usage) +{ const char *path; void *ctx = JLONG2PTR(jctx); int nidOut; @@ -2031,9 +2096,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_addTreeNode(JNIEnv *env, path = (*env)->GetStringUTFChars(env, jpath, 0); status = CTXCALLN(TreeAddNode, path, &nidOut, (char)usage); (*env)->ReleaseStringUTFChars(env, jpath, path); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return nidOut; } @@ -2044,7 +2108,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_Tree_addTreeNode(JNIEnv *env, */ JNIEXPORT void JNICALL Java_MDSplus_Tree_addTreeDevice(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jstring jname, jstring jtype) { + jlong jctx, jstring jname, jstring jtype) +{ const char *name, *type; void *ctx = JLONG2PTR(jctx); int nidOut; @@ -2055,9 +2120,8 @@ Java_MDSplus_Tree_addTreeDevice(JNIEnv *env, jclass cls __attribute__((unused)), status = CTXCALLN(TreeAddConglom, (char *)name, (char *)type, &nidOut); (*env)->ReleaseStringUTFChars(env, jname, name); (*env)->ReleaseStringUTFChars(env, jtype, type); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2069,7 +2133,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_deleteTreeNode(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, - jstring jpath) { + jstring jpath) +{ const char *path; int status, nid, count; void *ctx = JLONG2PTR(jctx); @@ -2077,17 +2142,14 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_deleteTreeNode(JNIEnv *env, path = (*env)->GetStringUTFChars(env, jpath, 0); status = CTXCALLN(TreeFindNode, (char *)path, &nid); (*env)->ReleaseStringUTFChars(env, jpath, path); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); status = CTXCALLN(TreeDeleteNodeInitialize, nid, &count, 1); - if - STATUS_OK - CTXCALL0(TreeDeleteNodeExecute); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_OK) + CTXCALL0(TreeDeleteNodeExecute); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2096,7 +2158,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_deleteTreeNode(JNIEnv *env, * Signature: (JLjava/lang/String;)V */ JNIEXPORT void JNICALL Java_MDSplus_Tree_removeTreeTag( - JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jtag) { + JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jtag) +{ const char *tag; int status; void *ctx = JLONG2PTR(jctx); @@ -2104,9 +2167,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_removeTreeTag( tag = (*env)->GetStringUTFChars(env, jtag, 0); status = CTXCALLN(TreeRemoveTag, (char *)tag); (*env)->ReleaseStringUTFChars(env, jtag, tag); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2116,7 +2178,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_removeTreeTag( */ JNIEXPORT jlong JNICALL Java_MDSplus_Tree_getDatafileSize( JNIEnv *env __attribute__((unused)), jclass cls __attribute__((unused)), - jlong jctx) { + jlong jctx) +{ // int status; int64_t size; void *ctx = JLONG2PTR(jctx); @@ -2134,7 +2197,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_compile(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jexpr, - jobjectArray jargs) { + jobjectArray jargs) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status, i, varIdx; @@ -2166,13 +2230,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_compile(JNIEnv *env, (*env)->ReleaseStringUTFChars(env, jexpr, expr); for (i = 0; i < numArgs; i++) FreeDescrip(arglist[3 + i]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, ctx, outXd.pointer, 0, 0, 0, 0); // printDecompiled1,ctx, outXd.pointer); MdsFree1Dx(&outXd, NULL); @@ -2188,7 +2252,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jstring jexpr, - jobjectArray jargs) { + jobjectArray jargs) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status, i, varIdx; @@ -2221,13 +2286,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *env, (*env)->ReleaseStringUTFChars(env, jexpr, expr); for (i = 0; i < numArgs; i++) FreeDescrip(arglist[3 + i]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, ctx, outXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&outXd, NULL); return ris; @@ -2241,7 +2306,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *env, JNIEXPORT jobject JNICALL Java_MDSplus_Tree_data(JNIEnv *env, jclass cls __attribute__((unused)), - jlong jctx, jobject jdata) { + jlong jctx, jobject jdata) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status; @@ -2258,13 +2324,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_data(JNIEnv *env, *(int *)&arglist[0] = 4; status = (int)(intptr_t)LibCallg(arglist, _TdiData); FreeDescrip(arglist[2]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, ctx, outXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&outXd, NULL); return ris; @@ -2279,7 +2345,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_evaluate(JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, - jobject jdata) { + jobject jdata) +{ EMPTYXD(outXd); void *arglist[MAX_ARGS]; int status; @@ -2296,13 +2363,13 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_evaluate(JNIEnv *env, *(int *)&arglist[0] = 4; status = (int)(intptr_t)LibCallg(arglist, _TdiEvaluate); FreeDescrip(arglist[2]); - if - STATUS_NOT_OK { - error_msg = (char *)MdsGetMsg(status); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, error_msg); - return NULL; - } + if (STATUS_NOT_OK) + { + error_msg = (char *)MdsGetMsg(status); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, error_msg); + return NULL; + } ris = DescripToObject(env, ctx, outXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&outXd, NULL); return ris; @@ -2319,7 +2386,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNci(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint nciType) { + jint nciType) +{ int status; int retNci = 0, retNciLen = sizeof(int); @@ -2328,9 +2396,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNci(JNIEnv *env, void *ctx = JLONG2PTR(jctx); nciList[0].code = (short)nciType; status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return retNci; } @@ -2341,7 +2408,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNci(JNIEnv *env, */ JNIEXPORT jlong JNICALL Java_MDSplus_TreeNode_getNciLong( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint nciType) { + jint nciType) +{ int status; int64_t retNci = 0; int retNciLen = sizeof(int); @@ -2352,9 +2420,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_TreeNode_getNciLong( nciList[0].code = (short)nciType; status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return retNci; } @@ -2365,7 +2432,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_TreeNode_getNciLong( */ JNIEXPORT jstring JNICALL Java_MDSplus_TreeNode_getNciString( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint nciType) { + jint nciType) +{ int status; char path[1024]; int pathLen = 0; @@ -2375,9 +2443,8 @@ JNIEXPORT jstring JNICALL Java_MDSplus_TreeNode_getNciString( nciList[0].code = (short)nciType; status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); path[pathLen] = 0; return (*env)->NewStringUTF(env, path); } @@ -2389,7 +2456,8 @@ JNIEXPORT jstring JNICALL Java_MDSplus_TreeNode_getNciString( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlag( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint flagOfs, jboolean flag) { + jint flagOfs, jboolean flag) +{ int status; int nciFlags; int nciFlagsLen = sizeof(int); @@ -2400,9 +2468,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlag( nciFlags = flagOfs; status = CTXCALLN(TreeSetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2412,7 +2479,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlag( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlags( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint flags) { + jint flags) +{ int status; int nciFlags; int nciFlagsLen = sizeof(int); @@ -2422,9 +2490,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlags( nciFlags = flags; status = CTXCALLN(TreeSetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2434,7 +2501,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setNciFlags( */ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_getNciFlag( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint flagOfs) { + jint flagOfs) +{ int status; int nciFlags; int nciFlagsLen = sizeof(int); @@ -2444,9 +2512,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_getNciFlag( void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return (nciFlags & flagOfs) ? 1 : 0; } @@ -2457,7 +2524,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_getNciFlag( * Signature: (IJ)I */ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNciFlags( - JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) { + JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) +{ int status; int nciFlags; int nciFlagsLen = sizeof(int); @@ -2466,9 +2534,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNciFlags( {NciEND_OF_LIST, 0, 0, 0}}; void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return nciFlags; } @@ -2480,7 +2547,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNciFlags( */ JNIEXPORT jintArray JNICALL Java_MDSplus_TreeNode_getNciNids( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint nciNumCode, jint nciCode) { + jint nciNumCode, jint nciCode) +{ int status; int nNids, nNidsLen = sizeof(int); int retLen = 0; @@ -2493,17 +2561,15 @@ JNIEXPORT jintArray JNICALL Java_MDSplus_TreeNode_getNciNids( void *ctx = JLONG2PTR(jctx); nciList[0].code = (short)nciNumCode; status = CTXCALLN(TreeGetNci, nid, nciList); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); nids = malloc(nNids * sizeof(int)); nciList1[0].code = (short)nciCode; nciList1[0].buffer_length = sizeof(int) * nNids; nciList1[0].pointer = nids; status = CTXCALLN(TreeGetNci, nid, nciList1); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); jnids = (*env)->NewIntArray(env, nNids); if (jnids) (*env)->SetIntArrayRegion(env, jnids, 0, nNids, (const jint *)nids); @@ -2520,7 +2586,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_turnOn(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jboolean on) { + jboolean on) +{ int status; void *ctx = JLONG2PTR(jctx); @@ -2528,9 +2595,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_turnOn(JNIEnv *env, status = CTXCALLN(TreeTurnOn, nid); else status = CTXCALLN(TreeTurnOff, nid); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2542,7 +2608,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isOn(JNIEnv *env __attribute__((unused)), jclass cls __attribute__((unused)), - jint nid, jlong jctx) { + jint nid, jlong jctx) +{ void *ctx = JLONG2PTR(jctx); return CTXCALLN(TreeIsOn, nid) == TreeON; } @@ -2554,7 +2621,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isOn(JNIEnv *env */ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isParentOff( JNIEnv *env __attribute__((unused)), jclass cls __attribute__((unused)), - jint nid, jlong jctx) { + jint nid, jlong jctx) +{ void *ctx = JLONG2PTR(jctx); return CTXCALLN(TreeIsOn, nid) == TreePARENT_OFF; } @@ -2567,7 +2635,8 @@ JNIEXPORT jboolean JNICALL Java_MDSplus_TreeNode_isParentOff( JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getData(JNIEnv *env, jclass cls __attribute__((unused)), - jint nid, jlong jctx) { + jint nid, jlong jctx) +{ int status; EMPTYXD(xd); jobject retObj; @@ -2575,9 +2644,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getData(JNIEnv *env, void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeGetRecord, nid, &xd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, xd.pointer, NULL, NULL, NULL, NULL); MdsFree1Dx(&xd, 0); @@ -2593,16 +2661,16 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putData(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata) { + jobject jdata) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); dataD = ObjectToDescrip(env, jdata); status = CTXCALLN(TreePutRecord, nid, dataD, 0); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); FreeDescrip(dataD); } /* @@ -2612,7 +2680,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putData(JNIEnv *env, */ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getExtendedAttribute( JNIEnv *env, jclass class __attribute__((unused)), jint nid, jlong jctx, - jstring jname) { + jstring jname) +{ int status; EMPTYXD(xd); jobject retObj; @@ -2620,9 +2689,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getExtendedAttribute( void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeGetXNci, nid, name, &xd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, xd.pointer, NULL, NULL, NULL, NULL); MdsFree1Dx(&xd, 0); @@ -2637,7 +2705,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getExtendedAttribute( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( JNIEnv *env, jclass class __attribute__((unused)), jint nid, jlong jctx, - jstring jname, jobject jdata) { + jstring jname, jobject jdata) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2645,9 +2714,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( dataD = ObjectToDescrip(env, jdata); status = CTXCALLN(TreeSetXNci, nid, name, dataD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); FreeDescrip(dataD); (*env)->ReleaseStringUTFChars(env, jname, name); } @@ -2659,14 +2727,14 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteData(JNIEnv *env, jclass cls __attribute__((unused)), - jint nid, jlong jctx) { + jint nid, jlong jctx) +{ EMPTYXD(emptyXd); int status; void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreePutRecord, nid, (struct descriptor *)&emptyXd, 0); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2678,7 +2746,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jstring jmethod) { + jstring jmethod) +{ const char *method; int status; void *ctx = JLONG2PTR(jctx); @@ -2694,9 +2763,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *env, status = CTXCALLN(TreeDoMethod, &nidD, &methodD, &xd MDS_END_ARG); MdsFree1Dx(&xd, 0); (*env)->ReleaseStringUTFChars(env, jmethod, method); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2706,7 +2774,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *env, */ #define MAX_TAGS 1024 JNIEXPORT jobjectArray JNICALL Java_MDSplus_TreeNode_getTags( - JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) { + JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) +{ void *wildCtx = 0; int nTags = 0; int i; @@ -2721,8 +2790,10 @@ JNIEXPORT jobjectArray JNICALL Java_MDSplus_TreeNode_getTags( stringCls = (*env)->FindClass(env, "java/lang/String"); jtags = (*env)->NewObjectArray(env, nTags, stringCls, 0); - if (jtags) { - for (i = 0; i < nTags; i++) { + if (jtags) + { + for (i = 0; i < nTags; i++) + { (*env)->SetObjectArrayElement( env, jtags, i, (jobject)(*env)->NewStringUTF(env, tagNames[i])); TreeFree(tagNames[i]); @@ -2739,7 +2810,8 @@ JNIEXPORT jobjectArray JNICALL Java_MDSplus_TreeNode_getTags( JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jobject jstart, jobject jend, jobject jdim, jobject jdata, - jint filledRows __attribute__((unused))) { + jint filledRows __attribute__((unused))) +{ struct descriptor *startD, *endD, *dimD, *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2756,9 +2828,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment( FreeDescrip(endD); FreeDescrip(dimD); FreeDescrip(dataD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2768,7 +2839,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jstart, jobject jend, jobject jdim, jobject jdata) { + jobject jstart, jobject jend, jobject jdim, jobject jdata) +{ struct descriptor *startD, *endD, *dimD, *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2785,9 +2857,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment( FreeDescrip(endD); FreeDescrip(dimD); FreeDescrip(dataD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2797,7 +2868,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata, jint offset) { + jobject jdata, jint offset) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2805,9 +2877,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment( dataD = ObjectToDescrip(env, jdata); status = CTXCALLN(TreePutSegment, nid, offset, (struct descriptor_a *)dataD); FreeDescrip(dataD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2817,7 +2888,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint segmentOffset, jobject jstart, jobject jend, jobject jdim) { + jint segmentOffset, jobject jstart, jobject jend, jobject jdim) +{ struct descriptor *startD, *endD, *dimD; int status; void *ctx = JLONG2PTR(jctx); @@ -2830,9 +2902,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment( FreeDescrip(startD); FreeDescrip(endD); FreeDescrip(dimD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2842,7 +2913,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata) { + jobject jdata) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2853,9 +2925,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( status = CTXCALLN(TreeBeginTimestampedSegment, nid, (struct descriptor_a *)dataD, -1); FreeDescrip(dataD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2865,7 +2936,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata, jlongArray jtimes) { + jobject jdata, jlongArray jtimes) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2882,9 +2954,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( (struct descriptor_a *)dataD, -1, numTimes); FreeDescrip(dataD); (*env)->ReleaseLongArrayElements(env, jtimes, times, JNI_ABORT); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2894,7 +2965,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata, jlongArray jtimes) { + jobject jdata, jlongArray jtimes) +{ struct descriptor *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2912,9 +2984,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( FreeDescrip(dataD); (*env)->ReleaseLongArrayElements(env, jtimes, times, JNI_ABORT); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } #define PUTROW_BUFSIZE 1024 @@ -2926,7 +2997,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jrow, jlong jtime, jint size) { + jobject jrow, jlong jtime, jint size) +{ struct descriptor *rowD; int status; void *ctx = JLONG2PTR(jctx); @@ -2936,9 +3008,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow( (struct descriptor_a *)rowD); FreeDescrip(rowD); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -2947,14 +3018,14 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow( * Signature: (IJZI)I */ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNumSegments( - JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) { + JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx) +{ int status, numSegments; void *ctx = JLONG2PTR(jctx); status = CTXCALLN(TreeGetNumSegments, nid, &numSegments); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return numSegments; } @@ -2965,7 +3036,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_getNumSegments( */ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentStart( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint idx) { + jint idx) +{ int status; void *ctx = JLONG2PTR(jctx); EMPTYXD(startXd); @@ -2973,9 +3045,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentStart( jobject retObj; status = CTXCALLN(TreeGetSegmentLimits, nid, idx, &startXd, &endXd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, startXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&startXd, 0); @@ -2990,7 +3061,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentStart( */ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentEnd( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint idx) { + jint idx) +{ int status; void *ctx = JLONG2PTR(jctx); EMPTYXD(startXd); @@ -2998,9 +3070,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentEnd( jobject retObj; status = CTXCALLN(TreeGetSegmentLimits, nid, idx, &startXd, &endXd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, endXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&startXd, 0); @@ -3015,7 +3086,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentEnd( */ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentDim( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint idx) { + jint idx) +{ int status; void *ctx = JLONG2PTR(jctx); EMPTYXD(dataXd); @@ -3023,9 +3095,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentDim( jobject retObj; status = CTXCALLN(TreeGetSegment, nid, idx, &dataXd, &timeXd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, timeXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&dataXd, 0); @@ -3040,7 +3111,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegmentDim( */ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint idx) { + jint idx) +{ int status; void *ctx = JLONG2PTR(jctx); EMPTYXD(dataXd); @@ -3048,9 +3120,8 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegment( jobject retObj; status = CTXCALLN(TreeGetSegment, nid, idx, &dataXd, &timeXd); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); retObj = DescripToObject(env, ctx, dataXd.pointer, 0, 0, 0, 0); MdsFree1Dx(&dataXd, 0); @@ -3065,26 +3136,23 @@ JNIEXPORT jobject JNICALL Java_MDSplus_TreeNode_getSegment( */ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addNode(JNIEnv *env, jclass cls __attribute__((unused)), - jint nid, jlong jctx, jstring jname, jint usage) { + jint nid, jlong jctx, jstring jname, jint usage) +{ int status, defNid, newNid = -1; void *ctx = JLONG2PTR(jctx); const char *name; name = (*env)->GetStringUTFChars(env, jname, 0); status = CTXCALLN(TreeGetDefaultNid, &defNid); - if - STATUS_OK - status = CTXCALLN(TreeSetDefaultNid, nid); - if - STATUS_OK - status = CTXCALLN(TreeAddNode, (char *)name, &newNid, (char)usage); - if - STATUS_OK - status = CTXCALLN(TreeSetDefaultNid, defNid); + if (STATUS_OK) + status = CTXCALLN(TreeSetDefaultNid, nid); + if (STATUS_OK) + status = CTXCALLN(TreeAddNode, (char *)name, &newNid, (char)usage); + if (STATUS_OK) + status = CTXCALLN(TreeSetDefaultNid, defNid); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return newNid; } @@ -3095,29 +3163,25 @@ Java_MDSplus_TreeNode_addNode(JNIEnv *env, jclass cls __attribute__((unused)), */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteNode( JNIEnv *env, jclass cls __attribute__((unused)), - jint nid __attribute__((unused)), jlong jctx, jstring jpath) { + jint nid __attribute__((unused)), jlong jctx, jstring jpath) +{ int status, defNid, delNid, count; const char *path; void *ctx = JLONG2PTR(jctx); path = (*env)->GetStringUTFChars(env, jpath, 0); status = CTXCALLN(TreeGetDefaultNid, &defNid); - if - STATUS_OK - status = CTXCALLN(TreeFindNode, (char *)path, &delNid); - if - STATUS_OK - status = CTXCALLN(TreeDeleteNodeInitialize, delNid, &count, 1); - if - STATUS_OK - CTXCALL0(TreeDeleteNodeExecute); - if - STATUS_OK - status = CTXCALLN(TreeSetDefaultNid, defNid); + if (STATUS_OK) + status = CTXCALLN(TreeFindNode, (char *)path, &delNid); + if (STATUS_OK) + status = CTXCALLN(TreeDeleteNodeInitialize, delNid, &count, 1); + if (STATUS_OK) + CTXCALL0(TreeDeleteNodeExecute); + if (STATUS_OK) + status = CTXCALLN(TreeSetDefaultNid, defNid); (*env)->ReleaseStringUTFChars(env, jpath, path); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -3129,7 +3193,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_renameNode(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jstring jname) { + jstring jname) +{ int status; void *ctx = JLONG2PTR(jctx); const char *name; @@ -3137,9 +3202,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_renameNode(JNIEnv *env, name = (*env)->GetStringUTFChars(env, jname, 0); status = CTXCALLN(TreeRenameNode, nid, (char *)name); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -3151,7 +3215,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_addTag(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jstring jtag) { + jstring jtag) +{ int status; void *ctx = JLONG2PTR(jctx); const char *tag; @@ -3159,9 +3224,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_addTag(JNIEnv *env, tag = (*env)->GetStringUTFChars(env, jtag, 0); status = CTXCALLN(TreeAddTag, nid, (char *)tag); (*env)->ReleaseStringUTFChars(env, jtag, tag); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -3173,7 +3237,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_removeTag(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jstring jtag) { + jstring jtag) +{ int status, currNid; void *ctx = JLONG2PTR(jctx); const char *tag; @@ -3185,20 +3250,20 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_removeTag(JNIEnv *env, status = CTXCALLN(TreeFindNode, bTag, &currNid); free(bTag); - if - STATUS_NOT_OK { - (*env)->ReleaseStringUTFChars(env, jtag, tag); - throwMdsException(env, status); - } - if (currNid != nid) { + if (STATUS_NOT_OK) + { + (*env)->ReleaseStringUTFChars(env, jtag, tag); + throwMdsException(env, status); + } + if (currNid != nid) + { (*env)->ReleaseStringUTFChars(env, jtag, tag); throwMdsExceptionStr(env, "No such tag for this tree node"); } status = CTXCALLN(TreeRemoveTag, (char *)tag); (*env)->ReleaseStringUTFChars(env, jtag, tag); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -3208,7 +3273,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_removeTag(JNIEnv *env, */ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addDevice( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jstring jname, jstring jtype) { + jstring jname, jstring jtype) +{ const char *name; const char *type; int status, newNid = -1, defNid = -1; @@ -3217,18 +3283,15 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_addDevice( name = (*env)->GetStringUTFChars(env, jname, 0); type = (*env)->GetStringUTFChars(env, jtype, 0); status = CTXCALLN(TreeGetDefaultNid, &defNid); - if - STATUS_OK - status = CTXCALLN(TreeSetDefaultNid, nid); - if - STATUS_OK - status = CTXCALLN(TreeAddConglom, (char *)name, (char *)type, &newNid); + if (STATUS_OK) + status = CTXCALLN(TreeSetDefaultNid, nid); + if (STATUS_OK) + status = CTXCALLN(TreeAddConglom, (char *)name, (char *)type, &newNid); CTXCALLN(TreeSetDefaultNid, defNid); (*env)->ReleaseStringUTFChars(env, jname, name); (*env)->ReleaseStringUTFChars(env, jtype, type); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); return newNid; } @@ -3241,7 +3304,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setSubtree(JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jboolean isSubtree) { + jboolean isSubtree) +{ int status; void *ctx = JLONG2PTR(jctx); @@ -3249,9 +3313,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setSubtree(JNIEnv *env, status = CTXCALLN(TreeSetSubtree, nid); else status = CTXCALLN(TreeSetNoSubtree, nid); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* @@ -3261,24 +3324,22 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setSubtree(JNIEnv *env, */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_moveNode( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jint parentNid, jstring jpath) { + jint parentNid, jstring jpath) +{ int status, defNid; void *ctx = JLONG2PTR(jctx); const char *path; path = (*env)->GetStringUTFChars(env, jpath, 0); status = CTXCALLN(TreeGetDefaultNid, &defNid); - if - STATUS_OK - status = CTXCALLN(TreeSetDefaultNid, parentNid); - if - STATUS_OK - status = CTXCALLN(TreeRenameNode, nid, (char *)path); + if (STATUS_OK) + status = CTXCALLN(TreeSetDefaultNid, parentNid); + if (STATUS_OK) + status = CTXCALLN(TreeRenameNode, nid, (char *)path); CTXCALLN(TreeSetDefaultNid, defNid); (*env)->ReleaseStringUTFChars(env, jpath, path); - if - STATUS_NOT_OK - throwMdsException(env, status); + if (STATUS_NOT_OK) + throwMdsException(env, status); } /* Class: MDSplus_TreeNode @@ -3289,17 +3350,20 @@ JNIEXPORT jint JNICALL Java_MDSplus_TreeNode_doAction(JNIEnv *env __attribute__((unused)), jclass cls __attribute__((unused)), - jint nid, jlong jctx) { + jint nid, jlong jctx) +{ return doAction(JLONG2PTR(jctx), nid); } static JavaVM *jvm; -static JNIEnv *getJNIEnv() { +static JNIEnv *getJNIEnv() +{ JNIEnv *jEnv; int retVal; retVal = (*jvm)->AttachCurrentThread(jvm, (void **)&jEnv, NULL); - if (retVal) { + if (retVal) + { printf("AttachCurrentThread error %d\n", retVal); return NULL; } @@ -3308,7 +3372,8 @@ static JNIEnv *getJNIEnv() { static void releaseJNIEnv() { (*jvm)->DetachCurrentThread(jvm); } -static void handleEvent(void *objPtr, int dim, char *buf) { +static void handleEvent(void *objPtr, int dim, char *buf) +{ jmethodID mid; JNIEnv *env; jclass cls; @@ -3353,7 +3418,8 @@ static void handleREvent(char *evName, char *buf, int dim, void *objPtr) */ // Record eventObj instances retrieved by NewGlobalref. They will be released // then the event is disposed (indexed by eventId) -struct EventDescr { +struct EventDescr +{ jobject eventObj; int64_t eventId; struct EventDescr *nxt; @@ -3361,7 +3427,8 @@ struct EventDescr { static pthread_mutex_t eventMutex = PTHREAD_MUTEX_INITIALIZER; static struct EventDescr *eventDescrHead = 0; -static void addEventDescr(jobject eventObj, int64_t eventId) { +static void addEventDescr(jobject eventObj, int64_t eventId) +{ struct EventDescr *newDescr = malloc(sizeof(struct EventDescr)); pthread_mutex_lock(&eventMutex); newDescr->eventId = eventId; @@ -3371,17 +3438,20 @@ static void addEventDescr(jobject eventObj, int64_t eventId) { pthread_mutex_unlock(&eventMutex); } -static jobject releaseEventDescr(int64_t eventId) { +static jobject releaseEventDescr(int64_t eventId) +{ jobject retObj = 0; struct EventDescr *currDescr, *prevDescr; pthread_mutex_lock(&eventMutex); currDescr = eventDescrHead; prevDescr = eventDescrHead; - while (currDescr && currDescr->eventId != eventId) { + while (currDescr && currDescr->eventId != eventId) + { prevDescr = currDescr; currDescr = currDescr->nxt; } - if (currDescr) { + if (currDescr) + { if (prevDescr != currDescr) prevDescr->nxt = currDescr->nxt; else @@ -3400,11 +3470,13 @@ static jobject releaseEventDescr(int64_t eventId) { */ JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *env, jobject obj, - jstring jevent) { + jstring jevent) +{ const char *event; int eventId = -1, status; jobject eventObj = (*env)->NewGlobalRef(env, obj); - if (jvm == 0) { + if (jvm == 0) + { status = (*env)->GetJavaVM(env, &jvm); if (status) printf("GetJavaVM error %d\n", status); @@ -3412,7 +3484,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *env, event = (*env)->GetStringUTFChars(env, jevent, 0); // make sure this Event instance will not be released by the garbage collector #ifdef _WIN32 - if (!critSectInitialized) { + if (!critSectInitialized) + { critSectInitialized = 1; InitializeCriticalSection(&critSect); } @@ -3421,9 +3494,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *env, status = MDSEventAst((char *)event, handleEvent, (void *)eventObj, &eventId); addEventDescr(eventObj, (int64_t)eventId); (*env)->ReleaseStringUTFChars(env, jevent, event); - if - STATUS_NOT_OK - return -1; + if (STATUS_NOT_OK) + return -1; return eventId; } @@ -3433,7 +3505,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_Event_registerEvent(JNIEnv *env, * Signature: (I)V */ JNIEXPORT void JNICALL Java_MDSplus_Event_unregisterEvent( - JNIEnv *env, jobject obj __attribute__((unused)), jlong eventId) { + JNIEnv *env, jobject obj __attribute__((unused)), jlong eventId) +{ jobject delObj = releaseEventDescr(eventId); MDSEventCan(eventId); // Allow Garbage Collector reclaim the Event object @@ -3449,7 +3522,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Event_setEventRaw(JNIEnv *env, jclass cls __attribute__((unused)), jstring jevent, - jbyteArray jbuf) { + jbyteArray jbuf) +{ int dim = (*env)->GetArrayLength(env, jbuf); char *buf = (char *)(*env)->GetByteArrayElements(env, jbuf, JNI_FALSE); const char *event = (*env)->GetStringUTFChars(env, jevent, 0); @@ -3463,7 +3537,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Event_setEventRaw(JNIEnv *env, * Signature: (J)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_MDSplus_Data_convertToDate( - JNIEnv *env, jclass cls __attribute__((unused)), jlong time) { + JNIEnv *env, jclass cls __attribute__((unused)), jlong time) +{ struct descriptor_d dateDsc = {0, DTYPE_T, CLASS_D, 0}; unsigned short len; jstring jdate; @@ -3487,7 +3562,8 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_convertToDate( JNIEXPORT jstring JNICALL Java_MDSplus_Data_getMdsMsg(JNIEnv *env, jclass cls __attribute__((unused)), - jint status) { + jint status) +{ char *msg = MdsGetMsg(status); jstring jmsg = (*env)->NewStringUTF(env, (const char *)msg); return jmsg; @@ -3501,7 +3577,8 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_getMdsMsg(JNIEnv *env, JNIEXPORT jlong JNICALL Java_MDSplus_Data_getTime(JNIEnv *env __attribute__((unused)), jclass cls - __attribute__((unused))) { + __attribute__((unused))) +{ int64_t time; LibConvertDateString("now", &time); return (long)time; @@ -3517,7 +3594,8 @@ JNIEXPORT jlong JNICALL Java_MDSplus_Data_getTime(JNIEnv *env * Signature: (LMDSplus/String;)I */ JNIEXPORT jint JNICALL Java_MDSplus_Connection_connectToMds( - JNIEnv *env, jobject obj __attribute__((unused)), jstring jAddr) { + JNIEnv *env, jobject obj __attribute__((unused)), jstring jAddr) +{ const char *addr = (*env)->GetStringUTFChars(env, jAddr, 0); int sockId = ConnectToMds((char *)addr); (*env)->ReleaseStringUTFChars(env, jAddr, addr); @@ -3531,7 +3609,8 @@ JNIEXPORT jint JNICALL Java_MDSplus_Connection_connectToMds( */ JNIEXPORT void JNICALL Java_MDSplus_Connection_disconnectFromMds( JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)), - jint sockId) { + jint sockId) +{ DisconnectFromMds(sockId); } @@ -3542,16 +3621,17 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_disconnectFromMds( */ JNIEXPORT void JNICALL Java_MDSplus_Connection_openTree( JNIEnv *env, jobject obj __attribute__((unused)), jint sockId, - jstring jname, jint shot) { + jstring jname, jint shot) +{ const char *name = (*env)->GetStringUTFChars(env, jname, 0); jobject exc; int status = MdsOpen(sockId, (char *)name, shot); (*env)->ReleaseStringUTFChars(env, jname, name); - if - STATUS_NOT_OK { - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - } + if (STATUS_NOT_OK) + { + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + } } /* @@ -3560,14 +3640,15 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_openTree( * Signature: (I)V */ JNIEXPORT void JNICALL Java_MDSplus_Connection_closeTree( - JNIEnv *env, jobject obj __attribute__((unused)), jint sockId) { + JNIEnv *env, jobject obj __attribute__((unused)), jint sockId) +{ jobject exc; int status = MdsClose(sockId); - if - STATUS_NOT_OK { - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - } + if (STATUS_NOT_OK) + { + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + } } /* @@ -3577,15 +3658,18 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_closeTree( */ JNIEXPORT void JNICALL Java_MDSplus_Connection_setDefault( JNIEnv *env, jobject obj __attribute__((unused)), jint sockId, - jstring jpath) { + jstring jpath) +{ const char *path = (*env)->GetStringUTFChars(env, jpath, 0); // jobject exc; MdsSetDefault(sockId, (char *)path); (*env)->ReleaseStringUTFChars(env, jpath, path); } -static int convertType(int mdsType) { - switch (mdsType) { +static int convertType(int mdsType) +{ + switch (mdsType) + { case DTYPE_B: return DTYPE_CHAR; case DTYPE_BU: @@ -3615,14 +3699,16 @@ static int convertType(int mdsType) { static char getDType(struct descriptor *dsc) { return convertType(dsc->dtype); } -static char getNDims(struct descriptor *dsc) { +static char getNDims(struct descriptor *dsc) +{ if (dsc->class == CLASS_S) return 0; return ((struct descriptor_a *)dsc)->dimct; } -static void getDims(struct descriptor *dsc, int *dims) { +static void getDims(struct descriptor *dsc, int *dims) +{ ARRAY_BOUNDS(char *, MAX_DIMS) * arrPtr; int i; @@ -3635,7 +3721,8 @@ static void getDims(struct descriptor *dsc, int *dims) { static short getLength(struct descriptor *dsc) { return dsc->length; } -static void *getPtr(struct descriptor *dsc) { +static void *getPtr(struct descriptor *dsc) +{ if (dsc->class == CLASS_S) return dsc->pointer; @@ -3649,7 +3736,8 @@ static void *getPtr(struct descriptor *dsc) { */ JNIEXPORT jobject JNICALL Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), - jint sockId, jstring jExpr, jobjectArray jargs) { + jint sockId, jstring jExpr, jobjectArray jargs) +{ const char *expr; jobject exc, currArg, retObj; int nArgs, i, status; @@ -3670,7 +3758,8 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), (*env)->ReleaseStringUTFChars(env, jExpr, expr); dscs = (struct descriptor **)malloc(nArgs * sizeof(struct descriptor *)); - for (i = 0; i < nArgs; i++) { + for (i = 0; i < nArgs; i++) + { currArg = (*env)->GetObjectArrayElement(env, jargs, i); dscs[i] = ObjectToDescrip(env, currArg); @@ -3682,31 +3771,33 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), status = SendArg(sockId, i + 1, dtype, nArgs + 1, length, nDims, dims, ptr); FreeDescrip(dscs[i]); - if - STATUS_NOT_OK { - free(dscs); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - return NULL; - } + if (STATUS_NOT_OK) + { + free(dscs); + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + return NULL; + } } free(dscs); status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, dims, &numBytes, &ptr, &mem); - if - STATUS_NOT_OK { - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - return NULL; - } + if (STATUS_NOT_OK) + { + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + return NULL; + } // printf("RECEIVED dtype: %d length: %d ndims: %d dim1: %d dim2: %d // numBytes: %d\n", // dtype, length, nDims, dims[0], dims[1], numBytes); - if (nDims == 0) { + if (nDims == 0) + { scalarDsc.length = numBytes; scalarDsc.pointer = ptr; - switch (dtype) { + switch (dtype) + { case DTYPE_CHAR: scalarDsc.dtype = DTYPE_B; break; @@ -3747,14 +3838,16 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), return NULL; } retObj = DescripToObject(env, NULL, &scalarDsc, 0, 0, 0, 0); - } else // nDims > 0 + } + else // nDims > 0 { arrayDsc.length = length; arrayDsc.arsize = numBytes; arrayDsc.pointer = ptr; arrayDsc.dimct = nDims; memcpy(&arrayDsc.m, dims, nDims * sizeof(int)); - switch (dtype) { + switch (dtype) + { case DTYPE_CHAR: arrayDsc.dtype = DTYPE_B; break; @@ -3810,7 +3903,8 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), */ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( JNIEnv *env, jobject obj __attribute__((unused)), jint sockId, - jstring jPath, jstring jExpr, jobjectArray jArgs) { + jstring jPath, jstring jExpr, jobjectArray jArgs) +{ const char *expr = (*env)->GetStringUTFChars(env, jExpr, 0); const char *inPath = (*env)->GetStringUTFChars(env, jPath, 0); char *path, *putExpr; @@ -3828,10 +3922,12 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( // Double backslashes!! path = malloc(strlen(inPath) + 2); - if (inPath[0] == '\\') { + if (inPath[0] == '\\') + { path[0] = '\\'; strcpy(&path[1], inPath); - } else + } + else strcpy(path, inPath); putExpr = malloc(strlen("TreePut(") + strlen(expr) + strlen(path) + 5 + @@ -3840,7 +3936,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( sprintf(putExpr, "TreePut(\'%s\',\'%s\',", path, expr); else sprintf(putExpr, "TreePut(\'%s\',\'%s\'", path, expr); - for (varIdx = 0; varIdx < nArgs; varIdx++) { + for (varIdx = 0; varIdx < nArgs; varIdx++) + { if (varIdx < nArgs - 1) sprintf(&putExpr[strlen(putExpr)], "$,"); else @@ -3857,7 +3954,8 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( free(putExpr); dscs = (struct descriptor **)malloc(nArgs * sizeof(struct descriptor *)); - for (i = 0; i < nArgs; i++) { + for (i = 0; i < nArgs; i++) + { currArg = (*env)->GetObjectArrayElement(env, jArgs, i); dscs[i] = ObjectToDescrip(env, currArg); dtype = getDType(dscs[i]); @@ -3867,38 +3965,39 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( ptr = getPtr(dscs[i]); status = SendArg(sockId, i + 1, dtype, nArgs + 1, length, nDims, dims, ptr); FreeDescrip(dscs[i]); - if - STATUS_NOT_OK { - free(dscs); - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - return; - } - } - free(dscs); - status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, dims, &numBytes, - &ptr, &mem); - if - STATUS_NOT_OK { + if (STATUS_NOT_OK) + { + free(dscs); exc = (*env)->FindClass(env, "MDSplus/MdsException"); (*env)->ThrowNew(env, exc, MdsGetMsg(status)); return; } + } + free(dscs); + status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, dims, &numBytes, + &ptr, &mem); + if (STATUS_NOT_OK) + { + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + return; + } if (status & 1 && dtype == DTYPE_LONG && nDims == 0 && numBytes == sizeof(int)) memcpy(&status, ptr, numBytes); if (mem) FreeMessage(mem); - if - STATUS_NOT_OK { - exc = (*env)->FindClass(env, "MDSplus/MdsException"); - (*env)->ThrowNew(env, exc, MdsGetMsg(status)); - } + if (STATUS_NOT_OK) + { + exc = (*env)->FindClass(env, "MDSplus/MdsException"); + (*env)->ThrowNew(env, exc, MdsGetMsg(status)); + } } ///////////////////GetDeviceField for Netbeans Builder -EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) { +EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) +{ int status, nid, curr_nid, i; char *names, *path; static int conglomerate_nids, conglomerate_nids_len; @@ -3909,7 +4008,8 @@ EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) { DESCRIPTOR_A(dsc, 1, DTYPE_B, 0, 0); conglomerate_nids = 0; path = getenv("device_beans_path"); - if (!path || !*path) { + if (!path || !*path) + { setenv("device_beans_path", getenv("HOME"), 0); } status = TreeOpenNew("device_beans", -1); @@ -3922,7 +4022,8 @@ EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) { printf("%s\n", MdsGetMsg(status)); if (status & 1) status = TreeGetNci(nid, nci_list); - if (!(status & 1) || conglomerate_nids == 0) { + if (!(status & 1) || conglomerate_nids == 0) + { TreeQuitTree("device_beans", -1); return &xd; } diff --git a/kbsidevices/hpe1429.c b/kbsidevices/hpe1429.c index f906cef17e..acd4df928b 100644 --- a/kbsidevices/hpe1429.c +++ b/kbsidevices/hpe1429.c @@ -74,7 +74,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define hpe1429_MANF_ID 4095 #define hpe1429_IDN_STRING "HEWLETT-PACKARD,E1429" -#define hpe1429_REV_CODE \ +#define hpe1429_REV_CODE \ "A.02.03" /* Driver Revision */ /* ??? you must change this */ #define hpe1429_ERR_MSG_LENGTH 256 /* size of error message buffer */ @@ -95,46 +95,46 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. if you do then you must also remove the routines that use them (_cmd_arr functions) */ -#define SWAP_FLOAT64(dest) \ - { \ - unsigned char src[8]; \ - *((double *)src) = *((double *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[7]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[6]; \ - ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[5]; \ - ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[4]; \ - ((unsigned char *)(dest))[4] = ((unsigned char *)(src))[3]; \ - ((unsigned char *)(dest))[5] = ((unsigned char *)(src))[2]; \ - ((unsigned char *)(dest))[6] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[7] = ((unsigned char *)(src))[0]; \ - } - -#define SWAP_FLOAT32(dest) \ - { \ - unsigned char src[4]; \ - *((float *)src) = *((float *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ - ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ - } - -#define SWAP_32(dest) \ - { \ - unsigned char src[4]; \ - *((long *)src) = *((long *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ - ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ - } - -#define SWAP_16(dest) \ - { \ - unsigned char src[2]; \ - *((int *)src) = *((int *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[0]; \ +#define SWAP_FLOAT64(dest) \ + { \ + unsigned char src[8]; \ + *((double *)src) = *((double *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[7]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[6]; \ + ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[5]; \ + ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[4]; \ + ((unsigned char *)(dest))[4] = ((unsigned char *)(src))[3]; \ + ((unsigned char *)(dest))[5] = ((unsigned char *)(src))[2]; \ + ((unsigned char *)(dest))[6] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[7] = ((unsigned char *)(src))[0]; \ + } + +#define SWAP_FLOAT32(dest) \ + { \ + unsigned char src[4]; \ + *((float *)src) = *((float *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ + ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ + } + +#define SWAP_32(dest) \ + { \ + unsigned char src[4]; \ + *((long *)src) = *((long *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ + ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ + } + +#define SWAP_16(dest) \ + { \ + unsigned char src[2]; \ + *((int *)src) = *((int *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[0]; \ } /*=============================================================== * @@ -143,7 +143,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *=============================================================== */ -#define hpe1429_MSG_VI_OPEN_ERR \ +#define hpe1429_MSG_VI_OPEN_ERR \ "vi was zero. Was the hpe1429_init() successful?" #define hpe1429_MSG_CONDITION "condition" @@ -152,11 +152,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define hpe1429_MSG_EVENT "event" /* hpe1429_statEvent_Q() */ -#define hpe1429_MSG_EVENT_HDLR_INSTALLED \ +#define hpe1429_MSG_EVENT_HDLR_INSTALLED \ "event handler is already installed for event happening" /* hpe1429_statEvent_Q() */ -#define hpe1429_MSG_EVENT_HDLR_INST2 \ +#define hpe1429_MSG_EVENT_HDLR_INST2 \ "Only 1 handler can be installed at a time." /* hpe1429_statEvent_Q() */ @@ -173,18 +173,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define hpe1429_MSG_IN_FUNCTION "in function" /* hpe1429_error_message() */ -#define hpe1429_MSG_INVALID_STATUS \ - "Parameter 2 is invalid" \ +#define hpe1429_MSG_INVALID_STATUS \ + "Parameter 2 is invalid" \ " in function hpe1429_error_message()." /* hpe1429_error_message() */ #define hpe1429_MSG_INVALID_STATUS_VALUE " is not a valid viStatus value." /* hpe1429_error_message() */ -#define hpe1429_MSG_INVALID_VI \ - "Parameter 1 is invalid" \ - " in function hpe1429_error_message()" \ - ". Using an inactive ViSession may cause this error." \ +#define hpe1429_MSG_INVALID_VI \ + "Parameter 1 is invalid" \ + " in function hpe1429_error_message()" \ + ". Using an inactive ViSession may cause this error." \ " Was the instrument driver closed prematurely?" /* hpe1429_message_query() */ @@ -253,7 +253,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define VI_ERROR_FAIL_ID_QUERY_MSG "Instrument IDN does not match." -#define INSTR_ERROR_INV_SESSION_MSG \ +#define INSTR_ERROR_INV_SESSION_MSG \ "ViSession (parameter 1) was not created by this driver." #define INSTR_ERROR_NULL_PTR_MSG "NULL pointer detected." @@ -262,7 +262,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define INSTR_ERROR_UNEXPECTED_MSG "An unexpected error occurred." -#define INSTR_ERROR_DETECTED_MSG \ +#define INSTR_ERROR_DETECTED_MSG \ "Instrument Error Detected, call hpe1429_error_query()." #define INSTR_ERROR_LOOKUP_MSG "String not found in table." @@ -271,31 +271,34 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* don't check the debug pointer all the time!*/ #ifdef DEBUG -#define hpe1429_DEBUG_CHK_THIS(vi, thisPtr) \ - /* check for NULL user data */ \ - if (0 == thisPtr) { \ - hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_INV_SESSION); \ - } \ - { \ - ViSession defRM; \ - \ - /* This should never fail */ \ - errStatus = viGetAttribute(vi, VI_ATTR_RM_SESSION, &defRM); \ - if (VI_SUCCESS > errStatus) { \ - hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_UNEXPECTED); \ - } \ - if (defRM != thisPtr->defRMSession) { \ - hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_INV_SESSION); \ - } \ +#define hpe1429_DEBUG_CHK_THIS(vi, thisPtr) \ + /* check for NULL user data */ \ + if (0 == thisPtr) \ + { \ + hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_INV_SESSION); \ + } \ + { \ + ViSession defRM; \ + \ + /* This should never fail */ \ + errStatus = viGetAttribute(vi, VI_ATTR_RM_SESSION, &defRM); \ + if (VI_SUCCESS > errStatus) \ + { \ + hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_UNEXPECTED); \ + } \ + if (defRM != thisPtr->defRMSession) \ + { \ + hpe1429_LOG_STATUS(vi, NULL, hpe1429_INSTR_ERROR_INV_SESSION); \ + } \ } #else #define hpe1429_DEBUG_CHK_THIS(vi, thisPtr) #endif #ifdef WANT_CDE_INIT -#define hpe1429_CDE_INIT(funcname) \ - strcpy(thisPtr->errFuncName, funcname); \ - thisPtr->errNumber = VI_SUCCESS; \ +#define hpe1429_CDE_INIT(funcname) \ + strcpy(thisPtr->errFuncName, funcname); \ + thisPtr->errNumber = VI_SUCCESS; \ thisPtr->errMessage[0] = 0; #define hpe1429_CDE_MESSAGE(message) strcpy(thisPtr->errMessage, message) @@ -305,7 +308,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define hpe1429_CDE_MESSAGE(message) strcpy(thisPtr->errMessage, message) #endif -struct hpe1429_globals { +struct hpe1429_globals +{ ViSession defRMSession; ViStatus errNumber; @@ -357,26 +361,32 @@ struct hpe1429_globals { #include #include -long setDelay(double val) { +long setDelay(double val) +{ // Delay should be absolute (e.g. 100 micro sec = 1e-4) double slice; _int64_t count; - if (!QueryPerformanceFrequency((LARGE_INTEGER *)&count)) { + if (!QueryPerformanceFrequency((LARGE_INTEGER *)&count)) + { // hdw doens't have high perfomance count so use getickcount slice = 1e-3; // units for gettick count - } else { + } + else + { slice = 1.0 / count; // Seconds per tick } return (long)(val / slice) + 1; } -void doDelay(long ticks) { +void doDelay(long ticks) +{ _int64_t startval, tmp; - if (!QueryPerformanceCounter((LARGE_INTEGER *)&startval)) { + if (!QueryPerformanceCounter((LARGE_INTEGER *)&startval)) + { DWORD sval; sval = GetTickCount(); while (GetTickCount() - sval < (DWORD)ticks) @@ -384,13 +394,15 @@ void doDelay(long ticks) { return; } tmp = startval; - while (tmp - startval < (DWORD)ticks) { + while (tmp - startval < (DWORD)ticks) + { QueryPerformanceCounter((LARGE_INTEGER *)&tmp); } } #else -long setDelay(double val) { +long setDelay(double val) +{ DWORD ts; DWORD te; ViInt32 count; @@ -434,14 +446,18 @@ long setDelay(double val) { return (long)(-((val / 1e-3) + 1)); } -void doDelay(long ticks) { +void doDelay(long ticks) +{ DWORD t = GetTickCount(); long count; - if (ticks < 0) { + if (ticks < 0) + { ticks = -ticks; while (GetTickCount() - t < (DWORD)ticks) ; - } else { + } + else + { count = 0; while (count < ticks) count++; @@ -456,14 +472,15 @@ void doDelay(long ticks) { * hpe1429_statusUpdate() in order to determine exactly where an error * occured in a driver. */ -#define hpe1429_LOG_STATUS(vi, thisPtr, status) \ +#define hpe1429_LOG_STATUS(vi, thisPtr, status) \ return hpe1429_statusUpdate(vi, thisPtr, status) /* declare this here since it is called by statusUpdate */ static void hpe1429_srqTraverse(ViSession vi, ViInt32 eventReg); ViStatus hpe1429_statusUpdate(ViSession vi, struct hpe1429_globals *thisPtr, - ViStatus s) { + ViStatus s) +{ ViUInt32 rc; ViStatus errStatus; char lc[20]; @@ -478,7 +495,8 @@ ViStatus hpe1429_statusUpdate(ViSession vi, struct hpe1429_globals *thisPtr, thisPtr->controler &= 0xFFFFE00B; /* 0 some bits */ if (thisPtr && thisPtr->errQueryDetect && - s != VI_ERROR_TMO /* don't access if already timed out! */) { + s != VI_ERROR_TMO /* don't access if already timed out! */) + { errStatus = viWrite(vi, "*ESR?", 5, &rc); if (errStatus < VI_SUCCESS) return VI_ERROR_SYSTEM_ERROR; @@ -506,7 +524,8 @@ ViStatus hpe1429_statusUpdate(ViSession vi, struct hpe1429_globals *thisPtr, * Error Message Structures */ -struct instrErrStruct { +struct instrErrStruct +{ ViStatus errStatus; ViString errMessage; }; @@ -541,14 +560,16 @@ const static struct instrErrStruct instrErrMsgTable[] = { }; /* macros for testing parameters */ -#define hpe1429_CHK_BOOLEAN(my_val, err) \ - if (hpe1429_chk_boolean(thisPtr, my_val)) \ +#define hpe1429_CHK_BOOLEAN(my_val, err) \ + if (hpe1429_chk_boolean(thisPtr, my_val)) \ hpe1429_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1429_chk_boolean(struct hpe1429_globals *thisPtr, - ViBoolean my_val) { + ViBoolean my_val) +{ char message[hpe1429_ERR_MSG_LENGTH]; - if ((my_val != VI_TRUE) && (my_val != VI_FALSE)) { + if ((my_val != VI_TRUE) && (my_val != VI_FALSE)) + { /* true = parameter is invalid */ sprintf(message, hpe1429_MSG_BOOLEAN, my_val); hpe1429_CDE_MESSAGE(message); @@ -560,16 +581,18 @@ static ViBoolean hpe1429_chk_boolean(struct hpe1429_globals *thisPtr, return VI_FALSE; } -#define hpe1429_CHK_REAL_RANGE(my_val, min, max, err) \ - if (hpe1429_chk_real_range(thisPtr, my_val, min, max)) \ +#define hpe1429_CHK_REAL_RANGE(my_val, min, max, err) \ + if (hpe1429_chk_real_range(thisPtr, my_val, min, max)) \ hpe1429_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1429_chk_real_range(struct hpe1429_globals *thisPtr, ViReal64 my_val, ViReal64 min, - ViReal64 max) { + ViReal64 max) +{ char message[hpe1429_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1429_MSG_REAL, min, max, my_val); hpe1429_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -578,16 +601,18 @@ static ViBoolean hpe1429_chk_real_range(struct hpe1429_globals *thisPtr, return VI_FALSE; } -#define hpe1429_CHK_INT_RANGE(my_val, min, max, err) \ - if (hpe1429_chk_int_range(thisPtr, my_val, min, max)) \ +#define hpe1429_CHK_INT_RANGE(my_val, min, max, err) \ + if (hpe1429_chk_int_range(thisPtr, my_val, min, max)) \ hpe1429_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1429_chk_int_range(struct hpe1429_globals *thisPtr, ViInt16 my_val, ViInt16 min, - ViInt16 max) { + ViInt16 max) +{ char message[hpe1429_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1429_MSG_INT, min, max, my_val); hpe1429_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -596,16 +621,18 @@ static ViBoolean hpe1429_chk_int_range(struct hpe1429_globals *thisPtr, return VI_FALSE; } -#define hpe1429_CHK_LONG_RANGE(my_val, min, max, err) \ - if (hpe1429_chk_long_range(thisPtr, my_val, min, max)) \ +#define hpe1429_CHK_LONG_RANGE(my_val, min, max, err) \ + if (hpe1429_chk_long_range(thisPtr, my_val, min, max)) \ hpe1429_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1429_chk_long_range(struct hpe1429_globals *thisPtr, ViInt32 my_val, ViInt32 min, - ViInt32 max) { + ViInt32 max) +{ char message[hpe1429_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1429_MSG_LONG, min, max, my_val); hpe1429_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -614,17 +641,19 @@ static ViBoolean hpe1429_chk_long_range(struct hpe1429_globals *thisPtr, return VI_FALSE; } -#define hpe1429_CHK_ENUM(my_val, limit, err) \ - if (hpe1429_chk_enum(thisPtr, my_val, limit)) \ +#define hpe1429_CHK_ENUM(my_val, limit, err) \ + if (hpe1429_chk_enum(thisPtr, my_val, limit)) \ hpe1429_LOG_STATUS(vi, thisPtr, err); /* utility routine which searches for a string in an array of strings. */ /* This is used by the CHK_ENUM macro */ static ViBoolean hpe1429_chk_enum(struct hpe1429_globals *thisPtr, - ViInt16 my_val, ViInt16 limit) { + ViInt16 my_val, ViInt16 limit) +{ char message[hpe1429_ERR_MSG_LENGTH]; - if ((my_val < 0) || (my_val > limit)) { + if ((my_val < 0) || (my_val > limit)) + { sprintf(message, hpe1429_MSG_INT, 0, limit, my_val); hpe1429_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -643,7 +672,8 @@ ViStatus hpe1429_findIndex(struct hpe1429_globals *thisPtr, const char *const array_of_strings[], /*last entry in array must be 0 */ const char *string, /* string read from instrument */ - ViPInt16 index) { /* result index */ + ViPInt16 index) +{ /* result index */ ViInt16 i; ViInt16 my_len; char search_str[20]; @@ -657,8 +687,10 @@ ViStatus hpe1429_findIndex(struct hpe1429_globals *thisPtr, if (search_str[my_len - 1] == '\n') search_str[my_len - 1] = '\0'; - for (i = 0; array_of_strings[i]; i++) { - if (!strcmp(array_of_strings[i], search_str)) { + for (i = 0; array_of_strings[i]; i++) + { + if (!strcmp(array_of_strings[i], search_str)) + { *index = i; return VI_SUCCESS; } @@ -672,12 +704,13 @@ ViStatus hpe1429_findIndex(struct hpe1429_globals *thisPtr, /* returns the globals pointer */ -#define GetGlobals(vi, thisPtr) \ - { \ - errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); \ - if (VI_SUCCESS > errStatus) { \ - hpe1429_LOG_STATUS(vi, NULL, errStatus); \ - } \ +#define GetGlobals(vi, thisPtr) \ + { \ + errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); \ + if (VI_SUCCESS > errStatus) \ + { \ + hpe1429_LOG_STATUS(vi, NULL, errStatus); \ + } \ } /**************************************************************************** @@ -709,7 +742,8 @@ hpe1429_init *****************************************************************************/ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, - ViBoolean do_reset, ViPSession vi) { + ViBoolean do_reset, ViPSession vi) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; ViSession defRM; @@ -723,7 +757,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, /* Find the Default Resource Manager */ errStatus = viOpenDefaultRM(&defRM); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_SYSTEM_ERROR * VI_ERROR_ALLOC */ @@ -732,7 +767,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, /* Open a session to the instrument */ errStatus = viOpen(defRM, InstrDesc, VI_NULL, VI_NULL, vi); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { viClose(defRM); /* Errors: VI_ERROR_NSUP_OPER * VI_ERROR_INV_RSRC_NAME @@ -746,7 +782,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, /* get memory for instance specific globals */ thisPtr = (struct hpe1429_globals *)malloc(sizeof(struct hpe1429_globals)); - if (0 == thisPtr) { + if (0 == thisPtr) + { viClose(defRM); /* also closes vi session */ *vi = VI_NULL; hpe1429_LOG_STATUS(*vi, NULL, VI_ERROR_ALLOC); @@ -757,7 +794,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, * and writable. */ errStatus = viSetAttribute(*vi, VI_ATTR_USER_DATA, (ViAttrState)thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { viClose(*vi); viClose(defRM); /* also closes vi session */ *vi = VI_NULL; @@ -777,9 +815,11 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, thisPtr->controler = 0; /* Assume no commander */ /* Check to see if this e1429 has an e1406 commander */ if (!viGetAttribute(*vi, VI_ATTR_INTF_TYPE, - &intf)) { /* Find interface type */ + &intf)) + { /* Find interface type */ if ((intf == VI_INTF_GPIB_VXI) || - (intf == VI_INTF_GPIB)) { /* may have e1406 */ + (intf == VI_INTF_GPIB)) + { /* may have e1406 */ ViUInt16 num, primary, secondary; ViSession vi1406; char idn_buf[256]; @@ -790,7 +830,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, it's GPIB-VXIn. /* Set the GPIB board number is the same had the GPIB-VXI board number */ - if (intf == VI_INTF_GPIB_VXI) { + if (intf == VI_INTF_GPIB_VXI) + { if (memcmp(InstrDesc, "GPIB-VXI", 8) || InstrDesc[8] < '0' || InstrDesc[8] > '9') num = 0; /* Problem with InstrDesc */ @@ -798,11 +839,14 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, num = (ViUInt16)strtol(InstrDesc + 8, NULL, 0); sprintf(thisPtr->cmdAddr, "GPIB-VXI%hu::0", num); if (viGetAttribute(*vi, VI_ATTR_GPIB_SECONDARY_ADDR, &secondary) < - VI_SUCCESS) { + VI_SUCCESS) + { viGetAttribute(*vi, VI_ATTR_VXI_LA, &secondary); secondary = secondary / 8; } - } else { + } + else + { if (memcmp(InstrDesc, "GPIB", 4) || InstrDesc[4] < '0' || InstrDesc[4] > '9') num = 0; /* Problem with InstrDesc */ @@ -813,39 +857,46 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, sprintf(thisPtr->cmdAddr, "GPIB%hu::%hu::0", num, primary); } errStatus = viOpen(defRM, thisPtr->cmdAddr, VI_NULL, VI_NULL, - &vi1406); /* Open commander */ - if (errStatus >= VI_SUCCESS) { /* opened commander */ + &vi1406); /* Open commander */ + if (errStatus >= VI_SUCCESS) + { /* opened commander */ viSetAttribute(vi1406, VI_ATTR_TMO_VALUE, 1000); errStatus = viClear(vi1406); if (errStatus < VI_SUCCESS) viClose(vi1406); - else { + else + { errStatus = viPrintf(vi1406, "*IDN?\n"); if (errStatus < VI_SUCCESS) viClose(vi1406); - else { + else + { errStatus = viScanf(vi1406, "%t", idn_buf); if (thisPtr) doDelay(thisPtr->myDelay); if (errStatus < VI_SUCCESS || memcmp(idn_buf, "HEWLETT-PACKARD,E140", 20)) /* not an e140x */ viClose(vi1406); - else { + else + { char rd_addr[80]; base_addr = (0x1FC000 + (secondary * 512)) + 6; sprintf(rd_addr, "DIAG:PEEK? %ld, 16\n", base_addr); errStatus = viPrintf(vi1406, rd_addr); if (errStatus < VI_SUCCESS) viClose(vi1406); - else { + else + { ViChar length_str[32]; ViUInt32 retbytes; errStatus = viRead(vi1406, length_str, 31, &retbytes); if (thisPtr) doDelay(thisPtr->myDelay); viClose(vi1406); - if (errStatus >= VI_SUCCESS) { - if (retbytes < 31) { + if (errStatus >= VI_SUCCESS) + { + if (retbytes < 31) + { length_str[retbytes] = 0; thisPtr->a24_addr = strtol(length_str, NULL, 0) * 256; thisPtr->controler = 1; /* passed all the tests */ @@ -856,15 +907,19 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, } } } - } else { + } + else + { if (intf == VI_INTF_VXI) thisPtr->controler = 10; /* a not as yet mapped embedded controler */ } } - if (VI_TRUE == do_reset) { + if (VI_TRUE == do_reset) + { /* dev clr andcall the reset function to reset the instrument */ - if (viClear(*vi) < VI_SUCCESS || hpe1429_reset(*vi) < VI_SUCCESS) { + if (viClear(*vi) < VI_SUCCESS || hpe1429_reset(*vi) < VI_SUCCESS) + { /* ignore any errors in PREFIX_close */ hpe1429_close(*vi); *vi = VI_NULL; @@ -873,12 +928,14 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, Sleep(100); } - if (VI_TRUE == id_query) { + if (VI_TRUE == id_query) + { ViUInt16 intf; char idn_buf[256]; /* find the interface type */ - if (errStatus = viGetAttribute(*vi, VI_ATTR_INTF_TYPE, &intf)) { + if (errStatus = viGetAttribute(*vi, VI_ATTR_INTF_TYPE, &intf)) + { /* Errors: VI_ERROR_NSUP_ATTR */ /* ignore any errors in PREFIX_close */ @@ -888,12 +945,14 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, hpe1429_LOG_STATUS(*vi, NULL, errStatus); } - switch (intf) { + switch (intf) + { case VI_INTF_GPIB: if (viClear(*vi) < VI_SUCCESS || viPrintf(*vi, "*IDN?\n") < VI_SUCCESS || viScanf(*vi, "%t", idn_buf) < VI_SUCCESS || /* check for a idn match */ - strncmp(idn_buf, hpe1429_IDN_STRING, strlen(hpe1429_IDN_STRING))) { + strncmp(idn_buf, hpe1429_IDN_STRING, strlen(hpe1429_IDN_STRING))) + { /* ignore any errors in PREFIX_close */ hpe1429_close(*vi); *vi = VI_NULL; @@ -909,7 +968,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, /* find the VXI manfacturer's ID */ errStatus = viGetAttribute(*vi, VI_ATTR_MANF_ID, &manfId); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_NSUP_ATTR */ /* ignore any errors in PREFIX_close */ @@ -922,7 +982,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, /* find the instrument's model code */ errStatus = viGetAttribute(*vi, VI_ATTR_MODEL_CODE, (ViPAttrState)(&modelCode)); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_NSUP_ATTR */ /* Note: this should never happen * with a VXI instrument @@ -934,7 +995,8 @@ ViStatus _VI_FUNC hpe1429_init(ViRsrc InstrDesc, ViBoolean id_query, hpe1429_LOG_STATUS(*vi, NULL, errStatus); } - if ((manfId != hpe1429_MANF_ID) || (modelCode != hpe1429_MODEL_CODE)) { + if ((manfId != hpe1429_MANF_ID) || (modelCode != hpe1429_MODEL_CODE)) + { /* ignore any errors in PREFIX_close */ hpe1429_close(*vi); *vi = VI_NULL; @@ -966,7 +1028,8 @@ hpe1429_close | | Instrument Handle returned from hpe1429_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1429_close(ViSession vi) { +ViStatus _VI_FUNC hpe1429_close(ViSession vi) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; ViSession defRM; @@ -978,7 +1041,8 @@ ViStatus _VI_FUNC hpe1429_close(ViSession vi) { defRM = thisPtr->defRMSession; /* free memory */ - if (thisPtr) { + if (thisPtr) + { /* make sure there is something to free */ free(thisPtr); } @@ -999,14 +1063,16 @@ hpe1429_reset | | Instrument Handle returned from hpe1429_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1429_reset(ViSession vi) { +ViStatus _VI_FUNC hpe1429_reset(ViSession vi) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; GetGlobals(vi, thisPtr) hpe1429_DEBUG_CHK_THIS(vi, thisPtr); errStatus = viPrintf(vi, "*RST\n"); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1039,7 +1105,8 @@ hpe1429_self_test *****************************************************************************/ ViStatus _VI_FUNC hpe1429_self_test(ViSession vi, ViPInt16 test_result, - ViPString test_message) { + ViPString test_message) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; @@ -1052,7 +1119,8 @@ ViStatus _VI_FUNC hpe1429_self_test(ViSession vi, ViPInt16 test_result, thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "*TST?\n"); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1060,13 +1128,15 @@ ViStatus _VI_FUNC hpe1429_self_test(ViSession vi, ViPInt16 test_result, errStatus = viScanf(vi, "%hd%*t", test_result); if (thisPtr) doDelay(thisPtr->myDelay); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { *test_result = -1; hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - switch (*test_result) { + switch (*test_result) + { case 0: sprintf(test_message, hpe1429_MSG_SELF_TEST_PASSED); break; @@ -1102,7 +1172,8 @@ hpe1429_error_query *****************************************************************************/ ViStatus _VI_FUNC hpe1429_error_query(ViSession vi, ViPInt32 error_number, - ViPString error_message) { + ViPString error_message) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; @@ -1115,7 +1186,8 @@ ViStatus _VI_FUNC hpe1429_error_query(ViSession vi, ViPInt32 error_number, thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "SYST:ERR?\n"); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1125,7 +1197,8 @@ ViStatus _VI_FUNC hpe1429_error_query(ViSession vi, ViPInt32 error_number, if (thisPtr) doDelay(thisPtr->myDelay); /* check for error during the scan */ - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { *error_number = -1; error_message[0] = 0; hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1174,28 +1247,35 @@ ViStatus _VI_FUNC hpe1429_error_message(ViSession vi, ViStatus error_number, thisPtr = NULL; /* try to find a thisPtr */ - if (VI_NULL != vi) { + if (VI_NULL != vi) + { GetGlobals(vi, thisPtr) hpe1429_DEBUG_CHK_THIS(vi, thisPtr); } - if (VI_SUCCESS == error_number) { + if (VI_SUCCESS == error_number) + { sprintf(message, hpe1429_MSG_NO_ERRORS); hpe1429_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } /* return the static error message */ for (idx = 0; idx < (sizeof instrErrMsgTable / sizeof(struct instrErrStruct)); - idx++) { + idx++) + { /* check for a matching error number */ - if (instrErrMsgTable[idx].errStatus == error_number) { - if ((thisPtr) && (thisPtr->errNumber == error_number)) { + if (instrErrMsgTable[idx].errStatus == error_number) + { + if ((thisPtr) && (thisPtr->errNumber == error_number)) + { /* context dependent error * message is available. */ sprintf(message, "%s " hpe1429_MSG_IN_FUNCTION " %s() %s", instrErrMsgTable[idx].errMessage, thisPtr->errFuncName, thisPtr->errMessage); - } else { + } + else + { /* No context dependent eror * message available so copy * the static error message @@ -1214,9 +1294,11 @@ ViStatus _VI_FUNC hpe1429_error_message(ViSession vi, ViStatus error_number, * At this point vi is either VALID or VI_NULL */ errStatus = viStatusDesc(vi, error_number, message); - if (VI_SUCCESS == errStatus) { + if (VI_SUCCESS == errStatus) + { /* check for a context dependent error message */ - if ((thisPtr) && (thisPtr->errNumber == error_number)) { + if ((thisPtr) && (thisPtr->errNumber == error_number)) + { /* context dependent error * message is available. */ @@ -1235,7 +1317,8 @@ ViStatus _VI_FUNC hpe1429_error_message(ViSession vi, ViStatus error_number, } /* if we have a VI_NULL, then we need to return a error message */ - if (VI_NULL == vi) { + if (VI_NULL == vi) + { strcpy(message, hpe1429_MSG_VI_OPEN_ERR); hpe1429_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } @@ -1269,7 +1352,8 @@ hpe1429_revision_query ViStatus _VI_FUNC hpe1429_revision_query(ViSession vi, ViChar _VI_FAR driver_rev[], - ViChar _VI_FAR instr_rev[]) { + ViChar _VI_FAR instr_rev[]) +{ struct hpe1429_globals *thisPtr; ViStatus errStatus; char temp_str[256]; /* temp hold for instr rev string */ @@ -1285,13 +1369,15 @@ ViStatus _VI_FUNC hpe1429_revision_query(ViSession vi, thisPtr->blockSrqIO = VI_TRUE; - if (errStatus = viPrintf(vi, "*IDN?\n")) { + if (errStatus = viPrintf(vi, "*IDN?\n")) + { driver_rev[0] = 0; hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (errStatus = viScanf(vi, "%s%*t", temp_str)) { + if (errStatus = viScanf(vi, "%s%*t", temp_str)) + { driver_rev[0] = 0; instr_rev[0] = 0; if (thisPtr) @@ -1303,7 +1389,8 @@ ViStatus _VI_FUNC hpe1429_revision_query(ViSession vi, last_comma = strrchr(temp_str, ','); /* error and exit if last comma not found */ - if (!last_comma) { + if (!last_comma) + { instr_rev[0] = 0; hpe1429_CDE_MESSAGE("no last comma found in IDN string"); hpe1429_LOG_STATUS(vi, thisPtr, hpe1429_INSTR_ERROR_UNEXPECTED); @@ -1338,7 +1425,8 @@ hpe1429_timeOut /* Purpose: Changes the timeout value of the instrument. Input is in */ /* milliseconds. */ /* ----------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_timeOut(ViSession vi, ViInt32 timeOut) { +ViStatus _VI_FUNC hpe1429_timeOut(ViSession vi, ViInt32 timeOut) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; @@ -1347,7 +1435,8 @@ ViStatus _VI_FUNC hpe1429_timeOut(ViSession vi, ViInt32 timeOut) { hpe1429_CHK_LONG_RANGE(timeOut, 1, 2147483647, VI_ERROR_PARAMETER2); errStatus = viSetAttribute(vi, VI_ATTR_TMO_VALUE, timeOut); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1374,14 +1463,16 @@ hpe1429_timeOut_Q /* Purpose: Returns the current setting of the timeout value of the */ /* instrument in milliseconds. */ /* ----------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_timeOut_Q(ViSession vi, ViPInt32 timeOut) { +ViStatus _VI_FUNC hpe1429_timeOut_Q(ViSession vi, ViPInt32 timeOut) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; GetGlobals(vi, thisPtr) hpe1429_DEBUG_CHK_THIS(vi, thisPtr); errStatus = viGetAttribute(vi, VI_ATTR_TMO_VALUE, timeOut); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1404,7 +1495,8 @@ hpe1429_errorQueryDetect | | automatic instrument error querying. *****************************************************************************/ -ViStatus _VI_FUNC hpe1429_errorQueryDetect(ViSession vi, ViBoolean errDetect) { +ViStatus _VI_FUNC hpe1429_errorQueryDetect(ViSession vi, ViBoolean errDetect) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; @@ -1434,7 +1526,8 @@ hpe1429_errorQueryDetect_Q *****************************************************************************/ ViStatus _VI_FUNC hpe1429_errorQueryDetect_Q(ViSession vi, - ViPBoolean pErrDetect) { + ViPBoolean pErrDetect) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; @@ -1456,14 +1549,16 @@ hpe1429_dcl | | Instrument Handle returned from hpe1429_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1429_dcl(ViSession vi) { +ViStatus _VI_FUNC hpe1429_dcl(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; GetGlobals(vi, thisPtr) hpe1429_DEBUG_CHK_THIS(vi, thisPtr); errStatus = viClear(vi); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1485,7 +1580,8 @@ hpe1429_readStatusByte_Q | | returns the contents of the status byte *****************************************************************************/ -ViStatus _VI_FUNC hpe1429_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { +ViStatus _VI_FUNC hpe1429_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; ViUInt16 stb; @@ -1496,7 +1592,8 @@ ViStatus _VI_FUNC hpe1429_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { errStatus = viReadSTB(vi, &stb); if (thisPtr) doDelay(thisPtr->myDelay); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1507,13 +1604,15 @@ ViStatus _VI_FUNC hpe1429_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { } /* hpe1429_operEvent_Q */ -ViStatus _VI_FUNC hpe1429_operEvent_Q(ViSession vi, ViPInt32 val) { +ViStatus _VI_FUNC hpe1429_operEvent_Q(ViSession vi, ViPInt32 val) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; ViInt32 count; char buf[20]; - GetGlobals(vi, thisPtr) { + GetGlobals(vi, thisPtr) + { errStatus = viWrite(vi, "STAT:OPER:EVEN?", 15, &count); if (errStatus < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1530,13 +1629,15 @@ ViStatus _VI_FUNC hpe1429_operEvent_Q(ViSession vi, ViPInt32 val) { } /* hpe1429_operCond_Q */ -ViStatus _VI_FUNC hpe1429_operCond_Q(ViSession vi, ViPInt32 val) { +ViStatus _VI_FUNC hpe1429_operCond_Q(ViSession vi, ViPInt32 val) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; ViInt32 count; char buf[20]; - GetGlobals(vi, thisPtr) { + GetGlobals(vi, thisPtr) + { errStatus = viWrite(vi, "STAT:OPER:COND?", 15, &count); if (errStatus < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1554,13 +1655,15 @@ ViStatus _VI_FUNC hpe1429_operCond_Q(ViSession vi, ViPInt32 val) { } /* hpe1429_statusQuesEven_Q */ -ViStatus _VI_FUNC hpe1429_quesEvent_Q(ViSession vi, ViPInt32 val) { +ViStatus _VI_FUNC hpe1429_quesEvent_Q(ViSession vi, ViPInt32 val) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; ViInt32 count; char buf[20]; - GetGlobals(vi, thisPtr) { + GetGlobals(vi, thisPtr) + { errStatus = viWrite(vi, "STAT:QUES:EVEN?", 15, &count); if (errStatus < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1577,13 +1680,15 @@ ViStatus _VI_FUNC hpe1429_quesEvent_Q(ViSession vi, ViPInt32 val) { } /* hpe1429_QuesCond_Q */ -ViStatus _VI_FUNC hpe1429_quesCond_Q(ViSession vi, ViPInt32 val) { +ViStatus _VI_FUNC hpe1429_quesCond_Q(ViSession vi, ViPInt32 val) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; ViInt32 count; char buf[20]; - GetGlobals(vi, thisPtr) { + GetGlobals(vi, thisPtr) + { errStatus = viWrite(vi, "STAT:QUES:COND?", 15, &count); if (errStatus < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1614,7 +1719,8 @@ ViStatus _VI_FUNC hpe1429_quesCond_Q(ViSession vi, ViPInt32 val) { */ ViStatus _VI_FUNC hpe1429_cmdString_Q(ViSession vi, ViString p1, ViInt32 p2, - ViChar _VI_FAR p3[]) { + ViChar _VI_FAR p3[]) +{ ViStatus errStatus; ViInt32 mySize; struct hpe1429_globals *thisPtr; @@ -1662,7 +1768,8 @@ ViStatus _VI_FUNC hpe1429_cmdString_Q(ViSession vi, ViString p1, ViInt32 p2, */ ViStatus _VI_FUNC hpe1429_cmdData_Q(ViSession vi, ViString p1, ViInt32 p2, - ViChar _VI_FAR p3[]) { + ViChar _VI_FAR p3[]) +{ ViStatus errStatus; ViInt32 mySize; struct hpe1429_globals *thisPtr; @@ -1704,7 +1811,8 @@ ViStatus _VI_FUNC hpe1429_cmdData_Q(ViSession vi, ViString p1, ViInt32 p2, assumes p1 is NULL terminated C string. */ -ViStatus _VI_FUNC hpe1429_cmd(ViSession vi, ViString p1) { +ViStatus _VI_FUNC hpe1429_cmd(ViSession vi, ViString p1) +{ ViInt32 bogus_size = 50; /* Parameter required for cscpi_exe() */ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -1730,7 +1838,8 @@ ViStatus _VI_FUNC hpe1429_cmd(ViSession vi, ViString p1) { comment: a non number instrument response would yeild zero in p2. */ -ViStatus _VI_FUNC hpe1429_cmdInt32_Q(ViSession vi, ViString p1, ViPInt32 p2) { +ViStatus _VI_FUNC hpe1429_cmdInt32_Q(ViSession vi, ViString p1, ViPInt32 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -1768,7 +1877,8 @@ ViStatus _VI_FUNC hpe1429_cmdInt32_Q(ViSession vi, ViString p1, ViPInt32 p2) { underfined. */ -ViStatus _VI_FUNC hpe1429_cmdReal32_Q(ViSession vi, ViString p1, ViPReal32 p2) { +ViStatus _VI_FUNC hpe1429_cmdReal32_Q(ViSession vi, ViString p1, ViPReal32 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -1805,7 +1915,8 @@ ViStatus _VI_FUNC hpe1429_cmdReal32_Q(ViSession vi, ViString p1, ViPReal32 p2) { underfined. */ -ViStatus _VI_FUNC hpe1429_cmdReal64_Q(ViSession vi, ViString p1, ViPReal64 p2) { +ViStatus _VI_FUNC hpe1429_cmdReal64_Q(ViSession vi, ViString p1, ViPReal64 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -1840,7 +1951,8 @@ ViStatus _VI_FUNC hpe1429_cmdReal64_Q(ViSession vi, ViString p1, ViPReal64 p2) { will return 0 if response is not a valid number */ -ViStatus _VI_FUNC hpe1429_cmdInt16_Q(ViSession vi, ViString p1, ViPInt16 p2) { +ViStatus _VI_FUNC hpe1429_cmdInt16_Q(ViSession vi, ViString p1, ViPInt16 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -1898,19 +2010,22 @@ ViStatus _VI_FUNC hpe1429_cmdReal64Arr_Q(ViSession vi, ViString p1, ViInt32 p2, if ((errStatus = viWrite(vi, p1, strlen(p1), &cnt)) < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (lc[0] != '#') { + if (lc[0] != '#') + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_INV_EXPR); } - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -1918,7 +2033,8 @@ ViStatus _VI_FUNC hpe1429_cmdReal64Arr_Q(ViSession vi, ViString p1, ViInt32 p2, nbytes = lc[0] - '0'; - if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2002,19 +2118,22 @@ ViStatus _VI_FUNC hpe1429_cmdReal32Arr_Q(ViSession vi, ViString p1, ViInt32 p2, if ((errStatus = viWrite(vi, p1, strlen(p1), &cnt)) < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (lc[0] != '#') { + if (lc[0] != '#') + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_INV_EXPR); } - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2022,7 +2141,8 @@ ViStatus _VI_FUNC hpe1429_cmdReal32Arr_Q(ViSession vi, ViString p1, ViInt32 p2, nbytes = lc[0] - '0'; - if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2104,19 +2224,22 @@ ViStatus _VI_FUNC hpe1429_cmdInt16Arr_Q(ViSession vi, ViString p1, ViInt32 p2, if ((errStatus = viWrite(vi, p1, strlen(p1), &cnt)) < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (lc[0] != '#') { + if (lc[0] != '#') + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_INV_EXPR); } - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2124,7 +2247,8 @@ ViStatus _VI_FUNC hpe1429_cmdInt16Arr_Q(ViSession vi, ViString p1, ViInt32 p2, nbytes = lc[0] - '0'; - if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2206,19 +2330,22 @@ ViStatus _VI_FUNC hpe1429_cmdInt32Arr_Q(ViSession vi, ViString p1, ViInt32 p2, if ((errStatus = viWrite(vi, p1, strlen(p1), &cnt)) < VI_SUCCESS) hpe1429_LOG_STATUS(vi, thisPtr, errStatus); - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (lc[0] != '#') { + if (lc[0] != '#') + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_INV_EXPR); } - if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, 1, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2226,7 +2353,8 @@ ViStatus _VI_FUNC hpe1429_cmdInt32Arr_Q(ViSession vi, ViString p1, ViInt32 p2, nbytes = lc[0] - '0'; - if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) { + if ((errStatus = viRead(vi, lc, nbytes, &cnt)) < VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); hpe1429_LOG_STATUS(vi, thisPtr, errStatus); @@ -2282,7 +2410,8 @@ ViStatus _VI_FUNC hpe1429_cmdInt32Arr_Q(ViSession vi, ViString p1, ViInt32 p2, scpi command p2 - integer parameter */ -ViStatus _VI_FUNC hpe1429_cmdInt(ViSession vi, ViString p1, ViInt32 p2) { +ViStatus _VI_FUNC hpe1429_cmdInt(ViSession vi, ViString p1, ViInt32 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -2305,7 +2434,8 @@ ViStatus _VI_FUNC hpe1429_cmdInt(ViSession vi, ViString p1, ViInt32 p2) { scpi command p2 - Real parameter */ -ViStatus _VI_FUNC hpe1429_cmdReal(ViSession vi, ViString p1, ViReal64 p2) { +ViStatus _VI_FUNC hpe1429_cmdReal(ViSession vi, ViString p1, ViReal64 p2) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -2328,7 +2458,8 @@ ViStatus _VI_FUNC hpe1429_cmdReal(ViSession vi, ViString p1, ViReal64 p2) { p1 - VI_TRUE if operations pending */ -ViStatus _VI_FUNC hpe1429_opc_Q(ViSession vi, ViPBoolean p1) { +ViStatus _VI_FUNC hpe1429_opc_Q(ViSession vi, ViPBoolean p1) +{ ViStatus errStatus; struct hpe1429_globals *thisPtr; @@ -2348,7 +2479,8 @@ ViStatus _VI_FUNC hpe1429_opc_Q(ViSession vi, ViPBoolean p1) { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } -ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) { +ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) +{ ViStatus errStatus; ViInt32 fetchCount; ViInt16 vmeMode, vmeSource; @@ -2356,7 +2488,8 @@ ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) { ViInt32 preCount, armCount; char idn_buf[256]; - if ((thisPtr->controler & 496) == 0) { /* no lbus/arm or vme bits set yet */ + if ((thisPtr->controler & 496) == 0) + { /* no lbus/arm or vme bits set yet */ errStatus = viPrintf(vi, "SWE:OFFS:POIN?\n"); if (errStatus < VI_SUCCESS) return errStatus; @@ -2375,7 +2508,8 @@ ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) { if (errStatus < VI_SUCCESS) return errStatus; - if ((armCount == 1) || (preCount == 0)) { + if ((armCount == 1) || (preCount == 0)) + { if ((errStatus = viPrintf(vi, "*IDN?\n")) < VI_SUCCESS) return errStatus; if ((errStatus = viScanf(vi, "%t", idn_buf)) < VI_SUCCESS) @@ -2384,14 +2518,16 @@ ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) { doDelay(thisPtr->myDelay); if (strncmp(idn_buf, "HEWLETT-PACKARD,E1429B", 22)) lbusMode = hpe1429_LBUS_OFF; - else { + else + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confLocalBus_Q(vi, &lbusMode, &lbusSource); if (errStatus < VI_SUCCESS) return errStatus; } - if (lbusMode == hpe1429_LBUS_OFF) { + if (lbusMode == hpe1429_LBUS_OFF) + { thisPtr->controler |= 16; thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confVME_Q(vi, &vmeMode, &vmeSource); @@ -2403,7 +2539,8 @@ ViStatus hpe1429_checkE1406(ViSession vi, struct hpe1429_globals *thisPtr) { } } } - if (thisPtr->controler & 16) { + if (thisPtr->controler & 16) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_cmdInt32_Q(vi, "FETC:COUN?", &fetchCount); if (errStatus < VI_SUCCESS) @@ -2421,7 +2558,8 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, #else ViInt16 _huge *fptr #endif -) { +) +{ ViStatus errStatus; ViStatus errStatus2; ViChar c[2]; @@ -2442,7 +2580,8 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, if (errStatus < VI_SUCCESS) return errStatus; - if (!(thisPtr->controler & 4096)) { + if (!(thisPtr->controler & 4096)) + { errStatus = hpe1429_checkE1406(vi, thisPtr); if (errStatus < VI_SUCCESS) return errStatus; @@ -2461,14 +2600,17 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, viSetAttribute(vi1406, VI_ATTR_TMO_VALUE, timeOut); errStatus = viClear(vi1406); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } - if (arrayLength > timeOut * 10) { + if (arrayLength > timeOut * 10) + { errStatus = viSetAttribute(vi1406, VI_ATTR_TMO_VALUE, arrayLength / 10); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } @@ -2481,26 +2623,33 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, vmeSource = (thisPtr->controler & 224) / 32; - switch (chan) { + switch (chan) + { case hpe1429_CHAN1: - if ((vmeMode == hpe1429_VME_OFF) || (vmeSource != hpe1429_VME_MEM_CHAN1)) { + if ((vmeMode == hpe1429_VME_OFF) || (vmeSource != hpe1429_VME_MEM_CHAN1)) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confVME(vi, hpe1429_VME_GEN, hpe1429_VME_MEM_CHAN1); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ hpe1429_confVME(vi, vmeMode, vmeSource); - } else + } + else gotit = 1; } break; case hpe1429_CHAN2: - if ((vmeMode == hpe1429_VME_OFF) || (vmeSource != hpe1429_VME_MEM_CHAN2)) { + if ((vmeMode == hpe1429_VME_OFF) || (vmeSource != hpe1429_VME_MEM_CHAN2)) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confVME(vi, hpe1429_VME_GEN, hpe1429_VME_MEM_CHAN2); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ hpe1429_confVME(vi, vmeMode, vmeSource); - } else + } + else gotit = 1; } break; @@ -2508,17 +2657,21 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, errStatus = VI_SUCCESS - 1; break; } - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } - if (gotit) { /* had to change VME--need to re-init it */ + if (gotit) + { /* had to change VME--need to re-init it */ ViInt16 bigdelay; - if (thisPtr && !(thisPtr->errQueryDetect)) { - thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ + if (thisPtr && !(thisPtr->errQueryDetect)) + { + thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_opc_Q(vi, &opc); /* let 1429 catch up */ - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } @@ -2526,7 +2679,8 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, errStatus = viPrintf(vi, "VINS:VME:MEM:INIT\n"); - if (thisPtr) { /* Give the 1429 about a millisecond to init */ + if (thisPtr) + { /* Give the 1429 about a millisecond to init */ for (bigdelay = 0; bigdelay < 10; bigdelay++) doDelay(thisPtr->myDelay); } @@ -2535,26 +2689,30 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, if (errStatus >= VI_SUCCESS) errStatus = viPrintf(vi1406, "DIAG:UPL:SADD? %ld, %ld\n", thisPtr->a24_addr + 0x0C, 2 * fetchCount); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } _ftime(&start_time); errStatus = viRead(vi1406, c, 2, &retbytes); /* Read Header #[1-9] */ - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } - if (retbytes != 2) { + if (retbytes != 2) + { viScanf(vi1406, "%*t"); /* Clear input. */ viClose(vi1406); return VI_ERROR_INV_RESPONSE; } digits = c[1] - '0'; - if ((digits < 1) || (9 < digits)) { + if ((digits < 1) || (9 < digits)) + { viScanf(vi1406, "%*t"); /* Clear input. */ viClose(vi1406); return VI_ERROR_INV_RESPONSE; @@ -2562,11 +2720,13 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* Scan DAB array count. */ errStatus = viRead(vi1406, length_str, digits, &retbytes); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); return errStatus; } - if (retbytes != digits) { + if (retbytes != digits) + { viScanf(vi1406, "%*t"); /* Clear input. */ viClose(vi1406); return VI_ERROR_INV_RESPONSE; @@ -2576,7 +2736,8 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, *nbytes = strtol(length_str, NULL, 0); /* Verify that caller's array is big enough. */ - if (((ViUInt32)arrayLength * 2) < *nbytes) { + if (((ViUInt32)arrayLength * 2) < *nbytes) + { viScanf(vi1406, "%*t"); /* Clear input. */ viClose(vi1406); return VI_ERROR_PARAMETER3; /* Caller's array too small. */ @@ -2595,9 +2756,11 @@ ViStatus hpe1429_fetcE1406(ViSession vi, ViInt16 chan, ViInt32 arrayLength, viClose(vi1406); errStatus = VI_SUCCESS; - if (gotit & 1) { /* VME has been changed--change it back */ + if (gotit & 1) + { /* VME has been changed--change it back */ errStatus = viPrintf(vi, "ABOR\n"); /* Just in case transfer not complete */ - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confVME(vi, vmeMode, vmeSource); } @@ -2617,7 +2780,8 @@ ViStatus hpe1429_fetcSCPI(ViSession vi, ViInt16 chan, ViInt32 arrayLength, #else ViInt16 _huge *fptr #endif -) { +) +{ ViStatus errStatus; ViChar c[2]; ViUInt32 digits; @@ -2631,7 +2795,8 @@ ViStatus hpe1429_fetcSCPI(ViSession vi, ViInt16 chan, ViInt32 arrayLength, errStatus = viRead(vi, c, 2, &retbytes); /* Read Header (should be #[1-9] */ if (errStatus < VI_SUCCESS) return errStatus; - if (retbytes != 2) { + if (retbytes != 2) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ if (thisPtr) doDelay(thisPtr->myDelay); @@ -2639,7 +2804,8 @@ ViStatus hpe1429_fetcSCPI(ViSession vi, ViInt16 chan, ViInt32 arrayLength, } digits = c[1] - '0'; - if ((digits < 1) || (9 < digits)) { + if ((digits < 1) || (9 < digits)) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ if (thisPtr) doDelay(thisPtr->myDelay); @@ -2650,7 +2816,8 @@ ViStatus hpe1429_fetcSCPI(ViSession vi, ViInt16 chan, ViInt32 arrayLength, errStatus = viRead(vi, length_str, digits, &retbytes); if (errStatus < VI_SUCCESS) return errStatus; - if (retbytes != digits) { + if (retbytes != digits) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ if (thisPtr) doDelay(thisPtr->myDelay); @@ -2661,7 +2828,8 @@ ViStatus hpe1429_fetcSCPI(ViSession vi, ViInt16 chan, ViInt32 arrayLength, *nbytes = strtol(length_str, NULL, 0); /* Verify that caller's array is big enough. */ - if (((ViUInt32)arrayLength * 2) < *nbytes) { + if (((ViUInt32)arrayLength * 2) < *nbytes) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ if (thisPtr) doDelay(thisPtr->myDelay); @@ -2709,8 +2877,9 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, base_addr = (char *)baseAddr; thisPtr->a24_addr = (long)baseAddr; - if (!(thisPtr->controler & 16384)) { /* SCPI INIT doesn't need this */ - /* + if (!(thisPtr->controler & 16384)) + { /* SCPI INIT doesn't need this */ + /* * This section sets up the traffic register and variables so that * memory is configured to be read. * @@ -2750,7 +2919,8 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* check to see if we wrapped around, and if we did, get most recent */ /* readings. */ - if (was_wrapped > 0) { + if (was_wrapped > 0) + { start_addr = last_addr - trig_count + 1; if (start_addr < seg_start_addr) /* we are in middle of buffer */ start_addr += trig_count; @@ -2806,7 +2976,8 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* Change the clock source to be the data register, and set up the final data */ /* source. */ - switch (chan) { + switch (chan) + { case hpe1429_CHAN1: poke1429b(base_addr + traffic, DATA_SRC_MEM | CLK_SRC_REG | DATA_CHAN1); break; @@ -2820,7 +2991,8 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* Now read the data */ #ifdef WIN32 - if (thisPtr->controler & 65536) { /* User has turned off block xfer */ + if (thisPtr->controler & 65536) + { /* User has turned off block xfer */ #else /* Windows 3.1 does not always have block move -- use single xfers */ #endif @@ -2830,7 +3002,8 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, #ifdef WIN32 } - else { + else + { /* WIN32 has block move */ viUnmapAddress(vi); errStatus = @@ -2848,7 +3021,8 @@ ViStatus hpe1429_fetcFast(ViSession vi, ViInt16 chan, ViInt32 arrayLength, return VI_SUCCESS; } -ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) { +ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) +{ uint8 div_by = (uint8)((thisPtr->controler >> 5) & 7); uint8 the_power = (uint8)((thisPtr->controler >> 8) & 15); int32 trigCount = thisPtr->trigs_per_arm; @@ -2894,10 +3068,13 @@ ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) { posprecount = thisPtr->precount; if (posprecount < 0) posprecount = -posprecount; - if (posprecount > 0) { + if (posprecount > 0) + { poke1429b(base_addr + trig_pre_lsb, (uint8)(posprecount - 2)); poke1429b(base_addr + trig_pre_msb, (uint8)((posprecount - 2) >> 8)); - } else { + } + else + { poke1429b(base_addr + trig_pre_lsb, 1); poke1429b(base_addr + trig_pre_msb, 0); } @@ -2923,10 +3100,13 @@ ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) { poke1429b(base_addr + refdiv_amount, 129); /* turn clk+ output off */ poke1429b(base_addr + refdiv_power, 255); - if (the_power == 8) { + if (the_power == 8) + { ref_power = 0; refbase = 129; - } else { + } + else + { refbase = 128; ref_power = (uint8)(1 << the_power); } @@ -2955,9 +3135,10 @@ ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) { poke1429b(base_addr + tb_load_acount, 0); poke1429b(base_addr + tb_init, 0); /* send initiate pulse */ - do { + do + { temp_reg = peek1429b(base_addr + tb_stat); - ++counter; /* this keeps the compiler from being "too efficient" */ + ++counter; /* this keeps the compiler from being "too efficient" */ } while (temp_reg & 0x2); /* loop until bit 1-timebase status low */ { @@ -2971,7 +3152,8 @@ ViStatus hpe1429_fastInit(char *base_addr, struct hpe1429_globals *thisPtr) { return VI_SUCCESS; } -void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { +void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) +{ /* Fast init/access will be enabled if and only if: * ARM:COUN == 1 **** TRIG:SOUR == TIMER -- Removed in Revision A.02.02 *** @@ -2996,24 +3178,30 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits Bit 13 */ errStatus = hpe1429_cmdInt32_Q(vi, "ARM:COUN?", &armCount); - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { if (armCount != 1) errStatus = VI_SUCCESS - 1; /* don't support non arm==1 */ } - if (errStatus >= VI_SUCCESS) { - if ((errStatus = viPrintf(vi, "*IDN?\n")) >= VI_SUCCESS) { - if ((errStatus = viScanf(vi, "%t", idn_buf)) >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { + if ((errStatus = viPrintf(vi, "*IDN?\n")) >= VI_SUCCESS) + { + if ((errStatus = viScanf(vi, "%t", idn_buf)) >= VI_SUCCESS) + { if (thisPtr) doDelay(thisPtr->myDelay); if (strncmp(idn_buf, "HEWLETT-PACKARD,E1429B", 22)) lbusMode = hpe1429_LBUS_OFF; - else { + else + { if (thisPtr) doDelay(thisPtr->myDelay); thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_confLocalBus_Q(vi, &lbusMode, &lbusSource); - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { if (lbusMode != hpe1429_LBUS_OFF) errStatus = (VI_SUCCESS - 1); } @@ -3022,7 +3210,8 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { } } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { ViInt32 trigs; thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_cmdInt32_Q(vi, "SENS:SWE:POIN?", &trigs); @@ -3031,7 +3220,8 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { errStatus = VI_SUCCESS - 1; } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { ViInt32 offset; ViInt16 goOn; @@ -3062,31 +3252,39 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { if (offset != 0) goOn = 0; - if (goOn) { + if (goOn) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_cmdString_Q(vi, "ROSC:SOUR?", 31, answer); - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { if ((answer[0] != 'I') && ((answer[0] != '"') || (answer[1] != 'I'))) goOn = 0; /* don't support non INT rosc sour */ - } else + } + else goOn = 0; } if (goOn && (!(thisPtr->controler & 0x00008000)) && - ((thisPtr->trigs_per_arm * trigTimer1) < 1.0)) { + ((thisPtr->trigs_per_arm * trigTimer1) < 1.0)) + { thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_cmdString_Q(vi, "ARM:SOUR1?", 31, answer); - if ((errStatus >= VI_SUCCESS) && (answer[2] == 'M')) { /* IMM arm sour */ + if ((errStatus >= VI_SUCCESS) && (answer[2] == 'M')) + { /* IMM arm sour */ ViInt32 ratio = (ViInt32)((trigTimer1 / 0.00000005) + .2); ViInt16 the_power = 0; - while (ratio > 9) { + while (ratio > 9) + { ratio /= 10; the_power++; } if (the_power > 8) errStatus = VI_SUCCESS - 1; /* something bad happened */ - else { - switch ((ViInt16)ratio) { + else + { + switch ((ViInt16)ratio) + { case 1: case 2: case 4: @@ -3109,11 +3307,14 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { { ViAddr base_addr; if (VI_SUCCESS <= viMapAddress(vi, VI_A24_SPACE, 0x00, 0xFF, VI_FALSE, - VI_NULL, &base_addr)) { + VI_NULL, &base_addr)) + { ViUInt16 kind; thisPtr->a24_addr = (long)base_addr; - if (VI_SUCCESS <= viGetAttribute(vi, VI_ATTR_WIN_ACCESS, &kind)) { - switch (kind) { + if (VI_SUCCESS <= viGetAttribute(vi, VI_ATTR_WIN_ACCESS, &kind)) + { + switch (kind) + { case VI_USE_OPERS: thisPtr->controler |= 1; break; /* VX_LINK */ @@ -3124,21 +3325,25 @@ void hpe1429_checkEmbedded(ViSession vi, struct hpe1429_globals *thisPtr) { break; /* access problem */ } thisPtr->controler &= 0xFFFFFFF7; /* 0 the not-mapped bit Bit 3 */ - } else + } + else thisPtr->controler = 0; /* access problem */ viUnmapAddress(vi); - } else + } + else thisPtr->controler = 0; /* access problem */ } if (thisPtr->controler) thisPtr->controler |= 4096; /* set "checked" bit */ } -ViStatus _VI_FUNC hpe1429_1406time(ViSession vi, ViPReal64 time) { +ViStatus _VI_FUNC hpe1429_1406time(ViSession vi, ViPReal64 time) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } if ((thisPtr->controler & 4115) == 4113) @@ -3178,8 +3383,9 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, base_addr = (char *)baseAddr; thisPtr->a24_addr = (long)baseAddr; - if (!(thisPtr->controler & 16384)) { /* SCPI INIT doesn't need this */ - /* + if (!(thisPtr->controler & 16384)) + { /* SCPI INIT doesn't need this */ + /* * This section sets up the traffic register and variables so that * memory is configured to be read. * @@ -3222,7 +3428,8 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* check to see if we wrapped around, and if we did, get most recent */ /* readings. */ - if (was_wrapped > 0) { + if (was_wrapped > 0) + { start_addr = last_addr - trig_count + 1; if (start_addr < seg_start_addr) /* we are in middle of buffer */ start_addr += trig_count; @@ -3278,7 +3485,8 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* Change the clock source to be the data register, and set up the final data */ /* source. */ - switch (chan) { + switch (chan) + { case hpe1429_CHAN1: linkbpoke(base_addr + traffic, DATA_SRC_MEM | CLK_SRC_REG | DATA_CHAN1); break; @@ -3292,11 +3500,13 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, /* Now read the data */ #ifdef WIN32 - if (thisPtr->controler & 65536) { /* User has disabled block xfer */ + if (thisPtr->controler & 65536) + { /* User has disabled block xfer */ #else /* Windows 3.1 does not always have block move -- use single xfers */ #endif - for (i = 0; i < trig_count; i++) { + for (i = 0; i < trig_count; i++) + { viPeek16(vi, (ViAddr)(base_addr + reading), &data); fptr[i] = data; } @@ -3304,7 +3514,8 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, #ifdef WIN32 } - else { + else + { /* WIN32 has block move */ viUnmapAddress(vi); errStatus = @@ -3323,7 +3534,8 @@ ViStatus hpe1429_fetcLINK(ViSession vi, ViInt16 chan, ViInt32 arrayLength, } ViStatus hpe1429_LINKInit(ViSession vi, char *base_addr, - struct hpe1429_globals *thisPtr) { + struct hpe1429_globals *thisPtr) +{ uint8 div_by = (uint8)((thisPtr->controler >> 5) & 7); uint8 the_power = (uint8)((thisPtr->controler >> 8) & 15); int32 trigCount = thisPtr->trigs_per_arm; @@ -3369,10 +3581,13 @@ ViStatus hpe1429_LINKInit(ViSession vi, char *base_addr, posprecount = thisPtr->precount; if (posprecount < 0) posprecount = -posprecount; - if (posprecount > 0) { + if (posprecount > 0) + { linkbpoke(base_addr + trig_pre_lsb, (uint8)(posprecount - 2)); linkbpoke(base_addr + trig_pre_msb, (uint8)((posprecount - 2) >> 8)); - } else { + } + else + { linkbpoke(base_addr + trig_pre_lsb, 1); linkbpoke(base_addr + trig_pre_msb, 0); } @@ -3399,10 +3614,13 @@ ViStatus hpe1429_LINKInit(ViSession vi, char *base_addr, linkbpoke(base_addr + refdiv_amount, 129); /* turn clk+ output off */ linkbpoke(base_addr + refdiv_power, 255); - if (the_power == 8) { + if (the_power == 8) + { ref_power = 0; refbase = 129; - } else { + } + else + { refbase = 128; ref_power = (uint8)(1 << the_power); } @@ -3431,9 +3649,10 @@ ViStatus hpe1429_LINKInit(ViSession vi, char *base_addr, linkbpoke(base_addr + tb_load_acount, 0); linkbpoke(base_addr + tb_init, 0); /* send initiate pulse */ - do { + do + { viPeek8(vi, (ViAddr)(base_addr + tb_stat), &temp_reg); - ++counter; /* this keeps the compiler from being "too efficient" */ + ++counter; /* this keeps the compiler from being "too efficient" */ } while (temp_reg & 0x2); /* loop until bit 1-timebase status low */ { @@ -3452,20 +3671,23 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, ViPInt32 checkTest, ViPInt32 numHits, ViInt32 arrayLength, ViInt16 _VI_FAR data[], - ViInt16 errData[]) { + ViInt16 errData[]) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; *checkTest = -1; *numHits = 0; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } hpe1429_DEBUG_CHK_THIS(vi, thisPtr); hpe1429_CDE_INIT("hpe1429_fetcCheck_Q"); - if (((chan & 3) < 1) || ((chan & 3) > 2)) { + if (((chan & 3) < 1) || ((chan & 3) > 2)) + { *checkTest = -2; hpe1429_LOG_STATUS(vi, 0, VI_ERROR_PARAMETER2); } @@ -3474,7 +3696,8 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, hpe1429_FETC_SIZE_MAX, VI_ERROR_PARAMETER4); *checkTest = 0; - if (!(chan & 4)) { + if (!(chan & 4)) + { if (arrayLength <= 500) *checkTest = -5; if ((thisPtr->controler & 3) == 0) @@ -3498,7 +3721,8 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, fptr = (ViInt16 _huge *)data; #endif - if (*checkTest == 0) { + if (*checkTest == 0) + { #ifdef WIN32 Wfy2 = (ViInt16 *)malloc((long)arrayLength * sizeof(ViInt16)); #else @@ -3506,16 +3730,21 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, #endif if (Wfy2 == NULL) *checkTest = -7; - else { - if (chan & 8) { + else + { + if (chan & 8) + { controlerWas = thisPtr->controler; precountWas = thisPtr->precount; thisPtr->controler = 0; } - if (chan & 4) { /* Send a test pattern into the e1429 */ + if (chan & 4) + { /* Send a test pattern into the e1429 */ char cmd[32]; sprintf(cmd, "DIAG:MEM%hd:FILL 1, %ld", chan & 3, arrayLength); - { errStatus = viPrintf(vi, "%s\n", cmd); } + { + errStatus = viPrintf(vi, "%s\n", cmd); + } thisPtr->controler &= 0xFFFFBFFF; /* clear theSCPI init bit */ } @@ -3526,7 +3755,8 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, errData[(int)j] = -32767; errStatus = hpe1429_fetc_Q(vi, (ViInt16)(chan & 3), arrayLength, Wfy2); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { #ifdef WIN32 free(Wfy2); #else @@ -3539,7 +3769,8 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, } if (chan & 8) thisPtr->controler = controlerWas; - else { + else + { controlerWas = thisPtr->controler; thisPtr->controler = 0; precountWas = thisPtr->precount; @@ -3550,11 +3781,14 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, errStatus = hpe1429_fetc_Q(vi, (ViInt16)(chan & 3), arrayLength, fptr); thisPtr->controler = controlerWas; thisPtr->precount = precountWas; - if (*checkTest == 0) { + if (*checkTest == 0) + { ViInt32 nextoff = 0; - if (chan & 4) { + if (chan & 4) + { ViInt16 shouldBe; - for (i = 0; i < arrayLength; i++) { + for (i = 0; i < arrayLength; i++) + { shouldBe = ((ViInt16)((i + 1) % 2000)) << 4; if (fptr[i] != shouldBe) *checkTest = i - 5999999; @@ -3562,7 +3796,8 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, if (Wfy2[i] != shouldBe) *checkTest = i - 6999999; - if (*checkTest) { + if (*checkTest) + { if ((ViInt32)MAXerrData > (arrayLength - i)) MAXerrData = (ViInt16)(arrayLength - i); for (j = 0; j < MAXerrData; j++) @@ -3570,14 +3805,21 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, i = arrayLength; } } - } else { - for (i = 0; i < arrayLength; i++) { - if (fptr[i] != Wfy2[i]) { + } + else + { + for (i = 0; i < arrayLength; i++) + { + if (fptr[i] != Wfy2[i]) + { (*numHits)++; - if (*checkTest) { + if (*checkTest) + { if (!nextoff) nextoff = i; - } else { + } + else + { if ((ViInt32)MAXerrData > (arrayLength - i)) MAXerrData = (ViInt16)(arrayLength - i); for (j = 0; j < MAXerrData; j++) @@ -3587,13 +3829,17 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, } } } - if (*checkTest) { /* something errored -- check more details */ - if (nextoff == *checkTest) { + if (*checkTest) + { /* something errored -- check more details */ + if (nextoff == *checkTest) + { /* The next point is bad too */ /* Try an off-by-one check */ ViInt32 moreHits = 1; nextoff = 999999; - for (i = *checkTest; i < arrayLength; i++) { - if (fptr[i - 1] != Wfy2[i]) { + for (i = *checkTest; i < arrayLength; i++) + { + if (fptr[i - 1] != Wfy2[i]) + { moreHits++; if (!nextoff) nextoff = i; @@ -3602,11 +3848,14 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, if (moreHits < *numHits) *numHits = moreHits; /* better this way */ if ((nextoff - 10) <= - *checkTest) { /* Not off that way, try the other */ + *checkTest) + { /* Not off that way, try the other */ moreHits = 1; nextoff = 999999; - for (i = *checkTest; i < arrayLength; i++) { - if (fptr[i] != Wfy2[i - 1]) { + for (i = *checkTest; i < arrayLength; i++) + { + if (fptr[i] != Wfy2[i - 1]) + { moreHits++; if (!nextoff) nextoff = i; @@ -3614,13 +3863,16 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, } if (moreHits < *numHits) *numHits = moreHits; - if ((nextoff - 10) > *checkTest) { /* it was off by 1 */ - if (nextoff == 999999) /*purely off by 1 */ + if ((nextoff - 10) > *checkTest) + { /* it was off by 1 */ + if (nextoff == 999999) /*purely off by 1 */ *checkTest -= 2000000; else /* some more points bad */ *checkTest -= 3000000; } - } else { /* it was off by 1 */ + } + else + { /* it was off by 1 */ if (nextoff == 999999) /*purely off by 1 */ *checkTest -= 4000000; @@ -3661,12 +3913,14 @@ ViStatus _VI_FUNC hpe1429_fetcCheck_Q(ViSession vi, ViInt16 chan, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_A24(ViSession vi, ViPInt32 a24_addr) { +ViStatus _VI_FUNC hpe1429_A24(ViSession vi, ViPInt32 a24_addr) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -3724,12 +3978,14 @@ ViStatus _VI_FUNC hpe1429_A24(ViSession vi, ViPInt32 a24_addr) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_HighSpeedStatus(ViSession vi, ViPInt32 status) { +ViStatus _VI_FUNC hpe1429_HighSpeedStatus(ViSession vi, ViPInt32 status) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -3763,12 +4019,14 @@ ViStatus _VI_FUNC hpe1429_HighSpeedStatus(ViSession vi, ViPInt32 status) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_abor(ViSession vi) { +ViStatus _VI_FUNC hpe1429_abor(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -3776,7 +4034,8 @@ ViStatus _VI_FUNC hpe1429_abor(ViSession vi) { hpe1429_CDE_INIT("hpe1429_abor"); errStatus = viPrintf(vi, "ABOR\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -3818,12 +4077,14 @@ ViStatus _VI_FUNC hpe1429_abor(ViSession vi) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_armStarDel(ViSession vi, ViPReal64 armStarDel) { +ViStatus _VI_FUNC hpe1429_armStarDel(ViSession vi, ViPReal64 armStarDel) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -3834,7 +4095,8 @@ ViStatus _VI_FUNC hpe1429_armStarDel(ViSession vi, ViPReal64 armStarDel) { hpe1429_ARM_STAR_DEL_MAX, VI_ERROR_PARAMETER2); errStatus = viPrintf(vi, "ARM:STAR:DEL %g\n", *armStarDel); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -3865,12 +4127,14 @@ ViStatus _VI_FUNC hpe1429_armStarDel(ViSession vi, ViPReal64 armStarDel) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_armStarDel_Q(ViSession vi, ViPReal64 armStarDel) { +ViStatus _VI_FUNC hpe1429_armStarDel_Q(ViSession vi, ViPReal64 armStarDel) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -3879,14 +4143,16 @@ ViStatus _VI_FUNC hpe1429_armStarDel_Q(ViSession vi, ViPReal64 armStarDel) { thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "ARM:STAR:DEL?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", armStarDel); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -3979,20 +4245,22 @@ ViStatus _VI_FUNC hpe1429_armStarDel_Q(ViSession vi, ViPReal64 armStarDel) { *----------------------------------------------------------------------------- */ static const char *const hpe1429_armStarEvent_source_a[] = { - "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", + "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", - "EXT", "INT1", "INT2", "IMM", 0}; + "EXT", "INT1", "INT2", "IMM", 0}; static const char *const hpe1429_armStarEvent_slope_a[] = {"POS", "NEG", "EITH", 0}; ViStatus _VI_FUNC hpe1429_armStarEvent(ViSession vi, ViInt16 event, - ViInt16 source, ViInt16 slope) { + ViInt16 source, ViInt16 slope) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4007,13 +4275,15 @@ ViStatus _VI_FUNC hpe1429_armStarEvent(ViSession vi, ViInt16 event, { errStatus = viPrintf(vi, "ARM:SOUR%hd %s\n", event, hpe1429_armStarEvent_source_a[source]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "ARM:SLOP%hd %s\n", event, hpe1429_armStarEvent_slope_a[slope]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4063,22 +4333,24 @@ ViStatus _VI_FUNC hpe1429_armStarEvent(ViSession vi, ViInt16 event, *----------------------------------------------------------------------------- */ static const char *const hpe1429_armStarEvent_Q_source_a[] = { - "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", + "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", - "EXT", "INT1", "INT2", "IMM", 0}; + "EXT", "INT1", "INT2", "IMM", 0}; static const char *const hpe1429_armStarEvent_Q_slope_a[] = {"POS", "NEG", "EITH", 0}; ViStatus _VI_FUNC hpe1429_armStarEvent_Q(ViSession vi, ViInt16 event, - ViPInt16 source, ViPInt16 slope) { + ViPInt16 source, ViPInt16 slope) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; char source_str[32]; char slope_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4091,50 +4363,59 @@ ViStatus _VI_FUNC hpe1429_armStarEvent_Q(ViSession vi, ViInt16 event, { thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "ARM:SOUR%hd?\n", event); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", source_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_armStarEvent_Q_source_a, source_str, source); - if (errStatus < VI_SUCCESS) { /* could be INT or INTERNAL2 */ + if (errStatus < VI_SUCCESS) + { /* could be INT or INTERNAL2 */ int quoted; quoted = 0; if (source_str[0] == '"') quoted = 1; if ((source_str[quoted] == 'I') && - (source_str[quoted + 1] == 'N')) { /*some INT */ - if (source_str[quoted + 3] == 'E') /* INTERNAL2 */ + (source_str[quoted + 1] == 'N')) + { /*some INT */ + if (source_str[quoted + 3] == 'E') /* INTERNAL2 */ *source = 14; else /* INT */ *source = 13; - } else { + } + else + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } errStatus = viPrintf(vi, "ARM:SLOP%hd?\n", event); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", slope_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_armStarEvent_Q_slope_a, slope_str, slope); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4163,12 +4444,14 @@ ViStatus _VI_FUNC hpe1429_armStarEvent_Q(ViSession vi, ViInt16 event, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_armStarImm(ViSession vi) { +ViStatus _VI_FUNC hpe1429_armStarImm(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4177,7 +4460,8 @@ ViStatus _VI_FUNC hpe1429_armStarImm(ViSession vi) { { errStatus = viPrintf(vi, "ARM\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ @@ -4238,12 +4522,14 @@ ViStatus _VI_FUNC hpe1429_armStarImm(ViSession vi) { static const char *const hpe1429_armStarLevels_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_armStarLevels(ViSession vi, ViInt16 chan, - ViReal64 negative, ViReal64 positive) { + ViReal64 negative, ViReal64 positive) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4259,7 +4545,8 @@ ViStatus _VI_FUNC hpe1429_armStarLevels(ViSession vi, ViInt16 chan, errStatus = viPrintf(vi, "ARM:STAR:LEV%s:NEG %g;POS %g\n", hpe1429_armStarLevels_chan_a[chan], negative, positive); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4301,12 +4588,14 @@ static const char *const hpe1429_armStarLevels_Q_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_armStarLevels_Q(ViSession vi, ViInt16 chan, ViPReal64 negative, - ViPReal64 positive) { + ViPReal64 positive) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4317,28 +4606,32 @@ ViStatus _VI_FUNC hpe1429_armStarLevels_Q(ViSession vi, ViInt16 chan, thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "ARM:LEV%s:NEG?\n", hpe1429_armStarLevels_Q_chan_a[chan]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", negative); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "ARM:LEV%s:POS?\n", hpe1429_armStarLevels_Q_chan_a[chan]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", positive); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4400,12 +4693,14 @@ static const char *const hpe1429_calZero_chan_a[] = {"", "1", "2", 0}; static const char *const hpe1429_calZero_mode_a[] = {"ALL", "ONE", 0}; ViStatus _VI_FUNC hpe1429_calZero(ViSession vi, ViInt16 chan, ViInt32 readings, - ViReal64 period, ViInt16 mode) { + ViReal64 period, ViInt16 mode) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4423,7 +4718,8 @@ ViStatus _VI_FUNC hpe1429_calZero(ViSession vi, ViInt16 chan, ViInt32 readings, errStatus = viPrintf(vi, "CAL%s:ZERO %ld, %g, %s\n", hpe1429_calZero_chan_a[chan], readings, period, hpe1429_calZero_mode_a[mode]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4579,12 +4875,14 @@ static const char *const hpe1429_confLocalBus_source_a[] = {"\"MEM:CHAN1\"", 0}; ViStatus _VI_FUNC hpe1429_confLocalBus(ViSession vi, ViInt16 mode, - ViInt16 source) { + ViInt16 source) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4596,7 +4894,8 @@ ViStatus _VI_FUNC hpe1429_confLocalBus(ViSession vi, ViInt16 mode, errStatus = viPrintf(vi, "VINS:LBUS:MODE %s;FEED %s\n", hpe1429_confLocalBus_mode_a[mode], hpe1429_confLocalBus_source_a[source]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4646,14 +4945,16 @@ static const char *const hpe1429_confLocalBus_Q_source_a[] = {"\"MEM:CHAN1\"", 0}; ViStatus _VI_FUNC hpe1429_confLocalBus_Q(ViSession vi, ViPInt16 mode, - ViPInt16 source) { + ViPInt16 source) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; char mode_str[32]; char source_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4663,38 +4964,44 @@ ViStatus _VI_FUNC hpe1429_confLocalBus_Q(ViSession vi, ViPInt16 mode, { thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "VINS:LBUS?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", mode_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_confLocalBus_Q_mode_a, mode_str, mode); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "VINS:LBUS:FEED?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", source_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_confLocalBus_Q_source_a, source_str, source); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4822,16 +5129,18 @@ ViStatus _VI_FUNC hpe1429_confLocalBus_Q(ViSession vi, ViPInt16 mode, static const char *const hpe1429_confVME_mode_a[] = {"OFF", "GEN", 0}; static const char *const hpe1429_confVME_source_a[] = { - "\"MEM:CHAN1\"", "\"MEM:CHAN2\"", "\"MEM:BOTH\"", - "\"MEM:BOTH32\"", "\"CONV:CHAN1\"", "\"CONV:CHAN2\"", - "\"CONV:BOTH\"", "\"CONV:BOTH32\"", 0}; + "\"MEM:CHAN1\"", "\"MEM:CHAN2\"", "\"MEM:BOTH\"", + "\"MEM:BOTH32\"", "\"CONV:CHAN1\"", "\"CONV:CHAN2\"", + "\"CONV:BOTH\"", "\"CONV:BOTH32\"", 0}; -ViStatus _VI_FUNC hpe1429_confVME(ViSession vi, ViInt16 mode, ViInt16 source) { +ViStatus _VI_FUNC hpe1429_confVME(ViSession vi, ViInt16 mode, ViInt16 source) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4843,7 +5152,8 @@ ViStatus _VI_FUNC hpe1429_confVME(ViSession vi, ViInt16 mode, ViInt16 source) { errStatus = viPrintf(vi, "VINS:VME:MODE %s;FEED %s\n", hpe1429_confVME_mode_a[mode], hpe1429_confVME_source_a[source]); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -4882,19 +5192,21 @@ ViStatus _VI_FUNC hpe1429_confVME(ViSession vi, ViInt16 mode, ViInt16 source) { static const char *const hpe1429_confVME_Q_mode_a[] = {"OFF", "GEN", 0}; static const char *const hpe1429_confVME_Q_source_a[] = { - "\"MEM:CHAN1\"", "\"MEM:CHAN2\"", "\"MEM:BOTH\"", - "\"MEM:BOTH32\"", "\"CONV:CHAN1\"", "\"CONV:CHAN2\"", - "\"CONV:BOTH\"", "\"CONV:BOTH32\"", 0}; + "\"MEM:CHAN1\"", "\"MEM:CHAN2\"", "\"MEM:BOTH\"", + "\"MEM:BOTH32\"", "\"CONV:CHAN1\"", "\"CONV:CHAN2\"", + "\"CONV:BOTH\"", "\"CONV:BOTH32\"", 0}; ViStatus _VI_FUNC hpe1429_confVME_Q(ViSession vi, ViPInt16 mode, - ViPInt16 source) { + ViPInt16 source) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; char mode_str[32]; char source_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -4904,38 +5216,44 @@ ViStatus _VI_FUNC hpe1429_confVME_Q(ViSession vi, ViPInt16 mode, { thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "VINS:VME?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", mode_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_confVME_Q_mode_a, mode_str, mode); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "VINS:VME:FEED?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", source_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_findIndex(thisPtr, hpe1429_confVME_Q_source_a, source_str, source); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -5070,12 +5388,14 @@ static const char *const hpe1429_configure_port_a[] = {"SINGLE", "DIFFER", 0}; ViStatus _VI_FUNC hpe1429_configure(ViSession vi, ViInt16 chan, ViInt16 port, ViPReal64 expected, ViInt32 numTriggers, - ViInt32 preTriggers, ViInt32 numArms) { + ViInt32 preTriggers, ViInt32 numArms) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5104,7 +5424,8 @@ ViStatus _VI_FUNC hpe1429_configure(ViSession vi, ViInt16 chan, ViInt16 port, /* Use (chan+2*port) to translate user's port to instrument's port */ errStatus = viPrintf(vi, "CONF%hd:ARR (%ld),%lg,(@%hd)\n", chan, numTriggers, *expected, (chan + 2 * port)); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -5113,11 +5434,13 @@ ViStatus _VI_FUNC hpe1429_configure(ViSession vi, ViInt16 chan, ViInt16 port, /* instrument there is only one way. And giving the user a */ /* positive number is a better presentation--so convert it here. */ errStatus = viPrintf(vi, "SWE:OFFS:POIN %ld\n", (-preTriggers)); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "ARM:COUN %ld\n", numArms); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } @@ -5185,13 +5508,15 @@ static const char *const hpe1429_configure_Q_port_a[] = {"SINGLE", "DIFFER", 0}; ViStatus _VI_FUNC hpe1429_configure_Q(ViSession vi, ViInt16 chan, ViPInt16 port, ViPReal64 range, ViPInt32 numTriggers, - ViPInt32 preTriggers, ViPInt32 numArms) { + ViPInt32 preTriggers, ViPInt32 numArms) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; char port_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5206,66 +5531,79 @@ ViStatus _VI_FUNC hpe1429_configure_Q(ViSession vi, ViInt16 chan, ViPInt16 port, ViReal64 bigArm; thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "SENS%hd:FUNC?\n", chan); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%t", port_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SENS%hd:VOLT:RANG?\n", chan); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", range); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SENS:SWE:POIN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", &bigTrig); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SENS:SWE:OFFS:POIN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%ld%*t", preTriggers); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "ARM:COUN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", &bigArm); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } *port = 0; if (chan == - 1) { /* Find 1 or 3 port number & convert to Single / Diff enum */ + 1) + { /* Find 1 or 3 port number & convert to Single / Diff enum */ if (port_str[5] == '3') *port = 1; - } else { /* chan 2 - Find 2 or 4 port number & convert to Single / Diff enum + } + else + { /* chan 2 - Find 2 or 4 port number & convert to Single / Diff enum */ if (port_str[5] == '4') @@ -5278,7 +5616,7 @@ ViStatus _VI_FUNC hpe1429_configure_Q(ViSession vi, ViInt16 chan, ViPInt16 port, else *numTriggers = -1; /* This driver doesn't support INF triggers */ - if (bigArm < 18000000) /* The instrument could be set to 9.9E37 */ + if (bigArm < 18000000) /* The instrument could be set to 9.9E37 */ *numArms = (ViInt32)(bigArm + 0.1); /* add .1 to solve CVI round off */ else *numArms = -1; /* This driver doesn't support INF arms */ @@ -5319,12 +5657,14 @@ ViStatus _VI_FUNC hpe1429_configure_Q(ViSession vi, ViInt16 chan, ViPInt16 port, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_disableHighSpeed(ViSession vi, ViInt16 mask) { +ViStatus _VI_FUNC hpe1429_disableHighSpeed(ViSession vi, ViInt16 mask) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5335,17 +5675,20 @@ ViStatus _VI_FUNC hpe1429_disableHighSpeed(ViSession vi, ViInt16 mask) { VI_ERROR_PARAMETER2); { - switch (mask) { + switch (mask) + { case 0: thisPtr->controler = 0; break; case 2: - if (thisPtr->controler & 2) { + if (thisPtr->controler & 2) + { thisPtr->controler |= 0x00010000; } break; default: - if (thisPtr->controler & 2) { + if (thisPtr->controler & 2) + { thisPtr->controler &= 0xFFFFFFFB; thisPtr->controler |= 0x0000A000; } @@ -5406,12 +5749,14 @@ static const char *const hpe1429_fetcScal_Q_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_fetcScal_Q(ViSession vi, ViInt16 chan, ViInt32 arrayLength, - ViReal64 _VI_FAR data[]) { + ViReal64 _VI_FAR data[]) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5434,42 +5779,51 @@ ViStatus _VI_FUNC hpe1429_fetcScal_Q(ViSession vi, ViInt16 chan, thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "FORM REAL;:FETC%hd?\n", chan); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%2c", c); /* Read Header (should be #[1-9] */ - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { digits = c[1] - '0'; - if ((digits < 1) || (9 < digits)) { + if ((digits < 1) || (9 < digits)) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_INV_RESPONSE; } } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { /* Scan DAB array count. */ errStatus = viScanf(vi, "%#c", &digits, length_str); - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { length_str[digits] = '\0'; /* null terminate the string */ nbytes = strtol(length_str, NULL, 0); /* Verify that caller's array is big enough. */ - if (((ViUInt32)arrayLength * 8) < nbytes) { + if (((ViUInt32)arrayLength * 8) < nbytes) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_PARAMETER3; /* Caller's array too small. */ } } } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { sprintf(fmtStr, "%%%ldc%%*t", nbytes); errStatus = viScanf(vi, fmtStr, (unsigned char *)data); #ifndef B_ENDIAN /* need byte swapping */ - if (errStatus >= VI_SUCCESS) { - for (i = 0; i < (ViInt32)(nbytes / 8); i++) { + if (errStatus >= VI_SUCCESS) + { + for (i = 0; i < (ViInt32)(nbytes / 8); i++) + { *((ViReal64 *)src) = *((ViReal64 *)(&data[i])); ((unsigned char *)(&data[i]))[0] = ((unsigned char *)(src))[7]; ((unsigned char *)(&data[i]))[1] = ((unsigned char *)(src))[6]; @@ -5485,7 +5839,8 @@ ViStatus _VI_FUNC hpe1429_fetcScal_Q(ViSession vi, ViInt16 chan, } if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ @@ -5547,12 +5902,14 @@ ViStatus _VI_FUNC hpe1429_fetcScal_Q(ViSession vi, ViInt16 chan, static const char *const hpe1429_fetc_Q_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, - ViInt32 arrayLength, ViInt16 _VI_FAR data[]) { + ViInt32 arrayLength, ViInt16 _VI_FAR data[]) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5580,10 +5937,12 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, gotit = 0; - if (arrayLength > 500) { + if (arrayLength > 500) + { if (((thisPtr->controler & 26) == 18) || ((thisPtr->controler & 19) == 17) || - ((thisPtr->controler & 4099) == 1)) { /* wait for done */ + ((thisPtr->controler & 4099) == 1)) + { /* wait for done */ /* This section makes sure the e1429 is idle before fetching data */ ViInt32 operCond; ViBoolean opc; @@ -5594,7 +5953,8 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, struct _timeb start_time, tic_time, now_time; errStatus = viGetAttribute(vi, VI_ATTR_TMO_VALUE, &timeOut); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } if (timeOut < 2000000.0) @@ -5607,21 +5967,26 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_opc_Q(vi, &opc); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } digits = 0; _ftime(&start_time); - while (digits < burnMore) { - thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ + while (digits < burnMore) + { + thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ errStatus = hpe1429_operCond_Q(vi, &operCond); /* check idle */ - thisPtr->controler &= 0xFFFFDFFF; /* Clear Flag if operCond doesn't */ - if (errStatus < VI_SUCCESS) { + thisPtr->controler &= 0xFFFFDFFF; /* Clear Flag if operCond doesn't */ + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (operCond) { /* busy, burn time */ + if (operCond) + { /* busy, burn time */ _ftime(&tic_time); - for (operCond = 0; operCond < burnTime; operCond++) { + for (operCond = 0; operCond < burnTime; operCond++) + { _ftime(&now_time); if (((now_time.time + 0.001 * now_time.millitm) - (tic_time.time + 0.001 * tic_time.millitm)) > 0.001) @@ -5633,18 +5998,21 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, (start_time.time + 0.001 * start_time.millitm)) > timeOut) & (timeOut > 1)) digits = burnMore; /* exit while loop early */ - } else + } + else digits = burnMore; digits++; } - if (operCond) { /* not idle yet */ + if (operCond) + { /* not idle yet */ hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_TMO); } } } if (((thisPtr->controler & 26) == 18) && - (arrayLength > 500)) { /* mapped embedded */ + (arrayLength > 500)) + { /* mapped embedded */ if (thisPtr->controler & 1) errStatus = hpe1429_fetcLINK(vi, chan, arrayLength, &nbytes, thisPtr, fptr); @@ -5653,47 +6021,58 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, hpe1429_fetcFast(vi, chan, arrayLength, &nbytes, thisPtr, fptr); if (errStatus >= VI_SUCCESS) gotit = 6; - else { - if (errStatus == VI_ERROR_PARAMETER3) { + else + { + if (errStatus == VI_ERROR_PARAMETER3) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } } - if (((thisPtr->controler & 3) == 1) && (arrayLength > 500)) { /* hpe1406 */ - if ((thisPtr->controler & 16) || (!(thisPtr->controler & 4096))) { + if (((thisPtr->controler & 3) == 1) && (arrayLength > 500)) + { /* hpe1406 */ + if ((thisPtr->controler & 16) || (!(thisPtr->controler & 4096))) + { errStatus = hpe1429_fetcE1406(vi, chan, arrayLength, &nbytes, thisPtr, fptr); if (errStatus >= VI_SUCCESS) gotit = 2; - else { + else + { if ((errStatus == VI_ERROR_PARAMETER3) || - (errStatus == VI_ERROR_TMO)) { + (errStatus == VI_ERROR_TMO)) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } } } - if (gotit < 2) { /* Something above failed--try FETCH way */ + if (gotit < 2) + { /* Something above failed--try FETCH way */ errStatus = hpe1429_fetcSCPI(vi, chan, arrayLength, &nbytes, thisPtr, fptr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } #ifndef B_ENDIAN /* need byte swapping */ - if ((errStatus >= VI_SUCCESS) && (gotit < 6)) { /* don't swap embedded */ - for (i = 0; i < (ViInt32)(nbytes / 2); i++) { + if ((errStatus >= VI_SUCCESS) && (gotit < 6)) + { /* don't swap embedded */ + for (i = 0; i < (ViInt32)(nbytes / 2); i++) + { *((ViInt16 *)src) = *((ViInt16 *)(&fptr[i])); ((unsigned char *)(&fptr[i]))[0] = ((unsigned char *)(src))[1]; ((unsigned char *)(&fptr[i]))[1] = ((unsigned char *)(src))[0]; } } #endif - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ @@ -5722,12 +6101,14 @@ ViStatus _VI_FUNC hpe1429_fetc_Q(ViSession vi, ViInt16 chan, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_initImm(ViSession vi) { +ViStatus _VI_FUNC hpe1429_initImm(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5739,23 +6120,27 @@ ViStatus _VI_FUNC hpe1429_initImm(ViSession vi) { // At the begining, controler==&B1010 (Embedded controler not mapped yet, // Embedded controler) 22==&B10110 (Using fast fetch, Using fast init, // Embedded controler) - if ((thisPtr->controler & 22) == 22) { /* give fast init */ + if ((thisPtr->controler & 22) == 22) + { /* give fast init */ // Reset Bit 14, 15 thisPtr->controler &= 0xFFFF3FFF; /* 0 the SCPI init bit */ if (VI_SUCCESS <= viMapAddress(vi, VI_A24_SPACE, 0x00, 0xFF, VI_FALSE, - VI_NULL, &base_addr)) { + VI_NULL, &base_addr)) + { if (thisPtr->controler & 1) /* VX_LINK */ errStatus = hpe1429_LINKInit(vi, (char *)base_addr, thisPtr); else errStatus = hpe1429_fastInit((char *)base_addr, thisPtr); viUnmapAddress(vi); - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { // Set Bit 13 thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ hpe1429_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } - } else + } + else thisPtr->controler = 0; /* Failing -- remove fast access */ } /* if we get here, fast init must not have happened--do normal init */ @@ -5764,7 +6149,8 @@ ViStatus _VI_FUNC hpe1429_initImm(ViSession vi) { if (thisPtr->controler & 2) thisPtr->controler |= 16384; /* set the used SCPI INIT flag, 16384==&x4000, Set Bit 14 */ - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -5853,12 +6239,14 @@ static const char *const hpe1429_maxMin_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, ViPReal64 maxTime, ViPReal64 minVolt, - ViPReal64 minTime) { + ViPReal64 minTime) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -5905,7 +6293,8 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, errStatus = hpe1429_configure_Q(vi, chan, &port, &range, &trigCount, &preTrigs, &numArms); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -5918,19 +6307,23 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, waiting = 0; thisPtr->blockSrqIO = VI_TRUE; - do { + do + { errStatus = viPrintf(vi, "STAT:OPER:COND? \n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%hd%*t", &busy); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } - if (busy & 256) { + if (busy & 256) + { spinner = 0; for (spin = 0; spin < 1000; spin++) /* burn some time to minimize I-O */ spinner = spinner + 1; @@ -5940,20 +6333,25 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, } while ((waiting < 1000) && (busy & 256)); if (busy & - 256) { /* still busy--set for max readings and see if timeout occurs */ + 256) + { /* still busy--set for max readings and see if timeout occurs */ if ((ViReal64)numArms * (ViReal64)trigCount < 524288) totalCount = numArms * trigCount; else totalCount = 524288; - } else { + } + else + { errStatus = viPrintf(vi, "FETC:COUN? \n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%ld%*t", &totalCount); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } @@ -5966,13 +6364,15 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, #else data = (ViInt16 _huge *)_halloc((long)totalCount, sizeof(ViInt16)); #endif - if (data == NULL) { + if (data == NULL) + { hpe1429_LOG_STATUS(vi, thisPtr, VI_ERROR_ALLOC); } errStatus = hpe1429_fetc_Q(vi, chan, totalCount, data); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { #ifdef WIN32 free(data); #else @@ -5982,12 +6382,15 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, } /* OK, got the data ... analize */ - for (i = 0; i < trigCount; i++) { - if (data[i] < minV) { + for (i = 0; i < trigCount; i++) + { + if (data[i] < minV) + { minV = data[i]; iMin = i; } - if (data[i] > maxV) { + if (data[i] > maxV) + { maxV = data[i]; iMax = i; } @@ -6002,26 +6405,31 @@ ViStatus _VI_FUNC hpe1429_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, *minVolt = range * minV / 32752.0; /* Subtract the pre-triggers */ - if (preTrigs) { + if (preTrigs) + { iMin -= preTrigs; iMax -= preTrigs; } - switch (trigSour) { /* See if trigger source is timer */ + switch (trigSour) + { /* See if trigger source is timer */ case hpe1429_TRIG_TIM: *maxTime = iMax * trigTime; *minTime = iMin * trigTime; break; case hpe1429_TRIG_DTIM: - if ((iMax > 0) || (iMin > 0)) { + if ((iMax > 0) || (iMin > 0)) + { errStatus = viPrintf(vi, "TRIG:TIM2? \n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", &timer2); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } @@ -6193,12 +6601,14 @@ ViStatus _VI_FUNC hpe1429_measure(ViSession vi, ViInt16 chan, ViInt16 port, ViReal64 expected, ViInt32 numTriggers, ViInt32 preTriggers, ViInt32 numArms, ViInt32 arrayLength, - ViReal64 _VI_FAR data[]) { + ViReal64 _VI_FAR data[]) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6225,23 +6635,28 @@ ViStatus _VI_FUNC hpe1429_measure(ViSession vi, ViInt16 chan, ViInt16 port, { errStatus = viPrintf(vi, "CONF%hd:ARR (%ld),%lg,(@%hd)\n", chan, numTriggers, expected, (chan + 2 * port)); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SWE:OFFS:POIN %ld\n", (-preTriggers)); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "ARM:COUN %ld\n", numArms); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_initImm(vi); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = hpe1429_fetcScal_Q(vi, chan, arrayLength, data); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } @@ -6275,12 +6690,14 @@ ViStatus _VI_FUNC hpe1429_measure(ViSession vi, ViInt16 chan, ViInt16 port, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_memBattStat(ViSession vi, ViBoolean memBattStat) { +ViStatus _VI_FUNC hpe1429_memBattStat(ViSession vi, ViBoolean memBattStat) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6290,7 +6707,8 @@ ViStatus _VI_FUNC hpe1429_memBattStat(ViSession vi, ViBoolean memBattStat) { hpe1429_CHK_BOOLEAN(memBattStat, VI_ERROR_PARAMETER2); errStatus = viPrintf(vi, "MEM:BATT:STAT %u\n", memBattStat); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -6321,12 +6739,14 @@ ViStatus _VI_FUNC hpe1429_memBattStat(ViSession vi, ViBoolean memBattStat) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_memBattStat_Q(ViSession vi, ViPBoolean memBattStat) { +ViStatus _VI_FUNC hpe1429_memBattStat_Q(ViSession vi, ViPBoolean memBattStat) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6335,14 +6755,16 @@ ViStatus _VI_FUNC hpe1429_memBattStat_Q(ViSession vi, ViPBoolean memBattStat) { thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "MEM:BATT:STAT?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%hd%*t", memBattStat); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -6394,12 +6816,14 @@ static const char *const hpe1429_recover_Q_chan_a[] = {"", "1", "2", 0}; ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, ViInt32 arrayLength, ViInt16 _VI_FAR data[], - ViPInt32 count) { + ViPInt32 count) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6430,40 +6854,48 @@ ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "FORM PACK;:FETC%hd:REC?\n", chan); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } /* errStatus = viScanf(vi, "%2c", c); Read Header (should be #[1-9] */ errStatus = viRead(vi, c, 2, &retbytes); /* Read Header (should be #[1-9] */ - if (retbytes != 2) { + if (retbytes != 2) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_INV_RESPONSE; } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { digits = c[1] - '0'; - if ((digits < 1) || (9 < digits)) { + if ((digits < 1) || (9 < digits)) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_INV_RESPONSE; } } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { /* Scan DAB array count. */ /* errStatus = viScanf(vi, "%#c", &digits, length_str); */ errStatus = viRead(vi, length_str, digits, &retbytes); - if (retbytes != digits) { + if (retbytes != digits) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_INV_RESPONSE; } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { length_str[digits] = '\0'; /* null terminate the string */ nbytes = strtol(length_str, NULL, 0); /* Verify that caller's array is big enough. */ - if (((ViUInt32)arrayLength * 2) < nbytes) { + if (((ViUInt32)arrayLength * 2) < nbytes) + { errStatus = viScanf(vi, "%*t"); /* Clear input. */ errStatus = VI_ERROR_PARAMETER3; /* Caller's array too small. */ } @@ -6471,7 +6903,8 @@ ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, } } - if (errStatus >= VI_SUCCESS) { + if (errStatus >= VI_SUCCESS) + { /* sprintf(fmtStr,"%%%ldc%%*t", nbytes); errStatus = viScanf(vi, fmtStr, (unsigned char*)fptr); */ errStatus = viRead(vi, (unsigned char *)fptr, nbytes, &retbytes); @@ -6480,8 +6913,10 @@ ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, #ifndef B_ENDIAN /* need byte swapping */ - if (errStatus >= VI_SUCCESS) { - for (i = 0; i < (ViInt32)(nbytes / 2); i++) { + if (errStatus >= VI_SUCCESS) + { + for (i = 0; i < (ViInt32)(nbytes / 2); i++) + { *((ViInt16 *)src) = *((ViInt16 *)(&fptr[i])); ((unsigned char *)(&fptr[i]))[0] = ((unsigned char *)(src))[1]; ((unsigned char *)(&fptr[i]))[1] = ((unsigned char *)(src))[0]; @@ -6491,7 +6926,8 @@ ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, } if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } } @@ -6518,12 +6954,14 @@ ViStatus _VI_FUNC hpe1429_recover_Q(ViSession vi, ViInt16 chan, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_trigStarImm(ViSession vi) { +ViStatus _VI_FUNC hpe1429_trigStarImm(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6532,7 +6970,8 @@ ViStatus _VI_FUNC hpe1429_trigStarImm(ViSession vi) { { errStatus = viPrintf(vi, "TRIG\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } thisPtr->controler |= 8192; /* Flag LOG_STATUS to not clear bits */ @@ -6667,17 +7106,19 @@ ViStatus _VI_FUNC hpe1429_trigStarImm(ViSession vi) { *----------------------------------------------------------------------------- */ static const char *const hpe1429_trigger_trigSour_a[] = { - "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", - "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT1", "EXT2", - "TIM", "DEXT", "DECL", "DTIM", "VME", 0}; + "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", + "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT1", "EXT2", + "TIM", "DEXT", "DECL", "DTIM", "VME", 0}; ViStatus _VI_FUNC hpe1429_trigger(ViSession vi, ViInt16 trigSour, - ViPReal64 trigTimer1) { + ViPReal64 trigTimer1) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6690,7 +7131,8 @@ ViStatus _VI_FUNC hpe1429_trigger(ViSession vi, ViInt16 trigSour, errStatus = viPrintf(vi, "TRIG:SOUR %s;TIM %g\n", hpe1429_trigger_trigSour_a[trigSour], *trigTimer1); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -6727,18 +7169,20 @@ ViStatus _VI_FUNC hpe1429_trigger(ViSession vi, ViInt16 trigSour, *----------------------------------------------------------------------------- */ static const char *const hpe1429_trigger_Q_trigSour_a[] = { - "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", - "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT1", "EXT2", - "TIM", "DEXT", "DECL", "DTIM", "VME", 0}; + "BUS", "HOLD", "ECLT0", "ECLT1", "TTLT0", "TTLT1", "TTLT2", + "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT1", "EXT2", + "TIM", "DEXT", "DECL", "DTIM", "VME", 0}; ViStatus _VI_FUNC hpe1429_trigger_Q(ViSession vi, ViPInt16 trigSour, - ViPReal64 trigTimer1) { + ViPReal64 trigTimer1) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; char trigSour_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6749,24 +7193,28 @@ ViStatus _VI_FUNC hpe1429_trigger_Q(ViSession vi, ViPInt16 trigSour, /* ViChar trigSour_str[32]; Don't need to declare -- (Autoscript does it) */ thisPtr->blockSrqIO = VI_TRUE; errStatus = viPrintf(vi, "TRIG:SOUR?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%s%*t", trigSour_str); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "TRIG:TIM? \n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", trigTimer1); if (thisPtr) doDelay(thisPtr->myDelay); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } @@ -6804,12 +7252,14 @@ ViStatus _VI_FUNC hpe1429_trigger_Q(ViSession vi, ViPInt16 trigSour, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1429_vinsConfLbusRes(ViSession vi) { +ViStatus _VI_FUNC hpe1429_vinsConfLbusRes(ViSession vi) +{ ViStatus errStatus = 0; struct hpe1429_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, 0, errStatus); } @@ -6817,7 +7267,8 @@ ViStatus _VI_FUNC hpe1429_vinsConfLbusRes(ViSession vi) { hpe1429_CDE_INIT("hpe1429_vinsConfLbusRes"); errStatus = viPrintf(vi, "VINS:LBUS:RES\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1429_LOG_STATUS(vi, thisPtr, errStatus); } diff --git a/kbsidevices/hpe1564.c b/kbsidevices/hpe1564.c index 1dd9f48858..64f3c19599 100644 --- a/kbsidevices/hpe1564.c +++ b/kbsidevices/hpe1564.c @@ -55,33 +55,33 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #define hpe1564_DECLARE_TIME_LOCALS SYSTEMTIME st; #define hpe1564_GET_TIME GetLocalTime(&st); -#define hpe1564_TIME_FIELDS \ +#define hpe1564_TIME_FIELDS \ st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds #else /* not win32 */ #include /* standard time functions */ #ifdef __hpux #define DWORD int #include -#define hpe1564_DECLARE_TIME_LOCALS \ - struct timeval tv; \ - struct timezone tz; \ +#define hpe1564_DECLARE_TIME_LOCALS \ + struct timeval tv; \ + struct timezone tz; \ struct tm *tmp; -#define hpe1564_GET_TIME \ - gettimeofday(&tv, &tz); \ +#define hpe1564_GET_TIME \ + gettimeofday(&tv, &tz); \ tmp = localtime((time_t *)&tv.tv_sec); -#define hpe1564_TIME_FIELDS \ - tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, \ +#define hpe1564_TIME_FIELDS \ + tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, \ tv.tv_usec / 1000 #else /* not unix, use ANSI time function */ -#define hpe1564_DECLARE_TIME_LOCALS \ - struct tm *tmp; \ +#define hpe1564_DECLARE_TIME_LOCALS \ + struct tm *tmp; \ time_t seconds; -#define hpe1564_GET_TIME \ - time(&seconds); \ +#define hpe1564_GET_TIME \ + time(&seconds); \ tmp = localtime(&seconds); -#define hpe1564_TIME_FIELDS \ +#define hpe1564_TIME_FIELDS \ tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, 0 #endif /* ifdef __hpux */ @@ -119,17 +119,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ViInt32 hpe1564_statusHap[hpe1564_MAX_STAT_HAP] = { hpe1564_USER_ERROR_HANDLER, hpe1564_INSTR_ERROR_HANDLER, - hpe1564_VOLT_OVLD, hpe1564_LIM1_FAIL, hpe1564_LIM2_FAIL, - hpe1564_LIM3_FAIL, hpe1564_LIM4_FAIL, + hpe1564_VOLT_OVLD, hpe1564_LIM1_FAIL, hpe1564_LIM2_FAIL, + hpe1564_LIM3_FAIL, hpe1564_LIM4_FAIL, - hpe1564_GOT_TRIG, hpe1564_PRETRIG_DONE, hpe1564_MEAS_DONE}; + hpe1564_GOT_TRIG, hpe1564_PRETRIG_DONE, hpe1564_MEAS_DONE}; /* Assumes we have driver copies of the event register. This is needed * because in IEEE 488.2, the event register are cleared after they are * read. Since the event register contains several events, we need to * keep this information around to pass back to the user. */ -struct hpe1564_statusAccess { +struct hpe1564_statusAccess +{ ViInt32 registerIdx; ViString condQry; ViString eventQry; @@ -143,13 +144,16 @@ const struct hpe1564_statusAccess hpe1564_accessInfo[hpe1564_MAX_STAT_REG] = { {800, "STAT:OPER:COND?", "STAT:OPER:EVEN?", "STAT:OPER:ENAB"}}; /* this will return the index associated with the happening */ -ViBoolean hpe1564_findHappeningIdx(ViInt32 happening, ViPInt32 pIdx) { +ViBoolean hpe1564_findHappeningIdx(ViInt32 happening, ViPInt32 pIdx) +{ /* Note: this is a linear search, for faster access this * could be done as a binary search since the data is arrange * in order numerically. */ - for (*pIdx = 0; *pIdx < hpe1564_MAX_STAT_HAP; *pIdx = *pIdx + 1) { - if (hpe1564_statusHap[*pIdx] == happening) { + for (*pIdx = 0; *pIdx < hpe1564_MAX_STAT_HAP; *pIdx = *pIdx + 1) + { + if (hpe1564_statusHap[*pIdx] == happening) + { return VI_TRUE; } } @@ -158,9 +162,12 @@ ViBoolean hpe1564_findHappeningIdx(ViInt32 happening, ViPInt32 pIdx) { } /* this will return the index that corresponds with regNum */ -static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { - for (*pIdx = 0; *pIdx < hpe1564_MAX_STAT_REG; *pIdx = *pIdx + 1) { - if (regNum == hpe1564_accessInfo[*pIdx].registerIdx) { +static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) +{ + for (*pIdx = 0; *pIdx < hpe1564_MAX_STAT_REG; *pIdx = *pIdx + 1) + { + if (regNum == hpe1564_accessInfo[*pIdx].registerIdx) + { return VI_TRUE; } } @@ -171,36 +178,36 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { if you do then you must also remove the routines that use them (_cmd_arr functions) */ -#define SWAP_FLOAT64(dest) \ - { \ - unsigned char src[8]; \ - *((double *)src) = *((double *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[7]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[6]; \ - ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[5]; \ - ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[4]; \ - ((unsigned char *)(dest))[4] = ((unsigned char *)(src))[3]; \ - ((unsigned char *)(dest))[5] = ((unsigned char *)(src))[2]; \ - ((unsigned char *)(dest))[6] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[7] = ((unsigned char *)(src))[0]; \ - } - -#define SWAP_32(dest) \ - { \ - unsigned char src[4]; \ - *((long *)src) = *((long *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ - ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ - } - -#define SWAP_16(dest) \ - { \ - unsigned char src[2]; \ - *((ViInt16 *)src) = *((ViInt16 *)dest); \ - ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[1]; \ - ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[0]; \ +#define SWAP_FLOAT64(dest) \ + { \ + unsigned char src[8]; \ + *((double *)src) = *((double *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[7]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[6]; \ + ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[5]; \ + ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[4]; \ + ((unsigned char *)(dest))[4] = ((unsigned char *)(src))[3]; \ + ((unsigned char *)(dest))[5] = ((unsigned char *)(src))[2]; \ + ((unsigned char *)(dest))[6] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[7] = ((unsigned char *)(src))[0]; \ + } + +#define SWAP_32(dest) \ + { \ + unsigned char src[4]; \ + *((long *)src) = *((long *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[3]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[2]; \ + ((unsigned char *)(dest))[2] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[3] = ((unsigned char *)(src))[0]; \ + } + +#define SWAP_16(dest) \ + { \ + unsigned char src[2]; \ + *((ViInt16 *)src) = *((ViInt16 *)dest); \ + ((unsigned char *)(dest))[0] = ((unsigned char *)(src))[1]; \ + ((unsigned char *)(dest))[1] = ((unsigned char *)(src))[0]; \ } /*=============================================================== * @@ -209,7 +216,7 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { *=============================================================== */ -#define hpe1564_MSG_VI_OPEN_ERR \ +#define hpe1564_MSG_VI_OPEN_ERR \ "vi was zero. Was the hpe1564_init() successful?" #define hpe1564_MSG_CONDITION "condition" @@ -218,11 +225,11 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define hpe1564_MSG_EVENT "event" /* hpe1564_statEvent_Q() */ -#define hpe1564_MSG_EVENT_HDLR_INSTALLED \ +#define hpe1564_MSG_EVENT_HDLR_INSTALLED \ "event handler is already installed for event happening" /* hpe1564_statEvent_Q() */ -#define hpe1564_MSG_EVENT_HDLR_INST2 \ +#define hpe1564_MSG_EVENT_HDLR_INST2 \ "Only 1 handler can be installed at a time." /* hpe1564_statEvent_Q() */ @@ -239,18 +246,18 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define hpe1564_MSG_IN_FUNCTION "in function" /* hpe1564_error_message() */ -#define hpe1564_MSG_INVALID_STATUS \ - "Parameter 2 is invalid" \ +#define hpe1564_MSG_INVALID_STATUS \ + "Parameter 2 is invalid" \ "in function hpe1564_error_message()." /* hpe1564_error_message() */ #define hpe1564_MSG_INVALID_STATUS_VALUE "is not a valid viStatus value." /* hpe1564_error_message() */ -#define hpe1564_MSG_INVALID_VI \ - "Parameter 1 is invalid" \ - " in function hpe1564_error_message()" \ - ". Using an inactive ViSession may cause this error." \ +#define hpe1564_MSG_INVALID_VI \ + "Parameter 1 is invalid" \ + " in function hpe1564_error_message()" \ + ". Using an inactive ViSession may cause this error." \ " Was the instrument driver closed prematurely?" /* hpe1564_message_query() */ @@ -263,7 +270,7 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define hpe1564_MSG_SELF_TEST_PASSED "Self test passed." /* hpe1564_self_test() */ -#define hpe1564_MSG_WARN_SELF_TEST \ +#define hpe1564_MSG_WARN_SELF_TEST \ "Power-on self test failed, run full self test." /* hpe1564_self_test() */ @@ -323,7 +330,7 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define VI_ERROR_FAIL_ID_QUERY_MSG "Instrument IDN does not match." -#define INSTR_ERROR_INV_SESSION_MSG \ +#define INSTR_ERROR_INV_SESSION_MSG \ "ViSession (parmeter 1) was not created by this driver" #define INSTR_ERROR_NULL_PTR_MSG "NULL pointer detected" @@ -332,48 +339,48 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define INSTR_ERROR_UNEXPECTED_MSG "An unexpected error occurred" -#define INSTR_ERROR_DETECTED_MSG \ +#define INSTR_ERROR_DETECTED_MSG \ "Instrument Error Detected, call hpe1564_error_query()." #define INSTR_ERROR_NOTFOUND_MSG "Instrument was not found." -#define INSTR_ERROR_MULTIPLE_MSG \ +#define INSTR_ERROR_MULTIPLE_MSG \ "Multiple Instruments were found, none were opened" #define INSTR_ERROR_A16MAP_FAILED_MSG "reset failed" #define INSTR_ERROR_LOOKUP_MSG "String not found in table" -#define INSTR_ERROR_SAMPTTL_MSG \ +#define INSTR_ERROR_SAMPTTL_MSG \ "output of SAMP disabled, sample source now using TTL trig line " -#define INSTR_ERROR_MASTER_TRIGTTL_MSG \ +#define INSTR_ERROR_MASTER_TRIGTTL_MSG \ "Trig source 2 conflicts with MASTER|SLAVE mode; trig source 2 set to HOLD" -#define INSTR_ERROR_MASTER_SAMPTTL_MSG \ - "Samp src TTLT conflicts with trig mode MASTER; setting samp src " \ +#define INSTR_ERROR_MASTER_SAMPTTL_MSG \ + "Samp src TTLT conflicts with trig mode MASTER; setting samp src " \ "TIMer" -#define INSTR_ERROR_SLAVE_SAMPLE_MSG \ +#define INSTR_ERROR_SLAVE_SAMPLE_MSG \ "Sample source changes not allowed while trig mode is SLAVE" -#define INSTR_ERROR_MASTER_OUTP_MSG \ +#define INSTR_ERROR_MASTER_OUTP_MSG \ "Output state ON not allowed while trig mode is MASTER|SLAVE" -#define INSTR_ERROR_TRIGTTL_MSG \ +#define INSTR_ERROR_TRIGTTL_MSG \ "output of TRIG disabled, trig source now using TTL trig line " #define INSTR_ERROR_LEVMIN_MSG "Trig or Limit level < MIN, setting to MIN." #define INSTR_ERROR_LEVMAX_MSG "Trig or Limit level > MAX, setting to MAX." -#define INSTR_ERROR_TRIGLIM_MSG \ +#define INSTR_ERROR_TRIGLIM_MSG \ "Trig level/Limit check conflict, limit check disabled" -#define INSTR_ERROR_LIMTRIG_MSG \ +#define INSTR_ERROR_LIMTRIG_MSG \ "Trig level/Limit check conflict, trig source set to IMMediate" -#define INSTR_ERROR_PRETRIG_MSG \ +#define INSTR_ERROR_PRETRIG_MSG \ "Pretrigger count >= total count; setting pretrigger to total - 1" #define INSTR_ERROR_TRIG_IGN_MSG "Trigger ignored." @@ -384,41 +391,41 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { #define INSTR_ERROR_CAL_OFF_MSG "Calibration not enabled, see hpe1564_calState" -#define INSTR_ERROR_BAD_CAL_VAL_MSG \ +#define INSTR_ERROR_BAD_CAL_VAL_MSG \ "Calibration value not between 85% and 98% of full scale" -#define INSTR_ERROR_FLASH_PROG_MSG \ +#define INSTR_ERROR_FLASH_PROG_MSG \ "Flash programming error; switches set incorrectly?" -#define INSTR_ERROR_FLASH_VPP_MSG \ +#define INSTR_ERROR_FLASH_VPP_MSG \ "Flash VPP low error; switches set incorrectly?" #define INSTR_ERROR_FLASH_ERASE_MSG "Error erasing flash; store aborted" -#define INSTR_ERROR_CAL_STALE_MSG \ +#define INSTR_ERROR_CAL_STALE_MSG \ "Calibration constants not modified; store aborted" -#define INSTR_ERROR_CAL_STORE_MSG \ +#define INSTR_ERROR_CAL_STORE_MSG \ "Calibration store unsuccessful; stored value incorrect" -#define INSTR_ERROR_CAL_NOT_STORED_MSG \ +#define INSTR_ERROR_CAL_NOT_STORED_MSG \ "Must STORE data before exiting Calibration state" #define INSTR_ERROR_CAL_NO_CONVERGE_MSG "Calibration not converging; exiting" #define INSTR_ERROR_BIG_VOLT_MSG "Overloads occurring, reduce signal level." -#define INSTR_ERROR_TRIG_DEAD_MSG \ +#define INSTR_ERROR_TRIG_DEAD_MSG \ "Trigger source deadlock detected, data fetch aborted" -#define INSTR_ERROR_SAMP_DEAD_MSG \ +#define INSTR_ERROR_SAMP_DEAD_MSG \ "Sample source deadlock detected, data fetch aborted" #define INSTR_ERROR_CAL_GAIN_AUTO_MSG "Error generating gain constant" #define INSTR_ERROR_CAL_OFFS_AUTO_MSG "Error generating filter offset" -#define INSTR_ERROR_OVLD_MSG \ +#define INSTR_ERROR_OVLD_MSG \ "Overload detected; Attempting re-connect of input relays" #define INSTR_ERROR_OVLD_DATA_MSG "Overload detected; data is questionable" @@ -427,22 +434,25 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { /* don't check the debug pointer all the time!*/ #ifdef DEBUG -#define hpe1564_DEBUG_CHK_THIS(vi, thisPtr) \ - /* check for NULL user data */ \ - if (0 == thisPtr) { \ - hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_INV_SESSION); \ - } \ - { \ - ViSession defRM; \ - \ - /* This should never fail */ \ - errStatus = viGetAttribute(vi, VI_ATTR_RM_SESSION, &defRM); \ - if (VI_SUCCESS > errStatus) { \ - hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_UNEXPECTED); \ - } \ - if (defRM != thisPtr->defRMSession) { \ - hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_INV_SESSION); \ - } \ +#define hpe1564_DEBUG_CHK_THIS(vi, thisPtr) \ + /* check for NULL user data */ \ + if (0 == thisPtr) \ + { \ + hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_INV_SESSION); \ + } \ + { \ + ViSession defRM; \ + \ + /* This should never fail */ \ + errStatus = viGetAttribute(vi, VI_ATTR_RM_SESSION, &defRM); \ + if (VI_SUCCESS > errStatus) \ + { \ + hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_UNEXPECTED); \ + } \ + if (defRM != thisPtr->defRMSession) \ + { \ + hpe1564_LOG_STATUS(vi, NULL, hpe1564_INSTR_ERROR_INV_SESSION); \ + } \ } #else #define hpe1564_DEBUG_CHK_THIS(vi, thisPtr) @@ -455,14 +465,15 @@ static ViBoolean hpe1564_findAccessIdx(ViInt32 regNum, ViPInt32 pIdx) { * hpe1564_statusUpdate() in order to determine exactly where an error * occured in a driver. */ -#define hpe1564_LOG_STATUS(vi, thisPtr, status) \ +#define hpe1564_LOG_STATUS(vi, thisPtr, status) \ return hpe1564_statusUpdate(vi, thisPtr, status) /* declare this here since it is called by statusUpdate */ static void hpe1564_srqTraverse(ViSession vi, ViInt32 eventReg); ViStatus hpe1564_statusUpdate(ViSession vi, hpe1564_globals *thisPtr, - ViStatus s) { + ViStatus s) +{ ViInt32 eventQ; ViUInt32 rc; char lc[20]; @@ -474,17 +485,20 @@ ViStatus hpe1564_statusUpdate(ViSession vi, hpe1564_globals *thisPtr, /* This is only done, if the vi is valid and * no other errors have occured. */ - if (s == VI_ERROR_TMO) { + if (s == VI_ERROR_TMO) + { thisPtr->errNumber = s; return s; } /* Check if user wants to query the instrument state. */ - if (thisPtr && thisPtr->errQueryDetect) { + if (thisPtr && thisPtr->errQueryDetect) + { /* assume IEEE 488.2 Instrument and query standard * status event register for a parser error */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viWrite(vi, (ViBuf) "*ESR?", 5, &rc); if (errStatus < VI_SUCCESS) return VI_ERROR_SYSTEM_ERROR; @@ -500,10 +514,12 @@ ViStatus hpe1564_statusUpdate(ViSession vi, hpe1564_globals *thisPtr, | 0x10 /* Execution Error */ | 0x20 /* Command Error */ ) & - eventQ) { + eventQ) + { /* See if the user has an instr error handler enabled */ if (thisPtr->eventHandlerArray[hpe1564_INSTR_ERROR_HANDLER_IDX] - .eventHandler) { + .eventHandler) + { /* call the users handler */ thisPtr->eventHandlerArray[hpe1564_INSTR_ERROR_HANDLER_IDX] .eventHandler( @@ -519,7 +535,8 @@ ViStatus hpe1564_statusUpdate(ViSession vi, hpe1564_globals *thisPtr, /* if a plug and play error occurs, see if the user has a handler enabled */ if (s != hpe1564_INSTR_ERROR_DETECTED && VI_SUCCESS > s && - thisPtr->eventHandlerArray[hpe1564_USER_ERROR_HANDLER_IDX].eventHandler) { + thisPtr->eventHandlerArray[hpe1564_USER_ERROR_HANDLER_IDX].eventHandler) + { /* call the users handler */ thisPtr->eventHandlerArray[hpe1564_USER_ERROR_HANDLER_IDX].eventHandler( vi, (ViInt32)s, @@ -535,7 +552,8 @@ ViStatus hpe1564_statusUpdate(ViSession vi, hpe1564_globals *thisPtr, * Error Message Structures */ -struct instrErrStruct { +struct instrErrStruct +{ ViStatus errStatus; ViString errMessage; }; @@ -605,14 +623,16 @@ const static struct instrErrStruct instrErrMsgTable[] = { }; /* macros for testing parameters */ -#define hpe1564_CHK_BOOLEAN(my_val, err) \ - if (hpe1564_chk_boolean(thisPtr, my_val)) \ +#define hpe1564_CHK_BOOLEAN(my_val, err) \ + if (hpe1564_chk_boolean(thisPtr, my_val)) \ hpe1564_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1564_chk_boolean(hpe1564_globals *thisPtr, - ViBoolean my_val) { + ViBoolean my_val) +{ char message[hpe1564_ERR_MSG_LENGTH]; - if ((my_val != VI_TRUE) && (my_val != VI_FALSE)) { + if ((my_val != VI_TRUE) && (my_val != VI_FALSE)) + { /* true = parameter is invalid */ sprintf(message, hpe1564_MSG_BOOLEAN, my_val); hpe1564_CDE_MESSAGE(message); @@ -624,16 +644,18 @@ static ViBoolean hpe1564_chk_boolean(hpe1564_globals *thisPtr, return VI_FALSE; } -#define hpe1564_CHK_REAL_RANGE(my_val, min, max, err) \ - if (hpe1564_chk_real_range(thisPtr, my_val, min, max)) \ +#define hpe1564_CHK_REAL_RANGE(my_val, min, max, err) \ + if (hpe1564_chk_real_range(thisPtr, my_val, min, max)) \ hpe1564_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1564_chk_real_range(hpe1564_globals *thisPtr, ViReal64 my_val, ViReal64 min, - ViReal64 max) { + ViReal64 max) +{ char message[hpe1564_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1564_MSG_REAL, min, max, my_val); hpe1564_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -642,15 +664,17 @@ static ViBoolean hpe1564_chk_real_range(hpe1564_globals *thisPtr, return VI_FALSE; } -#define hpe1564_CHK_INT_RANGE(my_val, min, max, err) \ - if (hpe1564_chk_int_range(thisPtr, my_val, min, max)) \ +#define hpe1564_CHK_INT_RANGE(my_val, min, max, err) \ + if (hpe1564_chk_int_range(thisPtr, my_val, min, max)) \ hpe1564_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1564_chk_int_range(hpe1564_globals *thisPtr, ViInt16 my_val, - ViInt16 min, ViInt16 max) { + ViInt16 min, ViInt16 max) +{ char message[hpe1564_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1564_MSG_INT, min, max, my_val); hpe1564_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -659,16 +683,18 @@ static ViBoolean hpe1564_chk_int_range(hpe1564_globals *thisPtr, ViInt16 my_val, return VI_FALSE; } -#define hpe1564_CHK_LONG_RANGE(my_val, min, max, err) \ - if (hpe1564_chk_long_range(thisPtr, my_val, min, max)) \ +#define hpe1564_CHK_LONG_RANGE(my_val, min, max, err) \ + if (hpe1564_chk_long_range(thisPtr, my_val, min, max)) \ hpe1564_LOG_STATUS(vi, thisPtr, err); static ViBoolean hpe1564_chk_long_range(hpe1564_globals *thisPtr, ViInt32 my_val, ViInt32 min, - ViInt32 max) { + ViInt32 max) +{ char message[hpe1564_ERR_MSG_LENGTH]; - if ((my_val < min) || (my_val > max)) { + if ((my_val < min) || (my_val > max)) + { sprintf(message, hpe1564_MSG_LONG, min, max, my_val); hpe1564_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -677,17 +703,19 @@ static ViBoolean hpe1564_chk_long_range(hpe1564_globals *thisPtr, return VI_FALSE; } -#define hpe1564_CHK_ENUM(my_val, limit, err) \ - if (hpe1564_chk_enum(thisPtr, my_val, limit)) \ +#define hpe1564_CHK_ENUM(my_val, limit, err) \ + if (hpe1564_chk_enum(thisPtr, my_val, limit)) \ hpe1564_LOG_STATUS(vi, thisPtr, err); /* utility routine which searches for a string in an array of strings. */ /* This is used by the CHK_ENUM macro */ static ViBoolean hpe1564_chk_enum(hpe1564_globals *thisPtr, ViInt16 my_val, - ViInt16 limit) { + ViInt16 limit) +{ char message[hpe1564_ERR_MSG_LENGTH]; - if ((my_val < 0) || (my_val > limit)) { + if ((my_val < 0) || (my_val > limit)) + { sprintf(message, hpe1564_MSG_INT, 0, limit, my_val); hpe1564_CDE_MESSAGE(message); /* true = parameter is invalid */ @@ -706,7 +734,8 @@ ViStatus hpe1564_findIndex(hpe1564_globals *thisPtr, const char *const array_of_strings[], /*last entry in array must be 0 */ const char *string, /* string read from instrument */ - ViPInt16 index) { /* result index */ + ViPInt16 index) +{ /* result index */ ViInt16 i; ViInt16 my_len; char search_str[20]; @@ -720,8 +749,10 @@ ViStatus hpe1564_findIndex(hpe1564_globals *thisPtr, if (search_str[my_len - 1] == '\n') search_str[my_len - 1] = '\0'; - for (i = 0; array_of_strings[i]; i++) { - if (!strcmp(array_of_strings[i], search_str)) { + for (i = 0; array_of_strings[i]; i++) + { + if (!strcmp(array_of_strings[i], search_str)) + { *index = i; return VI_SUCCESS; } @@ -735,14 +766,15 @@ ViStatus hpe1564_findIndex(hpe1564_globals *thisPtr, /* returns the globals pointer */ -#define GetGlobals(vi, thisPtr) \ - { \ - errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); \ - if (VI_SUCCESS > errStatus) \ - hpe1564_LOG_STATUS(vi, NULL, errStatus); \ +#define GetGlobals(vi, thisPtr) \ + { \ + errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); \ + if (VI_SUCCESS > errStatus) \ + hpe1564_LOG_STATUS(vi, NULL, errStatus); \ } -void hpe1564_delay(long delayTime) { +void hpe1564_delay(long delayTime) +{ struct timeb timebuffer; long t0; long t1; @@ -752,31 +784,38 @@ void hpe1564_delay(long delayTime) { t1 = (long)timebuffer.millitm; ftime(&timebuffer); while (((timebuffer.time - t0) * 1000 + ((long)timebuffer.millitm - t1)) < - delayTime) { + delayTime) + { ftime(&timebuffer); } } #ifndef __hpux -long setDelay(double val) { +long setDelay(double val) +{ double slice; _int64_t count; - if (!QueryPerformanceFrequency((LARGE_INTEGER *)&count)) { + if (!QueryPerformanceFrequency((LARGE_INTEGER *)&count)) + { // hdw doesn't have high perfomance count so use getickcount slice = 1e-3; // units for gettick count - } else { + } + else + { slice = 1.0 / count; // Seconds per tick } return (long)(val / slice) + 1; } -void hpe1564_doDelay(long ticks) { +void hpe1564_doDelay(long ticks) +{ _int64_t startval, tmp; - if (!QueryPerformanceCounter((LARGE_INTEGER *)&startval)) { + if (!QueryPerformanceCounter((LARGE_INTEGER *)&startval)) + { DWORD sval; sval = GetTickCount(); while (GetTickCount() - sval < (DWORD)ticks) @@ -784,16 +823,21 @@ void hpe1564_doDelay(long ticks) { return; } tmp = startval; - while (tmp - startval < (DWORD)ticks) { + while (tmp - startval < (DWORD)ticks) + { QueryPerformanceCounter((LARGE_INTEGER *)&tmp); } } #else -long setDelay(double val) { return val * 1E6; } +long setDelay(double val) +{ + return val * 1E6; +} -void doDelay(long ticks) { +void doDelay(long ticks) +{ struct timeval t0, t1; gettimeofday(&t0, NULL); t0.tv_usec += ticks; @@ -840,7 +884,8 @@ hpe1564_init *****************************************************************************/ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, - ViBoolean do_reset, ViPSession vi) { + ViBoolean do_reset, ViPSession vi) +{ hpe1564_globals *thisPtr = NULL; ViSession defRM = 0; ViStatus errStatus; @@ -861,7 +906,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* Find the Default Resource Manager */ errStatus = viOpenDefaultRM(&defRM); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_SYSTEM_ERROR * VI_ERROR_ALLOC */ @@ -870,7 +916,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, errStatus = viOpen(defRM, InstrDesc, VI_NULL, VI_NULL, vi); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { viClose(defRM); /* Errors: VI_ERROR_NSUP_OPER * VI_ERROR_INV_RSRC_NAME @@ -884,7 +931,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* get memory for instance specific globals */ thisPtr = (hpe1564_globals *)malloc(sizeof(hpe1564_globals)); - if (0 == thisPtr) { + if (0 == thisPtr) + { viClose(defRM); /* also closes vi session */ *vi = VI_NULL; hpe1564_LOG_STATUS(*vi, NULL, VI_ERROR_ALLOC); @@ -900,7 +948,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, p[i] = 0; } - if (errStatus = viGetAttribute(*vi, VI_ATTR_INTF_TYPE, &intf)) { + if (errStatus = viGetAttribute(*vi, VI_ATTR_INTF_TYPE, &intf)) + { viClose(*vi); viClose(defRM); *vi = VI_NULL; @@ -909,7 +958,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* check for 1406 internal driver by reading *IDN? of 0 and *IDN? of secondary for this address*/ - if (intf == VI_INTF_GPIB_VXI) { + if (intf == VI_INTF_GPIB_VXI) + { viGetAttribute(*vi, VI_ATTR_INTF_NUM, &num); viGetAttribute(*vi, VI_ATTR_GPIB_PRIMARY_ADDR, &primary); sprintf(gpibdesc, "GPIB%hd::%hd::0", num, primary); @@ -920,13 +970,15 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* try sending an IDN? to 1406 */ viSetAttribute(vi1406, VI_ATTR_TMO_VALUE, 1000); errStatus = viClear(vi1406); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); goto gpib_check_done; } errStatus = viPrintf(vi1406, "*IDN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { viClose(vi1406); goto gpib_check_done; } @@ -966,7 +1018,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, sprintf(gpibdesc, "GPIB%hd::%hd::%hd", num, primary, secondary); viClose(*vi); errStatus = viOpen(defRM, gpibdesc, VI_NULL, VI_NULL, vi); - if (errStatus < VI_SUCCESS) { /* this should never happen */ + if (errStatus < VI_SUCCESS) + { /* this should never happen */ viClose(defRM); *vi = VI_NULL; hpe1564_LOG_STATUS(*vi, NULL, errStatus); @@ -981,7 +1034,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, * and writable. */ errStatus = viSetAttribute(*vi, VI_ATTR_USER_DATA, (ViAttrState)thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { viClose(*vi); viClose(defRM); /* also closes vi session */ *vi = VI_NULL; @@ -1011,30 +1065,39 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, thisPtr->delay_100_usec = setDelay(100.0e-6); /* next line is true if we switched to GPIB above */ - if (intf == VI_INTF_GPIB) { + if (intf == VI_INTF_GPIB) + { thisPtr->e1406 = 1; /* mumble -- add back in when separate drivers if( VI_TRUE == id_query ) { */ if (viClear(*vi) < VI_SUCCESS || viPrintf(*vi, "*IDN?\n") < VI_SUCCESS || - viScanf(*vi, "%t", idn_buf) < VI_SUCCESS) { + viScanf(*vi, "%t", idn_buf) < VI_SUCCESS) + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; hpe1564_LOG_STATUS(*vi, NULL, VI_ERROR_FAIL_ID_QUERY); - } else { /* we got *IDN successfully */ + } + else + { /* we got *IDN successfully */ /* mumble -- alter for each driver? */ /* check for a idn match */ - if (!strncmp(idn_buf, hpe1564_IDN_STRING2, strlen(hpe1564_IDN_STRING2))) { + if (!strncmp(idn_buf, hpe1564_IDN_STRING2, strlen(hpe1564_IDN_STRING2))) + { thisPtr->E1563 = 1; thisPtr->numChans = 2; - } else if (!strncmp(idn_buf, hpe1564_IDN_STRING4, - strlen(hpe1564_IDN_STRING4))) { + } + else if (!strncmp(idn_buf, hpe1564_IDN_STRING4, + strlen(hpe1564_IDN_STRING4))) + { thisPtr->E1563 = 0; thisPtr->numChans = 4; - } else { + } + else + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1045,10 +1108,12 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, } */ - if (VI_TRUE == do_reset) { + if (VI_TRUE == do_reset) + { /* call the reset function to reset the instrument */ /* dcl did not work if VXI or GPIB-VXI */ - if (hpe1564_dcl(*vi) < VI_SUCCESS || hpe1564_reset(*vi) < VI_SUCCESS) { + if (hpe1564_dcl(*vi) < VI_SUCCESS || hpe1564_reset(*vi) < VI_SUCCESS) + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1058,7 +1123,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* set data format to packed */ errStatus = viPrintf(*vi, "FORM:DATA PACK\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1068,7 +1134,9 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* specify motorola format */ thisPtr->bigEndian = 1; - } else { /* either VXI or GPIB-VXI with no driver in command module */ + } + else + { /* either VXI or GPIB-VXI with no driver in command module */ #ifdef __hpux thisPtr->bigEndian = 1; @@ -1082,7 +1150,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* map A16 base */ errStatus = viMapAddress(*vi, VI_A16_SPACE, 0x00, 0x40, VI_FALSE, VI_NULL, &addr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1096,11 +1165,13 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, startup routine. We need to do it here for the gpib-vxi and vxi interface types. */ - if ((intf == VI_INTF_VXI) || (intf == VI_INTF_GPIB_VXI)) { + if ((intf == VI_INTF_VXI) || (intf == VI_INTF_GPIB_VXI)) + { /* find the VXI manufacturer's ID */ errStatus = viGetAttribute(*vi, VI_ATTR_MANF_ID, &manfId); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_NSUP_ATTR */ /* ignore any errors in hpe1564_close */ @@ -1113,7 +1184,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, /* find the instrument's model code */ errStatus = viGetAttribute(*vi, VI_ATTR_MODEL_CODE, (ViPAttrState)(&modelCode)); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { /* Errors: VI_ERROR_NSUP_ATTR */ /* Note: this should never happen * with a VXI instrument @@ -1125,7 +1197,8 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, hpe1564_LOG_STATUS(*vi, NULL, errStatus); } - if (manfId != hpe1564_MANF_ID) { + if (manfId != hpe1564_MANF_ID) + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1133,13 +1206,18 @@ ViStatus _VI_FUNC hpe1564_init(ViRsrc InstrDesc, ViBoolean id_query, hpe1564_LOG_STATUS(*vi, NULL, VI_ERROR_FAIL_ID_QUERY); } - if (modelCode == hpe1564_MODEL4_CODE) { + if (modelCode == hpe1564_MODEL4_CODE) + { thisPtr->E1563 = 0; thisPtr->numChans = 4; - } else if (modelCode == hpe1564_MODEL2_CODE) { + } + else if (modelCode == hpe1564_MODEL2_CODE) + { thisPtr->E1563 = 1; thisPtr->numChans = 2; - } else { + } + else + { /* ignore any errors in hpe1564_close */ hpe1564_close(*vi); *vi = VI_NULL; @@ -1195,7 +1273,8 @@ hpe1564_close | | Instrument Handle returned from hpe1564_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1564_close(ViSession vi) { +ViStatus _VI_FUNC hpe1564_close(ViSession vi) +{ hpe1564_globals *thisPtr; ViStatus errStatus; ViSession defRM; @@ -1207,12 +1286,14 @@ ViStatus _VI_FUNC hpe1564_close(ViSession vi) { defRM = thisPtr->defRMSession; /* if we have a handler, get rid of it */ - if (thisPtr->interrupts) { + if (thisPtr->interrupts) + { viUninstallHandler(vi, VI_EVENT_VXI_SIGP, VI_ANY_HNDLR, (ViAddr)thisPtr); } /* free memory */ - if (thisPtr) { + if (thisPtr) + { /* make sure there is something to free */ free(thisPtr); } @@ -1231,17 +1312,20 @@ hpe1564_reset | | Instrument Handle returned from hpe1564_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1564_reset(ViSession vi) { +ViStatus _VI_FUNC hpe1564_reset(ViSession vi) +{ hpe1564_globals *thisPtr; ViStatus errStatus; GetGlobals(vi, thisPtr) hpe1564_DEBUG_CHK_THIS(vi, thisPtr); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* have to let ourselves know format has changed */ thisPtr->digState.dataFormat = hpe1564_FORM_ASCII; errStatus = viPrintf(vi, "*RST\n"); - } else + } + else errStatus = hpe1564_regReset(vi, thisPtr); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -1270,7 +1354,8 @@ hpe1564_self_test *****************************************************************************/ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, - ViPString test_message) { + ViPString test_message) +{ hpe1564_globals *thisPtr; ViStatus errStatus; ViInt16 result, diagCode; @@ -1287,39 +1372,46 @@ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { char *theMssg[80]; /* save the user's timeout setting */ viGetAttribute(vi, VI_ATTR_TMO_VALUE, &timeOutVal); - if (timeOutVal < 180000) { + if (timeOutVal < 180000) + { /* this command takes a long time, set for 180 seconds */ viSetAttribute(vi, VI_ATTR_TMO_VALUE, 180000); } errStatus = viQueryf(vi, "*TST?\n", "%hd%*t", &result); - if (timeOutVal < 180000) { + if (timeOutVal < 180000) + { /* re-store user's timeout value */ viSetAttribute(vi, VI_ATTR_TMO_VALUE, timeOutVal); } - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { *test_result = -1; hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } /* if device clear, then blow outta here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { thisPtr->device_clear = 0; return VI_SUCCESS; } - if (result > 0) { + if (result > 0) + { errStatus = viQueryf(vi, "TEST:ERR? %hd\n", "%hd,%s%*t", result, &diagCode, theMssg); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { *test_result = -1; sprintf(test_message, "%s", "Visa error"); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -1327,16 +1419,20 @@ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, /* report failure */ sprintf(test_message, "code: %d, %s", diagCode, theMssg); - } else if (result == 0) + } + else if (result == 0) sprintf(test_message, "%s", "Self test Passed"); else /* got result < 0 */ sprintf(test_message, "%s", "Self test Failed"); - } else { + } + else + { /* allocate some memory for use by self test */ thisPtr->memPtr = malloc(400 * sizeof(ViInt16)); errStatus = hpe1564_regSelfTest_Q(vi, thisPtr, &result); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { *test_result = -1; sprintf(test_message, "%s", "Visa error in test."); @@ -1347,7 +1443,8 @@ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, } /* if we had a device_clear, handle it here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { hpe1564_regAbort(vi, thisPtr); thisPtr->device_clear = 0; @@ -1357,12 +1454,14 @@ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, return VI_SUCCESS; } - if (result > 0) { + if (result > 0) + { hpe1564_regTestErr_Q(vi, thisPtr, result, &diagCode, &errMssg); /* report failure */ sprintf(test_message, "code: %d, %s", diagCode, errMssg); - } else if (result == 0) + } + else if (result == 0) sprintf(test_message, "%s", "Self test Passed"); else /* got result < 0 */ @@ -1373,7 +1472,8 @@ ViStatus _VI_FUNC hpe1564_self_test(ViSession vi, ViPInt16 test_result, *test_result = result; /* if not D-SCPI, then free the malloced memory */ - if (!thisPtr->e1406) { + if (!thisPtr->e1406) + { /* free the memory we were using */ free(thisPtr->memPtr); thisPtr->memPtr = NULL; @@ -1401,7 +1501,8 @@ hpe1564_error_query *****************************************************************************/ ViStatus _VI_FUNC hpe1564_error_query(ViSession vi, ViPInt32 error_number, - ViPString error_message) { + ViPString error_message) +{ hpe1564_globals *thisPtr; ViStatus errStatus; @@ -1412,10 +1513,12 @@ ViStatus _VI_FUNC hpe1564_error_query(ViSession vi, ViPInt32 error_number, GetGlobals(vi, thisPtr) hpe1564_DEBUG_CHK_THIS(vi, thisPtr); /* get the error number */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "SYST:ERR?\n", "%ld,%t", error_number, error_message); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } @@ -1461,28 +1564,35 @@ ViStatus _VI_FUNC hpe1564_error_message(ViSession vi, ViStatus error_number, thisPtr = NULL; /* try to find a thisPtr */ - if (VI_NULL != vi) { + if (VI_NULL != vi) + { GetGlobals(vi, thisPtr) hpe1564_DEBUG_CHK_THIS(vi, thisPtr); } - if (VI_SUCCESS == error_number) { + if (VI_SUCCESS == error_number) + { sprintf(message, hpe1564_MSG_NO_ERRORS); hpe1564_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } /* return the static error message */ for (idx = 0; idx < (sizeof instrErrMsgTable / sizeof(struct instrErrStruct)); - idx++) { + idx++) + { /* check for a matching error number */ - if (instrErrMsgTable[idx].errStatus == error_number) { - if ((thisPtr) && (thisPtr->errNumber == error_number)) { + if (instrErrMsgTable[idx].errStatus == error_number) + { + if ((thisPtr) && (thisPtr->errNumber == error_number)) + { /* context dependent error * message is available. */ sprintf(message, "%s " hpe1564_MSG_IN_FUNCTION " %s() %s", instrErrMsgTable[idx].errMessage, thisPtr->errFuncName, thisPtr->errMessage); - } else { + } + else + { /* No context dependent error * message available so copy * the static error message @@ -1499,9 +1609,11 @@ ViStatus _VI_FUNC hpe1564_error_message(ViSession vi, ViStatus error_number, * At this point vi is either VALID or VI_NULL */ errStatus = viStatusDesc(vi, error_number, message); - if (VI_SUCCESS == errStatus) { + if (VI_SUCCESS == errStatus) + { /* check for a context dependent error message */ - if ((thisPtr) && (thisPtr->errNumber == error_number)) { + if ((thisPtr) && (thisPtr->errNumber == error_number)) + { /* context dependent error * message is available. */ @@ -1518,7 +1630,8 @@ ViStatus _VI_FUNC hpe1564_error_message(ViSession vi, ViStatus error_number, } /* if we have a VI_NULL, then we need to return a error message */ - if (VI_NULL == vi) { + if (VI_NULL == vi) + { strcpy(message, hpe1564_MSG_VI_OPEN_ERR); hpe1564_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } @@ -1552,7 +1665,8 @@ hpe1564_revision_query ViStatus _VI_FUNC hpe1564_revision_query(ViSession vi, ViChar _VI_FAR driver_rev[], - ViChar _VI_FAR instr_rev[]) { + ViChar _VI_FAR instr_rev[]) +{ hpe1564_globals *thisPtr; ViStatus errStatus; char temp_str[256]; /* temp hold for instr rev string */ @@ -1566,9 +1680,11 @@ ViStatus _VI_FUNC hpe1564_revision_query(ViSession vi, sprintf(driver_rev, "%s", hpe1564_REV_CODE); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "*IDN?\n", "%s%*t", temp_str); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { driver_rev[0] = 0; instr_rev[0] = 0; @@ -1577,15 +1693,17 @@ ViStatus _VI_FUNC hpe1564_revision_query(ViSession vi, last_comma = strrchr(temp_str, ','); /* error and exit if last comma not found */ - if (!last_comma) { + if (!last_comma) + { instr_rev[0] = 0; hpe1564_CDE_MESSAGE("no last comma found in IDN string"); hpe1564_LOG_STATUS(vi, thisPtr, hpe1564_INSTR_ERROR_UNEXPECTED); } strcpy(instr_rev, last_comma + 1); - - } else { + } + else + { /* driver rev and instr rev are same here */ sprintf(instr_rev, "%s", hpe1564_REV_CODE); } @@ -1612,7 +1730,8 @@ hpe1564_timeOut /* Purpose: Changes the timeout value of the instrument. Input is in */ /* milliseconds. */ /* ----------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_timeOut(ViSession vi, ViInt32 timeOut) { +ViStatus _VI_FUNC hpe1564_timeOut(ViSession vi, ViInt32 timeOut) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -1644,7 +1763,8 @@ hpe1564_timeOut_Q /* Purpose: Returns the current setting of the timeout value of the */ /* instrument in milliseconds. */ /* ----------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_timeOut_Q(ViSession vi, ViPInt32 timeOut) { +ViStatus _VI_FUNC hpe1564_timeOut_Q(ViSession vi, ViPInt32 timeOut) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -1724,7 +1844,8 @@ hpe1564_dcl | | Instrument Handle returned from hpe1564_init() *****************************************************************************/ -ViStatus _VI_FUNC hpe1564_dcl(ViSession vi) { +ViStatus _VI_FUNC hpe1564_dcl(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -1761,12 +1882,14 @@ ViStatus _VI_FUNC hpe1564_dcl(ViSession vi) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_cls(ViSession vi) { +ViStatus _VI_FUNC hpe1564_cls(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -1796,7 +1919,8 @@ hpe1564_readStatusByte_Q | | returns the contents of the status byte *****************************************************************************/ -ViStatus _VI_FUNC hpe1564_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { +ViStatus _VI_FUNC hpe1564_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViUInt16 stb; @@ -1805,7 +1929,8 @@ ViStatus _VI_FUNC hpe1564_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { hpe1564_DEBUG_CHK_THIS(vi, thisPtr); /* this function does nothing if not command module path */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viReadSTB(vi, &stb); if (VI_SUCCESS > errStatus) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -1825,17 +1950,21 @@ ViStatus _VI_FUNC hpe1564_readStatusByte_Q(ViSession vi, ViPInt16 statusByte) { p1 - VI_TRUE if operations pending */ -ViStatus _VI_FUNC hpe1564_opc_Q(ViSession vi, ViPBoolean p1) { +ViStatus _VI_FUNC hpe1564_opc_Q(ViSession vi, ViPBoolean p1) +{ ViStatus errStatus; hpe1564_globals *thisPtr; GetGlobals(vi, thisPtr); /* If (message-based I/O) then write to instrument. */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "*OPC?\n", "%hd%*t", p1); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { /* Must be register-based I/O */ + } + else + { /* Must be register-based I/O */ /* if we get here, oper was complete */ *p1 = 1; @@ -1868,12 +1997,14 @@ ViStatus _VI_FUNC hpe1564_opc_Q(ViSession vi, ViPBoolean p1) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_abort(ViSession vi) { +ViStatus _VI_FUNC hpe1564_abort(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -1904,7 +2035,8 @@ ViStatus _VI_FUNC hpe1564_abort(ViSession vi) { * swap - if == VI_TRUE, then does byte swapping. ************/ ViStatus hpe1564_scan16(ViSession vi, ViInt32 max_length, ViPChar b16, - ViPInt32 rtn_count, ViBoolean swap) { + ViPInt32 rtn_count, ViBoolean swap) +{ ViChar c[2]; ViChar length_str[16]; ViInt16 digits; @@ -1920,13 +2052,15 @@ ViStatus hpe1564_scan16(ViSession vi, ViInt32 max_length, ViPChar b16, digits = c[1] - '0'; /* c[0] is the # */ /* If digits was not [0-9] then syntax problem, blow away input and return */ - if ((digits < 0) || (9 < digits)) { + if ((digits < 0) || (9 < digits)) + { rtn_code = viScanf(vi, "%*t"); /* Clear input. */ return (VI_ERROR_INV_RESPONSE); } /* If (Definite Arbitrary Block) */ - if (digits != 0) { + if (digits != 0) + { /* Scan DAB array count. */ sprintf(fmtStr, "%%%ldc", digits); rtn_code = viScanf(vi, fmtStr, length_str); @@ -1940,7 +2074,9 @@ ViStatus hpe1564_scan16(ViSession vi, ViInt32 max_length, ViPChar b16, /* Verify that caller's array is big enough. */ if (n_bytes > (max_length * 2)) return (VI_ERROR_PARAMETER2); /* Caller's length too small. */ - } else { /* Indefinite Arbitrary Block */ + } + else + { /* Indefinite Arbitrary Block */ /* Read data up to max_length, else end of input. */ /* %t format reads to next END, else until n_bytes. */ @@ -1956,9 +2092,11 @@ ViStatus hpe1564_scan16(ViSession vi, ViInt32 max_length, ViPChar b16, *rtn_count = n_bytes / 2; - if (swap == VI_TRUE) { + if (swap == VI_TRUE) + { /* Byte reverse. */ - for (i = 0; i < n_bytes / 2; i++) { + for (i = 0; i < n_bytes / 2; i++) + { ViChar c; c = b16[1]; @@ -1981,7 +2119,8 @@ ViStatus hpe1564_scan16(ViSession vi, ViInt32 max_length, ViPChar b16, * num_bytes - number of bytes coming back. * ************/ -ViStatus hpe1564_readHeader(ViSession vi, ViPInt32 num_bytes) { +ViStatus hpe1564_readHeader(ViSession vi, ViPInt32 num_bytes) +{ ViChar c[2]; ViChar length_str[16]; ViInt16 digits; @@ -1996,13 +2135,15 @@ ViStatus hpe1564_readHeader(ViSession vi, ViPInt32 num_bytes) { digits = c[1] - '0'; /* c[0] is the # */ /* If digits was not [0-9] then syntax problem, blow away input and return */ - if ((digits < 0) || (9 < digits)) { + if ((digits < 0) || (9 < digits)) + { rtn_code = viScanf(vi, "%*t"); /* Clear input. */ return (VI_ERROR_INV_RESPONSE); } /* If (Definite Arbitrary Block) */ - if (digits != 0) { + if (digits != 0) + { /* Scan DAB array count. */ sprintf(fmtStr, "%%%ldc", digits); rtn_code = viScanf(vi, fmtStr, length_str); @@ -2012,8 +2153,9 @@ ViStatus hpe1564_readHeader(ViSession vi, ViPInt32 num_bytes) { length_str[digits] = '\0'; /* null terminate the string */ n_bytes = strtol(length_str, NULL, 0); - - } else { /* Indefinite Arbitrary Block, we don't handle, so error */ + } + else + { /* Indefinite Arbitrary Block, we don't handle, so error */ rtn_code = viScanf(vi, "%*t"); /* Clear input. */ return (VI_ERROR_INV_RESPONSE); @@ -2072,12 +2214,14 @@ ViStatus hpe1564_readHeader(ViSession vi, ViPInt32 num_bytes) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calDacVolt(ViSession vi, ViReal64 voltage) { +ViStatus _VI_FUNC hpe1564_calDacVolt(ViSession vi, ViReal64 voltage) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2091,9 +2235,11 @@ ViStatus _VI_FUNC hpe1564_calDacVolt(ViSession vi, ViReal64 voltage) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:DAC:VOLT %lg\n", voltage); - } else + } + else errStatus = hpe1564_regDacSour(vi, thisPtr, voltage); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2120,21 +2266,25 @@ ViStatus _VI_FUNC hpe1564_calDacVolt(ViSession vi, ViReal64 voltage) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calDacVolt_Q(ViSession vi, ViPReal64 voltage) { +ViStatus _VI_FUNC hpe1564_calDacVolt_Q(ViSession vi, ViPReal64 voltage) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_calDacVolt_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "CAL:DAC:VOLT?\n", "%lg%*t", voltage); - } else + } + else errStatus = hpe1564_regDacSour_Q(vi, thisPtr, voltage); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2197,12 +2347,14 @@ ViStatus _VI_FUNC hpe1564_calDacVolt_Q(ViSession vi, ViPReal64 voltage) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_calData_Q(ViSession vi, ViInt16 arrayLength, - ViInt16 _VI_FAR calData[]) { + ViInt16 _VI_FAR calData[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2212,7 +2364,8 @@ ViStatus _VI_FUNC hpe1564_calData_Q(ViSession vi, ViInt16 arrayLength, hpe1564_CHK_LONG_RANGE(arrayLength, hpe1564_CAL_ARRAY_MIN, hpe1564_CAL_ARRAY_MAX, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViInt32 howMany; errStatus = viPrintf(vi, "CAL:DATA?\n"); @@ -2226,7 +2379,8 @@ ViStatus _VI_FUNC hpe1564_calData_Q(ViSession vi, ViInt16 arrayLength, #else errStatus = hpe1564_scan16(vi, arrayLength, (char *)calData, &howMany, 1); #endif - } else + } + else errStatus = hpe1564_regCalData_Q(vi, thisPtr, arrayLength, (ViInt16 *)calData); @@ -2341,13 +2495,15 @@ ViStatus _VI_FUNC hpe1564_calData_Q(ViSession vi, ViInt16 arrayLength, */ ViStatus _VI_FUNC hpe1564_calGain(ViSession vi, ViInt16 channel, ViInt32 numSamples, ViReal64 period, - ViBoolean autoCal) { + ViBoolean autoCal) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViPInt16 rdgs; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2375,10 +2531,13 @@ ViStatus _VI_FUNC hpe1564_calGain(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:GAIN%hd %ld, %lg, %hd\n", channel, numSamples, period, autoCal); - } else { + } + else + { rdgs = (ViPInt16)malloc(numSamples * sizeof(ViInt16)); if (rdgs == NULL) hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_ALLOC); @@ -2457,13 +2616,15 @@ ViStatus _VI_FUNC hpe1564_calGain(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_calOffset(ViSession vi, ViInt16 channel, - ViInt32 numSamples, ViReal64 period) { + ViInt32 numSamples, ViReal64 period) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViInt16 *rdgs; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2489,13 +2650,16 @@ ViStatus _VI_FUNC hpe1564_calOffset(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:ZERO%hd %ld, %lg\n", channel, numSamples, period); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { + } + else + { rdgs = (ViPInt16)malloc(numSamples * sizeof(ViInt16)); if (rdgs == NULL) hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_ALLOC); @@ -2585,14 +2749,16 @@ ViStatus _VI_FUNC hpe1564_calOffset(ViSession vi, ViInt16 channel, */ ViStatus _VI_FUNC hpe1564_calOffsAll_Q(ViSession vi, ViInt16 channel, ViInt32 numSamples, ViReal64 period, - ViPInt16 errCode) { + ViPInt16 errCode) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViUInt32 timeOutVal; ViPInt16 rdgs; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2618,19 +2784,22 @@ ViStatus _VI_FUNC hpe1564_calOffsAll_Q(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* save the user's timeout setting */ viGetAttribute(vi, VI_ATTR_TMO_VALUE, &timeOutVal); /* change user's timeout value if too small */ - if (timeOutVal < 180000) { + if (timeOutVal < 180000) + { /* this command takes a long time, set for 180 seconds */ viSetAttribute(vi, VI_ATTR_TMO_VALUE, 180000); } errStatus = viPrintf(vi, "CAL:ZERO%hd:ALL? %ld, %lg\n", channel, numSamples, period); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { /* if error, re-store user's timeout value */ viSetAttribute(vi, VI_ATTR_TMO_VALUE, timeOutVal); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2638,12 +2807,14 @@ ViStatus _VI_FUNC hpe1564_calOffsAll_Q(ViSession vi, ViInt16 channel, errStatus = viScanf(vi, "%hd%*t", errCode); - if (timeOutVal < 180000) { + if (timeOutVal < 180000) + { /* re-store user's timeout value */ viSetAttribute(vi, VI_ATTR_TMO_VALUE, timeOutVal); } - - } else { + } + else + { rdgs = (ViPInt16)malloc(numSamples * sizeof(ViInt16)); if (rdgs == NULL) hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_ALLOC); @@ -2691,12 +2862,14 @@ ViStatus _VI_FUNC hpe1564_calOffsAll_Q(ViSession vi, ViInt16 channel, */ static const char *const hpe1564_calSource_source_a[] = {"INT", "EXT", 0}; -ViStatus _VI_FUNC hpe1564_calSource(ViSession vi, ViInt16 source) { +ViStatus _VI_FUNC hpe1564_calSource(ViSession vi, ViInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2709,10 +2882,12 @@ ViStatus _VI_FUNC hpe1564_calSource(ViSession vi, ViInt16 source) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:SOUR %s\n", hpe1564_calSource_source_a[source]); - } else + } + else errStatus = hpe1564_regCalSource(vi, thisPtr, source); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2746,27 +2921,31 @@ ViStatus _VI_FUNC hpe1564_calSource(ViSession vi, ViInt16 source) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calSource_Q(ViSession vi, ViPInt16 source) { +ViStatus _VI_FUNC hpe1564_calSource_Q(ViSession vi, ViPInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char source_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_calSource_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "CAL:SOUR?\n", "%s%*t", source_str); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = hpe1564_findIndex(thisPtr, hpe1564_calSource_source_a, source_str, source); - } else + } + else errStatus = hpe1564_regCalSource_Q(vi, thisPtr, source); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2802,12 +2981,14 @@ ViStatus _VI_FUNC hpe1564_calSource_Q(ViSession vi, ViPInt16 source) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calState(ViSession vi, ViBoolean state) { +ViStatus _VI_FUNC hpe1564_calState(ViSession vi, ViBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2820,11 +3001,13 @@ ViStatus _VI_FUNC hpe1564_calState(ViSession vi, ViBoolean state) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:STAT %hd\n", state); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regCalState(vi, thisPtr, state); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2861,23 +3044,27 @@ ViStatus _VI_FUNC hpe1564_calState(ViSession vi, ViBoolean state) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calState_Q(ViSession vi, ViPBoolean state) { +ViStatus _VI_FUNC hpe1564_calState_Q(ViSession vi, ViPBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_calState_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "CAL:STAT?\n", "%hd%*t", state); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regCalState_Q(vi, thisPtr, state); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2902,12 +3089,14 @@ ViStatus _VI_FUNC hpe1564_calState_Q(ViSession vi, ViPBoolean state) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calStore(ViSession vi) { +ViStatus _VI_FUNC hpe1564_calStore(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -2918,11 +3107,13 @@ ViStatus _VI_FUNC hpe1564_calStore(ViSession vi) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:STOR\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regCalStore(vi, thisPtr); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -2986,12 +3177,14 @@ ViStatus _VI_FUNC hpe1564_calStore(ViSession vi) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calValue(ViSession vi, ViReal64 voltage) { +ViStatus _VI_FUNC hpe1564_calValue(ViSession vi, ViReal64 voltage) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3001,11 +3194,13 @@ ViStatus _VI_FUNC hpe1564_calValue(ViSession vi, ViReal64 voltage) { hpe1564_CHK_REAL_RANGE(voltage, hpe1564_CAL_VALUE_MIN, hpe1564_CAL_VALUE_MAX, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CAL:VAL %lg\n", voltage); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regCalValue(vi, thisPtr, voltage); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -3034,23 +3229,27 @@ ViStatus _VI_FUNC hpe1564_calValue(ViSession vi, ViReal64 voltage) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_calValue_Q(ViSession vi, ViPReal64 voltage) { +ViStatus _VI_FUNC hpe1564_calValue_Q(ViSession vi, ViPReal64 voltage) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_calValue_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "CAL:VAL?\n", "%lg%*t", voltage); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regCalValue_Q(vi, thisPtr, voltage); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -3147,12 +3346,14 @@ ViStatus _VI_FUNC hpe1564_calValue_Q(ViSession vi, ViPReal64 voltage) { */ ViStatus _VI_FUNC hpe1564_configure(ViSession vi, ViInt16 channel, ViReal64 expectMax, ViInt32 numSamples, - ViInt32 numPreTriggers) { + ViInt32 numPreTriggers) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3196,7 +3397,8 @@ ViStatus _VI_FUNC hpe1564_configure(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, ":SWE:OFFS:POIN %ld;:SWE:POIN %ld\n", -numPreTriggers, numSamples); @@ -3238,8 +3440,9 @@ ViStatus _VI_FUNC hpe1564_configure(ViSession vi, ViInt16 channel, errStatus = viPrintf(vi, "OUTP:TTLT0:STAT OFF\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - - } else { + } + else + { /* don't bother checking return status here, only setting conflicts will happen and they should resolve correctly */ @@ -3337,12 +3540,14 @@ ViStatus _VI_FUNC hpe1564_configure(ViSession vi, ViInt16 channel, */ ViStatus _VI_FUNC hpe1564_configure_Q(ViSession vi, ViInt16 channel, ViPReal64 range, ViPInt32 numSamples, - ViPInt32 numPreTriggers) { + ViPInt32 numPreTriggers) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3350,42 +3555,50 @@ ViStatus _VI_FUNC hpe1564_configure_Q(ViSession vi, ViInt16 channel, hpe1564_CDE_INIT("hpe1564_configure_Q"); hpe1564_CHK_INT_RANGE(channel, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViReal64 bigTrig; errStatus = viPrintf(vi, "VOLT%hd:RANG?\n", channel); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", range); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SAMP:COUN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%lg%*t", &bigTrig); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viPrintf(vi, "SAMP:PRET:COUN?\n"); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viScanf(vi, "%ld%*t", numPreTriggers); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } - if (bigTrig < 180000000) /* The instrument could be set to 9.9E37 */ + if (bigTrig < 180000000) /* The instrument could be set to 9.9E37 */ *numSamples = (ViInt32)(bigTrig + 0.1); /* needed for CVI round off */ else *numSamples = -1; /* Driver doesn't support INF samples */ - - } else { + } + else + { errStatus = hpe1564_regInpRange_Q(vi, thisPtr, channel, range); if (errStatus < VI_SUCCESS) @@ -3448,12 +3661,14 @@ ViStatus _VI_FUNC hpe1564_configure_Q(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagDacGain(ViSession vi, ViInt16 chan, - ViInt16 data) { + ViInt16 data) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3517,12 +3732,14 @@ ViStatus _VI_FUNC hpe1564_diagDacGain(ViSession vi, ViInt16 chan, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagDacOffs(ViSession vi, ViInt16 chan, - ViInt16 data) { + ViInt16 data) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3587,12 +3804,14 @@ ViStatus _VI_FUNC hpe1564_diagDacOffs(ViSession vi, ViInt16 chan, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagDacOffsRamp(ViSession vi, ViInt16 chan, - ViInt16 count) { + ViInt16 count) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3643,12 +3862,14 @@ ViStatus _VI_FUNC hpe1564_diagDacOffsRamp(ViSession vi, ViInt16 chan, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagDacSour(ViSession vi, ViReal64 voltage) { +ViStatus _VI_FUNC hpe1564_diagDacSour(ViSession vi, ViReal64 voltage) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3714,12 +3935,14 @@ ViStatus _VI_FUNC hpe1564_diagDacSour(ViSession vi, ViReal64 voltage) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagDacSourRamp(ViSession vi, ViInt16 count) { +ViStatus _VI_FUNC hpe1564_diagDacSourRamp(ViSession vi, ViInt16 count) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3777,13 +4000,15 @@ ViStatus _VI_FUNC hpe1564_diagDacSourRamp(ViSession vi, ViInt16 count) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagFlashRead_Q(ViSession vi, ViInt16 arrayLength, - ViInt16 _VI_FAR flashData[]) { + ViInt16 _VI_FAR flashData[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViInt16 ii; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3794,7 +4019,8 @@ ViStatus _VI_FUNC hpe1564_diagFlashRead_Q(ViSession vi, ViInt16 arrayLength, hpe1564_CHK_LONG_RANGE(arrayLength, hpe1564_FLASH_ARRAY_MIN, hpe1564_FLASH_ARRAY_MAX, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViInt32 howMany; errStatus = viPrintf(vi, "DIAG:FLAS:DATA?\n"); @@ -3810,7 +4036,9 @@ ViStatus _VI_FUNC hpe1564_diagFlashRead_Q(ViSession vi, ViInt16 arrayLength, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); #endif - } else { + } + else + { /* places the data into the calArray */ errStatus = hpe1564_regFlashRead_Q(vi, thisPtr); @@ -3867,13 +4095,15 @@ ViStatus _VI_FUNC hpe1564_diagFlashRead_Q(ViSession vi, ViInt16 arrayLength, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagFlashWrite(ViSession vi, ViBoolean doCheckSum, - ViInt16 _VI_FAR flashData[]) { + ViInt16 _VI_FAR flashData[]) +{ ViStatus errStatus = 0; ViInt16 ii; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3887,14 +4117,16 @@ ViStatus _VI_FUNC hpe1564_diagFlashWrite(ViSession vi, ViBoolean doCheckSum, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "DIAG:FLAS:DATA %hd, %269hb\n", doCheckSum, flashData); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - - } else { + } + else + { /* copy data into calArray */ for (ii = 0; ii < FLASH_DATA_SIZE; ii++) thisPtr->digState.calArray[ii] = flashData[ii]; @@ -3937,12 +4169,14 @@ ViStatus _VI_FUNC hpe1564_diagFlashWrite(ViSession vi, ViBoolean doCheckSum, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagIntLine(ViSession vi, ViInt16 intLine) { +ViStatus _VI_FUNC hpe1564_diagIntLine(ViSession vi, ViInt16 intLine) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -3956,9 +4190,12 @@ ViStatus _VI_FUNC hpe1564_diagIntLine(ViSession vi, ViInt16 intLine) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "DIAG:INT:LINE %hd\n", intLine); - } else { + } + else + { errStatus = hpe1564_regDiagInt(vi, thisPtr, intLine); } @@ -3987,21 +4224,26 @@ ViStatus _VI_FUNC hpe1564_diagIntLine(ViSession vi, ViInt16 intLine) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagIntLine_Q(ViSession vi, ViPInt16 intLine) { +ViStatus _VI_FUNC hpe1564_diagIntLine_Q(ViSession vi, ViPInt16 intLine) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_diagIntLine_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "DIAG:INT:LINE?\n", "%hd", intLine); - } else { + } + else + { errStatus = hpe1564_regDiagInt_Q(vi, thisPtr, intLine); } @@ -4041,12 +4283,14 @@ ViStatus _VI_FUNC hpe1564_diagIntLine_Q(ViSession vi, ViPInt16 intLine) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagMemSize(ViSession vi, ViInt32 memSize) { +ViStatus _VI_FUNC hpe1564_diagMemSize(ViSession vi, ViInt32 memSize) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4060,9 +4304,12 @@ ViStatus _VI_FUNC hpe1564_diagMemSize(ViSession vi, ViInt32 memSize) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "DIAG:MEM:SIZE %ld\n", memSize); - } else { + } + else + { errStatus = hpe1564_regDiagMem(vi, thisPtr, memSize); } @@ -4089,21 +4336,26 @@ ViStatus _VI_FUNC hpe1564_diagMemSize(ViSession vi, ViInt32 memSize) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagMemSize_Q(ViSession vi, ViPInt32 memSize) { +ViStatus _VI_FUNC hpe1564_diagMemSize_Q(ViSession vi, ViPInt32 memSize) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_diagMemSize_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "DIAG:MEM:SIZE?\n", "%ld", memSize); - } else { + } + else + { errStatus = hpe1564_regDiagMem_Q(vi, thisPtr, memSize); } @@ -4142,12 +4394,14 @@ ViStatus _VI_FUNC hpe1564_diagMemSize_Q(ViSession vi, ViPInt32 memSize) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagPeek_Q(ViSession vi, ViInt16 regNum, - ViPInt16 data) { + ViPInt16 data) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4203,12 +4457,14 @@ ViStatus _VI_FUNC hpe1564_diagPeek_Q(ViSession vi, ViInt16 regNum, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_diagPoke(ViSession vi, ViInt16 regNum, ViInt16 data) { +ViStatus _VI_FUNC hpe1564_diagPoke(ViSession vi, ViInt16 regNum, ViInt16 data) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4266,12 +4522,14 @@ ViStatus _VI_FUNC hpe1564_diagPoke(ViSession vi, ViInt16 regNum, ViInt16 data) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagShort(ViSession vi, ViInt16 channel, - ViBoolean state) { + ViBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4322,12 +4580,14 @@ ViStatus _VI_FUNC hpe1564_diagShort(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagTest_Q(ViSession vi, ViInt32 arrayLength, - ViInt16 _VI_FAR results[]) { + ViInt16 _VI_FAR results[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4337,7 +4597,8 @@ ViStatus _VI_FUNC hpe1564_diagTest_Q(ViSession vi, ViInt32 arrayLength, hpe1564_CHK_LONG_RANGE(arrayLength, hpe1564_TEST_ARRAY_MIN, hpe1564_TEST_ARRAY_MAX, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViInt32 howMany; errStatus = viPrintf(vi, "TEST:TST?\n"); @@ -4348,7 +4609,8 @@ ViStatus _VI_FUNC hpe1564_diagTest_Q(ViSession vi, ViInt32 arrayLength, #else errStatus = hpe1564_scan16(vi, arrayLength, (char *)results, &howMany, 1); #endif - } else + } + else errStatus = hpe1564_regTestTst_Q(vi, thisPtr, results); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -4399,12 +4661,14 @@ ViStatus _VI_FUNC hpe1564_diagTest_Q(ViSession vi, ViInt32 arrayLength, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_diagTestNum_Q(ViSession vi, ViInt16 testNum, - ViInt16 iterations, ViPInt16 failures) { + ViInt16 iterations, ViPInt16 failures) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4420,13 +4684,15 @@ ViStatus _VI_FUNC hpe1564_diagTestNum_Q(ViSession vi, ViInt16 testNum, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "TEST:NUMB? %hd, %hd\n", "%hd%*t", testNum, iterations, failures); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, 0, errStatus); - - } else { + } + else + { /* allocate some memory for use by self test */ thisPtr->memPtr = malloc(400 * sizeof(ViInt16)); errStatus = @@ -4480,13 +4746,15 @@ ViStatus _VI_FUNC hpe1564_diagTestNum_Q(ViSession vi, ViInt16 testNum, */ ViStatus _VI_FUNC hpe1564_diagTestErr_Q(ViSession vi, ViInt16 testNum, ViPInt16 diagCode, - ViChar _VI_FAR test_message[]) { + ViChar _VI_FAR test_message[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char *mssgPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4496,11 +4764,13 @@ ViStatus _VI_FUNC hpe1564_diagTestErr_Q(ViSession vi, ViInt16 testNum, hpe1564_CHK_INT_RANGE(testNum, 1, hpe1564_TESTS_IMPLEMENTED, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, "TEST:ERR? %hd\n", "%hd,%s%*t", testNum, diagCode, test_message); - - } else { + } + else + { errStatus = hpe1564_regTestErr_Q(vi, thisPtr, testNum, diagCode, &mssgPtr); sprintf(test_message, "%s", mssgPtr); @@ -4573,12 +4843,14 @@ ViStatus _VI_FUNC hpe1564_diagTestErr_Q(ViSession vi, ViInt16 testNum, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_fetchAll_Q(ViSession vi, ViInt32 arrayLength, - ViInt32 _VI_FAR data[], ViPInt32 howMany) { + ViInt32 _VI_FAR data[], ViPInt32 howMany) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4589,13 +4861,15 @@ ViStatus _VI_FUNC hpe1564_fetchAll_Q(ViSession vi, ViInt32 arrayLength, hpe1564_FETCH_ALL_MAX, VI_ERROR_PARAMETER2); /* Format is set to PACKed when session is opened via hpe1564_init */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViBoolean need_comma = 0; ViInt32 readingsPerChan; readingsPerChan = (arrayLength * 2) / thisPtr->numChans; - if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) { + if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) + { errStatus = viPrintf(vi, "FORM:DATA PACK\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -4609,7 +4883,8 @@ ViStatus _VI_FUNC hpe1564_fetchAll_Q(ViSession vi, ViInt32 arrayLength, *howMany = 0; /* if device clear, then blow outta here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { thisPtr->device_clear = 0; return VI_SUCCESS; } @@ -4621,15 +4896,20 @@ ViStatus _VI_FUNC hpe1564_fetchAll_Q(ViSession vi, ViInt32 arrayLength, errStatus = hpe1564_scan16(vi, arrayLength * 2, (char *)data, howMany, 1); #endif /* if scan16 timed out, we are hung, so do device clear */ - if (errStatus == VI_ERROR_TMO) { + if (errStatus == VI_ERROR_TMO) + { viClear(vi); *howMany = 0; - } else + } + else *howMany = *howMany / 2; - } else { + } + else + { errStatus = hpe1564_regDataAll_Q(vi, thisPtr, arrayLength, data, howMany); /* if we had a device_clear, handle it here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { hpe1564_regAbort(vi, thisPtr); thisPtr->device_clear = 0; return VI_SUCCESS; @@ -4734,7 +5014,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, ViInt16 _VI_FAR data1[], ViInt16 _VI_FAR data2[], ViInt16 _VI_FAR data3[], - ViInt16 _VI_FAR data4[], ViPInt32 howMany) { + ViInt16 _VI_FAR data4[], ViPInt32 howMany) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -4748,7 +5029,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, ViInt32 num_bytes; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -4759,45 +5041,54 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, VI_ERROR_PARAMETER2); /* Format is set to PACKed when session is opened via hpe1564_init */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* initialize chan_list to empty */ chan_list[0] = '\0'; - if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) { + if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) + { errStatus = viPrintf(vi, "FORM:DATA PACK\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); thisPtr->digState.dataFormat = hpe1564_FORM_PACK; } - if (data1 != NULL) { + if (data1 != NULL) + { strcat(chan_list, "1"); need_comma = 1; } - if (data2 != NULL) { + if (data2 != NULL) + { if (need_comma) strcat(chan_list, ",2"); - else { + else + { need_comma = 1; strcat(chan_list, "2"); } } - if (data3 != NULL) { + if (data3 != NULL) + { if (need_comma) strcat(chan_list, ",3"); - else { + else + { need_comma = 1; strcat(chan_list, "3"); } } - if (data4 != NULL) { + if (data4 != NULL) + { if (need_comma) strcat(chan_list, ",4"); - else { + else + { need_comma = 1; strcat(chan_list, "4"); } @@ -4813,7 +5104,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, *howMany = 0; /* if device clear, then blow outta here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { thisPtr->device_clear = 0; return VI_SUCCESS; } @@ -4829,9 +5121,11 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, /* set fmtStr to large block, don't use %*t */ sprintf(fmtStr, "%%%ldc", BLOCK_SIZE * 2); - while (num_bytes > 0) { + while (num_bytes > 0) + { /* if num_bytes > 8000 (dataBlock array), get a chunk */ - if (num_bytes >= BLOCK_SIZE * 2) { + if (num_bytes >= BLOCK_SIZE * 2) + { errStatus = viScanf(vi, fmtStr, (char *)dataBlock); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -4840,7 +5134,9 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, /* update numRdgs for loop below */ numRdgs = BLOCK_SIZE; - } else { + } + else + { /* note %*t in format string to finish the read */ sprintf(fmtStr, "%%%ldc%%*t", num_bytes); errStatus = viScanf(vi, fmtStr, (char *)dataBlock); @@ -4856,8 +5152,10 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, /* sort the data into the proper arrays */ ii = 0; - while (ii < numRdgs) { - if (data1 != NULL) { + while (ii < numRdgs) + { + if (data1 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_16(&dataBlock[ii]); @@ -4866,7 +5164,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data2 != NULL) { + if (data2 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_16(&dataBlock[ii]); @@ -4875,7 +5174,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data3 != NULL) { + if (data3 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_16(&dataBlock[ii]); @@ -4884,7 +5184,8 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data4 != NULL) { + if (data4 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_16(&dataBlock[ii]); @@ -4898,15 +5199,17 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, } } /* end while (num_bytes > 0) */ - - } else { + } + else + { /* Cast data pointers to void and specify packed format (parm4 = 0 ) */ errStatus = hpe1564_regData_Q(vi, thisPtr, arrayLength, 0, (void *)data1, (void *)data2, (void *)data3, (void *)data4, howMany); /* if we had a device_clear, handle it here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { hpe1564_regAbort(vi, thisPtr); thisPtr->device_clear = 0; return VI_SUCCESS; @@ -4952,23 +5255,27 @@ ViStatus _VI_FUNC hpe1564_fetch_Q(ViSession vi, ViInt32 arrayLength, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_fetchCvt_Q(ViSession vi, ViInt16 _VI_FAR data[]) { +ViStatus _VI_FUNC hpe1564_fetchCvt_Q(ViSession vi, ViInt16 _VI_FAR data[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_fetchCvt_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViInt32 howMany; - if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) { + if (thisPtr->digState.dataFormat != hpe1564_FORM_PACK) + { errStatus = viPrintf(vi, "FORM:DATA PACK\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -4985,7 +5292,8 @@ ViStatus _VI_FUNC hpe1564_fetchCvt_Q(ViSession vi, ViInt16 _VI_FAR data[]) { #else errStatus = hpe1564_scan16(vi, 4, (char *)data, &howMany, 1); #endif - } else + } + else errStatus = hpe1564_regDataCvt_Q(vi, thisPtr, data); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5012,7 +5320,8 @@ ViStatus _VI_FUNC hpe1564_fetchCvt_Q(ViSession vi, ViInt16 _VI_FAR data[]) { * swap - if == VI_TRUE, then swap bytes to Little Endian. ************/ ViStatus hpe1564_scan64(ViSession vi, ViInt32 max_length, ViPReal64 f64_array, - ViPInt32 rtn_count, ViBoolean swap) { + ViPInt32 rtn_count, ViBoolean swap) +{ ViStatus rtn_code; ViChar c[2]; ViChar length_str[16]; @@ -5033,17 +5342,21 @@ ViStatus hpe1564_scan64(ViSession vi, ViInt32 max_length, ViPReal64 f64_array, digits = c[1] - '0'; /* c[0] is the # */ /* If digits was not [0-9] then syntax problem, blow away input and return */ - if ((digits < 0) || (9 < digits)) { + if ((digits < 0) || (9 < digits)) + { rtn_code = viScanf(vi, "%*t"); /* Clear input. */ return (VI_ERROR_INV_RESPONSE); } - if (digits == 0) { + if (digits == 0) + { /* Is (Indefinite Block) */ /* Read data up to max_length, else end of input. */ /* %nnnc format reads to next END, else until nnn bytes. */ nbytes = max_length * 8; - } else { /* Must be DAB. */ + } + else + { /* Must be DAB. */ /* Scan DAB array count. */ sprintf(fmtStr, "%%%ldc", digits); @@ -5070,11 +5383,13 @@ ViStatus hpe1564_scan64(ViSession vi, ViInt32 max_length, ViPReal64 f64_array, *rtn_count = nbytes / 8; /* If (caller requests byte swapping) */ - if (swap == VI_TRUE) { + if (swap == VI_TRUE) + { unsigned char src[8]; /* Byte Swap (bytes [0->7] into bytes [7->0]). */ - for (i = 0; i < (*rtn_count); i++) { + for (i = 0; i < (*rtn_count); i++) + { /* Place the 8 byte double into src[8]. */ *((double *)src) = *((double *)(&f64_array[i])); @@ -5119,23 +5434,27 @@ ViStatus hpe1564_scan64(ViSession vi, ViInt32 max_length, ViPReal64 f64_array, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_fetchScalCvt_Q(ViSession vi, - ViReal64 _VI_FAR data[]) { + ViReal64 _VI_FAR data[]) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_fetchScalCvt_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViInt32 howMany; - if (thisPtr->digState.dataFormat != hpe1564_FORM_REAL64) { + if (thisPtr->digState.dataFormat != hpe1564_FORM_REAL64) + { thisPtr->digState.dataFormat = hpe1564_FORM_REAL64; errStatus = viPrintf(vi, "FORM:DATA REAL,64\n"); if (errStatus < VI_SUCCESS) @@ -5152,7 +5471,8 @@ ViStatus _VI_FUNC hpe1564_fetchScalCvt_Q(ViSession vi, #else errStatus = hpe1564_scan64(vi, 4, data, &howMany, 1); #endif - } else + } + else errStatus = hpe1564_regScalDataCvt_Q(vi, thisPtr, data); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5237,13 +5557,15 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, ViReal64 _VI_FAR data2[], ViReal64 _VI_FAR data3[], ViReal64 _VI_FAR data4[], - ViPInt32 howMany) { + ViPInt32 howMany) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5254,7 +5576,8 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, VI_ERROR_PARAMETER2); /* Format is set to PACKed when session is opened via hpe1564_init */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { char chan_list[10]; ViBoolean need_comma = 0; ViChar fmtStr[30]; @@ -5265,22 +5588,26 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, /* initialize list to empty */ chan_list[0] = '\0'; - if (thisPtr->digState.dataFormat != hpe1564_FORM_REAL64) { + if (thisPtr->digState.dataFormat != hpe1564_FORM_REAL64) + { thisPtr->digState.dataFormat = hpe1564_FORM_REAL64; errStatus = viPrintf(vi, "FORM:DATA REAL,64\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } - if (data1 != NULL) { + if (data1 != NULL) + { strcat(chan_list, "1"); need_comma = 1; } - if (data2 != NULL) { + if (data2 != NULL) + { if (need_comma) strcat(chan_list, ",2"); - else { + else + { need_comma = 1; strcat(chan_list, "2"); } @@ -5291,19 +5618,23 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, MessageBox(NULL, mssg, "ERROR in IPRINTF", MB_OK | MB_TASKMODAL); */ - if (data3 != NULL) { + if (data3 != NULL) + { if (need_comma) strcat(chan_list, ",3"); - else { + else + { need_comma = 1; strcat(chan_list, "3"); } } - if (data4 != NULL) { + if (data4 != NULL) + { if (need_comma) strcat(chan_list, ",4"); - else { + else + { need_comma = 1; strcat(chan_list, "4"); } @@ -5319,7 +5650,8 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, *howMany = 0; /* if device clear, then blow outta here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { thisPtr->device_clear = 0; return VI_SUCCESS; } @@ -5335,9 +5667,11 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, /* set fmtStr to large block, don't use %*t */ sprintf(fmtStr, "%%%ldc", BLOCK_SIZE * 8); - while (num_bytes > 0) { + while (num_bytes > 0) + { /* if num_bytes > 32000 (dataBlock array), get a chunk */ - if (num_bytes >= BLOCK_SIZE * 8) { + if (num_bytes >= BLOCK_SIZE * 8) + { errStatus = viScanf(vi, fmtStr, (char *)dataBlock); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5346,7 +5680,9 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, /* update numRdgs for loop below */ numRdgs = BLOCK_SIZE; - } else { + } + else + { /* note %*t in format string to finish the read */ sprintf(fmtStr, "%%%ldc%%*t", num_bytes); errStatus = viScanf(vi, fmtStr, (char *)dataBlock); @@ -5362,8 +5698,10 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, /* sort the data into the proper arrays */ ii = 0; - while (ii < numRdgs) { - if (data1 != NULL) { + while (ii < numRdgs) + { + if (data1 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_FLOAT64(&dataBlock[ii]); @@ -5372,7 +5710,8 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data2 != NULL) { + if (data2 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_FLOAT64(&dataBlock[ii]); @@ -5381,7 +5720,8 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data3 != NULL) { + if (data3 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_FLOAT64(&dataBlock[ii]); @@ -5390,7 +5730,8 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, ii += 1; } - if (data4 != NULL) { + if (data4 != NULL) + { #ifndef BIG_ENDIAN /* byte swap if not Motorola platform */ SWAP_FLOAT64(&dataBlock[ii]); @@ -5404,15 +5745,17 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, } } /* end while (num_bytes > 0) */ - - } else { + } + else + { /* Cast data pointers to void and specify real format (parm4 = 1 ) */ errStatus = hpe1564_regData_Q(vi, thisPtr, arrayLength, 1, (void *)data1, (void *)data2, (void *)data3, (void *)data4, howMany); /* if we had a device_clear, handle it here */ - if (thisPtr->device_clear) { + if (thisPtr->device_clear) + { hpe1564_regAbort(vi, thisPtr); thisPtr->device_clear = 0; return VI_SUCCESS; @@ -5467,13 +5810,15 @@ ViStatus _VI_FUNC hpe1564_fetchScal_Q(ViSession vi, ViInt32 arrayLength, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_initCont(ViSession vi, ViBoolean state) { +ViStatus _VI_FUNC hpe1564_initCont(ViSession vi, ViBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5483,7 +5828,8 @@ ViStatus _VI_FUNC hpe1564_initCont(ViSession vi, ViBoolean state) { hpe1564_CHK_BOOLEAN(state, VI_ERROR_PARAMETER2); /* error if initiated and not e1406 path */ - if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) { + if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) + { /* we are already initiated, error if we are trying to turn ON */ if (state) return hpe1564_ERROR_INIT_IGN; @@ -5491,12 +5837,15 @@ ViStatus _VI_FUNC hpe1564_initCont(ViSession vi, ViBoolean state) { if (thisPtr->e1406) errStatus = viPrintf(vi, "INIT:CONT %hd\n", state); - else { - if (state) { + else + { + if (state) + { errStatus = hpe1564_regInitContOn(vi, thisPtr); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else errStatus = hpe1564_regInitContOff(vi, thisPtr); } hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5526,13 +5875,15 @@ ViStatus _VI_FUNC hpe1564_initCont(ViSession vi, ViBoolean state) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_initCont_Q(ViSession vi, ViPBoolean state) { +ViStatus _VI_FUNC hpe1564_initCont_Q(ViSession vi, ViPBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5568,13 +5919,15 @@ ViStatus _VI_FUNC hpe1564_initCont_Q(ViSession vi, ViPBoolean state) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_initImm(ViSession vi) { +ViStatus _VI_FUNC hpe1564_initImm(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5648,13 +6001,15 @@ ViStatus _VI_FUNC hpe1564_initImm(ViSession vi) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_inpFilt(ViSession vi, ViInt16 channel, - ViReal64 filter) { + ViReal64 filter) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5669,16 +6024,20 @@ ViStatus _VI_FUNC hpe1564_inpFilt(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { if (filter < 750.0) errStatus = viPrintf(vi, "INP%hd:FILT OFF\n", channel); else errStatus = viPrintf(vi, "INP%hd:FILT ON;FILT:FREQ %lg\n", channel, filter); - } else { + } + else + { if (filter < 750.0) errStatus = hpe1564_regInpFiltStat(vi, thisPtr, channel, hpe1564_OFF); - else { + else + { errStatus = hpe1564_regInpFiltFreq(vi, thisPtr, channel, filter); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5731,14 +6090,16 @@ ViStatus _VI_FUNC hpe1564_inpFilt(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_inpFilt_Q(ViSession vi, ViInt16 channel, - ViPReal64 filter) { + ViPReal64 filter) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViBoolean state; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5747,7 +6108,8 @@ ViStatus _VI_FUNC hpe1564_inpFilt_Q(ViSession vi, ViInt16 channel, hpe1564_CHK_INT_RANGE(channel, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "INP%hd:FILT?\n", channel); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5756,7 +6118,8 @@ ViStatus _VI_FUNC hpe1564_inpFilt_Q(ViSession vi, ViInt16 channel, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { errStatus = viPrintf(vi, "INP%hd:FILT:FREQ?\n", channel); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5764,10 +6127,12 @@ ViStatus _VI_FUNC hpe1564_inpFilt_Q(ViSession vi, ViInt16 channel, errStatus = viScanf(vi, "%lg%*t", filter); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else *filter = 0.0; - - } else { + } + else + { errStatus = hpe1564_regInpFiltStat_Q(vi, thisPtr, channel, &state); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5823,13 +6188,15 @@ ViStatus _VI_FUNC hpe1564_inpFilt_Q(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_inpState(ViSession vi, ViInt16 channel, - ViBoolean state) { + ViBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5845,7 +6212,8 @@ ViStatus _VI_FUNC hpe1564_inpState(ViSession vi, ViInt16 channel, if (thisPtr->e1406) errStatus = viPrintf(vi, "INP%hd %hd\n", channel, state); - else { + else + { errStatus = hpe1564_regInpStat(vi, thisPtr, channel, state); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -5900,13 +6268,15 @@ ViStatus _VI_FUNC hpe1564_inpState(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_inpState_Q(ViSession vi, ViInt16 channel, - ViPBoolean state) { + ViPBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -5914,13 +6284,15 @@ ViStatus _VI_FUNC hpe1564_inpState_Q(ViSession vi, ViInt16 channel, hpe1564_CDE_INIT("hpe1564_inpState_Q"); hpe1564_CHK_INT_RANGE(channel, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "INP%hd?\n", channel); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%hd%*t", state); - } else + } + else errStatus = hpe1564_regInpStat_Q(vi, thisPtr, channel, state); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6055,13 +6427,15 @@ ViStatus _VI_FUNC hpe1564_inpState_Q(ViSession vi, ViInt16 channel, ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, ViPReal64 range2, ViPReal64 filt2, ViPReal64 range3, ViPReal64 filt3, - ViPReal64 range4, ViPReal64 filt4) { + ViPReal64 range4, ViPReal64 filt4) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -6097,7 +6471,8 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* let's do 2 channels at a time -- that is, send the linefeed with the second channel. @@ -6136,7 +6511,9 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, errStatus = viPrintf(vi, "INP4:STAT ON;FILT ON;FILT:FREQ %lg;:VOLT4:RANG %lg\n", *filt4, *range4); - } else { + } + else + { /* do channel 1 */ errStatus = hpe1564_regInpRange(vi, thisPtr, 1, *range1); if (errStatus < VI_SUCCESS) @@ -6148,7 +6525,8 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, */ if (*filt1 < 750.0) errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 1, hpe1564_OFF); - else { + else + { errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 1, hpe1564_ON); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6173,7 +6551,8 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, */ if (*filt2 < 750.0) errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 2, hpe1564_OFF); - else { + else + { errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 2, hpe1564_ON); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6198,7 +6577,8 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, */ if (*filt3 < 750.0) errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 3, hpe1564_OFF); - else { + else + { errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 3, hpe1564_ON); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6223,7 +6603,8 @@ ViStatus _VI_FUNC hpe1564_input(ViSession vi, ViPReal64 range1, ViPReal64 filt1, */ if (*filt4 < 750.0) errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 4, hpe1564_OFF); - else { + else + { errStatus = hpe1564_regInpFiltStat(vi, thisPtr, 4, hpe1564_ON); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6305,21 +6686,24 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, ViPReal64 filt1, ViPReal64 range2, ViPReal64 filt2, ViPReal64 range3, ViPReal64 filt3, ViPReal64 range4, - ViPReal64 filt4) { + ViPReal64 filt4) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViBoolean state; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_input_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* get the data for chan 1 */ errStatus = viPrintf(vi, "INP1:FILT?\n"); if (errStatus < VI_SUCCESS) @@ -6329,7 +6713,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { errStatus = viPrintf(vi, "INP1:FILT:FREQ?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6337,7 +6722,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, errStatus = viScanf(vi, "%lg%*t", filt1); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else *filt1 = 0.0; errStatus = viPrintf(vi, "VOLT1:RANG?\n", range1); @@ -6357,7 +6743,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { errStatus = viPrintf(vi, "INP2:FILT:FREQ?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6365,7 +6752,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, errStatus = viScanf(vi, "%lg%*t", filt2); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else *filt2 = 0.0; errStatus = viPrintf(vi, "VOLT2:RANG?\n", range2); @@ -6385,7 +6773,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { errStatus = viPrintf(vi, "INP3:FILT:FREQ?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6393,7 +6782,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, errStatus = viScanf(vi, "%lg%*t", filt3); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else *filt3 = 0.0; errStatus = viPrintf(vi, "VOLT3:RANG?\n", range3); @@ -6413,7 +6803,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { errStatus = viPrintf(vi, "INP4:FILT:FREQ?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6421,7 +6812,8 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, errStatus = viScanf(vi, "%lg%*t", filt4); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else + } + else *filt4 = 0.0; errStatus = viPrintf(vi, "VOLT4:RANG?\n", range4); @@ -6429,8 +6821,9 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%lg%*t", range4); - - } else { + } + else + { /* query channel 1 */ errStatus = hpe1564_regInpRange_Q(vi, thisPtr, 1, range1); if (errStatus < VI_SUCCESS) @@ -6533,13 +6926,15 @@ ViStatus _VI_FUNC hpe1564_input_Q(ViSession vi, ViPReal64 range1, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_limitFail_Q(ViSession vi, ViInt16 channel, - ViPBoolean status) { + ViPBoolean status) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -6547,13 +6942,15 @@ ViStatus _VI_FUNC hpe1564_limitFail_Q(ViSession vi, ViInt16 channel, hpe1564_CDE_INIT("hpe1564_limitFail_Q"); hpe1564_CHK_INT_RANGE(channel, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CALC%hd:LIM:FAIL?\n", channel); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%hd%*t", status); - } else + } + else errStatus = hpe1564_regCalcLimFail_Q(vi, thisPtr, channel, status); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6621,14 +7018,16 @@ ViStatus _VI_FUNC hpe1564_limitFail_Q(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_limitSet(ViSession vi, ViInt16 channel, - ViReal64 level, ViInt16 mode) { + ViReal64 level, ViInt16 mode) +{ ViStatus errStatus = 0; ViStatus tempErrStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -6645,20 +7044,26 @@ ViStatus _VI_FUNC hpe1564_limitSet(ViSession vi, ViInt16 channel, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { - if (mode == hpe1564_LIMIT_OFF) { + if (thisPtr->e1406) + { + if (mode == hpe1564_LIMIT_OFF) + { errStatus = viPrintf(vi, "CALC%hd:LIM:UPP OFF\n", channel); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viPrintf(vi, "CALC%hd:LIM:LOW OFF\n", channel); - } else if (mode == hpe1564_LIMIT_BELOW) { + } + else if (mode == hpe1564_LIMIT_BELOW) + { errStatus = viPrintf(vi, "CALC%hd:LIM:LOW:DATA %lg\n", channel, level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viPrintf(vi, "CALC%hd:LIM:UPP OFF;LOW ON\n", channel); - } else { /* wants to enable upper limit check */ + } + else + { /* wants to enable upper limit check */ errStatus = viPrintf(vi, "CALC%hd:LIM:UPP:DATA %lg\n", channel, level); if (errStatus < VI_SUCCESS) @@ -6666,13 +7071,17 @@ ViStatus _VI_FUNC hpe1564_limitSet(ViSession vi, ViInt16 channel, errStatus = viPrintf(vi, "CALC%hd:LIM:LOW OFF;UPP ON\n", channel); } - - } else { - if (mode == hpe1564_LIMIT_BELOW) { + } + else + { + if (mode == hpe1564_LIMIT_BELOW) + { errStatus = hpe1564_regCalcLimLowData(vi, thisPtr, channel, level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else if (mode == hpe1564_LIMIT_ABOVE) { + } + else if (mode == hpe1564_LIMIT_ABOVE) + { errStatus = hpe1564_regCalcLimUppData(vi, thisPtr, channel, level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6746,14 +7155,16 @@ ViStatus _VI_FUNC hpe1564_limitSet(ViSession vi, ViInt16 channel, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, - ViPReal64 level, ViPInt16 mode) { + ViPReal64 level, ViPInt16 mode) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; ViBoolean state; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -6762,7 +7173,8 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, hpe1564_CHK_INT_RANGE(chan, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "CALC%hd:LIM:LOW?\n", chan); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6771,7 +7183,8 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { *mode = hpe1564_LIMIT_BELOW; errStatus = viPrintf(vi, "CALC%hd:LIM:LOW:DATA?\n", chan); if (errStatus < VI_SUCCESS) @@ -6780,7 +7193,9 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, errStatus = viScanf(vi, "%lg%*t", level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { /* check for upper limit enabled */ + } + else + { /* check for upper limit enabled */ errStatus = viPrintf(vi, "CALC%hd:LIM:UPP?\n", chan); if (errStatus < VI_SUCCESS) @@ -6790,7 +7205,8 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (state) { + if (state) + { *mode = hpe1564_LIMIT_ABOVE; errStatus = viPrintf(vi, "CALC%hd:LIM:UPP:DATA?\n", chan); if (errStatus < VI_SUCCESS) @@ -6799,27 +7215,36 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, errStatus = viScanf(vi, "%lg%*t", level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { /* limit checking not enabled */ + } + else + { /* limit checking not enabled */ *level = 0.0; *mode = hpe1564_LIMIT_OFF; } } - } else { /* not E1406 */ + } + else + { /* not E1406 */ errStatus = hpe1564_regCalcLimStat_Q(vi, thisPtr, chan, mode); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (*mode == hpe1564_LIMIT_BELOW) { /* lower limit check enabled */ + if (*mode == hpe1564_LIMIT_BELOW) + { /* lower limit check enabled */ errStatus = hpe1564_regCalcLimLowData_Q(vi, thisPtr, chan, level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else if (*mode == hpe1564_LIMIT_ABOVE) { /* see if upper limit */ + } + else if (*mode == hpe1564_LIMIT_ABOVE) + { /* see if upper limit */ errStatus = hpe1564_regCalcLimUppData_Q(vi, thisPtr, chan, level); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { /* limit checking not enabled */ + } + else + { /* limit checking not enabled */ *level = 0.0; } @@ -6897,12 +7322,14 @@ ViStatus _VI_FUNC hpe1564_limitSet_Q(ViSession vi, ViInt16 chan, */ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, ViPReal64 maxTime, ViPReal64 minVolt, - ViPReal64 minTime) { + ViPReal64 minTime) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -6944,7 +7371,8 @@ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, iMin = 99999999; /* make sure data format is packed */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "FORM:DATA PACK\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -6984,7 +7412,8 @@ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_ALLOC); totalCount = 0; /* total number we have read so far */ - while (sampCount > totalCount) { + while (sampCount > totalCount) + { if (chan == 1) errStatus = @@ -7003,12 +7432,15 @@ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, goto quit; /* OK, got the data ... analyze */ - for (i = 0; i < howMany; i++) { - if (data[i] < minV) { + for (i = 0; i < howMany; i++) + { + if (data[i] < minV) + { minV = data[i]; iMin = i + totalCount; } - if (data[i] > maxV) { + if (data[i] > maxV) + { maxV = data[i]; iMax = i + totalCount; } @@ -7021,15 +7453,19 @@ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, *minVolt = range * minV / 32768.0; /* Subtract the pre-triggers */ - if (preTrigs) { + if (preTrigs) + { iMin -= preTrigs; iMax -= preTrigs; } - if (sampSour == hpe1564_SAMP_TIM) { /* See if sample source is timer */ + if (sampSour == hpe1564_SAMP_TIM) + { /* See if sample source is timer */ *maxTime = iMax * sampTime; *minTime = iMin * sampTime; - } else { + } + else + { *maxTime = iMax; *minTime = iMin; } @@ -7159,14 +7595,16 @@ ViStatus _VI_FUNC hpe1564_maxMin(ViSession vi, ViInt16 chan, ViPReal64 maxVolt, ViStatus _VI_FUNC hpe1564_measure_Q( ViSession vi, ViReal64 expected, ViInt32 numSamples, ViInt32 arrayLength, ViReal64 _VI_FAR data1[], ViReal64 _VI_FAR data2[], - ViReal64 _VI_FAR data3[], ViReal64 _VI_FAR data4[], ViPInt32 howMany) { + ViReal64 _VI_FAR data3[], ViReal64 _VI_FAR data4[], ViPInt32 howMany) +{ ViStatus errStatus = 0; ViReal64 dTemp = 1.3e-6, dLevel = 0.0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7298,13 +7736,15 @@ static const char *const hpe1564_outpTtltSour_source_a[] = {"TRIG", "SAMP", "BOTH", 0}; ViStatus _VI_FUNC hpe1564_outpTtltSour(ViSession vi, ViInt16 line, - ViInt16 source) { + ViInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7318,10 +7758,13 @@ ViStatus _VI_FUNC hpe1564_outpTtltSour(ViSession vi, ViInt16 line, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "OUTP:TTLT%hd:SOUR %s\n", line, hpe1564_outpTtltSour_source_a[source]); - } else { + } + else + { errStatus = hpe1564_regOutpTtltSour(vi, thisPtr, line, source); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7383,14 +7826,16 @@ static const char *const hpe1564_outpTtltSour_Q_source_a[] = {"TRIG", "SAMP", "BOTH", 0}; ViStatus _VI_FUNC hpe1564_outpTtltSour_Q(ViSession vi, ViInt16 line, - ViPInt16 source) { + ViPInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char source_str[10]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7398,7 +7843,8 @@ ViStatus _VI_FUNC hpe1564_outpTtltSour_Q(ViSession vi, ViInt16 line, hpe1564_CDE_INIT("hpe1564_outpTtltSour_Q"); hpe1564_CHK_ENUM(line, 7, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "OUTP:TTLT%hd:SOUR?\n", line); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7409,7 +7855,8 @@ ViStatus _VI_FUNC hpe1564_outpTtltSour_Q(ViSession vi, ViInt16 line, errStatus = hpe1564_findIndex(thisPtr, hpe1564_outpTtltSour_Q_source_a, source_str, source); - } else + } + else errStatus = hpe1564_regOutpTtltSour_Q(vi, thisPtr, line, source); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7471,13 +7918,15 @@ ViStatus _VI_FUNC hpe1564_outpTtltSour_Q(ViSession vi, ViInt16 line, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_outpTtltStat(ViSession vi, ViInt16 line, - ViBoolean state) { + ViBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7493,7 +7942,8 @@ ViStatus _VI_FUNC hpe1564_outpTtltStat(ViSession vi, ViInt16 line, if (thisPtr->e1406) errStatus = viPrintf(vi, "OUTP:TTLT%hd %hd\n", line, state); - else { + else + { errStatus = hpe1564_regOutpTtltStat(vi, thisPtr, line, state); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7553,13 +8003,15 @@ ViStatus _VI_FUNC hpe1564_outpTtltStat(ViSession vi, ViInt16 line, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_outpTtltStat_Q(ViSession vi, ViInt16 line, - ViPBoolean state) { + ViPBoolean state) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7567,13 +8019,15 @@ ViStatus _VI_FUNC hpe1564_outpTtltStat_Q(ViSession vi, ViInt16 line, hpe1564_CDE_INIT("hpe1564_outpTtltStat_Q"); hpe1564_CHK_ENUM(line, 7, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "OUTP:TTLT%hd?\n", line); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%hd%*t", state); - } else + } + else errStatus = hpe1564_regOutpTtltStat_Q(vi, thisPtr, line, state); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7643,13 +8097,15 @@ ViStatus _VI_FUNC hpe1564_outpTtltStat_Q(ViSession vi, ViInt16 line, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_range(ViSession vi, ViInt16 chan, ViReal64 range) { +ViStatus _VI_FUNC hpe1564_range(ViSession vi, ViInt16 chan, ViReal64 range) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7666,7 +8122,8 @@ ViStatus _VI_FUNC hpe1564_range(ViSession vi, ViInt16 chan, ViReal64 range) { if (thisPtr->e1406) errStatus = viPrintf(vi, "VOLT%hd:RANG %lg\n", chan, range); - else { + else + { errStatus = hpe1564_regInpRange(vi, thisPtr, chan, range); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7712,13 +8169,15 @@ ViStatus _VI_FUNC hpe1564_range(ViSession vi, ViInt16 chan, ViReal64 range) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_range_Q(ViSession vi, ViInt16 chan, ViPReal64 range) { +ViStatus _VI_FUNC hpe1564_range_Q(ViSession vi, ViInt16 chan, ViPReal64 range) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7726,13 +8185,15 @@ ViStatus _VI_FUNC hpe1564_range_Q(ViSession vi, ViInt16 chan, ViPReal64 range) { hpe1564_CDE_INIT("hpe1564_range_Q"); hpe1564_CHK_INT_RANGE(chan, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "VOLT%hd:RANG?\n", chan); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%lg%*t", range); - } else + } + else errStatus = hpe1564_regInpRange_Q(vi, thisPtr, chan, range); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -7780,13 +8241,15 @@ ViStatus _VI_FUNC hpe1564_range_Q(ViSession vi, ViInt16 chan, ViPReal64 range) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_sampCount(ViSession vi, ViInt32 numSamples, - ViInt32 numPreTriggers) { + ViInt32 numPreTriggers) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -7810,7 +8273,8 @@ ViStatus _VI_FUNC hpe1564_sampCount(ViSession vi, ViInt32 numSamples, if (thisPtr->e1406) errStatus = viPrintf(vi, ":SAMP:COUN %ld;PRET:COUN %ld\n", numSamples, numPreTriggers); - else { + else + { char message[40]; /* the following checks can only be done on this path, because the @@ -7818,14 +8282,16 @@ ViStatus _VI_FUNC hpe1564_sampCount(ViSession vi, ViInt32 numSamples, */ /* check sample count against specific memory option */ - if (thisPtr->maxSampCount < numSamples) { + if (thisPtr->maxSampCount < numSamples) + { sprintf(message, "Max. count is %ld", thisPtr->maxSampCount); hpe1564_CDE_MESSAGE(message); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER2); } /* check pretrigger count against specific memory option */ - if (thisPtr->maxSampCount - 1 < numPreTriggers) { + if (thisPtr->maxSampCount - 1 < numPreTriggers) + { sprintf(message, "Max. pretrigger is %ld", thisPtr->maxSampCount - 1); hpe1564_CDE_MESSAGE(message); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER3); @@ -7889,43 +8355,53 @@ ViStatus _VI_FUNC hpe1564_sampCount(ViSession vi, ViInt32 numSamples, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_sampCount_Q(ViSession vi, ViPInt32 numSamples, - ViPInt32 numPreTriggers) { + ViPInt32 numPreTriggers) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_sampCount_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViReal64 bigSamp; errStatus = viQueryf(vi, "SAMP:COUN?\n", "%lg%*t", &bigSamp); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viQueryf(vi, "SAMP:PRET:COUN?\n", "%ld%*t", numPreTriggers); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } /* If CONTinuous init, D-SCPI will report back 9.9E37 for count, which is infinite. We will report back -1 here to caller. */ - if (bigSamp < 2.4E9) { /* The instrument could be set to 9.9E37 */ + if (bigSamp < 2.4E9) + { /* The instrument could be set to 9.9E37 */ bigSamp = bigSamp + 0.1; /* needed for CVI round off */ *numSamples = (ViInt32)(bigSamp); - } else + } + else *numSamples = -1; /* Indicate INF triggers */ - } else { + } + else + { errStatus = hpe1564_regSampCount_Q(vi, thisPtr, numSamples); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } @@ -7958,12 +8434,14 @@ ViStatus _VI_FUNC hpe1564_sampCount_Q(ViSession vi, ViPInt32 numSamples, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_sampImm(ViSession vi) { +ViStatus _VI_FUNC hpe1564_sampImm(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -8008,13 +8486,15 @@ ViStatus _VI_FUNC hpe1564_sampImm(ViSession vi) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_sampSlop(ViSession vi, ViBoolean slope) { +ViStatus _VI_FUNC hpe1564_sampSlop(ViSession vi, ViBoolean slope) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -8027,12 +8507,15 @@ ViStatus _VI_FUNC hpe1564_sampSlop(ViSession vi, ViBoolean slope) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { if (slope == hpe1564_SLOP_NEG) errStatus = viPrintf(vi, ":SAMP:SLOP NEG\n"); else errStatus = viPrintf(vi, ":SAMP:SLOP POS\n"); - } else { + } + else + { errStatus = hpe1564_regSampSlop(vi, thisPtr, slope); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8074,7 +8557,8 @@ ViStatus _VI_FUNC hpe1564_sampSlop(ViSession vi, ViBoolean slope) { */ static const char *const hpe1564_sampSlop_Q_slope_a[] = {"NEG", "POS", 0}; -ViStatus _VI_FUNC hpe1564_sampSlop_Q(ViSession vi, ViPBoolean slope) { +ViStatus _VI_FUNC hpe1564_sampSlop_Q(ViSession vi, ViPBoolean slope) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -8082,14 +8566,16 @@ ViStatus _VI_FUNC hpe1564_sampSlop_Q(ViSession vi, ViPBoolean slope) { ViInt16 tslope; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_sampSlop_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, ":SAMP:SLOP?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8101,7 +8587,8 @@ ViStatus _VI_FUNC hpe1564_sampSlop_Q(ViSession vi, ViPBoolean slope) { errStatus = hpe1564_findIndex(thisPtr, hpe1564_sampSlop_Q_slope_a, slope_str, &tslope); *slope = (0 == tslope) ? VI_FALSE : VI_TRUE; - } else + } + else errStatus = hpe1564_regSampSlop_Q(vi, thisPtr, slope); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8186,17 +8673,19 @@ ViStatus _VI_FUNC hpe1564_sampSlop_Q(ViSession vi, ViPBoolean slope) { *----------------------------------------------------------------------------- */ static const char *const hpe1564_sampSour_source_a[] = { - "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", - "TTLT5", "TTLT6", "TTLT7", "EXT", "EXT", 0}; + "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", + "TTLT5", "TTLT6", "TTLT7", "EXT", "EXT", 0}; -ViStatus _VI_FUNC hpe1564_sampSour(ViSession vi, ViInt16 source) { +ViStatus _VI_FUNC hpe1564_sampSour(ViSession vi, ViInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char source_str[10]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -8209,8 +8698,10 @@ ViStatus _VI_FUNC hpe1564_sampSour(ViSession vi, ViInt16 source) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { - switch (source) { + if (thisPtr->e1406) + { + switch (source) + { case hpe1564_SAMP_HOLD: errStatus = viPrintf(vi, ":SAMP:SOUR HOLD\n"); break; @@ -8234,18 +8725,22 @@ ViStatus _VI_FUNC hpe1564_sampSour(ViSession vi, ViInt16 source) { if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - } else { + } + else + { errStatus = hpe1564_regSampSour(vi, thisPtr, source); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - if (source == hpe1564_SAMP_EXT_RISE) { + if (source == hpe1564_SAMP_EXT_RISE) + { errStatus = hpe1564_regSampSlop(vi, thisPtr, hpe1564_SLOP_POS); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } - if (source == hpe1564_SAMP_EXT_FALL) { + if (source == hpe1564_SAMP_EXT_FALL) + { errStatus = hpe1564_regSampSlop(vi, thisPtr, hpe1564_SLOP_NEG); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8309,10 +8804,11 @@ ViStatus _VI_FUNC hpe1564_sampSour(ViSession vi, ViInt16 source) { */ static const char *const hpe1564_sampSour_Q_source_a[] = { - "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", - "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT", 0}; + "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", + "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT", 0}; -ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) { +ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -8321,14 +8817,16 @@ ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) { ViInt16 slope; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_sampSour_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, ":SAMP:SOUR?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8341,7 +8839,8 @@ ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) { source_str, source); /* if source was EXT, we need to know slope */ - if (*source > hpe1564_SAMP_TTLT7) { + if (*source > hpe1564_SAMP_TTLT7) + { errStatus = viPrintf(vi, "SAMP:SLOP?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8360,8 +8859,8 @@ ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) { if (slope == hpe1564_SLOP_NEG) *source = *source + 1; } - - } else + } + else errStatus = hpe1564_regSampSour_Q(vi, thisPtr, source); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8398,13 +8897,15 @@ ViStatus _VI_FUNC hpe1564_sampSour_Q(ViSession vi, ViPInt16 source) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_sampTim(ViSession vi, ViReal64 period) { +ViStatus _VI_FUNC hpe1564_sampTim(ViSession vi, ViReal64 period) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -8418,13 +8919,15 @@ ViStatus _VI_FUNC hpe1564_sampTim(ViSession vi, ViReal64 period) { if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { /* for longer periods, send 8 decimal places of info. */ if (period > 0.065) errStatus = viPrintf(vi, ":SAMP:TIM %0.8lg\n", period); else errStatus = viPrintf(vi, ":SAMP:TIM %lg\n", period); - } else + } + else errStatus = hpe1564_regSampTim(vi, thisPtr, period); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8454,26 +8957,30 @@ ViStatus _VI_FUNC hpe1564_sampTim(ViSession vi, ViReal64 period) { * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_sampTim_Q(ViSession vi, ViPReal64 period) { +ViStatus _VI_FUNC hpe1564_sampTim_Q(ViSession vi, ViPReal64 period) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_sampTim_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, ":SAMP:TIM?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%lg%*t", period); - } else + } + else errStatus = hpe1564_regSampTim_Q(vi, thisPtr, period); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8593,18 +9100,20 @@ ViStatus _VI_FUNC hpe1564_sampTim_Q(ViSession vi, ViPReal64 period) { *----------------------------------------------------------------------------- */ static const char *const hpe1564_sample_source_a[] = { - "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", - "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT", 0}; + "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", + "TTLT4", "TTLT5", "TTLT6", "TTLT7", "EXT", 0}; ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, ViInt32 numPreTriggers, ViInt16 source, - ViPReal64 period) { + ViPReal64 period) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -8632,8 +9141,10 @@ ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { - switch (source) { + if (thisPtr->e1406) + { + switch (source) + { case hpe1564_SAMP_HOLD: errStatus = viPrintf(vi, ":SAMP:SOUR HOLD\n"); break; @@ -8664,7 +9175,9 @@ ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, errStatus = viPrintf(vi, ":SAMP:COUN %ld;PRET:COUN %ld\n", numSamples, numPreTriggers); - } else { + } + else + { char message[40]; /* the following checks can only be done on this path, because the @@ -8672,14 +9185,16 @@ ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, */ /* check sample count against specific memory option */ - if (thisPtr->maxSampCount < numSamples) { + if (thisPtr->maxSampCount < numSamples) + { sprintf(message, "Max. count is %ld", thisPtr->maxSampCount); hpe1564_CDE_MESSAGE(message); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER2); } /* check pretrigger count against specific memory option */ - if (thisPtr->maxSampCount - 1 < numPreTriggers) { + if (thisPtr->maxSampCount - 1 < numPreTriggers) + { sprintf(message, "Max. pretrigger is %ld", thisPtr->maxSampCount - 1); hpe1564_CDE_MESSAGE(message); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER3); @@ -8701,7 +9216,8 @@ ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - switch (source) { + switch (source) + { case hpe1564_SAMP_TIM: errStatus = hpe1564_regSampTim(vi, thisPtr, *period); break; @@ -8780,13 +9296,14 @@ ViStatus _VI_FUNC hpe1564_sample(ViSession vi, ViInt32 numSamples, *----------------------------------------------------------------------------- */ static const char *const hpe1564_sample_Q_source_a[] = { - "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", - "TTLT5", "TTLT6", "TTLT7", "EXT", "EXT", 0}; + "HOLD", "TIM", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", + "TTLT5", "TTLT6", "TTLT7", "EXT", "EXT", 0}; static const char *const hpe1564_sample_Q_slope_a[] = {"NEG", "POS", 0}; ViStatus _VI_FUNC hpe1564_sample_Q(ViSession vi, ViPInt32 numSamples, ViPInt32 numPreTriggers, ViPInt16 source, - ViPReal64 period) { + ViPReal64 period) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -8795,14 +9312,16 @@ ViStatus _VI_FUNC hpe1564_sample_Q(ViSession vi, ViPInt32 numSamples, ViBoolean slope; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_sample_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { ViReal64 bigSamp; @@ -8828,7 +9347,8 @@ ViStatus _VI_FUNC hpe1564_sample_Q(ViSession vi, ViPInt32 numSamples, hpe1564_LOG_STATUS(vi, thisPtr, errStatus); /* if source was EXT, we need to know slope */ - if (*source > hpe1564_SAMP_TTLT7) { + if (*source > hpe1564_SAMP_TTLT7) + { errStatus = viPrintf(vi, "SAMP:SLOP?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8849,24 +9369,30 @@ ViStatus _VI_FUNC hpe1564_sample_Q(ViSession vi, ViPInt32 numSamples, } errStatus = viQueryf(vi, "SAMP:COUN?\n", "%lg%*t", &bigSamp); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } errStatus = viQueryf(vi, "SAMP:PRET:COUN?\n", "%ld%*t", numPreTriggers); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, thisPtr, errStatus); } /* If CONTinuous init, D-SCPI will report back 9.9E37 for count, which is infinite. We will report back -1 here to caller. */ - if (bigSamp < 2.4E9) { /* The instrument could be set to 9.9E37 */ + if (bigSamp < 2.4E9) + { /* The instrument could be set to 9.9E37 */ bigSamp = bigSamp; *numSamples = (ViInt32)(bigSamp + 0.1); - } else + } + else *numSamples = -1; /* Indicate INF triggers */ - } else { + } + else + { errStatus = hpe1564_regSampSour_Q(vi, thisPtr, source); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -8941,26 +9467,30 @@ ViStatus _VI_FUNC hpe1564_sample_Q(ViSession vi, ViPInt32 numSamples, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_status_Q(ViSession vi, ViPInt16 status) { +ViStatus _VI_FUNC hpe1564_status_Q(ViSession vi, ViPInt16 status) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_status_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "DIAG:STAT?\n"); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%hd%*t", status); - } else + } + else errStatus = hpe1564_regDiagStat_Q(vi, thisPtr, status); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -9011,12 +9541,14 @@ ViStatus _VI_FUNC hpe1564_status_Q(ViSession vi, ViPInt16 status) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_timeBase(ViSession vi, ViInt16 source, - ViReal64 freq) { + ViReal64 freq) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9031,12 +9563,15 @@ ViStatus _VI_FUNC hpe1564_timeBase(ViSession vi, ViInt16 source, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { + if (thisPtr->e1406) + { if (source == hpe1564_TIMEBASE_EXT) errStatus = viPrintf(vi, ":ROSC:SOUR EXT;EXT:FREQ %lg\n", freq); else errStatus = viPrintf(vi, ":ROSC:SOUR INT;EXT:FREQ 10.0e6\n"); - } else { + } + else + { /* no errors are returned from the next two calls */ errStatus = hpe1564_regRoscFreq(vi, thisPtr, freq); errStatus = hpe1564_regRoscSour(vi, thisPtr, source); @@ -9073,20 +9608,23 @@ ViStatus _VI_FUNC hpe1564_timeBase(ViSession vi, ViInt16 source, static const char *const hpe1564_timeBase_source_a[] = {"INT", "EXT", 0}; ViStatus _VI_FUNC hpe1564_timeBase_Q(ViSession vi, ViPInt16 source, - ViPReal64 freq) { + ViPReal64 freq) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char source_str[10]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } hpe1564_DEBUG_CHK_THIS(vi, thisPtr); hpe1564_CDE_INIT("hpe1564_timeBase_Q"); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, ":ROSC:SOUR? %s%*t\n", source_str); if (VI_SUCCESS > errStatus) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -9097,7 +9635,9 @@ ViStatus _VI_FUNC hpe1564_timeBase_Q(ViSession vi, ViPInt16 source, hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viQueryf(vi, ":ROSC:EXT:FREQ?\n", "%lg%*t", freq); - } else { + } + else + { /* no errors are returned from the next two calls */ errStatus = hpe1564_regRoscFreq_Q(vi, thisPtr, freq); errStatus = hpe1564_regRoscSour_Q(vi, thisPtr, source); @@ -9214,19 +9754,21 @@ ViStatus _VI_FUNC hpe1564_timeBase_Q(ViSession vi, ViPInt16 source, *----------------------------------------------------------------------------- */ static const char *const hpe1564_trigEvent_source_a[] = { - "BUS", "EXT", "EXT", "HOLD", "IMM", "INT1", "INT1", "INT2", - "INT2", "INT3", "INT3", "INT4", "INT4", "TTLT0", "TTLT1", "TTLT2", + "BUS", "EXT", "EXT", "HOLD", "IMM", "INT1", "INT1", "INT2", + "INT2", "INT3", "INT3", "INT4", "INT4", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", 0}; ViStatus _VI_FUNC hpe1564_trigEvent(ViSession vi, ViInt16 event, ViInt16 source, - ViPReal64 level) { + ViPReal64 level) +{ ViStatus errStatus = 0; ViStatus ignore = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9242,8 +9784,10 @@ ViStatus _VI_FUNC hpe1564_trigEvent(ViSession vi, ViInt16 event, ViInt16 source, if (thisPtr->e1406 == 0 && hpe1564_regIsInitiated(vi, thisPtr)) return hpe1564_ERROR_INIT_IGN; - if (thisPtr->e1406) { - switch (source) { + if (thisPtr->e1406) + { + switch (source) + { case hpe1564_TRIG_LEVEL1_FALL: case hpe1564_TRIG_LEVEL2_FALL: case hpe1564_TRIG_LEVEL3_FALL: @@ -9313,10 +9857,12 @@ ViStatus _VI_FUNC hpe1564_trigEvent(ViSession vi, ViInt16 event, ViInt16 source, errStatus = viPrintf(vi, "TRIG:SOUR%hd %s\n", event, hpe1564_trigEvent_source_a[source]); } /* end switch */ - } else + } + else /* make sure download enum numbers match source int here */ { - switch (source) { + switch (source) + { case hpe1564_TRIG_LEVEL1_FALL: case hpe1564_TRIG_LEVEL2_FALL: case hpe1564_TRIG_LEVEL3_FALL: @@ -9476,13 +10022,14 @@ ViStatus _VI_FUNC hpe1564_trigEvent(ViSession vi, ViInt16 event, ViInt16 source, /* note that EXT may be returned instead of EXT1 */ static const char *const hpe1564_trigEvent_Q_source_a[] = { - "BUS", "EXT", "EXT", "HOLD", "IMM", "INT", "INT1", "INT2", - "INT2", "INT3", "INT3", "INT4", "INT4", "TTLT0", "TTLT1", "TTLT2", + "BUS", "EXT", "EXT", "HOLD", "IMM", "INT", "INT1", "INT2", + "INT2", "INT3", "INT3", "INT4", "INT4", "TTLT0", "TTLT1", "TTLT2", "TTLT3", "TTLT4", "TTLT5", "TTLT6", "TTLT7", 0}; static const char *const hpe1564_trigEvent_Q_slope_a[] = {"NEG", "POS", 0}; ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, - ViPInt16 source, ViPReal64 level) { + ViPInt16 source, ViPReal64 level) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; @@ -9492,7 +10039,8 @@ ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, ViBoolean tslope; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9502,7 +10050,8 @@ ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, hpe1564_CHK_INT_RANGE(event, hpe1564_TRIG_EVENT_MIN, hpe1564_TRIG_EVENT_MAX, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "TRIG:SOUR%hd?\n", event); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -9519,7 +10068,8 @@ ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, /* return 0.0 for level if not active source */ *level = 0.0; - switch (*source) { + switch (*source) + { case hpe1564_TRIG_LEVEL1_FALL: case hpe1564_TRIG_LEVEL2_FALL: case hpe1564_TRIG_LEVEL3_FALL: @@ -9637,13 +10187,15 @@ ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, *source = *source - 1; break; } - - } else { + } + else + { errStatus = hpe1564_regTrigSour_Q(vi, thisPtr, event, source); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); - switch (*source) { + switch (*source) + { case hpe1564_TRIG_LEVEL1_FALL: case hpe1564_TRIG_LEVEL2_FALL: case hpe1564_TRIG_LEVEL3_FALL: @@ -9721,13 +10273,15 @@ ViStatus _VI_FUNC hpe1564_trigEvent_Q(ViSession vi, ViInt16 event, * *----------------------------------------------------------------------------- */ -ViStatus _VI_FUNC hpe1564_trigImm(ViSession vi) { +ViStatus _VI_FUNC hpe1564_trigImm(ViSession vi) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9789,13 +10343,15 @@ ViStatus _VI_FUNC hpe1564_trigImm(ViSession vi) { *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_trigLevel(ViSession vi, ViInt16 chan, - ViReal64 level) { + ViReal64 level) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9853,13 +10409,15 @@ ViStatus _VI_FUNC hpe1564_trigLevel(ViSession vi, ViInt16 chan, *----------------------------------------------------------------------------- */ ViStatus _VI_FUNC hpe1564_trigLevel_Q(ViSession vi, ViInt16 chan, - ViPReal64 level) { + ViPReal64 level) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (errStatus < VI_SUCCESS) { + if (errStatus < VI_SUCCESS) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9867,13 +10425,15 @@ ViStatus _VI_FUNC hpe1564_trigLevel_Q(ViSession vi, ViInt16 chan, hpe1564_CDE_INIT("hpe1564_trigLevel_Q"); hpe1564_CHK_INT_RANGE(chan, 1, 4, VI_ERROR_PARAMETER2); - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viPrintf(vi, "TRIG:LEV%hd?\n", chan); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = viScanf(vi, "%lg%*t", level); - } else + } + else errStatus = hpe1564_regTrigLev_Q(vi, thisPtr, chan, level); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -9944,14 +10504,16 @@ ViStatus _VI_FUNC hpe1564_trigLevel_Q(ViSession vi, ViInt16 chan, */ static const char *const hpe1564_trigMode_mode_a[] = { "NORMAL", "MASTER0", "MASTER2", "MASTER4", "MASTER6", - "SLAVE0", "SLAVE2", "SLAVE4", "SLAVE6", 0}; + "SLAVE0", "SLAVE2", "SLAVE4", "SLAVE6", 0}; -ViStatus _VI_FUNC hpe1564_trigMode(ViSession vi, ViInt16 mode) { +ViStatus _VI_FUNC hpe1564_trigMode(ViSession vi, ViInt16 mode) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -9963,7 +10525,8 @@ ViStatus _VI_FUNC hpe1564_trigMode(ViSession vi, ViInt16 mode) { hpe1564_CHK_ENUM(mode, 8, VI_ERROR_PARAMETER2); if (thisPtr->e1406) errStatus = viPrintf(vi, "TRIG:MODE %s\n", hpe1564_trigMode_mode_a[mode]); - else { + else + { errStatus = hpe1564_regTrigMode(vi, thisPtr, mode); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -10012,15 +10575,17 @@ ViStatus _VI_FUNC hpe1564_trigMode(ViSession vi, ViInt16 mode) { */ static const char *const hpe1564_trigMode_Q_mode_a[] = { "NORMAL", "MASTER0", "MASTER2", "MASTER4", "MASTER6", - "SLAVE0", "SLAVE2", "SLAVE4", "SLAVE6", 0}; + "SLAVE0", "SLAVE2", "SLAVE4", "SLAVE6", 0}; -ViStatus _VI_FUNC hpe1564_trigMode_Q(ViSession vi, ViPInt16 mode) { +ViStatus _VI_FUNC hpe1564_trigMode_Q(ViSession vi, ViPInt16 mode) +{ ViStatus errStatus = 0; hpe1564_globals *thisPtr; char mode_str[32]; errStatus = viGetAttribute(vi, VI_ATTR_USER_DATA, (ViAddr)&thisPtr); - if (VI_SUCCESS > errStatus) { + if (VI_SUCCESS > errStatus) + { hpe1564_LOG_STATUS(vi, 0, errStatus); } @@ -10029,15 +10594,16 @@ ViStatus _VI_FUNC hpe1564_trigMode_Q(ViSession vi, ViPInt16 mode) { hpe1564_CDE_INIT("hpe1564_trigMode_Q"); /* Perform Error Checking on Each Parameter */ - if (thisPtr->e1406) { + if (thisPtr->e1406) + { errStatus = viQueryf(vi, ":TRIG:MODE?\n", "%s%*t", mode_str); if (errStatus < VI_SUCCESS) hpe1564_LOG_STATUS(vi, thisPtr, errStatus); errStatus = hpe1564_findIndex(thisPtr, hpe1564_trigMode_Q_mode_a, mode_str, mode); - - } else + } + else errStatus = hpe1564_regTrigMode_Q(vi, thisPtr, mode); hpe1564_LOG_STATUS(vi, thisPtr, errStatus); @@ -10081,7 +10647,8 @@ hpe1564_statEvenHdlr *****************************************************************************/ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, hpe1564_InstrEventHandler eventHandler, - ViAddr userData) { + ViAddr userData) +{ ViUInt16 intf; hpe1564_globals *thisPtr; ViStatus errStatus; @@ -10098,17 +10665,20 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, hpe1564_CDE_INIT("hpe1564_statEvenHdlr"); /* if we are not VI_INTF_VXI, then only one happening allowed */ - if (intf != VI_INTF_VXI) { + if (intf != VI_INTF_VXI) + { /* return param 2 error if happening not USER_ERROR or INSTR_ERROR */ if ((hpe1564_USER_ERROR_HANDLER != happening) && - (hpe1564_INSTR_ERROR_HANDLER != happening)) { + (hpe1564_INSTR_ERROR_HANDLER != happening)) + { sprintf(errMsg, "%hd " hpe1564_MSG_INVALID_HAPPENING, happening); hpe1564_CDE_MESSAGE(errMsg); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER2); } } - if (hpe1564_USER_ERROR_HANDLER == happening) { + if (hpe1564_USER_ERROR_HANDLER == happening) + { /* store handler and user data */ thisPtr->eventHandlerArray[hpe1564_USER_ERROR_HANDLER_IDX].eventHandler = eventHandler; @@ -10117,7 +10687,8 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, hpe1564_LOG_STATUS(vi, thisPtr, VI_SUCCESS); } - if (hpe1564_INSTR_ERROR_HANDLER == happening) { + if (hpe1564_INSTR_ERROR_HANDLER == happening) + { /* store handler and user data */ thisPtr->eventHandlerArray[hpe1564_INSTR_ERROR_HANDLER_IDX].eventHandler = eventHandler; @@ -10127,7 +10698,8 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, } /* check validity of happening */ - if (VI_FALSE == hpe1564_findHappeningIdx(happening, &hapIdx)) { + if (VI_FALSE == hpe1564_findHappeningIdx(happening, &hapIdx)) + { sprintf(errMsg, "%ld " hpe1564_MSG_INVALID_HAPPENING, (long)happening); hpe1564_CDE_MESSAGE(errMsg); @@ -10136,12 +10708,16 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, } /* see if we want to enable or disable the handler */ - if (NULL != eventHandler) { + if (NULL != eventHandler) + { /* see if event handler already exists */ - if (NULL == thisPtr->eventHandlerArray[hapIdx].eventHandler) { + if (NULL == thisPtr->eventHandlerArray[hapIdx].eventHandler) + { /* okay - no event handler */ thisPtr->numEventHandlers = thisPtr->numEventHandlers + 1; - } else { + } + else + { /* error - event handler already exists */ sprintf(errMsg, hpe1564_MSG_EVENT_HDLR_INSTALLED @@ -10156,9 +10732,11 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr(ViSession vi, ViInt32 happening, thisPtr->eventHandlerArray[hapIdx].userData = userData; } /* if - install event handler */ - else { + else + { /* see if event handler already exists */ - if (NULL != thisPtr->eventHandlerArray[hapIdx].eventHandler) { + if (NULL != thisPtr->eventHandlerArray[hapIdx].eventHandler) + { /* We do have a handler we will be un-installing */ thisPtr->numEventHandlers = thisPtr->numEventHandlers - 1; } @@ -10206,7 +10784,8 @@ hpe1564_statEvenHdlr_Q *****************************************************************************/ ViStatus _VI_FUNC hpe1564_statEvenHdlr_Q( ViSession vi, ViInt32 happening, hpe1564_InstrPEventHandler pEventHandler, - ViPAddr pUserData) { + ViPAddr pUserData) +{ ViUInt16 intf; hpe1564_globals *thisPtr; ViStatus errStatus; @@ -10223,10 +10802,12 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr_Q( viGetAttribute(vi, VI_ATTR_INTF_TYPE, &intf); /* only 2 happenings allowed if we are not VXI intf */ - if (intf != VI_INTF_VXI) { + if (intf != VI_INTF_VXI) + { /* return param 2 error if happening not USER_ERROR or INSTR_ERROR */ if (hpe1564_USER_ERROR_HANDLER != happening && - hpe1564_INSTR_ERROR_HANDLER != happening) { + hpe1564_INSTR_ERROR_HANDLER != happening) + { sprintf(errMsg, "%hd " hpe1564_MSG_INVALID_HAPPENING, happening); hpe1564_CDE_MESSAGE(errMsg); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER2); @@ -10234,11 +10815,16 @@ ViStatus _VI_FUNC hpe1564_statEvenHdlr_Q( } /* check validity of happening */ - if (hpe1564_USER_ERROR_HANDLER == happening) { + if (hpe1564_USER_ERROR_HANDLER == happening) + { hapIdx = hpe1564_USER_ERROR_HANDLER_IDX; - } else if (hpe1564_INSTR_ERROR_HANDLER == happening) { + } + else if (hpe1564_INSTR_ERROR_HANDLER == happening) + { hapIdx = hpe1564_INSTR_ERROR_HANDLER_IDX; - } else if (VI_FALSE == hpe1564_findHappeningIdx(happening, &hapIdx)) { + } + else if (VI_FALSE == hpe1564_findHappeningIdx(happening, &hapIdx)) + { sprintf(errMsg, "%hd " hpe1564_MSG_INVALID_HAPPENING, happening); hpe1564_CDE_MESSAGE(errMsg); hpe1564_LOG_STATUS(vi, thisPtr, VI_ERROR_PARAMETER2); diff --git a/kbsidevices/ni5122.c b/kbsidevices/ni5122.c index a34a236024..bea9a78833 100644 --- a/kbsidevices/ni5122.c +++ b/kbsidevices/ni5122.c @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // id = ih °°Àº ¶æÀÌ´Ù. ¿©±â¼­´Â ih¸¦ »ç¿ë Çß´Ù. /* Print the error message */ -int NiScope_errorHandler(ViSession ih, ViInt32 code) { +int NiScope_errorHandler(ViSession ih, ViInt32 code) +{ ViStatus status; ViChar source[MAX_FUNCTION_NAME_SIZE]; ViChar desc[MAX_ERROR_DESCRIPTION]; @@ -55,7 +56,8 @@ int NiScope_errorHandler(ViSession ih, ViInt32 code) { } // NiScope_init -> NiScope_close -int NiScope_init(char *dev, ViSession *ih) { +int NiScope_init(char *dev, ViSession *ih) +{ // printf("%s\n", dev); // ViSession ih; ViStatus status; @@ -65,7 +67,8 @@ int NiScope_init(char *dev, ViSession *ih) { return status; } -int NiScope_initiateacquisition(ViSession ih) { +int NiScope_initiateacquisition(ViSession ih) +{ ViStatus status; status = niScope_InitiateAcquisition(ih); if (status != VI_SUCCESS) @@ -73,14 +76,16 @@ int NiScope_initiateacquisition(ViSession ih) { return status; } -int NiScope_acquisitionstatus(ViSession ih) { +int NiScope_acquisitionstatus(ViSession ih) +{ ViStatus status; ViInt32 as; status = niScope_AcquisitionStatus(ih, &as); if (status != VI_SUCCESS) NiScope_errorHandler(ih, status); - switch (as) { + switch (as) + { case NISCOPE_VAL_ACQ_IN_PROGRESS: printf("The acquisition is in progress.\n"); break; @@ -95,7 +100,8 @@ int NiScope_acquisitionstatus(ViSession ih) { } /* Device Setup */ -int NiScope_configuretriggerimmediate(ViSession ih) { +int NiScope_configuretriggerimmediate(ViSession ih) +{ ViStatus status; status = niScope_ConfigureTriggerImmediate(ih); if (status != VI_SUCCESS) @@ -104,7 +110,8 @@ int NiScope_configuretriggerimmediate(ViSession ih) { } int NiScope_ConfigureChanCharacteristics(ViSession ih, char *dev, - ViReal64 *impe) { + ViReal64 *impe) +{ ViStatus status; status = niScope_ConfigureChanCharacteristics(ih, dev, *impe, 0.00); if (status != VI_SUCCESS) @@ -114,7 +121,8 @@ int NiScope_ConfigureChanCharacteristics(ViSession ih, char *dev, } int NiScope_ConfigureVertical(ViSession ih, char *dev, ViReal64 *range, - ViReal64 *offset, ViInt32 coupl, ViReal64 *pa) { + ViReal64 *offset, ViInt32 coupl, ViReal64 *pa) +{ // ViBoolean Enable(channel enable true,false)==value -> // IVI_ATTR_BASE(1000000),IVI_CLASS_PUBLIC_ATTR_BASE (IVI_ATTR_BASE + 250000) // IVISCOPE_ATTR_CHANNEL_ENABLED (IVI_CLASS_PUBLIC_ATTR_BASE + 5L) ==>total @@ -136,7 +144,8 @@ int NiScope_ConfigureVertical(ViSession ih, char *dev, ViReal64 *range, //¹Þ°í Çѹø¿¡ ÀúÀåÀ» ÇÒ°ÍÀÎÁö Á¤ÇÑ´Ù. ±×·²¶§°¡ °¡²û ÇÊ¿äÇÏ´Ù. ¿ì¸®´Â º¸Åë 1ȸ¿¡ //Çѹø µ¥ÀÌÅ͸¦ ¹Þ´Â´Ù. int NiScope_ConfigureHorizontalTiming(ViSession ih, ViReal64 *msr, - ViInt32 mup) { + ViInt32 mup) +{ ViStatus status; status = niScope_ConfigureHorizontalTiming(ih, *msr, mup, 50.0, 1, NISCOPE_VAL_TRUE); @@ -147,7 +156,8 @@ int NiScope_ConfigureHorizontalTiming(ViSession ih, ViReal64 *msr, /* Trigger */ int NiScope_ConfigureTriggerEdge(ViSession ih, char *ts, ViReal64 *level, - ViInt32 slope, ViInt32 tc, ViReal64 *delay) { + ViInt32 slope, ViInt32 tc, ViReal64 *delay) +{ ViStatus status; status = niScope_ConfigureTriggerEdge(ih, ts, *level, slope, tc, 0.0, *delay); if (status != VI_SUCCESS) @@ -156,7 +166,8 @@ int NiScope_ConfigureTriggerEdge(ViSession ih, char *ts, ViReal64 *level, } /* commits to hardware all the parameter settings associated with the task.*/ -int NiScope_Commit(ViSession ih) { +int NiScope_Commit(ViSession ih) +{ ViStatus status; status = niScope_Commit(ih); if (status != VI_SUCCESS) @@ -167,7 +178,8 @@ int NiScope_Commit(ViSession ih) { /* stored */ // Returns the effective sample rate of the acquired waveform using the current // configuration in samples per second. -int NiScope_SampleRate(ViSession ih, ViReal64 *samplerate) { +int NiScope_SampleRate(ViSession ih, ViReal64 *samplerate) +{ ViStatus status; status = niScope_SampleRate(ih, samplerate); if (status != VI_SUCCESS) @@ -180,7 +192,8 @@ int NiScope_SampleRate(ViSession ih, ViReal64 *samplerate) { // determine the size of the waveforms that the digitizer acquires. // Allocate a ViReal64 array of this size or greater to pass as the // waveformArray parameter of niScope_ReadWaveform and niScope_FetchWaveform -int NiScope_ActualRecordLength(ViSession ih, ViPInt32 recordlength) { +int NiScope_ActualRecordLength(ViSession ih, ViPInt32 recordlength) +{ ViStatus status; status = niScope_ActualRecordLength(ih, recordlength); if (status != VI_SUCCESS) @@ -191,7 +204,8 @@ int NiScope_ActualRecordLength(ViSession ih, ViPInt32 recordlength) { // the array length can be determined by calling niScope_ActualNumWfms. // Allows you to declare appropriately-sized waveforms. NI-SCOPE handles the // channel list parsing for you. -int NiScope_ActualNumWfms(ViSession ih, char *dev, ViPInt32 numwfms) { +int NiScope_ActualNumWfms(ViSession ih, char *dev, ViPInt32 numwfms) +{ ViStatus status; status = niScope_ActualNumWfms(ih, dev, numwfms); if (status != VI_SUCCESS) @@ -200,7 +214,8 @@ int NiScope_ActualNumWfms(ViSession ih, char *dev, ViPInt32 numwfms) { } // Returns the total available size of an array measurement acquisition. -int NiScope_ActualMeasWfmSize(ViSession ih, ViPInt32 measwaveformsize) { +int NiScope_ActualMeasWfmSize(ViSession ih, ViPInt32 measwaveformsize) +{ ViStatus status; status = niScope_ActualMeasWfmSize(ih, NISCOPE_VAL_MULTIPLY_CHANNELS, measwaveformsize); @@ -330,7 +345,8 @@ MdsPut(pathName,"BUILD_SIGNAL(BUILD_WITH_UNITS(($*$VALUE)+$,'V'),(`$[0:$]),MAKE_ } */ -int NiScope_close(ViSession ih) { +int NiScope_close(ViSession ih) +{ ViStatus status; status = niScope_close(ih); if (status != VI_SUCCESS) diff --git a/kbsidevices/nidaq.c b/kbsidevices/nidaq.c index 73d8ec518b..bc2deb9295 100644 --- a/kbsidevices/nidaq.c +++ b/kbsidevices/nidaq.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define NTASK (4) #define DllExport __declspec(dllexport) -struct DataChain { +struct DataChain +{ int16 *data; uInt32 num; struct DataChain *next; @@ -41,7 +42,8 @@ struct DataChain { typedef struct DataChain sDataChain; -typedef struct { +typedef struct +{ TaskHandle handle; sDataChain *start; sDataChain *current; @@ -49,12 +51,14 @@ typedef struct { uInt32 num, numChannels; } sTask; -struct { +struct +{ unsigned int num; sTask *item; } tasks; -int task_insert(TaskHandle handle) { +int task_insert(TaskHandle handle) +{ int i, j, num; /* Find the next empty item */ @@ -63,7 +67,8 @@ int task_insert(TaskHandle handle) { if (tasks.item[i].handle == 0) break; /* If there is no empty one, make more rooms */ - if (i == num) { + if (i == num) + { tasks.num += NTASK; tasks.item = realloc(tasks.item, tasks.num * sizeof(sTask)); for (j = num + 1; j < tasks.num; j++) @@ -73,7 +78,8 @@ int task_insert(TaskHandle handle) { return i; } -int DllExport _nidaq_open(char *name) { +int DllExport _nidaq_open(char *name) +{ int id, status; char buf[256]; TaskHandle handle; @@ -81,7 +87,8 @@ int DllExport _nidaq_open(char *name) { sDataChain *pData; status = DAQmxLoadTask(name, &handle); - if (status) { + if (status) + { DAQmxGetErrorString(status, buf, 256); printf("%s\n", buf); return status; @@ -93,7 +100,8 @@ int DllExport _nidaq_open(char *name) { DAQmxGetReadAttribute(handle, DAQmx_Read_NumChans, &pTask->numChannels); DAQmxGetTimingAttribute(handle, DAQmx_SampTimingType, &pTask->type); - if (pTask->type == DAQmx_Val_OnDemand) { + if (pTask->type == DAQmx_Val_OnDemand) + { pData = malloc(sizeof(sDataChain)); pData->data = malloc(NBUF * pTask->numChannels * sizeof(short)); pData->num = 0; @@ -106,7 +114,8 @@ int DllExport _nidaq_open(char *name) { return id; } -int DllExport _nidaq_close(int id) { +int DllExport _nidaq_close(int id) +{ sTask *pTask; pTask = tasks.item + id; @@ -116,11 +125,13 @@ int DllExport _nidaq_close(int id) { return 1; } -int DllExport _nidaq_init(int id) { +int DllExport _nidaq_init(int id) +{ return DAQmxStartTask(tasks.item[id].handle); } -int DllExport _nidaq_read(int id) { +int DllExport _nidaq_read(int id) +{ int32 samplesRead; sTask *pTask; sDataChain *pData, *pNext; @@ -130,7 +141,8 @@ int DllExport _nidaq_read(int id) { return 0; pData = pTask->current; /* if the data is full, make another chain */ - if (pData->num == NBUF) { + if (pData->num == NBUF) + { pNext = malloc(sizeof(sDataChain)); pNext->data = malloc(NBUF * pTask->numChannels * sizeof(short)); pNext->num = 0; @@ -149,7 +161,8 @@ int DllExport _nidaq_read(int id) { return pTask->num; } -int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { +int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) +{ char channelName[256], pathName[256]; int16 *data; int32 stats, samplesRead, idesc, idesc1, idesc2, idesc3, idesc4, idesc5, @@ -161,14 +174,18 @@ int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { sDataChain *pData, *pNext; pTask = tasks.item + id; - if (simultaneous) { + if (simultaneous) + { dt = 0.0; - } else { + } + else + { DAQmxGetTimingAttribute(pTask->handle, DAQmx_AIConv_Rate, &convRate); dt = 1.0 / convRate; } - if (pTask->type == DAQmx_Val_OnDemand) { + if (pTask->type == DAQmx_Val_OnDemand) + { pData = pTask->current; samplesRead = pTask->num * NBUF + pData->num; arraySize = pTask->numChannels * samplesRead; @@ -176,7 +193,8 @@ int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { nPacket = NBUF * pTask->numChannels; packetSize = nPacket * sizeof(int16); pNext = pTask->start; - for (i = 0; i < pTask->num; i++) { + for (i = 0; i < pTask->num; i++) + { pData = pNext; memcpy(data + i * nPacket, pData->data, packetSize); pNext = pData->next; @@ -187,7 +205,9 @@ int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { pNext->num * pTask->numChannels * sizeof(int16)); free(pNext->data); free(pNext); - } else { + } + else + { /* # of samples */ DAQmxGetTimingAttribute(pTask->handle, DAQmx_SampQuant_SampPerChan, &numSamples); @@ -224,7 +244,8 @@ int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { idesc = descr(&dtype, &range, &null); idesc5 = descr(&dtype, &convRate, &null); idesc6 = descr(&dtype, &period, &null); - for (i = 0; i < pTask->numChannels; i++) { + for (i = 0; i < pTask->numChannels; i++) + { /* Translate a channel name to a node name */ DAQmxGetNthTaskChannel(pTask->handle, i + 1, channelName, 256); sprintf(pathName, "%s:%s:FOO", nodeName, channelName); @@ -245,8 +266,10 @@ int DllExport _nidaq_store(int id, char *nodeName, int simultaneous) { return 1; } -int __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { - switch (fdwReason) { +int __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + switch (fdwReason) + { case DLL_PROCESS_ATTACH: if (InitCVIRTE(hinstDLL, 0, 0) == 0) return 0; /* out of memory */ @@ -261,7 +284,8 @@ int __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { } int __stdcall DllEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason, - LPVOID lpvReserved) { + LPVOID lpvReserved) +{ /* Included for compatibility with Borland */ return DllMain(hinstDLL, fdwReason, lpvReserved); diff --git a/kbsidevices/tkvx4244.c b/kbsidevices/tkvx4244.c index 4d15551bb7..851ae283ef 100644 --- a/kbsidevices/tkvx4244.c +++ b/kbsidevices/tkvx4244.c @@ -76,7 +76,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ViUInt16 tkvx4244_modelCodes[] = {0x70b}; -#define tkvx4244_NUM_MODEL_CODES \ +#define tkvx4244_NUM_MODEL_CODES \ (sizeof(tkvx4244_modelCodes) / sizeof(ViUInt16)) /*************************************************************************** @@ -109,7 +109,8 @@ ViUInt16 tkvx4244_modelCodes[] = {0x70b}; * a per instrument basis */ -typedef struct { +typedef struct +{ ViString instrDesc; /* ASCII instrument descriptor string */ ViReal64 tkvx4244_version; /* Instrument firmware version */ ViInt16 tkvx4244_chOneActive; @@ -314,7 +315,7 @@ ViString tkvx4244_errorStrings[] = { "FDC starting memory address out of range.", "Invalid FDC buffer size."}; -#define tkvx4244_NUMBER_OF_ERRORS \ +#define tkvx4244_NUMBER_OF_ERRORS \ (sizeof(tkvx4244_errorStrings) / sizeof(ViString)) /*************************************************************************** * INSTRUMENT-DEPENDENT COMMAND ARRAYS @@ -375,18 +376,18 @@ ViString freqinval[] = {"TINT", "RANG"}; ViString arm_slopZ[] = {"SLOP POS", "SLOP NEG", "ZERO 1", "ZERO 0"}; /* trig source and logic commands */ -ViString trgsrcL[] = {"LOGI AND", "LOGI OR", "SOUR EXT", "SOUR IMM", +ViString trgsrcL[] = {"LOGI AND", "LOGI OR", "SOUR EXT", "SOUR IMM", "SOUR TTL 0", "SOUR TTL 1", "SOUR TTL 2", "SOUR TTL 3", "SOUR TTL 4", "SOUR TTL 5", "SOUR TTL 6", "SOUR TTL 7", - "SOUR THRE", "SOUR VXICMD"}; + "SOUR THRE", "SOUR VXICMD"}; /* threshold trigger descriptor commands */ ViString thrshCmd[] = {"PSL", "NSL", "GTL", "LTL"}; /* clock Synch Commands */ ViString clksynch[] = {"LEVEL POS", "LEVEL NEG", "LEVEL NEG", "IMM", - "TTL 8", "TTL 1", "TTL 2", "TTL 3", - "TTL 4", "TTL 5", "TTL 6", "TTL 7"}; + "TTL 8", "TTL 1", "TTL 2", "TTL 3", + "TTL 4", "TTL 5", "TTL 6", "TTL 7"}; /* postprocess commands */ ViString process[] = {"MIN", "MAX", "AVE", "PTR", "NTR", "TRMS"}; @@ -409,7 +410,8 @@ ViString fdcQuery[] = {"MODE", "TRANS", "QUE"}; ViInt16 tkvx4244_gNumberFound = 0; -struct { +struct +{ ViInt16 logAdr; /* Instrument logical address */ ViInt16 slot; /* Instrument slot # */ ViChar @@ -468,7 +470,8 @@ ViStatus tkvx4244_gplist_parse(ViInt16 g1, ViInt16 g2, ViInt16 g3, ViInt16 g4, ViStatus _VI_FUNC tkvx4244_autoConnectToAll(ViSession instrumentHndlArray[], ViInt16 arrayLength, - ViPInt16 numberConnected) { + ViPInt16 numberConnected) +{ ViStatus retError; /* Returned error status */ ViInt16 numFound; /* # instrs found */ ViInt16 theLogAdr[tkvx4244_MAX_NUM_OF_LA]; /* temporary storage for LAs */ @@ -479,19 +482,26 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToAll(ViSession instrumentHndlArray[], retError = tkvx4244_getSlotandLAList(VI_NULL, theLogAdr, tkvx4244_RCV_STRLEN, &numFound); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; - } else if (numFound == 0) { + } + else if (numFound == 0) + { return VI_ERROR_RSRC_NFOUND; - } else if (numFound > arrayLength) { + } + else if (numFound > arrayLength) + { numFound = arrayLength; } - for (ii = 0; ii < numFound; ii++) { + for (ii = 0; ii < numFound; ii++) + { retError = tkvx4244_tryAutoConnect(VI_NULL, theLogAdr[ii], &instrumentHndlArray[ii]); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; } @@ -516,15 +526,19 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToAll(ViSession instrumentHndlArray[], * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus _VI_FUNC tkvx4244_autoConnectToFirst(ViPSession instrumentHandle) { +ViStatus _VI_FUNC tkvx4244_autoConnectToFirst(ViPSession instrumentHandle) +{ ViStatus retError; /* Returned error status */ ViInt16 numFound; /* # instrs found */ ViInt16 theLogAdr; /* logical address */ retError = tkvx4244_getSlotandLAList(VI_NULL, &theLogAdr, 1, &numFound); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; - } else if (numFound == 0) { + } + else if (numFound == 0) + { return VI_ERROR_RSRC_NFOUND; } @@ -551,7 +565,8 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToFirst(ViPSession instrumentHandle) { */ ViStatus _VI_FUNC tkvx4244_autoConnectToLA(ViPSession instrumentHandle, - ViInt16 logicalAddress) { + ViInt16 logicalAddress) +{ ViStatus retError; /* Returned error status */ retError = tkvx4244_tryAutoConnect(VI_NULL, logicalAddress, instrumentHandle); @@ -583,7 +598,8 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToLA(ViPSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_autoConnectToSlot(ViSession instrumentArray[], ViInt16 arrayLength, ViPInt16 numberConnected, - ViInt16 slot) { + ViInt16 slot) +{ ViStatus retError; /* Returned error status */ ViInt16 numFound; /* Temporary storage for # instrs found */ ViInt16 theSlotPtr[tkvx4244_RCV_STRLEN]; @@ -594,14 +610,19 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToSlot(ViSession instrumentArray[], retError = tkvx4244_getSlotandLAList(theSlotPtr, theLogAdr, tkvx4244_RCV_STRLEN, &numFound); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; - } else if (numFound == 0) { + } + else if (numFound == 0) + { return VI_ERROR_RSRC_NFOUND; } - for (ii = 0; ii < numFound; ii++) { - if (theSlotPtr[ii] == slot) { + for (ii = 0; ii < numFound; ii++) + { + if (theSlotPtr[ii] == slot) + { retError = tkvx4244_tryAutoConnect(VI_NULL, theLogAdr[ii], &instrumentArray[*numberConnected]); if (retError < VI_SUCCESS) @@ -614,9 +635,12 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToSlot(ViSession instrumentArray[], break; } - if (*numberConnected == 0) { + if (*numberConnected == 0) + { return VI_ERROR_RSRC_NFOUND; - } else { + } + else + { return VI_SUCCESS; } } @@ -643,19 +667,22 @@ ViStatus _VI_FUNC tkvx4244_autoConnectToSlot(ViSession instrumentArray[], * after calling this routine. */ -ViStatus _VI_FUNC tkvx4244_close(ViSession instrumentHandle) { +ViStatus _VI_FUNC tkvx4244_close(ViSession instrumentHandle) +{ ViStatus retError; /* Returned error status */ ViAddr userData; /* User data stored in VI_ATTR_USER_DATA */ tkvx4244_PdrvrStruct drvrHdl; /* pointer to instrument specific data */ - if (instrumentHandle != VI_NULL) { + if (instrumentHandle != VI_NULL) + { retError = viGetAttribute(instrumentHandle, VI_ATTR_USER_DATA, &userData); if (retError < VI_SUCCESS) return retError; drvrHdl = (tkvx4244_PdrvrStruct)userData; - if (drvrHdl != NULL) { + if (drvrHdl != NULL) + { /* Free any mallocs in the tkvx4244_instr_array struct */ free(drvrHdl->instrDesc); @@ -664,7 +691,9 @@ ViStatus _VI_FUNC tkvx4244_close(ViSession instrumentHandle) { retError = viClose(instrumentHandle); return retError; - } else { + } + else + { return VI_SUCCESS; } } @@ -690,7 +719,8 @@ ViStatus _VI_FUNC tkvx4244_close(ViSession instrumentHandle) { ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, ViBoolean resetDevice, - ViPSession instrumentHandle) { + ViPSession instrumentHandle) +{ ViSession resMgr; /* Resource Manager Session */ ViStatus retError; /* Returned error status */ tkvx4244_PdrvrStruct drvrHdl; /* pointer to instrument specific data */ @@ -702,13 +732,15 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, /* Open Instrument */ retError = viGetDefaultRM(&resMgr); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { *instrumentHandle = VI_NULL; return retError; } retError = viOpen(resMgr, resourceName, VI_NULL, VI_NULL, instrumentHandle); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { *instrumentHandle = VI_NULL; return retError; } @@ -717,7 +749,8 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, retError = viSetAttribute(*instrumentHandle, VI_ATTR_USER_DATA, (ViAttr)VI_NULL); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return retError; @@ -725,9 +758,11 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, /* Perform ID Query */ - if (IDQuery) { + if (IDQuery) + { retError = tkvx4244_verifyID(*instrumentHandle); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return retError; @@ -735,9 +770,11 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, } /* Initialize the instrument to a known state. */ - if (resetDevice) { + if (resetDevice) + { retError = tkvx4244_reset(*instrumentHandle); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return retError; @@ -748,7 +785,8 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, retError = viSetAttribute(*instrumentHandle, VI_ATTR_TMO_VALUE, tkvx4244_DEFAULT_TIMEOUT); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return retError; @@ -757,7 +795,8 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, /* Initialize interface for instrument. */ drvrHdl = (tkvx4244_PdrvrStruct)malloc(sizeof(tkvx4244_drvrStruct)); - if (drvrHdl == NULL) { + if (drvrHdl == NULL) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return VI_ERROR_ALLOC; @@ -765,14 +804,16 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, retError = viSetAttribute(*instrumentHandle, VI_ATTR_USER_DATA, (ViAttr)drvrHdl); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return retError; } drvrHdl->instrDesc = (ViString)malloc(strlen(resourceName) + 1); - if (drvrHdl->instrDesc == NULL) { + if (drvrHdl->instrDesc == NULL) + { tkvx4244_close(*instrumentHandle); *instrumentHandle = VI_NULL; return VI_ERROR_ALLOC; @@ -797,7 +838,8 @@ ViStatus _VI_FUNC tkvx4244_init(ViRsrc resourceName, ViBoolean IDQuery, * Returns: * VI_VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus tkvx4244_variableInitialize(ViSession instrumentHandle) { +ViStatus tkvx4244_variableInitialize(ViSession instrumentHandle) +{ ViStatus retError; /* Returned error status */ ViAddr userData; /* User data stored in VI_ATTR_USER_DATA */ @@ -844,45 +886,59 @@ ViStatus tkvx4244_variableInitialize(ViSession instrumentHandle) { ViStatus _VI_FUNC tkvx4244_error_message(ViSession instrumentHandle, ViStatus errorCode, - ViChar errorMessage[]) { + ViChar errorMessage[]) +{ ViStatus retError; /* Returned error status */ retError = VI_SUCCESS; if ((errorCode >= tkvx4244_GENERIC_ERROR) && (errorCode <= 0xBFFC0FFFL) && - (errorCode < VI_SUCCESS)) { + (errorCode < VI_SUCCESS)) + { errorCode -= tkvx4244_GENERIC_ERROR; - if (errorCode < tkvx4244_NUMBER_OF_ERRORS) { + if (errorCode < tkvx4244_NUMBER_OF_ERRORS) + { sprintf(errorMessage, "%s Error: %s", tkvx4244_NAME, tkvx4244_errorStrings[errorCode]); - } else { + } + else + { sprintf(errorMessage, "%s Error: Unrecognized error %ld", tkvx4244_NAME, errorCode + tkvx4244_GENERIC_ERROR); } - } else { - switch (errorCode) { - case VI_WARN_NSUP_ID_QUERY: { + } + else + { + switch (errorCode) + { + case VI_WARN_NSUP_ID_QUERY: + { strcpy(errorMessage, "Warning: ID query is not supported."); break; } - case VI_WARN_NSUP_RESET: { + case VI_WARN_NSUP_RESET: + { strcpy(errorMessage, "Warning: reset is not supported."); break; } - case VI_WARN_NSUP_SELF_TEST: { + case VI_WARN_NSUP_SELF_TEST: + { strcpy(errorMessage, "Warning: self-test is not supported."); break; } - case VI_WARN_NSUP_ERROR_QUERY: { + case VI_WARN_NSUP_ERROR_QUERY: + { strcpy(errorMessage, "Warning: error query is not supported."); break; } - case VI_WARN_NSUP_REV_QUERY: { + case VI_WARN_NSUP_REV_QUERY: + { strcpy(errorMessage, "Warning: revision query is not supported."); break; } - default: { + default: + { retError = viStatusDesc(instrumentHandle, errorCode, errorMessage); } } @@ -908,7 +964,8 @@ ViStatus _VI_FUNC tkvx4244_error_message(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_error_query(ViSession instrumentHandle, ViPInt32 errorCode, - ViChar errorMessage[]) { + ViChar errorMessage[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* Instrument receive string */ ViInt32 retCnt; /* VISA return count */ @@ -950,14 +1007,16 @@ ViStatus _VI_FUNC tkvx4244_error_query(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_getInstrDesc(ViSession instrumentHandle, - ViChar instrumentDescriptor[]) { + ViChar instrumentDescriptor[]) +{ ViStatus retError; /* Returned error status */ ViAddr userData; /* User data attribute value */ tkvx4244_PdrvrStruct drvrHdl; /* pointer to instrument specific data */ retError = viGetAttribute(instrumentHandle, VI_ATTR_USER_DATA, &userData); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; } @@ -988,7 +1047,8 @@ ViStatus _VI_FUNC tkvx4244_getInstrDesc(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_getLogicalAddress(ViSession instrumentHandle, - ViPInt16 logicalAddress) { + ViPInt16 logicalAddress) +{ ViStatus retError; /* Returned error status */ retError = viGetAttribute(instrumentHandle, VI_ATTR_VXI_LA, logicalAddress); @@ -1012,7 +1072,8 @@ ViStatus _VI_FUNC tkvx4244_getLogicalAddress(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_getManufacturerID( - ViSession instrumentHandle, ViPInt16 manufacturerIdentification) { + ViSession instrumentHandle, ViPInt16 manufacturerIdentification) +{ ViStatus retError; /* Returned error status */ retError = viGetAttribute(instrumentHandle, VI_ATTR_MANF_ID, @@ -1038,7 +1099,8 @@ ViStatus _VI_FUNC tkvx4244_getManufacturerID( * VI_INTF_USB (7) */ ViStatus _VI_FUNC tkvx4244_getInterfaceType(ViSession instrumentHandle, - ViPUInt16 interface) { + ViPUInt16 interface) +{ ViStatus retError; /* Returned error status */ retError = viGetAttribute(instrumentHandle, VI_ATTR_INTF_TYPE, interface); @@ -1061,7 +1123,8 @@ ViStatus _VI_FUNC tkvx4244_getInterfaceType(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_getModelCode(ViSession instrumentHandle, - ViPInt16 modelCode) { + ViPInt16 modelCode) +{ ViStatus retError; /* Returned error status */ retError = viGetAttribute(instrumentHandle, VI_ATTR_MODEL_CODE, modelCode); @@ -1089,7 +1152,8 @@ ViStatus _VI_FUNC tkvx4244_getModelCode(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_getSlotandLAList(ViInt16 slotArray[], ViInt16 logicalAddressArray[], ViInt16 arrayLength, - ViPInt16 numberFound) { + ViPInt16 numberFound) +{ ViStatus retError; /* Returned error status */ ViInt16 ii; /* loop count */ @@ -1100,28 +1164,37 @@ ViStatus _VI_FUNC tkvx4244_getSlotandLAList(ViInt16 slotArray[], if (retError < VI_SUCCESS) return retError; - if (tkvx4244_gNumberFound == 0) { + if (tkvx4244_gNumberFound == 0) + { return VI_ERROR_RSRC_NFOUND; - } else if (tkvx4244_gNumberFound > arrayLength) { + } + else if (tkvx4244_gNumberFound > arrayLength) + { *numberFound = arrayLength; - } else { + } + else + { *numberFound = tkvx4244_gNumberFound; } - if ((slotArray == NULL) && (logicalAddressArray == NULL)) { + if ((slotArray == NULL) && (logicalAddressArray == NULL)) + { *numberFound = 0; } - for (ii = 0; ii < *numberFound; ii++) { + for (ii = 0; ii < *numberFound; ii++) + { /* * Add instrument slot number and logical address to arrays */ - if (slotArray != NULL) { + if (slotArray != NULL) + { slotArray[ii] = tkvx4244_instrAttr[ii].slot; } - if (logicalAddressArray != NULL) { + if (logicalAddressArray != NULL) + { logicalAddressArray[ii] = tkvx4244_instrAttr[ii].logAdr; } } @@ -1145,7 +1218,8 @@ ViStatus _VI_FUNC tkvx4244_getSlotandLAList(ViInt16 slotArray[], */ ViStatus _VI_FUNC tkvx4244_getSlotNumber(ViSession instrumentHandle, - ViPInt16 slot) { + ViPInt16 slot) +{ ViStatus retError; /* Returned error status */ retError = viGetAttribute(instrumentHandle, VI_ATTR_SLOT, slot); @@ -1171,7 +1245,8 @@ ViStatus _VI_FUNC tkvx4244_getSlotNumber(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_getSlotList(ViInt16 slotArray[], ViInt16 slotArrayLength, - ViPInt16 numberFound) { + ViPInt16 numberFound) +{ ViStatus retError; /* Returned error status */ retError = tkvx4244_getSlotandLAList(slotArray, VI_NULL, slotArrayLength, @@ -1196,7 +1271,8 @@ ViStatus _VI_FUNC tkvx4244_getSlotList(ViInt16 slotArray[], */ ViStatus _VI_FUNC tkvx4244_getVisaRev(ViSession instrumentHandle, - ViChar revision[]) { + ViChar revision[]) +{ ViStatus retError; /* Returned error status */ ViVersion tmpRev; /* VISA revision attribute */ ViInt16 tmpMajor; /* VISA major revison digits */ @@ -1209,7 +1285,8 @@ ViStatus _VI_FUNC tkvx4244_getVisaRev(ViSession instrumentHandle, retError = viGetAttribute(instrumentHandle, VI_ATTR_RSRC_SPEC_VERSION, &tmpRev); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { return retError; } @@ -1220,16 +1297,20 @@ ViStatus _VI_FUNC tkvx4244_getVisaRev(ViSession instrumentHandle, if (tmpMajor < 4) strcpy(vtl, "VTL "); - else { + else + { strcpy(vtl, ""); tmpMajor = (ViInt16)VI_VERSION_MAJOR(tmpRev); tmpMinor = (ViInt16)VI_VERSION_MINOR(tmpRev); tmpSubMinor = (ViInt16)VI_VERSION_SUBMINOR(tmpRev); } - if (tmpSubMinor == 0) { + if (tmpSubMinor == 0) + { sprintf(revision, "%s%hd.%hd", vtl, tmpMajor, tmpMinor); - } else { + } + else + { sprintf(revision, "%s%hd.%hd.%hd", vtl, tmpMajor, tmpMinor, tmpSubMinor); } @@ -1250,7 +1331,8 @@ ViStatus _VI_FUNC tkvx4244_getVisaRev(ViSession instrumentHandle, * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus _VI_FUNC tkvx4244_reset(ViSession instrumentHandle) { +ViStatus _VI_FUNC tkvx4244_reset(ViSession instrumentHandle) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViStatus retError; /* Returned error status */ ViInt32 retCnt; /* VISA return count */ @@ -1283,7 +1365,8 @@ ViStatus _VI_FUNC tkvx4244_reset(ViSession instrumentHandle) { ViStatus _VI_FUNC tkvx4244_revision_query(ViSession instrumentHandle, ViChar driverRevision[], - ViChar instrumentRevision[]) { + ViChar instrumentRevision[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* Instrument receive string */ ViStatus retError; /* Returned error status */ @@ -1333,7 +1416,8 @@ ViStatus _VI_FUNC tkvx4244_revision_query(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_self_test(ViSession instrumentHandle, ViPInt16 selfTestResult, - ViChar selfTestMessage[]) { + ViChar selfTestMessage[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* Instrument receive string */ ViStatus retError; /* Returned error status */ @@ -1355,10 +1439,13 @@ ViStatus _VI_FUNC tkvx4244_self_test(ViSession instrumentHandle, if (retError < VI_SUCCESS) return retError; - if (rcv[0] == '0') { + if (rcv[0] == '0') + { *selfTestResult = VI_FALSE; sprintf(selfTestMessage, "Self Test Passed"); - } else { + } + else + { *selfTestResult = VI_TRUE; sprintf(selfTestMessage, "Self Test Failed\n\rUse Error query to check failures"); @@ -1390,7 +1477,8 @@ ViStatus _VI_FUNC tkvx4244_self_test(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_perform_self_test(ViSession instrumentHandle, ViPStatus selfTestResult, - ViChar selfTestMessage[]) { + ViChar selfTestMessage[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* Instrument receive string */ ViStatus retError; /* Returned error status */ @@ -1412,10 +1500,13 @@ ViStatus _VI_FUNC tkvx4244_perform_self_test(ViSession instrumentHandle, if (retError < VI_SUCCESS) return retError; - if (rcv[0] == '0') { + if (rcv[0] == '0') + { *selfTestResult = VI_FALSE; sprintf(selfTestMessage, "Self Test Passed"); - } else { + } + else + { *selfTestResult = VI_TRUE; sprintf(selfTestMessage, "Self Test Failed\n\rUse Error query to check failures"); @@ -1437,7 +1528,8 @@ ViStatus _VI_FUNC tkvx4244_perform_self_test(ViSession instrumentHandle, * ViStatus VI_SUCCESS */ -ViStatus _VI_FUNC tkvx4244_sleep(ViInt32 secondsToDelay) { +ViStatus _VI_FUNC tkvx4244_sleep(ViInt32 secondsToDelay) +{ time_t start; /* time of entry into this routine */ time_t current; /* Updated time as routine progresses */ @@ -1445,8 +1537,9 @@ ViStatus _VI_FUNC tkvx4244_sleep(ViInt32 secondsToDelay) { time(¤t); /* initialize update time */ while ((current - start) < - (time_t)secondsToDelay) { /* has delay completed? */ - time(¤t); /* no, update */ + (time_t)secondsToDelay) + { /* has delay completed? */ + time(¤t); /* no, update */ } return VI_SUCCESS; } @@ -1466,7 +1559,8 @@ ViStatus _VI_FUNC tkvx4244_sleep(ViInt32 secondsToDelay) { * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus _VI_FUNC tkvx4244_write(ViSession instrumentHandle, ViString command) { +ViStatus _VI_FUNC tkvx4244_write(ViSession instrumentHandle, ViString command) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* Instrument command string */ ViStatus retError; /* Returned error status */ ViInt32 retCnt; /* VISA return count */ @@ -1494,7 +1588,8 @@ ViStatus _VI_FUNC tkvx4244_write(ViSession instrumentHandle, ViString command) { * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus _VI_FUNC tkvx4244_read(ViSession instrumentHandle, ViChar message[]) { +ViStatus _VI_FUNC tkvx4244_read(ViSession instrumentHandle, ViChar message[]) +{ ViChar rcv[tkvx4244_RCV_STRLEN]; /* Instrument receive string */ ViStatus retError; /* Returned error status */ ViInt32 retCnt; /* VISA return count */ @@ -1538,7 +1633,8 @@ ViStatus _VI_FUNC tkvx4244_read(ViSession instrumentHandle, ViChar message[]) { ViStatus _VI_FUNC tkvx4244_measCaptureReturnData( ViSession instrumentHandle, ViInt16 channel, ViInt16 voltageRange, ViInt16 intervalFrequency, ViReal64 *samplingRate, ViInt32 startingAddress, - ViInt16 numberOfSamples, ViChar dataArray[]) { + ViInt16 numberOfSamples, ViChar dataArray[]) +{ ViInt16 gpch1, gpch2, gpch3, gpch4; ViInt16 gone, gtwo, gthree, gfour; ViStatus retError; /* Returned error status */ @@ -1573,7 +1669,8 @@ ViStatus _VI_FUNC tkvx4244_measCaptureReturnData( if (retError) return retError; /*Define and enable the selected channel. Set up selected parameters */ - if (channel < tkvx4244_ANALYZE_CH5) { + if (channel < tkvx4244_ANALYZE_CH5) + { gone = VI_TRUE; if (channel == tkvx4244_ANALYZE_CH1) gpch1 = 1; @@ -1608,7 +1705,8 @@ ViStatus _VI_FUNC tkvx4244_measCaptureReturnData( return retError; } - if ((channel > tkvx4244_ANALYZE_CH4) && (channel < tkvx4244_ANALYZE_CH9)) { + if ((channel > tkvx4244_ANALYZE_CH4) && (channel < tkvx4244_ANALYZE_CH9)) + { gtwo = VI_TRUE; if (channel == tkvx4244_ANALYZE_CH5) gpch1 = 1; @@ -1642,7 +1740,8 @@ ViStatus _VI_FUNC tkvx4244_measCaptureReturnData( if (retError) return retError; } - if ((channel > tkvx4244_ANALYZE_CH8) && (channel < tkvx4244_ANALYZE_CH13)) { + if ((channel > tkvx4244_ANALYZE_CH8) && (channel < tkvx4244_ANALYZE_CH13)) + { gthree = VI_TRUE; if (channel == tkvx4244_ANALYZE_CH9) gpch1 = 1; @@ -1676,7 +1775,8 @@ ViStatus _VI_FUNC tkvx4244_measCaptureReturnData( if (retError) return retError; } - if (channel > tkvx4244_ANALYZE_CH12) { + if (channel > tkvx4244_ANALYZE_CH12) + { gfour = VI_TRUE; if (channel == tkvx4244_ANALYZE_CH13) gpch1 = 1; @@ -1743,7 +1843,8 @@ ViStatus _VI_FUNC tkvx4244_confTriggerSrcAndLogic( ViSession instrumentHandle, ViInt16 logic, ViInt16 ext, ViInt16 imm, ViInt16 thre, ViInt16 vxi, ViInt16 ttl0, ViInt16 ttl1, ViInt16 ttl2, ViInt16 ttl3, ViInt16 ttl4, ViInt16 ttl5, ViInt16 ttl6, ViInt16 ttl7, - ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 gpa) { + ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 gpa) +{ ViChar gplst[10]; ViChar mask[10]; int temp; @@ -1975,7 +2076,8 @@ ViStatus _VI_FUNC tkvx4244_confGpOneTrigSrcLogic( ViSession instrumentHandle, ViInt16 logic, ViInt16 external, ViInt16 immediate, ViInt16 threshold, ViInt16 vxicmd, ViInt16 ttl0, ViInt16 ttl1, ViInt16 ttl2, ViInt16 ttl3, ViInt16 ttl4, ViInt16 ttl5, - ViInt16 ttl6, ViInt16 ttl7) { + ViInt16 ttl6, ViInt16 ttl7) +{ ViChar mask[10]; int temp; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -2210,7 +2312,8 @@ ViStatus _VI_FUNC tkvx4244_confGpTwoTrigSrcLogic( ViSession instrumentHandle, ViInt16 logic, ViInt16 external, ViInt16 immediate, ViInt16 threshold, ViInt16 vxicmd, ViInt16 ttl0, ViInt16 ttl1, ViInt16 ttl2, ViInt16 ttl3, ViInt16 ttl4, ViInt16 ttl5, - ViInt16 ttl6, ViInt16 ttl7) { + ViInt16 ttl6, ViInt16 ttl7) +{ ViChar mask[10]; int temp; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -2445,7 +2548,8 @@ ViStatus _VI_FUNC tkvx4244_confGpThreeTrigSrcLogic( ViSession instrumentHandle, ViInt16 logic, ViInt16 external, ViInt16 immediate, ViInt16 threshold, ViInt16 vxicmd, ViInt16 ttl0, ViInt16 ttl1, ViInt16 ttl2, ViInt16 ttl3, ViInt16 ttl4, ViInt16 ttl5, - ViInt16 ttl6, ViInt16 ttl7) { + ViInt16 ttl6, ViInt16 ttl7) +{ ViChar mask[10]; int temp; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -2680,7 +2784,8 @@ ViStatus _VI_FUNC tkvx4244_confGpFourTrigSrcLogic( ViSession instrumentHandle, ViInt16 logic, ViInt16 external, ViInt16 immediate, ViInt16 threshold, ViInt16 vxicmd, ViInt16 ttl0, ViInt16 ttl1, ViInt16 ttl2, ViInt16 ttl3, ViInt16 ttl4, ViInt16 ttl5, - ViInt16 ttl6, ViInt16 ttl7) { + ViInt16 ttl6, ViInt16 ttl7) +{ ViChar mask[10]; int temp; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -2912,7 +3017,8 @@ ViStatus _VI_FUNC tkvx4244_confGpFourTrigSrcLogic( */ ViStatus _VI_FUNC tkvx4244_confSynchronousClocks(ViSession instrumentHandle, ViInt16 source, - ViInt16 ttlSource) { + ViInt16 ttlSource) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ ViInt32 retCnt; /* required parameter for visa calls */ @@ -2967,7 +3073,8 @@ ViStatus _VI_FUNC tkvx4244_confSynchronousClocks(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_readASCIIData(ViSession instrumentHandle, ViInt16 numberOfSamples, ViInt32 startingAddress, - ViInt16 channel, ViChar dataArray[]) { + ViInt16 channel, ViChar dataArray[]) +{ static char rdd[12288]; static int dtt[1000]; time_t delaytime; @@ -3043,7 +3150,8 @@ ViStatus _VI_FUNC tkvx4244_readASCIIData(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_getBinaryData(ViSession instrumentHandle, ViInt16 numberOfSamples, ViInt32 startingAddress, - ViInt16 channel, ViInt16 response[]) { + ViInt16 channel, ViInt16 response[]) +{ ViInt16 btcnt; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -3091,7 +3199,8 @@ ViStatus _VI_FUNC tkvx4244_getBinaryData(ViSession instrumentHandle, retCnt /= 2; pData = (char *)response; /* short(2Byte) array data -> char(1Byte) array */ - for (i = 0; i < retCnt; i++) { + for (i = 0; i < retCnt; i++) + { j = 2 * i; redata = pData[j]; pData[j] = pData[j + 1]; @@ -3122,7 +3231,8 @@ ViStatus _VI_FUNC tkvx4244_getBinaryDataSFP(ViSession instrumentHandle, ViInt16 numberOfSamples, ViInt32 startingAddress, ViInt16 channel, - ViInt16 response[]) { + ViInt16 response[]) +{ ViInt16 btcnt; ViInt32 ii; static ViChar *rdd; @@ -3166,7 +3276,8 @@ ViStatus _VI_FUNC tkvx4244_getBinaryDataSFP(ViSession instrumentHandle, /* Get the response from the instrument */ viSetAttribute(instrumentHandle, VI_ATTR_TERMCHAR_EN, VI_FALSE); retError = viRead(instrumentHandle, (ViPBuf)rdd, btcnt, (ViPUInt32)&retCnt); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { free(rdd); return retError; } @@ -3200,7 +3311,8 @@ ViStatus _VI_FUNC tkvx4244_getBinaryDataSFP(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_readBinaryData(ViSession instrumentHandle, ViInt16 numberOfSamples, ViInt32 startingAddress, - ViInt16 channel, ViChar response[]) { + ViInt16 channel, ViChar response[]) +{ ViInt16 btcnt; static ViChar rdd[10000]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -3262,7 +3374,8 @@ ViStatus _VI_FUNC tkvx4244_readBinaryData(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readTimetag(ViSession instrumentHandle, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, - ViInt16 all, ViChar timeTag[]) { + ViInt16 all, ViChar timeTag[]) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3338,7 +3451,8 @@ ViStatus _VI_FUNC tkvx4244_readTimetag(ViSession instrumentHandle, ViInt16 gp1, */ ViStatus _VI_FUNC tkvx4244_confFrontPanelOutTrig(ViSession instrumentHandle, ViInt16 groupNumber, - ViChar groupOutput[]) { + ViChar groupOutput[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -3396,7 +3510,8 @@ ViStatus _VI_FUNC tkvx4244_confFrontPanelOutTrig(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readSyncClkSource(ViSession instrumentHandle, ViInt16 synchronize, - ViChar activeLevel[]) { + ViChar activeLevel[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -3444,7 +3559,8 @@ ViStatus _VI_FUNC tkvx4244_readSyncClkSource(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readActiveChannels(ViSession instrumentHandle, ViInt16 queryCondition, - ViChar list[]) { + ViChar list[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -3497,7 +3613,8 @@ ViStatus _VI_FUNC tkvx4244_readSampleRates(ViSession instrumentHandle, ViInt16 definitions, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 all, - ViChar response[]) { + ViChar response[]) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3578,7 +3695,8 @@ ViStatus _VI_FUNC tkvx4244_readSampleRates(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_readCollectionCount(ViSession instrumentHandle, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, - ViInt16 all, ViChar count[]) { + ViInt16 all, ViChar count[]) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3657,7 +3775,8 @@ ViStatus _VI_FUNC tkvx4244_readArmSrcZero(ViSession instrumentHandle, ViInt16 armSourceOrMemoryZero, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 all, - ViChar armOrMemoryZeroResponse[]) { + ViChar armOrMemoryZeroResponse[]) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3736,7 +3855,8 @@ ViStatus _VI_FUNC tkvx4244_readArmSrcZero(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readInputVoltageSettings(ViSession instrumentHandle, ViInt16 rangeQuery, - ViChar inputVoltage[]) { + ViChar inputVoltage[]) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3805,7 +3925,8 @@ ViStatus _VI_FUNC tkvx4244_volt_rang_query( ViSession instrumentHandle, ViInt16 rang, ViInt16 c1, ViInt16 c2, ViInt16 c3, ViInt16 c4, ViInt16 c5, ViInt16 c6, ViInt16 c7, ViInt16 c8, ViInt16 c9, ViInt16 c10, ViInt16 c11, ViInt16 c12, ViInt16 c13, ViInt16 c14, - ViInt16 c15, ViInt16 c16, ViInt16 ca, ViChar answer[]) { + ViInt16 c15, ViInt16 c16, ViInt16 ca, ViChar answer[]) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -3918,7 +4039,8 @@ ViStatus _VI_FUNC tkvx4244_volt_rang_query( ViStatus _VI_FUNC tkvx4244_confExtClkSlopAndTtag(ViSession instrumentHandle, ViInt16 slope, ViInt16 timeTag, ViChar clockSlope[], - ViChar timeTagSource[]) { + ViChar timeTagSource[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -4003,7 +4125,8 @@ ViStatus _VI_FUNC tkvx4244_confExtClkSlopAndTtag(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_eventReqEnable(ViSession instrumentHandle, ViInt16 requestEventEnab, - ViInt16 maskDefinition) { + ViInt16 maskDefinition) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ ViInt32 retCnt; /* required parameter for visa calls */ @@ -4044,7 +4167,8 @@ ViStatus _VI_FUNC tkvx4244_eventReqEnable(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readStatus(ViSession instrumentHandle, ViInt16 select4882Command, - ViChar get4882Status[]) { + ViChar get4882Status[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -4097,7 +4221,8 @@ ViStatus _VI_FUNC tkvx4244_readStatus(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readPostprocessCalc( ViSession instrumentHandle, ViInt16 measurement, ViInt32 numberOfSamples, - ViInt32 startingAddress, ViInt16 channel, ViChar response[]) { + ViInt32 startingAddress, ViInt16 channel, ViChar response[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -4161,7 +4286,8 @@ ViStatus _VI_FUNC tkvx4244_readPostprocessCalc( ViStatus _VI_FUNC tkvx4244_initStopMeasurementCycle(ViSession instrumentHandle, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, - ViInt16 all) { + ViInt16 all) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4232,7 +4358,8 @@ ViStatus _VI_FUNC tkvx4244_confMastertrigOut(ViSession instrumentHandle, ViInt16 outputSelect, ViInt16 logic, ViInt16 slope, ViInt16 gp1, ViInt16 gp2, - ViInt16 gp3, ViInt16 gp4) { + ViInt16 gp3, ViInt16 gp4) +{ ViChar slpp[5]; ViChar mask[10]; ViInt16 temp; @@ -4391,7 +4518,8 @@ ViStatus _VI_FUNC tkvx4244_confTriggerThreshold(ViSession instrumentHandle, ViReal64 voltageLevel, ViInt16 group1, ViInt16 group2, ViInt16 group3, - ViInt16 group4) { + ViInt16 group4) +{ ViChar loc[20]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4467,7 +4595,8 @@ ViStatus _VI_FUNC tkvx4244_confArmSrcMemZero(ViSession instrumentHandle, ViInt16 source, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 allGroups, - ViInt16 memoryZero) { + ViInt16 memoryZero) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4550,7 +4679,8 @@ ViStatus _VI_FUNC tkvx4244_confArmSrcMemZero(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_confFrontPanelDisplay(ViSession instrumentHandle, ViInt16 groupNumber, - ViChar groupDisplayed[]) { + ViChar groupDisplayed[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -4607,7 +4737,8 @@ ViStatus _VI_FUNC tkvx4244_confFrontPanelDisplay(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGpOneVoltageRange(ViSession instrumentHandle, ViInt16 ch1, ViInt16 ch2, ViInt16 ch3, ViInt16 ch4, - ViInt16 voltageRange) { + ViInt16 voltageRange) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4676,7 +4807,8 @@ ViStatus _VI_FUNC tkvx4244_confGpOneVoltageRange(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGpTwoVoltageRange(ViSession instrumentHandle, ViInt16 ch5, ViInt16 ch6, ViInt16 ch7, ViInt16 ch8, - ViInt16 voltageRange) { + ViInt16 voltageRange) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4745,7 +4877,8 @@ ViStatus _VI_FUNC tkvx4244_confGpTwoVoltageRange(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGpThreeVoltageRange(ViSession instrumentHandle, ViInt16 ch9, ViInt16 ch10, ViInt16 ch11, ViInt16 ch12, - ViInt16 voltageRange) { + ViInt16 voltageRange) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4814,7 +4947,8 @@ ViStatus _VI_FUNC tkvx4244_confGpThreeVoltageRange(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGpFourVoltageRange(ViSession instrumentHandle, ViInt16 ch13, ViInt16 ch14, ViInt16 ch15, ViInt16 ch16, - ViInt16 voltageRange) { + ViInt16 voltageRange) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4894,7 +5028,8 @@ ViStatus _VI_FUNC tkvx4244_volt_rang(ViSession instrumentHandle, ViInt16 vlts, ViInt16 c7, ViInt16 c8, ViInt16 c9, ViInt16 c10, ViInt16 c11, ViInt16 c12, ViInt16 c13, ViInt16 c14, ViInt16 c15, - ViInt16 c16, ViInt16 ca) { + ViInt16 c16, ViInt16 ca) +{ ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -4997,7 +5132,8 @@ ViStatus _VI_FUNC tkvx4244_volt_rang(ViSession instrumentHandle, ViInt16 vlts, ViStatus _VI_FUNC tkvx4244_confSamplingInterval( ViSession instrumentHandle, ViInt16 source, ViInt16 intervalFrequency, ViReal64 *samplingRate, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, - ViInt16 allGroups) { + ViInt16 allGroups) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -5043,12 +5179,15 @@ ViStatus _VI_FUNC tkvx4244_confSamplingInterval( return retError; if (allGroups + gp1 + gp2 + gp3 + gp4 == VI_FALSE) return tkvx4244_NO_GRPS_SELECTED_ERROR; - if (*samplingRate > 1.0) { + if (*samplingRate > 1.0) + { retError = tkvx4244_invalidRealRange(*samplingRate, 30.6372, 200000.0, tkvx4244_ERROR_FREQ); if (retError) return retError; - } else { + } + else + { retError = tkvx4244_invalidRealRange(*samplingRate, 0.000005, 0.03264, tkvx4244_ERROR_FREQ); if (retError) @@ -5061,7 +5200,8 @@ ViStatus _VI_FUNC tkvx4244_confSamplingInterval( /* Parse the gp list */ tkvx4244_gplist_parse(gp1, gp2, gp3, gp4, allGroups, gplst); - if (source) { + if (source) + { /* Build the command string */ sprintf(cmd, "FREQ:SOUR %s (%s)\n", smpclk[source], gplst); /* Send the command string */ @@ -5077,7 +5217,9 @@ ViStatus _VI_FUNC tkvx4244_confSamplingInterval( viWrite(instrumentHandle, (ViBuf)cmd, strlen(cmd), (ViPUInt32)&retCnt); if (retError) return retError; - } else { + } + else + { /* Build the command string */ sprintf(cmd, "FREQ:SOUR %s (%s)\n", smpclk[source], gplst); /* Send the command string */ @@ -5108,7 +5250,8 @@ ViStatus _VI_FUNC tkvx4244_confFDCTransfer(ViSession instrumentHandle, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 allGroups, ViInt32 fdcBufferSize, - ViInt32 startingAddress) { + ViInt32 startingAddress) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -5180,7 +5323,8 @@ ViStatus _VI_FUNC tkvx4244_confFDCTransfer(ViSession instrumentHandle, } ViStatus _VI_FUNC tkvx4244_getFDCAttribute(ViSession instrumentHandle, - ViUInt16 attr[]) { + ViUInt16 attr[]) +{ ViStatus retError; /* 0-7 */ @@ -5228,7 +5372,8 @@ ViStatus _VI_FUNC tkvx4244_getFDCAttribute(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_getFDCData(ViSession instrumentHandle, ViInt16 fdcGroup, ViInt32 numberOfSamples, - ViInt16 dataArray[]) { + ViInt16 dataArray[]) +{ ViInt16 intface; ViStatus retError; /* Returned error status */ @@ -5266,7 +5411,8 @@ ViStatus _VI_FUNC tkvx4244_getFDCData(ViSession instrumentHandle, retError = viRead(instrumentHandle, (ViPBuf)dataArray, (2 * numberOfSamples), (ViPUInt32)&retCnt); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viSetAttribute(instrumentHandle, VI_ATTR_IO_PROT, VI_NORMAL); return retError; } @@ -5294,7 +5440,8 @@ ViStatus _VI_FUNC tkvx4244_getFDCData(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_readFDCData(ViSession instrumentHandle, ViInt16 fdcGroup, ViInt32 numberOfSamples, - ViChar dataArray[]) { + ViChar dataArray[]) +{ ViInt16 intface; ViStatus retError; /* Returned error status */ @@ -5329,7 +5476,8 @@ ViStatus _VI_FUNC tkvx4244_readFDCData(ViSession instrumentHandle, retError = viRead(instrumentHandle, (ViPBuf)dataArray, (2 * numberOfSamples), (ViPUInt32)&retCnt); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viSetAttribute(instrumentHandle, VI_ATTR_IO_PROT, VI_NORMAL); return retError; } @@ -5358,7 +5506,8 @@ ViStatus _VI_FUNC tkvx4244_readFDCState(ViSession instrumentHandle, ViInt16 stateQuery, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 all, - ViChar fdcQueryResponse[]) { + ViChar fdcQueryResponse[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; ViChar gplst[10]; @@ -5438,7 +5587,8 @@ ViStatus _VI_FUNC tkvx4244_readFDCState(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGroupOneChannels(ViSession instrumentHandle, ViInt16 ch1, ViInt16 ch2, ViInt16 ch3, ViInt16 ch4, - ViInt16 select) { + ViInt16 select) +{ ViChar cond[6]; ViChar chan[40]; ViInt16 chan1, chan2, chan3, chan4; @@ -5563,7 +5713,8 @@ ViStatus _VI_FUNC tkvx4244_confGroupOneChannels(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGroupTwoChannels(ViSession instrumentHandle, ViInt16 ch5, ViInt16 ch6, ViInt16 ch7, ViInt16 ch8, - ViInt16 select) { + ViInt16 select) +{ ViChar cond[6]; ViChar chan[40]; ViInt16 chan5, chan6, chan7, chan8; @@ -5689,7 +5840,8 @@ ViStatus _VI_FUNC tkvx4244_confGroupTwoChannels(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGroupThreeChannels(ViSession instrumentHandle, ViInt16 ch9, ViInt16 ch10, ViInt16 ch11, ViInt16 ch12, - ViInt16 select) { + ViInt16 select) +{ ViChar cond[6]; ViChar chan[40]; ViInt16 chan9, chan10, chan11, chan12; @@ -5817,7 +5969,8 @@ ViStatus _VI_FUNC tkvx4244_confGroupThreeChannels(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confGroupFourChannels(ViSession instrumentHandle, ViInt16 ch13, ViInt16 ch14, ViInt16 ch15, ViInt16 ch16, - ViInt16 select) { + ViInt16 select) +{ ViChar cond[6]; ViChar chan[40]; ViInt16 chan13, chan14, chan15, chan16; @@ -5968,7 +6121,8 @@ ViStatus _VI_FUNC tkvx4244_chanlist(ViSession instrumentHandle, ViInt16 select, ViInt16 ch7, ViInt16 ch8, ViInt16 ch9, ViInt16 ch10, ViInt16 ch11, ViInt16 ch12, ViInt16 ch13, ViInt16 ch14, ViInt16 ch15, - ViInt16 ch16, ViInt16 all) { + ViInt16 ch16, ViInt16 all) +{ ViChar cond[6]; ViChar chan[40]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ @@ -6099,7 +6253,8 @@ ViStatus _VI_FUNC tkvx4244_chanlist(ViSession instrumentHandle, ViInt16 select, return VI_SUCCESS; } -ViStatus _VI_FUNC tkvx4244_arm(ViSession instrumentHandle, ViUInt16 Protocol) { +ViStatus _VI_FUNC tkvx4244_arm(ViSession instrumentHandle, ViUInt16 Protocol) +{ ViStatus retError; ViInt16 trig_id; ViChar buf[256]; @@ -6107,7 +6262,8 @@ ViStatus _VI_FUNC tkvx4244_arm(ViSession instrumentHandle, ViUInt16 Protocol) { retError = viGetAttribute(instrumentHandle, VI_ATTR_TRIG_ID, &trig_id); printf("After get Attribute %d\n", retError); printf("TRIG ID: %d\n", trig_id); - if (retError) { + if (retError) + { viStatusDesc(instrumentHandle, retError, buf); printf("%s\n", buf); return retError; @@ -6134,7 +6290,8 @@ ViStatus _VI_FUNC tkvx4244_initMeasurementCycle(ViSession instrumentHandle, ViReal64 *delay, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 all, - ViInt16 initiate) { + ViInt16 initiate) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -6185,7 +6342,8 @@ ViStatus _VI_FUNC tkvx4244_initMeasurementCycle(ViSession instrumentHandle, /* Parse the gp list */ tkvx4244_gplist_parse(gp1, gp2, gp3, gp4, all, gplst); /* Build the command string */ - switch (initiate) { + switch (initiate) + { case 0: sprintf(cmd, "INIT:IMM (%s)\n", gplst); break; @@ -6225,7 +6383,8 @@ ViStatus _VI_FUNC tkvx4244_confDataCollectCount(ViSession instrumentHandle, ViInt32 numberOfSamples, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, - ViInt16 allGroups) { + ViInt16 allGroups) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViStatus retError; /* Returned error status */ @@ -6297,7 +6456,8 @@ ViStatus _VI_FUNC tkvx4244_confDataCollectCount(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_confExternalArmSlope(ViSession instrumentHandle, ViInt16 slope, - ViChar slopeVerification[]) { + ViChar slopeVerification[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -6353,7 +6513,8 @@ ViStatus _VI_FUNC tkvx4244_confExternalArmSlope(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_readMasterOutTrigger(ViSession instrumentHandle, ViInt16 outputTrigger, - ViChar masterOutputtrigger[]) { + ViChar masterOutputtrigger[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -6406,7 +6567,8 @@ ViStatus _VI_FUNC tkvx4244_readMasterOutTrigger(ViSession instrumentHandle, ViStatus _VI_FUNC tkvx4244_confMasterClock(ViSession instrumentHandle, ViReal64 frequency, ViInt16 source, ViChar masterClockSource[], - ViChar masterClockFrequency[]) { + ViChar masterClockFrequency[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -6424,12 +6586,14 @@ ViStatus _VI_FUNC tkvx4244_confMasterClock(ViSession instrumentHandle, retError = viGetAttribute(instrumentHandle, VI_ATTR_USER_DATA, &userData); drvrHdl = (tkvx4244_PdrvrStruct)userData; - if (!source) { + if (!source) + { if (tkvx4244_invalidRealRange(frequency, 30.6372, 2000000.0, tkvx4244_FREQ_RANGE_ERROR) != 0) return retError; - } else if (tkvx4244_invalidRealRange(frequency, 76.59310000000001, 5000000.0, - tkvx4244_FREQ_RANGE_ERROR) != 0) + } + else if (tkvx4244_invalidRealRange(frequency, 76.59310000000001, 5000000.0, + tkvx4244_FREQ_RANGE_ERROR) != 0) return retError; /* Build the command string */ @@ -6501,7 +6665,8 @@ ViStatus _VI_FUNC tkvx4244_confMasterClock(ViSession instrumentHandle, * VI_SUCCESS if no errors occurred, error code otherwise */ ViStatus _VI_FUNC tkvx4244_readTrigThreshold(ViSession instrumentHandle, - ViChar threshold[]) { + ViChar threshold[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -6548,7 +6713,8 @@ ViStatus _VI_FUNC tkvx4244_readTrigSrcAndLogic(ViSession instrumentHandle, ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, ViInt16 gp4, ViInt16 all, - ViChar triggerSettings[]) { + ViChar triggerSettings[]) +{ ViChar gplst[10]; ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ @@ -6630,7 +6796,8 @@ ViStatus _VI_FUNC tkvx4244_readTrigSrcAndLogic(ViSession instrumentHandle, */ ViStatus _VI_FUNC tkvx4244_confTriggerSlope(ViSession instrumentHandle, ViInt16 activeEdge, - ViChar slope[]) { + ViChar slope[]) +{ ViChar cmd[tkvx4244_CMD_STRLEN]; /* storage for instrument command strings */ ViChar rcv[tkvx4244_RCV_STRLEN]; /* storage for instrument receive strings */ ViStatus retError; /* Returned error status */ @@ -6686,7 +6853,8 @@ ViStatus _VI_FUNC tkvx4244_confTriggerSlope(ViSession instrumentHandle, * VI_SUCCESS if no errors occurred, error code otherwise */ ViStatus tkvx4244_gplist_parse(ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, - ViInt16 gp4, ViInt16 gpa, ViChar buf[]) { + ViInt16 gp4, ViInt16 gpa, ViChar buf[]) +{ ViChar gplst[10]; strcpy(gplst, ""); @@ -6699,12 +6867,14 @@ ViStatus tkvx4244_gplist_parse(ViInt16 gp1, ViInt16 gp2, ViInt16 gp3, strcat(gplst, "3,"); if (gp4 == 1) strcat(gplst, "4,"); - if (!gpa && !gplst[0]) { + if (!gpa && !gplst[0]) + { return tkvx4244_NO_GRPS_SELECTED_ERROR; } if (gpa == 1) sprintf(buf, "all"); - else { + else + { gplst[strlen(gplst) - 1] = 0; sprintf(buf, "@"); strcat(buf, gplst); @@ -6729,7 +6899,8 @@ ViStatus tkvx4244_chlst_parse(ViInt16 c1, ViInt16 c2, ViInt16 c3, ViInt16 c4, ViInt16 c5, ViInt16 c6, ViInt16 c7, ViInt16 c8, ViInt16 c9, ViInt16 c10, ViInt16 c11, ViInt16 c12, ViInt16 c13, ViInt16 c14, ViInt16 c15, - ViInt16 c16, ViInt16 ca, ViChar buf[]) { + ViInt16 c16, ViInt16 ca, ViChar buf[]) +{ ViChar chan[40]; strcpy(chan, ""); @@ -6770,7 +6941,8 @@ ViStatus tkvx4244_chlst_parse(ViInt16 c1, ViInt16 c2, ViInt16 c3, ViInt16 c4, return tkvx4244_NO_CHAN_SELECTED_ERROR; if (ca == 1) sprintf(buf, "all"); - else { + else + { chan[(strlen(chan)) - 1] = 0; sprintf(buf, "@%s", chan); } @@ -6795,7 +6967,8 @@ ViStatus tkvx4244_chlst_parse(ViInt16 c1, ViInt16 c2, ViInt16 c3, ViInt16 c4, */ ViStatus tkvx4244_invalidLongRange(ViInt32 val, ViInt32 min, ViInt32 max, - ViStatus retError) { + ViStatus retError) +{ if (val < min || val > max) return retError; return VI_SUCCESS; @@ -6819,7 +6992,8 @@ ViStatus tkvx4244_invalidLongRange(ViInt32 val, ViInt32 min, ViInt32 max, */ ViStatus tkvx4244_invalidRealRange(ViReal64 val, ViReal64 min, ViReal64 max, - ViStatus retError) { + ViStatus retError) +{ if ((val < min) || (val > max)) return retError; return VI_SUCCESS; @@ -6843,7 +7017,8 @@ ViStatus tkvx4244_invalidRealRange(ViReal64 val, ViReal64 min, ViReal64 max, */ ViStatus tkvx4244_invalidShortRange(ViInt16 val, ViInt16 min, ViInt16 max, - ViStatus retError) { + ViStatus retError) +{ if (val < min || val > max) return retError; return VI_SUCCESS; @@ -6862,12 +7037,14 @@ ViStatus tkvx4244_invalidShortRange(ViInt16 val, ViInt16 min, ViInt16 max, * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus tkvx4244_setupArrays(void) { +ViStatus tkvx4244_setupArrays(void) +{ ViSession resMgr; /* Resource Manager Session */ ViStatus retError; /* Returned error status */ if (tkvx4244_gNumberFound == - 0) { /* note that tkvx4244_gNumberFound is a global */ + 0) + { /* note that tkvx4244_gNumberFound is a global */ /************************************************************************* * Find all available tkvx4244s and store an instrument descriptor string * for each. This technique allows for faster autoconnects. @@ -6876,16 +7053,19 @@ ViStatus tkvx4244_setupArrays(void) { */ retError = viGetDefaultRM(&resMgr); - if (retError >= VI_SUCCESS) { + if (retError >= VI_SUCCESS) + { retError = tkvx4244_findInstruments(resMgr, tkvx4244_VXI_SEARCH); if ((retError < VI_SUCCESS) && (retError != VI_ERROR_RSRC_NFOUND) && - (retError != VI_ERROR_SYSTEM_ERROR)) { + (retError != VI_ERROR_SYSTEM_ERROR)) + { viClose(resMgr); return retError; } retError = tkvx4244_findInstruments(resMgr, tkvx4244_GPIB_VXI_SEARCH); - if ((retError < VI_SUCCESS) && (retError != VI_ERROR_RSRC_NFOUND)) { + if ((retError < VI_SUCCESS) && (retError != VI_ERROR_RSRC_NFOUND)) + { viClose(resMgr); return retError; } @@ -6893,12 +7073,17 @@ ViStatus tkvx4244_setupArrays(void) { viClose(resMgr); - if (tkvx4244_gNumberFound > 0) { + if (tkvx4244_gNumberFound > 0) + { return VI_SUCCESS; - } else { + } + else + { return VI_ERROR_RSRC_NFOUND; } - } else { + } + else + { return VI_SUCCESS; } } @@ -6923,11 +7108,12 @@ ViStatus tkvx4244_setupArrays(void) { *instruments Returns: VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { - ViStatus retError; /* Returned error status */ - ViSession session; /* VISA session */ - ViSession findSession; /* VISA find session */ - ViInt32 retCnt; /* Number of matches made by viFindRsrc */ +ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) +{ + ViStatus retError; /* Returned error status */ + ViSession session; /* VISA session */ + ViSession findSession; /* VISA find session */ + ViInt32 retCnt; /* Number of matches made by viFindRsrc */ ViChar descriptor[tkvx4244_RCV_STRLEN]; /* instrument descriptor */ ViInt16 logAdr; /* logical address */ ViInt16 slot; /* slot # */ @@ -6936,7 +7122,8 @@ ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { retError = viFindRsrc(resMgr, searchString, &findSession, (ViPUInt32)&retCnt, descriptor); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viClose(findSession); return retError; } @@ -6946,30 +7133,35 @@ ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { * time a tkvx4244 is located, add it to a list. */ - do { + do + { /* * get the slot number, manufacture id and model code * from the instrument. */ retError = viOpen(resMgr, descriptor, VI_NULL, VI_NULL, &session); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viClose(findSession); return retError; } retError = tkvx4244_verifyID(session); - if (retError >= VI_SUCCESS) { + if (retError >= VI_SUCCESS) + { retError = viGetAttribute(session, VI_ATTR_SLOT, &slot); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viClose(session); viClose(findSession); return retError; } retError = viGetAttribute(session, VI_ATTR_VXI_LA, &logAdr); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { viClose(session); viClose(findSession); return retError; @@ -6986,11 +7178,15 @@ ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { (tkvx4244_gNumberFound)++; viClose(session); - } else if (retError != VI_ERROR_RSRC_NFOUND) { + } + else if (retError != VI_ERROR_RSRC_NFOUND) + { viClose(session); viClose(findSession); return retError; - } else { + } + else + { viClose(session); } @@ -7000,9 +7196,12 @@ ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { viClose(findSession); - if (tkvx4244_gNumberFound > 0) { + if (tkvx4244_gNumberFound > 0) + { return VI_SUCCESS; - } else { + } + else + { return VI_ERROR_RSRC_NFOUND; } } @@ -7027,7 +7226,8 @@ ViStatus tkvx4244_findInstruments(ViSession resMgr, ViChar searchString[]) { */ ViStatus tkvx4244_tryAutoConnect(ViInt16 theSlot, ViInt16 theLogAdr, - ViPSession instrumentHandle) { + ViPSession instrumentHandle) +{ ViStatus retError; /* Returned error status */ ViString descriptor; /* instrument descriptor */ @@ -7041,16 +7241,20 @@ ViStatus tkvx4244_tryAutoConnect(ViInt16 theSlot, ViInt16 theLogAdr, retError = tkvx4244_returnDescriptor(theSlot, theLogAdr, &descriptor); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { /* * return error because instrument is not in theSlot or wrong LA */ *instrumentHandle = VI_NULL; - } else { + } + else + { retError = tkvx4244_init(descriptor, VI_FALSE, VI_TRUE, instrumentHandle); - if (retError < VI_SUCCESS) { + if (retError < VI_SUCCESS) + { *instrumentHandle = VI_NULL; } } @@ -7074,32 +7278,46 @@ ViStatus tkvx4244_tryAutoConnect(ViInt16 theSlot, ViInt16 theLogAdr, */ ViStatus tkvx4244_returnDescriptor(ViInt16 theSlot, ViInt16 theLogAdr, - ViString *descriptor) { + ViString *descriptor) +{ ViInt16 ii; /* loop count */ - if ((theSlot > 0) && (theLogAdr > 0)) { - for (ii = 0; ii < tkvx4244_gNumberFound; ii++) { + if ((theSlot > 0) && (theLogAdr > 0)) + { + for (ii = 0; ii < tkvx4244_gNumberFound; ii++) + { if ((tkvx4244_instrAttr[ii].slot == theSlot) && - (tkvx4244_instrAttr[ii].logAdr == theLogAdr)) { + (tkvx4244_instrAttr[ii].logAdr == theLogAdr)) + { *descriptor = tkvx4244_instrAttr[ii].instrDesc; return VI_SUCCESS; } } - } else if ((theSlot > 0) && (theLogAdr <= 0)) { - for (ii = 0; ii < tkvx4244_gNumberFound; ii++) { - if (tkvx4244_instrAttr[ii].slot == theSlot) { + } + else if ((theSlot > 0) && (theLogAdr <= 0)) + { + for (ii = 0; ii < tkvx4244_gNumberFound; ii++) + { + if (tkvx4244_instrAttr[ii].slot == theSlot) + { *descriptor = tkvx4244_instrAttr[ii].instrDesc; return VI_SUCCESS; } } - } else if ((theSlot <= 0) && (theLogAdr > 0)) { - for (ii = 0; ii < tkvx4244_gNumberFound; ii++) { - if (tkvx4244_instrAttr[ii].logAdr == theLogAdr) { + } + else if ((theSlot <= 0) && (theLogAdr > 0)) + { + for (ii = 0; ii < tkvx4244_gNumberFound; ii++) + { + if (tkvx4244_instrAttr[ii].logAdr == theLogAdr) + { *descriptor = tkvx4244_instrAttr[ii].instrDesc; return VI_SUCCESS; } } - } else { + } + else + { return VI_ERROR_RSRC_NFOUND; } return VI_ERROR_RSRC_NFOUND; @@ -7121,7 +7339,8 @@ ViStatus tkvx4244_returnDescriptor(ViInt16 theSlot, ViInt16 theLogAdr, * VI_SUCCESS if no errors occurred, error code otherwise */ -ViStatus tkvx4244_verifyID(ViSession instrumentHandle) { +ViStatus tkvx4244_verifyID(ViSession instrumentHandle) +{ ViUInt16 manfID; /* instrument manufacturer ID code */ ViUInt16 modelCode; /* instrument model code */ ViStatus retError; /* Returned error status */ @@ -7144,9 +7363,12 @@ ViStatus tkvx4244_verifyID(ViSession instrumentHandle) { if (tkvx4244_modelCodes[0] < 0x1000) modelCode &= 0x0fff; - if (manfID == tkvx4244_MANF_ID) { - for (ii = 0; ii < tkvx4244_NUM_MODEL_CODES; ii++) { - if (tkvx4244_modelCodes[ii] == modelCode) { + if (manfID == tkvx4244_MANF_ID) + { + for (ii = 0; ii < tkvx4244_NUM_MODEL_CODES; ii++) + { + if (tkvx4244_modelCodes[ii] == modelCode) + { return VI_SUCCESS; } } @@ -7159,7 +7381,8 @@ ViStatus tkvx4244_verifyID(ViSession instrumentHandle) { #ifdef tkvx4244_DLL #include -int _VI_FUNC LibMain(/*Handle, WORD, WORD, LPSTR */) { +int _VI_FUNC LibMain(/*Handle, WORD, WORD, LPSTR */) +{ /* * Put any initialization code here required * by your instrument Driver @@ -7167,7 +7390,8 @@ int _VI_FUNC LibMain(/*Handle, WORD, WORD, LPSTR */) { return 1; /* signifies success */ } -int _VI_FUNC WEP(ViInt32 arg) { +int _VI_FUNC WEP(ViInt32 arg) +{ /* * Put any clean up code required by your * driver here. diff --git a/math/boxsmooth.c b/math/boxsmooth.c index 058f6a20d6..e0c55aaeab 100644 --- a/math/boxsmooth.c +++ b/math/boxsmooth.c @@ -64,7 +64,8 @@ int boxsmooth(int *num, float *in, int *width, float *out) #include #include -EXPORT int boxsmooth(int *num, float *in, int *width, float *out) { +EXPORT int boxsmooth(int *num, float *in, int *width, float *out) +{ int i; int j; int w = *width; @@ -73,18 +74,22 @@ EXPORT int boxsmooth(int *num, float *in, int *width, float *out) { int *out_int = (int *)out; if (n <= 0) return 0; - if (n < w) { + if (n < w) + { memcpy(out, in, n * sizeof(float)); return 1; } w += (w % 2) ? 0 : 1; memcpy(out, in, w / 2 * sizeof(float)); - for (i = w / 2; i < n - w / 2; i++) { + for (i = w / 2; i < n - w / 2; i++) + { int div; double total = 0.; - for (div = 0, j = 0; j < w; j++) { + for (div = 0, j = 0; j < w; j++) + { int idx = i + j - w / 2; - if (in_int[idx] != 32768) { + if (in_int[idx] != 32768) + { total += in[i + j - w / 2]; div++; } diff --git a/math/testing/csint.c b/math/testing/csint.c index 9096344e2f..27f9123a1c 100644 --- a/math/testing/csint.c +++ b/math/testing/csint.c @@ -28,7 +28,8 @@ extern void csint_(int *n, float *x, float *y, float *br, float *coeff); #define N 5 #define fEQ(a, b, d) (((a > b) ? a - b : b - a) < d) -int main() { +int main() +{ float x[N] = {0.f, 1.f, 2.f, 3.f, 4.f}; float y[N] = {0.f, 1.f, 4.f, 1.f, 0.f}; int n = N; @@ -36,8 +37,26 @@ int main() { float cff[N * 4]; csint_(&n, x, y, brk, cff); float cffe[N * 4] = { - 0., -4., 14., -12., 1., 4., 2., -12., 4., 0., - -10., 12., 1., -4., 2., 12., 0., 4., 14., 12., + 0., + -4., + 14., + -12., + 1., + 4., + 2., + -12., + 4., + 0., + -10., + 12., + 1., + -4., + 2., + 12., + 0., + 4., + 14., + 12., }; float ebrk[N] = {0., 1., 2., 3., 4.}; int i; diff --git a/math/testing/toms510.c b/math/testing/toms510.c index 234ae660c8..06d224fe53 100644 --- a/math/testing/toms510.c +++ b/math/testing/toms510.c @@ -30,7 +30,8 @@ extern void toms510_(float *xin, float *yin, float *err, int *n, float *xout, #define N 5 #define fEQ(a, b, d) (((a > b) ? a - b : b - a) < d) -int main() { +int main() +{ float x[N] = {0.f, 1.f, 2.f, 3.f, 4.f}; float y[N] = {0.f, 1.f, 4.f, 1.f, 0.f}; float err = .02 * 4; // max(x)-min(x) = 4; @@ -38,7 +39,8 @@ int main() { float xout[N]; float yout[N]; int i; - for (i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { xout[i] = (float)i; yout[i] = (float)i; } @@ -49,7 +51,8 @@ int main() { toms510_(x, y, &err, &n, xout, yout, w, &k, &p); float ey[N] = {-.08, 1.08, 3.99781, 1., 0.}; float ex[N] = {0., 1., 2.0274, 3., 4.}; - for (i = 0; i < N; i++) { + for (i = 0; i < N; i++) + { if (!fEQ(ex[i], xout[i], 1e-5f)) return 1; if (!fEQ(ey[i], yout[i], 1e-5f)) diff --git a/mdsdcl/cmdExecute.c b/mdsdcl/cmdExecute.c index ac06b0669f..0dde002128 100644 --- a/mdsdcl/cmdExecute.c +++ b/mdsdcl/cmdExecute.c @@ -47,9 +47,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \param p [in,out] the address of a pointer to a dclParameter struct. */ -void freeParameter(dclParameterPtr *p_in) { +void freeParameter(dclParameterPtr *p_in) +{ dclParameterPtr p = *p_in; - if (p) { + if (p) + { int i; if (p->name != NULL) free(p->name); @@ -73,16 +75,20 @@ void freeParameter(dclParameterPtr *p_in) { \param q [in,out] The address of a pointer to a dclQualifier struct */ -static void freeQualifier(dclQualifierPtr *q_in) { - if (q_in) { +static void freeQualifier(dclQualifierPtr *q_in) +{ + if (q_in) + { dclQualifierPtr q = *q_in; - if (q) { + if (q) + { int i; free(q->name); free(q->defaultValue); free(q->type); free(q->syntax); - if (q->values) { + if (q->values) + { for (i = 0; i < q->value_count; i++) free(q->values[i]); free(q->values); @@ -97,17 +103,21 @@ static void freeQualifier(dclQualifierPtr *q_in) { \param cmdDef [in] A pointer to a dclCommand structure. */ -void freeCommandParamsAndQuals(dclCommandPtr cmdDef) { - if (cmdDef) { +void freeCommandParamsAndQuals(dclCommandPtr cmdDef) +{ + if (cmdDef) + { int i; - if (cmdDef->parameter_count > 0) { + if (cmdDef->parameter_count > 0) + { for (i = 0; i < cmdDef->parameter_count; i++) freeParameter(&cmdDef->parameters[i]); cmdDef->parameter_count = 0; free(cmdDef->parameters); cmdDef->parameters = 0; } - if (cmdDef->qualifier_count > 0) { + if (cmdDef->qualifier_count > 0) + { for (i = 0; i < cmdDef->qualifier_count; i++) freeQualifier(&cmdDef->qualifiers[i]); cmdDef->qualifier_count = 0; @@ -121,10 +131,13 @@ void freeCommandParamsAndQuals(dclCommandPtr cmdDef) { \param cmd [in,out] The address of a pointer to a dclCommand structure */ -static void freeCommand(dclCommandPtr *cmd_in) { - if (cmd_in) { +static void freeCommand(dclCommandPtr *cmd_in) +{ + if (cmd_in) + { dclCommandPtr cmd = *cmd_in; - if (cmd) { + if (cmd) + { free(cmd->verb); free(cmd->routine); free(cmd->image); @@ -150,24 +163,28 @@ static void freeCommand(dclCommandPtr *cmd_in) { */ -static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { +static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) +{ /* If the parent node is a verb */ xmlNodePtr parent = node->parent; - if (parent->name && (strcasecmp((const char *)parent->name, "verb") == 0)) { + if (parent->name && (strcasecmp((const char *)parent->name, "verb") == 0)) + { struct _xmlAttr *propNode; /* check to see if type is rest_of_line. If it is just set the cmd->rest_of_line and return; */ - for (propNode = parent->properties; propNode; propNode = propNode->next) { + for (propNode = parent->properties; propNode; propNode = propNode->next) + { if (propNode->name && (strcasecmp((const char *)propNode->name, "type") == 0) && propNode->children && propNode->children->content && (strcasecmp((const char *)propNode->children->content, - "rest_of_line") == 0)) { + "rest_of_line") == 0)) + { cmd->rest_of_line = 1; break; } @@ -177,7 +194,8 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { /* If the node ia a paramter (i.e. ) */ if ((cmd->rest_of_line == 0) && node->name && - (strcasecmp((const char *)node->name, "parameter") == 0)) { + (strcasecmp((const char *)node->name, "parameter") == 0)) + { struct _xmlAttr *propNode; /* allocate an empty parameter structure */ @@ -187,29 +205,33 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { /* Look at all the properties of the parameter */ - for (propNode = node->properties; propNode; propNode = propNode->next) { + for (propNode = node->properties; propNode; propNode = propNode->next) + { /* If this is a label property (i.e. ) duplicate the label value into the dclParameter structure. */ if (propNode->name && (strcasecmp((const char *)propNode->name, "label") == 0) && - propNode->children && propNode->children->content) { + propNode->children && propNode->children->content) + { parameter->label = strdup((const char *)propNode->children->content); /* else if this is a name property duplicate the name value */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "name") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "name") == 0) && + propNode->children && propNode->children->content) + { parameter->name = strdup((const char *)propNode->children->content); /* else if this is a required property set required if value is True. */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "required") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "required") == 0) && + propNode->children && propNode->children->content) + { parameter->required = strcasecmp((const char *)propNode->children->content, "True") == 0; @@ -222,49 +244,62 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { on the value specified by the user for this parameter. The cmd definition may be completely replaced later when user input is analyzed. ** */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "type") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "type") == 0) && + propNode->children && propNode->children->content) + { if (strcasecmp((const char *)propNode->children->content, - "rest_of_line") == 0) { + "rest_of_line") == 0) + { parameter->useRestOfLine = 1; - } else { + } + else + { parameter->type = strdup((const char *)propNode->children->content); } /* else if this ia a prompt property duplicate into the parameter structure. The prompt may be sent to the user if he failed to provide this parameter in the command string. */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "prompt") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "prompt") == 0) && + propNode->children && propNode->children->content) + { parameter->prompt = strdup((const char *)propNode->children->content); /* else if this ia a list property set listOk in the parameter if value is "True". When processing a command if the user provided multiple values for the parameter a syntax error will be issued. */ - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "list") == 0) && - propNode->children && propNode->children->content && - (strcasecmp((const char *)propNode->children->content, - "true") == 0)) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "list") == 0) && + propNode->children && propNode->children->content && + (strcasecmp((const char *)propNode->children->content, + "true") == 0)) + { parameter->listOk = 1; - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "default") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "default") == 0) && + propNode->children && propNode->children->content) + { char *value = strdup((const char *)propNode->children->content); char *c, *v; - for (v = value, c = strchr(v, ','); strlen(v); c = strchr(v, ',')) { + for (v = value, c = strchr(v, ','); strlen(v); c = strchr(v, ',')) + { if (c) *c = 0; - if (parameter->values) { + if (parameter->values) + { parameter->values = realloc(parameter->values, (parameter->value_count + 1) * sizeof(char *)); - } else { + } + else + { parameter->values = malloc(sizeof(char *)); } parameter->values[parameter->value_count++] = strdup(v); @@ -289,9 +324,10 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { cmd->parameter_count++; /* else if this is a qualifier node (i.e. ) */ - - } else if ((cmd->rest_of_line == 0) && node->name && - (strcasecmp((const char *)node->name, "qualifier") == 0)) { + } + else if ((cmd->rest_of_line == 0) && node->name && + (strcasecmp((const char *)node->name, "qualifier") == 0)) + { /* allocate an empty dclQualifier structure. */ @@ -301,22 +337,25 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { /* examine all the properties of this node */ - for (propNode = node->properties; propNode; propNode = propNode->next) { + for (propNode = node->properties; propNode; propNode = propNode->next) + { /* if this is a name property, duplicate to the qualifier structure. */ if (propNode->name && (strcasecmp((const char *)propNode->name, "name") == 0) && - propNode->children && propNode->children->content) { + propNode->children && propNode->children->content) + { qualifier->name = strdup((const char *)propNode->children->content); /* else if this is a defaulted property, set the isDefault flag if value is "True". If isDefault is true when processing the command, this qualifier will be included unless preceded by "no" */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "defaulted") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "defaulted") == 0) && + propNode->children && propNode->children->content) + { qualifier->isDefault = strcasecmp((const char *)propNode->children->content, "True") == 0; @@ -325,31 +364,34 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { processing the command, this will check to make sure the user provided a value with the qualifier (i.e. /qualifier=value). */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "required") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "required") == 0) && + propNode->children && propNode->children->content) + { qualifier->valueRequired = strcasecmp((const char *)propNode->children->content, "True") == 0; /* else if this is a nonnegatable property, set the nonnegateable flag if the value is "True". If nonnegatable is set then the user cannot prefix the qualifier with "no" (i.e. cmd /nogub is disallowed). */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "nonnegatable") == - 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "nonnegatable") == + 0) && + propNode->children && propNode->children->content) + { qualifier->nonnegatable = strcasecmp((const char *)propNode->children->content, "True") == 0; /* else if this is a list property, set the listOk flag if the value is "True". The listOk flag indicates whether more than one value is permitted with the qualifier. (i.e. cmd /gub=(val1,val2,val3)) */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "list") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "list") == 0) && + propNode->children && propNode->children->content) + { qualifier->listOk = strcasecmp((const char *)propNode->children->content, "True") == 0; @@ -357,20 +399,22 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { qualifier struct. The type property is used when processing the qualifier to check for valid values or whether the value(s) should be converted to integer during cli queries. */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "type") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "type") == 0) && + propNode->children && propNode->children->content) + { qualifier->type = strdup((const char *)propNode->children->content); /* else if this is a default property duplicate the value into the defaultValue qualifier struct member. This will be used to specify a default value if the user did not specify a value with the qualifier */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "default") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "default") == 0) && + propNode->children && propNode->children->content) + { qualifier->defaultValue = strdup((const char *)propNode->children->content); @@ -378,10 +422,11 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { into the qualifier structure. This will cause a command syntax replacement during command processing if the user included this qualifier in the command. */ - - } else if (propNode->name && - (strcasecmp((const char *)propNode->name, "syntax") == 0) && - propNode->children && propNode->children->content) { + } + else if (propNode->name && + (strcasecmp((const char *)propNode->name, "syntax") == 0) && + propNode->children && propNode->children->content) + { qualifier->syntax = strdup((const char *)propNode->children->content); } } @@ -397,18 +442,23 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { /* else if this is a routine node (i.e. duplicate the routine name into the command routine element. */ - - } else if (node->name && - (strcasecmp((const char *)node->name, "routine") == 0)) { + } + else if (node->name && + (strcasecmp((const char *)node->name, "routine") == 0)) + { if (node->properties && node->properties->children && - node->properties->children->content) { + node->properties->children->content) + { free(cmd->routine); cmd->routine = strdup((const char *)node->properties->children->content); } - } else if (node->name && - (strcasecmp((const char *)node->name, "image") == 0)) { + } + else if (node->name && + (strcasecmp((const char *)node->name, "image") == 0)) + { if (node->properties && node->properties->children && - node->properties->children->content) { + node->properties->children->content) + { free(cmd->image); cmd->image = strdup((const char *)node->properties->children->content); } @@ -441,7 +491,8 @@ static void findVerbInfo(xmlNodePtr node, dclCommandPtr cmd) { */ static void findEntity(xmlNodePtr node, const char *category, const char *name, - dclNodeListPtr list, int *exactFound) { + dclNodeListPtr list, int *exactFound) +{ /* If exact match already found just return */ @@ -456,13 +507,15 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, node->properties && node->properties->children && node->properties->children->content && (strncasecmp(name, (const char *)node->properties->children->content, - strlen(name)) == 0)) { + strlen(name)) == 0)) + { /* Check if it is an exact match */ if ((name == NULL) || (strlen(name) == strlen((const char *)node->properties->children - ->content))) { // if exact command match use it! + ->content))) + { // if exact command match use it! /* if already found other nodes but not exact match then free the "array" * of nodes. */ @@ -480,9 +533,12 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, /* Add this node to the list of nodes */ - if (list->count == 0) { + if (list->count == 0) + { list->nodes = malloc(sizeof(xmlNodePtr)); - } else { + } + else + { list->nodes = realloc(list->nodes, sizeof(xmlNodePtr) * (list->count + 1)); } @@ -525,7 +581,8 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, static int dispatchToHandler(char *image, dclCommandPtr cmd, dclCommandPtr cmdDef, char **prompt, char **error, char **output, char *(*getline)(), - void *getlineinfo) { + void *getlineinfo) +{ int i; int (*handler)(dclCommandPtr, char **, char **, char *(*getline)(), void *getlineinfo) = NULL; @@ -544,12 +601,15 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, the value with the complete text of the rest of the command line. Throw away the trailing parameters and qualifiers if any. */ - for (i = 0; i < cmdDef->parameter_count; i++) { - if (cmdDef->parameters[i]->useRestOfLine) { + for (i = 0; i < cmdDef->parameter_count; i++) + { + if (cmdDef->parameters[i]->useRestOfLine) + { int j; /* If user included this parameter */ - if (cmd->parameter_count > i) { + if (cmd->parameter_count > i) + { /* save the rest of line */ char *rol = cmd->parameters[i]->restOfLine; @@ -572,11 +632,14 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, cmd->parameters[i]->values[0] = rol; cmd->parameters[i]->value_count = 1; } - for (j = cmd->qualifier_count; j > 0; j--) { - if (cmd->qualifiers[j - 1]->position > i) { + for (j = cmd->qualifier_count; j > 0; j--) + { + if (cmd->qualifiers[j - 1]->position > i) + { freeQualifier(&cmd->qualifiers[j - 1]); cmd->qualifier_count--; - if (cmd->qualifier_count == 0) { + if (cmd->qualifier_count == 0) + { free(cmd->qualifiers); cmd->qualifiers = 0; } @@ -588,21 +651,27 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* Check to make sure the qualifiers specified are value for this command */ - for (i = 0; i < cmd->qualifier_count; i++) { + for (i = 0; i < cmd->qualifier_count; i++) + { int j; - for (j = 0; j < cmdDef->qualifier_count; j++) { + for (j = 0; j < cmdDef->qualifier_count; j++) + { if (strncasecmp(cmd->qualifiers[i]->name, cmdDef->qualifiers[j]->name, - strlen(cmd->qualifiers[i]->name)) == 0) { + strlen(cmd->qualifiers[i]->name)) == 0) + { break; - } else if ((strncasecmp(cmd->qualifiers[i]->name, "no", 2) == 0) && - (strlen(cmd->qualifiers[i]->name) > 2) && - (strncasecmp(cmd->qualifiers[i]->name + 2, - cmdDef->qualifiers[j]->name, - strlen(cmd->qualifiers[i]->name) - 2) == 0)) { + } + else if ((strncasecmp(cmd->qualifiers[i]->name, "no", 2) == 0) && + (strlen(cmd->qualifiers[i]->name) > 2) && + (strncasecmp(cmd->qualifiers[i]->name + 2, + cmdDef->qualifiers[j]->name, + strlen(cmd->qualifiers[i]->name) - 2) == 0)) + { break; } } - if (j == cmdDef->qualifier_count) { + if (j == cmdDef->qualifier_count) + { char *errstr = malloc(100); sprintf(errstr, "Qualifier \"%s\" is not valid for this command\n", cmd->qualifiers[i]->name); @@ -612,7 +681,8 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, } /* Check to make sure there are not too many parameters */ - if (cmd->parameter_count > cmdDef->parameter_count) { + if (cmd->parameter_count > cmdDef->parameter_count) + { char *errstr = malloc(100); sprintf(errstr, "Too many parameters specified in the command. Maximum supported " @@ -624,12 +694,15 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* For all the parameters */ - for (i = 0; i < cmdDef->parameter_count; i++) { + for (i = 0; i < cmdDef->parameter_count; i++) + { /* Check to make sure user did not specify too many values in parameters. */ - if (cmdDef->parameters[i]->listOk == 0) { - if ((i < cmd->parameter_count) && (cmd->parameters[i]->value_count > 1)) { + if (cmdDef->parameters[i]->listOk == 0) + { + if ((i < cmd->parameter_count) && (cmd->parameters[i]->value_count > 1)) + { char *errstr = malloc(500); sprintf(errstr, "Parameter number %d does not accept a list of values. " @@ -644,7 +717,8 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, * not provided */ if ((cmdDef->parameters[i]->value_count > 0) && - ((i + 1) > cmd->parameter_count)) { + ((i + 1) > cmd->parameter_count)) + { int j; dclParameterPtr pdef = cmdDef->parameters[i]; dclParameterPtr p = @@ -656,10 +730,13 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, p->values = malloc(p->value_count * sizeof(char *)); for (j = 0; j < p->value_count; j++) p->values[j] = strdup(pdef->values[j]); - if (cmd->parameter_count > 0) { + if (cmd->parameter_count > 0) + { cmd->parameters = realloc(cmd->parameters, (cmd->parameter_count + 1) * sizeof(char *)); - } else { + } + else + { cmd->parameters = malloc(sizeof(char *)); } cmd->parameters[cmd->parameter_count] = p; @@ -668,8 +745,10 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* Check to see if a required parameter was not specified. */ - if (cmdDef->parameters[i]->required) { - if (cmd->parameter_count < (i + 1)) { + if (cmdDef->parameters[i]->required) + { + if (cmd->parameter_count < (i + 1)) + { *prompt = strdup(cmdDef->parameters[i]->prompt ? cmdDef->parameters[i]->prompt : "What"); @@ -680,17 +759,22 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* For each possible qualifier */ - for (i = 0; i < cmdDef->qualifier_count; i++) { + for (i = 0; i < cmdDef->qualifier_count; i++) + { int j; /* If the qualifier is required and was used in the command, make sure user * provided a value */ - if (cmdDef->qualifiers[i]->valueRequired != 0) { + if (cmdDef->qualifiers[i]->valueRequired != 0) + { int q; - for (q = 0; q < cmd->qualifier_count; q++) { + for (q = 0; q < cmd->qualifier_count; q++) + { if (strncasecmp(cmd->qualifiers[q]->name, cmdDef->qualifiers[i]->name, - strlen(cmd->qualifiers[q]->name)) == 0) { - if (cmd->qualifiers[q]->value_count == 0) { + strlen(cmd->qualifiers[q]->name)) == 0) + { + if (cmd->qualifiers[q]->value_count == 0) + { char *errstr = malloc(100); sprintf(errstr, "Qualifier \"%s\" requires a value and none was provided\n", @@ -705,31 +789,39 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* Look for qualifiers that are default qualifiers and add them if not * already there in cmd */ - if (cmdDef->qualifiers[i]->isDefault) { + if (cmdDef->qualifiers[i]->isDefault) + { /* Look to see if the default qualifier is already provided by user. */ - for (j = 0; j < cmd->qualifier_count; j++) { + for (j = 0; j < cmd->qualifier_count; j++) + { if (strncasecmp(cmd->qualifiers[j]->name, cmdDef->qualifiers[i]->name, - strlen(cmd->qualifiers[j]->name)) == 0) { + strlen(cmd->qualifiers[j]->name)) == 0) + { break; } } /* If not already provided add this qualifier with default value if any */ - if (j == cmd->qualifier_count) { + if (j == cmd->qualifier_count) + { dclQualifierPtr qualifier = memset(malloc(sizeof(dclQualifier)), 0, sizeof(dclQualifier)); qualifier->name = strdup(cmdDef->qualifiers[i]->name); - if (cmdDef->qualifiers[i]->defaultValue != NULL) { + if (cmdDef->qualifiers[i]->defaultValue != NULL) + { qualifier->value_count = 1; qualifier->values = malloc(sizeof(char *)); qualifier->values[0] = strdup(cmdDef->qualifiers[i]->defaultValue); } - if (cmd->qualifier_count == 0) { + if (cmd->qualifier_count == 0) + { cmd->qualifiers = malloc(sizeof(dclQualifierPtr)); - } else { + } + else + { cmd->qualifiers = realloc(cmd->qualifiers, sizeof(dclQualifierPtr) * (cmd->qualifier_count + 1)); @@ -743,7 +835,8 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* Replace any parameter names and labels with the real command definition * parameter names. */ - for (i = 0; i < cmd->parameter_count; i++) { + for (i = 0; i < cmd->parameter_count; i++) + { free(cmd->parameters[i]->name); cmd->parameters[i]->name = strdup(cmdDef->parameters[i]->name); free(cmd->parameters[i]->label); @@ -754,25 +847,29 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* For all the qualifiers specified */ - for (i = 0; i < cmd->qualifier_count; i++) { + for (i = 0; i < cmd->qualifier_count; i++) + { int q; /* for all possible qualifiers */ - for (q = 0; q < cmdDef->qualifier_count; q++) { + for (q = 0; q < cmdDef->qualifier_count; q++) + { char *realname = cmdDef->qualifiers[q]->name; char *negated = strcpy(malloc(strlen(realname) + 3), "no"); strcat(negated, realname); if ((strncasecmp(cmd->qualifiers[i]->name, realname, strlen(cmd->qualifiers[i]->name)) == 0) || (strncasecmp(cmd->qualifiers[i]->name, negated, - strlen(cmd->qualifiers[i]->name)) == 0)) { + strlen(cmd->qualifiers[i]->name)) == 0)) + { /************* process type ************/ /* Check if there are too many values specified */ if ((cmd->qualifiers[i]->value_count > 1) && - (cmdDef->qualifiers[q]->listOk == 0)) { + (cmdDef->qualifiers[q]->listOk == 0)) + { char *errstr = malloc(100); sprintf(errstr, "Qualifier \"%s\" does not permit a list of values\n", cmdDef->qualifiers[i]->name); @@ -783,13 +880,16 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, /* Check to see if the command was negated and if that is allowed */ if ((strncasecmp(cmd->qualifiers[i]->name, "no", 2) == 0) && - (strncasecmp(realname, "no", 2) != 0)) { - if (cmdDef->qualifiers[q]->nonnegatable) { + (strncasecmp(realname, "no", 2) != 0)) + { + if (cmdDef->qualifiers[q]->nonnegatable) + { char *errstr = malloc(100); sprintf(errstr, "Qualifier \"%s\" cannot be negated\n", realname); *error = errstr; return MdsdclNOTNEGATABLE; - } else + } + else cmd->qualifiers[i]->negated = 1; } @@ -802,7 +902,8 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, } free(negated); } - if (q == cmdDef->qualifier_count) { + if (q == cmdDef->qualifier_count) + { char *errstr = malloc(100); sprintf(errstr, "Qualifier \"%s\" is not valid for this command\n", cmd->qualifiers[i]->name); @@ -811,12 +912,15 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, } } rest_of_line: - if (cmdDef->routine == NULL) { + if (cmdDef->routine == NULL) + { *error = strdup("No execution routine specified in command definition. " "Internal error, please report to MDSplus developers\n"); fprintf(stderr, "Command not supported\n"); return MdsdclIVVERB; - } else { + } + else + { free(cmd->routine); cmd->routine = strdup(cmdDef->routine); } @@ -826,14 +930,18 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, if (cmdDef->image) image = cmdDef->image; status = LibFindImageSymbol_C(image, cmdDef->routine, &handler); - if (status & 1) { + if (status & 1) + { status = handler(cmd, error, output, getline, getlineinfo); - if (!(status & 1)) { - if ((*error == 0) && (status != 0)) { + if (!(status & 1)) + { + if ((*error == 0) && (status != 0)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); sprintf(*error, "Error message was: %s\n", msg); - } else if (*error == 0) + } + else if (*error == 0) *error = strdup(""); *error = realloc(*error, strlen(*error) + strlen(cmd->command_line) + 100); @@ -890,7 +998,8 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, dclCommandPtr cmd, dclCommandPtr cmdDef, char **prompt, char **error, char **output, char *(*getline)(), - void *getlineinfo) { + void *getlineinfo) +{ xmlDocPtr doc = docList->doc; int i; int status = 0; @@ -900,7 +1009,8 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, /* loop in case syntax changes occur based on parameter or qualifiers */ - while (redo) { + while (redo) + { redo = 0; /* Gather all the known information about the command being processed from @@ -909,15 +1019,18 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, findVerbInfo(verbNode->children, cmdDef); /* For each possible parameter */ - for (i = 0; ((!isSyntax) && (i < cmdDef->parameter_count)); i++) { + for (i = 0; ((!isSyntax) && (i < cmdDef->parameter_count)); i++) + { /* if parameter has a type */ - if ((!isSyntax) && (cmdDef->parameters[i]->type != NULL)) { + if ((!isSyntax) && (cmdDef->parameters[i]->type != NULL)) + { /* If parameter was used in the command look up a type definition based * on the value of the parameter specified */ - if (cmd->parameter_count > i && cmd->parameters[i]->value_count == 1) { + if (cmd->parameter_count > i && cmd->parameters[i]->value_count == 1) + { char *keywordName = cmd->parameters[i]->values[0]; int exactFound = 0; dclNodeList list; @@ -928,7 +1041,8 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, /* If only one match found (which should be the case unless the * command definition is invalid!) */ - if (list.count == 1) { + if (list.count == 1) + { xmlNodePtr typeNode = list.nodes[0]; xmlNodePtr keywordNode; free(list.nodes); @@ -937,20 +1051,25 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, * matches it */ for (keywordNode = typeNode->children; keywordNode; - keywordNode = keywordNode->next) { + keywordNode = keywordNode->next) + { if (keywordNode->name && (strcasecmp((const char *)keywordNode->name, "keyword") == - 0)) { + 0)) + { struct _xmlAttr *nameNode = keywordNode->properties; if (nameNode && nameNode->name && - (strcasecmp((const char *)nameNode->name, "name") == 0)) { + (strcasecmp((const char *)nameNode->name, "name") == 0)) + { if (nameNode->children && nameNode->children->content && (strncasecmp(keywordName, (const char *)nameNode->children->content, - strlen(keywordName)) == 0)) { + strlen(keywordName)) == 0)) + { struct _xmlAttr *syntaxNode = nameNode->next; if (syntaxNode && syntaxNode->children && - syntaxNode->children->content) { + syntaxNode->children->content) + { dclNodeList list = {0, 0}; int exactFound = 0; @@ -964,7 +1083,8 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, command definition) reprocess the cmd using the new syntax definition */ - if (list.count == 1) { + if (list.count == 1) + { redo = 1; isSyntax = 1; verbNode = list.nodes[0]; @@ -990,28 +1110,34 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, /* process syntax switching on qualifiers */ - for (i = 0; (redo == 0) && (i < cmdDef->qualifier_count); i++) { - if (cmdDef->qualifiers[i]->syntax != NULL) { + for (i = 0; (redo == 0) && (i < cmdDef->qualifier_count); i++) + { + if (cmdDef->qualifiers[i]->syntax != NULL) + { int q; - for (q = 0; q < cmd->qualifier_count; q++) { + for (q = 0; q < cmd->qualifier_count; q++) + { char *realname = cmdDef->qualifiers[i]->name; char *negated = strcpy(malloc(strlen(realname) + 3), "no"); strcat(negated, realname); if ((strncasecmp(cmd->qualifiers[q]->name, realname, strlen(cmd->qualifiers[q]->name)) == 0) || (strncasecmp(cmd->qualifiers[q]->name, negated, - strlen(cmd->qualifiers[q]->name)) == 0)) { + strlen(cmd->qualifiers[q]->name)) == 0)) + { dclNodeList list = {0, 0}; int exactFound = 0; findEntity(doc->children, "syntax", cmdDef->qualifiers[i]->syntax, &list, &exactFound); - if (list.count == 1) { + if (list.count == 1) + { int k; freeQualifier(&cmd->qualifiers[q]); cmd->qualifier_count--; for (k = q; k < cmd->qualifier_count; k++) cmd->qualifiers[k] = cmd->qualifiers[k + 1]; - if (cmd->qualifier_count == 0) { + if (cmd->qualifier_count == 0) + { free(cmd->qualifiers); cmd->qualifiers = 0; } @@ -1029,11 +1155,13 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, } REDO: - if (redo) { + if (redo) + { freeCommandParamsAndQuals(cmdDef); } } - if (status == 0) { + if (status == 0) + { status = dispatchToHandler(docList->name, cmd, cmdDef, prompt, error, output, getline, getlineinfo); } @@ -1049,18 +1177,24 @@ int processCommand(dclDocListPtr docList, xmlNodePtr verbNode_in, \param doc [in] The xml document pointer. */ -static void mdsdclSetupCommands(xmlDocPtr doc) { +static void mdsdclSetupCommands(xmlDocPtr doc) +{ /* Set prompt and def_file if defined in top level module key */ struct _xmlAttr *p; - if (doc->children && doc->children) { + if (doc->children && doc->children) + { DCLTHREADSTATIC_INIT; - for (p = doc->children->properties; p; p = p->next) { + for (p = doc->children->properties; p; p = p->next) + { if ((strcasecmp((const char *)p->name, "prompt") == 0) && p->children && - p->children->content) { + p->children->content) + { free(DCL_PROMPT); DCL_PROMPT = strdup((char *)p->children->content); - } else if ((strcasecmp((const char *)p->name, "def_file") == 0) && - p->children && p->children->content) { + } + else if ((strcasecmp((const char *)p->name, "def_file") == 0) && + p->children && p->children->content) + { free(DCL_DEFFILE); if (p->children->content[0] == '*') DCL_DEFFILE = strdup((char *)p->children->content + 1); @@ -1080,19 +1214,22 @@ static void mdsdclSetupCommands(xmlDocPtr doc) { \param error [out] An error message if trouble finding and/or parsing the xml command definition file. */ -inline static void xmlInitParser_supp() { +inline static void xmlInitParser_supp() +{ // so it can targeted for valgrind suppression xmlInitParser(); } static inline void mdsdcl_alloc_docdef(dclDocListPtr doc_l, - DCLTHREADSTATIC_ARG) { + DCLTHREADSTATIC_ARG) +{ dclDocListPtr doc_p = malloc(sizeof(dclDocList)); doc_p->name = doc_l->name; doc_p->doc = doc_l->doc; doc_p->next = DCL_DOCS; DCL_DOCS = doc_p; } -EXPORT int mdsdclAddCommands(const char *name_in, char **error) { +EXPORT int mdsdclAddCommands(const char *name_in, char **error) +{ size_t i; char *name = 0; char *commands; @@ -1124,9 +1261,12 @@ EXPORT int mdsdclAddCommands(const char *name_in, char **error) { /* See if that command table has already been loaded in the private list. If it has, pop that table to the top of the stack and return */ DCLTHREADSTATIC_INIT; - for (doc_l = DCL_DOCS, doc_p = 0; doc_l; doc_p = doc_l, doc_l = doc_l->next) { - if (strcmp(doc_l->name, commands) == 0) { - if (doc_p) { + for (doc_l = DCL_DOCS, doc_p = 0; doc_l; doc_p = doc_l, doc_l = doc_l->next) + { + if (strcmp(doc_l->name, commands) == 0) + { + if (doc_p) + { doc_p->next = doc_l->next; doc_l->next = DCL_DOCS; DCL_DOCS = doc_l; @@ -1142,8 +1282,10 @@ EXPORT int mdsdclAddCommands(const char *name_in, char **error) { static dclDocListPtr dcl_docs_cache = NULL; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&lock); - for (doc_l = dcl_docs_cache; doc_l; doc_l = doc_l->next) { - if (strcmp(doc_l->name, commands) == 0) { + for (doc_l = dcl_docs_cache; doc_l; doc_l = doc_l->next) + { + if (strcmp(doc_l->name, commands) == 0) + { pthread_mutex_unlock(&lock); mdsdcl_alloc_docdef(doc_l, DCLTHREADSTATIC_VAR); free(commands); @@ -1160,7 +1302,8 @@ EXPORT int mdsdclAddCommands(const char *name_in, char **error) { mdsplus_dir = getenv("MDSPLUS_DIR"); if (mdsplus_dir == 0) mdsplus_dir = strdup("."); - else { + else + { mdsplus_dir = strcpy(malloc(strlen(mdsplus_dir) + 10), mdsplus_dir); strcat(mdsplus_dir, "/xml"); } @@ -1177,13 +1320,16 @@ EXPORT int mdsdclAddCommands(const char *name_in, char **error) { /* If cannot find the file or parse it, set the error string */ - if (doc == 0) { + if (doc == 0) + { pthread_mutex_unlock(&lock); char *errstr = malloc(strlen(filename) + 50); sprintf(errstr, " Error: unable to parse %s\n", filename); *error = errstr; status = -1; - } else { + } + else + { /* else stick the parsed xml document at the top of the command stack doc_p for the private entry and doc_l for the static one*/ doc_l = malloc(sizeof(dclDocList)); @@ -1200,15 +1346,18 @@ EXPORT int mdsdclAddCommands(const char *name_in, char **error) { return status; } -EXPORT int mdsdcl_do_command(char const *command) { +EXPORT int mdsdcl_do_command(char const *command) +{ char *error = 0; char *output = 0; int status = mdsdcl_do_command_extra_args(command, 0, &error, &output, 0, 0); - if (error) { + if (error) + { fprintf(stderr, "%s", error); free(error); } - if (output) { + if (output) + { fprintf(stdout, "%s", output); free(output); } @@ -1217,17 +1366,20 @@ EXPORT int mdsdcl_do_command(char const *command) { EXPORT int mdsdcl_do_command_dsc(char const *command, struct descriptor_xd *error_dsc, - struct descriptor_xd *output_dsc) { + struct descriptor_xd *output_dsc) +{ char *error = 0; char *output = 0; int status = mdsdcl_do_command_extra_args(command, 0, error_dsc ? &error : 0, output_dsc ? &output : 0, 0, 0); - if (error) { + if (error) + { struct descriptor d = {strlen(error), DTYPE_T, CLASS_S, error}; MdsCopyDxXd(&d, error_dsc); free(error); } - if (output) { + if (output) + { struct descriptor d = {strlen(output), DTYPE_T, CLASS_S, output}; MdsCopyDxXd(&d, output_dsc); free(output); @@ -1236,7 +1388,8 @@ EXPORT int mdsdcl_do_command_dsc(char const *command, } EXPORT int _mdsdcl_do_command_dsc(void **ctx, char const *command, struct descriptor_xd *error_dsc, - struct descriptor_xd *output_dsc) { + struct descriptor_xd *output_dsc) +{ int status; CTX_PUSH(ctx); status = mdsdcl_do_command_dsc(command, error_dsc, output_dsc); @@ -1247,11 +1400,12 @@ EXPORT int _mdsdcl_do_command_dsc(void **ctx, char const *command, #define facility(status) (status >> 16) #define msgnum(status) ((status & 0xffff) >> 3) #define MDSDCL_FACILITY 2050 -#define invalid_command(status) \ +#define invalid_command(status) \ ((facility(status) == MDSDCL_FACILITY) && (msgnum(status) > 100)) int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, - char **output_out, char *(*getline)(), void *getlineinfo) { + char **output_out, char *(*getline)(), void *getlineinfo) +{ int status = MdsdclIVVERB; char *prompt = 0; char *error = 0; @@ -1261,11 +1415,13 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, DCLTHREADSTATIC_INIT; if (!DCL_DOCS) mdsdclAddCommands("mdsdcl_commands", &error); - if (mdsdclVerify() && strlen(cmd->command_line) > 0) { + if (mdsdclVerify() && strlen(cmd->command_line) > 0) + { char *prompt = mdsdclGetPrompt(); if (error_out == NULL) fprintf(stderr, "%s%s\n", prompt, cmd->command_line); - else { + else + { if (*error_out == NULL) *error_out = strdup(""); *error_out = realloc(*error_out, strlen(*error_out) + strlen(prompt) + @@ -1278,7 +1434,8 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, } for (doc_l = DCL_DOCS; doc_l != NULL && invalid_command(status) && (status != MdsdclPROMPT_MORE); - doc_l = doc_l->next) { + doc_l = doc_l->next) + { dclCommandPtr cmdDef = memset(malloc(sizeof(dclCommand)), 0, sizeof(dclCommand)); cmdDef->verb = strdup(cmd->verb); @@ -1286,27 +1443,36 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, dclNodeList matchingVerbs = {0, 0}; findEntity(((xmlDocPtr)(doc_l->doc))->children, "verb", cmdDef->verb, &matchingVerbs, &exactFound); - if (matchingVerbs.count == 0 || matchingVerbs.count > 1) { + if (matchingVerbs.count == 0 || matchingVerbs.count > 1) + { if (matchingVerbs.nodes != NULL) free(matchingVerbs.nodes); status = MdsdclIVVERB; - } else { + } + else + { char *output_tmp = 0; char *error_tmp = 0; status = processCommand(doc_l, matchingVerbs.nodes[0], cmd, cmdDef, &prompt, &error_tmp, &output_tmp, getline, getlineinfo); - if (status & 1) { + if (status & 1) + { free(error); error = error_tmp; - } else { - if (error_tmp) { + } + else + { + if (error_tmp) + { if (error == NULL) error = error_tmp; - else { + else + { if (invalid_command(status)) free(error_tmp); - else { + else + { free(error); error = error_tmp; } @@ -1314,7 +1480,8 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, error_tmp = 0; } } - if (output_tmp) { + if (output_tmp) + { if (output == NULL) output = output_tmp; else @@ -1323,7 +1490,8 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, output_tmp); } free(matchingVerbs.nodes); - if (status == 0) { + if (status == 0) + { freeCommand(&cmdDef); break; } @@ -1331,16 +1499,21 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, freeCommand(&cmdDef); } freeCommand(&cmd); - if (status == MdsdclPROMPT_MORE) { - if (!prompt) { + if (status == MdsdclPROMPT_MORE) + { + if (!prompt) + { prompt = strdup("What: "); } } - if (prompt != NULL) { + if (prompt != NULL) + { if (prompt_out) *prompt_out = prompt; - else { - if (error != NULL) { + else + { + if (error != NULL) + { error = strcat( realloc(error, strlen(error) + 100), "\nCommand incomplete, missing parameter or qualifier value."); @@ -1348,42 +1521,58 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, free(prompt); } } - if ((prompt == NULL) && (error == 0) && (!(status & 1))) { - if (status == MdsdclIVVERB && error == NULL) { + if ((prompt == NULL) && (error == 0) && (!(status & 1))) + { + if (status == MdsdclIVVERB && error == NULL) + { error = strcpy(malloc(100), "mdsdcl: No such command\n"); - } else { + } + else + { char *msg = MdsGetMsg(status); error = malloc(strlen(msg) + 10); sprintf(error, "Error: %s\n", msg); } } - if (error != NULL) { - if (error_out == NULL) { + if (error != NULL) + { + if (error_out == NULL) + { fprintf(stderr, "%s", error); fflush(stderr); free(error); - } else { - if (*error_out) { + } + else + { + if (*error_out) + { *error_out = strcat( realloc(*error_out, strlen(*error_out) + strlen(error) + 1), error); free(error); - } else + } + else *error_out = error; mdsdclFlushError(*error_out); } } - if (output != NULL) { - if (output_out == NULL) { + if (output != NULL) + { + if (output_out == NULL) + { fprintf(stdout, "%s", output); fflush(stdout); free(output); - } else { - if (*output_out) { + } + else + { + if (*output_out) + { *output_out = strcat( realloc(*output_out, strlen(*output_out) + strlen(output) + 1), output); free(output); - } else + } + else *output_out = output; mdsdclFlushOutput(*output_out); } @@ -1391,55 +1580,72 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, return status; } -EXPORT int cli_present(void *ctx, const char *name) { +EXPORT int cli_present(void *ctx, const char *name) +{ dclCommandPtr cmd = (dclCommandPtr)ctx; int i; int ans = MdsdclABSENT; - for (i = 0; (ans == MdsdclABSENT) && (i < cmd->parameter_count); i++) { + for (i = 0; (ans == MdsdclABSENT) && (i < cmd->parameter_count); i++) + { char *pname = cmd->parameters[i]->label ? cmd->parameters[i]->label : cmd->parameters[i]->name; - if (strcasecmp(name, pname) == 0) { + if (strcasecmp(name, pname) == 0) + { ans = MdsdclPRESENT; } } - for (i = 0; (ans == MdsdclABSENT) && (i < cmd->qualifier_count); i++) { - if (strcasecmp(name, cmd->qualifiers[i]->name) == 0) { + for (i = 0; (ans == MdsdclABSENT) && (i < cmd->qualifier_count); i++) + { + if (strcasecmp(name, cmd->qualifiers[i]->name) == 0) + { ans = cmd->qualifiers[i]->negated ? MdsdclNEGATED : MdsdclPRESENT; } } return ans; } -EXPORT int cli_get_value(void *ctx, const char *name, char **value) { +EXPORT int cli_get_value(void *ctx, const char *name, char **value) +{ dclCommandPtr cmd = (dclCommandPtr)ctx; int i; int ans = MdsdclABSENT; - if (strcasecmp(name, "command_line") == 0) { + if (strcasecmp(name, "command_line") == 0) + { *value = strdup(cmd->command_line); return 1; } - for (i = 0; (ans == MdsdclABSENT) && (i < cmd->parameter_count); i++) { + for (i = 0; (ans == MdsdclABSENT) && (i < cmd->parameter_count); i++) + { if ((strcasecmp(name, cmd->parameters[i]->name) == 0) || ((cmd->parameters[i]->label) && - (strcasecmp(name, cmd->parameters[i]->label) == 0))) { - if (cmd->parameters[i]->value_idx >= cmd->parameters[i]->value_count) { + (strcasecmp(name, cmd->parameters[i]->label) == 0))) + { + if (cmd->parameters[i]->value_idx >= cmd->parameters[i]->value_count) + { ans = MdsdclABSENT; cmd->parameters[i]->value_idx = 0; - } else { + } + else + { *value = strdup(cmd->parameters[i]->values[cmd->parameters[i]->value_idx++]); ans = MdsdclPRESENT; } } } - for (i = 0; (ans == MdsdclABSENT) && (i < cmd->qualifier_count); i++) { - if (strcasecmp(name, cmd->qualifiers[i]->name) == 0) { - if (cmd->qualifiers[i]->value_idx >= cmd->qualifiers[i]->value_count) { + for (i = 0; (ans == MdsdclABSENT) && (i < cmd->qualifier_count); i++) + { + if (strcasecmp(name, cmd->qualifiers[i]->name) == 0) + { + if (cmd->qualifiers[i]->value_idx >= cmd->qualifiers[i]->value_count) + { ans = MdsdclABSENT; cmd->qualifiers[i]->value_idx = 0; - } else { + } + else + { *value = strdup(cmd->qualifiers[i]->values[cmd->qualifiers[i]->value_idx++]); ans = MdsdclPRESENT; @@ -1449,7 +1655,8 @@ EXPORT int cli_get_value(void *ctx, const char *name, char **value) { return ans; } -EXPORT char *mdsdclGetPrompt() { +EXPORT char *mdsdclGetPrompt() +{ char *ans; DCLTHREADSTATIC_INIT; if (!DCL_PROMPT) @@ -1461,26 +1668,32 @@ EXPORT char *mdsdclGetPrompt() { static void (*MDSDCL_OUTPUT_RTN)(char *output) = 0; static void (*MDSDCL_ERROR_RTN)(char *error) = 0; -EXPORT void *mdsdclSetOutputRtn(void (*rtn)()) { +EXPORT void *mdsdclSetOutputRtn(void (*rtn)()) +{ void *old_rtn = MDSDCL_OUTPUT_RTN; MDSDCL_OUTPUT_RTN = rtn; return old_rtn; } -EXPORT void mdsdclFlushOutput(char *output) { - if (MDSDCL_OUTPUT_RTN) { +EXPORT void mdsdclFlushOutput(char *output) +{ + if (MDSDCL_OUTPUT_RTN) + { MDSDCL_OUTPUT_RTN(output); } } -EXPORT void *mdsdclSetErrorRtn(void (*rtn)()) { +EXPORT void *mdsdclSetErrorRtn(void (*rtn)()) +{ void *old_rtn = MDSDCL_ERROR_RTN; MDSDCL_ERROR_RTN = rtn; return old_rtn; } -EXPORT void mdsdclFlushError(char *error) { - if (MDSDCL_ERROR_RTN) { +EXPORT void mdsdclFlushError(char *error) +{ + if (MDSDCL_ERROR_RTN) + { MDSDCL_ERROR_RTN(error); } } diff --git a/mdsdcl/cmdHelp.c b/mdsdcl/cmdHelp.c index 28b35a747c..9e0ccf60a5 100644 --- a/mdsdcl/cmdHelp.c +++ b/mdsdcl/cmdHelp.c @@ -60,7 +60,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ static void findEntity(xmlNodePtr node, const char *category, const char *name, - dclNodeListPtr list, int *exactFound) { + dclNodeListPtr list, int *exactFound) +{ /* If exact match already found just return */ @@ -77,13 +78,15 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, node->properties->children->content && (strncasecmp(name, (const char *)node->properties->children->content, - strlen(name)) == 0)))) { + strlen(name)) == 0)))) + { /* Check if it is an exact match */ if ((name != NULL) && (strlen(name) == strlen((const char *)node->properties->children - ->content))) { // if exact command match use it! + ->content))) + { // if exact command match use it! /* if already found other nodes but not exact match then free the "array" * of nodes. */ @@ -101,9 +104,12 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, /* Add this node to the list of nodes */ - if (list->count == 0) { + if (list->count == 0) + { list->nodes = malloc(sizeof(xmlNodePtr)); - } else { + } + else + { list->nodes = realloc(list->nodes, sizeof(xmlNodePtr) * (list->count + 1)); } @@ -122,7 +128,8 @@ static void findEntity(xmlNodePtr node, const char *category, const char *name, findEntity(node->children, category, name, list, exactFound); } -static char *formatHelp(char *content) { +static char *formatHelp(char *content) +{ int indentation = -1; int offset = 0; char *ans = strdup(""); @@ -131,30 +138,39 @@ static char *formatHelp(char *content) { char *line; int leading = 1; #ifdef HAVE_STRSEP - for (line = strsep(&hlp, "\n"); line; line = strsep(&hlp, "\n")) { + for (line = strsep(&hlp, "\n"); line; line = strsep(&hlp, "\n")) + { #else char *saveptr = 0; for (line = strtok_r(hlp, "\n", &saveptr); line; - line = strtok_r(0, "\n", &saveptr)) { + line = strtok_r(0, "\n", &saveptr)) + { #endif - if ((strlen(line) > 0) && (strspn(line, " \t") != strlen(line))) { + if ((strlen(line) > 0) && (strspn(line, " \t") != strlen(line))) + { char *nline; leading = 0; - if (indentation == -1) { + if (indentation == -1) + { for (indentation = 0; line[indentation] == ' '; indentation++) ; offset = indentation - 2; } - if (offset < 0) { + if (offset < 0) + { nline = strcpy(malloc(strlen(line) - offset + 1), " "); strcat(nline, line); - } else { + } + else + { nline = strcpy(malloc(strlen(line) - offset + 1), line + offset); } ans = strcat(realloc(ans, strlen(ans) + strlen(nline) + 2), nline); free(nline); strcat(ans, "\n"); - } else { + } + else + { if (leading == 0) ans = strcat(realloc(ans, strlen(ans) + 2), "\n"); } @@ -163,7 +179,8 @@ static char *formatHelp(char *content) { return ans; } -int mdsdcl_do_help(const char *command, char **error, char **output) { +int mdsdcl_do_help(const char *command, char **error, char **output) +{ int status = MdsdclIVVERB; dclDocListPtr doc_l; int helpFound = 0; @@ -178,20 +195,27 @@ int mdsdcl_do_help(const char *command, char **error, char **output) { doc_l = doc_l->next, docIdx--) docs[docIdx] = doc_l->doc; *output = strdup("\n"); - for (docIdx = 0; (status == MdsdclIVVERB) && (docIdx < numDocs); docIdx++) { + for (docIdx = 0; (status == MdsdclIVVERB) && (docIdx < numDocs); docIdx++) + { xmlDocPtr doc = docs[docIdx]; int exactFound = 0; dclNodeList matchingHelp = {0, 0}; - if (command != 0) { + if (command != 0) + { findEntity(doc->children, "help", command, &matchingHelp, &exactFound); - if (matchingHelp.count == 0) { + if (matchingHelp.count == 0) + { status = MdsdclIVVERB; - } else { + } + else + { int i; - for (i = 0; i < matchingHelp.count; i++) { + for (i = 0; i < matchingHelp.count; i++) + { char *content = (char *)(((xmlNodePtr)matchingHelp.nodes[i])->children->content); - if (content != NULL) { + if (content != NULL) + { char *help = formatHelp(content); helpFound = 1; *output = strcat( @@ -201,12 +225,15 @@ int mdsdcl_do_help(const char *command, char **error, char **output) { } free(matchingHelp.nodes); } - } else { + } + else + { findEntity(doc->children, "helpall", 0, &matchingHelp, &exactFound); if ((matchingHelp.count == 1) && matchingHelp.nodes && matchingHelp.nodes[0] && ((xmlNodePtr)matchingHelp.nodes[0])->children && - ((xmlNodePtr)matchingHelp.nodes[0])->children->content) { + ((xmlNodePtr)matchingHelp.nodes[0])->children->content) + { char *content = (char *)(((xmlNodePtr)matchingHelp.nodes[0])->children->content); char *help = formatHelp(content); @@ -219,8 +246,10 @@ int mdsdcl_do_help(const char *command, char **error, char **output) { free(matchingHelp.nodes); } } - if (helpFound == 0) { - if (*output) { + if (helpFound == 0) + { + if (*output) + { strcpy(*output, ""); } *error = strdup("No help available for that command.\n"); diff --git a/mdsdcl/dcl_p.h b/mdsdcl/dcl_p.h index 7b81195bb0..f070f11667 100644 --- a/mdsdcl/dcl_p.h +++ b/mdsdcl/dcl_p.h @@ -1,24 +1,27 @@ #ifndef DCL_P_H #define DCL_P_H -typedef struct dclValue { +typedef struct dclValue +{ char *value; char *restOfLine; } dclValue, *dclValuePtr; -typedef struct dclValueList { +typedef struct dclValueList +{ int count; /*!< number of values in values array */ char *restOfLine; /*!< rest of command line */ char **values; /*!< array of values */ } dclValueList, *dclValueListPtr; -typedef struct dclParameter { - char *name; /*!< Name of parameter for cli queries */ - char *prompt; /*!< Prompt to present if interactive and parameter is missing +typedef struct dclParameter +{ + char *name; /*!< Name of parameter for cli queries */ + char *prompt; /*!< Prompt to present if interactive and parameter is missing but required */ - char *label; /*!< Alternate name for cli queries */ - char *type; /*!< Used for syntax switching */ - int required; /*!< 1 if parameter is required */ + char *label; /*!< Alternate name for cli queries */ + char *type; /*!< Used for syntax switching */ + int required; /*!< 1 if parameter is required */ int value_count; /*!< number of value string present */ int value_idx; /*!< index of next value to return */ char **values; /*!< array of values strings */ @@ -28,7 +31,8 @@ typedef struct dclParameter { char *help; /*!< help string for the parameter */ } dclParameter, *dclParameterPtr; -typedef struct dclQualifier { +typedef struct dclQualifier +{ char *name; /*!< Name of qualifier for cli queries */ int value_count; /*!< Number of value strings present */ int value_idx; /*|< index of next value to return */ @@ -48,17 +52,18 @@ typedef struct dclQualifier { char *help; /*!< help string for qualifier */ } dclQualifier, *dclQualifierPtr; -typedef struct dclCommand { - char *command_line; /*!< full command line */ - int rest_of_line; /*!< command handler deals with parsing the command. +typedef struct dclCommand +{ + char *command_line; /*!< full command line */ + int rest_of_line; /*!< command handler deals with parsing the command. Parameters and qualifiers not checked generically. */ - char *verb; /*!< verb name of command */ - int parameter_count; /*!< number of parameters */ + char *verb; /*!< verb name of command */ + int parameter_count; /*!< number of parameters */ dclParameterPtr *parameters; /*!< array of parameters */ int qualifier_count; /*!< number of qualifiers */ dclQualifierPtr *qualifiers; /*!< array of qualifiers */ - char *routine; /*!< routine providing implementation of the command */ - char *image; /*!< optional image where routine can be found */ + char *routine; /*!< routine providing implementation of the command */ + char *image; /*!< optional image where routine can be found */ } dclCommand, *dclCommandPtr; #define YYSTYPE_IS_DECLARED @@ -72,14 +77,16 @@ typedef union YYSTYPE { /*!< Used for types used during bison/flex parsing of dclValuePtr pvalue; } YYSTYPE; -typedef struct dclNodeList { +typedef struct dclNodeList +{ int count; /*!< number of nodes in nodes array */ void **nodes; /*!< array of xmlNodePtr's */ } dclNodeList, *dclNodeListPtr; -typedef struct dclDocList { - char *name; /*!< Name of xml command definition (i.e. tcl_commands) */ - void *doc; /*!< xml document specifying the command syntax */ +typedef struct dclDocList +{ + char *name; /*!< Name of xml command definition (i.e. tcl_commands) */ + void *doc; /*!< xml document specifying the command syntax */ struct dclDocList *next; /*!< Next loaded document */ } dclDocList, *dclDocListPtr; @@ -92,7 +99,8 @@ extern int mdsdclDeltatimeToSeconds(const char *deltatime); extern int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, char **output_out, char *(*getline)(), void *getlineinfo); -typedef struct { +typedef struct +{ const char *GIT_TAG; const char *GIT_BRANCH; const char *GIT_REMOTE; diff --git a/mdsdcl/mdsdcl.c b/mdsdcl/mdsdcl.c index 8408fd7963..77098050c1 100644 --- a/mdsdcl/mdsdcl.c +++ b/mdsdcl/mdsdcl.c @@ -51,31 +51,39 @@ be added using the "SET COMMAND table-name" command. \param argv [in] An array of command line option strings. */ -static void flushOut(char *output) { +static void flushOut(char *output) +{ fprintf(stdout, "%s", output); fflush(stdout); output[0] = 0; } -static void flushError(char *error) { +static void flushError(char *error) +{ fprintf(stderr, "%s", error); fflush(stderr); error[0] = 0; } static char *prompt = NULL; -static void keyboard_interrupt(int signo __attribute__((__unused__))) { +static void keyboard_interrupt(int signo __attribute__((__unused__))) +{ fprintf(stderr, "KeyboardInterrupt\n"); } #ifdef _WIN32 -static inline void set_readline_handlers() { signal(SIGINT, SIG_IGN); } -static inline void set_execute_handlers() { +static inline void set_readline_handlers() +{ + signal(SIGINT, SIG_IGN); +} +static inline void set_execute_handlers() +{ signal(SIGINT, keyboard_interrupt); } #else // _WIN32 static struct sigaction act; #ifdef HAVE_RL_SET_SIGNALS -static inline void set_readline_handlers() { +static inline void set_readline_handlers() +{ rl_catch_signals = 1; rl_set_signals(); } @@ -84,7 +92,8 @@ static inline void set_execute_handlers() { rl_clear_signals(); } #ifdef _MACOSX #define _rl_sigint SIG_IGN #else // _MACOSX -static void _rl_sigint(int signo __attribute__((__unused__))) { +static void _rl_sigint(int signo __attribute__((__unused__))) +{ // reset readline line buffer and state before printing new prompt rl_free_line_state(); rl_cleanup_after_signal(); @@ -94,18 +103,21 @@ static void _rl_sigint(int signo __attribute__((__unused__))) { printf("\n%s", prompt); } #endif // !_MACOSX -static inline void set_readline_handlers() { +static inline void set_readline_handlers() +{ act.sa_handler = _rl_sigint; sigaction(SIGINT, &act, NULL); } -static inline void set_execute_handlers() { +static inline void set_execute_handlers() +{ act.sa_handler = keyboard_interrupt; sigaction(SIGINT, &act, NULL); } #endif // !HAVE_RL_SET_SIGNALS #endif // !_WIN32 -int main(int argc, char const *argv[]) { +int main(int argc, char const *argv[]) +{ char *history_file = NULL; char *command = NULL; int notDone = 1; @@ -120,7 +132,8 @@ int main(int argc, char const *argv[]) { mdsdclSetErrorRtn(flushError); mdsdclAddCommands("mdsdcl_commands", &error); - if (error) { + if (error) + { fprintf(stderr, "%s", error); fflush(stderr), free(error); exit(1); @@ -134,7 +147,8 @@ int main(int argc, char const *argv[]) { act.sa_handler = keyboard_interrupt; sigaction(SIGINT, &act, NULL); #endif - if ((argc > 2) && (strcmp("-prep", argv[1]) == 0)) { + if ((argc > 2) && (strcmp("-prep", argv[1]) == 0)) + { char *prep_cmd = strdup(argv[2]); int inquote = 0; size_t k; @@ -144,7 +158,8 @@ int main(int argc, char const *argv[]) { this to load the appropriate command definitions, set the prompt string and the history file. */ - for (k = 0; k < strlen(prep_cmd); k++) { + for (k = 0; k < strlen(prep_cmd); k++) + { if (prep_cmd[k] == '"') inquote = !inquote; else if ((!inquote) && (prep_cmd[k] == '-')) @@ -165,14 +180,17 @@ int main(int argc, char const *argv[]) { /* If other options on command line */ - if ((argc > 2) && (strcmp("-f", argv[1]) == 0)) { + if ((argc > 2) && (strcmp("-f", argv[1]) == 0)) + { FILE *fp = fopen(argv[2], "r"); - if (fp == NULL) { + if (fp == NULL) + { perror("Error opening file"); exit(EXIT_FAILURE); } char line[1024]; - while (fgets(line, sizeof(line), fp)) { + while (fgets(line, sizeof(line), fp)) + { size_t len = strlen(line); while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; @@ -185,11 +203,13 @@ int main(int argc, char const *argv[]) { exit(EXIT_SUCCESS); } - if (argc > 1) { + if (argc > 1) + { /* Concatenate rest of line into a mdsdcl command string */ char *cmd = strdup(argv[1]); - for (i = 2; i < argc; i++) { + for (i = 2; i < argc; i++) + { cmd = strcat(realloc(cmd, strlen(cmd) + strlen(argv[i]) + 2), " "); strcat(cmd, argv[i]); } @@ -207,7 +227,8 @@ int main(int argc, char const *argv[]) { /* While more commands to be entered */ - while (notDone) { + while (notDone) + { char *cmd; /* If prompt not defined get the prompt */ @@ -220,15 +241,20 @@ int main(int argc, char const *argv[]) { cmd = readline(prompt); /* If not EOF */ - if (cmd) { + if (cmd) + { /* If command continued from previous line or command need more input, append line to previous command portion */ - if (command) { - if (strlen(cmd) > 0) { + if (command) + { + if (strlen(cmd) > 0) + { command = (char *)realloc(command, strlen(command) + strlen(cmd) + 1); strcat(command, cmd); free(cmd); - } else { + } + else + { free(cmd); free(command); command = 0; @@ -236,12 +262,14 @@ int main(int argc, char const *argv[]) { prompt = 0; continue; } - } else + } + else command = cmd; /* If line ends in hyphen it is a continuation. Go get rest of line */ if (strlen(command) > 1) - if (command[strlen(command) - 1] == '-') { + if (command[strlen(command) - 1] == '-') + { command[strlen(command) - 1] = '\0'; free(prompt); prompt = strdup("Continue: "); @@ -250,20 +278,24 @@ int main(int argc, char const *argv[]) { /* If not an empty command line */ - if (strlen(command) > 0) { + if (strlen(command) > 0) + { char *prompt_more = 0; add_history(command); - if (output) { + if (output) + { free(output); output = 0; } set_execute_handlers(); status = mdsdcl_do_command_extra_args(command, &prompt_more, &error, &output, 0, 0); - if (prompt_more != NULL) { + if (prompt_more != NULL) + { HIST_ENTRY *hist; hist = remove_history(where_history()); - if (hist) { + if (hist) + { if (hist->line) free((void *)hist->line); free(hist); @@ -277,7 +309,8 @@ int main(int argc, char const *argv[]) { free(prompt_more); continue; } - if (error != NULL) { + if (error != NULL) + { fprintf(stderr, "%s", error); fflush(stderr); free(error); @@ -285,7 +318,8 @@ int main(int argc, char const *argv[]) { } free(prompt); prompt = 0; - if (status == MdsdclEXIT) { + if (status == MdsdclEXIT) + { free(command); status = 0; goto done; @@ -293,7 +327,9 @@ int main(int argc, char const *argv[]) { } free(command); command = 0; - } else { + } + else + { notDone = 0; printf("\n"); } diff --git a/mdsdcl/mdsdclThreadStatic.c b/mdsdcl/mdsdclThreadStatic.c index f86993962b..95901a87a9 100644 --- a/mdsdcl/mdsdclThreadStatic.c +++ b/mdsdcl/mdsdclThreadStatic.c @@ -33,14 +33,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../mdsshr/version.h" #include "mdsdclthreadstatic.h" -static inline DCLTHREADSTATIC_TYPE *buffer_alloc() { +static inline DCLTHREADSTATIC_TYPE *buffer_alloc() +{ return (DCLTHREADSTATIC_TYPE *)calloc(1, sizeof(DCLTHREADSTATIC_TYPE)); } -static void buffer_free(DCLTHREADSTATIC_ARG) { +static void buffer_free(DCLTHREADSTATIC_ARG) +{ free(DCL_PROMPT); free(DCL_DEFFILE); dclDocListPtr next, dcl; - for (dcl = DCL_DOCS; dcl; dcl = next) { + for (dcl = DCL_DOCS; dcl; dcl = next) + { next = dcl->next; free(dcl); } diff --git a/mdsdcl/mdsdcl_commands.c b/mdsdcl/mdsdcl_commands.c index ced69f48ab..ce477aaa67 100644 --- a/mdsdcl/mdsdcl_commands.c +++ b/mdsdcl/mdsdcl_commands.c @@ -49,7 +49,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define setenv(name, value, overwrite) _putenv_s(name, value) #endif -typedef struct dclMacroList { +typedef struct dclMacroList +{ char *name; /*!< macro name */ int lines; /*!< number of lines in macro */ char **cmds; /*!< cmds in macro */ @@ -87,7 +88,8 @@ static int STOP_ON_FAIL = 1; ****************************************************************/ EXPORT int mdsdcl_exit(void *ctx __attribute__((unused)), char *error __attribute__((unused)), - char *output __attribute__((unused))) { + char *output __attribute__((unused))) +{ return MdsdclEXIT; } @@ -106,7 +108,8 @@ static struct timeval TIMER_START_TIME; EXPORT int mdsdcl_init_timer(void *ctx __attribute__((unused)), char *error __attribute__((unused)), - char *output __attribute__((unused))) { + char *output __attribute__((unused))) +{ gettimeofday(&TIMER_START_TIME, 0); #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &TIMER_START_USAGE); @@ -117,7 +120,8 @@ EXPORT int mdsdcl_init_timer(void *ctx __attribute__((unused)), } EXPORT int mdsdcl_show_timer(void *ctx __attribute__((unused)), char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ struct timeval TIMER_NOW_TIME; long int esec = 0; long int emsec = 0; @@ -168,16 +172,20 @@ EXPORT int mdsdcl_show_timer(void *ctx __attribute__((unused)), char **error, * mdsdcl_set_prompt: **************************************************************/ EXPORT int mdsdcl_set_prompt(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *prompt = 0; int status; cli_get_value(ctx, "PROMPT", &prompt); - if (prompt) { + if (prompt) + { DCLTHREADSTATIC_INIT; free(DCL_PROMPT); DCL_PROMPT = prompt; status = MdsdclSUCCESS; - } else { + } + else + { status = MdsdclERROR; *error = strdup("No prompt specified\n"); } @@ -188,13 +196,17 @@ EXPORT int mdsdcl_set_prompt(void *ctx, char **error, * mdsdcl_type: ****************************************************************/ EXPORT int mdsdcl_type(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ char *text = 0; cli_get_value(ctx, "P1", &text); - if (text) { + if (text) + { text = strcat(realloc(text, strlen(text) + 2), "\n"); *output = text; - } else { + } + else + { *output = strdup("\n"); } return MdsdclSUCCESS; @@ -205,7 +217,8 @@ EXPORT int mdsdcl_type(void *ctx, char **error __attribute__((unused)), ****************************************************************/ EXPORT int mdsdcl_set_hyphen(void *ctx __attribute__((unused)), char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ *error = strdup("SET HYPHEN obsolete, no longer supported\n"); return MdsdclSUCCESS; } @@ -219,7 +232,8 @@ static int MDSDCL_VERIFY = 0; int mdsdclVerify() { return MDSDCL_VERIFY; } EXPORT int mdsdcl_set_verify(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *verify = 0; cli_get_value(ctx, "P1", &verify); MDSDCL_VERIFY = verify && (toupper(verify[0]) == 'V'); @@ -231,29 +245,32 @@ EXPORT int mdsdcl_set_verify(void *ctx, char **error __attribute__((unused)), * mdsdcl_define_symbol: ****************************************************************/ EXPORT int mdsdcl_define_symbol(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *name = NULL, *value = NULL; int status = cli_get_value(ctx, "SYMBOL", &name); - if - STATUS_NOT_OK { - *error = malloc(100); - sprintf(*error, "Error: problem getting symbol name"); - goto done; - } + if (STATUS_NOT_OK) + { + *error = malloc(100); + sprintf(*error, "Error: problem getting symbol name"); + goto done; + } status = cli_get_value(ctx, "VALUE", &value); - if - STATUS_NOT_OK { - *error = malloc(100); - sprintf(*error, "Error: problem getting value for symbol"); - goto done; - } + if (STATUS_NOT_OK) + { + *error = malloc(100); + sprintf(*error, "Error: problem getting value for symbol"); + goto done; + } status = setenv(name, value, 1); - if (status) { + if (status) + { *error = malloc(100); sprintf(*error, "setenv returned %d. Environment variable not set.", status); status = MdsdclERROR; - } else + } + else status = MdsdclSUCCESS; done: free(name); @@ -262,31 +279,40 @@ EXPORT int mdsdcl_define_symbol(void *ctx, char **error, } EXPORT int mdsdcl_env(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *name, *value; int status = cli_get_value(ctx, "P1", &name); for (value = name; value[0] && value[0] != '='; value++) ; - if (value[0] == '\0') { + if (value[0] == '\0') + { value = getenv(name); - if (value) { + if (value) + { *output = malloc(strlen(name) + strlen(value) + 7); sprintf(*output, "%s=%s\n", name, value); // free(value); - } else { + } + else + { *error = malloc(strlen(name) + 19); sprintf(*error, "\"%s\" not defined\n", name); } - } else { + } + else + { value[0] = '\0'; value++; status = setenv(name, value, 1); - if (status) { + if (status) + { *error = malloc(100); sprintf(*error, "setenv returned %d. Environment variable not set.", status); status = MdsdclERROR; - } else + } + else status = MdsdclSUCCESS; } free(name); @@ -299,7 +325,8 @@ extern int LibSpawn(); * mdsdcl_spawn: **************************************************************/ EXPORT int mdsdcl_spawn(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int notifyFlag; int waitFlag; int status; @@ -308,13 +335,15 @@ EXPORT int mdsdcl_spawn(void *ctx, char **error, cli_get_value(ctx, "COMMAND", &cmd); notifyFlag = cli_present(ctx, "NOTIFY") & 1; waitFlag = cli_present(ctx, "WAIT") & 1; - if (cmd) { + if (cmd) + { cmd_dsc.length = strlen(cmd); cmd_dsc.pointer = cmd; } status = LibSpawn(&cmd_dsc, waitFlag, notifyFlag); free(cmd); - if (status) { + if (status) + { *error = malloc(100); sprintf(*error, "Spawn returned: %d\n", status); return MdsdclERROR; @@ -342,64 +371,74 @@ EXPORT char *mdsdclGetHistoryFile() { return history_file; } * mdsdcl_set_command: ****************************************************************/ EXPORT int mdsdcl_set_command(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status; char *table = 0; char *prompt = 0; char *def_file = 0; char *history = 0; cli_get_value(ctx, "TABLE", &table); - if (table) { + if (table) + { status = mdsdclAddCommands(table, error) == 0; free(table); - } else { + } + else + { *error = strdup("Error: command table not specified\n"); status = MdsdclERROR; } - if - STATUS_OK { - /*------------------------------------------------------ + if (STATUS_OK) + { + /*------------------------------------------------------ * Check for other qualifiers ... *-----------------------------------------------------*/ - DCLTHREADSTATIC_INIT; - cli_get_value(ctx, "PROMPT", &prompt); - if (prompt) { - free(DCL_PROMPT); - DCL_PROMPT = prompt; + DCLTHREADSTATIC_INIT; + cli_get_value(ctx, "PROMPT", &prompt); + if (prompt) + { + free(DCL_PROMPT); + DCL_PROMPT = prompt; + } + cli_get_value(ctx, "DEF_FILE", &def_file); + if (def_file) + { + if (def_file[0] == '*') + { + char *tmp = strdup(def_file + 1); + free(def_file); + def_file = tmp; } - cli_get_value(ctx, "DEF_FILE", &def_file); - if (def_file) { - if (def_file[0] == '*') { - char *tmp = strdup(def_file + 1); - free(def_file); - def_file = tmp; - } - free(DCL_DEFFILE); - if (def_file[0] == '*') { - char *c; - for (c = def_file; *c; c++) - c[0] = c[1]; - } - DCL_DEFFILE = def_file; + free(DCL_DEFFILE); + if (def_file[0] == '*') + { + char *c; + for (c = def_file; *c; c++) + c[0] = c[1]; } - cli_get_value(ctx, "HISTORY", &history); - if (history) { + DCL_DEFFILE = def_file; + } + cli_get_value(ctx, "HISTORY", &history); + if (history) + { #ifdef _WIN32 - char *home = getenv("USERPROFILE"); - char *sep = "\\"; + char *home = getenv("USERPROFILE"); + char *sep = "\\"; #else - char *home = getenv("HOME"); - char *sep = "/"; + char *home = getenv("HOME"); + char *sep = "/"; #endif - free(history_file); - if (home) { - history_file = malloc(strlen(history) + strlen(home) + 100); - sprintf(history_file, "%s%s%s", home, sep, history); - free(history); - read_history(history_file); - } + free(history_file); + if (home) + { + history_file = malloc(strlen(history) + strlen(home) + 100); + sprintf(history_file, "%s%s%s", home, sep, history); + free(history); + read_history(history_file); } } + } return status; } @@ -409,30 +448,35 @@ EXPORT int mdsdcl_set_command(void *ctx, char **error, **************************************************************/ EXPORT int mdsdcl_wait(void *ctx, char **error, char **output - __attribute__((unused))) { /* Return: status */ + __attribute__((unused))) +{ /* Return: status */ char *deltatime = 0; int status = MdsdclSUCCESS; int seconds; cli_get_value(ctx, "DELTA_TIME", &deltatime); - if (deltatime == NULL) { + if (deltatime == NULL) + { *error = strdup("No wait time specified\n"); return MdsdclERROR; } seconds = mdsdclDeltatimeToSeconds(deltatime); - if (seconds == -1) { + if (seconds == -1) + { *error = malloc(strlen(deltatime) + 100); sprintf(*error, "Error: Invalid wait time specified - %s\n" "Specify: [ndays] [nhours:][nminutes:]nseconds\n", deltatime); status = MdsdclERROR; - } else + } + else sleep(seconds); free(deltatime); return status; } -EXPORT int mdsdcl_help(void *ctx, char **error, char **output) { +EXPORT int mdsdcl_help(void *ctx, char **error, char **output) +{ char *p1 = 0; int status; cli_get_value(ctx, "P1", &p1); @@ -443,21 +487,26 @@ EXPORT int mdsdcl_help(void *ctx, char **error, char **output) { static dclMacroListPtr MLIST = 0; -static dclMacroListPtr mdsdclNewMacro(char *name) { +static dclMacroListPtr mdsdclNewMacro(char *name) +{ dclMacroListPtr l, prev = 0; size_t i; for (i = 0; i < strlen(name); i++) name[i] = toupper(name[i]); - for (l = MLIST; l; prev = l, l = l->next) { + for (l = MLIST; l; prev = l, l = l->next) + { if (strcasecmp(name, l->name) == 0) break; } - if (l) { + if (l) + { int i; for (i = 0; i < l->lines; i++) free(l->cmds[i]); l->lines = 0; - } else { + } + else + { l = malloc(sizeof(dclMacroList)); l->name = name; l->lines = 0; @@ -473,20 +522,23 @@ static dclMacroListPtr mdsdclNewMacro(char *name) { EXPORT int mdsdcl_define(void *ctx, char **error, char **output __attribute__((unused)), - char *(*getline)(), void *getlineinfo) { + char *(*getline)(), void *getlineinfo) +{ char *name = 0; char *line; dclMacroListPtr macro; cli_get_value( ctx, "p1", &name); /*** do not free name as it is used in macro definition ***/ - if (name == NULL) { + if (name == NULL) + { *error = strdup("No macro name specified\n"); return MdsdclIVVERB; } macro = mdsdclNewMacro(name); while ((line = (getline ? getline(getlineinfo) : readline("DEFMAC> "))) && - (strlen(line)) > 0) { + (strlen(line)) > 0) + { macro->cmds = realloc(macro->cmds, sizeof(char *) * (macro->lines + 1)); macro->cmds[macro->lines++] = line; if (getline == NULL) @@ -497,16 +549,19 @@ EXPORT int mdsdcl_define(void *ctx, char **error, return MdsdclSUCCESS; } -static void mdsdcl_print_macro(dclMacroListPtr l, int full, char **output) { +static void mdsdcl_print_macro(dclMacroListPtr l, int full, char **output) +{ if (*output == 0) *output = strdup(""); *output = strcat(realloc(*output, strlen(*output) + strlen(l->name) + 5), "\n"); strcat(*output, l->name); strcat(*output, "\n"); - if (full == MdsdclPRESENT) { + if (full == MdsdclPRESENT) + { int i; - for (i = 0; i < l->lines; i++) { + for (i = 0; i < l->lines; i++) + { *output = strcat( realloc(*output, strlen(*output) + strlen(l->cmds[i]) + 5), " "); strcat(*output, l->cmds[i]); @@ -515,23 +570,29 @@ static void mdsdcl_print_macro(dclMacroListPtr l, int full, char **output) { } } -EXPORT int mdsdcl_show_macro(void *ctx, char **error, char **output) { +EXPORT int mdsdcl_show_macro(void *ctx, char **error, char **output) +{ char *name = 0; int full = cli_present(ctx, "FULL"); dclMacroListPtr l; cli_get_value(ctx, "P2", &name); - if (name && (strlen(name) > 0)) { - for (l = MLIST; l; l = l->next) { + if (name && (strlen(name) > 0)) + { + for (l = MLIST; l; l = l->next) + { if (strcasecmp(name, l->name) == 0) break; } if (l) mdsdcl_print_macro(l, full, output); - else { + else + { *error = malloc(100 + strlen(name)); sprintf(*error, "Error finding macro called %s\n", name); } - } else { + } + else + { for (l = MLIST; l; l = l->next) mdsdcl_print_macro(l, full, output); } @@ -540,16 +601,21 @@ EXPORT int mdsdcl_show_macro(void *ctx, char **error, char **output) { } static void mdsdclSubstitute(char **cmd, char *p1, char *p2, char *p3, char *p4, - char *p5, char *p6, char *p7) { + char *p5, char *p6, char *p7) +{ char *ps[7] = {p1, p2, p3, p4, p5, p6, p7}; int p; - for (p = 0; p < 7; p++) { + for (p = 0; p < 7; p++) + { char param[15]; size_t i; sprintf(param, "'p%d'", p + 1); - for (i = 0; (i + 3) < strlen(*cmd); i++) { - if (strncasecmp((*cmd) + i, param, strlen(param)) == 0) { - if (ps[p] && (strlen(ps[p]) > 0)) { + for (i = 0; (i + 3) < strlen(*cmd); i++) + { + if (strncasecmp((*cmd) + i, param, strlen(param)) == 0) + { + if (ps[p] && (strlen(ps[p]) > 0)) + { char *newcmd = malloc(strlen(*cmd) + strlen(ps[p])); (*cmd)[i] = 0; strcpy(newcmd, *cmd); @@ -557,7 +623,9 @@ static void mdsdclSubstitute(char **cmd, char *p1, char *p2, char *p3, char *p4, strcat(newcmd, (*cmd) + i + 4); free(*cmd); *cmd = newcmd; - } else { + } + else + { memmove(*cmd + i, (*cmd) + i + 4, strlen(*cmd) - (i + 4)); (*cmd)[strlen(*cmd) - 4] = 0; } @@ -566,12 +634,14 @@ static void mdsdclSubstitute(char **cmd, char *p1, char *p2, char *p3, char *p4, } } -typedef struct getNextLineInfo { +typedef struct getNextLineInfo +{ int *idx; dclMacroListPtr m; } getNextLineInfo, *getNextLineInfoPtr; -static char *getNextLine(getNextLineInfoPtr info) { +static char *getNextLine(getNextLineInfoPtr info) +{ *info->idx = *info->idx + 1; if (*info->idx < info->m->lines) return strdup(info->m->cmds[*info->idx]); @@ -579,7 +649,8 @@ static char *getNextLine(getNextLineInfoPtr info) { return strdup(""); } -EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { +EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) +{ char *name = 0; char *defname = 0; char *times_s = 0; @@ -597,14 +668,16 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { cli_get_value(ctx, "p6", &p6); cli_get_value(ctx, "p7", &p7); // void *oldOutputRtn = mdsdclSetOutputRtn(0); - if (indirect) { + if (indirect) + { FILE *f = NULL; char line[4096]; DCLTHREADSTATIC_INIT; if (DCL_DEFFILE && (strlen(DCL_DEFFILE) > 0) && !((strlen(name) > strlen(DCL_DEFFILE)) && (strcmp(name + strlen(name) - strlen(DCL_DEFFILE), DCL_DEFFILE) == - 0))) { + 0))) + { defname = strdup(name); defname = strcat(realloc(defname, strlen(defname) + strlen(DCL_DEFFILE) + 1), @@ -613,19 +686,25 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { } if (f == NULL) f = fopen(name, "r"); - if (f == NULL) { - if (defname) { + if (f == NULL) + { + if (defname) + { *error = malloc(strlen(name) + strlen(defname) + 100); sprintf(*error, "Error: Unable to open either %s or %s\n", defname, name); - } else { + } + else + { *error = malloc(strlen(name) + 100); sprintf(*error, "Error: Unable to open %s\n", name); } } - if (f != NULL) { + if (f != NULL) + { l = memset(malloc(sizeof(dclMacroList)), 0, sizeof(dclMacroList)); - while (fgets(line, sizeof(line), f)) { + while (fgets(line, sizeof(line), f)) + { l->lines++; l->cmds = realloc(l->cmds, l->lines * sizeof(char *)); if (line[strlen(line) - 1] == '\n') @@ -634,28 +713,36 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { } fclose(f); } - } else { - for (l = MLIST; l; l = l->next) { + } + else + { + for (l = MLIST; l; l = l->next) + { if (strcasecmp(name, l->name) == 0) break; } - if (l == NULL) { + if (l == NULL) + { *error = malloc(strlen(name) + 100); sprintf(*error, "Error: Macro %s is not defined\n", name); status = MdsdclERROR; } } - if (l != NULL) { + if (l != NULL) + { int times = 1; int time; int failed = 0; - if (times_s) { + if (times_s) + { times = strtol(times_s, NULL, 0); free(times_s); } - for (time = 0; (failed == 0) && (time < times); time++) { + for (time = 0; (failed == 0) && (time < times); time++) + { int i; - for (i = 0; (failed == 0) && (i < l->lines); i++) { + for (i = 0; (failed == 0) && (i < l->lines); i++) + { char *m_output = 0; char *m_error = 0; getNextLineInfo info = {&i, l}; @@ -667,7 +754,8 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { status = mdsdcl_do_command_extra_args(cmd, 0, &m_error, &m_output, getNextLine, &info); free(cmd); - if (m_error) { + if (m_error) + { if ((*error) == NULL) *error = strdup(""); *error = strcat(realloc(*error, strlen(*error) + strlen(m_error) + 1), @@ -675,7 +763,8 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { free(m_error); m_error = 0; } - if (m_output) { + if (m_output) + { if ((*output) == NULL) *output = strdup(""); *output = @@ -688,7 +777,8 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { failed = 1; } } - if (indirect) { + if (indirect) + { int i; for (i = 0; i < l->lines; i++) free(l->cmds[i]); @@ -710,14 +800,17 @@ EXPORT int mdsdcl_do_macro(void *ctx, char **error, char **output) { } EXPORT int mdsdcl_delete_macro(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status = MdsdclSUCCESS; char *name = 0; int all = cli_present(ctx, "ALL"); cli_get_value(ctx, "name", &name); - if (all & 1) { + if (all & 1) + { dclMacroListPtr l; - for (l = MLIST, MLIST = 0; l;) { + for (l = MLIST, MLIST = 0; l;) + { int i; dclMacroListPtr next = l->next; free(l->name); @@ -727,13 +820,17 @@ EXPORT int mdsdcl_delete_macro(void *ctx, char **error, free(l); l = next; } - } else if (name) { + } + else if (name) + { dclMacroListPtr l, prev = 0; - for (l = MLIST; l; prev = l, l = l->next) { + for (l = MLIST; l; prev = l, l = l->next) + { if (strcasecmp(name, l->name) == 0) break; } - if (l) { + if (l) + { int i; free(l->name); for (i = 0; i < l->lines; i++) @@ -744,12 +841,16 @@ EXPORT int mdsdcl_delete_macro(void *ctx, char **error, else MLIST = l->next; free(l); - } else { + } + else + { *error = malloc(strlen(name) + 100); sprintf(*error, "Error: Macro not found - %s\n", name); status = MdsdclERROR; } - } else { + } + else + { *error = strdup("Error: Either specify macro name or use the /ALL qualifier.\n"); status = MdsdclERROR; @@ -760,7 +861,8 @@ EXPORT int mdsdcl_delete_macro(void *ctx, char **error, EXPORT int mdsdcl_set_stoponfail(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ if (cli_present(ctx, "ON") & 1) STOP_ON_FAIL = 1; else if (cli_present(ctx, "OFF") & 1) diff --git a/mdsdcl/mdsdcl_show_version.c b/mdsdcl/mdsdcl_show_version.c index 53c4966732..b995076a6b 100644 --- a/mdsdcl/mdsdcl_show_version.c +++ b/mdsdcl/mdsdcl_show_version.c @@ -16,7 +16,8 @@ extern const char *MdsRelease(); EXPORT int mdsdcl_show_version(void *ctx __attribute__((unused)), char **error __attribute__((unused)), - char **output) { + char **output) +{ char *info = *output = malloc(1024); info += sprintf(info, "\n\n"); info += sprintf(info, "MDSplus version: %d.%d.%d\n", MdsVersion.MAJOR, @@ -34,9 +35,10 @@ EXPORT int mdsdcl_show_version(void *ctx __attribute__((unused)), return 1; } -EXPORT int mdsdcl_show_git_info(void *ctx, char **error, char **output) { +EXPORT int mdsdcl_show_git_info(void *ctx, char **error, char **output) +{ int status; - int qfr[] = {cli_present(ctx, "TAG"), cli_present(ctx, "BRANCH"), + int qfr[] = {cli_present(ctx, "TAG"), cli_present(ctx, "BRANCH"), cli_present(ctx, "REMOTE"), cli_present(ctx, "REMOTE_URL"), cli_present(ctx, "COMMIT"), cli_present(ctx, "SRCDIR")}; @@ -55,7 +57,8 @@ EXPORT int mdsdcl_show_git_info(void *ctx, char **error, char **output) { strlen(MDSplusGitVersion.GIT_COMMIT) + strlen(MDSplusGitVersion.GIT_SRCDIR) + 1000); - if (s) { + if (s) + { if (qfr[0] == MdsdclPRESENT) info += sprintf(info, "%s ", MDSplusGitVersion.GIT_TAG); if (qfr[1] == MdsdclPRESENT) @@ -69,7 +72,9 @@ EXPORT int mdsdcl_show_git_info(void *ctx, char **error, char **output) { if (qfr[5] == MdsdclPRESENT) info += sprintf(info, "%s ", MDSplusGitVersion.GIT_SRCDIR); info += sprintf(info, "\n"); - } else { + } + else + { info += sprintf(info, "\n MDSplus code info:\n"); info += sprintf(info, "----------------------\n"); info += sprintf(info, " Tag: %s\n", MDSplusGitVersion.GIT_TAG); diff --git a/mdsdcl/mdsdclthreadstatic.h b/mdsdcl/mdsdclthreadstatic.h index e224fc4674..985fe93c5b 100644 --- a/mdsdcl/mdsdclthreadstatic.h +++ b/mdsdcl/mdsdclthreadstatic.h @@ -7,7 +7,8 @@ #define DCLTHREADSTATIC_ARG DCLTHREADSTATIC_TYPE *const DCLTHREADSTATIC_VAR #define DCLTHREADSTATIC(MTS) DCLTHREADSTATIC_ARG = DclGetThreadStatic(MTS) #define DCLTHREADSTATIC_INIT DCLTHREADSTATIC(NULL) -typedef struct { +typedef struct +{ char *prompt; char *def_file; dclDocListPtr docs; diff --git a/mdsdcl/yylex/outfiles b/mdsdcl/yylex/outfiles deleted file mode 100644 index 45b5187dd2..0000000000 --- a/mdsdcl/yylex/outfiles +++ /dev/null @@ -1 +0,0 @@ -mdsdcl/mdsdclDeltatimeToSeconds.c diff --git a/mdsdebug.c b/mdsdebug.c index 1f5042de81..988f723d4e 100644 --- a/mdsdebug.c +++ b/mdsdebug.c @@ -20,7 +20,8 @@ */ int status_ok(int status) { return ((status & 1) == 1); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int status; int shot = 3; @@ -34,7 +35,8 @@ int main(int argc, char *argv[]) { /* Open tree */ status = MdsOpen("cryocon18i", &shot); - if (!status_ok(status)) { + if (!status_ok(status)) + { printf("Error shot number %d\n", shot); fprintf(stderr, "Error shot number %d\n", shot); return -1; @@ -45,7 +47,8 @@ int main(int argc, char *argv[]) { /* status = MdsValue("TCL(\"set def cryo18i\",_output)", &idesc, &null, &len); */ status = MdsValue("TCL(\"set def cryo18i\",_output)", &idesc, &null, &len); - if (!status_ok(status)) { + if (!status_ok(status)) + { printf("Error with set def command.\n"); fprintf(stderr, "Error with set def command.\n"); return -1; @@ -53,9 +56,11 @@ int main(int argc, char *argv[]) { printf("Status of TCL(\"set def\") = %i\n", tstat); /* If the command was successful, print its output. */ - if (status_ok(tstat)) { + if (status_ok(tstat)) + { status = MdsValue("_output", &sdesc, &null, &len); - if (!status_ok(status)) { + if (!status_ok(status)) + { fprintf(stderr, "Error getting _output from set def command.\n"); return -1; } diff --git a/mdsdebugc.c b/mdsdebugc.c index 6697987202..61edbd28fb 100644 --- a/mdsdebugc.c +++ b/mdsdebugc.c @@ -22,7 +22,8 @@ */ int status_ok(int status) { return ((status & 1) == 1); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int status; int shot = 3; /*char const tree="cryocon18i"; @@ -37,7 +38,8 @@ int main(int argc, char *argv[]) { status = _TreeOpen(&dbid, "cryocon18i", shot, read_only); /*status = _TreeOpen(TreeCtx(), "cryocon18i", shot, read_only);*/ - if (!status_ok(status)) { + if (!status_ok(status)) + { printf("Error shot number %d\n", shot); fprintf(stderr, "Error shot number %d\n", shot); return -1; diff --git a/mdslib/MdsLib.c b/mdslib/MdsLib.c index cff8049177..974258e3a9 100644 --- a/mdslib/MdsLib.c +++ b/mdslib/MdsLib.c @@ -67,11 +67,14 @@ static void mds_value_set(struct descriptor *outdsc, struct descriptor *indsc, /* Key for the thread-specific buffer */ static pthread_key_t buffer_key; /* Free the thread-specific buffer */ -static void buffer_destroy(void *buf) { +static void buffer_destroy(void *buf) +{ int i; struct descriptor **d = (struct descriptor **)buf; - for (i = 0; i < NDESCRIP_CACHE; i++) { - if (d[i]) { + for (i = 0; i < NDESCRIP_CACHE; i++) + { + if (d[i]) + { if (d[i]->class == CLASS_XD) free_xd(d[i]); else if (d[i]->class == CLASS_D) @@ -81,21 +84,25 @@ static void buffer_destroy(void *buf) { } free(buf); } -static void buffer_key_alloc() { +static void buffer_key_alloc() +{ pthread_key_create(&buffer_key, buffer_destroy); } /* Return the thread-specific buffer */ -static struct descriptor **GetDescriptorCache() { +static struct descriptor **GetDescriptorCache() +{ RUN_FUNCTION_ONCE(buffer_key_alloc); void *buf = pthread_getspecific(buffer_key); - if (!buf) { + if (!buf) + { buf = calloc(NDESCRIP_CACHE, sizeof(struct descriptor *)); pthread_setspecific(buffer_key, buf); } return (struct descriptor **)buf; } -extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { +extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) +{ /* variable length argument list: * (# elements in dim 1), (# elements in dim 2) ... 0, [length of (each) @@ -106,7 +113,8 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { int totsize = *dim1; int retval; - if (data == NULL) { + if (data == NULL) + { printf("NULL pointer passed as data pointer\n"); return -1; } @@ -116,17 +124,23 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { /* decide what type of descriptor is needed (descriptor, descriptor_a, * array_coeff) */ - if (*dim1 == 0) { + if (*dim1 == 0) + { GetDescriptorCache()[next] = malloc(sizeof(struct descriptor)); - } else { + } + else + { va_list incrmtr; int *dim; va_start(incrmtr, dim1); dim = va_arg(incrmtr, int *); - if (*dim == 0) { + if (*dim == 0) + { GetDescriptorCache()[next] = malloc(sizeof(struct descriptor_a)); - } else { + } + else + { GetDescriptorCache()[next] = malloc(sizeof(array_coeff)); } } @@ -142,17 +156,22 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { * dtype_length(). */ - if (*dim1 == 0) { + if (*dim1 == 0) + { dsc->class = CLASS_S; - if (dsc->dtype == DTYPE_CSTRING) { /* && dsc->length == 0) */ + if (dsc->dtype == DTYPE_CSTRING) + { /* && dsc->length == 0) */ va_list incrmtr; va_start(incrmtr, dim1); dsc->length = *va_arg(incrmtr, int *); - } else + } + else dsc->length = dtype_length( dsc); /* must set length after dtype and data pointers are set */ - } else { + } + else + { va_list incrmtr; @@ -162,7 +181,8 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { /* count the number of dimensions beyond the first */ va_start(incrmtr, dim1); - for (ndim = 1; *dim != 0; ndim++) { + for (ndim = 1; *dim != 0; ndim++) + { dim = va_arg(incrmtr, int *); } ndim = ndim - 1; /* ndim is actually the number of dimensions specified */ @@ -178,12 +198,14 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { dsc->length = dtype_length( dsc); /* must set length after dtype and data pointers are set */ - if (ndim > 1) { + if (ndim > 1) + { int i; array_coeff *adsc = (array_coeff *)dsc; adsc->class = CLASS_A; - if (ndim > MAX_DIMS) { + if (ndim > MAX_DIMS) + { ndim = MAX_DIMS; printf("(descr.c) WARNING: requested ndim>MAX_DIMS, forcing to " "MAX_DIMS\n"); @@ -202,15 +224,19 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { adsc->m[0] = *dim1; va_start(incrmtr, dim1); - for (i = 1; i < ndim; i++) { + for (i = 1; i < ndim; i++) + { adsc->m[i] = *(va_arg(incrmtr, int *)); totsize = totsize * adsc->m[i]; } - for (i = ndim; i < MAX_DIMS; i++) { + for (i = ndim; i < MAX_DIMS; i++) + { adsc->m[i] = 0; } adsc->arsize = totsize * adsc->length; - } else { + } + else + { struct descriptor_a *adsc = (struct descriptor_a *)dsc; adsc->class = CLASS_A; adsc->arsize = totsize * adsc->length; @@ -234,7 +260,8 @@ extern EXPORT int descr(int *dtype, void *data, int *dim1, ...) { return retval; } -EXPORT int descr2(int *dtype, int *dim1, ...) { +EXPORT int descr2(int *dtype, int *dim1, ...) +{ /* variable length argument list: * (# elements in dim 1), (# elements in dim 2) ... 0, [length of (each) @@ -250,17 +277,23 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { /* decide what type of descriptor is needed (descriptor, descriptor_a, * array_coeff) */ - if (*dim1 == 0) { + if (*dim1 == 0) + { GetDescriptorCache()[next] = malloc(sizeof(struct descriptor)); - } else { + } + else + { va_list incrmtr; int *dim; va_start(incrmtr, dim1); dim = va_arg(incrmtr, int *); - if (*dim == 0) { + if (*dim == 0) + { GetDescriptorCache()[next] = malloc(sizeof(struct descriptor_a)); - } else { + } + else + { GetDescriptorCache()[next] = malloc(sizeof(array_coeff)); } } @@ -277,17 +310,22 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { * dtype_length(). */ - if (*dim1 == 0) { + if (*dim1 == 0) + { dsc->class = CLASS_S; - if (dsc->dtype == DTYPE_CSTRING) { + if (dsc->dtype == DTYPE_CSTRING) + { va_list incrmtr; va_start(incrmtr, dim1); dsc->length = *va_arg(incrmtr, int *); - } else + } + else dsc->length = dtype_length( dsc); /* must set length after dtype and data pointers are set */ - } else { + } + else + { va_list incrmtr; @@ -297,7 +335,8 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { /* count the number of dimensions beyond the first */ va_start(incrmtr, dim1); - for (ndim = 1; *dim != 0; ndim++) { + for (ndim = 1; *dim != 0; ndim++) + { dim = va_arg(incrmtr, int *); } ndim = ndim - 1; /* ndim is actually the number of dimensions specified */ @@ -313,12 +352,14 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { dsc->length = dtype_length( dsc); /* must set length after dtype and data pointers are set */ - if (ndim > 1) { + if (ndim > 1) + { int i; array_coeff *adsc = (array_coeff *)dsc; adsc->class = CLASS_A; - if (ndim > MAX_DIMS) { + if (ndim > MAX_DIMS) + { ndim = MAX_DIMS; printf("(descr.c) WARNING: requested ndim>MAX_DIMS, forcing to " "MAX_DIMS\n"); @@ -336,15 +377,19 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { adsc->m[0] = *dim1; va_start(incrmtr, dim1); - for (i = 1; i < ndim; i++) { + for (i = 1; i < ndim; i++) + { adsc->m[i] = *(va_arg(incrmtr, int *)); totsize = totsize * adsc->m[i]; } - for (i = ndim; i < MAX_DIMS; i++) { + for (i = ndim; i < MAX_DIMS; i++) + { adsc->m[i] = 0; } adsc->arsize = totsize * adsc->length; - } else { + } + else + { struct descriptor_a *adsc = (struct descriptor_a *)dsc; adsc->class = CLASS_A; adsc->arsize = totsize * adsc->length; @@ -366,8 +411,10 @@ EXPORT int descr2(int *dtype, int *dim1, ...) { return retval; } #ifndef _CLIENT_ONLY -static inline struct descriptor *fixDtypes(struct descriptor *dsc) { - switch (dsc->dtype) { +static inline struct descriptor *fixDtypes(struct descriptor *dsc) +{ + switch (dsc->dtype) + { case DTYPE_FLOAT: dsc->dtype = DTYPE_NATIVE_FLOAT; break; @@ -388,7 +435,8 @@ static inline struct descriptor *fixDtypes(struct descriptor *dsc) { #endif static inline int mds_value_vargs(va_list incrmtr, int connection, - char *expression, ...) { + char *expression, ...) +{ int a_count; int i; unsigned char nargs; @@ -404,21 +452,25 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, #endif va_copy(initial_incrmtr, incrmtr); - for (a_count = 0; *descnum != 0; a_count++) { + for (a_count = 0; *descnum != 0; a_count++) + { descnum = va_arg(incrmtr, int *); } a_count--; /* subtract one for terminator of argument list */ length = va_arg(incrmtr, int *); #ifdef OLD_FORTRAN_API - if (length && (*length != 1)) { + if (length && (*length != 1)) + { #else - if (length) { + if (length) + { #endif *length = 0; } - if (connection != -1) { /* CLIENT/SERVER */ + if (connection != -1) + { /* CLIENT/SERVER */ struct descriptor *dscAnswer; struct descrip exparg; struct descrip *arg = &exparg; @@ -446,20 +498,25 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, /* send each argument */ va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= nargs && (status & 1); i++) { + for (i = 1; i <= nargs && (status & 1); i++) + { descnum = va_arg(incrmtr, int *); - if (*descnum > 0) { + if (*descnum > 0) + { dsc = GetDescriptorCache()[*descnum - 1]; arg = make_mdsip_descrip(arg, dsc); status = SendArg(connection, (unsigned char)i, arg->dtype, (char)(nargs + 1), ArgLen(arg), arg->ndims, arg->dims, arg->ptr); - } else { + } + else + { printf("I: %d BAD DESCRIPTOR!!!\n", i); } } - if (status & 1) { + if (status & 1) + { int numbytes; short len; void *dptr; @@ -476,7 +533,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, ** present for client-only library. **/ - if (status & 1) { + if (status & 1) + { int ansdescr = 0; int dims[MAX_DIMS]; int null = 0; @@ -487,7 +545,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, dims[i] = (int)arg->dims[i]; if (arg->dtype == DTYPE_CSTRING && arg->ndims > 0 && - dlen != dscAnswer->length) { + dlen != dscAnswer->length) + { /** rewrite string array so that it gets copied to answer descriptor * dscAnswer correctly **/ int i; @@ -503,7 +562,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, dlen = dscAnswer->length; } - switch (arg->ndims) { + switch (arg->ndims) + { case 0: ansdescr = descr(&dtype, dptr, &null, &dlen); break; @@ -542,8 +602,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, } free(dnew); } - - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -563,7 +623,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, dexpression.pointer = (char *)expression; arglist[argidx++] = (void *)&dexpression; va_copy(incrmtr, initial_incrmtr); - for (i = 1; i < a_count; i++) { + for (i = 1; i < a_count; i++) + { descnum = va_arg(incrmtr, int *); dsc = fixDtypes(GetDescriptorCache()[*descnum - 1]); arglist[argidx++] = (void *)dsc; @@ -573,14 +634,16 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, *(int *)&arglist[0] = argidx - 1; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) { + if (status & 1) + { descnum = va_arg(incrmtr, int *); dsc = fixDtypes(GetDescriptorCache()[*descnum - 1]); status = TdiData(xd1.pointer, &xd2 MDS_END_ARG); - if (status & 1 && xd2.pointer != 0 && xd2.pointer->pointer != 0) { + if (status & 1 && xd2.pointer != 0 && xd2.pointer->pointer != 0) + { int templen = (xd2.pointer)->length; status = TdiCvt(&xd2, dsc, &xd3 MDS_END_ARG); /** get string length right if scalar string (if answer descriptor has @@ -594,7 +657,8 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, (xd3.pointer)->length = MIN(templen, (xd3.pointer)->length); } - if (status & 1) { + if (status & 1) + { mds_value_set(dsc, xd3.pointer, length); MdsFree1Dx(&xd1, NULL); @@ -610,20 +674,23 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, return (status); } -EXPORT int MdsValueR(int *connection, char *expression, ...) { +EXPORT int MdsValueR(int *connection, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_value_vargs(incrmtr, *connection, expression); } -EXPORT int MdsValue(char *expression, ...) { +EXPORT int MdsValue(char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_value_vargs(incrmtr, MdsCONNECTION, expression); } static inline int mds_value2_vargs(va_list incrmtr, int connection, - char *expression, ...) { + char *expression, ...) +{ va_list initial_incrmtr; int a_count; int i; @@ -633,7 +700,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, int status = 1; int *descnum = &status; /* initialize to point at non zero value */ va_copy(initial_incrmtr, incrmtr); - for (a_count = 0; *descnum != 0; a_count++) { + for (a_count = 0; *descnum != 0; a_count++) + { descnum = va_arg(incrmtr, int *); if (*descnum != 0) va_arg(incrmtr, void *); @@ -642,14 +710,17 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, length = va_arg(incrmtr, int *); #ifdef OLD_FORTRAN_API - if (length && (*length != 1)) { + if (length && (*length != 1)) + { #else - if (length) { + if (length) + { #endif *length = 0; } - if (MdsCONNECTION != -1) { /* CLIENT/SERVER */ + if (MdsCONNECTION != -1) + { /* CLIENT/SERVER */ struct descriptor *dscAnswer; struct descrip exparg; struct descrip *arg = &exparg; @@ -679,21 +750,26 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, /* send each argument */ va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= nargs && (status & 1); i++) { + for (i = 1; i <= nargs && (status & 1); i++) + { descnum = va_arg(incrmtr, int *); - if (*descnum > 0) { + if (*descnum > 0) + { dsc = GetDescriptorCache()[*descnum - 1]; dsc->pointer = va_arg(incrmtr, void *); arg = make_mdsip_descrip(arg, dsc); status = SendArg(connection, (unsigned char)i, arg->dtype, (char)(nargs + 1), ArgLen(arg), arg->ndims, arg->dims, arg->ptr); - } else { + } + else + { printf("I: %d BAD DESCRIPTOR!!!\n", i); } } - if (status & 1) { + if (status & 1) + { int numbytes; short len; void *dptr; @@ -710,7 +786,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, ** present for client-only library. **/ - if (status & 1) { + if (status & 1) + { int ansdescr = 0; int dims[MAX_DIMS]; int null = 0; @@ -721,7 +798,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, dims[i] = (int)arg->dims[i]; if (arg->dtype == DTYPE_CSTRING && arg->ndims > 0 && - dlen != dscAnswer->length) { + dlen != dscAnswer->length) + { /** rewrite string array so that it gets copied to answer descriptor * dscAnswer correctly **/ int i; @@ -737,7 +815,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, dlen = dscAnswer->length; } - switch (arg->ndims) { + switch (arg->ndims) + { case 0: ansdescr = descr(&dtype, dptr, &null, &dlen); break; @@ -776,8 +855,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, } free(dnew); } - - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -797,7 +876,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, dexpression.pointer = (char *)expression; arglist[argidx++] = (void *)&dexpression; va_copy(incrmtr, initial_incrmtr); - for (i = 1; i < a_count; i++) { + for (i = 1; i < a_count; i++) + { descnum = va_arg(incrmtr, int *); dsc = fixDtypes(GetDescriptorCache()[*descnum - 1]); dsc->pointer = va_arg(incrmtr, void *); @@ -808,7 +888,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, *(int *)&arglist[0] = argidx - 1; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) { + if (status & 1) + { descnum = va_arg(incrmtr, int *); dsc = GetDescriptorCache()[*descnum - 1]; @@ -816,7 +897,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, status = TdiData(xd1.pointer, &xd2 MDS_END_ARG); - if (status & 1 && xd2.pointer) { + if (status & 1 && xd2.pointer) + { int templen = (xd2.pointer)->length; status = TdiCvt(&xd2, dsc, &xd3 MDS_END_ARG); /** get string length right if scalar string (if answer descriptor has @@ -830,7 +912,8 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, (xd3.pointer)->length = MIN(templen, (xd3.pointer)->length); } - if (status & 1) { + if (status & 1) + { mds_value_set(dsc, xd3.pointer, length); MdsFree1Dx(&xd1, NULL); @@ -844,20 +927,23 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, return (status); } -EXPORT int MdsValue2R(int *connection, char *expression, ...) { +EXPORT int MdsValue2R(int *connection, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_value2_vargs(incrmtr, *connection, expression); } -EXPORT int MdsValue2(char *expression, ...) { +EXPORT int MdsValue2(char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_value2_vargs(incrmtr, MdsCONNECTION, expression); } static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, - char *expression, ...) { + char *expression, ...) +{ va_list initial_incrmtr; int a_count; int i; @@ -867,12 +953,14 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, int status = 1; int *descnum = &status; /* initialize to point at non zero value */ va_copy(initial_incrmtr, incrmtr); - for (a_count = 0; *descnum != 0; a_count++) { + for (a_count = 0; *descnum != 0; a_count++) + { descnum = va_arg(incrmtr, int *); } a_count--; /* subtract one for terminator of argument list */ - if (connection != -1) { /* CLIENT/SERVER */ + if (connection != -1) + { /* CLIENT/SERVER */ static char *putexpprefix = "TreePut("; static char *argplace = "$,"; char *putexp; @@ -898,17 +986,20 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, status = SendArg(connection, idx++, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); arg = MakeDescrip(&exparg, DTYPE_CSTRING, 0, 0, expression); - for (i = idx; i < nargs && (status & 1); i++) { + for (i = idx; i < nargs && (status & 1); i++) + { status = SendArg(connection, (char)i, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); descnum = va_arg(incrmtr, int *); - if (*descnum > 0) { + if (*descnum > 0) + { dsc = GetDescriptorCache()[*descnum - 1]; arg = make_mdsip_descrip(arg, dsc); } } - if (status & 1) { + if (status & 1) + { char dtype; int dims[MAX_DIMS]; char ndims; @@ -921,7 +1012,8 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, numbytes == sizeof(int)) memcpy(&status, dptr, numbytes); } - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -938,12 +1030,14 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, int i; int nid; - if ((status = TreeFindNode(pathname, &nid)) & 1) { + if ((status = TreeFindNode(pathname, &nid)) & 1) + { dexpression.length = strlen((char *)expression); dexpression.pointer = (char *)expression; arglist[argidx++] = (void *)&dexpression; va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= a_count; i++) { + for (i = 1; i <= a_count; i++) + { descnum = va_arg(incrmtr, int *); dsc = fixDtypes(GetDescriptorCache()[*descnum - 1]); arglist[argidx++] = (void *)dsc; @@ -954,10 +1048,12 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) { + if (status & 1) + { if ((status = TreePutRecord( nid, (struct descriptor *)arglist[argidx - 2], 0)) & - 1) { + 1) + { TreeWait(); } } @@ -968,20 +1064,23 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, return (status); } -EXPORT int MdsPutR(int *connection, char *node, char *expression, ...) { +EXPORT int MdsPutR(int *connection, char *node, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_put_vargs(incrmtr, *connection, node, expression); } -EXPORT int MdsPut(char *node, char *expression, ...) { +EXPORT int MdsPut(char *node, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_put_vargs(incrmtr, MdsCONNECTION, node, expression); } static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, - char *expression, ...) { + char *expression, ...) +{ va_list initial_incrmtr; int a_count; int i; @@ -992,13 +1091,15 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, int *descnum = &status; /* initialize to point at non zero value */ va_copy(initial_incrmtr, incrmtr); - for (a_count = 0; *descnum != 0; a_count++) { + for (a_count = 0; *descnum != 0; a_count++) + { descnum = va_arg(incrmtr, int *); va_arg(incrmtr, void *); } a_count--; /* subtract one for terminator of argument list */ - if (MdsCONNECTION != -1) { /* CLIENT/SERVER */ + if (MdsCONNECTION != -1) + { /* CLIENT/SERVER */ static char *putexpprefix = "TreePut("; static char *argplace = "$,"; char *putexp; @@ -1024,18 +1125,21 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, status = SendArg(connection, idx++, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); arg = MakeDescrip(&exparg, DTYPE_CSTRING, 0, 0, expression); - for (i = idx; i < nargs && (status & 1); i++) { + for (i = idx; i < nargs && (status & 1); i++) + { status = SendArg(connection, (char)i, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); descnum = va_arg(incrmtr, int *); - if (*descnum > 0) { + if (*descnum > 0) + { dsc = GetDescriptorCache()[*descnum - 1]; dsc->pointer = va_arg(incrmtr, void *); arg = make_mdsip_descrip(arg, dsc); } } - if (status & 1) { + if (status & 1) + { char dtype; int dims[MAX_DIMS]; char ndims; @@ -1048,7 +1152,8 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, numbytes == sizeof(int)) memcpy(&status, dptr, numbytes); } - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -1065,12 +1170,14 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, int i; int nid; - if ((status = TreeFindNode(pathname, &nid)) & 1) { + if ((status = TreeFindNode(pathname, &nid)) & 1) + { dexpression.length = strlen((char *)expression); dexpression.pointer = (char *)expression; arglist[argidx++] = (void *)&dexpression; va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= a_count; i++) { + for (i = 1; i <= a_count; i++) + { descnum = va_arg(incrmtr, int *); dsc = fixDtypes(GetDescriptorCache()[*descnum - 1]); dsc->pointer = va_arg(incrmtr, void *); @@ -1082,11 +1189,13 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) { + if (status & 1) + { if ((status = TreePutRecord(nid, (struct descriptor *)arglist[argidx - 2]), 0) & - 1) { + 1) + { TreeWait(); } } @@ -1097,19 +1206,22 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, return (status); } -EXPORT int MdsPut2R(int *connection, char *node, char *expression, ...) { +EXPORT int MdsPut2R(int *connection, char *node, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_put2_vargs(incrmtr, *connection, node, expression); } -EXPORT int MdsPut2(char *node, char *expression, ...) { +EXPORT int MdsPut2(char *node, char *expression, ...) +{ va_list incrmtr; va_start(incrmtr, expression); return mds_put2_vargs(incrmtr, MdsCONNECTION, node, expression); } -static int dtype_length(struct descriptor *d) { +static int dtype_length(struct descriptor *d) +{ short len; /* This function needs to handle the DTYPE values in ipdesc.h as well @@ -1118,7 +1230,8 @@ static int dtype_length(struct descriptor *d) { * be returned with native DTYPE. */ - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_UCHAR: case DTYPE_CHAR: len = sizeof(char); @@ -1170,9 +1283,13 @@ static int dtype_length(struct descriptor *d) { } #ifdef _CLIENT_ONLY -extern EXPORT int *cdescr() { return NULL; } +extern EXPORT int *cdescr() +{ + return NULL; +} #else -extern EXPORT int *cdescr(int dtype, void *data, ...) { +extern EXPORT int *cdescr(int dtype, void *data, ...) +{ void *arglist[MAXARGS]; va_list incrmtr; int dsc; @@ -1184,12 +1301,14 @@ extern EXPORT int *cdescr(int dtype, void *data, ...) { va_start(incrmtr, data); dsc = 1; /* initialize ok */ - for (; dsc != 0;) { + for (; dsc != 0;) + { dsc = va_arg(incrmtr, int); arglist[argidx++] = (void *)&dsc; } - if (dtype == DTYPE_CSTRING) { + if (dtype == DTYPE_CSTRING) + { dsc = va_arg(incrmtr, int); arglist[argidx++] = (void *)&dsc; } @@ -1201,12 +1320,14 @@ extern EXPORT int *cdescr(int dtype, void *data, ...) { #endif static struct descrip *make_mdsip_descrip(struct descrip *arg, - struct descriptor *dsc) { + struct descriptor *dsc) +{ char dtype; dtype = dsc->dtype; - switch (dtype) { + switch (dtype) + { default: break; case DTYPE_NATIVE_FLOAT: @@ -1223,13 +1344,16 @@ static struct descrip *make_mdsip_descrip(struct descrip *arg, break; } - if (dsc->class == CLASS_S) { + if (dsc->class == CLASS_S) + { if (dsc->length) arg = MakeDescripWithLength(arg, (char)dtype, (int)dsc->length, (char)0, (int *)0, dsc->pointer); else arg = MakeDescrip(arg, (char)dtype, (char)0, (int *)0, dsc->pointer); - } else { + } + else + { int i; array_coeff *adsc = (array_coeff *)dsc; int dims[MAX_DIMS]; @@ -1250,9 +1374,11 @@ static struct descrip *make_mdsip_descrip(struct descrip *arg, return arg; } -static int mds_value_length(struct descriptor *dsc) { +static int mds_value_length(struct descriptor *dsc) +{ int length; - switch (dsc->class) { + switch (dsc->class) + { case CLASS_S: case CLASS_D: length = dsc->length; @@ -1268,7 +1394,8 @@ static int mds_value_length(struct descriptor *dsc) { } static char *mds_value_remote_expression(char *expression, - struct descriptor *dsc) { + struct descriptor *dsc) +{ /* This function will wrap expression in the appropriate type * conversion function to ensure that the return value of MdsValue @@ -1284,7 +1411,8 @@ static char *mds_value_remote_expression(char *expression, * conversion steps. */ - switch (DTYPE_NATIVE_FLOAT) { + switch (DTYPE_NATIVE_FLOAT) + { default: // printf("Unknown DTYPE_NATIVE_FLOAT: %d. Using FS_FLOAT.\n", // DTYPE_NATIVE_FLOAT); @@ -1298,7 +1426,8 @@ static char *mds_value_remote_expression(char *expression, break; } - switch (DTYPE_NATIVE_DOUBLE) { + switch (DTYPE_NATIVE_DOUBLE) + { default: // printf("Unknown DTYPE_NATIVE_DOUBLE: %d. Using FT_FLOAT.\n", // DTYPE_NATIVE_DOUBLE); @@ -1321,7 +1450,8 @@ static char *mds_value_remote_expression(char *expression, * NATIVE_FLOAT etc. */ - switch ((int)dsc->dtype) { + switch ((int)dsc->dtype) + { case DTYPE_UCHAR: strcpy(newexpression, "BYTE_UNSIGNED"); break; @@ -1370,26 +1500,31 @@ static char *mds_value_remote_expression(char *expression, } static void mds_value_move(int source_length, char *source_array, char fill, - int dest_length, char *dest_array) { + int dest_length, char *dest_array) +{ int i; if (!source_array) return; memcpy(dest_array, source_array, MIN(source_length, dest_length)); - for (i = 0; i < dest_length - source_length; i++) { + for (i = 0; i < dest_length - source_length; i++) + { dest_array[source_length + i] = fill; } } static void mds_value_copy(int dim, int length, char fill, char *in, - unsigned int *in_m, char *out, unsigned int *out_m) { + unsigned int *in_m, char *out, unsigned int *out_m) +{ unsigned int i; int j; if (dim == 1) mds_value_move(length * in_m[0], in, fill, length * out_m[0], out); - else { + else + { int in_increment = length; int out_increment = length; - for (j = 0; j < dim - 1; j++) { + for (j = 0; j < dim - 1; j++) + { in_increment *= in_m[j]; out_increment *= out_m[j]; } @@ -1400,13 +1535,17 @@ static void mds_value_copy(int dim, int length, char fill, char *in, } static void mds_value_set(struct descriptor *outdsc, struct descriptor *indsc, - int *length) { + int *length) +{ char fill; - if (indsc == 0) { + if (indsc == 0) + { #ifdef OLD_FORTRAN_API - if (length && (*length != 1)) { + if (length && (*length != 1)) + { #else - if (length) { + if (length) + { #endif *length = 0; } @@ -1416,29 +1555,38 @@ static void mds_value_set(struct descriptor *outdsc, struct descriptor *indsc, if ((indsc->class == CLASS_A) && (outdsc->class == CLASS_A) && (((struct descriptor_a *)outdsc)->dimct > 1) && (((struct descriptor_a *)outdsc)->dimct == - ((struct descriptor_a *)indsc)->dimct)) { + ((struct descriptor_a *)indsc)->dimct)) + { array_coeff *in_a = (array_coeff *)indsc; array_coeff *out_a = (array_coeff *)outdsc; mds_value_move(0, 0, fill, mds_value_length(outdsc), out_a->pointer); mds_value_copy(out_a->dimct, in_a->length, fill, in_a->pointer, in_a->m, out_a->pointer, out_a->m); - } else { + } + else + { mds_value_move(mds_value_length(indsc), indsc->pointer, fill, mds_value_length(outdsc), outdsc->pointer); } #ifdef OLD_FORTRAN_API - if (length && (*length != 1)) { + if (length && (*length != 1)) + { #else - if (length) { + if (length) + { #endif if (indsc->class == CLASS_A) *length = MIN(((struct descriptor_a *)outdsc)->arsize / outdsc->length, ((struct descriptor_a *)indsc)->arsize / indsc->length); - else { - if (indsc->dtype == DTYPE_CSTRING) { + else + { + if (indsc->dtype == DTYPE_CSTRING) + { *length = MIN(outdsc->length, indsc->length); - } else { + } + else + { *length = MIN(outdsc->length / dtype_length(outdsc), indsc->length / dtype_length(indsc)); } @@ -1446,9 +1594,11 @@ static void mds_value_set(struct descriptor *outdsc, struct descriptor *indsc, } } -EXPORT int MdsOpenR(int *connection, char *tree, int *shot) { +EXPORT int MdsOpenR(int *connection, char *tree, int *shot) +{ int status = 0; - if (*connection != -1) { + if (*connection != -1) + { long answer; int length; @@ -1465,11 +1615,14 @@ EXPORT int MdsOpenR(int *connection, char *tree, int *shot) { d3 = descr(&dtype_long, &answer, &null); status = MdsValueR(connection, expression, &d1, &d2, &d3, &null, &length); - if ((status & 1)) { + if ((status & 1)) + { return *(int *)&answer; - } else + } + else return 0; - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -1483,19 +1636,23 @@ EXPORT int MdsOpenR(int *connection, char *tree, int *shot) { return status; } -EXPORT int MdsOpen(char *tree, int *shot) { +EXPORT int MdsOpen(char *tree, int *shot) +{ return MdsOpenR(&MdsCONNECTION, tree, shot); } -extern EXPORT int MdsSetSocket(int *newsocket) { +extern EXPORT int MdsSetSocket(int *newsocket) +{ int oldsocket = MdsCONNECTION; MdsCONNECTION = *newsocket; return oldsocket; } -extern EXPORT int MdsCloseR(int *connection, char *tree, int *shot) { +extern EXPORT int MdsCloseR(int *connection, char *tree, int *shot) +{ int status = 0; - if (*connection != -1) { + if (*connection != -1) + { long answer; int length; @@ -1513,11 +1670,14 @@ extern EXPORT int MdsCloseR(int *connection, char *tree, int *shot) { status = MdsValueR(connection, expression, &d1, &d2, &d3, &null, &length); - if ((status & 1)) { + if ((status & 1)) + { return *(int *)&answer; - } else + } + else return 0; - } else + } + else #ifdef _CLIENT_ONLY { printf("Must ConnectToMds first\n"); @@ -1531,14 +1691,17 @@ extern EXPORT int MdsCloseR(int *connection, char *tree, int *shot) { return status; } -EXPORT int MdsClose(char *tree, int *shot) { +EXPORT int MdsClose(char *tree, int *shot) +{ return MdsCloseR(&MdsCONNECTION, tree, shot); } -EXPORT int MdsSetDefaultR(int *connection, char *node) { +EXPORT int MdsSetDefaultR(int *connection, char *node) +{ int status; - if (*connection != -1) { + if (*connection != -1) + { char *expression = strcpy((char *)malloc(strlen(node) + 20), "TreeSetDefault('"); long answer; @@ -1552,9 +1715,11 @@ EXPORT int MdsSetDefaultR(int *connection, char *node) { strcat(expression, "')"); status = MdsValueR(connection, expression, &d1, &null, &length); free(expression); - if ((status & 1)) { + if ((status & 1)) + { return *(int *)&answer; - } else + } + else return 0; } @@ -1575,23 +1740,28 @@ EXPORT int MdsSetDefaultR(int *connection, char *node) { return status; } -EXPORT int MdsSetDefault(char *node) { +EXPORT int MdsSetDefault(char *node) +{ return MdsSetDefaultR(&MdsCONNECTION, node); } EXPORT void MdsDisconnectR(int *connection) { DisconnectFromMds(*connection); } -EXPORT void MdsDisconnect() { +EXPORT void MdsDisconnect() +{ MdsDisconnectR(&MdsCONNECTION); MdsCONNECTION = -1; } -EXPORT int MdsConnectR(char *host) { +EXPORT int MdsConnectR(char *host) +{ return ConnectToMds(host); /*** SETS GLOBAL VARIABLE mdsSOCKET ***/ } -EXPORT int MdsConnect(char *host) { - if (MdsCONNECTION != -1) { +EXPORT int MdsConnect(char *host) +{ + if (MdsCONNECTION != -1) + { MdsDisconnect(); } MdsCONNECTION = MdsConnectR(host); diff --git a/mdslib/fortran_aliases_mac.h b/mdslib/fortran_aliases_mac.h index c97f76910f..6420a415b6 100644 --- a/mdslib/fortran_aliases_mac.h +++ b/mdslib/fortran_aliases_mac.h @@ -1,11 +1,13 @@ EXPORT int descr_(int *dtype, void *data, int *dim1, int *dim2, int *dim3, int *dim4, int *dim5, int *dim6, int *dim7, int *dim8, - int *dim9) { + int *dim9) +{ return descr(dtype, data, dim1, dim2, dim3, dim4, dim5, dim6, dim7, dim8, dim9); } EXPORT int descr2_(int *dtype, int *dim1, int *dim2, int *dim3, int *dim4, - int *dim5, int *dim6, int *dim7, int *dim8, int *dim9) { + int *dim5, int *dim6, int *dim7, int *dim8, int *dim9) +{ return descr2(dtype, dim1, dim2, dim3, dim4, dim5, dim6, dim7, dim8, dim9); } EXPORT int mdsconnect_(char *host) { return MdsConnect(host); } @@ -29,7 +31,8 @@ mdsput_(char *node, char *expression, int *a00, int *a01, int *a02, int *a03, int *a74, int *a75, int *a76, int *a77, int *a78, int *a79, int *a80, int *a81, int *a82, int *a83, int *a84, int *a85, int *a86, int *a87, int *a88, int *a89, int *a90, int *a91, int *a92, int *a93, int *a94, - int *a95, int *a96, int *a97, int *a98, int *a99) { + int *a95, int *a96, int *a97, int *a98, int *a99) +{ return MdsPut( node, expression, a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, @@ -54,7 +57,8 @@ mdsvalue_(char *expression, int *a00, int *a01, int *a02, int *a03, int *a04, int *a75, int *a76, int *a77, int *a78, int *a79, int *a80, int *a81, int *a82, int *a83, int *a84, int *a85, int *a86, int *a87, int *a88, int *a89, int *a90, int *a91, int *a92, int *a93, int *a94, int *a95, - int *a96, int *a97, int *a98, int *a99) { + int *a96, int *a97, int *a98, int *a99) +{ return MdsValue( expression, a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, @@ -80,7 +84,8 @@ mdsput2_(char *node, char *expression, int *a00, int *a01, int *a02, int *a03, int *a74, int *a75, int *a76, int *a77, int *a78, int *a79, int *a80, int *a81, int *a82, int *a83, int *a84, int *a85, int *a86, int *a87, int *a88, int *a89, int *a90, int *a91, int *a92, int *a93, int *a94, - int *a95, int *a96, int *a97, int *a98, int *a99) { + int *a95, int *a96, int *a97, int *a98, int *a99) +{ return MdsPut2( node, expression, a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, @@ -106,7 +111,8 @@ mdsvalue2_(char *expression, int *a00, int *a01, int *a02, int *a03, int *a04, int *a75, int *a76, int *a77, int *a78, int *a79, int *a80, int *a81, int *a82, int *a83, int *a84, int *a85, int *a86, int *a87, int *a88, int *a89, int *a90, int *a91, int *a92, int *a93, int *a94, int *a95, - int *a96, int *a97, int *a98, int *a99) { + int *a96, int *a97, int *a98, int *a99) +{ return MdsValue2( expression, a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, diff --git a/mdslib/testing/dtype_test.c b/mdslib/testing/dtype_test.c index bb7eb214ba..e82427c0b9 100644 --- a/mdslib/testing/dtype_test.c +++ b/mdslib/testing/dtype_test.c @@ -37,7 +37,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define CSTRING_TEST1 "THIS IS A TEST" int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ long status; int dsc; diff --git a/mdslib/testing/mdslib_ctest.c b/mdslib/testing/mdslib_ctest.c index 2d35a396fa..8a06ae1578 100644 --- a/mdslib/testing/mdslib_ctest.c +++ b/mdslib/testing/mdslib_ctest.c @@ -49,24 +49,30 @@ int dtype_cstring = DTYPE_CSTRING; #define TEST(test) \ { \ int s = test; \ - if ((s & 1) == 0) { \ + if ((s & 1) == 0) \ + { \ fprintf(stderr, "%s:%d : " #test " = %d => ERROR\n", __FILE__, __LINE__, \ s); \ exit(1); \ } \ } -int testOpen(char *tree, int shot) { return MdsOpen(tree, &shot); } +int testOpen(char *tree, int shot) +{ + return MdsOpen(tree, &shot); +} int testClose(char *tree, int shot) { return MdsClose(tree, &shot); } -int testScalarString(char *expression, char *expected) { +int testScalarString(char *expression, char *expected) +{ int length = strlen(expected); int lenalloc = length + 32; char *string = calloc(lenalloc, 1); int dsc = descr(&dtype_cstring, string, &null, &lenalloc); returnlength = 0; status = MdsValue(expression, &dsc, &null, &returnlength); - if (status & 1) { + if (status & 1) + { fprintf(stderr, "testScalarString(%.*s -- %s %d)\n", returnlength, string, expected, returnlength); status = (returnlength == length) && (strncmp(string, expected, length) == 0); @@ -77,7 +83,8 @@ int testScalarString(char *expression, char *expected) { int testSetDefault(char *node) { return (MdsSetDefault(node)); } -int testNull(char *expression) { +int testNull(char *expression) +{ char *buf = malloc(BUFFLEN); int bufflen = BUFFLEN; int dsc = descr(&dtype_cstring, buf, &null, &bufflen); @@ -85,11 +92,13 @@ int testNull(char *expression) { return ((status & 1) == 0 && (returnlength == 0)); } -int testPut1Dsc(char *node, char *expression, int dsc) { +int testPut1Dsc(char *node, char *expression, int dsc) +{ return (MdsPut(node, expression, &dsc, &null)); } -int testPut2Dsc(char *node, char *expression, int dsc1, int dsc2) { +int testPut2Dsc(char *node, char *expression, int dsc1, int dsc2) +{ return (MdsPut(node, expression, &dsc1, &dsc2, &null)); } @@ -97,7 +106,8 @@ int testClearNode(char *node) { return (MdsPut(node, "", &null)); } /******** MAJOR TEST SECTIONS ********/ -void TestTreeOpenClose() { +void TestTreeOpenClose() +{ TEST(testOpen(TREE, SHOT)); TEST(testOpen("FOOFOOFOO", 0xDEAD) ^ 1); TEST(testClose("FOOFOOFOO", 0xDEAD) == TreeNOT_OPEN); @@ -108,7 +118,8 @@ void TestTreeOpenClose() { TEST(testNull("$EXPT")); } -void TestTdi() { +void TestTdi() +{ int status; float result[10], result1; int dsc, dsc1, dsc2, i; @@ -127,7 +138,8 @@ void TestTdi() { dsc = descr(&dtype_float, result, &sresult, &null); status = MdsValue("2. : 20. : 2.", &dsc, &null, &returnlength); status = (status && (returnlength == 10)); - if (status & 1) { + if (status & 1) + { for (i = 0; i < returnlength; i++) status = status && (result[i] == 2. * (i + 1)); } @@ -146,7 +158,8 @@ void TestTdi() { TEST(testScalarString("MACHINE()", machine)); } -void TestArray1D() { +void TestArray1D() +{ int i; int dsc; int size = 100; @@ -162,9 +175,11 @@ void TestArray1D() { dsc = descr(&dtype_float, compare, &size, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) { + if (status & 1) + { status = (returnlength == size); - if (status & 1) { + if (status & 1) + { int i; for (i = 0; i < size; i++) status = status && (array[i] == compare[i]); @@ -178,7 +193,8 @@ void TestArray1D() { free(compare); } -void TestArray2D() { +void TestArray2D() +{ int dsc; int sx = 2; int sy = 13; @@ -190,12 +206,14 @@ void TestArray2D() { {0., 31., 29., 31., 30., 31., 30., 31., 31., 30., 31., 30., 31.}}; float compare[2][13]; float compareBigger[4][20]; - for (i = 0; i < sx; i++) { + for (i = 0; i < sx; i++) + { int j; for (j = 0; j < sy; j++) compare[i][j] = 0; } - for (i = 0; i < sxx; i++) { + for (i = 0; i < sxx; i++) + { int j; for (j = 0; j < syy; j++) compareBigger[i][j] = 0; @@ -208,13 +226,17 @@ void TestArray2D() { dsc = descr(&dtype_float, compare, &sx, &sy, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) { + if (status & 1) + { status = (returnlength == sx * sy); - if (status & 1) { + if (status & 1) + { int i; - for (i = 0; i < sx; i++) { + for (i = 0; i < sx; i++) + { int j; - for (j = 0; j < sy; j++) { + for (j = 0; j < sy; j++) + { status = status && (array[i][j] == compare[i][j]); } } @@ -223,13 +245,17 @@ void TestArray2D() { TEST(status); dsc = descr(&dtype_float, compareBigger, &sxx, &syy, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) { + if (status & 1) + { status = (returnlength == sx * sy); - if (status & 1) { + if (status & 1) + { int i; - for (i = 0; i < sx; i++) { + for (i = 0; i < sx; i++) + { int j; - for (j = 0; j < sy; j++) { + for (j = 0; j < sy; j++) + { status = status && (array[i][j] == compare[i][j]); } } @@ -240,13 +266,15 @@ void TestArray2D() { TEST(testClearNode("\\TOP:A")); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ (void)argv; int returnlength = 0; int status = 0; int dsc = descr(&dtype_long, &status, &null); TEST(MdsValue("setenv('test_path=.')", &dsc, &null, &returnlength)); - if (argc > 1) { + if (argc > 1) + { SOCKET socket; printf("Connecting to: local://0\n"); socket = MdsConnect("local://0"); diff --git a/mdslib/visual_basic_api.h b/mdslib/visual_basic_api.h index a78b802cc8..c8daee6140 100644 --- a/mdslib/visual_basic_api.h +++ b/mdslib/visual_basic_api.h @@ -3,130 +3,162 @@ EXPORT int __stdcall MdsConnectVB(char *host) { return MdsConnect(host); } EXPORT void __stdcall MdsDisconnectVB() { MdsDisconnect(); } -EXPORT int __stdcall MdsCloseVB(char *tree, int *shot) { +EXPORT int __stdcall MdsCloseVB(char *tree, int *shot) +{ return MdsClose(tree, shot); } -EXPORT int __stdcall MdsSetSocketVB(int *newsocket) { +EXPORT int __stdcall MdsSetSocketVB(int *newsocket) +{ return MdsSetSocket(newsocket); } -EXPORT int __stdcall WINAPI MdsSetDefaultVB(char *node) { +EXPORT int __stdcall WINAPI MdsSetDefaultVB(char *node) +{ return MdsSetDefault(node); } -EXPORT int __stdcall MdsOpenVB(char *tree, int *shot) { +EXPORT int __stdcall MdsOpenVB(char *tree, int *shot) +{ return MdsOpen(tree, shot); } -EXPORT int __stdcall descr1VB(int *dtype, void *value) { - if (*dtype == DTYPE_CSTRING) { +EXPORT int __stdcall descr1VB(int *dtype, void *value) +{ + if (*dtype == DTYPE_CSTRING) + { int len = strlen(value); return descr(dtype, value, (int *)&zero, &len); - } else + } + else return descr(dtype, value, (int *)&zero); } -EXPORT int __stdcall descr1VB2(int *dtype, int *len) { +EXPORT int __stdcall descr1VB2(int *dtype, int *len) +{ return (descr2(dtype, (int *)&zero, len)); } -EXPORT int __stdcall descr2VB(int *dtype, int *num, void *value) { - if (*dtype == DTYPE_CSTRING) { +EXPORT int __stdcall descr2VB(int *dtype, int *num, void *value) +{ + if (*dtype == DTYPE_CSTRING) + { int len = strlen(value); return descr(dtype, value, num, (int *)&zero, &len); - } else + } + else return descr(dtype, value, num, (int *)&zero); } -EXPORT int __stdcall descr2VB2(int *dtype, int *num, int *len) { +EXPORT int __stdcall descr2VB2(int *dtype, int *num, int *len) +{ return (descr2(dtype, num, (int *)&zero, len)); } -EXPORT int __stdcall descr3VB(int *dtype, int *n1, int *n2, void *value) { - if (*dtype == DTYPE_CSTRING) { +EXPORT int __stdcall descr3VB(int *dtype, int *n1, int *n2, void *value) +{ + if (*dtype == DTYPE_CSTRING) + { int len = strlen(value); return descr(dtype, value, n1, n2, (int *)&zero, &len); - } else + } + else return descr(dtype, value, n1, n2, (int *)&zero); } -EXPORT int __stdcall descr3VB2(int *dtype, int *n1, int *n2, int *len) { +EXPORT int __stdcall descr3VB2(int *dtype, int *n1, int *n2, int *len) +{ return (descr2(dtype, n1, n2, (int *)&zero, len)); } EXPORT int __stdcall descr4VB(int *dtype, int *n1, int *n2, int *n3, - void *value) { - if (*dtype == DTYPE_CSTRING) { + void *value) +{ + if (*dtype == DTYPE_CSTRING) + { int len = strlen(value); return descr(dtype, value, n1, n2, n3, (int *)&zero, &len); - } else + } + else return descr(dtype, value, n1, n2, n3, (int *)&zero); } EXPORT int __stdcall descr4VB2(int *dtype, int *n1, int *n2, int *n3, - int *len) { + int *len) +{ return (descr2(dtype, n1, n2, n3, (int *)&zero, len)); } -EXPORT int __stdcall MdsValue1VB(char *expression, int *ansd, int *retlen) { +EXPORT int __stdcall MdsValue1VB(char *expression, int *ansd, int *retlen) +{ return MdsValue(expression, ansd, (int *)&zero, retlen); } EXPORT int __stdcall MdsValue1VB2(char *expression, int *ansd, void *value, - int *retlen) { + int *retlen) +{ return MdsValue2(expression, ansd, value, (int *)&zero, retlen); } EXPORT int __stdcall MdsValue2VB(char *expression, int *arg1d, int *ansd, - int *retlen) { + int *retlen) +{ return MdsValue(expression, arg1d, ansd, (int *)&zero, retlen); } EXPORT int __stdcall MdsValue2VB2(char *expression, int *arg1d, void *arg1v, - int *ansd, void *value, int *retlen) { + int *ansd, void *value, int *retlen) +{ return MdsValue2(expression, arg1d, arg1v, ansd, value, (int *)&zero, retlen); } EXPORT int __stdcall MdsValue3VB(char *expression, int *arg1d, int *arg2d, - int *ansd, int *retlen) { + int *ansd, int *retlen) +{ return MdsValue(expression, arg1d, arg2d, ansd, (int *)&zero, retlen); } EXPORT int __stdcall MdsValue3VB2(char *expression, int *arg1d, void *arg1v, int *arg2d, void *arg2v, int *ansd, - void *value, int *retlen) { + void *value, int *retlen) +{ return MdsValue2(expression, arg1d, arg1v, arg2d, arg2v, ansd, value, (int *)&zero, retlen); } -EXPORT int __stdcall MdsPut1VB(char *node, char *expression, int *ansd) { +EXPORT int __stdcall MdsPut1VB(char *node, char *expression, int *ansd) +{ return MdsPut(node, expression, ansd, (int *)&zero); } EXPORT int __stdcall MdsPut1VB2(char *node, char *expression, int *ansd, - void *value) { + void *value) +{ return MdsPut2(node, expression, ansd, value, (int *)&zero); } EXPORT int __stdcall MdsPut2VB(char *node, char *expression, int *arg1d, - int *ansd) { + int *ansd) +{ return MdsPut(node, expression, arg1d, ansd, (int *)&zero); } EXPORT int __stdcall MdsPut2VB2(char *node, char *expression, int *arg1d, - void *arg1v, int *ansd, void *value) { + void *arg1v, int *ansd, void *value) +{ return MdsPut2(node, expression, arg1d, arg1v, ansd, value, (int *)&zero); } EXPORT int __stdcall MdsPut3VB(char *node, char *expression, int *arg1d, - int *arg2d, int *ansd) { + int *arg2d, int *ansd) +{ return MdsPut(node, expression, arg1d, arg2d, ansd, (int *)&zero); } EXPORT int __stdcall MdsPut3VB2(char *node, char *expression, int *arg1d, void *arg1v, int *arg2d, void *arg2v, int *ansd, - void *value) { + void *value) +{ return MdsPut2(node, expression, arg1d, arg1v, arg2d, arg2v, ansd, value, (int *)&zero); } diff --git a/mdslibidl/MdsLibIdl.c b/mdslibidl/MdsLibIdl.c index 4bd1abac5d..a4f830962b 100644 --- a/mdslibidl/MdsLibIdl.c +++ b/mdslibidl/MdsLibIdl.c @@ -43,14 +43,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define UnBlockSig(a) #define SIGALRM 0 #else -static int BlockSig(int sig_number) { +static int BlockSig(int sig_number) +{ sigset_t newsigset; sigemptyset(&newsigset); sigaddset(&newsigset, sig_number); return sigprocmask(SIG_BLOCK, &newsigset, NULL); } -static int UnBlockSig(int sig_number) { +static int UnBlockSig(int sig_number) +{ sigset_t newsigset; sigemptyset(&newsigset); sigaddset(&newsigset, sig_number); @@ -61,12 +63,14 @@ static int UnBlockSig(int sig_number) { #define min(a, b) (((a) < (b)) ? (a) : (b)) -EXPORT int IdlMdsClose(int argc, void **argv) { +EXPORT int IdlMdsClose(int argc, void **argv) +{ int status; BlockSig(SIGALRM); if (argc > 1) status = TreeClose((char *)argv[0], (int)(intptr_t)argv[1]); - else { + else + { status = TreeClose(0, 0); while (TreeClose(0, 0) & 1) ; @@ -75,9 +79,11 @@ EXPORT int IdlMdsClose(int argc, void **argv) { return status; } -EXPORT int IdlMdsOpen(int argc, void **argv) { +EXPORT int IdlMdsOpen(int argc, void **argv) +{ int status = 0; - if (argc == 2) { + if (argc == 2) + { BlockSig(SIGALRM); status = TreeOpen((char *)argv[0], (int)(intptr_t)argv[1], 0); UnBlockSig(SIGALRM); @@ -85,10 +91,12 @@ EXPORT int IdlMdsOpen(int argc, void **argv) { return status; } -EXPORT int IdlMdsSetDefault(int argc, void **argv) { +EXPORT int IdlMdsSetDefault(int argc, void **argv) +{ int status = 0; int nid; - if (argc == 1) { + if (argc == 1) + { BlockSig(SIGALRM); status = TreeSetDefault((char *)argv[0], &nid); UnBlockSig(SIGALRM); @@ -100,19 +108,22 @@ static EMPTYXD(mdsValueAnswer); static array_coeff arrayArgs[16]; static struct descriptor scalarArgs[16]; -typedef struct { +typedef struct +{ unsigned short slen; /* Length of string */ short stype; /* type of string: (0) static, (!0) dynamic */ char *s; /* Addr of string, invalid if slen == 0. */ } IDL_STRING; -typedef struct { +typedef struct +{ unsigned int slen; /* Length of string */ short stype; /* type of string: (0) static, (!0) dynamic */ char *s; /* Addr of string, invalid if slen == 0. */ } IDL_STRING_L; -static int ShortStrings(char *b) { +static int ShortStrings(char *b) +{ #ifndef _WIN32 extern char *__progname; int isGdl = strcmp(__progname, "gdl") == 0; @@ -131,11 +142,14 @@ static int ShortStrings(char *b) { return ((b[t1_idx] != 0) && (b[t1_idx] != 1)) || (b[t2_idx] != 0); } -static void *MakeDescr(int idx, int *argsize, void *bytes) { - if (argsize[0] == 0) { +static void *MakeDescr(int idx, int *argsize, void *bytes) +{ + if (argsize[0] == 0) + { scalarArgs[idx].class = CLASS_S; scalarArgs[idx].pointer = (char *)bytes; - switch (argsize[1]) { + switch (argsize[1]) + { case 1: scalarArgs[idx].length = 1; scalarArgs[idx].dtype = DTYPE_BU; @@ -193,7 +207,9 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { return 0; } return (void *)&scalarArgs[idx]; - } else { + } + else + { int i; arrayArgs[idx].class = CLASS_A; arrayArgs[idx].pointer = arrayArgs[idx].a0 = (char *)bytes; @@ -203,7 +219,8 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { arrayArgs[idx].aflags.coeff = 1; for (i = 0; i < argsize[0]; i++) arrayArgs[idx].m[i] = argsize[i + 1]; - switch (argsize[argsize[0] + 1]) { + switch (argsize[argsize[0] + 1]) + { case 1: arrayArgs[idx].length = 1; arrayArgs[idx].dtype = DTYPE_BU; @@ -234,8 +251,10 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { arrayArgs[idx].dtype = DTYPE_FSC; arrayArgs[idx].arsize = argsize[argsize[0] + 2] * 8; break; - case 7: { - if (ShortStrings(bytes)) { + case 7: + { + if (ShortStrings(bytes)) + { IDL_STRING *str; int num = 1; unsigned short maxlen; @@ -247,7 +266,8 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { maxlen = str->slen; arrayArgs[idx].length = maxlen; arrayArgs[idx].arsize = maxlen * num; - if (arrayArgs[idx].arsize > 0) { + if (arrayArgs[idx].arsize > 0) + { char *ptr; char *blanks; blanks = malloc(maxlen + 1); @@ -255,16 +275,20 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { malloc(arrayArgs[idx].arsize + 1); memset(blanks, 32, maxlen); for (i = 0, str = (IDL_STRING *)bytes; i < num; - i++, str++, ptr += maxlen) { + i++, str++, ptr += maxlen) + { if (str->s) strcpy(ptr, str->s); if (str->slen < maxlen) strncat(ptr, blanks, maxlen - str->slen); } free(blanks); - } else + } + else arrayArgs[idx].pointer = 0; - } else { + } + else + { IDL_STRING_L *str; int num = 1; unsigned short maxlen; @@ -277,7 +301,8 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { maxlen = str->slen; arrayArgs[idx].length = maxlen; arrayArgs[idx].arsize = maxlen * num; - if (arrayArgs[idx].arsize > 0) { + if (arrayArgs[idx].arsize > 0) + { char *ptr; char *blanks; blanks = malloc(maxlen + 1); @@ -285,17 +310,20 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { malloc(arrayArgs[idx].arsize + 1); memset(blanks, 32, maxlen); for (i = 0, str = (IDL_STRING_L *)bytes; i < num; - i++, str++, ptr += maxlen) { + i++, str++, ptr += maxlen) + { if (str->s) strcpy(ptr, str->s); if (str->slen < maxlen) strncat(ptr, blanks, maxlen - str->slen); } free(blanks); - } else + } + else arrayArgs[idx].pointer = 0; } - } break; + } + break; case 9: arrayArgs[idx].length = 16; arrayArgs[idx].dtype = DTYPE_FTC; @@ -328,7 +356,8 @@ static void *MakeDescr(int idx, int *argsize, void *bytes) { } } -EXPORT int IdlMdsValue(int argc, void **argv) { +EXPORT int IdlMdsValue(int argc, void **argv) +{ int status; int arglistlen = 3 + (argc / 2); void **arglist = (void **)alloca(arglistlen * sizeof(void *)); @@ -343,7 +372,8 @@ EXPORT int IdlMdsValue(int argc, void **argv) { expression.length = strlen((char *)argv[0]); expression.pointer = (char *)argv[0]; arglist[argidx++] = (void *)&expression; - for (i = 3; i < argc; i += 2, argidx++) { + for (i = 3; i < argc; i += 2, argidx++) + { arglist[argidx] = (void *)MakeDescr(argidx - 2, (int *)argv[i], argv[i + 1]); } @@ -351,23 +381,28 @@ EXPORT int IdlMdsValue(int argc, void **argv) { arglist[argidx++] = MdsEND_ARG; *(long *)&arglist[0] = argidx; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) { + if (status & 1) + { status = TdiData(tmp.pointer, &mdsValueAnswer MDS_END_ARG); MdsFree1Dx(&tmp, NULL); - if (status & 1) { + if (status & 1) + { if (mdsValueAnswer.pointer->dtype == DTYPE_F || - mdsValueAnswer.pointer->dtype == DTYPE_FS) { + mdsValueAnswer.pointer->dtype == DTYPE_FS) + { float float_v = (float)0.0; DESCRIPTOR_FLOAT(float_d, 0); float_d.pointer = (char *)&float_v; if (float_d.dtype != mdsValueAnswer.pointer->dtype) TdiCvt((struct descriptor *)&mdsValueAnswer, &float_d, &mdsValueAnswer MDS_END_ARG); - } else if (mdsValueAnswer.pointer->dtype == DTYPE_D || - mdsValueAnswer.pointer->dtype == DTYPE_G || - mdsValueAnswer.pointer->dtype == DTYPE_FT || - mdsValueAnswer.pointer->dtype == DTYPE_O || - mdsValueAnswer.pointer->dtype == DTYPE_OU) { + } + else if (mdsValueAnswer.pointer->dtype == DTYPE_D || + mdsValueAnswer.pointer->dtype == DTYPE_G || + mdsValueAnswer.pointer->dtype == DTYPE_FT || + mdsValueAnswer.pointer->dtype == DTYPE_O || + mdsValueAnswer.pointer->dtype == DTYPE_OU) + { double double_v = 0.0; struct descriptor double_d = {sizeof(double), DTYPE_NATIVE_DOUBLE, CLASS_S, 0}; @@ -376,8 +411,10 @@ EXPORT int IdlMdsValue(int argc, void **argv) { if (double_d.dtype != mdsValueAnswer.pointer->dtype) TdiCvt((struct descriptor *)&mdsValueAnswer, &double_d, &mdsValueAnswer MDS_END_ARG); - } else if (mdsValueAnswer.pointer->dtype == DTYPE_FC || - mdsValueAnswer.pointer->dtype == DTYPE_FSC) { + } + else if (mdsValueAnswer.pointer->dtype == DTYPE_FC || + mdsValueAnswer.pointer->dtype == DTYPE_FSC) + { float float_v[2] = {(float)0.0, (float)0.0}; struct descriptor complex_d = {sizeof(float_v), DTYPE_FLOAT_COMPLEX, CLASS_S, 0}; @@ -385,9 +422,11 @@ EXPORT int IdlMdsValue(int argc, void **argv) { if (complex_d.dtype != mdsValueAnswer.pointer->dtype) TdiCvt((struct descriptor *)&mdsValueAnswer, &complex_d, &mdsValueAnswer MDS_END_ARG); - } else if (mdsValueAnswer.pointer->dtype == DTYPE_DC || - mdsValueAnswer.pointer->dtype == DTYPE_GC || - mdsValueAnswer.pointer->dtype == DTYPE_FTC) { + } + else if (mdsValueAnswer.pointer->dtype == DTYPE_DC || + mdsValueAnswer.pointer->dtype == DTYPE_GC || + mdsValueAnswer.pointer->dtype == DTYPE_FTC) + { double double_v[2] = {0.0, 0.0}; struct descriptor dcomplex_d = {sizeof(double_v), DTYPE_DOUBLE_COMPLEX, CLASS_S, 0}; @@ -397,8 +436,10 @@ EXPORT int IdlMdsValue(int argc, void **argv) { &mdsValueAnswer MDS_END_ARG); } ((char *)argv[2])[0] = 0; - if (mdsValueAnswer.pointer->class == CLASS_S) { - switch (mdsValueAnswer.pointer->dtype) { + if (mdsValueAnswer.pointer->class == CLASS_S) + { + switch (mdsValueAnswer.pointer->dtype) + { default: break; // TODO: handle invalid dtypes case DTYPE_B: @@ -439,26 +480,33 @@ EXPORT int IdlMdsValue(int argc, void **argv) { strcpy((char *)argv[1], "answer = dcomplex(0.0)"); break; case DTYPE_T: - if (mdsValueAnswer.pointer->length > 0) { + if (mdsValueAnswer.pointer->length > 0) + { sprintf((char *)argv[1], "answer = bytarr(%d)", mdsValueAnswer.pointer->length); strcpy((char *)argv[2], "answer = string(answer)"); - } else { + } + else + { strcpy((char *)argv[1], "answer = ''"); } break; } - } else if (mdsValueAnswer.pointer->class == CLASS_A) { + } + else if (mdsValueAnswer.pointer->class == CLASS_A) + { array_coeff *ptr = (array_coeff *)mdsValueAnswer.pointer; char dims[512] = "("; int i; if (ptr->aflags.coeff) - for (i = 0; i < ptr->dimct; i++) { + for (i = 0; i < ptr->dimct; i++) + { char dim[16]; sprintf(dim, "%d,", ptr->m[i] > 0 ? ptr->m[i] : 1); strcat(dims, dim); } - else { + else + { char dim[16]; sprintf(dim, "%d,", ((ptr->arsize / ptr->length) > 0) @@ -468,7 +516,8 @@ EXPORT int IdlMdsValue(int argc, void **argv) { } dims[strlen(dims) - 1] = '\0'; strcat(dims, ")"); - switch (mdsValueAnswer.pointer->dtype) { + switch (mdsValueAnswer.pointer->dtype) + { default: break; // TODO: handle invalid dtypes case DTYPE_B: @@ -520,12 +569,15 @@ EXPORT int IdlMdsValue(int argc, void **argv) { strcat((char *)argv[1], dims); break; case DTYPE_T: - if (mdsValueAnswer.pointer->length > 0) { + if (mdsValueAnswer.pointer->length > 0) + { sprintf((char *)argv[1], "answer = bytarr(%d,", mdsValueAnswer.pointer->length); strcat((char *)argv[1], &dims[1]); strcpy((char *)argv[2], "answer = strtrim(string(answer))"); - } else { + } + else + { strcpy((char *)argv[1], "answer = strarr"); strcat((char *)argv[1], dims); } @@ -534,8 +586,10 @@ EXPORT int IdlMdsValue(int argc, void **argv) { } } } - for (i = 0; i < 16; i++) { - if (arrayArgs[i].dtype == DTYPE_T && arrayArgs[i].pointer != NULL) { + for (i = 0; i < 16; i++) + { + if (arrayArgs[i].dtype == DTYPE_T && arrayArgs[i].pointer != NULL) + { free(arrayArgs[i].pointer); arrayArgs[i].pointer = 0; } @@ -546,7 +600,8 @@ EXPORT int IdlMdsValue(int argc, void **argv) { return status; } -EXPORT int IdlMdsPut(int argc, void **argv) { +EXPORT int IdlMdsPut(int argc, void **argv) +{ int status; int arglistlen = 4 + (argc / 2); void **arglist = (void **)alloca(arglistlen * sizeof(void *)); @@ -558,11 +613,13 @@ EXPORT int IdlMdsPut(int argc, void **argv) { memset(arglist, 0, arglistlen * sizeof(void *)); BlockSig(SIGALRM); status = TreeFindNode((char *)argv[0], &nid); - if (status & 1) { + if (status & 1) + { expression.length = strlen((char *)argv[1]); expression.pointer = (char *)argv[1]; arglist[argidx++] = (void *)&expression; - for (i = 2; i < argc; i += 2, argidx++) { + for (i = 2; i < argc; i += 2, argidx++) + { arglist[argidx] = (void *)MakeDescr(argidx - 2, (int *)argv[i], argv[i + 1]); } @@ -570,12 +627,15 @@ EXPORT int IdlMdsPut(int argc, void **argv) { arglist[argidx++] = MdsEND_ARG; *(int *)&arglist[0] = argidx; status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) { + if (status & 1) + { status = TreePutRecord(nid, (struct descriptor *)&tmp, 0); MdsFree1Dx(&tmp, NULL); } - for (i = 0; i < 16; i++) { - if (arrayArgs[i].dtype == DTYPE_T && arrayArgs[i].pointer != NULL) { + for (i = 0; i < 16; i++) + { + if (arrayArgs[i].dtype == DTYPE_T && arrayArgs[i].pointer != NULL) + { free(arrayArgs[i].pointer); arrayArgs[i].pointer = 0; } @@ -585,13 +645,18 @@ EXPORT int IdlMdsPut(int argc, void **argv) { return status; } -EXPORT int IdlGetAns(int argc, void **argv) { +EXPORT int IdlGetAns(int argc, void **argv) +{ int status = 1; - if (argc == 1) { - if (mdsValueAnswer.pointer->class == CLASS_S) { + if (argc == 1) + { + if (mdsValueAnswer.pointer->class == CLASS_S) + { memcpy(argv[0], mdsValueAnswer.pointer->pointer, mdsValueAnswer.pointer->length); - } else if (mdsValueAnswer.pointer->class == CLASS_A) { + } + else if (mdsValueAnswer.pointer->class == CLASS_A) + { memcpy(argv[0], mdsValueAnswer.pointer->pointer, ((struct descriptor_a *)mdsValueAnswer.pointer)->arsize); } diff --git a/mdsmisc/MdsFilter.c b/mdsmisc/MdsFilter.c index 4736192b44..d5b0f08e6a 100644 --- a/mdsmisc/MdsFilter.c +++ b/mdsmisc/MdsFilter.c @@ -58,7 +58,8 @@ Invariance Method #include EXPORT struct descriptor_xd *MdsFilter(float *in_data, float *in_dim, int *size, - float *cut_off, int *num_in_poles) { + float *cut_off, int *num_in_poles) +{ static struct descriptor_xd out_xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; DESCRIPTOR_A(data_d, sizeof(float), DTYPE_FLOAT, 0, 0); @@ -117,7 +118,8 @@ EXPORT struct descriptor_xd *MdsFilter(float *in_data, float *in_dim, int *size, i++) ; - if (i > 1) { + if (i > 1) + { phs_steep = (phs[1] - phs[i]) / ((i / 1000.) * fc / 2.); delay = phs_steep / (2 * PI); } @@ -139,10 +141,12 @@ EXPORT struct descriptor_xd *MdsFilter(float *in_data, float *in_dim, int *size, return &out_xd; } -EXPORT void PrintFilter(Filter *filter) { +EXPORT void PrintFilter(Filter *filter) +{ int i, j; - for (i = 0; i < filter->num_parallels; i++) { + for (i = 0; i < filter->num_parallels; i++) + { // if(filter->units[i].den_degree > 0) { for (j = 0; j < filter->units[i].num_degree; j++) diff --git a/mdsmisc/ScopeUtilities.c b/mdsmisc/ScopeUtilities.c index 5cf443f0f7..88bf783e4f 100644 --- a/mdsmisc/ScopeUtilities.c +++ b/mdsmisc/ScopeUtilities.c @@ -44,25 +44,29 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SWAP32(out, in) memcpy((char *)(out), (char *)(in), 4) #define SWAP64(out, in) memcpy((char *)(out), (char *)(in), 8) #else -#define SWAP(out, in, a, b) \ - ((char *)(out))[a] = ((char *)(in))[b]; \ +#define SWAP(out, in, a, b) \ + ((char *)(out))[a] = ((char *)(in))[b]; \ ((char *)(out))[b] = ((char *)(in))[a] -#define SWAP32(out, in) \ - do { \ - SWAP(out, in, 0, 3); \ - SWAP(out, in, 2, 1); \ +#define SWAP32(out, in) \ + do \ + { \ + SWAP(out, in, 0, 3); \ + SWAP(out, in, 2, 1); \ } while (0) -#define SWAP64(out, in) \ - do { \ - SWAP(out, in, 0, 7); \ - SWAP(out, in, 2, 5); \ - SWAP(out, in, 4, 3); \ - SWAP(out, in, 6, 1); \ +#define SWAP64(out, in) \ + do \ + { \ + SWAP(out, in, 0, 7); \ + SWAP(out, in, 2, 5); \ + SWAP(out, in, 4, 3); \ + SWAP(out, in, 6, 1); \ } while (0) #endif static double to_doublex(const void *const ptr, const dtype_t dtype, - const double defval, const int is_time) { - switch (dtype) { + const double defval, const int is_time) +{ + switch (dtype) + { case DTYPE_FLOAT: return (double)*(float *)ptr; case DTYPE_DOUBLE: @@ -86,10 +90,12 @@ static double to_doublex(const void *const ptr, const dtype_t dtype, return defval; } } -inline static double to_double(const void *const ptr, const dtype_t dtype) { +inline static double to_double(const void *const ptr, const dtype_t dtype) +{ return to_doublex(ptr, dtype, 0, FALSE); } -static int recIsSegmented(const mdsdsc_t *const dsc) { +static int recIsSegmented(const mdsdsc_t *const dsc) +{ /* returns nid of the first segmented node found * or 0 if none found */ @@ -100,9 +106,12 @@ static int recIsSegmented(const mdsdsc_t *const dsc) { EMPTYXD(xd); mdsdsc_r_t *rDsc; - switch (dsc->class) { - case CLASS_S: { - if (dsc->dtype == DTYPE_NID) { + switch (dsc->class) + { + case CLASS_S: + { + if (dsc->dtype == DTYPE_NID) + { nid = *(int *)dsc->pointer; status = TreeGetNumSegments(nid, &numSegments); if (STATUS_OK && numSegments > 0) @@ -115,35 +124,42 @@ static int recIsSegmented(const mdsdsc_t *const dsc) { status = TreeGetNci(nid, nciList); if (STATUS_OK && (nciClass == CLASS_R || (nciClass == CLASS_S && - (nciDtype == DTYPE_NID || nciDtype == DTYPE_PATH)))) { + (nciDtype == DTYPE_NID || nciDtype == DTYPE_PATH)))) + { status = TreeGetRecord(nid, &xd); - if (STATUS_OK && xd.l_length > 0) { + if (STATUS_OK && xd.l_length > 0) + { nid = recIsSegmented(xd.pointer); MdsFree1Dx(&xd, 0); return nid; } } - } else if (dsc->dtype == DTYPE_PATH) { + } + else if (dsc->dtype == DTYPE_PATH) + { char *path = malloc(dsc->length + 1); memcpy(path, dsc->pointer, dsc->length); path[dsc->length] = 0; status = TreeFindNode(path, &nid); free(path); - if - STATUS_OK { - status = TreeGetNumSegments(nid, &numSegments); - if (STATUS_OK) { - if (numSegments > 0) { - return nid; - } - status = TreeGetRecord(nid, &xd); - if (STATUS_OK && xd.l_length > 0) { - nid = recIsSegmented(xd.pointer); - MdsFree1Dx(&xd, 0); - return nid; - } + if (STATUS_OK) + { + status = TreeGetNumSegments(nid, &numSegments); + if (STATUS_OK) + { + if (numSegments > 0) + { + return nid; + } + status = TreeGetRecord(nid, &xd); + if (STATUS_OK && xd.l_length > 0) + { + nid = recIsSegmented(xd.pointer); + MdsFree1Dx(&xd, 0); + return nid; } } + } } break; } @@ -153,12 +169,14 @@ static int recIsSegmented(const mdsdsc_t *const dsc) { if (dsc->pointer) return recIsSegmented((mdsdsc_t *)dsc->pointer); break; - case CLASS_R: { + case CLASS_R: + { rDsc = (mdsdsc_r_t *)dsc; if (rDsc->dtype == DTYPE_SIGNAL) break; // If the expression includes a Signal descriptor, the time base // may be different from that of the segmented node - for (i = 0; i < rDsc->ndesc; i++) { + for (i = 0; i < rDsc->ndesc; i++) + { if (rDsc->dscptrs[i] && (nid = recIsSegmented(rDsc->dscptrs[i]))) return nid; } @@ -184,7 +202,8 @@ inline static int64_t estimateNumSamples(const mdsdsc_t *const dsc, mdsdsc_t *const xMin, mdsdsc_t *const xMax, int *const estimatedSegmentSamples, double *const dMin, double *const dMax, double *const sMin, - double *const sMax, int *const dIsLong) { + double *const sMax, int *const dIsLong) +{ /* return the number of samples the signal holds based on meta information or -1 if something went wrong */ @@ -198,17 +217,18 @@ estimateNumSamples(const mdsdsc_t *const dsc, mdsdsc_t *const xMin, if (!nid) goto return_neg1; int status = TreeGetNumSegments(nid, &numSegments); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; status = TreeGetSegmentLimits(nid, 0, NULL, &xd); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; status = TdiData(xd.pointer, &xd MDS_END_ARG); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; *dIsLong = xd.pointer && (xd.pointer->dtype == DTYPE_Q || xd.pointer->dtype == DTYPE_QU); - if (xMin != NULL || xMax != NULL) { + if (xMin != NULL || xMax != NULL) + { if (xMin) XTreeConvertToLongTime(xMin, &startTime); if (xMax) @@ -216,14 +236,16 @@ estimateNumSamples(const mdsdsc_t *const dsc, mdsdsc_t *const xMin, if (numSegments < NUM_SEGMENTS_THRESHOLD) goto return_neg1; startIdx = 0; // If no start time specified, take all initial segments - if (xMin) { - while (startIdx < numSegments) { + if (xMin) + { + while (startIdx < numSegments) + { status = TreeGetSegmentLimits(nid, startIdx, NULL, &xd); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; status = XTreeConvertToLongTime(xd.pointer, &currEnd); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; if (currEnd >= startTime) // First overlapping segment break; startIdx++; @@ -233,15 +255,17 @@ estimateNumSamples(const mdsdsc_t *const dsc, mdsdsc_t *const xMin, goto return_neg1; // All segments antecedent to start time if (!xMax) endIdx = numSegments - 1; - else { + else + { segmentIdx = startIdx; - while (segmentIdx < numSegments) { + while (segmentIdx < numSegments) + { status = TreeGetSegmentLimits(nid, segmentIdx, NULL, &xd); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; status = XTreeConvertToLongTime(xd.pointer, &currEnd); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; if (currEnd >= endTime) // Last overlapping segment break; segmentIdx++; @@ -250,53 +274,61 @@ estimateNumSamples(const mdsdsc_t *const dsc, mdsdsc_t *const xMin, endIdx = (segmentIdx == numSegments) ? numSegments - 1 : segmentIdx; } numActSegments = endIdx - startIdx + 1; - } else { + } + else + { startIdx = 0; numActSegments = numSegments; endIdx = numSegments - 1; } status = TreeGetSegmentInfo(nid, startIdx, &dtype, &dimct, dims, &nextRow); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_NOT_OK) + goto return_neg1; segmentSamples = nextRow; // Compute duration status = TreeGetSegmentLimits(nid, startIdx, &xd, NULL); - if - STATUS_OK status = TdiData(xd.pointer, &xd MDS_END_ARG); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_OK) + status = TdiData(xd.pointer, &xd MDS_END_ARG); + if (STATUS_NOT_OK) + goto return_neg1; *sMin = to_doublex(xd.pointer->pointer, xd.pointer->dtype, -INFINITY, TRUE); status = TreeGetSegmentLimits(nid, endIdx, NULL, &xd); - if - STATUS_OK status = TdiData((mdsdsc_t *)&xd, &xd MDS_END_ARG); - if - STATUS_NOT_OK goto return_neg1; + if (STATUS_OK) + status = TdiData((mdsdsc_t *)&xd, &xd MDS_END_ARG); + if (STATUS_NOT_OK) + goto return_neg1; *sMax = to_doublex(xd.pointer->pointer, xd.pointer->dtype, INFINITY, TRUE); MdsFree1Dx(&xd, NULL); *dMin = xMin ? to_doublex(xMin->pointer, xMin->dtype, -INFINITY, TRUE) : *sMin; *dMax = xMax ? to_doublex(xMax->pointer, xMax->dtype, INFINITY, TRUE) : *sMax; - if(numActSegments == 1 && xMin && xMax) //Handle the case of a single (likely large) segment + if (numActSegments == 1 && xMin && xMax) //Handle the case of a single (likely large) segment { - double givenTimeSpan = to_doublex(xMax->pointer, xMax->dtype, -INFINITY, TRUE) - to_doublex(xMin->pointer, xMin->dtype, -INFINITY, TRUE); - double segmentTimeSpan = *sMax - *sMin; - if(segmentTimeSpan > 0 && segmentTimeSpan > givenTimeSpan) - return (int64_t)(segmentSamples * givenTimeSpan / segmentTimeSpan); + double givenTimeSpan = to_doublex(xMax->pointer, xMax->dtype, -INFINITY, TRUE) - to_doublex(xMin->pointer, xMin->dtype, -INFINITY, TRUE); + double segmentTimeSpan = *sMax - *sMin; + if (segmentTimeSpan > 0 && segmentTimeSpan > givenTimeSpan) + return (int64_t)(segmentSamples * givenTimeSpan / segmentTimeSpan); } *estimatedSegmentSamples = segmentSamples; return segmentSamples * (int64_t)numActSegments; return_neg1:; - if (xMin && IS_OK(TdiData(xMin, &xd MDS_END_ARG))) { + if (xMin && IS_OK(TdiData(xMin, &xd MDS_END_ARG))) + { *sMin = to_doublex(xd.pointer->pointer, xd.pointer->dtype, -INFINITY, TRUE); *dMin = to_doublex(xMin->pointer, xMin->dtype, -INFINITY, TRUE); - } else { + } + else + { *sMin = -INFINITY; *dMin = -INFINITY; } - if (xMax && IS_OK(TdiData(xMax, &xd MDS_END_ARG))) { + if (xMax && IS_OK(TdiData(xMax, &xd MDS_END_ARG))) + { *sMax = to_doublex(xd.pointer->pointer, xd.pointer->dtype, INFINITY, TRUE); *dMax = to_doublex(xMax->pointer, xMax->dtype, INFINITY, TRUE); - } else { + } + else + { *sMax = INFINITY; *dMax = INFINITY; } @@ -310,7 +342,8 @@ static inline void trimData(float *const y, mdsdsc_a_t *const x, const int nSamples, const int reqPoints, const double xMin, const double xMax, int *const retPoints, float *const retResolution, - int treeshrResampled) { + int treeshrResampled) +{ /* if(nSamples < 10 * reqPoints) { //Does not perform any compression @@ -346,7 +379,8 @@ static inline void trimData(float *const y, mdsdsc_a_t *const x, ? 1 : (endIdx - startIdx + 1) / reqPoints; - if (nSamples < 10 * reqPoints) { + if (nSamples < 10 * reqPoints) + { // Does not perform any compression *retResolution = 1E12; *retPoints = nSamples; @@ -362,19 +396,25 @@ static inline void trimData(float *const y, mdsdsc_a_t *const x, int curIdx = startIdx; int outIdx = 0; - if (deltaIdx == 1) { + if (deltaIdx == 1) + { *retResolution = 1E12; - if (outIdx < curIdx) { // check if not src == dst - while (curIdx < endIdx) { + if (outIdx < curIdx) + { // check if not src == dst + while (curIdx < endIdx) + { memcpy(&x->pointer[outIdx * x->length], &x->pointer[curIdx * x->length], x->length); y[outIdx++] = y[curIdx++]; } - } else // but in this case the number of points must be reported!!! + } + else // but in this case the number of points must be reported!!! { outIdx = endIdx - startIdx; } - } else { + } + else + { *retResolution = reqPoints / (to_doublex(&x->pointer[endIdx * x->length], x->dtype, INFINITY, TRUE) - to_doublex(&x->pointer[startIdx * x->length], @@ -382,14 +422,16 @@ static inline void trimData(float *const y, mdsdsc_a_t *const x, const double deltaTime = (deltaIdx == 1) ? 0 : (xMax - xMin) / (double)reqPoints; float minY, maxY; - while (curIdx < endIdx) { + while (curIdx < endIdx) + { minY = maxY = y[curIdx]; int i, actSamples = 0; const double endXDouble = to_doublex(&x->pointer[curIdx * x->length], x->dtype, INFINITY, TRUE) + deltaTime; for (i = curIdx; i < nSamples && i < curIdx + deltaIdx; - i++, actSamples++) { + i++, actSamples++) + { if (to_doublex(&x->pointer[i * x->length], x->dtype, -INFINITY, TRUE) > endXDouble) break; // Handle dual speed clocks @@ -420,26 +462,30 @@ static inline void trimData(float *const y, mdsdsc_a_t *const x, } static int recGetXxxx(const mdsdsc_t *const dsc_in, mdsdsc_xd_t *const xd_out, - const int getHelp) { + const int getHelp) +{ const mdsdsc_t *dsc = dsc_in; again:; if (!dsc) return MDSplusERROR; int status; - switch (dsc->class) { + switch (dsc->class) + { case CLASS_S: - if (dsc->dtype == DTYPE_NID || dsc->dtype == DTYPE_PATH) { + if (dsc->dtype == DTYPE_NID || dsc->dtype == DTYPE_PATH) + { int nid; if (dsc->dtype == DTYPE_NID) nid = *(int *)dsc->pointer; - else { // if(dsc->dtype == DTYPE_PATH) + else + { // if(dsc->dtype == DTYPE_PATH) char *path = malloc(dsc->length + 1); memcpy(path, dsc->pointer, dsc->length); path[dsc->length] = 0; status = TreeFindNode(path, &nid); free(path); - if - STATUS_NOT_OK goto status_not_ok_out; + if (STATUS_NOT_OK) + goto status_not_ok_out; } int numSegments; status = TreeGetNumSegments(nid, &numSegments); @@ -447,8 +493,8 @@ again:; goto error_out; EMPTYXD(xd); status = TreeGetRecord(nid, &xd); - if - STATUS_OK status = recGetXxxx(xd.pointer, xd_out, getHelp); + if (STATUS_OK) + status = recGetXxxx(xd.pointer, xd_out, getHelp); MdsFree1Dx(&xd, NULL); goto status_out; } @@ -461,13 +507,16 @@ again:; dsc = (mdsdsc_t *)dsc->pointer; goto again; case CLASS_R: - if (getHelp) { - if (dsc->dtype == DTYPE_PARAM) { + if (getHelp) + { + if (dsc->dtype == DTYPE_PARAM) + { mds_param_t *pDsc = (mds_param_t *)dsc; - if (pDsc->help) { + if (pDsc->help) + { status = TdiData(pDsc->help, xd_out MDS_END_ARG); - if - STATUS_NOT_OK goto status_not_ok_out; + if (STATUS_NOT_OK) + goto status_not_ok_out; if (xd_out->pointer && xd_out->pointer->class == CLASS_S && xd_out->pointer->dtype == DTYPE_T) goto status_out; @@ -476,52 +525,64 @@ again:; } mdsdsc_r_t *rDsc = (mdsdsc_r_t *)dsc; int i; - for (i = 0; i < rDsc->ndesc; i++) { + for (i = 0; i < rDsc->ndesc; i++) + { status = recGetXxxx(rDsc->dscptrs[i], xd_out, getHelp); - if - STATUS_OK goto status_out; + if (STATUS_OK) + goto status_out; } - } else { - if (dsc->dtype == DTYPE_WITH_UNITS) { + } + else + { + if (dsc->dtype == DTYPE_WITH_UNITS) + { mds_with_units_t *uDsc = (mds_with_units_t *)dsc; - if (uDsc->units) { + if (uDsc->units) + { status = TdiData(uDsc->units, xd_out MDS_END_ARG); - if - STATUS_NOT_OK goto status_not_ok_out; + if (STATUS_NOT_OK) + goto status_not_ok_out; if (xd_out->pointer && xd_out->pointer->class == CLASS_S && xd_out->pointer->dtype == DTYPE_T) goto status_out; } break; } - if (dsc->dtype == DTYPE_PARAM) { + if (dsc->dtype == DTYPE_PARAM) + { dsc = ((mds_param_t *)dsc)->value; ; goto again; } - if (dsc->dtype == DTYPE_SIGNAL) { + if (dsc->dtype == DTYPE_SIGNAL) + { dsc = ((mds_signal_t *)dsc)->data; goto again; } mdsdsc_r_t *rDsc = (mdsdsc_r_t *)dsc; - if (rDsc->ndesc == 1) { + if (rDsc->ndesc == 1) + { dsc = rDsc->dscptrs[0]; goto again; } - if (rDsc->dtype == DTYPE_FUNCTION && rDsc->pointer) { + if (rDsc->dtype == DTYPE_FUNCTION && rDsc->pointer) + { int i; if (*(opcode_t *)rDsc->pointer == OPC_ADD || - *(opcode_t *)rDsc->pointer == OPC_SUBTRACT) { + *(opcode_t *)rDsc->pointer == OPC_SUBTRACT) + { status = recGetXxxx(rDsc->dscptrs[0], xd_out, getHelp); - if - STATUS_NOT_OK goto status_not_ok_out; + if (STATUS_NOT_OK) + goto status_not_ok_out; EMPTYXD(xd); - for (i = 1; i < rDsc->ndesc; i++) { + for (i = 1; i < rDsc->ndesc; i++) + { status = recGetXxxx(rDsc->dscptrs[i], &xd, getHelp); if (STATUS_NOT_OK || xd.pointer->length != xd_out->pointer->length || strncmp(xd.pointer->pointer, xd_out->pointer->pointer, - xd.pointer->length)) { + xd.pointer->length)) + { MdsFree1Dx(&xd, NULL); goto error_out; // Different units } @@ -530,31 +591,37 @@ again:; goto status_out; } if (*(opcode_t *)rDsc->pointer == OPC_MULTIPLY || - *(opcode_t *)rDsc->pointer == OPC_DIVIDE) { + *(opcode_t *)rDsc->pointer == OPC_DIVIDE) + { mdsdsc_t da = {0, DTYPE_T, CLASS_D, NULL}; char mulDivC = (*(opcode_t *)rDsc->pointer == OPC_MULTIPLY) ? '*' : '/'; mdsdsc_t mulDiv = {1, DTYPE_T, CLASS_S, &mulDivC}; EMPTYXD(xd); - for (i = 0; i < rDsc->ndesc; i++) { + for (i = 0; i < rDsc->ndesc; i++) + { status = recGetXxxx(rDsc->dscptrs[i], &xd, getHelp); - if - STATUS_OK { - if (da.pointer) { - status = StrConcat(&da, &da, &mulDiv, xd.pointer MDS_END_ARG); - if - STATUS_NOT_OK { - MdsFree1Dx(&xd, NULL); - goto status_not_ok_out; - } - } else { - da.length = xd.pointer->length; - da.pointer = strdup(xd.pointer->pointer); + if (STATUS_OK) + { + if (da.pointer) + { + status = StrConcat(&da, &da, &mulDiv, xd.pointer MDS_END_ARG); + if (STATUS_NOT_OK) + { + MdsFree1Dx(&xd, NULL); + goto status_not_ok_out; } } + else + { + da.length = xd.pointer->length; + da.pointer = strdup(xd.pointer->pointer); + } + } } MdsFree1Dx(&xd, NULL); - if (da.pointer) { + if (da.pointer) + { da.class = CLASS_S; MdsCopyDxXd((mdsdsc_t *)&da, xd_out); free(da.pointer); @@ -578,28 +645,32 @@ success:; } static inline int recGetHelp(const mdsdsc_t *const dsc, - mdsdsc_xd_t *const xd_out) { + mdsdsc_xd_t *const xd_out) +{ return recGetXxxx(dsc, xd_out, TRUE); } static inline int recGetUnits(const mdsdsc_t *const dsc, - mdsdsc_xd_t *const xd_out) { + mdsdsc_xd_t *const xd_out) +{ return recGetXxxx(dsc, xd_out, FALSE); } // Check if the passed expression contains at least one segmented node -EXPORT int IsSegmented(char *const expr) { +EXPORT int IsSegmented(char *const expr) +{ EMPTYXD(xd); mdsdsc_t exprD = {strlen(expr), DTYPE_T, CLASS_S, expr}; - if - IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG)) return FALSE; + if (IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG))) + return FALSE; int segNid = recIsSegmented(xd.pointer); MdsFree1Dx(&xd, NULL); return segNid; } // Check if the passed expression contains at least one segmented node -EXPORT struct descriptor_xd *GetPathOf(int *nid) { +EXPORT struct descriptor_xd *GetPathOf(int *nid) +{ static EMPTYXD(retXd); mdsdsc_t pathD = {0, DTYPE_T, CLASS_S, 0}; char *path = TreeGetPath(*nid); @@ -612,20 +683,22 @@ EXPORT struct descriptor_xd *GetPathOf(int *nid) { return &retXd; } -EXPORT int TestGetHelp(char *const expr) { +EXPORT int TestGetHelp(char *const expr) +{ EMPTYXD(xd); mdsdsc_t exprD = {strlen(expr), DTYPE_T, CLASS_S, expr}; - if - IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG)) return FALSE; + if (IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG))) + return FALSE; MdsFree1Dx(&xd, 0); return TRUE; } -EXPORT int TestGetUnits(char *const expr) { +EXPORT int TestGetUnits(char *const expr) +{ EMPTYXD(xd); mdsdsc_t exprD = {strlen(expr), DTYPE_T, CLASS_S, expr}; - if - IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG)) return FALSE; + if (IS_NOT_OK(TdiCompile(&exprD, &xd MDS_END_ARG))) + return FALSE; MdsFree1Dx(&xd, 0); return TRUE; } @@ -633,37 +706,47 @@ EXPORT int TestGetUnits(char *const expr) { static inline int pack_meta(const mdsdsc_t *const title, const mdsdsc_t *const xLabel, const mdsdsc_t *const yLabel, const float res, - char *const retArr, int idx) { + char *const retArr, int idx) +{ // idx is the current index in retArr // Write title, xLabel, yLabel as length followed by chars int len; - if (title) { + if (title) + { len = title->length & 0xffff; SWAP32(&retArr[idx], &len); idx += sizeof(int); memcpy(&retArr[idx], title->pointer, len); idx += len; - } else { + } + else + { *(int *)&retArr[idx] = 0; // no swap required idx += 4; } - if (xLabel) { + if (xLabel) + { len = xLabel->length & 0xffff; SWAP32(&retArr[idx], &len); idx += sizeof(int); memcpy(&retArr[idx], xLabel->pointer, len); idx += len; - } else { + } + else + { *(int *)&retArr[idx] = 0; // no swap required idx += 4; } - if (yLabel) { + if (yLabel) + { len = yLabel->length & 0xffff; SWAP32(&retArr[idx], &len); idx += sizeof(int); memcpy(&retArr[idx], yLabel->pointer, len); idx += len; - } else { + } + else + { *(int *)&retArr[idx] = 0; // no swap required idx += 4; } @@ -673,20 +756,23 @@ static inline int pack_meta(const mdsdsc_t *const title, inline static int getNSamples(const mdsdsc_xd_t *const yXd, const mdsdsc_xd_t *const xXd, - int *const nSamples) { + int *const nSamples) +{ if (yXd->pointer->class != CLASS_A) return TdiINVCLADSC; if (xXd->pointer->class != CLASS_A) return TdiINVCLADSC; - if (yXd->pointer->dtype == DTYPE_F) { + if (yXd->pointer->dtype == DTYPE_F) + { const int status = TdiFloat(yXd->pointer, yXd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } - if (xXd->pointer->dtype == DTYPE_F) { + if (xXd->pointer->dtype == DTYPE_F) + { const int status = TdiFloat(xXd->pointer, xXd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } // Number of samples set to minimum between X and Y const int ySamples = @@ -698,10 +784,12 @@ inline static int getNSamples(const mdsdsc_xd_t *const yXd, } inline static float *getFloatArray(const mdsdsc_a_t *const yArrD, - const int nSamples) { + const int nSamples) +{ int i; float *y; - switch (yArrD->dtype) { + switch (yArrD->dtype) + { case DTYPE_B: case DTYPE_BU: y = (float *)malloc(nSamples * sizeof(float)); @@ -739,45 +827,53 @@ inline static float *getFloatArray(const mdsdsc_a_t *const yArrD, } static inline int getXArray(const mdsdsc_a_t *const xArrD, const int retSamples, - char *const retArr, int idx) { + char *const retArr, int idx) +{ int i; - switch (xArrD->dtype) { + switch (xArrD->dtype) + { default: return -1; case DTYPE_B: case DTYPE_BU: - for (i = 0; i < retSamples; i++, idx += 4) { + for (i = 0; i < retSamples; i++, idx += 4) + { const float tmp = *((int8_t *)(&xArrD->pointer[i * xArrD->length])); SWAP32(&retArr[idx], &tmp); } break; case DTYPE_W: case DTYPE_WU: - for (i = 0; i < retSamples; i++, idx += 4) { + for (i = 0; i < retSamples; i++, idx += 4) + { const float tmp = *((int16_t *)(&xArrD->pointer[i * xArrD->length])); SWAP32(&retArr[idx], &tmp); } break; case DTYPE_L: case DTYPE_LU: - for (i = 0; i < retSamples; i++, idx += 4) { + for (i = 0; i < retSamples; i++, idx += 4) + { const float tmp = *((int32_t *)(&xArrD->pointer[i * xArrD->length])); SWAP32(&retArr[idx], &tmp); } break; case DTYPE_Q: case DTYPE_QU: - for (i = 0; i < retSamples; i++, idx += 8) { + for (i = 0; i < retSamples; i++, idx += 8) + { SWAP64(&retArr[idx], &xArrD->pointer[i * xArrD->length]); } break; case DTYPE_FLOAT: - for (i = 0; i < retSamples; i++, idx += 4) { + for (i = 0; i < retSamples; i++, idx += 4) + { SWAP32(&retArr[idx], &xArrD->pointer[i * xArrD->length]); } break; case DTYPE_DOUBLE: - for (i = 0; i < retSamples; i++, idx += 8) { + for (i = 0; i < retSamples; i++, idx += 8) + { SWAP64(&retArr[idx], &xArrD->pointer[i * xArrD->length]); } break; @@ -787,7 +883,8 @@ static inline int getXArray(const mdsdsc_a_t *const xArrD, const int retSamples, EXPORT int GetXYSignalXd(mdsdsc_t *const inY, mdsdsc_t *const inX, mdsdsc_t *const inXMin, mdsdsc_t *const inXMax, - const int reqNSamples, mdsdsc_xd_t *const retXd) { + const int reqNSamples, mdsdsc_xd_t *const retXd) +{ if (!inY) return TdiNULL_PTR; EMPTYXD(yXd); @@ -807,10 +904,11 @@ EXPORT int GetXYSignalXd(mdsdsc_t *const inY, mdsdsc_t *const inX, xMinP = (xmin > -INFINITY) ? inXMin : NULL; xMaxP = (xmax < INFINITY) ? inXMax : NULL; - //printf("ESTIMATED SAMPLES: %d THRESHOLD: %d\n", estimatedSamples, - //NUM_SAMPLES_THRESHOLD); + //printf("ESTIMATED SAMPLES: %d THRESHOLD: %d\n", estimatedSamples, + //NUM_SAMPLES_THRESHOLD); - if (estimatedSamples > NUM_SAMPLES_THRESHOLD) { + if (estimatedSamples > NUM_SAMPLES_THRESHOLD) + { delta = estimatedSamples / reqNSamples; if (xmin > -INFINITY && xmax < INFINITY && smax > smin) delta *= (xmax - xmin) / (smax - smin); @@ -826,22 +924,20 @@ EXPORT int GetXYSignalXd(mdsdsc_t *const inY, mdsdsc_t *const inX, if (isLong) delta /= 1e9; // quick compensation of xtreeshr conversion - - //printf("DELTA: %e\n", delta); - + //printf("DELTA: %e\n", delta); + deltaP = (delta > 1e-9) ? &deltaD : NULL; - } else + } + else deltaP = NULL; // Set limits if any - - - + int status = TreeSetTimeContext(xMinP, xMaxP, deltaP); - if - STATUS_OK status = TdiEvaluate(inY, &yXd MDS_END_ARG); - if - STATUS_NOT_OK goto return_err; + if (STATUS_OK) + status = TdiEvaluate(inY, &yXd MDS_END_ARG); + if (STATUS_NOT_OK) + goto return_err; // Get Y, title, and yLabel, if any EMPTYXD(title); EMPTYXD(xLabel); @@ -853,20 +949,20 @@ EXPORT int GetXYSignalXd(mdsdsc_t *const inY, mdsdsc_t *const inX, status = TdiDimOf(yXd.pointer, &xXd MDS_END_ARG); else // Get xLabel, if any status = TdiEvaluate(inX, &xXd MDS_END_ARG); - if - STATUS_NOT_OK goto return_err; + if (STATUS_NOT_OK) + goto return_err; recGetUnits(xXd.pointer, &xLabel); - if - STATUS_OK status = TdiData((mdsdsc_t *)&xXd, &xXd MDS_END_ARG); - if - STATUS_OK status = TdiData((mdsdsc_t *)&yXd, &yXd MDS_END_ARG); + if (STATUS_OK) + status = TdiData((mdsdsc_t *)&xXd, &xXd MDS_END_ARG); + if (STATUS_OK) + status = TdiData((mdsdsc_t *)&yXd, &yXd MDS_END_ARG); int nSamples = 0; - if - STATUS_OK status = getNSamples(&yXd, &xXd, &nSamples); - if - STATUS_NOT_OK goto return_err; + if (STATUS_OK) + status = getNSamples(&yXd, &xXd, &nSamples); + if (STATUS_NOT_OK) + goto return_err; mdsdsc_a_t *xArrD = (mdsdsc_a_t *)xXd.pointer; mdsdsc_a_t *yArrD = (mdsdsc_a_t *)yXd.pointer; float *y = getFloatArray(yArrD, nSamples); @@ -905,7 +1001,8 @@ return_err:; EXPORT int _GetXYSignalXd(void **const ctx, mdsdsc_t *const y, mdsdsc_t *const x, mdsdsc_t *const xmin, mdsdsc_t *const xmax, const int num, - mdsdsc_xd_t *const retXd) { + mdsdsc_xd_t *const retXd) +{ int status; void *ps = TreeCtxPush(ctx); pthread_cleanup_push(TreeCtxPop, ps); @@ -914,15 +1011,18 @@ EXPORT int _GetXYSignalXd(void **const ctx, mdsdsc_t *const y, return status; } EXPORT int GetXYWaveXd(mdsdsc_t *sig, mdsdsc_t *xmin, mdsdsc_t *xmax, int num, - mdsdsc_xd_t *retXd) { + mdsdsc_xd_t *retXd) +{ return GetXYSignalXd(sig, NULL, xmin, xmax, num, retXd); } static mdsdsc_xd_t *encodeError(const char *error, const int line, - mdsdsc_xd_t *out_xd) { + mdsdsc_xd_t *out_xd) +{ /* converts message to packed error message (float res,int len,char msg[len]) */ - typedef struct __attribute__((__packed__)) { + typedef struct __attribute__((__packed__)) + { int line; int len; char msg[0]; @@ -941,7 +1041,8 @@ static mdsdsc_xd_t *encodeError(const char *error, const int line, return out_xd; } -static mdsdsc_xd_t *getPackedDsc(mdsdsc_xd_t *retXd) { +static mdsdsc_xd_t *getPackedDsc(mdsdsc_xd_t *retXd) +{ /*Assemble result. Format: -retResolution(float) -number of samples (minumum between X and Y) @@ -951,22 +1052,28 @@ static mdsdsc_xd_t *getPackedDsc(mdsdsc_xd_t *retXd) { */ mdsdsc_t *title, *xLabel, *yLabel; mdsdsc_t const *sig = retXd->pointer; - if (sig->dtype == DTYPE_PARAM) { + if (sig->dtype == DTYPE_PARAM) + { title = ((mdsdsc_r_t *)sig)->dscptrs[1]; sig = ((mdsdsc_r_t *)sig)->dscptrs[0]; - } else + } + else title = NULL; mdsdsc_t const *dat = ((mdsdsc_r_t *)sig)->dscptrs[0]; - if (dat->dtype == DTYPE_WITH_UNITS) { + if (dat->dtype == DTYPE_WITH_UNITS) + { yLabel = ((mdsdsc_r_t *)dat)->dscptrs[1]; dat = ((mdsdsc_r_t *)dat)->dscptrs[0]; - } else + } + else yLabel = NULL; mdsdsc_t const *dim = ((mdsdsc_r_t *)sig)->dscptrs[2]; - if (dim->dtype == DTYPE_WITH_UNITS) { + if (dim->dtype == DTYPE_WITH_UNITS) + { xLabel = ((mdsdsc_r_t *)dim)->dscptrs[1]; dim = ((mdsdsc_r_t *)dim)->dscptrs[0]; - } else + } + else xLabel = NULL; float retResolution = *(float *)(((mdsdsc_r_t *)sig)->dscptrs[1]->pointer); const int retSamples = ((mdsdsc_a_t *)dat)->arsize / dat->length; @@ -995,11 +1102,13 @@ static mdsdsc_xd_t *getPackedDsc(mdsdsc_xd_t *retXd) { else retArr[8] = 3; int i, idx = 9; - for (i = 0; i < retSamples; i++, idx += sizeof(float)) { + for (i = 0; i < retSamples; i++, idx += sizeof(float)) + { SWAP32(&retArr[idx], &((float *)dat->pointer)[i]); } idx = getXArray((mdsdsc_a_t *)dim, retSamples, retArr, idx); - if (idx < 0) { + if (idx < 0) + { encodeError("Cannot Convert X data dtype", __LINE__, retXd); return retXd; } @@ -1011,7 +1120,8 @@ static mdsdsc_xd_t *getPackedDsc(mdsdsc_xd_t *retXd) { } EXPORT mdsdsc_xd_t *GetXYSignal(char *inY, char *inX, float *inXMin, - float *inXMax, int *reqNSamples) { + float *inXMax, int *reqNSamples) +{ static EMPTYXD(retXd); const size_t len = strlen(inY); // printf("GET XY SIGNAL %s xmin: %f xmax: %f Req samples: %d \n", inY, @@ -1027,23 +1137,25 @@ EXPORT mdsdsc_xd_t *GetXYSignal(char *inY, char *inX, float *inXMin, mdsdsc_t expY = {len, DTYPE_T, CLASS_S, inY}; status = TdiCompile(&expY, &yXd MDS_END_ARG); } - if (STATUS_OK && inX && *inX) { + if (STATUS_OK && inX && *inX) + { mdsdsc_t expX = {strlen(inX), DTYPE_T, CLASS_S, inX}; status = TdiCompile(&expX, &xXd MDS_END_ARG); } - if - STATUS_OK status = + if (STATUS_OK) + status = GetXYSignalXd(yXd.pointer, xXd.pointer, inXMin ? &xMinD : NULL, inXMax ? &xMaxD : NULL, *reqNSamples, &retXd); MdsFree1Dx(&yXd, NULL); MdsFree1Dx(&xXd, NULL); - if - STATUS_NOT_OK return (encodeError(MdsGetMsg(status), __LINE__, &retXd)); + if (STATUS_NOT_OK) + return (encodeError(MdsGetMsg(status), __LINE__, &retXd)); return getPackedDsc(&retXd); } EXPORT mdsdsc_xd_t *GetXYSignalLongTimes(char *inY, char *inX, int64_t *inXMin, - int64_t *inXMax, int *reqNSamples) { + int64_t *inXMax, int *reqNSamples) +{ static EMPTYXD(xd); const size_t len = strlen(inY); @@ -1057,22 +1169,24 @@ EXPORT mdsdsc_xd_t *GetXYSignalLongTimes(char *inY, char *inX, int64_t *inXMin, mdsdsc_t expY = {len, DTYPE_T, CLASS_S, inY}; status = TdiCompile(&expY, &yXd MDS_END_ARG); } - if (STATUS_OK && inX && *inX) { + if (STATUS_OK && inX && *inX) + { mdsdsc_t expX = {strlen(inX), DTYPE_T, CLASS_S, inX}; status = TdiCompile(&expX, &xd MDS_END_ARG); } - if - STATUS_OK status = + if (STATUS_OK) + status = GetXYSignalXd(yXd.pointer, xd.pointer, inXMin ? &xMinD : NULL, inXMax ? &xMaxD : NULL, *reqNSamples, &xd); MdsFree1Dx(&yXd, NULL); - if - STATUS_NOT_OK return (encodeError(MdsGetMsg(status), __LINE__, &xd)); + if (STATUS_NOT_OK) + return (encodeError(MdsGetMsg(status), __LINE__, &xd)); return getPackedDsc(&xd); } EXPORT mdsdsc_xd_t *GetXYWave(char *inY, float *inXMin, float *inXMax, - int *reqNSamples) { + int *reqNSamples) +{ static EMPTYXD(xd); const size_t len = strlen(inY); if (len == 0) @@ -1084,16 +1198,17 @@ EXPORT mdsdsc_xd_t *GetXYWave(char *inY, float *inXMin, float *inXMax, mdsdsc_t expY = {len, DTYPE_T, CLASS_S, inY}; status = TdiCompile(&expY, &xd MDS_END_ARG); } - if - STATUS_OK status = GetXYSignalXd(xd.pointer, NULL, inXMin ? &xMinD : NULL, - inXMax ? &xMaxD : NULL, *reqNSamples, &xd); - if - STATUS_NOT_OK return (encodeError(MdsGetMsg(status), __LINE__, &xd)); + if (STATUS_OK) + status = GetXYSignalXd(xd.pointer, NULL, inXMin ? &xMinD : NULL, + inXMax ? &xMaxD : NULL, *reqNSamples, &xd); + if (STATUS_NOT_OK) + return (encodeError(MdsGetMsg(status), __LINE__, &xd)); return &xd; } EXPORT mdsdsc_xd_t *GetXYWaveLongTimes(char *inY, int64_t *inXMin, - int64_t *inXMax, int *reqNSamples) { + int64_t *inXMax, int *reqNSamples) +{ static EMPTYXD(xd); const size_t len = strlen(inY); if (len == 0) @@ -1105,10 +1220,10 @@ EXPORT mdsdsc_xd_t *GetXYWaveLongTimes(char *inY, int64_t *inXMin, mdsdsc_t expY = {len, DTYPE_T, CLASS_S, inY}; status = TdiCompile(&expY, &xd MDS_END_ARG); } - if - STATUS_OK status = GetXYSignalXd(xd.pointer, NULL, inXMin ? &xMinD : NULL, - inXMax ? &xMaxD : NULL, *reqNSamples, &xd); - if - STATUS_NOT_OK return (encodeError(MdsGetMsg(status), __LINE__, &xd)); + if (STATUS_OK) + status = GetXYSignalXd(xd.pointer, NULL, inXMin ? &xMinD : NULL, + inXMax ? &xMaxD : NULL, *reqNSamples, &xd); + if (STATUS_NOT_OK) + return (encodeError(MdsGetMsg(status), __LINE__, &xd)); return &xd; } diff --git a/mdsmisc/bessel.c b/mdsmisc/bessel.c index 0f33a9f994..b29584ab14 100644 --- a/mdsmisc/bessel.c +++ b/mdsmisc/bessel.c @@ -183,7 +183,8 @@ static int ConvertCoord(float x, float y, float *out_r, float *out_theta) } */ -EXPORT double BessJ0(double x) { +EXPORT double BessJ0(double x) +{ double result, y, ax, z, xx; static double p1 = 1., p2 = -0.1098628627E-2, p3 = 0.2734510407E-4, p4 = -0.2073370639E-5, p5 = 0.2093887211E-6, @@ -195,11 +196,14 @@ EXPORT double BessJ0(double x) { s3 = 9494680.718, s4 = 59272.64853, s5 = 267.8532712, s6 = 1.; ax = fabs(x); - if (ax < 8.) { + if (ax < 8.) + { y = x * x; result = (r1 + y * (r2 + y * (r3 + y * (r4 + y * (r5 + y * r6))))) / (s1 + y * (s2 + y * (s3 + y * (s4 + y * (s5 + y * s6))))); - } else { + } + else + { z = 8 / ax; y = z * z; xx = ax - 0.785398164; @@ -210,7 +214,8 @@ EXPORT double BessJ0(double x) { return result; } -EXPORT double BessJ1(double x) { +EXPORT double BessJ1(double x) +{ double result, y, ax, z, xx; static double r1 = 72362614232., r2 = -7895059235., r3 = 242396853.1, r4 = -2972611.439, r5 = 15704.48260, r6 = -30.16036606, @@ -221,11 +226,14 @@ EXPORT double BessJ1(double x) { q3 = 0.8449199096E-5, q4 = -0.88228987E-6, q5 = 0.105787412E-6; ax = fabs(x); - if (ax < 8) { + if (ax < 8) + { y = x * x; result = x * (r1 + y * (r2 + y * (r3 + y * (r4 + y * (r5 + y * r6))))) / (s1 + y * (s2 + y * (s3 + y * (s4 + y * (s5 + y * s6))))); - } else { + } + else + { z = 8 / ax; y = z * z; xx = ax - 2.356194491; @@ -238,13 +246,15 @@ EXPORT double BessJ1(double x) { return result; } -EXPORT double BessJn(int n, double x) { +EXPORT double BessJn(int n, double x) +{ int iacc = 40; static double bigno = 1E10, bigni = 1E-10; double ax, tox, bjm, bj, bjp, jsum, sum, bessj; int j, m; - if (n < 0) { + if (n < 0) + { printf("Bad n argument in BessJn"); return 0; } @@ -255,18 +265,23 @@ EXPORT double BessJn(int n, double x) { ax = fabs(x); if (ax == 0) bessj = 0; - else { - if (ax > n) { + else + { + if (ax > n) + { tox = 2 / ax; bjm = BessJ0(ax); bj = BessJ1(ax); - for (j = 1; j < n; j++) { + for (j = 1; j < n; j++) + { bjp = j * tox * bj - bjm; bjm = bj; bj = bjp; } bessj = bj; - } else { + } + else + { tox = 2 / ax; m = 2 * ((n + (int)sqrt(iacc * n)) / 2); bessj = 0; @@ -274,11 +289,13 @@ EXPORT double BessJn(int n, double x) { sum = 0; bjp = 0; bj = 1; - for (j = m; j >= 1; j--) { + for (j = m; j >= 1; j--) + { bjm = j * tox * bj - bjp; bjp = bj; bj = bjm; - if (fabs(bj) > bigno) { + if (fabs(bj) > bigno) + { bj = bj * bigni; bjp = bjp * bigni; bessj = bessj * bigni; @@ -299,7 +316,8 @@ EXPORT double BessJn(int n, double x) { return bessj; } -EXPORT double BessJnD(int n, double x) { +EXPORT double BessJnD(int n, double x) +{ /* Computes Jn'(x) using relations: 2 * Jn'(x) = Jn-1(x) - Jn+1(x) and @@ -311,7 +329,8 @@ EXPORT double BessJnD(int n, double x) { return (BessJn(n - 1, x) - BessJn(n + 1, x)) / 2; } -EXPORT void BessRoots() { +EXPORT void BessRoots() +{ char filename[256]; int idx, root_idx; FILE *fil_ptr = 0; @@ -319,26 +338,33 @@ EXPORT void BessRoots() { printf("\nComputation of Roots for Bessel functions\n\nOut File (0 for " "screen):"); - if ((scanf("%s", filename) != 1) && strcmp(filename, "0")) { - if ((fil_ptr = fopen(filename, "w")) == 0) { + if ((scanf("%s", filename) != 1) && strcmp(filename, "0")) + { + if ((fil_ptr = fopen(filename, "w")) == 0) + { printf("\nCannot open file %s\n", filename); return; } } - for (idx = 0; idx <= MAX_BESSEL_IDX; idx++) { + for (idx = 0; idx <= MAX_BESSEL_IDX; idx++) + { curr_x = 0; - for (root_idx = 0; root_idx < NUM_ROOTS; root_idx++) { + for (root_idx = 0; root_idx < NUM_ROOTS; root_idx++) + { if (idx > 0 && root_idx == 0) curr_root = 0; else curr_root = FindRoot(idx, &curr_x); - if (fil_ptr) { + if (fil_ptr) + { fprintf(fil_ptr, "%4.8f", curr_root); if (root_idx < NUM_ROOTS - 1) fprintf(fil_ptr, ", "); else fprintf(fil_ptr, "\n"); - } else { + } + else + { printf("%4.8f", curr_root); if (root_idx < NUM_ROOTS - 1) printf(", "); @@ -349,11 +375,13 @@ EXPORT void BessRoots() { } } -static double FindRoot(int n, double *x) { +static double FindRoot(int n, double *x) +{ double y1, y2, curr_x, result; curr_x = *x; - do { + do + { curr_x += STEP_ROOT; y1 = BessJn(n, curr_x); y2 = BessJn(n, curr_x + STEP_ROOT); @@ -363,12 +391,14 @@ static double FindRoot(int n, double *x) { return result; } -static double Bisection(int n, double x1, double x2, double y1, double y2) { +static double Bisection(int n, double x1, double x2, double y1, double y2) +{ double x, y; x = (x1 + x2) / 2; if ((x2 - x1) < TOLERANCE) return x; - else { + else + { y = BessJn(n, x); if (SameSign(y1, y)) return Bisection(n, x, x2, y, y2); @@ -378,7 +408,8 @@ static double Bisection(int n, double x1, double x2, double y1, double y2) { } EXPORT double **Bessel(int mc_max, int ms_max, int l_max, int num_chords, - double *p, double *fi) { + double *p, double *fi) +{ int ms, mc, l, c, num_cols, curr_col, m, n, m_max; double **w, **w_temp, inv_cos, sum, curr_val; @@ -394,13 +425,17 @@ EXPORT double **Bessel(int mc_max, int ms_max, int l_max, int num_chords, w_temp[c] = (double *)malloc((l_max + 1) * sizeof(double)); /* Compute values */ - for (c = 0; c < num_chords; c++) { + for (c = 0; c < num_chords; c++) + { /* Compute Fml(p) in temporary matrix */ inv_cos = acos(p[c]); - for (m = 0; m < m_max; m++) { - for (l = 0; l <= l_max; l++) { + for (m = 0; m < m_max; m++) + { + for (l = 0; l <= l_max; l++) + { for (sum = 0, n = 0; n < MAX_BESSEL_EXPANSION; n++) - if (n != m) { + if (n != m) + { curr_val = BessJn(n, bessel_root[m][l]) * sin(n * PI / 2 - bessel_root[m][l] * p[c]) * (sin((m + n) * inv_cos) / (m + n) + @@ -435,7 +470,8 @@ EXPORT double **Bessel(int mc_max, int ms_max, int l_max, int num_chords, } EXPORT double **BesselStartRebuild(double r, int mc_max, int ms_max, - int l_max) { + int l_max) +{ double **j_temp; int m_max, m, l; @@ -455,7 +491,8 @@ EXPORT double **BesselStartRebuild(double r, int mc_max, int ms_max, EXPORT double BesselRebuildModes(double *a, int mc_max, int ms_max __attribute__((unused)), int l_max, - double **j_temp, int mode, int is_cosine) { + double **j_temp, int mode, int is_cosine) +{ double result = 0; int l, curr_idx; @@ -474,17 +511,20 @@ EXPORT double BesselRebuildModes(double *a, int mc_max, EXPORT double BesselRebuild(double r __attribute__((unused)), double theta, double *a, int mc_max, int ms_max, int l_max, - double **j_temp) { + double **j_temp) +{ double result = 0, sum; int m, l, curr_idx; /* Compute emissivity */ - for (m = curr_idx = 0; m <= mc_max; m++) { + for (m = curr_idx = 0; m <= mc_max; m++) + { for (sum = 0, l = 0; l <= l_max; l++) sum += a[curr_idx++] * j_temp[m][l]; result += sum * cos(m * theta); } - for (m = 1; m <= ms_max; m++) { + for (m = 1; m <= ms_max; m++) + { for (sum = 0, l = 0; l <= l_max; l++) sum += a[curr_idx++] * j_temp[m][l]; result += sum * sin(m * theta); @@ -506,31 +546,38 @@ EXPORT void BesselEndRebuild(double **j_temp, int mc_max, int ms_max) static double bess_delay; -EXPORT Complex *BessCRoots(int n, double *g) { +EXPORT Complex *BessCRoots(int n, double *g) +{ int n_poles, i, j; Complex *poles; double a, b, c; n_poles = n; poles = (Complex *)malloc(n_poles * sizeof(Complex)); - if (n_poles % 2) { + if (n_poles % 2) + { poles[0].re = -BesselFactors[n - 1][1] / bess_delay; poles[0].im = 0; j = 2; i = 1; - } else { + } + else + { j = 0; i = 0; } - while (i < n_poles) { + while (i < n_poles) + { b = BesselFactors[n - 1][j++]; c = BesselFactors[n - 1][j++]; - if (n >= 5) { + if (n >= 5) + { c = c * c + b * b; b *= 2; } a = b * b - 4 * c; - if (a >= 0) { + if (a >= 0) + { printf("Internal error in BessCRoots\n"); exit(1); } @@ -555,22 +602,26 @@ EXPORT Filter *BessInvar(float *fp, float *fs, float *ap, float *as, float *fc, static Complex *FindBessPoles(double Wp, double Ws, double ap, double as, double fc __attribute__((unused)), int *N, - double *gain) { + double *gain) +{ double norm_wp, norm_ws; int n1, n2, n, i; norm_wp = Wp * bess_delay; norm_ws = Ws * bess_delay; - if (*N == 0) { - for (n1 = 3; n1 < 10; n1++) { + if (*N == 0) + { + for (n1 = 3; n1 < 10; n1++) + { for (i = 1; i < NUM_STEP_MAG_ATT && (norm_wp > i * 0.5); i++) ; if (MagnitudeAtt[n1 - 3][i - 1] <= ap) break; /* current value of n1 satisfies attenuation requirements */ } - for (n2 = 3; n2 < 10; n2++) { + for (n2 = 3; n2 < 10; n2++) + { for (i = 1; i < NUM_STEP_DEL_ERR && (norm_ws > i * 0.5); i++) ; if (DelayErr[n2 - 3][i - 1] <= as) @@ -578,7 +629,8 @@ static Complex *FindBessPoles(double Wp, double Ws, double ap, double as, } n = (n1 > n2) ? n1 : n2; *N = n; - } else + } + else n = *N; return BessCRoots(n, gain); } diff --git a/mdsmisc/bessel.h b/mdsmisc/bessel.h index 3d701a2863..ff4ff7bca4 100644 --- a/mdsmisc/bessel.h +++ b/mdsmisc/bessel.h @@ -61,31 +61,31 @@ static double bessel_root[MAX_BESSEL_IDX + 1][NUM_ROOTS] = { */ static double bessel_root[MAX_BESSEL_IDX + 1][NUM_ROOTS - 1] = { - {2.40482556, 5.52007811, 8.65372792, 11.79153444, 14.93091771, - 18.07106397, 21.21163663, 24.35247153, 27.49347913, 30.63460647, - 33.77582022, 36.91709835, 40.05842576, 43.19979171, 46.34118837, - 49.48260990, 52.62405184, 55.76551075, 58.90698393, 62.04846919, - 65.18996480, 68.33146933, 71.47298160, 74.61450064, 77.75602563, - 80.89755587, 84.03909078, 87.18062985, 90.32217264, 93.46371878, - 96.60526795, 99.74681986, 102.88837425, 106.02993092, 109.17148965, + {2.40482556, 5.52007811, 8.65372792, 11.79153444, 14.93091771, + 18.07106397, 21.21163663, 24.35247153, 27.49347913, 30.63460647, + 33.77582022, 36.91709835, 40.05842576, 43.19979171, 46.34118837, + 49.48260990, 52.62405184, 55.76551075, 58.90698393, 62.04846919, + 65.18996480, 68.33146933, 71.47298160, 74.61450064, 77.75602563, + 80.89755587, 84.03909078, 87.18062985, 90.32217264, 93.46371878, + 96.60526795, 99.74681986, 102.88837425, 106.02993092, 109.17148965, 112.31305028, 115.45461265, 118.59617663, 121.7377420}, - {3.83170597, 7.01558668, 10.17346813, 13.32369194, 16.47063005, - 19.61585851, 22.76008438, 25.90367209, 29.04682854, 32.18967991, - 35.33230755, 38.47476623, 41.61709422, 44.75931900, 47.90146089, - 51.04353518, 54.18555364, 57.32752544, 60.46945784, 63.61135670, - 66.75322674, 69.89507184, 73.03689522, 76.17869959, 79.32048717, - 82.46225992, 85.60401944, 88.74576714, 91.88750425, 95.02923181, - 98.17095073, 101.31266182, 104.45436579, 107.59606326, 110.73775478, + {3.83170597, 7.01558668, 10.17346813, 13.32369194, 16.47063005, + 19.61585851, 22.76008438, 25.90367209, 29.04682854, 32.18967991, + 35.33230755, 38.47476623, 41.61709422, 44.75931900, 47.90146089, + 51.04353518, 54.18555364, 57.32752544, 60.46945784, 63.61135670, + 66.75322674, 69.89507184, 73.03689522, 76.17869959, 79.32048717, + 82.46225992, 85.60401944, 88.74576714, 91.88750425, 95.02923181, + 98.17095073, 101.31266182, 104.45436579, 107.59606326, 110.73775478, 113.87944085, 117.02112190, 120.16279833, 123.30447049}, - {5.15640219, 8.41724414, 11.61984117, 14.79595178, 17.95981949, - 21.11699705, 24.27011231, 27.42057355, 30.56920449, 33.71651951, - 36.86285651, 40.00844673, 43.15345378, 46.29799668, 49.44216411, - 52.58602351, 55.72962705, 58.87301577, 62.01622236, 65.15927319, - 68.30218978, 71.44498987, 74.58768817, 77.73029706, 80.87282695, - 84.01528671, 87.15768394, 90.30002516, 93.44231602, 96.58456145, - 99.72676574, 102.86893265, 106.01106552, 109.15316729, 112.29524056, + {5.15640219, 8.41724414, 11.61984117, 14.79595178, 17.95981949, + 21.11699705, 24.27011231, 27.42057355, 30.56920449, 33.71651951, + 36.86285651, 40.00844673, 43.15345378, 46.29799668, 49.44216411, + 52.58602351, 55.72962705, 58.87301577, 62.01622236, 65.15927319, + 68.30218978, 71.44498987, 74.58768817, 77.73029706, 80.87282695, + 84.01528671, 87.15768394, 90.30002516, 93.44231602, 96.58456145, + 99.72676574, 102.86893265, 106.01106552, 109.15316729, 112.29524056, 115.43728766, 118.57931068, 121.72131148, 124.86329174}}; static double BesselFactors[10][10] = { diff --git a/mdsmisc/boxsmooth.c b/mdsmisc/boxsmooth.c index 3e579934d1..d40d042420 100644 --- a/mdsmisc/boxsmooth.c +++ b/mdsmisc/boxsmooth.c @@ -64,7 +64,8 @@ int boxsmooth(int *num, float *in, int *width, float *out) #include #include -EXPORT int boxsmooth(int *num, float *in, int *width, float *out) { +EXPORT int boxsmooth(int *num, float *in, int *width, float *out) +{ int i; int j; int w = *width; @@ -73,18 +74,22 @@ EXPORT int boxsmooth(int *num, float *in, int *width, float *out) { int *out_int = (int *)out; if (n <= 0) return 0; - if (n < w) { + if (n < w) + { memcpy(out, in, n * sizeof(float)); return 1; } w += (w % 2) ? 0 : 1; memcpy(out, in, w / 2 * sizeof(float)); - for (i = w / 2; i < n - w / 2; i++) { + for (i = w / 2; i < n - w / 2; i++) + { int div; double total = 0.; - for (div = 0, j = 0; j < w; j++) { + for (div = 0, j = 0; j < w; j++) + { int idx = i + j - w / 2; - if (in_int[idx] != 32768) { + if (in_int[idx] != 32768) + { total += in[i + j - w / 2]; div++; } diff --git a/mdsmisc/butterworth.c b/mdsmisc/butterworth.c index 332c136d09..83c4deba95 100644 --- a/mdsmisc/butterworth.c +++ b/mdsmisc/butterworth.c @@ -115,35 +115,41 @@ static Complex *FindButtwPoles(double fp, double fs, double ap, double as, double fc, int *N, double *gain); Filter *ButtwInvar(float *fp, float *fs, float *ap, float *as, float *fc, - int *out_n) { + int *out_n) +{ return Invariant(*fp, *fs, *ap, *as, *fc, out_n, FindButtwPoles); } EXPORT Filter *ButtwBilinear(float *fp, float *fs, float *ap, float *as, - float *fc, int *out_n) { + float *fc, int *out_n) +{ return Bilinear(*fp, *fs, *ap, *as, *fc, out_n, FindButtwPoles); } EXPORT Filter *ChebInvar(float *fp, float *fs, float *ap, float *as, float *fc, - int *out_n) { + int *out_n) +{ return Invariant(*fp, *fs, *ap, *as, *fc, out_n, FindChebPoles); } EXPORT Filter *ChebBilinear(float *fp, float *fs, float *ap, float *as, - float *fc, int *out_n) { + float *fc, int *out_n) +{ return Bilinear(*fp, *fs, *ap, *as, *fc, out_n, FindChebPoles); } static Complex *FindButtwPoles(double Wp, double Ws, double ap, double as, double fc __attribute__((unused)), int *N, - double *gain) { + double *gain) +{ double n_real, Wc, l10; int n, j, i; Complex *poles; l10 = log(10.); - if (*N == 0) { + if (*N == 0) + { *gain = 1; n_real = 0.5 * (log10(exp(l10 * as / 10) - 1) - log10(exp(l10 * ap / 10) - 1)) / @@ -153,24 +159,30 @@ static Complex *FindButtwPoles(double Wp, double Ws, double ap, double as, else n = n_real; Wc = exp(l10 * (log10(Wp) - log10(exp(l10 * ap / 10) - 1) / (2. * n))); - } else { + } + else + { n = *N; Wc = Wp; } /* Find poles */ poles = (Complex *)malloc(n * sizeof(Complex)); j = 0; - if (n % 2) { /* odd N */ + if (n % 2) + { /* odd N */ poles[j].re = -Wc; poles[j++].im = 0; - for (i = 1; i < (n + 1) / 2; i++) { + for (i = 1; i < (n + 1) / 2; i++) + { poles[j].re = -Wc * cos(PI * i / n); poles[j++].im = Wc * sin(PI * i / n); poles[j].re = -Wc * cos(PI * i / n); poles[j++].im = -Wc * sin(PI * i / n); } - } else /* even N */ - for (i = 0; i < n / 2; i++) { + } + else /* even N */ + for (i = 0; i < n / 2; i++) + { poles[j].re = -Wc * cos(PI * (i + 0.5) / n); poles[j++].im = Wc * sin(PI * (i + 0.5) / n); poles[j].re = -Wc * cos(PI * (i + 0.5) / n); @@ -183,7 +195,8 @@ static Complex *FindButtwPoles(double Wp, double Ws, double ap, double as, static Complex *FindChebPoles(double Wp, double Ws, double ap, double as, double fc __attribute__((unused)), int *N, - double *gain) { + double *gain) +{ double eps, Wc, alpha, a, b, l10, treshold, curr_val, angle, V, Vprev, Vnew; int n, i, j; Complex *poles; @@ -195,11 +208,13 @@ static Complex *FindChebPoles(double Wp, double Ws, double ap, double as, treshold = exp(l10 * as / 10); - if (*N == 0) { + if (*N == 0) + { n = 1; Vprev = 1; V = Ws / Wp; - do { + do + { n++; Vnew = 2 * V * Ws / Wp - Vprev; curr_val = 1 + eps * eps * Vnew * Vnew; @@ -207,7 +222,8 @@ static Complex *FindChebPoles(double Wp, double Ws, double ap, double as, V = Vnew; } while (curr_val < treshold); *N = n; - } else + } + else n = *N; alpha = 1 / eps + sqrt(1 + 1 / (eps * eps)); @@ -215,11 +231,13 @@ static Complex *FindChebPoles(double Wp, double Ws, double ap, double as, b = 0.5 * Wc * (exp(log(alpha) / n) + exp(-log(alpha) / n)); poles = (Complex *)malloc(n * sizeof(Complex)); - if (n % 2) { + if (n % 2) + { poles[0].re = -a; poles[0].im = 0; j = 1; - for (i = 1; i < (n + 1) / 2; i++) { + for (i = 1; i < (n + 1) / 2; i++) + { angle = i * PI / n; poles[j].im = -b * sin(angle); poles[j].re = -a * sqrt(1 - poles[j].im * poles[j].im / (b * b)); @@ -228,9 +246,12 @@ static Complex *FindChebPoles(double Wp, double Ws, double ap, double as, poles[j].im = -poles[j - 1].im; j++; } - } else { + } + else + { j = 0; - for (i = 0; i < n / 2; i++) { + for (i = 0; i < n / 2; i++) + { angle = (i + 0.5) * PI / n; poles[j].im = b * sin(angle); poles[j].re = -a * sqrt(1 - poles[j].im * poles[j].im / (b * b)); diff --git a/mdsmisc/bwfilter.c b/mdsmisc/bwfilter.c index 32e0a95b32..2e9df723d2 100644 --- a/mdsmisc/bwfilter.c +++ b/mdsmisc/bwfilter.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define max_order 10 EXPORT int bwfilter(float *w_cut_in, int *order_in, int *num, float *in, - float *out) { + float *out) +{ int M, N; int p, q, order = *order_in; double num_coeff, den_coeff, c[max_order + 1], d[max_order + 1]; @@ -44,7 +45,8 @@ EXPORT int bwfilter(float *w_cut_in, int *order_in, int *num, float *in, double x_current[max_order + 1], y_filtered[max_order + 1]; double sum_c, sum_d; - if (order > max_order) { + if (order > max_order) + { printf("Maximum order is 10\n"); return 0; } @@ -54,52 +56,63 @@ EXPORT int bwfilter(float *w_cut_in, int *order_in, int *num, float *in, den_coeff = -(2.0 - omega_cut) / (2.0 + omega_cut); coeff[0][0] = coeff[0][1] = 1.0; - for (p = 2; p <= order; p++) { + for (p = 2; p <= order; p++) + { coeff[1][0] = coeff[1][p] = 1.0; - for (q = 1; q <= p - 1; q++) { + for (q = 1; q <= p - 1; q++) + { coeff[1][q] = coeff[0][q] + coeff[0][q - 1]; } - for (q = 0; q <= p; q++) { + for (q = 0; q <= p; q++) + { coeff[0][q] = coeff[1][q]; } } c[0] = pow(num_coeff, (double)order); - for (q = 1; q <= order; q++) { + for (q = 1; q <= order; q++) + { c[q] = c[0] * coeff[1][q]; d[q] = pow(den_coeff, (double)q) * coeff[1][q]; } upto = M >= N ? M : N; - for (i = 0; i <= upto; i++) { + for (i = 0; i <= upto; i++) + { x_current[upto - i] = (double)in[in_idx++]; } - for (j = 1; j <= N; j++) { + for (j = 1; j <= N; j++) + { y_filtered[j] = x_current[j]; } /* Do dynamic filtering in time domain until input stream stops */ - for (out_idx = 0; out_idx < *num && in_idx < *num; out_idx++) { + for (out_idx = 0; out_idx < *num && in_idx < *num; out_idx++) + { y_filtered[0] = 0.0; sum_c = 0.0; sum_d = 0.0; - for (k = 0; k <= M; k++) { + for (k = 0; k <= M; k++) + { sum_c += c[k] * x_current[k]; } - for (j = 1; j <= N; j++) { + for (j = 1; j <= N; j++) + { sum_d += -d[j] * y_filtered[j]; } y_filtered[0] = sum_c + sum_d; out[out_idx] = (float)y_filtered[0]; - for (i = M; i >= 1; i--) { + for (i = M; i >= 1; i--) + { x_current[i] = x_current[i - 1]; } - for (j = N - 1; j > 1; j--) { + for (j = N - 1; j > 1; j--) + { y_filtered[j + 1] = y_filtered[j]; } diff --git a/mdsmisc/complex.c b/mdsmisc/complex.c index 450def86af..8b5ac41c81 100644 --- a/mdsmisc/complex.c +++ b/mdsmisc/complex.c @@ -40,7 +40,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -EXPORT Complex AddC(Complex c1, Complex c2) { +EXPORT Complex AddC(Complex c1, Complex c2) +{ // This ckeck is required to avoid floating point underflow!! if (fabs(c1.re) < 1E-30) c1.re = 0; @@ -56,7 +57,8 @@ EXPORT Complex AddC(Complex c1, Complex c2) { return ris; } -EXPORT Complex SubC(Complex c1, Complex c2) { +EXPORT Complex SubC(Complex c1, Complex c2) +{ Complex ris; // This ckeck is required to avoid floating point underflow!! if (fabs(c1.re) < 1E-30) @@ -72,7 +74,8 @@ EXPORT Complex SubC(Complex c1, Complex c2) { return ris; } -EXPORT Complex MulC(Complex c1, Complex c2) { +EXPORT Complex MulC(Complex c1, Complex c2) +{ Complex ris; // This ckeck is required to avoid floating point underflow!! @@ -90,7 +93,8 @@ EXPORT Complex MulC(Complex c1, Complex c2) { return ris; } -EXPORT Complex DivC(Complex c1, Complex c2) { +EXPORT Complex DivC(Complex c1, Complex c2) +{ Complex ris; double den; // This ckeck is required to avoid floating point underflow!! @@ -103,7 +107,8 @@ EXPORT Complex DivC(Complex c1, Complex c2) { if (fabs(c2.im) < 1E-30) c2.im = 0; den = c2.re * c2.re + c2.im * c2.im; - if (den == 0) { + if (den == 0) + { printf("DivC: division by Zero\n"); exit(1); } @@ -113,7 +118,8 @@ EXPORT Complex DivC(Complex c1, Complex c2) { return ris; } -EXPORT Complex ExpC(Complex c) { +EXPORT Complex ExpC(Complex c) +{ Complex ris; // This ckeck is required to avoid floating point underflow!! if (fabs(c.re) < 1E-30) @@ -125,7 +131,8 @@ EXPORT Complex ExpC(Complex c) { return ris; } -EXPORT double Mod2(Complex c) { +EXPORT double Mod2(Complex c) +{ // This ckeck is required to avoid floating point underflow!! if (fabs(c.re) < 1E-30) c.re = 0; diff --git a/mdsmisc/complex.h b/mdsmisc/complex.h index 6342b30051..7770e27ccb 100644 --- a/mdsmisc/complex.h +++ b/mdsmisc/complex.h @@ -14,7 +14,8 @@ #define COMPLEX_H #define PI 3.1415926535898 -typedef struct { +typedef struct +{ double re; double im; } Complex; diff --git a/mdsmisc/fformat.c b/mdsmisc/fformat.c index 03366467e6..0c932e3ed7 100644 --- a/mdsmisc/fformat.c +++ b/mdsmisc/fformat.c @@ -25,7 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -EXPORT struct descriptor *fformat(double *f, int *width, int *precision) { +EXPORT struct descriptor *fformat(double *f, int *width, int *precision) +{ static char c[1024]; static struct descriptor d = {0, DTYPE_T, CLASS_S, c}; d.length = sprintf(c, "%*.*f", *width, *precision, *f); diff --git a/mdsmisc/filter.c b/mdsmisc/filter.c index cac42cbd2f..7fedf959c2 100644 --- a/mdsmisc/filter.c +++ b/mdsmisc/filter.c @@ -109,7 +109,8 @@ structure filter. module and phase must be already allocated static void NormalizeFilter(Filter *filter); -EXPORT void DoFilter(Filter *filter, float *in, float *out, int *n_s) { +EXPORT void DoFilter(Filter *filter, float *in, float *out, int *n_s) +{ int start_idx = 0, delta_idx = 1, out_s; out_s = *n_s; DoFilterResample(filter, in, out, n_s, &start_idx, &delta_idx, &out_s); @@ -117,7 +118,8 @@ EXPORT void DoFilter(Filter *filter, float *in, float *out, int *n_s) { EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, int *start_idx, int *delta_idx, - int *max_out_samples) { + int *max_out_samples) +{ int i, j, curr_sample, k_num, k_den, n_samples, start, delta, *curr_idx, out_idx, idx; float **history, *curr_out; @@ -134,8 +136,10 @@ EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, curr_idx = (int *)malloc(filter->num_parallels * sizeof(int)); curr_out = (float *)malloc(filter->num_parallels * sizeof(float)); - for (i = 0; i < filter->num_parallels; i++) { - if (filter->units[i].den_degree > 1) { + for (i = 0; i < filter->num_parallels; i++) + { + if (filter->units[i].den_degree > 1) + { history[i] = (float *)calloc(filter->units[i].den_degree * sizeof(float), 1); curr_idx[i] = filter->units[i].den_degree - 1; @@ -143,8 +147,10 @@ EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, } for (curr_sample = 0; curr_sample < n_samples && out_idx < *max_out_samples; - curr_sample++) { - for (i = 0; i < filter->num_parallels; i++) { + curr_sample++) + { + for (i = 0; i < filter->num_parallels; i++) + { curr_out[i] = 0; if (curr_sample + 1 >= filter->units[i].num_degree) k_num = filter->units[i].num_degree; @@ -156,14 +162,16 @@ EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, k_den = curr_sample + 1; for (j = 0; j < k_num; j++) curr_out[i] += filter->units[i].num[j] * in[curr_sample - j]; - for (j = 1; j < k_den; j++) { + for (j = 1; j < k_den; j++) + { idx = (curr_idx[i] - 1 + j) % filter->units[i].den_degree; curr_out[i] -= filter->units[i].den[j] * history[i][idx]; } /* Update history */ /* move marker in circolar buffer */ - if (filter->units[i].den_degree > 1) { + if (filter->units[i].den_degree > 1) + { curr_idx[i]--; if (curr_idx[i] < 0) curr_idx[i] = filter->units[i].den_degree - 1; @@ -172,7 +180,8 @@ EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, } /* store sample in out if needed */ - if (curr_sample >= start && !((curr_sample - start) % delta)) { + if (curr_sample >= start && !((curr_sample - start) % delta)) + { for (i = 0, out[out_idx] = 0; i < filter->num_parallels; i++) out[out_idx] += curr_out[i]; out_idx++; @@ -196,7 +205,8 @@ EXPORT void DoFilterResample(Filter *filter, float *in, float *out, int *n_s, EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, int *start_idx, int *delta_idx, - int *max_out_samples, int step_raw) { + int *max_out_samples, int step_raw) +{ int i, j, k, curr_sample, k_num, k_den, n_samples, start, delta, *curr_idx, out_idx, idx; float **history, *curr_out; @@ -213,8 +223,10 @@ EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, curr_idx = (int *)malloc(filter->num_parallels * sizeof(int)); curr_out = (float *)malloc(filter->num_parallels * sizeof(float)); - for (i = 0; i < filter->num_parallels; i++) { - if (filter->units[i].den_degree > 1) { + for (i = 0; i < filter->num_parallels; i++) + { + if (filter->units[i].den_degree > 1) + { history[i] = (float *)calloc(filter->units[i].den_degree * sizeof(float), 1); curr_idx[i] = filter->units[i].den_degree - 1; @@ -222,8 +234,10 @@ EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, } for (curr_sample = 0; curr_sample < n_samples && out_idx < *max_out_samples; - curr_sample += step_raw) { - for (i = 0; i < filter->num_parallels; i++) { + curr_sample += step_raw) + { + for (i = 0; i < filter->num_parallels; i++) + { curr_out[i] = 0; if (curr_sample / step_raw + 1 >= filter->units[i].num_degree) k_num = filter->units[i].num_degree; @@ -235,14 +249,16 @@ EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, k_den = curr_sample / step_raw + 1; for (j = k = 0; k < k_num; j += step_raw, k++) curr_out[i] += filter->units[i].num[k] * in[curr_sample - j]; - for (j = 1; j < k_den; j++) { + for (j = 1; j < k_den; j++) + { idx = (curr_idx[i] - 1 + j) % filter->units[i].den_degree; curr_out[i] -= filter->units[i].den[j] * history[i][idx]; } /* Update history */ /* move marker in circolar buffer */ - if (filter->units[i].den_degree > 1) { + if (filter->units[i].den_degree > 1) + { curr_idx[i]--; if (curr_idx[i] < 0) curr_idx[i] = filter->units[i].den_degree - 1; @@ -251,7 +267,8 @@ EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, } /* store sample in out if needed */ - if (curr_sample >= start && !((curr_sample - start) % delta)) { + if (curr_sample >= start && !((curr_sample - start) % delta)) + { for (i = 0, out[out_idx] = 0; i < filter->num_parallels; i++) out[out_idx] += curr_out[i]; out_idx++; @@ -273,7 +290,8 @@ EXPORT void DoFilterResampleVME(Filter *filter, short *in, float *out, int *n_s, } EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, - float *phase) { + float *phase) +{ float curr_f, step_f; int i, j, k, idx; Complex curr_fc, curr_c, curr_fac, curr_num, curr_den, curr_z; @@ -282,13 +300,16 @@ EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, NormalizeFilter(filter); step_f = fc / (2 * (n_points + 1)); - for (curr_f = step_f, idx = 0; idx < n_points; idx++, curr_f += step_f) { + for (curr_f = step_f, idx = 0; idx < n_points; idx++, curr_f += step_f) + { curr_fc.re = cos(2 * PI * curr_f / fc); curr_fc.im = sin(2 * PI * curr_f / fc); curr_z.im = curr_z.re = 0; - for (i = 0; i < filter->num_parallels; i++) { + for (i = 0; i < filter->num_parallels; i++) + { curr_num.re = curr_num.im = 0; - for (j = 0; j < filter->units[i].num_degree; j++) { + for (j = 0; j < filter->units[i].num_degree; j++) + { curr_c.re = 1; curr_c.im = 0; curr_fac.im = 0; @@ -298,7 +319,8 @@ EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, curr_num = AddC(curr_num, MulC(curr_c, curr_fac)); } curr_den.re = curr_den.im = 0; - for (j = 0; j < filter->units[i].den_degree; j++) { + for (j = 0; j < filter->units[i].den_degree; j++) + { curr_c.re = 1; curr_c.im = 0; curr_fac.im = 0; @@ -319,12 +341,14 @@ EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, curr_z.re = 0; if (fabs(curr_z.im) < 1E-10) curr_z.im = 0; - if (curr_z.re == 0 && curr_z.im == 0) { + if (curr_z.re == 0 && curr_z.im == 0) + { phase[idx] = 0; continue; } - if (curr_z.re < 0) { + if (curr_z.re < 0) + { if (curr_z.im >= 0) if (fabs(curr_z.re) > fabs(curr_z.im)) phase[idx] = PI + atan(curr_z.im / curr_z.re); @@ -334,7 +358,9 @@ EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, phase[idx] = PI + atan(curr_z.im / curr_z.re); else phase[idx] = 3 * PI / 2 - atan(curr_z.re / curr_z.im); - } else { /* curr_z.re > 0 */ + } + else + { /* curr_z.re > 0 */ if (curr_z.im >= 0) if (fabs(curr_z.re) > fabs(curr_z.im)) @@ -350,10 +376,12 @@ EXPORT void TestFilter(Filter *filter, float fc, int n_points, float *module, } } -EXPORT void FreeFilter(Filter *filter) { +EXPORT void FreeFilter(Filter *filter) +{ int i; - for (i = 0; i < filter->num_parallels; i++) { + for (i = 0; i < filter->num_parallels; i++) + { free(filter->units[i].num); if (filter->units[i].den_degree) free(filter->units[i].den); @@ -362,11 +390,14 @@ EXPORT void FreeFilter(Filter *filter) { free(filter); } -static void NormalizeFilter(Filter *filter) { +static void NormalizeFilter(Filter *filter) +{ int i, j; - for (i = 0; i < filter->num_parallels; i++) { - if (filter->units[i].den_degree > 0) { + for (i = 0; i < filter->num_parallels; i++) + { + if (filter->units[i].den_degree > 0) + { for (j = 0; j < filter->units[i].num_degree; j++) filter->units[i].num[j] /= filter->units[i].den[0]; for (j = 1; j < filter->units[i].den_degree; j++) @@ -377,7 +408,8 @@ static void NormalizeFilter(Filter *filter) { } // Prepare the description of a butterworth -EXPORT Filter *prepareFilter(float cutFreq, float samplingFreq, int numPoles) { +EXPORT Filter *prepareFilter(float cutFreq, float samplingFreq, int numPoles) +{ Filter *outFilter; float zero = 0; outFilter = (Filter *)ButtwInvar(&cutFreq, &zero, &zero, &zero, &samplingFreq, @@ -390,7 +422,8 @@ EXPORT Filter *prepareFilter(float cutFreq, float samplingFreq, int numPoles) { // *out_n); // Initialize then data structures whichb are required for real-time filtering -EXPORT void initializeRunTimeFilter(RunTimeFilter *rtf) { +EXPORT void initializeRunTimeFilter(RunTimeFilter *rtf) +{ RunTimeFilter *runTimeFilter = (RunTimeFilter *)rtf; memset(runTimeFilter->oldX, 0, MAX_FILTER_BUF * sizeof(double)); memset(runTimeFilter->oldY, 0, @@ -399,7 +432,8 @@ EXPORT void initializeRunTimeFilter(RunTimeFilter *rtf) { } /* Perform step filtering */ -EXPORT double getFiltered(double in, Filter *flt, RunTimeFilter *rtf) { +EXPORT double getFiltered(double in, Filter *flt, RunTimeFilter *rtf) +{ int i, j; double totOut = 0, currOut; Filter *filter = (Filter *)flt; @@ -411,16 +445,19 @@ EXPORT double getFiltered(double in, Filter *flt, RunTimeFilter *rtf) { idx = runFilter->idx; oldX = runFilter->oldX; - for (i = 0; i < filter->num_parallels; i++) { + for (i = 0; i < filter->num_parallels; i++) + { currOut = filter->units[i].num[0] * in; - for (j = 1; j < filter->units[i].num_degree; j++) { + for (j = 1; j < filter->units[i].num_degree; j++) + { currIdx = idx - j; if (currIdx < 0) currIdx += MAX_FILTER_BUF; currOut += filter->units[i].num[j] * oldX[currIdx]; } - for (j = 1; j < filter->units[i].den_degree; j++) { + for (j = 1; j < filter->units[i].den_degree; j++) + { currIdx = idx - j; if (currIdx < 0) currIdx += MAX_FILTER_BUF; diff --git a/mdsmisc/filter.h b/mdsmisc/filter.h index 11da18ff87..292c8cdbde 100644 --- a/mdsmisc/filter.h +++ b/mdsmisc/filter.h @@ -22,12 +22,14 @@ /* DEC/CMS REPLACEMENT HISTORY, Element FILTER.H */ #include "complex.h" -typedef struct { +typedef struct +{ int num_degree, den_degree; double *num, *den; } FilterUnit; -typedef struct { +typedef struct +{ int num_parallels; FilterUnit *units; } Filter; @@ -35,7 +37,8 @@ typedef struct { #define MAX_FILTER_BUF 64 #define MAX_FILTER_UNITS 16 -typedef struct { +typedef struct +{ double oldX[MAX_FILTER_BUF]; double oldY[MAX_FILTER_UNITS][MAX_FILTER_BUF]; int idx; diff --git a/mdsmisc/fir.c b/mdsmisc/fir.c index c498e0d4e1..041147a960 100644 --- a/mdsmisc/fir.c +++ b/mdsmisc/fir.c @@ -71,28 +71,34 @@ static void Hanning(double *w, int n); static void Hamming(double *w, int n); static void Blackmann(double *w, int n); -EXPORT Filter *FirRectangular(float *fc, float *s_f, int *n) { +EXPORT Filter *FirRectangular(float *fc, float *s_f, int *n) +{ return Fir(*fc, *s_f, *n, Rectangular); } -EXPORT Filter *FirBartlett(float *fc, float *s_f, int *n) { +EXPORT Filter *FirBartlett(float *fc, float *s_f, int *n) +{ return Fir(*fc, *s_f, *n, Bartlett); } -EXPORT Filter *FirHanning(float *fc, float *s_f, int *n) { +EXPORT Filter *FirHanning(float *fc, float *s_f, int *n) +{ return Fir(*fc, *s_f, *n, Hanning); } -EXPORT Filter *FirHamming(float *fc, float *s_f, int *n) { +EXPORT Filter *FirHamming(float *fc, float *s_f, int *n) +{ return Fir(*fc, *s_f, *n, Hamming); } -EXPORT Filter *FirBlackmann(float *fc, float *s_f, int *n) { +EXPORT Filter *FirBlackmann(float *fc, float *s_f, int *n) +{ return Fir(*fc, *s_f, *n, Blackmann); } static Filter *Fir(double fc, double s_f, int n, - void (*Window)(double *, int)) { + void (*Window)(double *, int)) +{ int i; Filter *filter; double *w, wc, alpha; @@ -118,13 +124,15 @@ static Filter *Fir(double fc, double s_f, int n, return filter; } -static void Rectangular(double *w, int n) { +static void Rectangular(double *w, int n) +{ int i; for (i = 0; i < n; i++) w[i] = 1; } -static void Bartlett(double *w, int n) { +static void Bartlett(double *w, int n) +{ int i; for (i = 0; i <= (n - 1) / 2; i++) w[i] = 2 * i / (double)(n - 1); @@ -132,19 +140,22 @@ static void Bartlett(double *w, int n) { w[i] = 2 - 2 * i / (double)(n - 1); } -static void Hanning(double *w, int n) { +static void Hanning(double *w, int n) +{ int i; for (i = 0; i < n; i++) w[i] = 0.5 * (1 - cos(2 * PI * i / (double)(n - 1))); } -static void Hamming(double *w, int n) { +static void Hamming(double *w, int n) +{ int i; for (i = 0; i < n; i++) w[i] = 0.54 - 0.46 * cos(2 * PI * i / (double)(n - 1)); } -static void Blackmann(double *w, int n) { +static void Blackmann(double *w, int n) +{ int i; for (i = 0; i < n; i++) w[i] = 0.42 - 0.5 * cos(2 * PI * i / (double)(n - 1)) + diff --git a/mdsmisc/getnidarray.c b/mdsmisc/getnidarray.c index aa85f3ce0d..c9bc34efaa 100644 --- a/mdsmisc/getnidarray.c +++ b/mdsmisc/getnidarray.c @@ -60,7 +60,8 @@ int GetNidArray(struct dsc$descriptor *list, int **nids, int *num_nids) extern unsigned short OpcVector; -EXPORT int GetNidArray(struct descriptor *list, int **nids, int *num_nids) { +EXPORT int GetNidArray(struct descriptor *list, int **nids, int *num_nids) +{ struct descriptor *ptr; int arg; @@ -70,12 +71,14 @@ EXPORT int GetNidArray(struct descriptor *list, int **nids, int *num_nids) { ptr = (struct descriptor *)ptr->pointer) ; if ((ptr->class == CLASS_R) && (ptr->dtype == DTYPE_FUNCTION) && - (*(unsigned short *)ptr->pointer == OpcVector)) { + (*(unsigned short *)ptr->pointer == OpcVector)) + { struct descriptor_r *r_ptr = (struct descriptor_r *)ptr; *num_nids = r_ptr->ndesc; *nids = (int *)malloc(sizeof(int) * *num_nids); nidarray = *nids; - for (arg = 0; arg < *num_nids; arg++) { + for (arg = 0; arg < *num_nids; arg++) + { struct descriptor *ptr; for (ptr = r_ptr->dscptrs[arg]; (ptr && (ptr->dtype == DTYPE_DSC)); ptr = (struct descriptor *)ptr->pointer) @@ -85,7 +88,9 @@ EXPORT int GetNidArray(struct descriptor *list, int **nids, int *num_nids) { else nidarray[arg] = 0; } - } else { + } + else + { *num_nids = 0; *nids = 0; return 0; diff --git a/mdsmisc/getreferences.c b/mdsmisc/getreferences.c index 74a272eb3e..f9903b4308 100644 --- a/mdsmisc/getreferences.c +++ b/mdsmisc/getreferences.c @@ -33,37 +33,46 @@ static void FillRefs(struct descriptor *src, int *ans, int *idx); static int GetNid(struct descriptor *dsc); static EMPTYXD(src); -EXPORT int GetReferenceCount(int *nid) { +EXPORT int GetReferenceCount(int *nid) +{ int cnt = 0; int status = TreeGetRecord(*nid, &src); - if (status & 1) { + if (status & 1) + { cnt = CountRefs((struct descriptor *)&src); } return cnt; } -EXPORT void GetReferences(int *nid __attribute__((unused)), int *ans) { +EXPORT void GetReferences(int *nid __attribute__((unused)), int *ans) +{ int idx = 0; FillRefs((struct descriptor *)&src, ans, &idx); MdsFree1Dx(&src, 0); } -static void FillRefs(struct descriptor *src, int *ans, int *idx) { +static void FillRefs(struct descriptor *src, int *ans, int *idx) +{ for (; src->dtype == DTYPE_DSC; src = (struct descriptor *)src->pointer) ; if ((src->dtype == DTYPE_NID) || (src->dtype == DTYPE_PATH)) - if (src->class == CLASS_A) { + if (src->class == CLASS_A) + { struct descriptor_a *aptr = (struct descriptor_a *)src; unsigned int i; - for (i = 0; i < aptr->arsize / aptr->length; i++) { + for (i = 0; i < aptr->arsize / aptr->length; i++) + { ans[*idx] = GetNid(((struct descriptor *)aptr->pointer) + i); (*idx)++; } - } else { + } + else + { ans[*idx] = GetNid(src); (*idx)++; } - else if (src->class == CLASS_R) { + else if (src->class == CLASS_R) + { struct descriptor_r *rptr = (struct descriptor_r *)src; int i; for (i = 0; i < rptr->ndesc; i++) @@ -71,31 +80,38 @@ static void FillRefs(struct descriptor *src, int *ans, int *idx) { } } -static int CountRefs(struct descriptor *src) { +static int CountRefs(struct descriptor *src) +{ /* remove any leading dsc descriptors */ for (; src->dtype == DTYPE_DSC; src = (struct descriptor *)src->pointer) ; if ((src->dtype == DTYPE_NID) || (src->dtype == DTYPE_PATH)) - if (src->class == CLASS_A) { + if (src->class == CLASS_A) + { struct descriptor_a *aptr = (struct descriptor_a *)src; return aptr->arsize / aptr->length; - } else + } + else return 1; - else if (src->class == CLASS_R) { + else if (src->class == CLASS_R) + { struct descriptor_r *rptr = (struct descriptor_r *)src; int count = 0; int i; for (i = 0; i < rptr->ndesc; i++) count += CountRefs(rptr->dscptrs[i]); return count; - } else + } + else return 0; } -static int GetNid(struct descriptor *dsc) { +static int GetNid(struct descriptor *dsc) +{ if (dsc->dtype == DTYPE_NID) return *(int *)dsc->pointer; - else { + else + { int ans; char *tmp = strncpy(malloc(dsc->length + 1), dsc->pointer, dsc->length); int status; diff --git a/mdsmisc/iir.c b/mdsmisc/iir.c index 258f477e6b..5c8b1a267d 100644 --- a/mdsmisc/iir.c +++ b/mdsmisc/iir.c @@ -89,7 +89,8 @@ which actually perform digital filtering. #include EXPORT Complex *FindFactors(Complex *poles, double fc, int n, - double gain __attribute__((unused))) { + double gain __attribute__((unused))) +{ int i, j; double currA; Complex *Ak; @@ -106,15 +107,19 @@ EXPORT Complex *FindFactors(Complex *poles, double fc, int n, /* Ak :denominators of single factors */ Ak = (Complex *)malloc(2 * n * sizeof(Complex)); - for (i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { Ak[i].re = 1; Ak[i].im = 0; - for (j = 0; j < n; j++) { - if (j != i) { + for (j = 0; j < n; j++) + { + if (j != i) + { Ak[i] = MulC(Ak[i], SubC(poles[i], poles[j])); } - if ((n % 2 && (j % 2 || j == 0)) || (!(n % 2) && !(j % 2))) { + if ((n % 2 && (j % 2 || j == 0)) || (!(n % 2) && !(j % 2))) + { if (j == 0 && n % 2) currA = -poles[j].re; else @@ -131,7 +136,8 @@ EXPORT Complex *FindFactors(Complex *poles, double fc, int n, } EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, - int *out_n, Complex *(*FindPoles)()) { + int *out_n, Complex *(*FindPoles)()) +{ Complex *poles, *Ak, cplx1, cplx2; Filter *filter; int n, i; @@ -149,7 +155,8 @@ EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, filter = (Filter *)malloc(sizeof(Filter)); /* Allocate storage for output filter */ - if (n % 2) { + if (n % 2) + { /* If n is odd there is a real pole */ filter->num_parallels = (n + 1) / 2; filter->units = (FilterUnit *)malloc(sizeof(FilterUnit) * (n + 1) / 2); @@ -157,18 +164,21 @@ EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, filter->units[0].num = (double *)malloc(sizeof(double)); filter->units[0].den_degree = 2; filter->units[0].den = (double *)malloc(sizeof(double) * 2); - for (i = 1; i < (n + 1) / 2; i++) { /* For each pair of coniugate poles */ + for (i = 1; i < (n + 1) / 2; i++) + { /* For each pair of coniugate poles */ filter->units[i].num_degree = 2; filter->units[i].num = (double *)malloc(sizeof(double) * 2); filter->units[i].den_degree = 3; filter->units[i].den = (double *)malloc(sizeof(double) * 3); } - } else + } + else /* In n is even there are only pairs of coniugate poles */ { filter->num_parallels = n / 2; filter->units = (FilterUnit *)malloc(sizeof(FilterUnit) * n / 2); - for (i = 0; i < n / 2; i++) { /* For each pair of coniugate poles */ + for (i = 0; i < n / 2; i++) + { /* For each pair of coniugate poles */ filter->units[i].num_degree = 2; filter->units[i].num = (double *)malloc(sizeof(double) * 2); filter->units[i].den_degree = 3; @@ -177,20 +187,24 @@ EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, } /* Compute filter coefficients */ - if (n % 2) { + if (n % 2) + { filter->units[0].num[0] = 1 / Ak[0].re; filter->units[0].den[0] = 1; filter->units[0].den[1] = -exp(poles[0].re * T); - for (i = 1; i < (n + 1) / 2; i++) { + for (i = 1; i < (n + 1) / 2; i++) + { cplx1 = MulC(Ak[2 * i], Ak[2 * i - 1]); cplx2 = AddC(Ak[2 * i], Ak[2 * i - 1]); - if (fabs(cplx1.im) > 1E-4 || fabs(cplx2.im) > 1E-4) { /* Must be real */ + if (fabs(cplx1.im) > 1E-4 || fabs(cplx2.im) > 1E-4) + { /* Must be real */ printf("\nInternal error in Invariant conversion"); } filter->units[i].num[0] = cplx2.re / cplx1.re; cplx2 = AddC(MulC(Ak[2 * i], ExpC(MulC(Tc, poles[2 * i]))), MulC(Ak[2 * i - 1], ExpC(MulC(Tc, poles[2 * i - 1])))); - if (fabs(cplx2.im) > 1E-4) { /* Must be real */ + if (fabs(cplx2.im) > 1E-4) + { /* Must be real */ printf("\nInternal error in Invariant conversion"); } filter->units[i].num[1] = -cplx2.re / cplx1.re; @@ -200,17 +214,21 @@ EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, -2 * exp(poles[2 * i].re * T) * cos(poles[2 * i].im * T); filter->units[i].den[2] = exp(2 * poles[2 * i].re * T); } - } else /* n even */ - for (i = 0; i < n / 2; i++) { + } + else /* n even */ + for (i = 0; i < n / 2; i++) + { cplx1 = MulC(Ak[2 * i], Ak[2 * i + 1]); cplx2 = AddC(Ak[2 * i], Ak[2 * i + 1]); - if (fabs(cplx1.im) > 1E-4 || fabs(cplx2.im) > 1E-4) { /* Must be real */ + if (fabs(cplx1.im) > 1E-4 || fabs(cplx2.im) > 1E-4) + { /* Must be real */ printf("\nInternal error in Invariant conversion"); } filter->units[i].num[0] = cplx2.re / cplx1.re; cplx2 = AddC(MulC(Ak[2 * i], ExpC(MulC(Tc, poles[2 * i]))), MulC(Ak[2 * i + 1], ExpC(MulC(Tc, poles[2 * i + 1])))); - if (fabs(cplx2.im) > 1E-4) { /* Must be real */ + if (fabs(cplx2.im) > 1E-4) + { /* Must be real */ printf("\nInternal error in Invariant conversion"); } filter->units[i].num[1] = -cplx2.re / cplx1.re; @@ -226,7 +244,8 @@ EXPORT Filter *Invariant(double fp, double fs, double ap, double as, double fc, } EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, - int *out_n, Complex *(*FindPoles)()) { + int *out_n, Complex *(*FindPoles)()) +{ Complex *poles, *Ak, cplx; Filter *filter; int n, i; @@ -248,13 +267,15 @@ EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, Ak = FindFactors( poles, fc, n, gain); /* Remind that 1/Ak are normalized such that H(0) = T */ - for (i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { Ak[i].re *= T; Ak[i].im *= T; } filter = (Filter *)malloc(sizeof(Filter)); /* Allocate storage for output filter */ - if (n % 2) { + if (n % 2) + { /* If n is odd there is a real pole */ filter->num_parallels = (n + 1) / 2; filter->units = (FilterUnit *)malloc(sizeof(FilterUnit) * (n + 1) / 2); @@ -262,18 +283,21 @@ EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, filter->units[0].num = (double *)malloc(sizeof(double) * 2); filter->units[0].den_degree = 2; filter->units[0].den = (double *)malloc(sizeof(double) * 2); - for (i = 1; i < (n + 1) / 2; i++) { /* For each pair of coniugate poles */ + for (i = 1; i < (n + 1) / 2; i++) + { /* For each pair of coniugate poles */ filter->units[i].num_degree = 3; filter->units[i].num = (double *)malloc(sizeof(double) * 3); filter->units[i].den_degree = 3; filter->units[i].den = (double *)malloc(sizeof(double) * 3); } - } else + } + else /* In n is even there are only pairs of coniugate poles */ { filter->num_parallels = n / 2; filter->units = (FilterUnit *)malloc(sizeof(FilterUnit) * n / 2); - for (i = 0; i < n / 2; i++) { /* For each pair of coniugate poles */ + for (i = 0; i < n / 2; i++) + { /* For each pair of coniugate poles */ filter->units[i].num_degree = 3; filter->units[i].num = (double *)malloc(sizeof(double) * 3); filter->units[i].den_degree = 3; @@ -282,13 +306,15 @@ EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, } /* Compute filter coefficients */ - if (n % 2) { + if (n % 2) + { filter->units[0].num[0] = filter->units[0].num[1] = T2 / Ak[0].re; filter->units[0].den[0] = 1 - poles[0].re * T2; filter->units[0].den[1] = -1 - poles[0].re * T2; T2c.re = T2; T2c.im = 0; - for (i = 1; i < (n + 1) / 2; i++) { + for (i = 1; i < (n + 1) / 2; i++) + { Ac = DivC(T2c, Ak[2 * i]); A1c = DivC(T2c, Ak[2 * i - 1]); ac.re = 1 - poles[2 * i].re * T2; @@ -300,47 +326,56 @@ EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, b1c.re = 1 + poles[2 * i - 1].re * T2; b1c.im = poles[2 * i - 1].im * T2; cplx = AddC(MulC(A1c, ac), MulC(Ac, a1c)); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[0] = cplx.re; cplx = SubC(AddC(MulC(A1c, ac), MulC(Ac, a1c)), AddC(MulC(A1c, bc), MulC(Ac, b1c))); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[1] = cplx.re; cplx = AddC(MulC(A1c, bc), MulC(Ac, b1c)); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[2] = -cplx.re; cplx = MulC(ac, a1c); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[0] = cplx.re; cplx = AddC(MulC(a1c, bc), MulC(b1c, ac)); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[1] = -cplx.re; cplx = MulC(bc, b1c); - if (fabs(cplx.im) > 1E-4) { + if (fabs(cplx.im) > 1E-4) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[2] = cplx.re; } - } else { /* n even */ + } + else + { /* n even */ T2c.re = T2; T2c.im = 0; - for (i = 0; i < n / 2; i++) { + for (i = 0; i < n / 2; i++) + { Ac = DivC(T2c, Ak[2 * i]); A1c = DivC(T2c, Ak[2 * i + 1]); ac.re = 1 - poles[2 * i].re * T2; @@ -352,38 +387,44 @@ EXPORT Filter *Bilinear(double fp, double fs, double ap, double as, double fc, b1c.re = 1 + poles[2 * i + 1].re * T2; b1c.im = poles[2 * i + 1].im * T2; cplx = AddC(MulC(A1c, ac), MulC(Ac, a1c)); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[0] = cplx.re; cplx = SubC(AddC(MulC(A1c, ac), MulC(Ac, a1c)), AddC(MulC(A1c, bc), MulC(Ac, b1c))); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[1] = cplx.re; cplx = AddC(MulC(A1c, bc), MulC(Ac, b1c)); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].num[2] = -cplx.re; cplx = MulC(ac, a1c); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[0] = cplx.re; cplx = AddC(MulC(a1c, bc), MulC(b1c, ac)); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[1] = -cplx.re; cplx = MulC(bc, b1c); - if (fabs(cplx.im) > 1E-5) { + if (fabs(cplx.im) > 1E-5) + { printf("\nInternal error in Bilinear conversion"); } filter->units[i].den[2] = cplx.re; diff --git a/mdsmisc/resample.c b/mdsmisc/resample.c index def5c06fbb..f451fee3d4 100644 --- a/mdsmisc/resample.c +++ b/mdsmisc/resample.c @@ -65,19 +65,21 @@ extern int TdiDimOf(); struct descriptor *Resample(struct descriptor *in_sig, struct descriptor *in_x); EXPORT struct descriptor *resample(struct descriptor *in_sig, - struct descriptor *in_x) { + struct descriptor *in_x) +{ return Resample(in_sig, in_x); } EXPORT struct descriptor *Resample(struct descriptor *in_sig, - struct descriptor *in_x) { + struct descriptor *in_x) +{ -#define return_on_error(func, error) \ - if (!((status = func) & 1)) \ +#define return_on_error(func, error) \ + if (!((status = func) & 1)) \ return error //#define interp(x1,y1,x2,y2,x) (((y2)-(y1))/((x2)-(x1)) * (x) + //(((y1)*(x2))-((y2)*(x1)))/((x2)-(x1))) -#define interp(x1, y1, x2, y2, x) \ +#define interp(x1, y1, x2, y2, x) \ (y1) + ((y2) - (y1)) / ((x2) - (x1)) * ((x) - (x1)) int status; @@ -147,12 +149,14 @@ EXPORT struct descriptor *Resample(struct descriptor *in_sig, if (!sig_elements || ((unsigned)sig_elements > (sig_x->arsize / sig_x->length))) return (struct descriptor *)&bad_sig_in; - for (i = 0; i < new_elements; i++) { + for (i = 0; i < new_elements; i++) + { if (new_x_f[i] <= sig_x_f[0]) new_y_f[i] = sig_y_f[0]; else if (new_x_f[i] >= sig_x_f[sig_elements - 1]) new_y_f[i] = sig_y_f[sig_elements - 1]; - else { + else + { for (; j < sig_elements; j++) if (new_x_f[i] <= sig_x_f[j]) break; diff --git a/mdsmisc/step_resample.c b/mdsmisc/step_resample.c index 02af919e33..377019c996 100644 --- a/mdsmisc/step_resample.c +++ b/mdsmisc/step_resample.c @@ -65,10 +65,11 @@ extern int TdiDimOf(); extern int TdiCvt(); EXPORT struct descriptor *StepResample(struct descriptor *in_sig, - struct descriptor *in_x) { + struct descriptor *in_x) +{ -#define return_on_error(func) \ - if (!((status = func) & 1)) \ +#define return_on_error(func) \ + if (!((status = func) & 1)) \ return (struct descriptor *)&emptyxd; int status; @@ -133,12 +134,14 @@ EXPORT struct descriptor *StepResample(struct descriptor *in_sig, if (!sig_elements || (sig_elements != (int)(sig_x->arsize / sig_x->length))) return 0; sig_y_b[sig_elements - 1] = sig_y_b[sig_elements - 2]; - for (i = 0; i < new_elements; i++) { + for (i = 0; i < new_elements; i++) + { if (new_x_f[i] <= sig_x_f[0]) new_y_b[i] = 0; else if (new_x_f[i] >= sig_x_f[sig_elements - 1]) new_y_b[i] = 0; - else { + else + { for (; j < sig_elements; j++) if (new_x_f[i] < sig_x_f[j]) break; diff --git a/mdsmisc/whoami.c b/mdsmisc/whoami.c index 47cbafc263..a7f89d1b50 100644 --- a/mdsmisc/whoami.c +++ b/mdsmisc/whoami.c @@ -29,7 +29,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -EXPORT struct descriptor *whoami() { +EXPORT struct descriptor *whoami() +{ static struct descriptor ans = {0, DTYPE_T, CLASS_S, 0}; GETUSERNAME_BEGIN(ans.pointer); ans.length = (unsigned short)strlen(ans.pointer); diff --git a/mdsobjects/cpp/mdsdata.c b/mdsobjects/cpp/mdsdata.c index fc0dbb8d5a..92287811d8 100644 --- a/mdsobjects/cpp/mdsdata.c +++ b/mdsobjects/cpp/mdsdata.c @@ -69,7 +69,8 @@ extern void convertTimeToAscii(int64_t *timePtr, char *dateBuf, int bufLen, extern void *getManyObj(char *serializedIn); extern void *putManyObj(char *serializedIn); -void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr) { +void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr) +{ EMPTYXD(emptyXd); int status; struct descriptor dsc; @@ -83,7 +84,8 @@ void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr) { dsc.length = length; dsc.pointer = ptr; status = MdsCopyDxXd(&dsc, xdPtr); - if (!(status & 1)) { + if (!(status & 1)) + { printf("PANIC in convertToScalarDsc: MdsCopyDxXd failed\n"); exit(0); } @@ -91,7 +93,8 @@ void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr) { } void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, - int *dims, void *ptr) { + int *dims, void *ptr) +{ EMPTYXD(emptyXd); int status, i; DESCRIPTOR_A(arr1Dsc, length, dtype, ptr, arsize); @@ -100,10 +103,12 @@ void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); *xdPtr = emptyXd; - if (nDims == 1) { + if (nDims == 1) + { arr1Dsc.class = clazz; status = MdsCopyDxXd((struct descriptor *)&arr1Dsc, xdPtr); - if (!(status & 1)) { + if (!(status & 1)) + { printf("PANIC in convertToArrayDsc: MdsCopyDxXd failed: %s\n", MdsGetMsg(status)); exit(0); @@ -116,7 +121,8 @@ void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, arrNDsc.pointer = ptr; status = MdsCopyDxXd((struct descriptor *)&arrNDsc, xdPtr); - if (!(status & 1)) { + if (!(status & 1)) + { printf("PANIC in convertToArrayDsc: MdsCopyDxXd failed\n"); exit(0); } @@ -126,7 +132,8 @@ void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, #define MAX_ARGS 128 void *convertToCompoundDsc(int clazz __attribute__((unused)), int dtype, - int length, void *ptr, int ndescs, void **descs) { + int length, void *ptr, int ndescs, void **descs) +{ EMPTYXD(emptyXd); struct descriptor_xd *xds[MAX_ARGS]; int status, i; @@ -138,21 +145,26 @@ void *convertToCompoundDsc(int clazz __attribute__((unused)), int dtype, recDsc.length = length; recDsc.pointer = ptr; recDsc.ndesc = ndescs; - for (i = 0; i < ndescs; i++) { + for (i = 0; i < ndescs; i++) + { xds[i] = 0; - if (descs[i]) { + if (descs[i]) + { xds[i] = (struct descriptor_xd *)convertDataToDsc(descs[i]); recDsc.dscptrs[i] = xds[i]->pointer; - } else + } + else recDsc.dscptrs[i] = 0; } status = MdsCopyDxXd((struct descriptor *)&recDsc, xdPtr); - if (!(status & 1)) { + if (!(status & 1)) + { printf("PANIC in convertToCompoundDsc: MdsCopyDxXd failed\n"); exit(0); } for (i = 0; i < ndescs; i++) - if (xds[i]) { + if (xds[i]) + { MdsFree1Dx(xds[i], 0); free(xds[i]); } @@ -160,7 +172,8 @@ void *convertToCompoundDsc(int clazz __attribute__((unused)), int dtype, return xdPtr; } -void *convertToApdDsc(int type, int ndescs, void **descs) { +void *convertToApdDsc(int type, int ndescs, void **descs) +{ EMPTYXD(emptyXd); struct descriptor_xd **xds = (struct descriptor_xd **)malloc(ndescs * sizeof(struct descriptor_xd *)); @@ -172,22 +185,27 @@ void *convertToApdDsc(int type, int ndescs, void **descs) { apdDsc.dtype = type; apdDsc.arsize = ndescs * sizeof(struct descriptor *); apdDsc.pointer = malloc(ndescs * sizeof(struct descriptor *)); - for (i = 0; i < ndescs; i++) { + for (i = 0; i < ndescs; i++) + { xds[i] = 0; - if (descs[i]) { + if (descs[i]) + { xds[i] = (struct descriptor_xd *)convertDataToDsc(descs[i]); ((struct descriptor **)apdDsc.pointer)[i] = xds[i]->pointer; - } else + } + else ((struct descriptor **)apdDsc.pointer)[i] = 0; } status = MdsCopyDxXd((struct descriptor *)&apdDsc, xdPtr); - if (!(status & 1)) { + if (!(status & 1)) + { printf("PANIC in convertToApdDsc: MdsCopyDxXd failed\n"); exit(0); } free(apdDsc.pointer); for (i = 0; i < ndescs; i++) - if (xds[i]) { + if (xds[i]) + { MdsFree1Dx(xds[i], 0); free(xds[i]); } @@ -195,19 +213,23 @@ void *convertToApdDsc(int type, int ndescs, void **descs) { return xdPtr; } -void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus) { +void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus) +{ EMPTYXD(emptyXd); int status; struct descriptor_xd *xdPtr = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); *xdPtr = emptyXd; - if (isEvaluate) { + if (isEvaluate) + { if (ctx) status = _TdiEvaluate(&ctx, dscPtr, xdPtr MDS_END_ARG); else status = TdiEvaluate(dscPtr, xdPtr MDS_END_ARG); - } else { + } + else + { if (ctx) status = _TdiData(&ctx, (struct descriptor *)dscPtr, xdPtr MDS_END_ARG); else @@ -219,7 +241,8 @@ void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus) { return (void *)xdPtr; } -void *convertFromDsc(void *ptr, void *tree) { +void *convertFromDsc(void *ptr, void *tree) +{ struct descriptor_xd *xdPtr = (struct descriptor_xd *)ptr; struct descriptor *dscPtr; int i, status; @@ -249,16 +272,20 @@ void *convertFromDsc(void *ptr, void *tree) { dscRPtr = (struct descriptor_r *)dscPtr; while (dscRPtr->class == CLASS_R && (dscRPtr->dtype == DTYPE_WITH_ERROR || dscRPtr->dtype == DTYPE_WITH_UNITS || - dscRPtr->dtype == DTYPE_PARAM)) { - if (!errorData && dscRPtr->dtype == DTYPE_WITH_ERROR) { + dscRPtr->dtype == DTYPE_PARAM)) + { + if (!errorData && dscRPtr->dtype == DTYPE_WITH_ERROR) + { errorData = convertFromDsc(dscRPtr->dscptrs[1], tree); dscRPtr = (struct descriptor_r *)dscRPtr->dscptrs[0]; } - if (!unitsData && dscRPtr->dtype == DTYPE_WITH_UNITS) { + if (!unitsData && dscRPtr->dtype == DTYPE_WITH_UNITS) + { unitsData = convertFromDsc(dscRPtr->dscptrs[1], tree); dscRPtr = (struct descriptor_r *)dscRPtr->dscptrs[0]; } - if (dscRPtr->dtype == DTYPE_PARAM) { + if (dscRPtr->dtype == DTYPE_PARAM) + { helpData = (dscRPtr->dscptrs[1]) ? convertFromDsc(dscRPtr->dscptrs[1], tree) : 0; validationData = @@ -270,27 +297,31 @@ void *convertFromDsc(void *ptr, void *tree) { // printf("CONVERTFROMDSC class %d type %d\n", dscPtr->class, dscPtr->dtype); - switch (dscPtr->class) { + switch (dscPtr->class) + { case CLASS_S: return createScalarData(dscPtr->dtype, dscPtr->length, dscPtr->pointer, unitsData, errorData, helpData, validationData, tree); case CLASS_CA: status = TdiData(dscPtr, &caXd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Cannot evaluate CA descriptor\n"); return NULL; } isCa = 1; MDS_ATTR_FALLTHROUGH - case CLASS_A: { + case CLASS_A: + { ARRAY_COEFF(char, 64) * arrDscPtr; if (isCa) arrDscPtr = (void *)caXd.pointer; else arrDscPtr = (void *)dscPtr; - if (arrDscPtr->dimct > 1) { + if (arrDscPtr->dimct > 1) + { void *res = createArrayData(arrDscPtr->dtype, arrDscPtr->length, arrDscPtr->dimct, (int *)&arrDscPtr->m, arrDscPtr->pointer, unitsData, @@ -298,7 +329,9 @@ void *convertFromDsc(void *ptr, void *tree) { if (isCa) MdsFree1Dx(&caXd, 0); return res; - } else { + } + else + { int dims = (arrDscPtr->arsize > 0) ? arrDscPtr->arsize / arrDscPtr->length : 0; void *res = createArrayData(arrDscPtr->dtype, arrDscPtr->length, 1, &dims, @@ -309,27 +342,32 @@ void *convertFromDsc(void *ptr, void *tree) { return res; } } - case CLASS_R: { + case CLASS_R: + { void *retData; char **descs = malloc(dscRPtr->ndesc * sizeof(char *)); // Remove WITH_UNITS, WITH ERROR, PARAM which are not on the top of the Data // tree dscRPtr = (struct descriptor_r *)dscPtr; if (dscRPtr->dtype == DTYPE_WITH_UNITS || - dscRPtr->dtype == DTYPE_WITH_ERROR || dscRPtr->dtype == DTYPE_PARAM) { + dscRPtr->dtype == DTYPE_WITH_ERROR || dscRPtr->dtype == DTYPE_PARAM) + { EMPTYXD(currXd); MdsCopyDxXd(dscRPtr->dscptrs[0], &currXd); retData = convertFromDsc(&currXd, tree); MdsFree1Dx(&currXd, 0); return retData; } - for (i = 0; i < dscRPtr->ndesc; i++) { - if (dscRPtr->dscptrs[i]) { + for (i = 0; i < dscRPtr->ndesc; i++) + { + if (dscRPtr->dscptrs[i]) + { EMPTYXD(currXd); MdsCopyDxXd(dscRPtr->dscptrs[i], &currXd); descs[i] = convertFromDsc(&currXd, tree); MdsFree1Dx(&currXd, 0); - } else + } + else descs[i] = 0; } retData = createCompoundData( @@ -338,21 +376,26 @@ void *convertFromDsc(void *ptr, void *tree) { free(descs); return retData; } - case CLASS_APD: { + case CLASS_APD: + { struct descriptor_a *arrPtr = (struct descriptor_a *)dscPtr; char **descs = malloc(arrPtr->arsize); void *retData; int size = arrPtr->arsize / arrPtr->length; - for (i = 0; i < size; i++) { - if (((char **)arrPtr->pointer)[i]) { + for (i = 0; i < size; i++) + { + if (((char **)arrPtr->pointer)[i]) + { EMPTYXD(currXd); MdsCopyDxXd(((struct descriptor **)arrPtr->pointer)[i], &currXd); descs[i] = convertFromDsc(&currXd, tree); MdsFree1Dx(&currXd, 0); - } else + } + else descs[i] = 0; } - switch (dscPtr->dtype) { + switch (dscPtr->dtype) + { case DTYPE_LIST: retData = createListData(size, descs, unitsData, errorData, helpData, validationData); @@ -375,12 +418,14 @@ void *convertFromDsc(void *ptr, void *tree) { return (0); } -void freeDsc(void *dscPtr) { +void freeDsc(void *dscPtr) +{ struct descriptor_xd *xdPtr = (struct descriptor_xd *)dscPtr; if (!dscPtr) return; - if (xdPtr->class != CLASS_XD) { + if (xdPtr->class != CLASS_XD) + { printf("PANIC in convertFromDsc: not an XD\n"); exit(0); } @@ -388,7 +433,8 @@ void freeDsc(void *dscPtr) { free(xdPtr); } -char *decompileDsc(void *ptr, void *ctx) { +char *decompileDsc(void *ptr, void *ctx) +{ int status; EMPTYXD(xd); char *buf; @@ -397,7 +443,8 @@ char *decompileDsc(void *ptr, void *ctx) { status = _TdiDecompile(&ctx, dscPtr, &xd MDS_END_ARG); else status = TdiDecompile(dscPtr, &xd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Error decompiling expression: %s\n", MdsGetMsg(status)); return NULL; } @@ -411,7 +458,8 @@ char *decompileDsc(void *ptr, void *ctx) { } void *compileFromExprWithArgs(char *expr, int nArgs, void **args, void *tree, - void *ctx, int *retStatus) { + void *ctx, int *retStatus) +{ int varIdx; int i, status; void *arglist[MAX_ARGS]; @@ -423,15 +471,19 @@ void *compileFromExprWithArgs(char *expr, int nArgs, void **args, void *tree, exprD.length = (uint16_t)strlen(expr); exprD.pointer = (char *)expr; - if (ctx) { + if (ctx) + { arglist[1] = &ctx; arglist[2] = &exprD; varIdx = 3; - } else { + } + else + { arglist[1] = &exprD; varIdx = 2; } - for (i = 0; i < nArgs; i++) { + for (i = 0; i < nArgs; i++) + { arglistXd[i] = (struct descriptor_xd *)args[i]; if (arglistXd[i]->l_length > 0) arglist[varIdx] = arglistXd[i]->pointer; @@ -443,9 +495,12 @@ void *compileFromExprWithArgs(char *expr, int nArgs, void **args, void *tree, arglist[varIdx++] = MdsEND_ARG; *(int *)&arglist[0] = varIdx - 1; - if (ctx) { + if (ctx) + { status = *retStatus = (int)(intptr_t)LibCallg(arglist, _TdiCompile); - } else { + } + else + { status = *retStatus = (int)(intptr_t)LibCallg(arglist, TdiCompile); } if (!(status & 1)) @@ -459,7 +514,8 @@ void *compileFromExprWithArgs(char *expr, int nArgs, void **args, void *tree, return data; } -void *convertToByte(void *dsc) { +void *convertToByte(void *dsc) +{ int status; unsigned short opcode = OPC_BYTE; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -470,14 +526,16 @@ void *convertToByte(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToByteUnsigned(void *dsc) { +void *convertToByteUnsigned(void *dsc) +{ int status; unsigned short opcode = OPC_BYTE_UNSIGNED; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -488,14 +546,16 @@ void *convertToByteUnsigned(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToShort(void *dsc) { +void *convertToShort(void *dsc) +{ int status; unsigned short opcode = OPC_WORD; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -506,14 +566,16 @@ void *convertToShort(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToShortUnsigned(void *dsc) { +void *convertToShortUnsigned(void *dsc) +{ int status; unsigned short opcode = OPC_WORD_UNSIGNED; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -524,14 +586,16 @@ void *convertToShortUnsigned(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToInt(void *dsc) { +void *convertToInt(void *dsc) +{ int status; unsigned short opcode = OPC_LONG; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -542,14 +606,16 @@ void *convertToInt(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToIntUnsigned(void *dsc) { +void *convertToIntUnsigned(void *dsc) +{ int status; unsigned short opcode = OPC_LONG_UNSIGNED; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -560,14 +626,16 @@ void *convertToIntUnsigned(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToLong(void *dsc) { +void *convertToLong(void *dsc) +{ int status; unsigned short opcode = OPC_QUADWORD; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -578,14 +646,16 @@ void *convertToLong(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToLongUnsigned(void *dsc) { +void *convertToLongUnsigned(void *dsc) +{ int status; unsigned short opcode = OPC_QUADWORD_UNSIGNED; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -596,14 +666,16 @@ void *convertToLongUnsigned(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToFloat(void *dsc) { +void *convertToFloat(void *dsc) +{ int status; unsigned short opcode = OPC_FLOAT; @@ -615,14 +687,16 @@ void *convertToFloat(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToDouble(void *dsc) { +void *convertToDouble(void *dsc) +{ int status; unsigned short opcode = OPC_FT_FLOAT; @@ -634,14 +708,16 @@ void *convertToDouble(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToShape(void *dsc) { +void *convertToShape(void *dsc) +{ int status; unsigned short opcode = OPC_SHAPE; DESCRIPTOR_FUNCTION(funD, &opcode, 1); @@ -652,14 +728,16 @@ void *convertToShape(void *dsc) { *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { free(xdPtr); return 0; } return xdPtr; } -void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc) { +void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc) +{ struct descriptor_xd *retXd; EMPTYXD(emptyXd); struct descriptor_xd *xd = (struct descriptor_xd *)dsc; @@ -667,13 +745,16 @@ void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc) { struct descriptor_xd *validationXd = (struct descriptor_xd *)validationDsc; DESCRIPTOR_PARAM(paramD, 0, 0, 0); - if (xd) { + if (xd) + { paramD.value = xd->pointer; } - if (helpXd) { + if (helpXd) + { paramD.help = helpXd->pointer; } - if (validationXd) { + if (validationXd) + { paramD.validation = validationXd->pointer; } retXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); @@ -682,17 +763,20 @@ void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc) { return retXd; } -void *convertToUnits(void *dsc, void *unitsDsc) { +void *convertToUnits(void *dsc, void *unitsDsc) +{ struct descriptor_xd *retXd; EMPTYXD(emptyXd); struct descriptor_xd *xd = (struct descriptor_xd *)dsc; struct descriptor_xd *unitsXd = (struct descriptor_xd *)unitsDsc; DESCRIPTOR_WITH_UNITS(withUnitsD, 0, 0); - if (xd) { + if (xd) + { withUnitsD.data = xd->pointer; } - if (unitsXd) { + if (unitsXd) + { withUnitsD.units = unitsXd->pointer; } retXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); @@ -701,17 +785,20 @@ void *convertToUnits(void *dsc, void *unitsDsc) { return retXd; } -void *convertToError(void *dsc, void *errorDsc) { +void *convertToError(void *dsc, void *errorDsc) +{ struct descriptor_xd *retXd; EMPTYXD(emptyXd); struct descriptor_xd *xd = (struct descriptor_xd *)dsc; struct descriptor_xd *errorXd = (struct descriptor_xd *)errorDsc; DESCRIPTOR_WITH_ERROR(withErrorD, 0, 0); - if (xd) { + if (xd) + { withErrorD.data = xd->pointer; } - if (errorXd) { + if (errorXd) + { withErrorD.error = errorXd->pointer; } retXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); @@ -720,7 +807,8 @@ void *convertToError(void *dsc, void *errorDsc) { return retXd; } -char *serializeData(void *dsc, int *retSize, void **retDsc) { +char *serializeData(void *dsc, int *retSize, void **retDsc) +{ int status; struct descriptor *dscIn = (struct descriptor *)dsc; EMPTYXD(emptyXd); @@ -731,12 +819,14 @@ char *serializeData(void *dsc, int *retSize, void **retDsc) { *xdPtr = emptyXd; status = MdsSerializeDscOut(dscIn, xdPtr); - if (!(status & 1) || !xdPtr->pointer) { + if (!(status & 1) || !xdPtr->pointer) + { free(xdPtr); return 0; } arrPtr = (struct descriptor_a *)xdPtr->pointer; - if (arrPtr->dtype != DTYPE_B && arrPtr->dtype != DTYPE_BU) { + if (arrPtr->dtype != DTYPE_B && arrPtr->dtype != DTYPE_BU) + { printf("Fatal error: MdsSerializeDscOut returned a wrong type"); return 0; } @@ -745,7 +835,8 @@ char *serializeData(void *dsc, int *retSize, void **retDsc) { return arrPtr->pointer; } -void *deserializeData(char const *serialized) { +void *deserializeData(char const *serialized) +{ EMPTYXD(emptyXd); struct descriptor_xd *xdPtr; int status; @@ -759,7 +850,8 @@ void *deserializeData(char const *serialized) { } void convertTimeToAscii(int64_t *timePtr, char *dateBuf, int bufLen, - int *retLen) { + int *retLen) +{ struct descriptor_d dateDsc = {0, DTYPE_T, CLASS_D, 0}; unsigned short len; LibSysAscTim(&len, (struct descriptor *)&dateDsc, (int *)timePtr); @@ -771,7 +863,8 @@ void convertTimeToAscii(int64_t *timePtr, char *dateBuf, int bufLen, *retLen = len; } -int64_t convertAsciiToTime(const char *ascTime) { +int64_t convertAsciiToTime(const char *ascTime) +{ int64_t time; // LibConvertDateString("now", &time); LibConvertDateString(ascTime, &time); @@ -780,7 +873,8 @@ int64_t convertAsciiToTime(const char *ascTime) { // Conversion from VMS to IEEE float void convertToIEEEFloatArray(int dtype, int length, int nDims, int *dims, - void *ptr) { + void *ptr) +{ int status, arsize, i; float *fArr; DESCRIPTOR_A(inArrD, 0, 0, 0, 0); @@ -810,13 +904,15 @@ void convertToIEEEFloatArray(int dtype, int length, int nDims, int *dims, free(fArr); } -void convertToIEEEFloat(int dtype, int length, void *ptr) { +void convertToIEEEFloat(int dtype, int length, void *ptr) +{ int dims[1] = {1}; convertToIEEEFloatArray(dtype, length, 1, dims, ptr); } ///////////////mdsip support for Connection class/////////// -struct descriptor_xd EXPORT *GetManyExecute(char *serializedIn) { +struct descriptor_xd EXPORT *GetManyExecute(char *serializedIn) +{ static EMPTYXD(xd); struct descriptor_xd *serResult; @@ -829,7 +925,8 @@ struct descriptor_xd EXPORT *GetManyExecute(char *serializedIn) { return &xd; } -struct descriptor_xd *PutManyExecute(char *serializedIn) { +struct descriptor_xd *PutManyExecute(char *serializedIn) +{ static EMPTYXD(xd); struct descriptor *serResult; diff --git a/mdsobjects/cpp/mdsdataobjects.cpp b/mdsobjects/cpp/mdsdataobjects.cpp index 3bd7d68500..c67337534d 100644 --- a/mdsobjects/cpp/mdsdataobjects.cpp +++ b/mdsobjects/cpp/mdsdataobjects.cpp @@ -41,58 +41,62 @@ using namespace std; ///@{ \ingroup Descrmap -extern "C" { -// From mdsshr.h. Can't include because of class keyword usage in mdsdescrip.h -char *MdsGetMsg(int sts); - -void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr); -void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus); -void freeDsc(void *dscPtr); -void *convertFromDsc(void *dscPtr); -char *decompileDsc(void *ctx, void *dscPtr); -void *compileFromExprWithArgs(const char *expr, int nArgs, void *args, - void *tree, void *ctx, int *retStatus); -void *convertToArrayDsc(int clazz, int dtype, int length, int l_length, - int nDims, int *dims, void *ptr); -void *convertToCompoundDsc(int clazz, int dtype, int length, void *ptr, - int ndescs, void **descs); -void *convertToApdDsc(int type, int ndescs, void **ptr); -char *serializeData(void *dsc, int *retSize, void **retDsc); -void *deserializeData(char const *serialized); - -void *convertToByte(void *dsc); -void *convertToShort(void *dsc); -void *convertToInt(void *dsc); -void *convertToLong(void *dsc); -void *convertToByteUnsigned(void *dsc); -void *convertToShortUnsigned(void *dsc); -void *convertToIntUnsigned(void *dsc); -void *convertToLongUnsigned(void *dsc); -void *convertToFloat(void *dsc); -void *convertToDouble(void *dsc); -void *convertToShape(void *dcs); -void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc); -void *convertToUnits(void *dsc, void *unitsDsc); -void *convertToError(void *dsc, void *errorDsc); -void convertToIEEEFloat(int dtype, int length, void *ptr); -void convertToIEEEFloatArray(int dtype, int length, int nDims, int *dims, - void *ptr); -void convertTimeToAscii(int64_t *timePtr, char *dateBuf, int bufLen, - int *retLen); +extern "C" +{ + // From mdsshr.h. Can't include because of class keyword usage in mdsdescrip.h + char *MdsGetMsg(int sts); + + void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr); + void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus); + void freeDsc(void *dscPtr); + void *convertFromDsc(void *dscPtr); + char *decompileDsc(void *ctx, void *dscPtr); + void *compileFromExprWithArgs(const char *expr, int nArgs, void *args, + void *tree, void *ctx, int *retStatus); + void *convertToArrayDsc(int clazz, int dtype, int length, int l_length, + int nDims, int *dims, void *ptr); + void *convertToCompoundDsc(int clazz, int dtype, int length, void *ptr, + int ndescs, void **descs); + void *convertToApdDsc(int type, int ndescs, void **ptr); + char *serializeData(void *dsc, int *retSize, void **retDsc); + void *deserializeData(char const *serialized); + + void *convertToByte(void *dsc); + void *convertToShort(void *dsc); + void *convertToInt(void *dsc); + void *convertToLong(void *dsc); + void *convertToByteUnsigned(void *dsc); + void *convertToShortUnsigned(void *dsc); + void *convertToIntUnsigned(void *dsc); + void *convertToLongUnsigned(void *dsc); + void *convertToFloat(void *dsc); + void *convertToDouble(void *dsc); + void *convertToShape(void *dcs); + void *convertToParameter(void *dsc, void *helpDsc, void *validationDsc); + void *convertToUnits(void *dsc, void *unitsDsc); + void *convertToError(void *dsc, void *errorDsc); + void convertToIEEEFloat(int dtype, int length, void *ptr); + void convertToIEEEFloatArray(int dtype, int length, int nDims, int *dims, + void *ptr); + void convertTimeToAscii(int64_t *timePtr, char *dateBuf, int bufLen, + int *retLen); } //////Wrapper functions called by C code to build a Data class instance from a ///MDSplus descriptor/////////// -extern "C" void *convertDataToDsc(void *data) { +extern "C" void *convertDataToDsc(void *data) +{ return ((Data *)data)->convertToDsc(); } extern "C" void *createScalarData(int dtype, int length, char *ptr, Data *unitsData, Data *errorData, Data *helpData, Data *validationData, - Tree *tree) { - switch (dtype) { + Tree *tree) +{ + switch (dtype) + { case DTYPE_B: return new Int8(*ptr, unitsData, errorData, helpData, validationData); case DTYPE_BU: @@ -155,11 +159,13 @@ extern "C" void *createScalarData(int dtype, int length, char *ptr, extern "C" void *createArrayData(int dtype, int length, int nDims, int *dims, char *ptr, Data *unitsData, Data *errorData, - Data *helpData, Data *validationData) { + Data *helpData, Data *validationData) +{ int revDims[MAX_ARGS]; for (int i = 0; i < nDims; i++) revDims[i] = dims[nDims - i - 1]; - switch (dtype) { + switch (dtype) + { case DTYPE_B: return new Int8Array(ptr, nDims, revDims, unitsData, errorData, helpData, validationData); @@ -214,9 +220,11 @@ extern "C" void *createArrayData(int dtype, int length, int nDims, int *dims, extern "C" void *createCompoundData(int dtype, int length, char *ptr, int nDescs, char **descs, Data *unitsData, Data *errorData, Data *helpData, - Data *validationData) { + Data *validationData) +{ // printf("CREATE COMPOUND DATA nDescs = %d ptr= %x\n", nDescs, ptr); - switch (dtype) { + switch (dtype) + { case DTYPE_SIGNAL: return new Signal(dtype, length, ptr, nDescs, descs, unitsData, errorData, helpData, validationData); @@ -269,19 +277,22 @@ extern "C" void *createCompoundData(int dtype, int length, char *ptr, extern "C" void *createApdData(int nData, char **dataPtrs, Data *unitsData, Data *errorData, Data *helpData, - Data *validationData) { + Data *validationData) +{ return new Apd(nData, (Data **)dataPtrs, unitsData, errorData, helpData, validationData); } extern "C" void *createListData(int nData, char **dataPtrs, Data *unitsData, Data *errorData, Data *helpData, - Data *validationData) { + Data *validationData) +{ return new List(nData, (Data **)dataPtrs, unitsData, errorData, helpData, validationData); } extern "C" void *createDictionaryData(int nData, char **dataPtrs, Data *unitsData, Data *errorData, - Data *helpData, Data *validationData) { + Data *helpData, Data *validationData) +{ return new Dictionary(nData, (Data **)dataPtrs, unitsData, errorData, helpData, validationData); } @@ -297,7 +308,8 @@ MdsException::MdsException(int status) : msg(MdsGetMsg(status)) {} ///////////////////Data methods implementation//////////////////////// -Data::~Data() { +Data::~Data() +{ // decRefCount(); } @@ -316,27 +328,35 @@ Data::~Data() { // ::operator delete(p); //} -void MDSplus::deleteData(Data *data) { - if (data->refCount <= 1) { - if (data->units) { +void MDSplus::deleteData(Data *data) +{ + if (data->refCount <= 1) + { + if (data->units) + { data->units->decRefCount(); deleteData(data->units); } - if (data->error) { + if (data->error) + { data->error->decRefCount(); deleteData(data->error); } - if (data->help) { + if (data->help) + { data->help->decRefCount(); deleteData(data->help); } - if (data->validation) { + if (data->validation) + { data->validation->decRefCount(); deleteData(data->validation); } delete data; data = NULL; - } else { + } + else + { data->decRefCount(); } } @@ -349,7 +369,8 @@ void Data::decRefCount() { decRefCount(this); } void Data::incRefCount() { incRefCount(this); } -static Data *getMember(Data *member) { +static Data *getMember(Data *member) +{ if (member) member->incRefCount(); return member; @@ -363,12 +384,15 @@ Data *Data::getHelp() { return getMember(help); } Data *Data::getValidation() { return getMember(validation); } -static void setMember(Data *&target, Data *member) { - if (target) { +static void setMember(Data *&target, Data *member) +{ + if (target) + { target->decRefCount(); deleteData(target); } - if (member) { + if (member) + { target = member; target->incRefCount(); } @@ -382,7 +406,8 @@ void Data::setHelp(Data *in) { setMember(this->help, in); } void Data::setValidation(Data *in) { setMember(this->validation, in); } -Data *Data::data() { +Data *Data::data() +{ void *dscPtr = convertToDsc(); int retStatus; void *evalPtr = evaluateData(dscPtr, NULL, 0, &retStatus); @@ -394,7 +419,8 @@ Data *Data::data() { freeDsc(evalPtr); return retData; } -Data *Data::data(Tree *tree) { +Data *Data::data(Tree *tree) +{ void *dscPtr = convertToDsc(); int retStatus; void *evalPtr = @@ -408,7 +434,8 @@ Data *Data::data(Tree *tree) { return retData; } -Data *Data::evaluate() { +Data *Data::evaluate() +{ void *dscPtr = convertToDsc(); int retStatus; void *evalPtr = evaluateData(dscPtr, NULL, 1, &retStatus); @@ -420,7 +447,8 @@ Data *Data::evaluate() { return retData; } -Data *Data::evaluate(Tree *tree) { +Data *Data::evaluate(Tree *tree) +{ void *dscPtr = convertToDsc(); int retStatus; void *evalPtr = @@ -433,7 +461,8 @@ Data *Data::evaluate(Tree *tree) { return retData; } -char *Data::decompile() { +char *Data::decompile() +{ void *dscPtr = convertToDsc(); char *retStr = decompileDsc(dscPtr, 0); freeDsc(dscPtr); @@ -444,19 +473,22 @@ char *Data::decompile() { return retDec; } -void *Scalar::convertToDsc() { +void *Scalar::convertToDsc() +{ return completeConversionToDsc(convertToScalarDsc(clazz, dtype, length, ptr)); } // Make a dymanically allocated copy of the Data instance Tee -Data *Data::clone() { +Data *Data::clone() +{ void *dscPtr = convertToDsc(); Data *retData = (Data *)convertFromDsc(dscPtr); freeDsc(dscPtr); return retData; } -int *Data::getShape(int *numDim) { +int *Data::getShape(int *numDim) +{ void *dscPtr = convertToDsc(); void *retDsc = convertToShape(dscPtr); Data *retData = (Data *)convertFromDsc(retDsc); @@ -472,10 +504,12 @@ int *Data::getShape(int *numDim) { /// \ingroup Descrmap /// -Data *Data::getData(int classType, int dataType) { +Data *Data::getData(int classType, int dataType) +{ void *dscPtr = convertToDsc(); void *retDsc = NULL; - switch (dataType) { + switch (dataType) + { case DTYPE_B: retDsc = convertToByte(dscPtr); break; @@ -512,7 +546,7 @@ Data *Data::getData(int classType, int dataType) { freeDsc(retDsc); if (!retData) throw MdsException("Cannot get data"); - if(retData->clazz != classType) + if (retData->clazz != classType) { deleteData(retData); throw MdsException("Cannot convert to desired type"); @@ -525,7 +559,9 @@ Data *Data::getArrayData(int dtype) { return getData(CLASS_A, dtype); } Data *Data::getScalarData(int dtype) { return getData(CLASS_S, dtype); } -template static std::vector getArray(T *data, int size) { +template +static std::vector getArray(T *data, int size) +{ std::vector v(data, data + size); delete[] data; return v; @@ -544,128 +580,151 @@ void MDSplus::deleteNativeArray(double *array) { delete[] array; } void MDSplus::deleteNativeArray(char **array) { delete[] array; } void MDSplus::deleteNativeArray(MDSplus::Data **array) { delete[] array; } -char *Data::getByteArray(int *numElements) { +char *Data::getByteArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_B)); return array.ptr->getByteArray(numElements); } -std::vector Data::getByteArray() { +std::vector Data::getByteArray() +{ int numElements; char *retData = getByteArray(&numElements); return getArray(retData, numElements); } -unsigned char *Data::getByteUnsignedArray(int *numElements) { +unsigned char *Data::getByteUnsignedArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_BU)); return array.ptr->getByteUnsignedArray(numElements); } -std::vector Data::getByteUnsignedArray() { +std::vector Data::getByteUnsignedArray() +{ int numElements; unsigned char *retData = getByteUnsignedArray(&numElements); return getArray(retData, numElements); } -short *Data::getShortArray(int *numElements) { +short *Data::getShortArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_W)); return array.ptr->getShortArray(numElements); } -std::vector Data::getShortArray() { +std::vector Data::getShortArray() +{ int numElements; short *retData = getShortArray(&numElements); return getArray(retData, numElements); } -unsigned short *Data::getShortUnsignedArray(int *numElements) { +unsigned short *Data::getShortUnsignedArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_WU)); return array.ptr->getShortUnsignedArray(numElements); } -std::vector Data::getShortUnsignedArray() { +std::vector Data::getShortUnsignedArray() +{ int numElements; unsigned short *retData = getShortUnsignedArray(&numElements); return getArray(retData, numElements); } -int *Data::getIntArray(int *numElements) { +int *Data::getIntArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_L)); return array.ptr->getIntArray(numElements); } -std::vector Data::getIntArray() { +std::vector Data::getIntArray() +{ int numElements; int *retData = getIntArray(&numElements); return getArray(retData, numElements); } -unsigned int *Data::getIntUnsignedArray(int *numElements) { +unsigned int *Data::getIntUnsignedArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_LU)); return array.ptr->getIntUnsignedArray(numElements); } -std::vector Data::getIntUnsignedArray() { +std::vector Data::getIntUnsignedArray() +{ int numElements; unsigned int *retData = getIntUnsignedArray(&numElements); return getArray(retData, numElements); } -int64_t *Data::getLongArray(int *numElements) { +int64_t *Data::getLongArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_Q)); return array.ptr->getLongArray(numElements); } -std::vector Data::getLongArray() { +std::vector Data::getLongArray() +{ int numElements; int64_t *retData = getLongArray(&numElements); return getArray(retData, numElements); } -uint64_t *Data::getLongUnsignedArray(int *numElements) { +uint64_t *Data::getLongUnsignedArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_QU)); return array.ptr->getLongUnsignedArray(numElements); } -std::vector Data::getLongUnsignedArray() { +std::vector Data::getLongUnsignedArray() +{ int numElements; uint64_t *retData = getLongUnsignedArray(&numElements); return getArray(retData, numElements); } -float *Data::getFloatArray(int *numElements) { +float *Data::getFloatArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_FLOAT)); return array.ptr->getFloatArray(numElements); } -std::vector Data::getFloatArray() { +std::vector Data::getFloatArray() +{ int numElements; float *retData = getFloatArray(&numElements); return getArray(retData, numElements); } -double *Data::getDoubleArray(int *numElements) { +double *Data::getDoubleArray(int *numElements) +{ AutoPointer array(getArrayData(DTYPE_DOUBLE)); return array.ptr->getDoubleArray(numElements); } -std::vector Data::getDoubleArray() { +std::vector Data::getDoubleArray() +{ int numElements; double *retData = getDoubleArray(&numElements); return getArray(retData, numElements); } -std::vector > Data::getComplexArray() { +std::vector > Data::getComplexArray() +{ int numElements; std::complex *retData = getComplexArray(&numElements); return getArray(retData, numElements); } -char *Data::serialize(int *size) { +char *Data::serialize(int *size) +{ void *dscPtr = convertToDsc(); void *retDsc; int retSize; char *serialized = serializeData(dscPtr, &retSize, &retDsc); - if (!serialized) { + if (!serialized) + { freeDsc(dscPtr); throw MdsException("Cannot serialize Data object"); } @@ -677,57 +736,68 @@ char *Data::serialize(int *size) { return retSerialized; } -char Data::getByte() { +char Data::getByte() +{ AutoPointer scalar(getScalarData(DTYPE_B)); return scalar.ptr->getByte(); } -short Data::getShort() { +short Data::getShort() +{ AutoPointer scalar(getScalarData(DTYPE_W)); return scalar.ptr->getShort(); } -int Data::getInt() { +int Data::getInt() +{ AutoPointer scalar(getScalarData(DTYPE_L)); return scalar.ptr->getInt(); } -int64_t Data::getLong() { +int64_t Data::getLong() +{ AutoPointer scalar(getScalarData(DTYPE_Q)); return scalar.ptr->getLong(); } -unsigned char Data::getByteUnsigned() { +unsigned char Data::getByteUnsigned() +{ AutoPointer scalar(getScalarData(DTYPE_BU)); return scalar.ptr->getByteUnsigned(); } -unsigned short Data::getShortUnsigned() { +unsigned short Data::getShortUnsigned() +{ AutoPointer scalar(getScalarData(DTYPE_WU)); return scalar.ptr->getShortUnsigned(); } -unsigned int Data::getIntUnsigned() { +unsigned int Data::getIntUnsigned() +{ AutoPointer scalar(getScalarData(DTYPE_LU)); return scalar.ptr->getIntUnsigned(); } -uint64_t Data::getLongUnsigned() { +uint64_t Data::getLongUnsigned() +{ AutoPointer scalar(getScalarData(DTYPE_QU)); return scalar.ptr->getLongUnsigned(); } -float Data::getFloat() { +float Data::getFloat() +{ AutoPointer scalar(getScalarData(DTYPE_FLOAT)); return scalar.ptr->getFloat(); } -double Data::getDouble() { +double Data::getDouble() +{ AutoPointer scalar(getScalarData(DTYPE_DOUBLE)); return scalar.ptr->getDouble(); } -Data *Data::getDimensionAt(int dimIdx __attribute__((unused))) { +Data *Data::getDimensionAt(int dimIdx __attribute__((unused))) +{ return executeWithArgs("DIM_OF($)", 1, this); } @@ -744,8 +814,10 @@ Data *MDSplus::compile(const char *expr) { return compileWithArgs(expr, 0); } /// /// -Data *MDSplus::compileWithArgs(const char *expr, int nArgs...) { - struct Lambda { +Data *MDSplus::compileWithArgs(const char *expr, int nArgs...) +{ + struct Lambda + { std::vector args; ~Lambda() { std::for_each(args.begin(), args.end(), freeDsc); } } lambda; @@ -759,12 +831,15 @@ Data *MDSplus::compileWithArgs(const char *expr, int nArgs...) { int status; Data *res; - try { + try + { AutoPointer actTree(getActiveTree()); res = (Data *)compileFromExprWithArgs(expr, nArgs, &args[0], actTree, (actTree) ? actTree->getCtx() : NULL, &status); - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { res = (Data *)compileFromExprWithArgs(expr, nArgs, &args[0], NULL, NULL, &status); } @@ -780,7 +855,8 @@ Data *MDSplus::compileWithArgs(const char *expr, int nArgs...) { /// \param tree Tree target pointer /// \return new instanced Data representing compiled script /// -Data *MDSplus::compile(const char *expr, Tree *tree) { +Data *MDSplus::compile(const char *expr, Tree *tree) +{ return compileWithArgs(expr, tree, 0); } @@ -790,13 +866,15 @@ Data *MDSplus::compile(const char *expr, Tree *tree) { /// pointer \param nArgs number of arguments of expression \return new instanced /// Data representing compiled script /// -Data *MDSplus::compileWithArgs(const char *expr, Tree *tree, int nArgs...) { +Data *MDSplus::compileWithArgs(const char *expr, Tree *tree, int nArgs...) +{ int i; void *args[MAX_ARGS]; va_list v; va_start(v, nArgs); - for (i = 0; i < nArgs; i++) { + for (i = 0; i < nArgs; i++) + { Data *currArg = va_arg(v, Data *); args[i] = currArg->convertToDsc(); } @@ -812,21 +890,26 @@ Data *MDSplus::compileWithArgs(const char *expr, Tree *tree, int nArgs...) { Data *MDSplus::execute(const char *expr) { return executeWithArgs(expr, 0); } -Data *MDSplus::executeWithArgs(const char *expr, int nArgs...) { +Data *MDSplus::executeWithArgs(const char *expr, int nArgs...) +{ void *args[MAX_ARGS]; va_list v; va_start(v, nArgs); - for (int i = 0; i < nArgs; i++) { + for (int i = 0; i < nArgs; i++) + { Data *currArg = va_arg(v, Data *); args[i] = currArg->convertToDsc(); } int status; Tree *actTree = 0; - try { + try + { actTree = getActiveTree(); - } catch (MdsException const &exc) { + } + catch (MdsException const &exc) + { actTree = 0; } Data *compData = (Data *)compileFromExprWithArgs( @@ -844,16 +927,19 @@ Data *MDSplus::executeWithArgs(const char *expr, int nArgs...) { return evalData; } -Data *MDSplus::execute(const char *expr, Tree *tree) { +Data *MDSplus::execute(const char *expr, Tree *tree) +{ return executeWithArgs(expr, tree, 0); } -Data *MDSplus::executeWithArgs(const char *expr, Tree *tree, int nArgs...) { +Data *MDSplus::executeWithArgs(const char *expr, Tree *tree, int nArgs...) +{ void *args[MAX_ARGS]; va_list v; va_start(v, nArgs); - for (int i = 0; i < nArgs; i++) { + for (int i = 0; i < nArgs; i++) + { Data *currArg = va_arg(v, Data *); args[i] = currArg->convertToDsc(); } @@ -875,10 +961,12 @@ Data *MDSplus::executeWithArgs(const char *expr, Tree *tree, int nArgs...) { // Complete Conversion to Dsc by condsidering help, units and error -void *Data::completeConversionToDsc(void *dsc) { +void *Data::completeConversionToDsc(void *dsc) +{ void *retDsc = dsc; - if (help || validation) { + if (help || validation) + { void *helpDsc = (help) ? help->convertToDsc() : 0; void *validationDsc = (validation) ? validation->convertToDsc() : 0; void *oldDsc = retDsc; @@ -891,7 +979,8 @@ void *Data::completeConversionToDsc(void *dsc) { freeDsc(oldDsc); } - if (error) { + if (error) + { void *errorDsc = error->convertToDsc(); void *oldDsc = retDsc; retDsc = convertToError(retDsc, errorDsc); @@ -901,7 +990,8 @@ void *Data::completeConversionToDsc(void *dsc) { freeDsc(oldDsc); } - if (units) { + if (units) + { void *unitsDsc = units->convertToDsc(); void *oldDsc = retDsc; retDsc = convertToUnits(retDsc, unitsDsc); @@ -917,7 +1007,8 @@ void *Data::completeConversionToDsc(void *dsc) { // TDIbind end ///@} -void Data::plot() { +void Data::plot() +{ Data *dim = getDimensionAt(0); Scope *scope = new Scope(""); scope->plot(this, dim); @@ -926,7 +1017,8 @@ void Data::plot() { deleteData(dim); } -int *Array::getShape(int *numDims) { +int *Array::getShape(int *numDims) +{ int *retDims = new int[nDims]; *numDims = nDims; for (int i = 0; i < nDims; i++) @@ -935,7 +1027,8 @@ int *Array::getShape(int *numDims) { } // Array Methods setElementAt and getElementAt -Data *Array::getElementAt(int *getDims, int getNumDims) { +Data *Array::getElementAt(int *getDims, int getNumDims) +{ // Check Dimensionality if (getNumDims > nDims) throw MdsException("Invalid passed dimensions in Array::getElementAt"); @@ -972,7 +1065,8 @@ Data *Array::getElementAt(int *getDims, int getNumDims) { return retData; } -Array *Array::getSubArray(int startDim, int nSamples) { +Array *Array::getSubArray(int startDim, int nSamples) +{ int i; // Check Dimensionality @@ -1000,7 +1094,8 @@ Array *Array::getSubArray(int startDim, int nSamples) { return retArr; } -void Array::setElementAt(int *getDims, int getNumDims, Data *data) { +void Array::setElementAt(int *getDims, int getNumDims, Data *data) +{ int i; Array *arrayData; @@ -1013,7 +1108,8 @@ void Array::setElementAt(int *getDims, int getNumDims, Data *data) { // Check Dimensionality if (getNumDims > nDims) throw MdsException("Invalid passed dimensions in Array::setElementAt"); - for (i = 0; i < getNumDims; i++) { + for (i = 0; i < getNumDims; i++) + { if (getDims[i] < 0 || getDims[i] >= dims[i]) throw MdsException("Invalid passed dimensions in Array::setElementAt"); } @@ -1029,16 +1125,20 @@ void Array::setElementAt(int *getDims, int getNumDims, Data *data) { for (i = 0; i < getNumDims; i++) startIdx += getDims[i] * rowDims[i]; - if (data->clazz == CLASS_A) { + if (data->clazz == CLASS_A) + { arrayData = (Array *)data; // If passed data is an array, its dimensions must match the remaining // dimensions - if (arrayData->nDims != nDims - getNumDims) { + if (arrayData->nDims != nDims - getNumDims) + { delete[] rowDims; throw MdsException("Invalid passed dimensions in Array::setElementAt"); } - for (i = 0; i < arrayData->nDims; i++) { - if (arrayData->dims[i] != dims[getNumDims + i]) { + for (i = 0; i < arrayData->nDims; i++) + { + if (arrayData->dims[i] != dims[getNumDims + i]) + { delete[] rowDims; throw MdsException("Invalid passed dimensions in Array::setElementAt"); } @@ -1046,7 +1146,8 @@ void Array::setElementAt(int *getDims, int getNumDims, Data *data) { // Dimensionality check passed: copy passed Array memcpy(ptr + (length * startIdx), arrayData->ptr, rowDims[getNumDims - 1] * length); - } else // data->clazz == CLASS_S + } + else // data->clazz == CLASS_S { scalarData = (Scalar *)data; // Propagate the passed scalar to all the remaining dimensions @@ -1056,11 +1157,14 @@ void Array::setElementAt(int *getDims, int getNumDims, Data *data) { delete[] rowDims; } -char *Array::getByteArray(int *numElements) { +char *Array::getByteArray(int *numElements) +{ int size = arsize / length; char *retArr = new char[arsize / length]; - for (int i = 0; i < size; i++) { - switch (dtype) { + for (int i = 0; i < size; i++) + { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); @@ -1101,11 +1205,14 @@ char *Array::getByteArray(int *numElements) { *numElements = size; return retArr; } -unsigned char *Array::getByteUnsignedArray(int *numElements) { +unsigned char *Array::getByteUnsignedArray(int *numElements) +{ int size = arsize / length; unsigned char *retArr = new unsigned char[arsize / length]; - for (int i = 0; i < size; i++) { - switch (dtype) { + for (int i = 0; i < size; i++) + { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1149,11 +1256,13 @@ unsigned char *Array::getByteUnsignedArray(int *numElements) { *numElements = size; return retArr; } -short *Array::getShortArray(int *numElements) { +short *Array::getShortArray(int *numElements) +{ short *retArr = new short[arsize / length]; int size = arsize / length; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); @@ -1193,11 +1302,13 @@ short *Array::getShortArray(int *numElements) { *numElements = size; return retArr; } -unsigned short *Array::getShortUnsignedArray(int *numElements) { +unsigned short *Array::getShortUnsignedArray(int *numElements) +{ unsigned short *retArr = new unsigned short[arsize / length]; int size = arsize / length; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1240,11 +1351,13 @@ unsigned short *Array::getShortUnsignedArray(int *numElements) { *numElements = size; return retArr; } -int *Array::getIntArray(int *numElements) { +int *Array::getIntArray(int *numElements) +{ int size = arsize / length; int *retArr = new int[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1283,11 +1396,13 @@ int *Array::getIntArray(int *numElements) { *numElements = size; return retArr; } -unsigned int *Array::getIntUnsignedArray(int *numElements) { +unsigned int *Array::getIntUnsignedArray(int *numElements) +{ int size = arsize / length; unsigned int *retArr = new unsigned int[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1329,11 +1444,13 @@ unsigned int *Array::getIntUnsignedArray(int *numElements) { *numElements = size; return retArr; } -int64_t *Array::getLongArray(int *numElements) { +int64_t *Array::getLongArray(int *numElements) +{ int size = arsize / length; int64_t *retArr = new int64_t[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1373,11 +1490,13 @@ int64_t *Array::getLongArray(int *numElements) { return retArr; } -uint64_t *Array::getLongUnsignedArray(int *numElements) { +uint64_t *Array::getLongUnsignedArray(int *numElements) +{ int size = arsize / length; uint64_t *retArr = new uint64_t[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1421,11 +1540,13 @@ uint64_t *Array::getLongUnsignedArray(int *numElements) { return retArr; } -float *Array::getFloatArray(int *numElements) { +float *Array::getFloatArray(int *numElements) +{ int size = arsize / length; float *retArr = new float[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1464,11 +1585,13 @@ float *Array::getFloatArray(int *numElements) { *numElements = size; return retArr; } -double *Array::getDoubleArray(int *numElements) { +double *Array::getDoubleArray(int *numElements) +{ int size = arsize / length; double *retArr = new double[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_B: retArr[i] = numeric_cast(*(char *)&ptr[i * length]); break; @@ -1509,11 +1632,13 @@ double *Array::getDoubleArray(int *numElements) { return retArr; } -std::complex *Array::getComplexArray(int *numElements) { +std::complex *Array::getComplexArray(int *numElements) +{ int size = arsize / length; std::complex *retArr = new std::complex[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_FSC: retArr[i] = std::complex(((float *)ptr)[2 * i], ((float *)ptr)[2 * i + 1]); @@ -1531,11 +1656,13 @@ std::complex *Array::getComplexArray(int *numElements) { return retArr; } -char **Array::getStringArray(int *numElements) { +char **Array::getStringArray(int *numElements) +{ int size = (length > 0) ? arsize / length : 0; char **retArr = new char *[size]; for (int i = 0; i < size; i++) - switch (dtype) { + switch (dtype) + { case DTYPE_T: retArr[i] = new char[length + 1]; memcpy(retArr[i], &ptr[i * length], length); @@ -1553,7 +1680,8 @@ char **Array::getStringArray(int *numElements) { return retArr; } -bool String::equals(Data *data) { +bool String::equals(Data *data) +{ if (data->clazz != clazz || data->dtype != dtype) return false; @@ -1561,7 +1689,8 @@ bool String::equals(Data *data) { return std::string(ptr) == second.string; } -char *Uint64::getDate() { +char *Uint64::getDate() +{ char dateBuf[512]; int bufLen; convertTimeToAscii((int64_t *)ptr, dateBuf, 512, &bufLen); @@ -1571,33 +1700,39 @@ char *Uint64::getDate() { return retDate; } -void *TreePath::convertToDsc() { +void *TreePath::convertToDsc() +{ return completeConversionToDsc(convertToScalarDsc( clazz, dtype, path.length(), const_cast(path.c_str()))); } -void *Array::convertToDsc() { +void *Array::convertToDsc() +{ return completeConversionToDsc( convertToArrayDsc(clazz, dtype, length, arsize, nDims, dims, ptr)); } -void *Compound::convertToDsc() { +void *Compound::convertToDsc() +{ return completeConversionToDsc( convertToCompoundDsc(clazz, dtype, sizeof(short), (void *)&opcode, descs.size(), (void **)(&descs[0]))); } -void *Signal::convertToDsc() { +void *Signal::convertToDsc() +{ return completeConversionToDsc(convertToCompoundDsc( clazz, dtype, 0, (void *)&opcode, descs.size(), (void **)(&descs[0]))); } -void *Apd::convertToDsc() { +void *Apd::convertToDsc() +{ return completeConversionToDsc( convertToApdDsc(dtype, descs.size(), (void **)&descs[0])); } -Data *MDSplus::deserialize(char const *serialized) { +Data *MDSplus::deserialize(char const *serialized) +{ void *dscPtr = deserializeData(serialized); if (!dscPtr) throw MdsException("Cannot build Data instance from serialized content"); @@ -1606,7 +1741,8 @@ Data *MDSplus::deserialize(char const *serialized) { return retData; } -Data *MDSplus::deserialize(Data *serializedData) { +Data *MDSplus::deserialize(Data *serializedData) +{ Uint8Array *serializedArr = (Uint8Array *)serializedData; return deserialize((const char *)serializedArr->ptr); } @@ -1621,7 +1757,8 @@ Data *MDSplus::deserialize(Data *serializedData) { return output; } */ -std::ostream &MDSplus::operator<<(std::ostream &output, Data *data) { +std::ostream &MDSplus::operator<<(std::ostream &output, Data *data) +{ // output << data->decompile(); // return output; char *str = data->decompile(); @@ -1631,14 +1768,16 @@ std::ostream &MDSplus::operator<<(std::ostream &output, Data *data) { } Data *Uint8Array::deserialize() { return (Data *)deserializeData(ptr); } -void Scope::show() { +void Scope::show() +{ char expr[256]; std::sprintf(expr, "JavaShowWindow(%d, %d, %d, %d, %d)", idx, x, y, width, height); Data *ris = execute(expr); deleteData(ris); } -Scope::Scope(const char *name, int x, int y, int width, int height) { +Scope::Scope(const char *name, int x, int y, int width, int height) +{ std::string expr("JavaNewWindow(" + std::string(name) + ", -1"); Data *ris = execute(expr.c_str()); idx = ris->getInt(); @@ -1649,14 +1788,16 @@ Scope::Scope(const char *name, int x, int y, int width, int height) { this->height = height; show(); } -void Scope::plot(Data *x, Data *y, int row, int col, const char *color) { +void Scope::plot(Data *x, Data *y, int row, int col, const char *color) +{ char expr[256]; std::sprintf(expr, "JavaReplaceSignal(%d, $1, $2, %d, %d, \"%s\")", idx, row, col, color); Data *ris = executeWithArgs(expr, 2, x, y); deleteData(ris); } -void Scope::oplot(Data *x, Data *y, int row, int col, const char *color) { +void Scope::oplot(Data *x, Data *y, int row, int col, const char *color) +{ char expr[256]; std::sprintf(expr, "JavaAddSignal(%d, $1, $2, %d, %d, \"%s\")", idx, row, col, color); diff --git a/mdsobjects/cpp/mdsdatastreams.cpp b/mdsobjects/cpp/mdsdatastreams.cpp index 9f2d4fe3fc..43b2edd83b 100644 --- a/mdsobjects/cpp/mdsdatastreams.cpp +++ b/mdsobjects/cpp/mdsdatastreams.cpp @@ -33,10 +33,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include using namespace rapidjson; - #ifdef _MSC_VER inline int nanosleep(const struct timespec *req, - struct timespec *rem __attribute__((unused))) { + struct timespec *rem __attribute__((unused))) +{ DWORD sleep_ms = ((DWORD)req->tv_sec * 1000) + ((DWORD)req->tv_nsec / 1000000); Sleep(sleep_ms); @@ -48,18 +48,18 @@ inline int nanosleep(const struct timespec *req, // set of methods for sending chuncks of data as MDSplus events. Stream data are sent as a JSON message // with the following filds: // name: name of the stream -// shot: reference shot number +// shot: reference shot number // timestamp: increasing timestamp // absolute_time: relative (0) / absolute(1) time reference // dimension: dimension array [0] means scalar; [n] 1D array with n elementd [n, m] 2D (mxn) array // times: long for absolute times, float for relative times) -// samples: (float, 1D array) the dimension of the values array is related to the number oftimes and +// samples: (float, 1D array) the dimension of the values array is related to the number oftimes and // the declared dimension ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace MDSplus; static std::vector chanNames; -static std::vector chanTimestamps; +static std::vector chanTimestamps; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static uint64_t getAndIncrementTimestamp(const char *stream) @@ -67,13 +67,13 @@ static uint64_t getAndIncrementTimestamp(const char *stream) pthread_mutex_lock(&mutex); for (size_t i = 0; i < chanNames.size(); i++) { - if (chanNames[i] == stream) - { - uint64_t retTimestamp = chanTimestamps[i]; - chanTimestamps[i]++; - pthread_mutex_unlock(&mutex); - return retTimestamp; - } + if (chanNames[i] == stream) + { + uint64_t retTimestamp = chanTimestamps[i]; + chanTimestamps[i]++; + pthread_mutex_unlock(&mutex); + return retTimestamp; + } } chanNames.push_back(std::string(stream)); chanTimestamps.push_back(1); @@ -81,39 +81,39 @@ static uint64_t getAndIncrementTimestamp(const char *stream) return 0; } -static void makeSampleArray(Value &samplesVal, float * samples, int nDims, int *dims, Document::AllocatorType &allocator) +static void makeSampleArray(Value &samplesVal, float *samples, int nDims, int *dims, Document::AllocatorType &allocator) { - if(nDims > 1) + if (nDims > 1) { int sampleSize = 1; - for(int i = 1; i < nDims; i++) + for (int i = 1; i < nDims; i++) sampleSize *= dims[i]; - for(int i = 0; i < dims[0]; i++) + for (int i = 0; i < dims[0]; i++) { Value v(kArrayType); - makeSampleArray(v, &samples[i * sampleSize], nDims - 1, &dims[1],allocator); + makeSampleArray(v, &samples[i * sampleSize], nDims - 1, &dims[1], allocator); samplesVal.PushBack(v, allocator); } } else { - for(int i = 0; i < dims[0]; i++) + for (int i = 0; i < dims[0]; i++) samplesVal.PushBack(samples[i], allocator); } - } +} -EXPORT void EventStream::send(int shot, const char *name, bool isAbsTime, int nTimes, void *times, +EXPORT void EventStream::send(int shot, const char *name, bool isAbsTime, int nTimes, void *times, int nDim, int *dims, float *samples) { Document d; d.SetObject(); - Document::AllocatorType& allocator = d.GetAllocator(); + Document::AllocatorType &allocator = d.GetAllocator(); Value timesVal(kArrayType); Value samplesVal(kArrayType); makeSampleArray(samplesVal, samples, nDim, dims, allocator); - for(int i = 0; i < nTimes; i++) + for (int i = 0; i < nTimes; i++) { - if(isAbsTime) + if (isAbsTime) timesVal.PushBack(((uint64_t *)times)[i], allocator); else timesVal.PushBack(((float *)times)[i], allocator); @@ -121,7 +121,7 @@ EXPORT void EventStream::send(int shot, const char *name, bool isAbsTime, int nT Value seqNumberVal; seqNumberVal.SetInt(getAndIncrementTimestamp(name)); Value absTimeVal; - absTimeVal.SetInt(isAbsTime?1:0); + absTimeVal.SetInt(isAbsTime ? 1 : 0); Value shotVal; shotVal.SetInt(shot); Value nameVal; @@ -140,136 +140,141 @@ EXPORT void EventStream::send(int shot, const char *name, bool isAbsTime, int nT d.AddMember("absolute_time", absTimeVal, allocator); StringBuffer sb; PrettyWriter writer(sb); - d.Accept(writer); // Accept() traverses the DOM and generates Handler events. + d.Accept(writer); // Accept() traverses the DOM and generates Handler events. const char *msgBuf = sb.GetString(); - // Event::setEventRaw("STREAMING", strlen(msgBuf), (char *)msgBuf); + // Event::setEventRaw("STREAMING", strlen(msgBuf), (char *)msgBuf); Event::setEventRaw(name, strlen(msgBuf), (char *)msgBuf); } EXPORT void EventStream::send(int shot, const char *name, float time, - float sample) + float sample) { int dim = 1; EventStream::send(shot, name, false, 1, &time, 1, &dim, &sample); } EXPORT void EventStream::send(int shot, const char *name, uint64_t time, - float sample) + float sample) { int dim = 1; EventStream::send(shot, name, true, 1, &time, 1, &dim, &sample); } EXPORT void EventStream::send(int shot, const char *name, int numSamples, - float *times, float *samples) + float *times, float *samples) { - - EventStream::send(shot, name, false, numSamples, times, 1, &numSamples, samples); + + EventStream::send(shot, name, false, numSamples, times, 1, &numSamples, samples); } EXPORT void EventStream::send(int shot, const char *name, int numSamples, - uint64_t *times, float *samples) + uint64_t *times, float *samples) { EventStream::send(shot, name, true, numSamples, times, 1, &numSamples, samples); } EXPORT void EventStream::send(int shot, const char *name, int numTimes, - uint64_t *times, int numSamples, float *samples) + uint64_t *times, int numSamples, float *samples) { EventStream::send(shot, name, true, numTimes, times, 1, &numSamples, samples); } -EXPORT void EventStream::send(int shot, const char *name, Data *timesD, Data *samplesD) +EXPORT void EventStream::send(int shot, const char *name, Data *timesD, Data *samplesD) { bool isAbsTime = (timesD->dtype == DTYPE_Q || timesD->dtype == DTYPE_QU); int nTimes, nSamples; int *dims; float *samples, sample; int nDims = 1; - + bool isTimesScalar = false, isSamplesScalar = false; - try { + try + { samples = samplesD->getFloatArray(&nSamples); dims = samplesD->getShape(&nDims); } - catch(MdsException &exc) + catch (MdsException &exc) { - sample = samplesD->getFloat(); - samples = &sample; - nSamples = 1; - isSamplesScalar = true; + sample = samplesD->getFloat(); + samples = &sample; + nSamples = 1; + isSamplesScalar = true; } - if(isAbsTime) + if (isAbsTime) { uint64_t *times, time; - try { - times = (uint64_t *)timesD->getLongArray(&nTimes); + try + { + times = (uint64_t *)timesD->getLongArray(&nTimes); } - catch(MdsException &exc) + catch (MdsException &exc) { time = timesD->getLong(); times = &time; nTimes = 1; isTimesScalar = true; } - if(isSamplesScalar) + if (isSamplesScalar) EventStream::send(shot, name, true, nTimes, times, 1, &nSamples, samples); else { - EventStream::send(shot, name, true, nTimes, times, nDims, dims, samples); - delete [] dims; + EventStream::send(shot, name, true, nTimes, times, nDims, dims, samples); + delete[] dims; } - if(!isTimesScalar) delete[] times; + if (!isTimesScalar) + delete[] times; } else { float *times, time; - try { + try + { times = timesD->getFloatArray(&nTimes); } - catch(MdsException &exc) + catch (MdsException &exc) { - time = timesD->getFloat(); - times = &time; - nTimes = 1; - isTimesScalar = true; + time = timesD->getFloat(); + times = &time; + nTimes = 1; + isTimesScalar = true; } - if(isSamplesScalar) + if (isSamplesScalar) EventStream::send(shot, name, false, nTimes, times, 1, &nSamples, samples); else { - EventStream::send(shot, name, false, nTimes, times, nDims, dims, samples); - delete [] dims; + EventStream::send(shot, name, false, nTimes, times, nDims, dims, samples); + delete[] dims; } - if(!isTimesScalar) delete[] times; + if (!isTimesScalar) + delete[] times; } - if(!isSamplesScalar) delete[] samples; + if (!isSamplesScalar) + delete[] samples; } - -EXPORT void EventStream::run() { -// const char *eventName = getName(); // Get the name of the event - // if (strcmp(eventName, "STREAMING")) - // return; // Should neve return +EXPORT void EventStream::run() +{ + // const char *eventName = getName(); // Get the name of the event + // if (strcmp(eventName, "STREAMING")) + // return; // Should neve return size_t bufSize; const char *buf = getRaw(&bufSize); // Get raw data - - - if(bufSize == 0) return; - - if(buf[0] == '{') //JSON payload + + if (bufSize == 0) + return; + + if (buf[0] == '{') //JSON payload { - char *newPayload = new char[bufSize+1]; + char *newPayload = new char[bufSize + 1]; memcpy(newPayload, buf, bufSize); newPayload[bufSize] = 0; //std::cout << newPayload << std::endl; - - + handleJSONPayload(newPayload); delete[] newPayload; return; } - char *str = new char[bufSize + 1]; // Make it a string + char *str = new char[bufSize + 1]; // Make it a string memcpy(str, buf, bufSize); str[bufSize] = 0; int shot, numSamples; @@ -278,30 +283,36 @@ EXPORT void EventStream::run() { // std::endl; int readItems = sscanf(str, "%d %s %s %d", &shot, name, timeFormat, &numSamples); - if (readItems < 4) { + if (readItems < 4) + { delete[] str; return; // Incorrect message } // skip to fourth blank int len = strlen(str); int j = 0; - for (int i = 0; j < len && i < 4; i++) { + for (int i = 0; j < len && i < 4; i++) + { while (j < len && str[j] != ' ') j++; - if (j == len) { + if (j == len) + { delete[] str; return; // Incorrect message } j++; } Data *timesD; - if (timeFormat[0] == 'F') { + if (timeFormat[0] == 'F') + { float *times = new float[numSamples]; - for (int i = 0; i < numSamples; i++) { + for (int i = 0; i < numSamples; i++) + { sscanf(&str[j], "%f", ×[i]); while (j < len && str[j] != ' ') j++; - if (i < numSamples && j == len) { + if (i < numSamples && j == len) + { delete[] times; delete[] str; return; // Incorrect message @@ -313,13 +324,17 @@ EXPORT void EventStream::run() { else timesD = new Float32(times[0]); delete[] times; - } else if (timeFormat[0] != 'B') { + } + else if (timeFormat[0] != 'B') + { uint64_t *times = new uint64_t[numSamples]; - for (int i = 0; i < numSamples; i++) { + for (int i = 0; i < numSamples; i++) + { sscanf(&str[j], "%lu", (unsigned long *)×[i]); while (j < len && str[j] != ' ') j++; - if (i < numSamples - 1 && j == len) { + if (i < numSamples - 1 && j == len) + { delete[] times; delete[] str; return; // Incorrect message @@ -331,13 +346,15 @@ EXPORT void EventStream::run() { else timesD = new Uint64(times[0]); delete[] times; - } else // Mode B + } + else // Mode B { Data *timesD = deserialize(&str[j]); Data *samplesD = deserialize(&str[j + numSamples]); // Expressions already available, do not need any further action std::string nameStr(name); - for (size_t i = 0; i < listeners.size(); i++) { + for (size_t i = 0; i < listeners.size(); i++) + { if (names[i] == nameStr) listeners[i]->dataReceived(samplesD, timesD, shot); } @@ -348,11 +365,13 @@ EXPORT void EventStream::run() { } Data *samplesD; float *samples = new float[numSamples]; - for (int i = 0; i < numSamples; i++) { + for (int i = 0; i < numSamples; i++) + { sscanf(&str[j], "%f", &samples[i]); while (j < len && str[j] != ' ') j++; - if (i < numSamples - 1 && j == len) { + if (i < numSamples - 1 && j == len) + { delete[] samples; delete[] str; deleteData(timesD); @@ -368,7 +387,8 @@ EXPORT void EventStream::run() { delete[] samples; std::string nameStr(name); - for (size_t i = 0; i < listeners.size(); i++) { + for (size_t i = 0; i < listeners.size(); i++) + { if (names[i] == nameStr) listeners[i]->dataReceived(samplesD, timesD, shot); } @@ -379,12 +399,12 @@ EXPORT void EventStream::run() { static int countSampleArray(const Value &samplesVal) { int size = samplesVal.Size(); - if(size == 0) + if (size == 0) return 0; if (samplesVal[0].IsArray()) { int retSize = 0; - for(int i = 0; i< size; i++) + for (int i = 0; i < size; i++) retSize += countSampleArray(samplesVal[i]); return retSize; } @@ -392,25 +412,26 @@ static int countSampleArray(const Value &samplesVal) } static int readSampleArray(const Value &samplesVal, float *samples, int *dimensions, int depth) //Return number of dimensions { - if(depth >= 64) return 0; //Avoid core dumps in case of wrong payload + if (depth >= 64) + return 0; //Avoid core dumps in case of wrong payload int dimCount = 0; int size = samplesVal.Size(); - if(size == 0) + if (size == 0) return 0; dimensions[0] = size; if (samplesVal[0].IsArray()) { int currIndex = 0; - for(int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { dimCount = readSampleArray(samplesVal[i], &samples[currIndex], &dimensions[1], depth + 1); currIndex += countSampleArray(samplesVal[i]); } return dimCount + 1; } - else + else { - for(int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { samples[i] = samplesVal[i].GetFloat(); } @@ -421,39 +442,39 @@ static int readSampleArray(const Value &samplesVal, float *samples, int *dimensi EXPORT void EventStream::handleJSONPayload(char *payload) { Document d; - if(d.Parse(payload).HasParseError()) + if (d.Parse(payload).HasParseError()) { std::cout << "JSON parse error: " << payload << std::endl; return; } int shot = d["shot"].GetInt(); int absTime = d["absolute_time"].GetInt(); - + bool isAbsTime = (absTime == 1); const Value ×Val = d["times"]; const char *nameStr = d["name"].GetString(); Data *timesD; - if(isAbsTime) + if (isAbsTime) { - uint64_t *times = new uint64_t[timesVal.Size()]; - for(size_t i = 0; i < timesVal.Size(); i++) - times[i] = timesVal[i].GetInt64(); - if(timesVal.Size() == 1) - timesD = new Uint64(times[0]); - else - timesD = new Uint64Array(times, timesVal.Size()); - delete[] times; + uint64_t *times = new uint64_t[timesVal.Size()]; + for (size_t i = 0; i < timesVal.Size(); i++) + times[i] = timesVal[i].GetInt64(); + if (timesVal.Size() == 1) + timesD = new Uint64(times[0]); + else + timesD = new Uint64Array(times, timesVal.Size()); + delete[] times; } else { - float *times = new float[timesVal.Size()]; - for(size_t i = 0; i < timesVal.Size(); i++) - times[i] = timesVal[i].GetFloat(); - if(timesVal.Size() == 1) - timesD = new Float32(times[0]); - else - timesD = new Float32Array(times, timesVal.Size()); - delete[] times; + float *times = new float[timesVal.Size()]; + for (size_t i = 0; i < timesVal.Size(); i++) + times[i] = timesVal[i].GetFloat(); + if (timesVal.Size() == 1) + timesD = new Float32(times[0]); + else + timesD = new Float32Array(times, timesVal.Size()); + delete[] times; } const Value &samplesVal = d["samples"]; int numSamples = countSampleArray(samplesVal); @@ -461,25 +482,27 @@ EXPORT void EventStream::handleJSONPayload(char *payload) int dims[64]; int numDims = readSampleArray(samplesVal, samples, dims, 0); Data *samplesD; - if(numSamples == 1) + if (numSamples == 1) samplesD = new Float32(samples[0]); else samplesD = new Float32Array(samples, numDims, dims); - delete [] samples; - for (size_t i = 0; i < listeners.size(); i++) { + delete[] samples; + for (size_t i = 0; i < listeners.size(); i++) + { if (names[i] == nameStr) listeners[i]->dataReceived(samplesD, timesD, shot); } deleteData(samplesD); deleteData(timesD); -} +} -EXPORT void EventStream::registerListener(DataStreamListener *listener, - const char *inName) { +EXPORT void EventStream::registerListener(DataStreamListener *listener, + const char *inName) +{ listeners.push_back(listener); names.push_back(std::string(inName)); } -EXPORT void EventStream::registerListener(DataStreamListener *listener) +EXPORT void EventStream::registerListener(DataStreamListener *listener) { listeners.push_back(listener); names.push_back(std::string(name)); diff --git a/mdsobjects/cpp/mdseventobjects.cpp b/mdsobjects/cpp/mdseventobjects.cpp index 20571d93ba..263c6539e6 100644 --- a/mdsobjects/cpp/mdseventobjects.cpp +++ b/mdsobjects/cpp/mdseventobjects.cpp @@ -40,20 +40,21 @@ using namespace std; #define MAX_ARGS 512 -extern "C" { -int64_t convertAsciiToTime(const char *ascTime); -int MDSEventAst(const char *eventNameIn, void (*astadr)(void *, int, char *), - void *astprm, int *eventid); -int MDSEventAstMask(const char *eventNameIn, void (*astadr)(void *, int, char *), - void *astprm, int *eventid, unsigned int cpuMask); -int MDSEventCan(int id); -int MDSEvent(const char *eventNameIn, int bufLen, char *buf); -void *MdsEventAddListener(char *name, - void (*callback)(char *, char *, int, void *), - void *callbackArg); -void MdsEventRemoveListener(void *eventId); -int MdsEventTrigger(char *name, char *buf, int size); -int MdsEventTriggerAndWait(char *name, char *buf, int size); +extern "C" +{ + int64_t convertAsciiToTime(const char *ascTime); + int MDSEventAst(const char *eventNameIn, void (*astadr)(void *, int, char *), + void *astprm, int *eventid); + int MDSEventAstMask(const char *eventNameIn, void (*astadr)(void *, int, char *), + void *astprm, int *eventid, unsigned int cpuMask); + int MDSEventCan(int id); + int MDSEvent(const char *eventNameIn, int bufLen, char *buf); + void *MdsEventAddListener(char *name, + void (*callback)(char *, char *, int, void *), + void *callbackArg); + void MdsEventRemoveListener(void *eventId); + int MdsEventTrigger(char *name, char *buf, int size); + int MdsEventTriggerAndWait(char *name, char *buf, int size); } #ifdef _WIN32 @@ -63,32 +64,36 @@ static CRITICAL_SECTION critSect; static pthread_mutex_t evMutex = PTHREAD_MUTEX_INITIALIZER; #endif -namespace MDSplus { +namespace MDSplus +{ -void eventAst(void *arg, int len, char *buf) { + void eventAst(void *arg, int len, char *buf) + { #ifdef _WIN32 - EnterCriticalSection(&critSect); + EnterCriticalSection(&critSect); #else - pthread_mutex_lock(&evMutex); + pthread_mutex_lock(&evMutex); #endif - Event *ev = (Event *)arg; - ev->eventBuf.assign(buf, len); - ev->eventTime = convertAsciiToTime("now"); - ev->run(); + Event *ev = (Event *)arg; + ev->eventBuf.assign(buf, len); + ev->eventTime = convertAsciiToTime("now"); + ev->run(); - // notify all waiting threads // - ev->notify(); + // notify all waiting threads // + ev->notify(); #ifdef _WIN32 - LeaveCriticalSection(&critSect); + LeaveCriticalSection(&critSect); #else - pthread_mutex_unlock(&evMutex); + pthread_mutex_unlock(&evMutex); #endif -} + } } // namespace MDSplus -void Event::connectToEvents() { +void Event::connectToEvents() +{ #ifdef _WIN32 - if (!critSectInitialized) { + if (!critSectInitialized) + { critSectInitialized = true; InitializeCriticalSection(&critSect); } @@ -97,7 +102,8 @@ void Event::connectToEvents() { throw MdsException("failed to connect to event listener"); } -void Event::disconnectFromEvents() { +void Event::disconnectFromEvents() +{ if (!MDSEventCan(eventId)) throw MdsException("failed to close event listener"); } @@ -105,20 +111,22 @@ void Event::disconnectFromEvents() { void Event::run() {} Event::Event(const char *name, unsigned int cpuMask) - : eventName(name), eventId(-1), cpuMask(cpuMask), eventTime(convertAsciiToTime("now")){} + : eventName(name), eventId(-1), cpuMask(cpuMask), eventTime(convertAsciiToTime("now")) {} Event::Event(const char *name) - : eventName(name), eventId(-1), cpuMask(0), eventTime(convertAsciiToTime("now")){} + : eventName(name), eventId(-1), cpuMask(0), eventTime(convertAsciiToTime("now")) {} Event::~Event() { stop(); } -Data *Event::getData() const { +Data *Event::getData() const +{ if (eventBuf.length() == 0) return NULL; return deserialize(eventBuf.c_str()); } -const char *Event::getRaw(size_t *size) const { +const char *Event::getRaw(size_t *size) const +{ *size = eventBuf.length(); return eventBuf.c_str(); } @@ -129,8 +137,10 @@ const char *Event::getName() const { return eventName.c_str(); } void Event::start() { connectToEvents(); } -void Event::stop() { - if (eventId > -1) { +void Event::stop() +{ + if (eventId > -1) + { disconnectFromEvents(); eventId = -1; } @@ -138,7 +148,8 @@ void Event::stop() { bool Event::isStarted() const { return eventId > -1; } -void Event::wait(size_t secs) { +void Event::wait(size_t secs) +{ if (!isStarted()) start(); if (secs == 0) @@ -149,13 +160,15 @@ void Event::wait(size_t secs) { void Event::notify() { condition.notify(); } -void Event::setEvent(const char *evName, Data *evData) { +void Event::setEvent(const char *evName, Data *evData) +{ int bufLen; char *buf = evData->serialize(&bufLen); setEventRaw(evName, bufLen, buf); delete[] buf; } -void Event::setEventRaw(const char *evName, int bufLen, char *buf) { +void Event::setEventRaw(const char *evName, int bufLen, char *buf) +{ MDSEvent(evName, bufLen, buf); } diff --git a/mdsobjects/cpp/mdsipobjects.cpp b/mdsobjects/cpp/mdsipobjects.cpp index 169f576067..ab349e8038 100644 --- a/mdsobjects/cpp/mdsipobjects.cpp +++ b/mdsobjects/cpp/mdsipobjects.cpp @@ -77,8 +77,10 @@ extern "C" void FreeMessage(void *m); #define DTYPE_DOUBLE_IP 11 #define DTYPE_CSTRING_IP 14 -static int convertType(int mdsType) { - switch (mdsType) { +static int convertType(int mdsType) +{ + switch (mdsType) + { case DTYPE_B: return DTYPE_CHAR_IP; case DTYPE_BU: @@ -106,7 +108,8 @@ static int convertType(int mdsType) { } } -void *getManyObj(char *serializedIn) throw(MdsException) { +void *getManyObj(char *serializedIn) throw(MdsException) +{ AutoData inArgs((List *)deserialize((const char *)serializedIn)); if (inArgs->clazz != CLASS_APD) // || inArgs->dtype != DTYPE_LIST) throw MdsException( @@ -118,7 +121,8 @@ void *getManyObj(char *serializedIn) throw(MdsException) { String exprKey("exp"); String argsKey("args"); AutoData result(new Dictionary()); - for (int idx = 0; idx < nArgs; idx++) { + for (int idx = 0; idx < nArgs; idx++) + { AutoData currArg((Dictionary *)inArgs->getElementAt(idx)); if (currArg->clazz != CLASS_APD) // || currArg->dtype != DTYPE_DICTIONARY) throw MdsException( @@ -129,11 +133,14 @@ void *getManyObj(char *serializedIn) throw(MdsException) { AutoArray expr(exprData->getString()); AutoData argsData((List *)currArg->getItem(&argsKey)); AutoData answDict(new Dictionary()); - try { + try + { Data *currAnsw; - if (argsData.get() && argsData->len() > 0) { + if (argsData.get() && argsData->len() > 0) + { MDSplus::Data **args = argsData->getDscs(); - switch (argsData->len()) { + switch (argsData->len()) + { case 1: currAnsw = executeWithArgs(expr.get(), 1, args[0]); break; @@ -214,12 +221,16 @@ void *getManyObj(char *serializedIn) throw(MdsException) { args[12], args[13], args[14], args[15]); break; } - } else { + } + else + { currAnsw = execute(expr.get()); } AutoData valueKey(new String("value")); answDict->setItem(valueKey.get(), currAnsw); - } catch (MdsException const &e) { + } + catch (MdsException const &e) + { AutoData errorKey(new String("error")); AutoData errorData(new String(e.what())); answDict->setItem(errorKey.get(), errorData.get()); @@ -230,7 +241,8 @@ void *getManyObj(char *serializedIn) throw(MdsException) { return result->convertToDsc(); } -void *putManyObj(char *serializedIn) throw(MdsException) { +void *putManyObj(char *serializedIn) throw(MdsException) +{ AutoData inArgs((List *)deserialize((const char *)serializedIn)); if (inArgs->clazz != CLASS_APD) // || inArgs->dtype != DTYPE_LIST) throw MdsException( @@ -241,7 +253,8 @@ void *putManyObj(char *serializedIn) throw(MdsException) { String exprKey("exp"); String argsKey("args"); AutoData result(new Dictionary()); - for (int idx = 0; idx < nArgs; idx++) { + for (int idx = 0; idx < nArgs; idx++) + { AutoData currArg((Dictionary *)inArgs->getElementAt(idx)); if (currArg->clazz != CLASS_APD) // || currArg->dtype != DTYPE_DICTIONARY) throw MdsException( @@ -256,7 +269,8 @@ void *putManyObj(char *serializedIn) throw(MdsException) { if (argsData.get()) nPutArgs = argsData->len(); - try { + try + { AutoPointer tree(getActiveTree()); AutoData compiledData = (Data *)compileFromExprWithArgs( expr.get(), nPutArgs, (argsData.get()) ? argsData->getDscs() : 0, @@ -265,7 +279,9 @@ void *putManyObj(char *serializedIn) throw(MdsException) { node->putData(compiledData.get()); AutoData successData(new String("Success")); result->setItem(nodeNameData.get(), successData.get()); - } catch (MdsException const &e) { + } + catch (MdsException const &e) + { AutoData errorData(new String(e.what())); result->setItem(nodeNameData.get(), errorData.get()); } @@ -285,14 +301,16 @@ Connection::Connection(char *mdsipAddr, SetCompressionLevel(clevel); sockId = ConnectToMds(mdsipAddr); unlockGlobal(); - if (sockId <= 0) { + if (sockId <= 0) + { std::string msg("Cannot connect to "); msg += mdsipAddr; throw MdsException(msg); } } -Connection::~Connection() { +Connection::~Connection() +{ lockGlobal(); DisconnectFromMds(sockId); unlockGlobal(); @@ -306,20 +324,23 @@ void Connection::lockGlobal() { globalMutex.lock(); } void Connection::unlockGlobal() { globalMutex.unlock(); } -void Connection::openTree(char *tree, int shot) { +void Connection::openTree(char *tree, int shot) +{ int status = MdsOpen(sockId, tree, shot); // std::cout << "SOCK ID: " << sockId << std::endl; if (!(status & 1)) throw MdsException(status); } -void Connection::closeAllTrees() { +void Connection::closeAllTrees() +{ int status = MdsClose(sockId); if (!(status & 1)) throw MdsException(status); } -Data *Connection::get(const char *expr, Data **args, int nArgs) { +Data *Connection::get(const char *expr, Data **args, int nArgs) +{ char clazz, dtype, nDims; short length; int *dims; @@ -329,7 +350,8 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { Data *resData; // Check whether arguments are compatible (Scalars or Arrays) - for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) { + for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) + { args[argIdx]->getInfo(&clazz, &dtype, &length, &nDims, &dims, &ptr); delete[] dims; if (!ptr) @@ -341,17 +363,20 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { // lockGlobal(); status = SendArg(sockId, 0, DTYPE_CSTRING_IP, nArgs + 1, std::string(expr).size(), 0, 0, (char *)expr); - if (!(status & 1)) { + if (!(status & 1)) + { unlockLocal(); throw MdsException(status); } - for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) { + for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) + { args[argIdx]->getInfo(&clazz, &dtype, &length, &nDims, &dims, &ptr); status = SendArg(sockId, argIdx + 1, convertType(dtype), nArgs + 1, length, nDims, dims, (char *)ptr); delete[] dims; - if (!(status & 1)) { + if (!(status & 1)) + { unlockLocal(); throw MdsException(status); } @@ -360,12 +385,15 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, retDims, &numBytes, &ptr, &mem); unlockLocal(); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } - if (nDims == 0) { - switch (dtype) { + if (nDims == 0) + { + switch (dtype) + { case DTYPE_CHAR_IP: resData = new Int8(*(char *)ptr); break; @@ -396,7 +424,8 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { case DTYPE_DOUBLE_IP: resData = new Float64(*(double *)ptr); break; - case DTYPE_CSTRING_IP: { + case DTYPE_CSTRING_IP: + { std::string buf(reinterpret_cast(ptr), length); resData = new String(buf.c_str()); break; @@ -406,9 +435,12 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { << std::endl; throw MdsException("Unexpected data type returned by mdsip"); } - } else { + } + else + { // nDims > 0 - switch (dtype) { + switch (dtype) + { case DTYPE_CHAR_IP: resData = new Int8Array((char *)ptr, nDims, retDims); break; @@ -448,7 +480,8 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) { return resData; } -void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) { +void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) +{ char clazz, dtype, nDims; short length; int *dims; @@ -456,7 +489,8 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) { void *ptr, *mem = 0; // Check whether arguments are compatible (Scalars or Arrays) - for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) { + for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) + { args[argIdx]->getInfo(&clazz, &dtype, &length, &nDims, &dims, &ptr); if (!ptr) throw MdsException("Invalid argument passed to Connection::put(). Can " @@ -480,16 +514,19 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) { status = SendArg(sockId, 0, DTYPE_CSTRING_IP, nArgs + 1, putExpr.length(), 0, 0, const_cast(putExpr.c_str())); - if (!(status & 1)) { + if (!(status & 1)) + { unlockLocal(); throw MdsException(status); } - for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) { + for (std::size_t argIdx = 0; argIdx < (std::size_t)nArgs; ++argIdx) + { args[argIdx]->getInfo(&clazz, &dtype, &length, &nDims, &dims, &ptr); status = SendArg(sockId, argIdx + 1, convertType(dtype), nArgs + 1, length, nDims, dims, (char *)ptr); - if (!(status & 1)) { + if (!(status & 1)) + { unlockLocal(); throw MdsException(status); } @@ -511,13 +548,15 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) { throw MdsException(status); } -void Connection::setDefault(char *path) { +void Connection::setDefault(char *path) +{ int status = MdsSetDefault(sockId, path); if (!(status & 1)) throw MdsException(status); } -TreeNodeThinClient *Connection::getNode(char *path) { +TreeNodeThinClient *Connection::getNode(char *path) +{ char expr[256]; sprintf(expr, "GETNCI(%s, \'NID_NUMBER\')", path); AutoData nidData(get(expr)); @@ -529,7 +568,8 @@ TreeNodeThinClient *Connection::getNode(char *path) { #ifndef _MSC_VER void Connection::registerStreamListener(DataStreamListener *listener, - char *expr, char *tree, int shot) { + char *expr, char *tree, int shot) +{ char regExpr[64 + strlen(expr) + strlen(tree)]; sprintf(regExpr, "MdsObjectsCppShr->registerListener(\"%s\",\"%s\",val(%d))", expr, tree, shot); @@ -539,9 +579,11 @@ void Connection::registerStreamListener(DataStreamListener *listener, listenerV.push_back(listener); listenerIdV.push_back(id); } -void Connection::unregisterStreamListener(DataStreamListener *listener) { +void Connection::unregisterStreamListener(DataStreamListener *listener) +{ int idx; - for (idx = 0; idx < (int)listenerV.size(); idx++) { + for (idx = 0; idx < (int)listenerV.size(); idx++) + { if (listenerV[idx] == listener) break; } @@ -555,9 +597,12 @@ void Connection::unregisterStreamListener(DataStreamListener *listener) { listenerIdV.erase(listenerIdV.begin() + idx); } #endif -void Connection::checkDataAvailability() { - try { - while (true) { +void Connection::checkDataAvailability() +{ + try + { + while (true) + { AutoData serData( get("MdsObjectsCppShr->getNewSamplesSerializedXd:DSC()")); int numBytes; @@ -566,15 +611,18 @@ void Connection::checkDataAvailability() { delete[] serialized; int numDescs = apdData->getDimension(); Data **descs = apdData->getDscs(); - for (int i = 0; i < numDescs / 2; i++) { + for (int i = 0; i < numDescs / 2; i++) + { int id = descs[2 * i]->getInt(); Signal *sig = (Signal *)descs[2 * i + 1]; int idx; - for (idx = 0; idx < (int)listenerIdV.size(); idx++) { + for (idx = 0; idx < (int)listenerIdV.size(); idx++) + { if (listenerIdV[idx] == id) break; } - if (idx < (int)listenerV.size()) { + if (idx < (int)listenerV.size()) + { AutoData sigData(sig->getData()); AutoData sigDim(sig->getDimension()); if (((Array *)sigData.get())->getSize() > 0) @@ -583,38 +631,45 @@ void Connection::checkDataAvailability() { } deleteData(apdData); } - } catch (MdsException &exc) { + } + catch (MdsException &exc) + { } // Likely because of a resetConnection call } -static void *checkDataStream(void *connPtr) { +static void *checkDataStream(void *connPtr) +{ Connection *conn = (Connection *)connPtr; conn->checkDataAvailability(); return NULL; } #ifndef _MSC_VER -void Connection::startStreaming() { +void Connection::startStreaming() +{ pthread_t thread; pthread_create(&thread, NULL, checkDataStream, this); } #endif -void Connection::resetConnection() { +void Connection::resetConnection() +{ lockGlobal(); DisconnectFromMds(sockId); SetCompressionLevel(clevel); char *mdsipAddr = (char *)mdsipAddrStr.c_str(); sockId = ConnectToMds(mdsipAddr); unlockGlobal(); - if (sockId <= 0) { + if (sockId <= 0) + { std::string msg("Cannot connect to "); msg += mdsipAddr; throw MdsException(msg.c_str()); } } -void GetMany::insert(int idx, char *name, char *expr, Data **args, int nArgs) { +void GetMany::insert(int idx, char *name, char *expr, Data **args, int nArgs) +{ // They are freed by the List descructor /* AutoData fieldName(new String("name")); AutoData nameStr(new String(name)); @@ -642,17 +697,20 @@ void GetMany::insert(int idx, char *name, char *expr, Data **args, int nArgs) { List::insert(idx, dict); } -void GetMany::append(char *name, char *expr, Data **args, int nArgs) { +void GetMany::append(char *name, char *expr, Data **args, int nArgs) +{ insert(len(), name, expr, args, nArgs); } void GetMany::insert(char *beforeName __attribute__((unused)), char *name, - char *expr, Data **args, int nArgs) { + char *expr, Data **args, int nArgs) +{ int nItems = len(); int idx; String nameKey("name"); String nameStr(name); - for (idx = 0; idx < nItems; idx++) { + for (idx = 0; idx < nItems; idx++) + { AutoData currDict((Dictionary *)getElementAt(idx)); AutoData currName((String *)currDict->getItem(&nameKey)); if (currName->equals(&nameStr)) @@ -662,12 +720,14 @@ void GetMany::insert(char *beforeName __attribute__((unused)), char *name, insert(idx, name, expr, args, nArgs); } -void GetMany::remove(char *name) { +void GetMany::remove(char *name) +{ int nItems = len(); int idx; String nameKey("name"); String nameStr(name); - for (idx = 0; idx < nItems; idx++) { + for (idx = 0; idx < nItems; idx++) + { AutoData currDict((Dictionary *)getElementAt(idx)); AutoData currName((String *)currDict->getItem(&nameKey)); if (currName->equals(&nameStr)) @@ -675,7 +735,8 @@ void GetMany::remove(char *name) { } } -void GetMany::execute() { +void GetMany::execute() +{ int serSize; AutoArray ser(serialize(&serSize)); @@ -686,7 +747,8 @@ void GetMany::execute() { evalRes = (Dictionary *)deserialize(serEvalRes.get()); } -Data *GetMany::get(char *name) { +Data *GetMany::get(char *name) +{ if (!evalRes) throw MdsException("Data not yet evaluated"); @@ -704,7 +766,8 @@ Data *GetMany::get(char *name) { AutoData error((String *)dictionary->getItem(&errorKey)); if (!error.get()) throw MdsException("Unknown Error"); - else { + else + { AutoPointer errBuf(error->getString()); throw MdsException(errBuf.get()); } @@ -715,7 +778,8 @@ Data *GetMany::get(char *name) { ///////////////// void PutMany::insert(int idx, char *nodeName, char *expr, Data **args, - int nArgs) { + int nArgs) +{ AutoData node(new String("node")); AutoData nodeNameStr(new String(nodeName)); AutoData exp(new String("exp")); @@ -737,17 +801,20 @@ void PutMany::insert(int idx, char *nodeName, char *expr, Data **args, List::insert(idx, dict.get()); } -void PutMany::append(char *name, char *expr, Data **args, int nArgs) { +void PutMany::append(char *name, char *expr, Data **args, int nArgs) +{ insert(len(), name, expr, args, nArgs); } void PutMany::insert(char *beforeName __attribute__((unused)), char *nodeName, - char *expr, Data **args, int nArgs) { + char *expr, Data **args, int nArgs) +{ int nItems = len(); int idx; String nameKey("node"); String nodeNameStr(nodeName); - for (idx = 0; idx < nItems; idx++) { + for (idx = 0; idx < nItems; idx++) + { AutoData currDict((Dictionary *)getElementAt(idx)); AutoData currName = (String *)currDict->getItem(&nameKey); if (currName->equals(&nodeNameStr)) @@ -757,11 +824,13 @@ void PutMany::insert(char *beforeName __attribute__((unused)), char *nodeName, insert(idx, nodeName, expr, args, nArgs); } -void PutMany::remove(char *nodeName) { +void PutMany::remove(char *nodeName) +{ std::size_t nItems = len(); String nodeKey("node"); String nodeNameStr(nodeName); - for (std::size_t idx = 0; idx < nItems; ++idx) { + for (std::size_t idx = 0; idx < nItems; ++idx) + { AutoData currDict = (Dictionary *)getElementAt(idx); AutoData currName = (String *)currDict->getItem(&nodeKey); if (currName->equals(&nodeNameStr)) @@ -769,7 +838,8 @@ void PutMany::remove(char *nodeName) { } } -void PutMany::execute() { +void PutMany::execute() +{ int serSize; AutoArray ser(serialize(&serSize)); @@ -780,7 +850,8 @@ void PutMany::execute() { evalRes = (Dictionary *)deserialize(serEvalRes.get()); } -void PutMany::checkStatus(char *nodeName) { +void PutMany::checkStatus(char *nodeName) +{ if (!evalRes) throw MdsException("Data not yet written"); @@ -789,7 +860,8 @@ void PutMany::checkStatus(char *nodeName) { if (!resItem.get()) throw MdsException("Missing data item in evaluation list"); - if (!String("Success").equals(resItem.get())) { + if (!String("Success").equals(resItem.get())) + { AutoArray errMsg(resItem->getString()); throw MdsException(errMsg.get()); } diff --git a/mdsobjects/cpp/mdsobjects.c b/mdsobjects/cpp/mdsobjects.c index 905f394807..698a69f1f2 100644 --- a/mdsobjects/cpp/mdsobjects.c +++ b/mdsobjects/cpp/mdsobjects.c @@ -52,7 +52,8 @@ static void freeDescrip(struct descriptor *desc); static JavaVM *jvm; static jobject localDataProviderInstance; -static JNIEnv *getJNIEnv() { +static JNIEnv *getJNIEnv() +{ JNIEnv *jEnv; int retVal; @@ -65,13 +66,15 @@ static JNIEnv *getJNIEnv() { static void releaseJNIEnv() { (*jvm)->DetachCurrentThread(jvm); } // Debug functions -static void printDecompiled(struct descriptor *inD) { +static void printDecompiled(struct descriptor *inD) +{ int status; EMPTYXD(out_xd); char *buf; status = TdiDecompile(inD, &out_xd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("%s\n", MdsGetMsg(status)); return; } @@ -84,7 +87,8 @@ static void printDecompiled(struct descriptor *inD) { MdsFree1Dx(&out_xd, 0); } -static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { +static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) +{ jclass cls, data_cls; jmethodID constr; int i, length, count, status; @@ -111,7 +115,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { EMPTYXD(ca_xd); int is_ca = 0; - if (!desc) { + if (!desc) + { return NULL; } // printf("DescripToObject dtype = %d class = %d\n", desc->dtype, @@ -119,9 +124,11 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { if (desc->class == CLASS_XD) return DescripToObject(env, ((struct descriptor_xd *)desc)->pointer); - switch (desc->class) { + switch (desc->class) + { case CLASS_S: - switch (desc->dtype) { + switch (desc->dtype) + { case DTYPE_BU: is_unsigned = 1; case DTYPE_B: @@ -255,7 +262,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { } case CLASS_CA: status = TdiData(desc, &ca_xd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Cannot evaluate CA descriptor\n"); return NULL; } @@ -266,7 +274,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { else array_d = (struct descriptor_a *)desc; length = array_d->arsize / array_d->length; - switch (array_d->dtype) { + switch (array_d->dtype) + { case DTYPE_MISSING: cls = (*env)->FindClass(env, "mdsdata/IntArray"); constr = @@ -393,7 +402,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { jobjects = (*env)->NewObjectArray(env, length, data_cls, 0); buf = malloc(array_d->length + 1); buf[array_d->length] = 0; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { memcpy(buf, &array_d->pointer[i * array_d->length], array_d->length); (*env)->SetObjectArrayElement(env, jobjects, i, (jobject)(*env)->NewStringUTF(env, buf)); @@ -406,7 +416,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { } case CLASS_R: record_d = (struct descriptor_r *)desc; - switch (record_d->dtype) { + switch (record_d->dtype) + { case DTYPE_PARAM: cls = (*env)->FindClass(env, "mdsdata/ParamData"); constr = @@ -506,7 +517,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { obj = (*env)->CallStaticObjectMethodA(env, cls, constr, args); data_cls = (*env)->FindClass(env, "mdsdata/Data"); jobjects = (*env)->NewObjectArray(env, record_d->ndesc, data_cls, 0); - for (i = count = 0; count < record_d->ndesc; i++, count++) { + for (i = count = 0; count < record_d->ndesc; i++, count++) + { (*env)->SetObjectArrayElement(env, jobjects, i, DescripToObject(env, record_d->dscptrs[i])); } @@ -516,10 +528,12 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { (record_d->dtype == DTYPE_FUNCTION || record_d->dtype == DTYPE_DEPENDENCY || record_d->dtype == DTYPE_CONDITION || record_d->dtype == DTYPE_CALL || - record_d->dtype == DTYPE_DISPATCH)) { + record_d->dtype == DTYPE_DISPATCH)) + { opcode_fid = (*env)->GetFieldID(env, cls, "opcode", "I"); opcode = 0; - switch (record_d->length) { + switch (record_d->length) + { case 1: opcode = *(unsigned char *)record_d->pointer; break; @@ -541,7 +555,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { constr = (*env)->GetStaticMethodID(env, cls, "getData", "([Lmdsdata/Data;)Lmdsdata/Data;"); jobjects = (*env)->NewObjectArray(env, length, data_cls, 0); - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { if (curr_obj = DescripToObject(env, ((struct descriptor **)array_d->pointer)[i])) (*env)->SetObjectArrayElement(env, jobjects, i, curr_obj); @@ -552,7 +567,8 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) { return 0; } -static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { +static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) +{ jclass cls; jfieldID datum_fid, descs_fid, opcode_fid, dtype_fid, dclass_fid; static DESCRIPTOR_A(template_array, 0, 0, 0, 0); @@ -582,7 +598,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { const char *string; struct descriptor *desc; - if (!obj) { + if (!obj) + { return NULL; } cls = (*env)->GetObjectClass(env, obj); @@ -590,12 +607,14 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { dclass_fid = (*env)->GetFieldID(env, cls, "clazz", "I"); dtype = (*env)->GetIntField(env, obj, dtype_fid), dclass = (*env)->GetIntField(env, obj, dclass_fid); - switch (dclass) { + switch (dclass) + { case CLASS_S: desc = (struct descriptor *)malloc(sizeof(struct descriptor)); desc->class = dclass; desc->dtype = dtype; - switch (dtype) { + switch (dtype) + { case DTYPE_B: case DTYPE_BU: datum_fid = (*env)->GetFieldID(env, cls, "data", "B"); @@ -644,10 +663,12 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { java_string = (*env)->GetObjectField(env, obj, datum_fid); string = (*env)->GetStringUTFChars(env, java_string, 0); desc->length = strlen(string); - if (desc->length > 0) { + if (desc->length > 0) + { desc->pointer = (char *)malloc(desc->length); memcpy(desc->pointer, string, desc->length); - } else + } + else desc->pointer = 0; (*env)->ReleaseStringUTFChars(env, java_string, string); return desc; @@ -680,7 +701,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { array_d = (struct descriptor_a *)malloc(sizeof(struct descriptor_a)); memcpy(array_d, &template_array, sizeof(struct descriptor_a)); array_d->dtype = dtype; - switch (dtype) { + switch (dtype) + { case DTYPE_B: case DTYPE_BU: datum_fid = (*env)->GetFieldID(env, cls, "data", "[B"); @@ -782,7 +804,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { strings = malloc(length * sizeof(char *)); jstrings = malloc(length * sizeof(jstring)); maxlen = 0; - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { jstrings[i] = (*env)->GetObjectArrayElement(env, jobjects, i); strings[i] = (char *)(*env)->GetStringUTFChars(env, jstrings[i], 0); if (maxlen < (int)strlen(strings[i])) @@ -790,7 +813,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { } array_d->pointer = (char *)malloc(length * maxlen); memset(array_d->pointer, ' ', length * maxlen); - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { memcpy(&array_d->pointer[i * maxlen], strings[i], maxlen); (*env)->ReleaseStringUTFChars(env, jstrings[i], strings[i]); } @@ -815,18 +839,21 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { record_d->pointer = 0; if (dtype == DTYPE_FUNCTION || dtype == DTYPE_DEPENDENCY || dtype == DTYPE_CONDITION || dtype == DTYPE_CALL || - dtype == DTYPE_DISPATCH) { + dtype == DTYPE_DISPATCH) + { record_d->length = sizeof(short); record_d->pointer = (unsigned char *)malloc(sizeof(short)); *(short *)record_d->pointer = opcode; } - if (dtype == DTYPE_CALL) { + if (dtype == DTYPE_CALL) + { record_d->length = sizeof(char); record_d->pointer = (unsigned char *)malloc(sizeof(char)); *(char *)record_d->pointer = opcode; } record_d->ndesc = ndescs; - for (i = 0; i < ndescs; i++) { + for (i = 0; i < ndescs; i++) + { record_d->dscptrs[i] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jdescs, i)); } @@ -844,7 +871,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { array_d->length = sizeof(struct descriptor *); array_d->arsize = array_d->length * ndescs; array_d->pointer = (char *)malloc(sizeof(void *) * ndescs); - for (i = 0; i < ndescs; i++) { + for (i = 0; i < ndescs; i++) + { ((struct descriptor **)(array_d->pointer))[i] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jdescs, i)); } @@ -855,7 +883,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) { return 0; } -static void freeDescrip(struct descriptor *desc) { +static void freeDescrip(struct descriptor *desc) +{ struct descriptor_r *record_d; struct descriptor_a *array_d; int i; @@ -865,7 +894,8 @@ static void freeDescrip(struct descriptor *desc) { /*printf("freeDescrip class %d dtype %d\n", desc->class, desc->dtype);*/ - switch (desc->class) { + switch (desc->class) + { case CLASS_S: free(desc->pointer); break; @@ -895,7 +925,8 @@ static void freeDescrip(struct descriptor *desc) { * Signature: (Ljava/lang/String;[Lmdsdata/Data;)Lmdsdata/Data; */ JNIEXPORT jstring JNICALL Java_mdsdata_Data_decompile(JNIEnv *env, - jobject obj) { + jobject obj) +{ EMPTYXD(out_xd); jstring ris; @@ -905,7 +936,8 @@ JNIEXPORT jstring JNICALL Java_mdsdata_Data_decompile(JNIEnv *env, struct descriptor *data_d = ObjectToDescrip(env, obj); status = TdiDecompile(data_d, &out_xd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Error decompiling expression: %s\n", MdsGetMsg(status)); return NULL; } @@ -928,7 +960,8 @@ JNIEXPORT jstring JNICALL Java_mdsdata_Data_decompile(JNIEnv *env, */ JNIEXPORT jobject JNICALL Java_mdsdata_Data_compileWithArgs( - JNIEnv *env, jclass cls, jstring jexpr, jobjectArray jargs) { + JNIEnv *env, jclass cls, jstring jexpr, jobjectArray jargs) +{ EMPTYXD(outXd); int argLen, varIdx, i; const char *expr = (*env)->GetStringUTFChars(env, jexpr, 0); @@ -944,7 +977,8 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_compileWithArgs( argLen = MAX_ARGS; varIdx = 2; arglist[1] = &exprD; - for (i = 0; i < argLen; i++) { + for (i = 0; i < argLen; i++) + { arglist[varIdx++] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jargs, i)); } @@ -957,7 +991,8 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_compileWithArgs( (*env)->ReleaseStringUTFChars(env, jexpr, expr); if (outXd.pointer) ris = DescripToObject(env, outXd.pointer); - else { + else + { exc = (*env)->FindClass(env, "SyntaxException"); (*env)->ThrowNew(env, exc, "Syntax error"); } @@ -970,7 +1005,8 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_compileWithArgs( * Method: evaluate * Signature: ()Lmdsdata/Data; */ -JNIEXPORT jobject JNICALL Java_mdsdata_Data_evaluate(JNIEnv *env, jobject obj) { +JNIEXPORT jobject JNICALL Java_mdsdata_Data_evaluate(JNIEnv *env, jobject obj) +{ EMPTYXD(xd); int status; jobject ris = 0; @@ -978,7 +1014,8 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_evaluate(JNIEnv *env, jobject obj) { jclass exc; status = TdiData(dataD, &xd MDS_END_ARG); - if (!(status & 1) || !xd.pointer) { + if (!(status & 1) || !xd.pointer) + { exc = (*env)->FindClass(env, "mdsdata/DataException"); (*env)->ThrowNew(env, exc, MdsGetMsg(status)); } @@ -989,7 +1026,8 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_evaluate(JNIEnv *env, jobject obj) { } /////////////////////////////////mdstree stuff//////////////////////// -static void RaiseException(JNIEnv *env, char *msg, int status) { +static void RaiseException(JNIEnv *env, char *msg, int status) +{ char fullMsg[2048]; jclass exc = (*env)->FindClass(env, "mdstree/TreeException"); sprintf(fullMsg, "%d:%s", status, msg); @@ -1003,7 +1041,8 @@ static void RaiseException(JNIEnv *env, char *msg, int status) { * Signature: (I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getPath(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ char *path = TreeGetPath(nid); jstring jpath = (*env)->NewStringUTF(env, path); TreeFree(path); @@ -1017,7 +1056,8 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getPath(JNIEnv *env, jclass cls, */ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getFullPath(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ char fullPath[512]; int fullPathLen, status; jstring jFullPath; @@ -1026,7 +1066,8 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getFullPath(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } @@ -1040,13 +1081,15 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getFullPath(JNIEnv *env, * Signature: (I)Lmdsdata/Data; */ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getData(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ EMPTYXD(xd); int status; jobject retObj; status = TreeGetRecord(nid, &xd); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } @@ -1062,12 +1105,14 @@ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getData(JNIEnv *env, jclass cls, * Signature: (I)V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_deleteData(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ EMPTYXD(xd); int status; status = TreePutRecord(nid, (struct descriptor *)&xd, 0); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); } } @@ -1078,12 +1123,14 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_deleteData(JNIEnv *env, jclass cls, * Signature: (ILmdsdata/Data;)V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putData(JNIEnv *env, jclass cls, - jint nid, jobject jData) { + jint nid, jobject jData) +{ int status; struct descriptor *dataD = ObjectToDescrip(env, jData); status = TreePutRecord(nid, dataD, 0); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); } freeDescrip(dataD); @@ -1095,9 +1142,11 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putData(JNIEnv *env, jclass cls, * Signature: (I)V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOn(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int status = TreeTurnOn(nid); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); } } @@ -1108,9 +1157,11 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOn(JNIEnv *env, jclass cls, * Signature: (I)V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOff(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int status = TreeTurnOff(nid); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); } } @@ -1121,12 +1172,14 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOff(JNIEnv *env, jclass cls, * Signature: (I)Z */ JNIEXPORT jboolean JNICALL Java_mdstree_MdsTree_isOn(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int status = TreeIsOn(nid); return (status & 1); } -static void convertTime(int *time, char *retTime) { +static void convertTime(int *time, char *retTime) +{ char timeStr[512]; int retLen; struct descriptor time_dsc = {511, DTYPE_T, CLASS_S, timeStr}; @@ -1143,7 +1196,8 @@ static void convertTime(int *time, char *retTime) { */ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getInsertionDate(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int timeInserted[2]; int timeLen; @@ -1168,7 +1222,8 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getInsertionDate(JNIEnv *env, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_open(JNIEnv *env, jclass cls, jstring jexperiment, - jint shot) { + jint shot) +{ char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeOpen(experiment, shot, 0); @@ -1184,7 +1239,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_open(JNIEnv *env, jclass cls, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_close(JNIEnv *env, jclass cls, jstring jexperiment, - jint shot) { + jint shot) +{ char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeClose(experiment, shot); @@ -1199,7 +1255,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_close(JNIEnv *env, jclass cls, * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_find(JNIEnv *env, jclass cls, - jstring jpath) { + jstring jpath) +{ char *path = (char *)(*env)->GetStringUTFChars(env, jpath, 0); int nid = 0, status; @@ -1218,7 +1275,8 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_find(JNIEnv *env, jclass cls, JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_findWild(JNIEnv *env, jclass cls, jstring jpath, - jint usageMask) { + jint usageMask) +{ jintArray jnids; int *nids; @@ -1232,7 +1290,8 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_findWild(JNIEnv *env, nids = (int *)malloc(sizeof(int) * numNids); ctx = 0; - for (i = 0; i < numNids; i++) { + for (i = 0; i < numNids; i++) + { TreeFindNodeWild(path, &nids[i], &ctx, usageMask); } jnids = (*env)->NewIntArray(env, numNids); @@ -1248,7 +1307,8 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_findWild(JNIEnv *env, */ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getMembersOf(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ jintArray jnids; int numNids, numNidsLen, status; int *nids; @@ -1259,17 +1319,20 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getMembersOf(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list1); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } - if (numNids > 0) { + if (numNids > 0) + { nids = (int *)malloc(numNids * sizeof(nid)); nci_list2[0].buffer_length = sizeof(int) * numNids; nci_list2[0].pointer = nids; status = TreeGetNci(nid, nci_list2); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } @@ -1287,7 +1350,8 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getMembersOf(JNIEnv *env, */ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getChildrenOf(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ jintArray jnids; int *nids; int numNids, numNidsLen, status; @@ -1298,17 +1362,20 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getChildrenOf(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list1); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } - if (numNids > 0) { + if (numNids > 0) + { nids = (int *)malloc(numNids * sizeof(nid)); nci_list2[0].buffer_length = sizeof(int) * numNids; nci_list2[0].pointer = nids; status = TreeGetNci(nid, nci_list2); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } @@ -1325,7 +1392,8 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getChildrenOf(JNIEnv *env, * Signature: (I)I */ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getParent(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int parentNid; int nidLen = sizeof(int); struct nci_itm nciList[] = {{4, NciPARENT, &parentNid, &nidLen}, @@ -1343,7 +1411,8 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getParent(JNIEnv *env, jclass cls, * Signature: ()I */ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getDefault(JNIEnv *env, - jclass cls) { + jclass cls) +{ int defaultNid, status; status = TreeGetDefaultNid(&defaultNid); @@ -1358,7 +1427,8 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getDefault(JNIEnv *env, * Signature: (I)V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_setDefault(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ int status = TreeSetDefaultNid(nid); if (!(status & 1)) RaiseException(env, MdsGetMsg(status), status); @@ -1371,7 +1441,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_setDefault(JNIEnv *env, jclass cls, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginSegment( JNIEnv *env, jclass cls, jint nid, jobject data, jobject start, jobject end, - jobject dim) { + jobject dim) +{ struct descriptor *dataD, *startD, *endD, *dimD; int status; @@ -1399,7 +1470,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginSegment( JNIEXPORT void JNICALL Java_mdstree_MdsTree_putRow(JNIEnv *env, jclass cls, jint nid, jobject data, jlong jtime, - jboolean isFirst) { + jboolean isFirst) +{ struct descriptor *dataD; int status; @@ -1418,7 +1490,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putRow(JNIEnv *env, jclass cls, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginCachedSegment( JNIEnv *env, jclass cls, jint nid, jobject data, jobject start, jobject end, - jobject dim) { + jobject dim) +{ struct descriptor *dataD, *startD, *endD, *dimD; int status; @@ -1431,7 +1504,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginCachedSegment( freeDescrip(startD); freeDescrip(endD); freeDescrip(dimD); - if (!(status & 1)) { + if (!(status & 1)) + { freeDescrip(dataD); RaiseException(env, MdsGetMsg(status), status); } @@ -1452,7 +1526,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedRow(JNIEnv *env, jclass cls, jint nid, jobject data, jlong jtime, - jboolean isLast) { + jboolean isLast) +{ struct descriptor *dataD; int status; @@ -1473,7 +1548,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedRow(JNIEnv *env, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_openCached(JNIEnv *env, jclass cls, jstring jexperiment, - jint shot) { + jint shot) +{ char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = RTreeOpen(experiment, shot); @@ -1489,7 +1565,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_openCached(JNIEnv *env, jclass cls, */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_closeCached(JNIEnv *env, jclass cls, jstring jexperiment, - jint shot) { + jint shot) +{ char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeClose(experiment, shot); @@ -1506,7 +1583,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_closeCached(JNIEnv *env, jclass cls, JNIEXPORT void JNICALL Java_mdstree_MdsTree_configureCache(JNIEnv *env, jclass cls, jboolean shared, - jint size) { + jint size) +{ RTreeConfigure(shared, size); } @@ -1516,7 +1594,8 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_configureCache(JNIEnv *env, * Signature: ()V */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_synchCache(JNIEnv *env, - jclass cls) { + jclass cls) +{ RTreeSynch(); } @@ -1529,7 +1608,8 @@ static void callback(int nid, void *obj); */ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedData(JNIEnv *env, jclass cls, jint nid, - jobject data) { + jobject data) +{ int status; struct descriptor *dataD; @@ -1547,13 +1627,15 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedData(JNIEnv *env, */ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getCachedData(JNIEnv *env, jclass cls, - jint nid) { + jint nid) +{ EMPTYXD(xd); int status; jobject retObj; status = RTreeGetRecord(nid, &xd); - if (!(status & 1)) { + if (!(status & 1)) + { RaiseException(env, MdsGetMsg(status), status); return NULL; } @@ -1564,16 +1646,20 @@ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getCachedData(JNIEnv *env, } #define MAX_CALLBACKS 512 -static struct { +static struct +{ jobject object; char *callbackDescr; } callbackInfo[MAX_CALLBACKS]; -static char *getCallbackDesc(jobject obj, JNIEnv *env) { +static char *getCallbackDesc(jobject obj, JNIEnv *env) +{ int i; - for (i = 0; i < MAX_CALLBACKS; i++) { + for (i = 0; i < MAX_CALLBACKS; i++) + { if (callbackInfo[i].object && - (*env)->IsSameObject(env, obj, callbackInfo[i].object)) { + (*env)->IsSameObject(env, obj, callbackInfo[i].object)) + { callbackInfo[i].object = 0; return callbackInfo[i].callbackDescr; } @@ -1581,10 +1667,13 @@ static char *getCallbackDesc(jobject obj, JNIEnv *env) { return 0; } -static void setCallbackDesc(jobject object, char *callbackDescr) { +static void setCallbackDesc(jobject object, char *callbackDescr) +{ int i; - for (i = 0; i < MAX_CALLBACKS; i++) { - if (!callbackInfo[i].object) { + for (i = 0; i < MAX_CALLBACKS; i++) + { + if (!callbackInfo[i].object) + { callbackInfo[i].object = object; callbackInfo[i].callbackDescr = callbackDescr; return; @@ -1600,13 +1689,15 @@ static void setCallbackDesc(jobject object, char *callbackDescr) { JNIEXPORT void JNICALL Java_mdstree_MdsTree_registerCallback(JNIEnv *env, jclass cls, jint nid, - jobject object) { + jobject object) +{ int status; jobject refObj = (*env)->NewGlobalRef(env, object); char *callbackDescr = RTreeSetCallback(nid, (void *)refObj, callback); RTreeSetWarm(nid, 1); - if (jvm == 0) { + if (jvm == 0) + { status = (*env)->GetJavaVM(env, &jvm); if (status) printf("GetJavaVM error %d\n", status); @@ -1622,13 +1713,15 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_registerCallback(JNIEnv *env, JNIEXPORT void JNICALL Java_mdstree_MdsTree_unregisterCallback(JNIEnv *env, jclass cls, jint nid, - jobject object) { + jobject object) +{ char *callbackDescr = getCallbackDesc(object, env); if (callbackDescr) RTreeClearCallback(nid, callbackDescr); } -static void callback(int nid, void *obj) { +static void callback(int nid, void *obj) +{ jmethodID mid; JNIEnv *env; jclass cls; diff --git a/mdsobjects/cpp/mdstree.c b/mdsobjects/cpp/mdstree.c index 65a21b5378..13dc2f56d8 100644 --- a/mdsobjects/cpp/mdstree.c +++ b/mdsobjects/cpp/mdstree.c @@ -83,7 +83,8 @@ int putTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size); int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc); -int getTreeData(void *dbid, int nid, void **data, void *tree) { +int getTreeData(void *dbid, int nid, void **data, void *tree) +{ EMPTYXD(xd); int status; @@ -96,7 +97,8 @@ int getTreeData(void *dbid, int nid, void **data, void *tree) { return status; } -int putTreeData(void *dbid, int nid, void *data) { +int putTreeData(void *dbid, int nid, void *data) +{ struct descriptor_xd *xdPtr; int status; @@ -106,7 +108,8 @@ int putTreeData(void *dbid, int nid, void *data) { return status; } -int deleteTreeData(void *dbid, int nid) { +int deleteTreeData(void *dbid, int nid) +{ EMPTYXD(xd); int status; @@ -114,7 +117,8 @@ int deleteTreeData(void *dbid, int nid) { return status; } -void convertTime(int *time, char *retTime) { +void convertTime(int *time, char *retTime) +{ char timeStr[512]; unsigned short retLen; struct descriptor time_dsc = {511, DTYPE_T, CLASS_S, timeStr}; @@ -124,7 +128,8 @@ void convertTime(int *time, char *retTime) { strcpy(retTime, timeStr); } -int doTreeMethod(void *dbid, int nid, char *method) { +int doTreeMethod(void *dbid, int nid, char *method) +{ struct descriptor nidD = {sizeof(int), DTYPE_NID, CLASS_S, (char *)&nid}; struct descriptor methodD = {strlen(method), DTYPE_T, CLASS_S, method}; @@ -132,7 +137,8 @@ int doTreeMethod(void *dbid, int nid, char *method) { } int beginTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *dimDsc) { + void *endDsc, void *dimDsc) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -152,7 +158,8 @@ int beginTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, } int makeTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *dimDsc, int rowsFilled) { + void *endDsc, void *dimDsc, int rowsFilled) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -173,7 +180,8 @@ int makeTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, int makeTreeSegmentResampled(void *dbid, int nid, void *dataDsc, void *startDsc, void *endDsc, void *dimDsc, int rowsFilled, - int resNid, int resFactor) { + int resNid, int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -194,7 +202,8 @@ int makeTreeSegmentResampled(void *dbid, int nid, void *dataDsc, void *startDsc, } int makeTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, void *endDsc, void *dimDsc, int rowsFilled, - int resNid, int resFactor) { + int resNid, int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -216,7 +225,8 @@ int makeTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, int beginTreeSegmentResampled(void *dbid, int nid, void *dataDsc, void *startDsc, void *endDsc, void *dimDsc, - int resNid, int resFactor) { + int resNid, int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -237,7 +247,8 @@ int beginTreeSegmentResampled(void *dbid, int nid, void *dataDsc, int beginTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, void *endDsc, void *dimDsc, int resNid, - int resFactor) { + int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; @@ -257,7 +268,8 @@ int beginTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, } #define PUTROW_BUFSIZE 1000 -int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size) { +int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -267,7 +279,8 @@ int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size) { return status; } -int putTreeSegment(void *dbid, int nid, void *dataDsc, int ofs) { +int putTreeSegment(void *dbid, int nid, void *dataDsc, int ofs) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -278,7 +291,8 @@ int putTreeSegment(void *dbid, int nid, void *dataDsc, int ofs) { } int putTreeSegmentResampled(void *dbid, int nid, void *dataDsc, int ofs, - int resNid, int resFactor) { + int resNid, int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -290,7 +304,8 @@ int putTreeSegmentResampled(void *dbid, int nid, void *dataDsc, int ofs, } int putTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, int ofs, - int resNid, int resFactor) { + int resNid, int resFactor) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -302,18 +317,21 @@ int putTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, int ofs, } int updateTreeSegment(void *dbid, int nid, int segIdx, void *startDsc, - void *endDsc, void *timeDsc) { + void *endDsc, void *timeDsc) +{ struct descriptor_xd *startXd = (struct descriptor_xd *)startDsc; struct descriptor_xd *endXd = (struct descriptor_xd *)endDsc; struct descriptor_xd *timeXd = (struct descriptor_xd *)timeDsc; int status, numSegments, segmentIdx; - if (segIdx == -1) { + if (segIdx == -1) + { status = _TreeGetNumSegments(dbid, nid, &numSegments); if (!(status & 1)) return status; segmentIdx = numSegments - 1; - } else + } + else segmentIdx = segIdx; status = _TreeUpdateSegment(dbid, nid, (struct descriptor *)startXd->pointer, (struct descriptor *)endXd->pointer, @@ -324,12 +342,14 @@ int updateTreeSegment(void *dbid, int nid, int segIdx, void *startDsc, return status; } -int getTreeNumSegments(void *dbid, int nid, int *numSegments) { +int getTreeNumSegments(void *dbid, int nid, int *numSegments) +{ return _TreeGetNumSegments(dbid, nid, numSegments); } int getTreeSegmentLimits(void *dbid, int nid, int idx, void **startPtr, - void **endPtr) { + void **endPtr) +{ struct descriptor_xd *startXd, *endXd; EMPTYXD(emptyXd); @@ -344,29 +364,34 @@ int getTreeSegmentLimits(void *dbid, int nid, int idx, void **startPtr, } int getTreeSegmentInfo(void *dbid, int nid, int segIdx, char *dtype, - char *dimct, int *dims, int *nextRow) { + char *dimct, int *dims, int *nextRow) +{ return _TreeGetSegmentInfo(dbid, nid, segIdx, dtype, dimct, dims, nextRow); } int getTreeSegment(void *dbid, int nid, int segIdx, void **dataDsc, - void **timeDsc) { + void **timeDsc) +{ EMPTYXD(emptyXd); struct descriptor_xd *timeXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); *timeXd = emptyXd; *timeDsc = timeXd; struct descriptor_xd *dataXd; - if (dataDsc) { + if (dataDsc) + { dataXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); *dataXd = emptyXd; *dataDsc = dataXd; - } else + } + else dataXd = NULL; return _TreeGetSegment(dbid, nid, segIdx, dataXd, timeXd); } int setTreeTimeContext(void *dbid, void *startDsc, void *endDsc, - void *deltaDsc) { + void *deltaDsc) +{ int status; status = _TreeSetTimeContext(dbid, (struct descriptor *)startDsc, @@ -382,7 +407,8 @@ int setTreeTimeContext(void *dbid, void *startDsc, void *endDsc, return status; } -int beginTreeTimestampedSegment(void *dbid, int nid, void *dataDsc) { +int beginTreeTimestampedSegment(void *dbid, int nid, void *dataDsc) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -393,7 +419,8 @@ int beginTreeTimestampedSegment(void *dbid, int nid, void *dataDsc) { } int putTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, - int64_t *times) { + int64_t *times) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -404,7 +431,8 @@ int putTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, } int makeTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, - int64_t *times, int rowsFilled) { + int64_t *times, int rowsFilled) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -414,7 +442,8 @@ int makeTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, return status; } -int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc) { +int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc) +{ struct descriptor_xd *dataXd = (struct descriptor_xd *)dataDsc; int status; @@ -424,7 +453,8 @@ int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc) { } int getTreeXNci(void *dbid, int nid, const char *name, void **data, - void *tree) { + void *tree) +{ EMPTYXD(xd); int status; @@ -436,7 +466,8 @@ int getTreeXNci(void *dbid, int nid, const char *name, void **data, return status; } -int getTreeSegmentScale(void *dbid, int nid, void **sclDsc) { +int getTreeSegmentScale(void *dbid, int nid, void **sclDsc) +{ EMPTYXD(emptyXd); struct descriptor_xd *sclXd = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); @@ -444,7 +475,8 @@ int getTreeSegmentScale(void *dbid, int nid, void **sclDsc) { *sclDsc = sclXd; return _TreeGetSegmentScale(dbid, nid, sclXd); } -int setTreeSegmentScale(void *dbid, int nid, void *sclDsc) { +int setTreeSegmentScale(void *dbid, int nid, void *sclDsc) +{ struct descriptor_xd *sclXd = (struct descriptor_xd *)sclDsc; int status = _TreeSetSegmentScale(dbid, nid, sclXd->pointer); freeDsc(sclXd); diff --git a/mdsobjects/cpp/mdstreeobjects.cpp b/mdsobjects/cpp/mdstreeobjects.cpp index 41176ad8df..60f0bfab13 100644 --- a/mdsobjects/cpp/mdstreeobjects.cpp +++ b/mdsobjects/cpp/mdstreeobjects.cpp @@ -39,96 +39,98 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace MDSplus; using namespace std; -extern "C" { -// From treeshrp.h -int TreeFindTag(char *tagnam, char *treename, int *tagidx); - -// From libroutines.h -int LibConvertDateString(char *asc_time, int64_t *qtime); - -// From mdsshr.h -const char *MdsClassString(int id); -const char *MdsDtypeString(int id); - -// From mdsdata.c -void freeDsc(void *dscPtr); -void *compileFromExprWithArgs(char *expr, int nArgs, void *args, void *tree); -void *evaluateData(void *dscPtr, int isEvaluate); -void *deserializeData(char *serialized, int size); -char *decompileDsc(void *dscPtr); -void *convertFromDsc(void *dscPtr, Tree *tree); - -void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr); -void *convertToArrayDsc(int clazz, int dtype, int length, int l_length, - int nDims, int *dims, void *ptr); -void *convertToCompoundDsc(int clazz, int dtype, int length, void *ptr, - int ndescs, void **descs); -void *convertToApdDsc(int ndescs, void **ptr); -void *convertToByte(void *dsc); -void *convertToShort(void *dsc); -void *convertToInt(void *dsc); -void *convertToLong(void *dsc); -void *convertToFloat(void *dsc); -void *convertToDouble(void *dsc); -void *convertToShape(void *dcs); - -// From mdstree.c -void convertTime(void *dbid, int *time, char *retTime); -int getTreeData(void *dbid, int nid, void **data, void *tree); -int putTreeData(void *dbid, int nid, void *data); -int deleteTreeData(void *dbid, int nid); -int doTreeMethod(void *dbid, int nid, char *method); -int beginTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *timeDsc); -int beginTreeSegmentResampled(void *dbid, int nid, void *dataDsc, - void *startDsc, void *endDsc, void *timeDsc, - int resNid, int resFactor); -int beginTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *timeDsc, int resNid, - int resFactor); -int makeTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *timeDsc, int rowsFilled); -int makeTreeSegmentResampled(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *timeDsc, int rowsFilled, - int resNid, int resFactor); -int makeTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, - void *endDsc, void *timeDsc, int rowsFilled, - int resNid, int resFactor); -int putTreeSegment(void *dbid, int nid, void *dataDsc, int ofs); -int putTreeSegmentResampled(void *dbid, int nid, void *dataDsc, int ofs, +extern "C" +{ + // From treeshrp.h + int TreeFindTag(char *tagnam, char *treename, int *tagidx); + + // From libroutines.h + int LibConvertDateString(char *asc_time, int64_t *qtime); + + // From mdsshr.h + const char *MdsClassString(int id); + const char *MdsDtypeString(int id); + + // From mdsdata.c + void freeDsc(void *dscPtr); + void *compileFromExprWithArgs(char *expr, int nArgs, void *args, void *tree); + void *evaluateData(void *dscPtr, int isEvaluate); + void *deserializeData(char *serialized, int size); + char *decompileDsc(void *dscPtr); + void *convertFromDsc(void *dscPtr, Tree *tree); + + void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr); + void *convertToArrayDsc(int clazz, int dtype, int length, int l_length, + int nDims, int *dims, void *ptr); + void *convertToCompoundDsc(int clazz, int dtype, int length, void *ptr, + int ndescs, void **descs); + void *convertToApdDsc(int ndescs, void **ptr); + void *convertToByte(void *dsc); + void *convertToShort(void *dsc); + void *convertToInt(void *dsc); + void *convertToLong(void *dsc); + void *convertToFloat(void *dsc); + void *convertToDouble(void *dsc); + void *convertToShape(void *dcs); + + // From mdstree.c + void convertTime(void *dbid, int *time, char *retTime); + int getTreeData(void *dbid, int nid, void **data, void *tree); + int putTreeData(void *dbid, int nid, void *data); + int deleteTreeData(void *dbid, int nid); + int doTreeMethod(void *dbid, int nid, char *method); + int beginTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, + void *endDsc, void *timeDsc); + int beginTreeSegmentResampled(void *dbid, int nid, void *dataDsc, + void *startDsc, void *endDsc, void *timeDsc, + int resNid, int resFactor); + int beginTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, + void *endDsc, void *timeDsc, int resNid, + int resFactor); + int makeTreeSegment(void *dbid, int nid, void *dataDsc, void *startDsc, + void *endDsc, void *timeDsc, int rowsFilled); + int makeTreeSegmentResampled(void *dbid, int nid, void *dataDsc, void *startDsc, + void *endDsc, void *timeDsc, int rowsFilled, + int resNid, int resFactor); + int makeTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, void *startDsc, + void *endDsc, void *timeDsc, int rowsFilled, int resNid, int resFactor); -int putTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, int ofs, - int resNid, int resFactor); -int updateTreeSegment(void *dbid, int nid, int segIdx, void *startDsc, - void *endDsc, void *timeDsc); -int getTreeNumSegments(void *dbid, int nid, int *numSegments); -int getTreeSegmentScale(void *dbid, int nid, void *scale); -int setTreeSegmentScale(void *dbid, int nid, void *scale); -int getTreeSegmentLimits(void *dbid, int nid, int idx, void **startDsc, - void **endDsc); -int getTreeSegment(void *dbid, int nid, int segIdx, void **dataDsc, - void **timeDsc); -int setTreeTimeContext(void *dbid, void *startDsc, void *endDsc, - void *deltaDsc); -int beginTreeTimestampedSegment(void *dbid, int nid, void *dataDsc); -int putTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, - int64_t *times); -int makeTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, - int64_t *times, int rowsFilled); -int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc); -int getTreeXNci(void *dbid, int nid, const char *name, void **data, void *tree); -int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size); -int getTreeSegmentInfo(void *dbid, int nid, int segIdx, char *dtype, - char *dimct, int *dims, int *nextRow); -// From TreeFindTagWild.c -char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout); -char *MdsGetMsg(int status); -void *TreeDbid(); + int putTreeSegment(void *dbid, int nid, void *dataDsc, int ofs); + int putTreeSegmentResampled(void *dbid, int nid, void *dataDsc, int ofs, + int resNid, int resFactor); + int putTreeSegmentMinMax(void *dbid, int nid, void *dataDsc, int ofs, + int resNid, int resFactor); + int updateTreeSegment(void *dbid, int nid, int segIdx, void *startDsc, + void *endDsc, void *timeDsc); + int getTreeNumSegments(void *dbid, int nid, int *numSegments); + int getTreeSegmentScale(void *dbid, int nid, void *scale); + int setTreeSegmentScale(void *dbid, int nid, void *scale); + int getTreeSegmentLimits(void *dbid, int nid, int idx, void **startDsc, + void **endDsc); + int getTreeSegment(void *dbid, int nid, int segIdx, void **dataDsc, + void **timeDsc); + int setTreeTimeContext(void *dbid, void *startDsc, void *endDsc, + void *deltaDsc); + int beginTreeTimestampedSegment(void *dbid, int nid, void *dataDsc); + int putTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, + int64_t *times); + int makeTreeTimestampedSegment(void *dbid, int nid, void *dataDsc, + int64_t *times, int rowsFilled); + int setTreeXNci(void *dbid, int nid, const char *name, void *dataDsc); + int getTreeXNci(void *dbid, int nid, const char *name, void **data, void *tree); + int putTreeRow(void *dbid, int nid, void *dataDsc, int64_t *time, int size); + int getTreeSegmentInfo(void *dbid, int nid, int segIdx, char *dtype, + char *dimct, int *dims, int *nextRow); + // From TreeFindTagWild.c + char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout); + char *MdsGetMsg(int status); + void *TreeDbid(); } #define MAX_ARGS 512 -static int convertUsage(std::string const &usage) { +static int convertUsage(std::string const &usage) +{ if (usage == "ACTION") return TreeUSAGE_ACTION; else if (usage == "ANY") @@ -162,7 +164,8 @@ static int convertUsage(std::string const &usage) { static Mutex treeMutex; Tree::Tree(char const *name, int shot) - : name(name), shot(shot), ctx(nullptr), fromActiveTree(false) { + : name(name), shot(shot), ctx(nullptr), fromActiveTree(false) +{ int status = _TreeOpen(&ctx, name, shot, 0); if (!(status & 1)) throw MdsException(status); @@ -173,11 +176,13 @@ Tree::Tree(char const *name, int shot, void *ctx) : name(name), shot(shot), ctx(ctx), fromActiveTree(true) {} Tree::Tree(Tree *tree) - : name(tree->name), shot(tree->shot), ctx(tree->ctx), fromActiveTree(true) { + : name(tree->name), shot(tree->shot), ctx(tree->ctx), fromActiveTree(true) +{ } Tree::Tree(char const *name, int shot, char const *mode) - : name(name), shot(shot), ctx(nullptr), fromActiveTree(false) { + : name(name), shot(shot), ctx(nullptr), fromActiveTree(false) +{ std::string upMode(mode); std::transform(upMode.begin(), upMode.end(), upMode.begin(), static_cast(&std::toupper)); @@ -198,15 +203,19 @@ Tree::Tree(char const *name, int shot, char const *mode) throw MdsException(status); } -Tree::~Tree() { +Tree::~Tree() +{ if (fromActiveTree) return; - if (isModified()) { + if (isModified()) + { int status = _TreeQuitTree(&ctx, name.c_str(), shot); (void)status; // if(!(status & 1)) // throw MdsException(status); - } else { + } + else + { int status = _TreeClose(&ctx, name.c_str(), shot); (void)status; // if(!(status & 1)) @@ -221,7 +230,8 @@ EXPORT void *Tree::operator new(size_t sz) { return ::operator new(sz); } EXPORT void Tree::operator delete(void *p) { ::operator delete(p); } -void Tree::edit(const bool st) { +void Tree::edit(const bool st) +{ if (isReadOnly()) throw MdsException("Tree is read only"); int status = st ? _TreeOpenEdit(&ctx, name.c_str(), shot) @@ -230,7 +240,8 @@ void Tree::edit(const bool st) { throw MdsException(status); } -void Tree::write() { +void Tree::write() +{ int status = _TreeWriteTree(&ctx, name.c_str(), shot); if (!(status & 1)) throw MdsException(status); @@ -247,81 +258,99 @@ Data *Tree::tdiEvaluate(Data *data) { return data->evaluate(this); } Data *Tree::tdiData(Data *data) { return data->data(this); } -Data *Tree::tdiCompile(const char *expr) { +Data *Tree::tdiCompile(const char *expr) +{ return MDSplus::compile(expr, this); } -Data *Tree::tdiCompile(const char *expr, Data *arg1) { +Data *Tree::tdiCompile(const char *expr, Data *arg1) +{ return MDSplus::compileWithArgs(expr, this, 1, arg1); } -Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2) { +Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2) +{ return MDSplus::compileWithArgs(expr, this, 2, arg1, arg2); } -Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3) { +Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3) +{ return MDSplus::compileWithArgs(expr, this, 3, arg1, arg2, arg3); } Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4) { + Data *arg4) +{ return MDSplus::compileWithArgs(expr, this, 4, arg1, arg2, arg3, arg4); } Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5) { + Data *arg4, Data *arg5) +{ return MDSplus::compileWithArgs(expr, this, 5, arg1, arg2, arg3, arg4, arg5); } Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6) { + Data *arg4, Data *arg5, Data *arg6) +{ return MDSplus::compileWithArgs(expr, this, 6, arg1, arg2, arg3, arg4, arg5, arg6); } Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7) { + Data *arg4, Data *arg5, Data *arg6, Data *arg7) +{ return MDSplus::compileWithArgs(expr, this, 7, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } Data *Tree::tdiCompile(const char *expr, Data *arg1, Data *arg2, Data *arg3, Data *arg4, Data *arg5, Data *arg6, Data *arg7, - Data *arg8) { + Data *arg8) +{ return MDSplus::compileWithArgs(expr, this, 8, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } Data *Tree::tdiExecute(const char *expr) { return execute(expr, this); } -Data *Tree::tdiExecute(const char *expr, Data *arg1) { +Data *Tree::tdiExecute(const char *expr, Data *arg1) +{ return MDSplus::executeWithArgs(expr, this, 1, arg1); } -Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2) { +Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2) +{ return MDSplus::executeWithArgs(expr, this, 2, arg1, arg2); } -Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3) { +Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3) +{ return MDSplus::executeWithArgs(expr, this, 3, arg1, arg2, arg3); } Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4) { + Data *arg4) +{ return MDSplus::executeWithArgs(expr, this, 4, arg1, arg2, arg3, arg4); } Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5) { + Data *arg4, Data *arg5) +{ return MDSplus::executeWithArgs(expr, this, 5, arg1, arg2, arg3, arg4, arg5); } Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6) { + Data *arg4, Data *arg5, Data *arg6) +{ return MDSplus::executeWithArgs(expr, this, 6, arg1, arg2, arg3, arg4, arg5, arg6); } Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, - Data *arg4, Data *arg5, Data *arg6, Data *arg7) { + Data *arg4, Data *arg5, Data *arg6, Data *arg7) +{ return MDSplus::executeWithArgs(expr, this, 7, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } Data *Tree::tdiExecute(const char *expr, Data *arg1, Data *arg2, Data *arg3, Data *arg4, Data *arg5, Data *arg6, Data *arg7, - Data *arg8) { + Data *arg8) +{ return MDSplus::executeWithArgs(expr, this, 8, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } -TreeNode *Tree::addNode(char const *name, char const *usage) { +TreeNode *Tree::addNode(char const *name, char const *usage) +{ int newNid; int status = _TreeAddNode(ctx, name, &newNid, convertUsage(usage)); if (!(status & 1)) @@ -329,7 +358,8 @@ TreeNode *Tree::addNode(char const *name, char const *usage) { return new TreeNode(newNid, this); } -TreeNode *Tree::addDevice(char const *name, char const *type) { +TreeNode *Tree::addDevice(char const *name, char const *type) +{ int newNid; int status = _TreeAddConglom(ctx, name, type, &newNid); if (!(status & 1)) @@ -337,7 +367,8 @@ TreeNode *Tree::addDevice(char const *name, char const *type) { return new TreeNode(newNid, this); } -void Tree::remove(char const *name) { +void Tree::remove(char const *name) +{ int count; AutoPointer delNode(getNode(name)); int status = _TreeDeleteNodeInitialize(ctx, delNode.ptr->getNid(), &count, 1); @@ -347,27 +378,32 @@ void Tree::remove(char const *name) { throw MdsException(status); } -TreeNode *Tree::getNode(char const *path) { +TreeNode *Tree::getNode(char const *path) +{ int nid; int status = _TreeFindNode(ctx, path, &nid); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } return new TreeNode(nid, this); } -TreeNode *Tree::getNode(TreePath *path) { +TreeNode *Tree::getNode(TreePath *path) +{ AutoArray pathName(path->getString()); return getNode(pathName.ptr); } -TreeNode *Tree::getNode(String *path) { +TreeNode *Tree::getNode(String *path) +{ AutoArray pathName(path->getString()); return getNode(pathName.ptr); } -TreeNodeArray *Tree::getNodeWild(char const *path, int usageMask) { +TreeNodeArray *Tree::getNodeWild(char const *path, int usageMask) +{ // FIXME: This function doesn't need nids at all. Store a vector of TreeNodes // built right in the while loop. Need better testing before that change, // though. @@ -392,17 +428,20 @@ TreeNodeArray *Tree::getNodeWild(char const *path, int usageMask) { return nodeArray; } -TreeNodeArray *Tree::getNodeWild(char const *path) { +TreeNodeArray *Tree::getNodeWild(char const *path) +{ return getNodeWild(path, -1); } -void Tree::setDefault(TreeNode *treeNode) { +void Tree::setDefault(TreeNode *treeNode) +{ int status = _TreeSetDefaultNid(ctx, treeNode->getNid()); if (!(status & 1)) throw MdsException(status); } -TreeNode *Tree::getDefault() { +TreeNode *Tree::getDefault() +{ int nid; int status = _TreeGetDefaultNid(ctx, &nid); @@ -411,7 +450,8 @@ TreeNode *Tree::getDefault() { return new TreeNode(nid, this); } -static bool dbiTest(void *ctx, short int code) { +static bool dbiTest(void *ctx, short int code) +{ int supports; int len; struct dbi_itm dbiList[] = {{sizeof(int), code, &supports, &len}, @@ -424,11 +464,13 @@ static bool dbiTest(void *ctx, short int code) { return supports ? true : false; } -bool Tree::versionsInPulseEnabled() { +bool Tree::versionsInPulseEnabled() +{ return dbiTest(ctx, DbiVERSIONS_IN_PULSE); } -bool Tree::versionsInModelEnabled() { +bool Tree::versionsInModelEnabled() +{ return dbiTest(ctx, DbiVERSIONS_IN_MODEL); } @@ -438,7 +480,8 @@ bool Tree::isOpenForEdit() { return dbiTest(ctx, DbiOPEN_FOR_EDIT); } bool Tree::isReadOnly() { return dbiTest(ctx, DbiOPEN_READONLY); } -static void dbiSet(void *ctx, short int code, bool value) { +static void dbiSet(void *ctx, short int code, bool value) +{ int len; int intVal = value ? 1 : 0; struct dbi_itm dbiList[] = {{sizeof(int), code, &intVal, &len}, @@ -449,15 +492,18 @@ static void dbiSet(void *ctx, short int code, bool value) { throw MdsException(status); } -void Tree::setVersionsInModel(bool verEnabled) { +void Tree::setVersionsInModel(bool verEnabled) +{ dbiSet(ctx, DbiVERSIONS_IN_MODEL, verEnabled); } -void Tree::setVersionsInPulse(bool verEnabled) { +void Tree::setVersionsInPulse(bool verEnabled) +{ dbiSet(ctx, DbiVERSIONS_IN_PULSE, verEnabled); } -void Tree::setViewDate(char *date) { +void Tree::setViewDate(char *date) +{ int64_t qtime; int status = LibConvertDateString(date, &qtime); @@ -468,7 +514,8 @@ void Tree::setViewDate(char *date) { throw MdsException(status); } -void Tree::setTimeContext(Data *start, Data *end, Data *delta) { +void Tree::setTimeContext(Data *start, Data *end, Data *delta) +{ int status = setTreeTimeContext(ctx, (start) ? start->convertToDsc() : 0, (end) ? end->convertToDsc() : 0, (delta) ? delta->convertToDsc() : 0); @@ -476,35 +523,41 @@ void Tree::setTimeContext(Data *start, Data *end, Data *delta) { throw MdsException(status); } -void Tree::setCurrent(char const *treeName, int shot) { +void Tree::setCurrent(char const *treeName, int shot) +{ int status = TreeSetCurrentShotId(treeName, shot); if (!(status & 1)) throw MdsException(status); } -int Tree::getCurrent(char const *treeName) { +int Tree::getCurrent(char const *treeName) +{ return TreeGetCurrentShotId(treeName); } -void Tree::createPulse(int shot) { +void Tree::createPulse(int shot) +{ int status = _TreeCreatePulseFile(getCtx(), shot, 0, NULL); if (!(status & 1)) throw MdsException(status); } -void Tree::deletePulse(int shot) { +void Tree::deletePulse(int shot) +{ int status = _TreeDeletePulseFile(getCtx(), shot, 1); if (!(status & 1)) throw MdsException(status); } -StringArray *Tree::findTags(char *wild) { +StringArray *Tree::findTags(char *wild) +{ const int MAX_TAGS = 1024; char *tagNames[MAX_TAGS]; void *ctx = 0; int nTags = 0; int nidOut; - for (nTags = 0; nTags < MAX_TAGS; nTags++) { + for (nTags = 0; nTags < MAX_TAGS; nTags++) + { char *currTag = _TreeFindTagWild(getCtx(), wild, &nidOut, &ctx); if (!currTag) break; @@ -516,13 +569,15 @@ StringArray *Tree::findTags(char *wild) { delete[] tagNames[i]; return stArr; } -void Tree::removeTag(char const *tagName) { +void Tree::removeTag(char const *tagName) +{ int status = _TreeRemoveTag(getCtx(), tagName); if (!(status & 1)) throw MdsException(status); } -int64_t Tree::getDatafileSize() { +int64_t Tree::getDatafileSize() +{ int64_t size = _TreeGetDatafileSize(getCtx()); if (size == -1) throw MdsException("Cannot retrieve datafile size"); @@ -533,7 +588,8 @@ int64_t Tree::getDatafileSize() { // TreeNode ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void *TreeNode::convertToDsc() { +void *TreeNode::convertToDsc() +{ // AutoLock lock(treeMutex); // setActiveTree(tree); void *retDsc = completeConversionToDsc( @@ -542,7 +598,8 @@ void *TreeNode::convertToDsc() { return retDsc; } -Data *TreeNode::data() { +Data *TreeNode::data() +{ Data *d = getData(); AutoLock lock(treeMutex); setActiveTree(tree); @@ -551,7 +608,9 @@ Data *TreeNode::data() { return outD; } -template static T getNci(void *ctx, int nid, short int code) { +template +static T getNci(void *ctx, int nid, short int code) +{ T value = 0; int len; struct nci_itm nciList[] = {{sizeof(T), (nci_t)code, &value, &len}, @@ -564,7 +623,9 @@ template static T getNci(void *ctx, int nid, short int code) { return value; } -template <> std::string getNci(void *ctx, int nid, short int code) { +template <> +std::string getNci(void *ctx, int nid, short int code) +{ char value[1024] = {}; int len; struct nci_itm nciList[] = {{sizeof(value), (nci_t)code, &value, &len}, @@ -577,7 +638,8 @@ template <> std::string getNci(void *ctx, int nid, short int code) { return value; } -void TreeNode::setFlag(int flagOfs, bool flag) { +void TreeNode::setFlag(int flagOfs, bool flag) +{ int nciFlags; int status; int nciFlagsLen = sizeof(int); @@ -596,7 +658,8 @@ void TreeNode::setFlag(int flagOfs, bool flag) { } TreeNode::TreeNode(int nid, Tree *tree, Data *units, Data *error, Data *help, - Data *validation) { + Data *validation) +{ this->tree = 0; if (!tree && nid != 0) this->tree = getActiveTree(); @@ -611,7 +674,8 @@ TreeNode::TreeNode(int nid, Tree *tree, Data *units, Data *error, Data *help, setAccessory(units, error, help, validation); } -void TreeNode::setTree(Tree *tree) { +void TreeNode::setTree(Tree *tree) +{ if (this->tree) delete this->tree; this->tree = new Tree(tree); @@ -620,28 +684,34 @@ void TreeNode::setTree(Tree *tree) { EXPORT void *TreeNode::operator new(size_t sz) { return ::operator new(sz); } EXPORT void TreeNode::operator delete(void *p) { ::operator delete(p); } -TreeNode::~TreeNode() { +TreeNode::~TreeNode() +{ if (tree) delete tree; } -std::string TreeNode::getNciString(int itm) { +std::string TreeNode::getNciString(int itm) +{ return getNci(tree->getCtx(), nid, itm); } -char TreeNode::getNciChar(int itm) { +char TreeNode::getNciChar(int itm) +{ return getNci(tree->getCtx(), nid, itm); } -int TreeNode::getNciInt(int itm) { +int TreeNode::getNciInt(int itm) +{ return getNci(tree->getCtx(), nid, itm); } -int64_t TreeNode::getNciInt64(int itm) { +int64_t TreeNode::getNciInt64(int itm) +{ return getNci(tree->getCtx(), nid, itm); } -char *TreeNode::getPath() { +char *TreeNode::getPath() +{ resolveNid(); char *currPath = _TreeGetPath(tree->getCtx(), nid); char *path = new char[strlen(currPath) + 1]; @@ -650,12 +720,14 @@ char *TreeNode::getPath() { return path; } -std::string TreeNode::getPathStr() { +std::string TreeNode::getPathStr() +{ resolveNid(); return AutoString(getPath()).string; } -char *TreeNode::getMinPath() { +char *TreeNode::getMinPath() +{ resolveNid(); std::string path = getNciString(NciMINPATH); char *retPath = new char[path.length() + 1]; @@ -663,11 +735,13 @@ char *TreeNode::getMinPath() { return retPath; } -std::string TreeNode::getMinPathStr() { +std::string TreeNode::getMinPathStr() +{ return AutoString(getMinPath()).string; } -char *TreeNode::getFullPath() { +char *TreeNode::getFullPath() +{ resolveNid(); std::string path = getNciString(NciFULLPATH); char *retPath = new char[path.length() + 1]; @@ -675,11 +749,13 @@ char *TreeNode::getFullPath() { return retPath; } -std::string TreeNode::getFullPathStr() { +std::string TreeNode::getFullPathStr() +{ return AutoString(getFullPath()).string; } -char *TreeNode::getOriginalPartName() { +char *TreeNode::getOriginalPartName() +{ resolveNid(); std::string path = getNciString(NciORIGINAL_PART_NAME); char *retPath = new char[path.length() + 1]; @@ -687,11 +763,13 @@ char *TreeNode::getOriginalPartName() { return retPath; } -std::string TreeNode::getOriginalPartNameStr() { +std::string TreeNode::getOriginalPartNameStr() +{ return AutoString(getOriginalPartName()).string; } -char *TreeNode::getNodeName() { +char *TreeNode::getNodeName() +{ resolveNid(); std::string path = getNciString(NciNODE_NAME); char *retPath = new char[path.length() + 1]; @@ -703,42 +781,51 @@ char *TreeNode::getNodeName() { return retPath; } -std::string TreeNode::getNodeNameStr() { +std::string TreeNode::getNodeNameStr() +{ return AutoString(getNodeName()).string; } -Data *TreeNode::getData() { +Data *TreeNode::getData() +{ Data *data = 0; resolveNid(); int status = getTreeData(tree->getCtx(), nid, (void **)&data, tree); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } return data; } -void TreeNode::putData(Data *data) { +void TreeNode::putData(Data *data) +{ resolveNid(); int status = putTreeData(tree->getCtx(), nid, (void *)data); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } } -void TreeNode::deleteData() { +void TreeNode::deleteData() +{ resolveNid(); int status = deleteTreeData(tree->getCtx(), nid); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } } -bool TreeNode::isOn() { +bool TreeNode::isOn() +{ resolveNid(); return (_TreeIsOn(tree->getCtx(), nid) & 1) ? true : false; } -void TreeNode::setOn(bool on) { +void TreeNode::setOn(bool on) +{ resolveNid(); if (on) _TreeTurnOn(tree->getCtx(), nid); @@ -746,32 +833,38 @@ void TreeNode::setOn(bool on) { _TreeTurnOff(tree->getCtx(), nid); } -int TreeNode::getLength() { +int TreeNode::getLength() +{ resolveNid(); return getNciInt(NciLENGTH); } -int TreeNode::getCompressedLength() { +int TreeNode::getCompressedLength() +{ resolveNid(); return getNciInt(NciRLENGTH); } -int TreeNode::getStatus() { +int TreeNode::getStatus() +{ resolveNid(); return getNciInt(NciSTATUS); } -int TreeNode::getOwnerId() { +int TreeNode::getOwnerId() +{ resolveNid(); return getNciInt(NciOWNER_ID); } -int64_t TreeNode::getTimeInserted() { +int64_t TreeNode::getTimeInserted() +{ resolveNid(); return getNciInt64(NciTIME_INSERTED); } -Data *TreeNode::getExtendedAttribute(const char *name) { +Data *TreeNode::getExtendedAttribute(const char *name) +{ Data *data = NULL; int status = getTreeXNci(tree->getCtx(), nid, name, (void **)&data, tree); if (!(status & 1)) @@ -779,18 +872,21 @@ Data *TreeNode::getExtendedAttribute(const char *name) { return data; } -Data *TreeNode::getExtendedAttribute(std::string name) { +Data *TreeNode::getExtendedAttribute(std::string name) +{ return getExtendedAttribute(name.c_str()); } -void TreeNode::setExtendedAttribute(const char *name, Data *data) { +void TreeNode::setExtendedAttribute(const char *name, Data *data) +{ resolveNid(); int status = setTreeXNci(tree->getCtx(), nid, name, data->convertToDsc()); if (!(status & 1)) throw MdsException(status); } -void TreeNode::setExtendedAttribute(std::string name, Data *data) { +void TreeNode::setExtendedAttribute(std::string name, Data *data) +{ resolveNid(); int status = setTreeXNci(tree->getCtx(), nid, name.c_str(), data->convertToDsc()); @@ -798,14 +894,16 @@ void TreeNode::setExtendedAttribute(std::string name, Data *data) { throw MdsException(status); } -void TreeNode::doMethod(char *method) { +void TreeNode::doMethod(char *method) +{ resolveNid(); int status = doTreeMethod(tree->getCtx(), nid, method); if (!(status & 1)) throw MdsException(status); } -bool TreeNode::getFlag(int flagOfs) { +bool TreeNode::getFlag(int flagOfs) +{ resolveNid(); int nciFlags = getNciInt(NciGET_FLAGS); return (nciFlags & flagOfs) ? true : false; @@ -819,13 +917,15 @@ void TreeNode::setWriteOnce(bool flag) { setFlag(NciM_WRITE_ONCE, flag); } bool TreeNode::isCompressOnPut() { return getFlag(NciM_COMPRESS_ON_PUT); } -void TreeNode::setCompressOnPut(bool flag) { +void TreeNode::setCompressOnPut(bool flag) +{ setFlag(NciM_COMPRESS_ON_PUT, flag); } bool TreeNode::isNoWriteModel() { return getFlag(NciM_NO_WRITE_MODEL); } -void TreeNode::setNoWriteModel(bool flag) { +void TreeNode::setNoWriteModel(bool flag) +{ setFlag(NciM_NO_WRITE_MODEL, flag); } @@ -842,67 +942,79 @@ bool TreeNode::isIncludeInPulse() { return getFlag(NciM_INCLUDE_IN_PULSE); } bool TreeNode::containsVersions() { return getFlag(NciM_VERSIONS); } -bool TreeNode::isMember() { +bool TreeNode::isMember() +{ resolveNid(); int par = getNciInt(NciPARENT_RELATIONSHIP); return (par & NciK_IS_MEMBER) ? true : false; } -bool TreeNode::isChild() { +bool TreeNode::isChild() +{ resolveNid(); int par = getNciInt(NciPARENT_RELATIONSHIP); return (par & NciK_IS_CHILD) ? true : false; } -void TreeNode::setIncludedInPulse(bool flag) { +void TreeNode::setIncludedInPulse(bool flag) +{ TreeNode::setIncludeInPulse(flag); } -void TreeNode::setIncludeInPulse(bool flag) { +void TreeNode::setIncludeInPulse(bool flag) +{ setFlag(NciM_INCLUDE_IN_PULSE, flag); } -TreeNode *TreeNode::getParent() { +TreeNode *TreeNode::getParent() +{ resolveNid(); int nodeId = getNciInt(NciPARENT); return new TreeNode(nodeId, tree); } -TreeNode *TreeNode::getBrother() { +TreeNode *TreeNode::getBrother() +{ resolveNid(); int nodeId = getNciInt(NciBROTHER); return new TreeNode(nodeId, tree); } -TreeNode *TreeNode::getChild() { +TreeNode *TreeNode::getChild() +{ resolveNid(); int nodeId = getNciInt(NciCHILD); return new TreeNode(nodeId, tree); } -TreeNode *TreeNode::getMember() { +TreeNode *TreeNode::getMember() +{ resolveNid(); int nodeId = getNciInt(NciMEMBER); return new TreeNode(nodeId, tree); } -int TreeNode::getNumChildren() { +int TreeNode::getNumChildren() +{ resolveNid(); return getNciInt(NciNUMBER_OF_CHILDREN); } -int TreeNode::getNumMembers() { +int TreeNode::getNumMembers() +{ resolveNid(); return getNciInt(NciNUMBER_OF_MEMBERS); } -int TreeNode::getNumDescendants() { +int TreeNode::getNumDescendants() +{ resolveNid(); int members = getNciInt(NciNUMBER_OF_MEMBERS); int children = getNciInt(NciNUMBER_OF_CHILDREN); return members + children; } -TreeNode **TreeNode::getDescendants(int *numDescendants) { +TreeNode **TreeNode::getDescendants(int *numDescendants) +{ int numMembers; TreeNode **members = getMembers(&numMembers); @@ -924,7 +1036,8 @@ TreeNode **TreeNode::getDescendants(int *numDescendants) { return retDescendants; } -TreeNode **TreeNode::getChildren(int *numChildren) { +TreeNode **TreeNode::getChildren(int *numChildren) +{ int nidCnt = getNumChildren(); std::vector nids(nidCnt); *numChildren = nidCnt; @@ -945,7 +1058,8 @@ TreeNode **TreeNode::getChildren(int *numChildren) { return retNodes; } -TreeNode **TreeNode::getMembers(int *numMembers) { +TreeNode **TreeNode::getMembers(int *numMembers) +{ int nidCnt = getNumMembers(); std::vector nids(nidCnt); *numMembers = nidCnt; @@ -966,23 +1080,27 @@ TreeNode **TreeNode::getMembers(int *numMembers) { return retNodes; } -const char *TreeNode::getClass() { +const char *TreeNode::getClass() +{ resolveNid(); char type = getNciChar(NciCLASS); return MdsClassString(type); } -const char *TreeNode::getDType() { +const char *TreeNode::getDType() +{ resolveNid(); char type = getNciChar(NciDTYPE); return MdsDtypeString(type); } -const char *TreeNode::getUsage() { +const char *TreeNode::getUsage() +{ resolveNid(); int usage = getNciInt(NciUSAGE); - switch (usage) { + switch (usage) + { case TreeUSAGE_ACTION: return "ACTION"; case TreeUSAGE_ANY: @@ -1013,17 +1131,20 @@ const char *TreeNode::getUsage() { return "Unknown"; } -int TreeNode::getConglomerateElt() { +int TreeNode::getConglomerateElt() +{ resolveNid(); return getNciChar(NciCONGLOMERATE_ELT); } -int TreeNode::getNumElts() { +int TreeNode::getNumElts() +{ resolveNid(); return getNciInt(NciNUMBER_OF_ELTS); } -TreeNodeArray *TreeNode::getConglomerateNodes() { +TreeNodeArray *TreeNode::getConglomerateNodes() +{ int nNidsLen, retLen; int nNids; struct nci_itm nciList[] = {{4, NciNUMBER_OF_ELTS, (char *)&nNids, &nNidsLen}, @@ -1048,7 +1169,8 @@ TreeNodeArray *TreeNode::getConglomerateNodes() { return resArray; } -int TreeNode::getDepth() { +int TreeNode::getDepth() +{ resolveNid(); return getNciInt(NciDEPTH); } @@ -1060,7 +1182,8 @@ int TreeNode::getDepth() { #endif void TreeNode::makeSegment(Data *start, Data *end, Data *time, - Array *initialData) { + Array *initialData) +{ resolveNid(); int numDims; int *shape = initialData->getShape(&numDims); @@ -1077,7 +1200,8 @@ void TreeNode::makeSegment(Data *start, Data *end, Data *time, void TreeNode::makeSegmentMinMax(Data *start, Data *end, Data *time, Array *initialData, TreeNode *resampledNode, - int resFactor) { + int resFactor) +{ resolveNid(); int numDims; int *shape = initialData->getShape(&numDims); @@ -1094,7 +1218,8 @@ void TreeNode::makeSegmentMinMax(Data *start, Data *end, Data *time, void TreeNode::makeSegmentResampled(Data *start, Data *end, Data *time, Array *initialData, TreeNode *resampledNode, - int resFactor) { + int resFactor) +{ resolveNid(); int numDims; int *shape = initialData->getShape(&numDims); @@ -1109,7 +1234,8 @@ void TreeNode::makeSegmentResampled(Data *start, Data *end, Data *time, throw MdsException(status); } void TreeNode::beginSegment(Data *start, Data *end, Data *time, - Array *initialData) { + Array *initialData) +{ resolveNid(); // if(tree) tree->lock(); int status = beginTreeSegment( @@ -1121,7 +1247,8 @@ void TreeNode::beginSegment(Data *start, Data *end, Data *time, } void TreeNode::beginSegmentResampled(Data *start, Data *end, Data *time, Array *initialData, - TreeNode *resampledNode, int resFactor) { + TreeNode *resampledNode, int resFactor) +{ resolveNid(); int status = beginTreeSegmentResampled( tree->getCtx(), getNid(), initialData->convertToDsc(), @@ -1132,7 +1259,8 @@ void TreeNode::beginSegmentResampled(Data *start, Data *end, Data *time, } void TreeNode::beginSegmentMinMax(Data *start, Data *end, Data *time, Array *initialData, TreeNode *resampledNode, - int resFactor) { + int resFactor) +{ resolveNid(); int status = beginTreeSegmentMinMax( tree->getCtx(), getNid(), initialData->convertToDsc(), @@ -1183,7 +1311,8 @@ resampledNode->convertToDsc()); beginSegment(start, end, time, initialData); } */ -void TreeNode::putSegment(Array *data, int ofs) { +void TreeNode::putSegment(Array *data, int ofs) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1194,7 +1323,8 @@ void TreeNode::putSegment(Array *data, int ofs) { } void TreeNode::putSegmentResampled(Array *data, int ofs, - TreeNode *resampledNode, int resFactor) { + TreeNode *resampledNode, int resFactor) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1205,7 +1335,8 @@ void TreeNode::putSegmentResampled(Array *data, int ofs, throw MdsException(status); } void TreeNode::putSegmentMinMax(Array *data, int ofs, TreeNode *resampledNode, - int resFactor) { + int resFactor) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1248,7 +1379,8 @@ numRows/resFactor)); resampledNode->putSegment(resData, ofs); putSegment(data, ofs); } */ -void TreeNode::updateSegment(Data *start, Data *end, Data *time) { +void TreeNode::updateSegment(Data *start, Data *end, Data *time) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1259,7 +1391,8 @@ void TreeNode::updateSegment(Data *start, Data *end, Data *time) { throw MdsException(status); } -void TreeNode::updateSegment(int segIdx, Data *start, Data *end, Data *time) { +void TreeNode::updateSegment(int segIdx, Data *start, Data *end, Data *time) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1270,7 +1403,8 @@ void TreeNode::updateSegment(int segIdx, Data *start, Data *end, Data *time) { throw MdsException(status); } -int TreeNode::getNumSegments() { +int TreeNode::getNumSegments() +{ int numSegments; resolveNid(); @@ -1283,7 +1417,8 @@ int TreeNode::getNumSegments() { } void TreeNode::getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, - int *nextRow) { + int *nextRow) +{ resolveNid(); int status = getTreeSegmentInfo(tree->getCtx(), getNid(), segIdx, dtype, dimct, dims, nextRow); @@ -1291,7 +1426,8 @@ void TreeNode::getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, throw MdsException(status); } -void TreeNode::getSegmentLimits(int segmentIdx, Data **start, Data **end) { +void TreeNode::getSegmentLimits(int segmentIdx, Data **start, Data **end) +{ void *startDsc, *endDsc; resolveNid(); // if(tree) tree->lock(); @@ -1306,7 +1442,8 @@ void TreeNode::getSegmentLimits(int segmentIdx, Data **start, Data **end) { freeDsc(endDsc); } -Array *TreeNode::getSegment(int segIdx) { +Array *TreeNode::getSegment(int segIdx) +{ void *dataDsc; void *timeDsc; resolveNid(); @@ -1314,7 +1451,8 @@ Array *TreeNode::getSegment(int segIdx) { int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, &dataDsc, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) { + if (!(status & 1)) + { freeDsc(dataDsc); freeDsc(timeDsc); throw MdsException(status); @@ -1325,13 +1463,15 @@ Array *TreeNode::getSegment(int segIdx) { return retData; } -Data *TreeNode::getSegmentDim(int segIdx) { +Data *TreeNode::getSegmentDim(int segIdx) +{ void *timeDsc; resolveNid(); // if(tree) tree->lock(); int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, NULL, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) { + if (!(status & 1)) + { freeDsc(timeDsc); throw MdsException(status); } @@ -1341,7 +1481,8 @@ Data *TreeNode::getSegmentDim(int segIdx) { } void TreeNode::getSegmentAndDimension(int segIdx, Array *&segment, - Data *&dimension) { + Data *&dimension) +{ void *dataDsc; void *timeDsc; resolveNid(); @@ -1349,7 +1490,8 @@ void TreeNode::getSegmentAndDimension(int segIdx, Array *&segment, int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, &dataDsc, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) { + if (!(status & 1)) + { freeDsc(dataDsc); freeDsc(timeDsc); throw MdsException(status); @@ -1360,13 +1502,15 @@ void TreeNode::getSegmentAndDimension(int segIdx, Array *&segment, freeDsc(timeDsc); } -Data *TreeNode::getSegmentScale() { +Data *TreeNode::getSegmentScale() +{ void *sclDsc; resolveNid(); // if(tree) tree->lock(); int status = getTreeSegmentScale(tree->getCtx(), getNid(), &sclDsc); // if(tree) tree->unlock(); - if (!(status & 1)) { + if (!(status & 1)) + { freeDsc(sclDsc); sclDsc = NULL; } @@ -1375,7 +1519,8 @@ Data *TreeNode::getSegmentScale() { return retScl; } -void TreeNode::setSegmentScale(Data *scale) { +void TreeNode::setSegmentScale(Data *scale) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1385,7 +1530,8 @@ void TreeNode::setSegmentScale(Data *scale) { throw MdsException(status); } -void TreeNode::beginTimestampedSegment(Array *initData) { +void TreeNode::beginTimestampedSegment(Array *initData) +{ resolveNid(); // if(tree) tree->lock(); int status = beginTreeTimestampedSegment(tree->getCtx(), getNid(), @@ -1395,7 +1541,8 @@ void TreeNode::beginTimestampedSegment(Array *initData) { throw MdsException(status); } -void TreeNode::makeTimestampedSegment(Array *data, int64_t *times) { +void TreeNode::makeTimestampedSegment(Array *data, int64_t *times) +{ int numDims; int *shape = data->getShape(&numDims); @@ -1409,7 +1556,8 @@ void TreeNode::makeTimestampedSegment(Array *data, int64_t *times) { throw MdsException(status); } -void TreeNode::putTimestampedSegment(Array *data, int64_t *times) { +void TreeNode::putTimestampedSegment(Array *data, int64_t *times) +{ resolveNid(); // if(tree) tree->lock(); int status = putTreeTimestampedSegment(tree->getCtx(), getNid(), @@ -1419,7 +1567,8 @@ void TreeNode::putTimestampedSegment(Array *data, int64_t *times) { throw MdsException(status); } -void TreeNode::putRow(Data *data, int64_t *time, int size) { +void TreeNode::putRow(Data *data, int64_t *time, int size) +{ resolveNid(); // if(tree) tree->lock(); int status = @@ -1429,7 +1578,8 @@ void TreeNode::putRow(Data *data, int64_t *time, int size) { throw MdsException(status); } -TreeNode *TreeNode::getNode(char const *relPath) { +TreeNode *TreeNode::getNode(char const *relPath) +{ int newNid; resolveNid(); @@ -1440,7 +1590,8 @@ TreeNode *TreeNode::getNode(char const *relPath) { return new TreeNode(newNid, tree); } -TreeNode *TreeNode::getNode(String *relPathStr) { +TreeNode *TreeNode::getNode(String *relPathStr) +{ int newNid; resolveNid(); AutoArray relPath(relPathStr->getString()); @@ -1452,7 +1603,8 @@ TreeNode *TreeNode::getNode(String *relPathStr) { return new TreeNode(newNid, tree); } -TreeNodeArray *TreeNode::getNodeWild(char const *path, int usageMask) { +TreeNodeArray *TreeNode::getNodeWild(char const *path, int usageMask) +{ int status; void *wildCtx = 0; @@ -1475,11 +1627,13 @@ TreeNodeArray *TreeNode::getNodeWild(char const *path, int usageMask) { return nodeArray; } -TreeNodeArray *TreeNode::getNodeWild(char const *path) { +TreeNodeArray *TreeNode::getNodeWild(char const *path) +{ return getNodeWild(path, -1); } -TreeNode *TreeNode::addNode(char const *name, char const *usage) { +TreeNode *TreeNode::addNode(char const *name, char const *usage) +{ int defNid; int newNid; resolveNid(); @@ -1495,7 +1649,8 @@ TreeNode *TreeNode::addNode(char const *name, char const *usage) { return new TreeNode(newNid, tree); } -void TreeNode::remove(char const *name) { +void TreeNode::remove(char const *name) +{ int count; int defNid; resolveNid(); @@ -1513,7 +1668,8 @@ void TreeNode::remove(char const *name) { throw MdsException(status); } -TreeNode *TreeNode::addDevice(char const *name, char const *type) { +TreeNode *TreeNode::addDevice(char const *name, char const *type) +{ int defNid; int newNid; resolveNid(); @@ -1529,33 +1685,38 @@ TreeNode *TreeNode::addDevice(char const *name, char const *type) { return new TreeNode(newNid, tree); } -void TreeNode::rename(std::string const &newName) { +void TreeNode::rename(std::string const &newName) +{ resolveNid(); int status = _TreeRenameNode(tree->getCtx(), nid, newName.c_str()); if (!(status & 1)) throw MdsException(status); } -void TreeNode::move(TreeNode *parent, std::string const &newName) { +void TreeNode::move(TreeNode *parent, std::string const &newName) +{ resolveNid(); AutoString parentPath(parent->getFullPath()); rename(parentPath.string + ":" + newName); } -void TreeNode::move(TreeNode *parent) { +void TreeNode::move(TreeNode *parent) +{ resolveNid(); AutoString name(getNodeName()); move(parent, name.string); } -void TreeNode::addTag(std::string const &tagName) { +void TreeNode::addTag(std::string const &tagName) +{ resolveNid(); int status = _TreeAddTag(tree->getCtx(), nid, tagName.c_str()); if (!(status & 1)) throw MdsException(status); } -void TreeNode::removeTag(std::string const &tagName) { +void TreeNode::removeTag(std::string const &tagName) +{ resolveNid(); int currNid; std::string bTag("\\" + tagName); @@ -1568,7 +1729,8 @@ void TreeNode::removeTag(std::string const &tagName) { throw MdsException(status); } -void TreeNode::setSubtree(bool isSubtree) { +void TreeNode::setSubtree(bool isSubtree) +{ resolveNid(); int status; if (isSubtree) @@ -1579,7 +1741,8 @@ void TreeNode::setSubtree(bool isSubtree) { throw MdsException(status); } -StringArray *TreeNode::findTags() { +StringArray *TreeNode::findTags() +{ resolveNid(); const int MAX_TAGS = 1024; char *tagNames[MAX_TAGS]; @@ -1600,19 +1763,22 @@ StringArray *TreeNode::findTags() { TreePath::TreePath(std::string const &path, Tree *tree, Data *units, Data *error, Data *help, Data *validation) - : TreeNode(0, tree, units, error, help, validation), path(path) { + : TreeNode(0, tree, units, error, help, validation), path(path) +{ clazz = CLASS_S; dtype = DTYPE_PATH; } TreePath::TreePath(char const *path, int len, Tree *tree, Data *units, Data *error, Data *help, Data *validation) - : TreeNode(0, tree, units, error, help, validation), path(path, len) { + : TreeNode(0, tree, units, error, help, validation), path(path, len) +{ clazz = CLASS_S; dtype = DTYPE_PATH; } -void TreePath::resolveNid() { +void TreePath::resolveNid() +{ if (!tree) tree = getActiveTree(); int status = _TreeFindNode(tree->getCtx(), path.c_str(), &nid); @@ -1624,7 +1790,8 @@ void TreePath::resolveNid() { // TreeNodeArray ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -TreeNodeArray::TreeNodeArray(TreeNode **nodes, int numNodes) { +TreeNodeArray::TreeNodeArray(TreeNode **nodes, int numNodes) +{ this->numNodes = numNodes; this->nodes = new TreeNode *[numNodes]; @@ -1632,7 +1799,8 @@ TreeNodeArray::TreeNodeArray(TreeNode **nodes, int numNodes) { this->nodes[i] = nodes[i]; } -TreeNodeArray::TreeNodeArray(int *nids, int numNodes, Tree *tree) { +TreeNodeArray::TreeNodeArray(int *nids, int numNodes, Tree *tree) +{ this->numNodes = numNodes; this->nodes = new TreeNode *[numNodes]; @@ -1640,8 +1808,10 @@ TreeNodeArray::TreeNodeArray(int *nids, int numNodes, Tree *tree) { this->nodes[i] = new TreeNode(nids[i], tree); } -TreeNodeArray::~TreeNodeArray() { - if (numNodes > 0) { +TreeNodeArray::~TreeNodeArray() +{ + if (numNodes > 0) + { for (int i = 0; i < numNodes; i++) deleteData(nodes[i]); delete[] nodes; @@ -1652,7 +1822,8 @@ void *TreeNodeArray::operator new(size_t sz) { return ::operator new(sz); } void TreeNodeArray::operator delete(void *p) { ::operator delete(p); } -StringArray *TreeNodeArray::getPath() { +StringArray *TreeNodeArray::getPath() +{ /* WRONG!! AutoArray cannot wok here because AutoArray objects are instantiated several times and then go out of scope, this triggering multiple deallocation of the same C string and crashing the program @@ -1678,7 +1849,8 @@ StringArray *TreeNodeArray::getPath() { return new StringArray(&nativePaths[0], numNodes); } -StringArray *TreeNodeArray::getFullPath() { +StringArray *TreeNodeArray::getFullPath() +{ /* Same as before std::vector > paths; for(int i = 0; i < numNodes; ++i) @@ -1701,7 +1873,8 @@ StringArray *TreeNodeArray::getFullPath() { return new StringArray(&nativePaths[0], numNodes); } -Int32Array *TreeNodeArray::getNid() { +Int32Array *TreeNodeArray::getNid() +{ std::vector nids; for (int i = 0; i < numNodes; ++i) nids.push_back(nodes[i]->getNid()); @@ -1709,7 +1882,8 @@ Int32Array *TreeNodeArray::getNid() { return new Int32Array(&nids[0], numNodes); } -Int8Array *TreeNodeArray::isOn() { +Int8Array *TreeNodeArray::isOn() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info.push_back(nodes[i]->isOn()); @@ -1717,7 +1891,8 @@ Int8Array *TreeNodeArray::isOn() { return new Int8Array(&info[0], numNodes); } -void TreeNodeArray::setOn(Int8Array *info) { +void TreeNodeArray::setOn(Int8Array *info) +{ std::vector infoArray = dynamic_cast(info)->getByteArray(); // FIXME: numNodes should be size_t @@ -1726,7 +1901,8 @@ void TreeNodeArray::setOn(Int8Array *info) { nodes[i]->setOn((infoArray[i]) ? true : false); } -Int8Array *TreeNodeArray::isSetup() { +Int8Array *TreeNodeArray::isSetup() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info[i] = nodes[i]->isSetup(); @@ -1734,7 +1910,8 @@ Int8Array *TreeNodeArray::isSetup() { return new Int8Array(&info[0], numNodes); } -Int8Array *TreeNodeArray::isWriteOnce() { +Int8Array *TreeNodeArray::isWriteOnce() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info[i] = nodes[i]->isWriteOnce(); @@ -1742,7 +1919,8 @@ Int8Array *TreeNodeArray::isWriteOnce() { return new Int8Array(&info[0], numNodes); } -void TreeNodeArray::setWriteOnce(Int8Array *info) { +void TreeNodeArray::setWriteOnce(Int8Array *info) +{ std::vector infoArray = dynamic_cast(info)->getByteArray(); // FIXME: numNodes should be size_t @@ -1750,7 +1928,8 @@ void TreeNodeArray::setWriteOnce(Int8Array *info) { for (std::size_t i = 0; i < MAX; ++i) nodes[i]->setWriteOnce((infoArray[i]) ? true : false); } -Int8Array *TreeNodeArray::isCompressOnPut() { +Int8Array *TreeNodeArray::isCompressOnPut() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info[i] = nodes[i]->isCompressOnPut(); @@ -1758,7 +1937,8 @@ Int8Array *TreeNodeArray::isCompressOnPut() { return new Int8Array(&info[0], numNodes); } -void TreeNodeArray::setCompressOnPut(Int8Array *info) { +void TreeNodeArray::setCompressOnPut(Int8Array *info) +{ std::vector infoArray = dynamic_cast(info)->getByteArray(); // FIXME: numNodes should be size_t @@ -1767,7 +1947,8 @@ void TreeNodeArray::setCompressOnPut(Int8Array *info) { nodes[i]->setCompressOnPut((infoArray[i]) ? true : false); } -Int8Array *TreeNodeArray::isNoWriteModel() { +Int8Array *TreeNodeArray::isNoWriteModel() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info[i] = nodes[i]->isNoWriteModel(); @@ -1775,7 +1956,8 @@ Int8Array *TreeNodeArray::isNoWriteModel() { return new Int8Array(&info[0], numNodes); } -void TreeNodeArray::setNoWriteModel(Int8Array *info) { +void TreeNodeArray::setNoWriteModel(Int8Array *info) +{ std::vector infoArray = dynamic_cast(info)->getByteArray(); // FIXME: numNodes should be size_t @@ -1784,7 +1966,8 @@ void TreeNodeArray::setNoWriteModel(Int8Array *info) { nodes[i]->setNoWriteModel((infoArray[i]) ? true : false); } -Int8Array *TreeNodeArray::isNoWriteShot() { +Int8Array *TreeNodeArray::isNoWriteShot() +{ std::vector info; for (int i = 0; i < numNodes; ++i) info[i] = nodes[i]->isNoWriteShot(); @@ -1792,7 +1975,8 @@ Int8Array *TreeNodeArray::isNoWriteShot() { return new Int8Array(&info[0], numNodes); } -void TreeNodeArray::setNoWriteShot(Int8Array *info) { +void TreeNodeArray::setNoWriteShot(Int8Array *info) +{ std::vector infoArray = dynamic_cast(info)->getByteArray(); // FIXME: numNodes should be size_t @@ -1801,7 +1985,8 @@ void TreeNodeArray::setNoWriteShot(Int8Array *info) { nodes[i]->setNoWriteShot((infoArray[i]) ? true : false); } -Int32Array *TreeNodeArray::getLength() { +Int32Array *TreeNodeArray::getLength() +{ std::vector sizes; for (int i = 0; i < numNodes; ++i) sizes.push_back(nodes[i]->getLength()); @@ -1809,7 +1994,8 @@ Int32Array *TreeNodeArray::getLength() { return new Int32Array(&sizes[0], numNodes); } -Int32Array *TreeNodeArray::getCompressedLength() { +Int32Array *TreeNodeArray::getCompressedLength() +{ std::vector sizes; for (int i = 0; i < numNodes; ++i) sizes.push_back(nodes[i]->getCompressedLength()); @@ -1817,7 +2003,8 @@ Int32Array *TreeNodeArray::getCompressedLength() { return new Int32Array(&sizes[0], numNodes); } -StringArray *TreeNodeArray::getUsage() { +StringArray *TreeNodeArray::getUsage() +{ std::vector usages; for (int i = 0; i < numNodes; ++i) usages.push_back(nodes[i]->getUsage()); @@ -1829,8 +2016,10 @@ StringArray *TreeNodeArray::getUsage() { ////////////////End TreeNodeArray methods///////////////////// ////////////////TreeNodeThinClient methods /////////////////// -static const char *convertNciItm(int nciItm) { - switch (nciItm) { +static const char *convertNciItm(int nciItm) +{ + switch (nciItm) + { case NciTIME_INSERTED: return "\'TIME_INSERTED\'"; case NciOWNER_ID: @@ -1892,7 +2081,8 @@ static const char *convertNciItm(int nciItm) { TreeNodeThinClient::TreeNodeThinClient(int nid, Connection *connection, Data *units, Data *error, Data *help, - Data *validation) { + Data *validation) +{ this->tree = 0; this->nid = nid; this->connection = connection; @@ -1901,7 +2091,8 @@ TreeNodeThinClient::TreeNodeThinClient(int nid, Connection *connection, setAccessory(units, error, help, validation); } -std::string TreeNodeThinClient::getNciString(int itm) { +std::string TreeNodeThinClient::getNciString(int itm) +{ char expr[64]; sprintf(expr, "GETNCI(%d,%s)", nid, convertNciItm(itm)); AutoData retStringData(connection->get(expr)); @@ -1912,7 +2103,8 @@ std::string TreeNodeThinClient::getNciString(int itm) { return as.string; } -char TreeNodeThinClient::getNciChar(int itm) { +char TreeNodeThinClient::getNciChar(int itm) +{ char expr[64]; sprintf(expr, "GETNCI(%d,%s)", nid, convertNciItm(itm)); AutoData retData(connection->get(expr)); @@ -1922,7 +2114,8 @@ char TreeNodeThinClient::getNciChar(int itm) { return retChar; } -int TreeNodeThinClient::getNciInt(int itm) { +int TreeNodeThinClient::getNciInt(int itm) +{ char expr[64]; sprintf(expr, "GETNCI(%d,%s)", nid, convertNciItm(itm)); AutoData retData(connection->get(expr)); @@ -1931,7 +2124,8 @@ int TreeNodeThinClient::getNciInt(int itm) { return retData->getInt(); } -int64_t TreeNodeThinClient::getNciInt64(int itm) { +int64_t TreeNodeThinClient::getNciInt64(int itm) +{ char expr[64]; sprintf(expr, "GETNCI(%d,%s)", nid, convertNciItm(itm)); AutoData retData(connection->get(expr)); @@ -1940,7 +2134,8 @@ int64_t TreeNodeThinClient::getNciInt64(int itm) { return retData->getLong(); } -char *TreeNodeThinClient::getPath() { +char *TreeNodeThinClient::getPath() +{ char expr[64]; sprintf(expr, "GETNCI(%d,\'PATH\')", nid); AutoData retData(connection->get(expr)); @@ -1949,7 +2144,8 @@ char *TreeNodeThinClient::getPath() { return retData->getString(); } -EXPORT Data *TreeNodeThinClient::getData() { +EXPORT Data *TreeNodeThinClient::getData() +{ char expr[64]; sprintf(expr, "GETNCI(%d,\'RECORD\')", nid); Data *retData = connection->get(expr); @@ -1958,20 +2154,23 @@ EXPORT Data *TreeNodeThinClient::getData() { return retData; } -EXPORT void TreeNodeThinClient::putData(Data *data) { +EXPORT void TreeNodeThinClient::putData(Data *data) +{ AutoArray path(getPath()); AutoData argsD[] = {data->data()}; Data *args[] = {argsD[0].get()}; connection->put(path, (char *)"$", args, 1); } -EXPORT void TreeNodeThinClient::deleteData() { +EXPORT void TreeNodeThinClient::deleteData() +{ AutoArray path = getFullPath(); Data *args[1] = {0}; connection->put(path, (char *)"*", args, 0); } -EXPORT bool TreeNodeThinClient::isOn() { +EXPORT bool TreeNodeThinClient::isOn() +{ char expr[64]; sprintf(expr, "GETNCI(%d,\'STATE\')", nid); AutoData retData(connection->get(expr)); @@ -1982,7 +2181,8 @@ EXPORT bool TreeNodeThinClient::isOn() { return (onData) ? false : true; } -EXPORT void TreeNodeThinClient::setOn(bool on) { +EXPORT void TreeNodeThinClient::setOn(bool on) +{ char expr[64]; if (on) sprintf(expr, "TreeTurnOn(%d)", nid); @@ -1992,7 +2192,8 @@ EXPORT void TreeNodeThinClient::setOn(bool on) { } EXPORT void TreeNodeThinClient::beginSegment(Data *start, Data *end, Data *time, - Array *initialData) { + Array *initialData) +{ char expr[256]; AutoData argsD[] = {start->data(), end->data(), time->data(), initialData->data()}; @@ -2003,7 +2204,8 @@ EXPORT void TreeNodeThinClient::beginSegment(Data *start, Data *end, Data *time, } EXPORT void TreeNodeThinClient::makeSegment(Data *start, Data *end, Data *time, - Array *initialData) { + Array *initialData) +{ char expr[256]; AutoData argsD[] = {start->data(), end->data(), time->data(), initialData->data()}; @@ -2013,7 +2215,8 @@ EXPORT void TreeNodeThinClient::makeSegment(Data *start, Data *end, Data *time, AutoData retData(connection->get(expr, args, 4)); } -EXPORT void TreeNodeThinClient::putSegment(Array *data, int ofs) { +EXPORT void TreeNodeThinClient::putSegment(Array *data, int ofs) +{ char expr[256]; AutoData argsD[] = {data->data()}; Data *args[] = {argsD[0].get()}; @@ -2021,7 +2224,8 @@ EXPORT void TreeNodeThinClient::putSegment(Array *data, int ofs) { AutoData retData(connection->get(expr, args, 1)); } -EXPORT int TreeNodeThinClient::getNumSegments() { +EXPORT int TreeNodeThinClient::getNumSegments() +{ char expr[64]; sprintf(expr, "GetNumSegments(%d)", nid); AutoData data(connection->get(expr)); @@ -2031,7 +2235,8 @@ EXPORT int TreeNodeThinClient::getNumSegments() { } EXPORT void TreeNodeThinClient::getSegmentLimits(int segmentIdx, Data **start, - Data **end) { + Data **end) +{ char expr[64]; sprintf(expr, "GetSegmentLimits(%d, %d)", nid, segmentIdx); AutoData limitsArr((Array *)connection->get(expr)); @@ -2042,7 +2247,8 @@ EXPORT void TreeNodeThinClient::getSegmentLimits(int segmentIdx, Data **start, *end = limitsArr->getElementAt(&endIdx, 1); } -EXPORT Array *TreeNodeThinClient::getSegment(int segIdx) { +EXPORT Array *TreeNodeThinClient::getSegment(int segIdx) +{ char expr[64]; sprintf(expr, "GetSegment(%d, %d)", nid, segIdx); Array *retSegment = (Array *)connection->get(expr); @@ -2051,7 +2257,8 @@ EXPORT Array *TreeNodeThinClient::getSegment(int segIdx) { return retSegment; } -EXPORT Data *TreeNodeThinClient::getSegmentDim(int segIdx) { +EXPORT Data *TreeNodeThinClient::getSegmentDim(int segIdx) +{ char expr[64]; sprintf(expr, "DIM_OF(GetSegment(%d, %d))", nid, segIdx); Data *retDim = connection->get(expr); @@ -2062,7 +2269,8 @@ EXPORT Data *TreeNodeThinClient::getSegmentDim(int segIdx) { EXPORT void TreeNodeThinClient::getSegmentAndDimension(int segIdx, Array *&segment, - Data *&dimension) { + Data *&dimension) +{ char expr[64]; sprintf(expr, "GetSegment(%d, %d)", nid, segIdx); segment = (Array *)connection->get(expr); @@ -2072,7 +2280,8 @@ EXPORT void TreeNodeThinClient::getSegmentAndDimension(int segIdx, throw MdsException("Error in Remote evaluation of GetSegment"); } -EXPORT void TreeNodeThinClient::beginTimestampedSegment(Array *initData) { +EXPORT void TreeNodeThinClient::beginTimestampedSegment(Array *initData) +{ char expr[64]; AutoData argsD[] = {initData->data()}; Data *args[] = {argsD[0].get()}; @@ -2081,7 +2290,8 @@ EXPORT void TreeNodeThinClient::beginTimestampedSegment(Array *initData) { } EXPORT void TreeNodeThinClient::putTimestampedSegment(Array *data, - int64_t *times) { + int64_t *times) +{ char expr[64]; int len = data->getSize(); AutoData argsD[] = {new Int64Array(times, len), data->data()}; @@ -2091,12 +2301,14 @@ EXPORT void TreeNodeThinClient::putTimestampedSegment(Array *data, } EXPORT void TreeNodeThinClient::makeTimestampedSegment(Array *data, - int64_t *times) { + int64_t *times) +{ beginTimestampedSegment(data); putTimestampedSegment(data, times); } -EXPORT void TreeNodeThinClient::putRow(Data *data, int64_t *time, int size) { +EXPORT void TreeNodeThinClient::putRow(Data *data, int64_t *time, int size) +{ AutoData argsD[] = {new Int64(*time), data->data()}; Data *args[] = {argsD[0].get(), argsD[1].get()}; char expr[64]; @@ -2104,7 +2316,8 @@ EXPORT void TreeNodeThinClient::putRow(Data *data, int64_t *time, int size) { AutoData retData(connection->get(expr, args, 2)); } -EXPORT StringArray *TreeNodeThinClient::findTags() { +EXPORT StringArray *TreeNodeThinClient::findTags() +{ char expr[64]; sprintf(expr, "TreeFindNodeTags(%d)", nid); AutoData retData(connection->get(expr)); @@ -2123,7 +2336,8 @@ EXPORT StringArray *TreeNodeThinClient::findTags() { void MDSplus::setActiveTree(Tree *tree) { TreeSwitchDbid(tree->getCtx()); } -Tree *MDSplus::getActiveTree() { +Tree *MDSplus::getActiveTree() +{ char name[1024]; int shot; int retNameLen, retShotLen; @@ -2131,12 +2345,14 @@ Tree *MDSplus::getActiveTree() { {sizeof(int), DbiSHOTID, &shot, &retShotLen}, {0, DbiEND_OF_LIST, 0, 0}}; int status = TreeGetDbi(dbiItems); - if (!(status & 1)) { + if (!(status & 1)) + { throw MdsException(status); } return new Tree(name, shot, TreeDbid()); } -ostream &operator<<(ostream &stream, TreeNode *treeNode) { +ostream &operator<<(ostream &stream, TreeNode *treeNode) +{ return stream << treeNode->getPathStr(); } diff --git a/mdsobjects/cpp/testing/MdsActionTest.cpp b/mdsobjects/cpp/testing/MdsActionTest.cpp index 6682e84d92..14b14302d5 100644 --- a/mdsobjects/cpp/testing/MdsActionTest.cpp +++ b/mdsobjects/cpp/testing/MdsActionTest.cpp @@ -33,7 +33,8 @@ using namespace MDSplus; using namespace testing; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Action); SKIP_TEST("Action test is not implemented yet"); // TO BE DONE // diff --git a/mdsobjects/cpp/testing/MdsApdTest.cpp b/mdsobjects/cpp/testing/MdsApdTest.cpp index f422d1b888..4666740c73 100644 --- a/mdsobjects/cpp/testing/MdsApdTest.cpp +++ b/mdsobjects/cpp/testing/MdsApdTest.cpp @@ -33,7 +33,8 @@ using namespace MDSplus; using namespace testing; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Apd); SKIP_TEST("Apd test is not implemented yet"); diff --git a/mdsobjects/cpp/testing/MdsCallTest.cpp b/mdsobjects/cpp/testing/MdsCallTest.cpp index 7cd578175e..56635c765f 100644 --- a/mdsobjects/cpp/testing/MdsCallTest.cpp +++ b/mdsobjects/cpp/testing/MdsCallTest.cpp @@ -39,7 +39,8 @@ using namespace testing; /// This test refers to three C functions compiled into a shared library that /// should be present in ./testutils/libMdsTestDummy.so -int main(int, char **argv __attribute__((unused))) { +int main(int, char **argv __attribute__((unused))) +{ BEGIN_TESTING(Call); SKIP_TEST( diff --git a/mdsobjects/cpp/testing/MdsCompoundTest.cpp b/mdsobjects/cpp/testing/MdsCompoundTest.cpp index 82fc8f8fc7..c9576b91d3 100644 --- a/mdsobjects/cpp/testing/MdsCompoundTest.cpp +++ b/mdsobjects/cpp/testing/MdsCompoundTest.cpp @@ -62,7 +62,8 @@ using namespace testing; // virtual ~Compound(); int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Compound); Compound *com1 = new Compound(); diff --git a/mdsobjects/cpp/testing/MdsConglomTest.cpp b/mdsobjects/cpp/testing/MdsConglomTest.cpp index 92e6057fe1..964afe8ecc 100644 --- a/mdsobjects/cpp/testing/MdsConglomTest.cpp +++ b/mdsobjects/cpp/testing/MdsConglomTest.cpp @@ -61,7 +61,8 @@ using namespace testing; //}; int main(int argc __attribute__((unused)), - char **argv __attribute__((unused))) { + char **argv __attribute__((unused))) +{ BEGIN_TESTING(Conglom); { // CTR diff --git a/mdsobjects/cpp/testing/MdsConnectionSuppression.cpp b/mdsobjects/cpp/testing/MdsConnectionSuppression.cpp index bdb6935573..d75ed1e665 100644 --- a/mdsobjects/cpp/testing/MdsConnectionSuppression.cpp +++ b/mdsobjects/cpp/testing/MdsConnectionSuppression.cpp @@ -40,7 +40,8 @@ using namespace MDSplus; using namespace testing; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ Connection cnx((char *)"udt://localhost:8000", 0); cnx.openTree((char *)"test_tree", -1); diff --git a/mdsobjects/cpp/testing/MdsConnectionTest.cpp b/mdsobjects/cpp/testing/MdsConnectionTest.cpp index 2cb512e3bc..72540142af 100644 --- a/mdsobjects/cpp/testing/MdsConnectionTest.cpp +++ b/mdsobjects/cpp/testing/MdsConnectionTest.cpp @@ -47,31 +47,39 @@ using namespace MDSplus; using namespace testing; static char test[256]; -inline static Data *cnx_get(Connection *cnx, const char *cmd) { +inline static Data *cnx_get(Connection *cnx, const char *cmd) +{ strcpy(test, cmd); return cnx->get(test); } void _test_tree_open(const char *prot, const unsigned short port, - const char *mode) { + const char *mode) +{ MdsIpInstancer mdsip(prot, port, mode); std::string addr = mdsip.getAddress(); std::cout << "attempt to connect to: " << addr; if (mode) std::cout << " (" << mode << ")"; - std::cout << "\n" << std::flush; + std::cout << "\n" + << std::flush; unique_ptr cnx = NULL; int retry = 3; for (; !cnx; retry--) - try { + try + { cnx = new Connection(const_cast(addr.c_str())); - } catch (...) { + } + catch (...) + { if (retry <= 1) TEST0("could not connect"); - std::cout << "retry\n" << std::flush; + std::cout << "retry\n" + << std::flush; usleep(500000); } - std::cout << "success: starting test\n" << std::flush; + std::cout << "success: starting test\n" + << std::flush; // test client-server communication with max 8 dims// unique_ptr data = cnx_get(cnx, "zero([1,1,1,1,1,1,1,1],1)"); TEST1(AutoString(data->getString()).string == "[[[[[[[[0]]]]]]]]"); @@ -109,11 +117,17 @@ void _test_tree_open(const char *prot, const unsigned short port, } void test_tree_open(const char *prot, const unsigned short port, - const char *mode) { - try { + const char *mode) +{ + try + { _test_tree_open(prot, port, mode); - } catch (const std::exception &e) { - std::cout << "ERROR: " << test << '\n' << e.what() << '\n' << std::flush; + } + catch (const std::exception &e) + { + std::cout << "ERROR: " << test << '\n' + << e.what() << '\n' + << std::flush; TEST0("exception"); } } @@ -122,7 +136,8 @@ void test_tree_open(const char *prot, const unsigned short port, // main ////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int ipv6 = (argc > 1 && !strcmp(argv[1], "ipv6")); TEST_TIMEOUT(30); setenv("t_connect_path", ".", 1); @@ -141,13 +156,16 @@ int main(int argc, char *argv[]) { // this makes the t_connect in a separate process so that all static // variables instanced are destroied when the child ends. - try { + try + { unique_ptr tree = new Tree("t_connect", -1, "NEW"); unique_ptr(tree->addNode("test_cnx", "NUMERIC")); tree->write(); tree->edit(false); tree->createPulse(1); - } catch (...) { + } + catch (...) + { std::cerr << "Error creating model tree"; } @@ -174,7 +192,8 @@ int main(int argc, char *argv[]) { test_tree_open("tcp", 8601, "-m"); END_TESTING; - if (ipv6) { + if (ipv6) + { // tcpv6 // BEGIN_TESTING(Connection tcpv6 - s); test_tree_open("tcpv6", 8602, "-s"); @@ -192,7 +211,8 @@ int main(int argc, char *argv[]) { test_tree_open("udt", 8605, "-m"); END_TESTING; - if (ipv6) { + if (ipv6) + { // udtv6 // BEGIN_TESTING(Connection udtv6 - s); test_tree_open("udtv6", 8606, "-s"); diff --git a/mdsobjects/cpp/testing/MdsDataStreamTest.c b/mdsobjects/cpp/testing/MdsDataStreamTest.c index 317f504cbf..591a22ef46 100644 --- a/mdsobjects/cpp/testing/MdsDataStreamTest.c +++ b/mdsobjects/cpp/testing/MdsDataStreamTest.c @@ -39,13 +39,15 @@ EXPORT void unregisterListener(int listenerId); EXPORT struct descriptor_xd *getNewSamplesSerializedXd(); extern int TdiDecompile(); -static void printDecompiled(struct descriptor *inD) { +static void printDecompiled(struct descriptor *inD) +{ int status; EMPTYXD(out_xd); char *buf; status = TdiDecompile(inD, &out_xd MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { printf("%s\n", MdsGetMsg(status)); return; } @@ -58,7 +60,8 @@ static void printDecompiled(struct descriptor *inD) { MdsFree1Dx(&out_xd, 0); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int id, id1; int status; struct timespec waitTime; @@ -67,18 +70,22 @@ int main(int argc, char *argv[]) { id = registerListener("2 * test_0", "test", 1); id1 = registerListener("10 * build_path('test_1')", "test", 1); - while (1) { + while (1) + { retXd = getNewSamplesSerializedXd(); - if (!retXd->pointer) { + if (!retXd->pointer) + { printf("Error: Null serialized returned\n"); exit(0); } - if (retXd->pointer->class != CLASS_A) { + if (retXd->pointer->class != CLASS_A) + { printf("Error: Unexpected serilized class\n"); exit(0); } status = MdsSerializeDscIn(retXd->pointer->pointer, &xd); - if (!(status & 1)) { + if (!(status & 1)) + { printf("Error: decompressing result\n"); exit(0); } diff --git a/mdsobjects/cpp/testing/MdsDataTest.cpp b/mdsobjects/cpp/testing/MdsDataTest.cpp index 3bcea9d6f0..94328add2d 100644 --- a/mdsobjects/cpp/testing/MdsDataTest.cpp +++ b/mdsobjects/cpp/testing/MdsDataTest.cpp @@ -44,7 +44,8 @@ using namespace MDSplus; using namespace testing; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Mds Data Test); { // CONSTRUCTORS diff --git a/mdsobjects/cpp/testing/MdsDataTest.h b/mdsobjects/cpp/testing/MdsDataTest.h index 80b217ad31..0465b192d4 100644 --- a/mdsobjects/cpp/testing/MdsDataTest.h +++ b/mdsobjects/cpp/testing/MdsDataTest.h @@ -15,329 +15,355 @@ // using namespace MDSplus; namespace mds = MDSplus; -namespace testing { - -//////////////////////////////////////////////////////////////////////////////// -// TEST STRING CONVERSION //////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -inline void print_type_encoded(mds::Data *data) { - char *str = data->getString(); - std::cout << "data in tdi string: " << str << "\n"; - delete[] str; -} - -inline std::string mdsdata_to_string(mds::Data *data) { - char *str = data->getString(); - std::string out(str); - delete[] str; - return out; -} - -//////////////////////////////////////////////////////////////////////////////// -// MDS DATA TEST CLASS /////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -// we assume vector std allocator to be contiguous // -// see note: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#69 -// -class MdsDataTest { - - template struct ArrayFnptr { - typedef typename detail::FunctionTypes<_Fn>::ReturnType ReturnType; - typedef typename detail::remove_pointer::type type; - typedef typename std::vector VectorType; +namespace testing +{ + + //////////////////////////////////////////////////////////////////////////////// + // TEST STRING CONVERSION //////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + inline void print_type_encoded(mds::Data *data) + { + char *str = data->getString(); + std::cout << "data in tdi string: " << str << "\n"; + delete[] str; + } + + inline std::string mdsdata_to_string(mds::Data *data) + { + char *str = data->getString(); + std::string out(str); + delete[] str; + return out; + } + + //////////////////////////////////////////////////////////////////////////////// + // MDS DATA TEST CLASS /////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + // we assume vector std allocator to be contiguous // + // see note: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#69 + // + class MdsDataTest + { + + template + struct ArrayFnptr + { + typedef typename detail::FunctionTypes<_Fn>::ReturnType ReturnType; + typedef typename detail::remove_pointer::type type; + typedef typename std::vector VectorType; + }; + + template + static typename ArrayFnptr::VectorType get_vector(mds::Data *data, Fn fn); + + template + static void test_numeric_cast_function(mds::Data *data, Fn fn, const T value); + + public: + template + static void test_data_numerics(mds::Data *data, const T value); + + template + static void test_data_numerics(mds::Data *data, const std::complex value); + + template + static void test_data_numerics(mds::Data *data, const std::vector &array); + + template + static void test_data_numerics(mds::Data *data, + const std::vector > &array); + + static void test_data_string(mds::Data *data, const char *str) + { + char *data_str = data->getString(); + int data_getString_differs_from_test = strcmp(data_str, str); + TEST0(data_getString_differs_from_test); + if (data_getString_differs_from_test) + std::cout << "tdi decompile: " << data_str << "\n" + << "test string: " << str << "\n"; + delete[] data_str; + } }; + /// + /// Takes a Data object and a getter of Array and returns a vector of the + /// obtained elements. + /// template - static typename ArrayFnptr::VectorType get_vector(mds::Data *data, Fn fn); + inline typename MdsDataTest::ArrayFnptr::VectorType + MdsDataTest::get_vector(mds::Data *data, Fn fn) + { + typedef typename ArrayFnptr::type R; + + std::vector out; + int size; + R *array = (data->*fn)(&size); + for (size_t i = 0; i < (unsigned int)size; ++i) + out.push_back(array[i]); + delete[] array; + return out; + } + /// + /// If the numeric_cast throws an exception this catch and compare with the + /// getter method of the Data object. Otherwise the casted values are checked. + /// template - static void test_numeric_cast_function(mds::Data *data, Fn fn, const T value); + inline void MdsDataTest::test_numeric_cast_function(mds::Data *data, Fn fn, + const T value) + { + typedef typename detail::FunctionTypes::ReturnType R; + try + { + mds::numeric_cast(value); + } + catch (std::exception &e) + { + TEST_STD_EXCEPTION((data->*fn)(), e.what()); + } + try + { + // NOTE: seems that the optimizer makes a fail in 32bit if these are not + // volatile variables ( failing case is: test_conversion_limits ) + volatile R casted_val = mds::numeric_cast(value); + volatile R data_val = (data->*fn)(); + TEST1(casted_val == data_val); + } + catch (...) + { + } // do not throw // + } -public: - template - static void test_data_numerics(mds::Data *data, const T value); +#define MDS_GETARRAY_FUNCPT(type, name) \ + ((type * (mds::Data::*)(int *)) & mds::Data::name) - template - static void test_data_numerics(mds::Data *data, const std::complex value); +#define MDS_GETNUMERIC_FUNCPT(type, name) \ + ((type(mds::Data::*)()) & mds::Data::name) + /// + /// All numeric conversion implemented for MDS numeric types are tested. + /// + /// The actual conversion is now handled by the templated + /// test_numeric_cast_function to account the possible exception throw if the + /// conversion is forbidden. + /// template - static void test_data_numerics(mds::Data *data, const std::vector &array); + inline void MdsDataTest::test_data_numerics(mds::Data *data, const T value) + { + TEST1(data->getSize() == 1); + + // TEST1( data->getByte() == mds::numeric_cast(value) ); + // TEST1( data->getShort() == mds::numeric_cast(value) ); + // TEST1( data->getInt() == mds::numeric_cast(value) ); + // TEST1( data->getLong() == mds::numeric_cast(value) ); + // TEST1( data->getByteUnsigned() == mds::numeric_cast(value) ); TEST1( data->getShortUnsigned() == + // mds::numeric_cast(value) ); TEST1( + // data->getIntUnsigned() == mds::numeric_cast(value) ); + // TEST1( data->getLongUnsigned() == mds::numeric_cast(value) + // ); TEST1( data->getFloat() == mds::numeric_cast(value) ); + // TEST1( data->getDouble() == mds::numeric_cast(value) ); + + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(char, getByte), value); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(short, getShort), + value); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int, getInt), value); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int64_t, getLong), + value); + + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned char, getByteUnsigned), value); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned short, getShortUnsigned), value); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned int, getIntUnsigned), value); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(uint64_t, getLongUnsigned), value); + + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(float, getFloat), + value); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(double, getDouble), + value); + + try + { + data->getComplex(); + } + catch (mds::MdsException &e) + { + TEST0(strcmp(e.what(), + "getComplex() not supported for non Complex data types")); + } + } + /// + /// Overload for all complex value conversions .. that in the case of a scalar + /// value is implemented to NOT throwing an exception but converting to the real + /// part. + /// template - static void test_data_numerics(mds::Data *data, - const std::vector > &array); - - static void test_data_string(mds::Data *data, const char *str) { - char *data_str = data->getString(); - int data_getString_differs_from_test = strcmp(data_str, str); - TEST0(data_getString_differs_from_test); - if (data_getString_differs_from_test) - std::cout << "tdi decompile: " << data_str << "\n" - << "test string: " << str << "\n"; - delete[] data_str; - } -}; - -/// -/// Takes a Data object and a getter of Array and returns a vector of the -/// obtained elements. -/// -template -inline typename MdsDataTest::ArrayFnptr::VectorType -MdsDataTest::get_vector(mds::Data *data, Fn fn) { - typedef typename ArrayFnptr::type R; - - std::vector out; - int size; - R *array = (data->*fn)(&size); - for (size_t i = 0; i < (unsigned int)size; ++i) - out.push_back(array[i]); - delete[] array; - return out; -} - -/// -/// If the numeric_cast throws an exception this catch and compare with the -/// getter method of the Data object. Otherwise the casted values are checked. -/// -template -inline void MdsDataTest::test_numeric_cast_function(mds::Data *data, Fn fn, - const T value) { - typedef typename detail::FunctionTypes::ReturnType R; - try { - mds::numeric_cast(value); - } catch (std::exception &e) { - TEST_STD_EXCEPTION((data->*fn)(), e.what()); + inline void MdsDataTest::test_data_numerics(mds::Data *data, + const std::complex value) + { + TEST1(data->getSize() == 1); + + // TEST1( data->getByte() == numeric_cast(value.real()) ); + // TEST1( data->getShort() == numeric_cast(value.real()) ); + // TEST1( data->getInt() == numeric_cast(value.real()) ); + // TEST1( data->getLong() == numeric_cast(value.real()) ); + // TEST1( data->getByteUnsigned() == numeric_cast(value.real()) ); TEST1( data->getShortUnsigned() == + // numeric_cast(value.real()) ); TEST1( + // data->getIntUnsigned() == numeric_cast(value.real()) ); + // TEST1( data->getLongUnsigned() == numeric_cast(value.real()) + // ); TEST1( data->getFloat() == numeric_cast(value.real()) ); + // TEST1( data->getDouble() == numeric_cast(value.real()) ); + + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(char, getByte), + value.real()); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(short, getShort), + value.real()); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int, getInt), + value.real()); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int64_t, getLong), + value.real()); + + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned char, getByteUnsigned), + value.real()); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned short, getShortUnsigned), + value.real()); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(unsigned int, getIntUnsigned), value.real()); + test_numeric_cast_function( + data, MDS_GETNUMERIC_FUNCPT(uint64_t, getLongUnsigned), value.real()); + + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(float, getFloat), + value.real()); + test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(double, getDouble), + value.real()); + + std::complex value_d(value.real(), value.imag()); + TEST1(data->getComplex() == value_d); } - try { - // NOTE: seems that the optimizer makes a fail in 32bit if these are not - // volatile variables ( failing case is: test_conversion_limits ) - volatile R casted_val = mds::numeric_cast(value); - volatile R data_val = (data->*fn)(); - TEST1(casted_val == data_val); - } catch (...) { - } // do not throw // -} - -#define MDS_GETARRAY_FUNCPT(type, name) \ - ((type * (mds::Data::*)(int *)) & mds::Data::name) - -#define MDS_GETNUMERIC_FUNCPT(type, name) \ - ((type(mds::Data::*)()) & mds::Data::name) -/// -/// All numeric conversion implemented for MDS numeric types are tested. -/// -/// The actual conversion is now handled by the templated -/// test_numeric_cast_function to account the possible exception throw if the -/// conversion is forbidden. -/// -template -inline void MdsDataTest::test_data_numerics(mds::Data *data, const T value) { - TEST1(data->getSize() == 1); - - // TEST1( data->getByte() == mds::numeric_cast(value) ); - // TEST1( data->getShort() == mds::numeric_cast(value) ); - // TEST1( data->getInt() == mds::numeric_cast(value) ); - // TEST1( data->getLong() == mds::numeric_cast(value) ); - // TEST1( data->getByteUnsigned() == mds::numeric_cast(value) ); TEST1( data->getShortUnsigned() == - // mds::numeric_cast(value) ); TEST1( - // data->getIntUnsigned() == mds::numeric_cast(value) ); - // TEST1( data->getLongUnsigned() == mds::numeric_cast(value) - // ); TEST1( data->getFloat() == mds::numeric_cast(value) ); - // TEST1( data->getDouble() == mds::numeric_cast(value) ); - - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(char, getByte), value); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(short, getShort), - value); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int, getInt), value); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int64_t, getLong), - value); - - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned char, getByteUnsigned), value); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned short, getShortUnsigned), value); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned int, getIntUnsigned), value); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(uint64_t, getLongUnsigned), value); - - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(float, getFloat), - value); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(double, getDouble), - value); - - try { - data->getComplex(); - } catch (mds::MdsException &e) { - TEST0(strcmp(e.what(), - "getComplex() not supported for non Complex data types")); - } -} - -/// -/// Overload for all complex value conversions .. that in the case of a scalar -/// value is implemented to NOT throwing an exception but converting to the real -/// part. -/// -template -inline void MdsDataTest::test_data_numerics(mds::Data *data, - const std::complex value) { - TEST1(data->getSize() == 1); - - // TEST1( data->getByte() == numeric_cast(value.real()) ); - // TEST1( data->getShort() == numeric_cast(value.real()) ); - // TEST1( data->getInt() == numeric_cast(value.real()) ); - // TEST1( data->getLong() == numeric_cast(value.real()) ); - // TEST1( data->getByteUnsigned() == numeric_cast(value.real()) ); TEST1( data->getShortUnsigned() == - // numeric_cast(value.real()) ); TEST1( - // data->getIntUnsigned() == numeric_cast(value.real()) ); - // TEST1( data->getLongUnsigned() == numeric_cast(value.real()) - // ); TEST1( data->getFloat() == numeric_cast(value.real()) ); - // TEST1( data->getDouble() == numeric_cast(value.real()) ); - - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(char, getByte), - value.real()); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(short, getShort), - value.real()); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int, getInt), - value.real()); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(int64_t, getLong), - value.real()); - - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned char, getByteUnsigned), - value.real()); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned short, getShortUnsigned), - value.real()); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(unsigned int, getIntUnsigned), value.real()); - test_numeric_cast_function( - data, MDS_GETNUMERIC_FUNCPT(uint64_t, getLongUnsigned), value.real()); - - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(float, getFloat), - value.real()); - test_numeric_cast_function(data, MDS_GETNUMERIC_FUNCPT(double, getDouble), - value.real()); - - std::complex value_d(value.real(), value.imag()); - TEST1(data->getComplex() == value_d); -} - -/// -/// Test data numeric conversion for Array data. This function overload treats -/// all data numeric types but the complex that should produce an exception. -/// The first function tests the size of the produced array, than all the -/// vector conversions and the array conversions. -/// -template -inline void MdsDataTest::test_data_numerics(mds::Data *data, - const std::vector &array) { - TEST1((unsigned int)data->getSize() == array.size()); - - TEST1(data->getByteArray() == array); - TEST1(data->getShortArray() == array); - TEST1(data->getIntArray() == array); - TEST1(data->getLongArray() == array); - - TEST1(data->getByteUnsignedArray() == array); - TEST1(data->getShortUnsignedArray() == array); - TEST1(data->getIntUnsignedArray() == array); - TEST1(data->getLongUnsignedArray() == array); - - TEST1(data->getFloatArray() == array); - TEST1(data->getDoubleArray() == array); - - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(char, getByteArray)) == array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(short, getShortArray)) == array); - TEST1(MdsDataTest::get_vector(data, MDS_GETARRAY_FUNCPT(int, getIntArray)) == - array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(int64_t, getLongArray)) == array); - - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(unsigned char, getByteUnsignedArray)) == - array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(unsigned short, getShortUnsignedArray)) == - array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(unsigned int, getIntUnsignedArray)) == - array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(uint64_t, getLongUnsignedArray)) == - array); - - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(float, getFloatArray)) == array); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(double, getDoubleArray)) == array); - - // see complex specialization below // - try { - data->getComplexArray(); - } catch (mds::MdsException &e) { - TEST0(strcmp(e.what(), - "getComplexArray() not supported for non Complex data types")); + /// + /// Test data numeric conversion for Array data. This function overload treats + /// all data numeric types but the complex that should produce an exception. + /// The first function tests the size of the produced array, than all the + /// vector conversions and the array conversions. + /// + template + inline void MdsDataTest::test_data_numerics(mds::Data *data, + const std::vector &array) + { + TEST1((unsigned int)data->getSize() == array.size()); + + TEST1(data->getByteArray() == array); + TEST1(data->getShortArray() == array); + TEST1(data->getIntArray() == array); + TEST1(data->getLongArray() == array); + + TEST1(data->getByteUnsignedArray() == array); + TEST1(data->getShortUnsignedArray() == array); + TEST1(data->getIntUnsignedArray() == array); + TEST1(data->getLongUnsignedArray() == array); + + TEST1(data->getFloatArray() == array); + TEST1(data->getDoubleArray() == array); + + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(char, getByteArray)) == array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(short, getShortArray)) == array); + TEST1(MdsDataTest::get_vector(data, MDS_GETARRAY_FUNCPT(int, getIntArray)) == + array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(int64_t, getLongArray)) == array); + + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(unsigned char, getByteUnsignedArray)) == + array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(unsigned short, getShortUnsignedArray)) == + array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(unsigned int, getIntUnsignedArray)) == + array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(uint64_t, getLongUnsignedArray)) == + array); + + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(float, getFloatArray)) == array); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(double, getDoubleArray)) == array); + + // see complex specialization below // + try + { + data->getComplexArray(); + } + catch (mds::MdsException &e) + { + TEST0(strcmp(e.what(), + "getComplexArray() not supported for non Complex data types")); + } } -} - -/// -/// All complex array are hadled by this overload that should produce an -/// exception when a conversionn to standard numeric type are performed. -/// -template -inline void -MdsDataTest::test_data_numerics(mds::Data *data, - const std::vector > &array) { - TEST1((unsigned int)data->getSize() == array.size()); - - TEST_MDS_EXCEPTION(data->getByteArray(), - "getByteArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION(data->getShortArray(), - "getShortArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION(data->getIntArray(), - "getIntArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION(data->getLongArray(), - "getLongArray() not supported for Complex data type"); - - TEST_MDS_EXCEPTION( - data->getByteUnsignedArray(), - "getByteUnsignedArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION( - data->getShortUnsignedArray(), - "getShortUnsignedArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION( - data->getIntUnsignedArray(), - "getIntUnsignedArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION( - data->getLongUnsignedArray(), - "getLongUnsignedArray() not supported for Complex data type"); - - TEST_MDS_EXCEPTION(data->getFloatArray(), - "getFloatArray() not supported for Complex data type"); - TEST_MDS_EXCEPTION(data->getDoubleArray(), - "getDoubleArray() not supported for Complex data type"); - - // cast T to double as all complex in Mds are double // - std::vector > array_d; - for (size_t i = 0; i < array.size(); ++i) { - const std::complex &el = array[i]; - array_d.push_back(std::complex(el.real(), el.imag())); + + /// + /// All complex array are hadled by this overload that should produce an + /// exception when a conversionn to standard numeric type are performed. + /// + template + inline void + MdsDataTest::test_data_numerics(mds::Data *data, + const std::vector > &array) + { + TEST1((unsigned int)data->getSize() == array.size()); + + TEST_MDS_EXCEPTION(data->getByteArray(), + "getByteArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION(data->getShortArray(), + "getShortArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION(data->getIntArray(), + "getIntArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION(data->getLongArray(), + "getLongArray() not supported for Complex data type"); + + TEST_MDS_EXCEPTION( + data->getByteUnsignedArray(), + "getByteUnsignedArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION( + data->getShortUnsignedArray(), + "getShortUnsignedArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION( + data->getIntUnsignedArray(), + "getIntUnsignedArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION( + data->getLongUnsignedArray(), + "getLongUnsignedArray() not supported for Complex data type"); + + TEST_MDS_EXCEPTION(data->getFloatArray(), + "getFloatArray() not supported for Complex data type"); + TEST_MDS_EXCEPTION(data->getDoubleArray(), + "getDoubleArray() not supported for Complex data type"); + + // cast T to double as all complex in Mds are double // + std::vector > array_d; + for (size_t i = 0; i < array.size(); ++i) + { + const std::complex &el = array[i]; + array_d.push_back(std::complex(el.real(), el.imag())); + } + TEST1(data->getComplexArray() == array_d); + TEST1(MdsDataTest::get_vector( + data, MDS_GETARRAY_FUNCPT(std::complex, getComplexArray)) == + array_d); } - TEST1(data->getComplexArray() == array_d); - TEST1(MdsDataTest::get_vector( - data, MDS_GETARRAY_FUNCPT(std::complex, getComplexArray)) == - array_d); -} #undef MDS_GETARRAY_FUNCPT #undef MDS_GETNUMERIC_FUNCPT diff --git a/mdsobjects/cpp/testing/MdsDimensionTest.cpp b/mdsobjects/cpp/testing/MdsDimensionTest.cpp index 1ea59bf04c..f859ee6d46 100644 --- a/mdsobjects/cpp/testing/MdsDimensionTest.cpp +++ b/mdsobjects/cpp/testing/MdsDimensionTest.cpp @@ -54,7 +54,8 @@ using namespace testing; // void setAxis(Data *axis){ assignDescAt(axis, 1); } //}; -int main() { +int main() +{ BEGIN_TESTING(Dimension); { // CTR diff --git a/mdsobjects/cpp/testing/MdsEventSuppression.cpp b/mdsobjects/cpp/testing/MdsEventSuppression.cpp index 1b8d71748b..bf088dec25 100644 --- a/mdsobjects/cpp/testing/MdsEventSuppression.cpp +++ b/mdsobjects/cpp/testing/MdsEventSuppression.cpp @@ -34,9 +34,12 @@ using namespace MDSplus; using namespace testing; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ - { Event::setEvent((char *)"test_event"); } + { + Event::setEvent((char *)"test_event"); + } { unique_ptr str = new String("test event string"); diff --git a/mdsobjects/cpp/testing/MdsEventTest.cpp b/mdsobjects/cpp/testing/MdsEventTest.cpp index 8a932d3d65..6f1a8ba26f 100644 --- a/mdsobjects/cpp/testing/MdsEventTest.cpp +++ b/mdsobjects/cpp/testing/MdsEventTest.cpp @@ -36,7 +36,8 @@ using namespace MDSplus; using namespace testing; namespace mds = MDSplus; -static void *sendStream(void *streamName) { +static void *sendStream(void *streamName) +{ sleep(1); Data *timeD = new Float32(1.0); Data *sampleD = new Float32(123.); @@ -47,7 +48,8 @@ static void *sendStream(void *streamName) { return NULL; } -static void *sendStreamAbs(void *streamName) { +static void *sendStreamAbs(void *streamName) +{ sleep(1); Data *timeD = new Uint64(1); Data *sampleD = new Float32(123.); @@ -58,10 +60,11 @@ static void *sendStreamAbs(void *streamName) { return NULL; } -static void *sendStreamArr(void *streamName) { +static void *sendStreamArr(void *streamName) +{ sleep(1); - float times[] = {1.,2}; - float samples[] = {10,11}; + float times[] = {1., 2}; + float samples[] = {10, 11}; Data *timesD = new Float32Array(times, 2); Data *samplesD = new Float32Array(samples, 2); EventStream::send(1, (char *)streamName, timesD, samplesD); @@ -71,10 +74,11 @@ static void *sendStreamArr(void *streamName) { return NULL; } -static void *sendStreamAbsArr(void *streamName) { +static void *sendStreamAbsArr(void *streamName) +{ sleep(1); - uint64_t times[] = {1,2}; - float samples[] = {10,11}; + uint64_t times[] = {1, 2}; + float samples[] = {10, 11}; Data *timesD = new Uint64Array(times, 2); Data *samplesD = new Float32Array(samples, 2); EventStream::send(1, (char *)streamName, timesD, samplesD); @@ -84,7 +88,8 @@ static void *sendStreamAbsArr(void *streamName) { return NULL; } -static void *setevent(void *evname) { +static void *setevent(void *evname) +{ sleep(1); Event::setEvent((char *)evname); // std::cout << "Event set\n" << std::flush; @@ -92,7 +97,8 @@ static void *setevent(void *evname) { return NULL; } -static void *seteventraw(void *args) { +static void *seteventraw(void *args) +{ sleep(1); std::string *str = ((std::string **)args)[1]; Event::setEventRaw(((char **)args)[0], str->size(), (char *)str->c_str()); @@ -101,7 +107,8 @@ static void *seteventraw(void *args) { return NULL; } -static void *seteventdata(void *args) { +static void *seteventdata(void *args) +{ sleep(1); Event::setEvent(((char **)args)[0], ((Data **)args)[1]); // std::cout << "EventData set\n" << std::flush; @@ -109,132 +116,150 @@ static void *seteventdata(void *args) { return NULL; } -class TestListenerScalarRelative: public MDSplus::DataStreamListener +class TestListenerScalarRelative : public MDSplus::DataStreamListener { - ConditionVar condition; - float retTime; - float retSample; - int retShot; + ConditionVar condition; + float retTime; + float retSample; + int retShot; + public: - TestListenerScalarRelative() - { - } - void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) - { - retTime = times->getFloat(); - retSample = samples->getFloat(); - retShot = shot; - condition.notify(); - } - void waitStream() - { + TestListenerScalarRelative() + { + } + void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) + { + retTime = times->getFloat(); + retSample = samples->getFloat(); + retShot = shot; + condition.notify(); + } + void waitStream() + { - if (condition.waitTimeout(10 * 1000) == false) - throw MdsException("Timeout Occurred"); - } - float getTime() {return retTime;} - float getSample() {return retSample;} - int getShot() {return retShot;} + if (condition.waitTimeout(10 * 1000) == false) + throw MdsException("Timeout Occurred"); + } + float getTime() { return retTime; } + float getSample() { return retSample; } + int getShot() { return retShot; } }; -class TestListenerScalarAbsolute: public MDSplus::DataStreamListener +class TestListenerScalarAbsolute : public MDSplus::DataStreamListener { - ConditionVar condition; - uint64_t retTime; - float retSample; - int retShot; + ConditionVar condition; + uint64_t retTime; + float retSample; + int retShot; + public: - TestListenerScalarAbsolute() - { - } - void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) - { - retTime = (uint64_t)times->getLong(); - retSample = samples->getFloat(); - retShot = shot; - condition.notify(); - } - void waitStream() - { + TestListenerScalarAbsolute() + { + } + void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) + { + retTime = (uint64_t)times->getLong(); + retSample = samples->getFloat(); + retShot = shot; + condition.notify(); + } + void waitStream() + { - if (condition.waitTimeout(10 * 1000) == false) - throw MdsException("Timeout Occurred"); - } - uint64_t getTime() {return retTime;} - float getSample() {return retSample;} - int getShot() {return retShot;} + if (condition.waitTimeout(10 * 1000) == false) + throw MdsException("Timeout Occurred"); + } + uint64_t getTime() { return retTime; } + float getSample() { return retSample; } + int getShot() { return retShot; } }; -class TestListenerArrayRelative: public MDSplus::DataStreamListener +class TestListenerArrayRelative : public MDSplus::DataStreamListener { - ConditionVar condition; - float *retTimes; - float *retSamples; - int retShot, retTimesLen, retSamplesLen; + ConditionVar condition; + float *retTimes; + float *retSamples; + int retShot, retTimesLen, retSamplesLen; + public: - TestListenerArrayRelative() - { - } - void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) - { - retTimes = times->getFloatArray(&retTimesLen); - retSamples= samples->getFloatArray(&retSamplesLen); - retShot = shot; - condition.notify(); - } - void waitStream() - { + TestListenerArrayRelative() + { + } + void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) + { + retTimes = times->getFloatArray(&retTimesLen); + retSamples = samples->getFloatArray(&retSamplesLen); + retShot = shot; + condition.notify(); + } + void waitStream() + { - if (condition.waitTimeout(10 * 1000) == false) - throw MdsException("Timeout Occurred"); - } - float *getTimes(int *retTimeLen) {*retTimeLen = retTimesLen; return retTimes;} - float *getSamples(int *retSampleLen) {*retSampleLen = retSamplesLen; return retSamples;} - int getShot() {return retShot;} + if (condition.waitTimeout(10 * 1000) == false) + throw MdsException("Timeout Occurred"); + } + float *getTimes(int *retTimeLen) + { + *retTimeLen = retTimesLen; + return retTimes; + } + float *getSamples(int *retSampleLen) + { + *retSampleLen = retSamplesLen; + return retSamples; + } + int getShot() { return retShot; } }; -class TestListenerArrayAbsolute: public MDSplus::DataStreamListener +class TestListenerArrayAbsolute : public MDSplus::DataStreamListener { - ConditionVar condition; - uint64_t *retTimes; - float *retSamples; - int retShot, retTimesLen, retSamplesLen; + ConditionVar condition; + uint64_t *retTimes; + float *retSamples; + int retShot, retTimesLen, retSamplesLen; + public: - TestListenerArrayAbsolute() - { - } - void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) - { - retTimes = (uint64_t *)times->getLongArray(&retTimesLen); - retSamples= samples->getFloatArray(&retSamplesLen); - retShot = shot; - condition.notify(); - } - void waitStream() - { + TestListenerArrayAbsolute() + { + } + void dataReceived(MDSplus::Data *samples, MDSplus::Data *times, int shot) + { + retTimes = (uint64_t *)times->getLongArray(&retTimesLen); + retSamples = samples->getFloatArray(&retSamplesLen); + retShot = shot; + condition.notify(); + } + void waitStream() + { - if (condition.waitTimeout(10 * 1000) == false) - throw MdsException("Timeout Occurred"); - } - uint64_t *getTimes(int *retTimeLen) {*retTimeLen = retTimesLen; return retTimes;} - float *getSamples(int *retSampleLen) {*retSampleLen = retSamplesLen; return retSamples;} - int getShot() {return retShot;} + if (condition.waitTimeout(10 * 1000) == false) + throw MdsException("Timeout Occurred"); + } + uint64_t *getTimes(int *retTimeLen) + { + *retTimeLen = retTimesLen; + return retTimes; + } + float *getSamples(int *retSampleLen) + { + *retSampleLen = retSamplesLen; + return retSamples; + } + int getShot() { return retShot; } }; - - - - - int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Event); pthread_attr_t attr, *attrp; if (pthread_attr_init(&attr)) attrp = NULL; - else { + else + { attrp = &attr; pthread_attr_setstacksize(&attr, 0x100000); } - try { + try + { static char evname[100] = "empty"; if (strcmp(evname, "empty") == 0) sprintf(evname, "event_test_%d", getpid()); @@ -244,9 +269,11 @@ int main(int argc __attribute__((unused)), if (pthread_create(&thread, attrp, setevent, (void *)evname)) throw std::runtime_error("ERROR: Could not create thread for setevent"); Event ev(evname); - std::cout << "Waiting for wait\n" << std::flush; + std::cout << "Waiting for wait\n" + << std::flush; ev.wait(); - std::cout << "Waiting for thread\n" << std::flush; + std::cout << "Waiting for thread\n" + << std::flush; pthread_join(thread, NULL); } @@ -259,9 +286,11 @@ int main(int argc __attribute__((unused)), "ERROR: Could not create thread for seteventraw"); Event ev(evname); size_t buf_len = 0; - std::cout << "Waiting for waitRaw\n" << std::flush; + std::cout << "Waiting for waitRaw\n" + << std::flush; const char *buf = ev.waitRaw(&buf_len); - std::cout << "Waiting for thread\n" << std::flush; + std::cout << "Waiting for thread\n" + << std::flush; pthread_join(thread, NULL); TEST1(std::string(str) == std::string(buf)); } @@ -274,14 +303,16 @@ int main(int argc __attribute__((unused)), throw std::runtime_error( "ERROR: Could not create thread for seteventdata"); Event ev(evname); - std::cout << "Waiting for waitData\n" << std::flush; + std::cout << "Waiting for waitData\n" + << std::flush; unique_ptr data = ev.waitData(); - std::cout << "Waiting for thread\n" << std::flush; + std::cout << "Waiting for thread\n" + << std::flush; pthread_join(thread, NULL); TEST1(AutoString(data->getString()).string == AutoString(str->getString()).string); } - + MDSplus::EventStream evStreamScalarRelative("EVENT_TEST:[]SCALAR_RELATIVE"); MDSplus::EventStream evStreamScalarAbsolute("EVENT_TEST:[]SCALAR_ABSOLUTE"); MDSplus::EventStream evStreamArrayRelative("EVENT_TEST:[]ARRAY_RELATIVE"); @@ -304,7 +335,7 @@ int main(int argc __attribute__((unused)), throw std::runtime_error( "ERROR: Could not create thread for sendStream"); - // std::cout << "Waiting for stream\n" << std::flush; + // std::cout << "Waiting for stream\n" << std::flush; testListenerScalarRelative.waitStream(); pthread_join(thread, NULL); float retTime = testListenerScalarRelative.getTime(); @@ -320,7 +351,7 @@ int main(int argc __attribute__((unused)), throw std::runtime_error( "ERROR: Could not create thread for sendStream"); - // std::cout << "Waiting for stream\n" << std::flush; + // std::cout << "Waiting for stream\n" << std::flush; testListenerScalarAbsolute.waitStream(); pthread_join(thread, NULL); uint64_t retTime = testListenerScalarAbsolute.getTime(); @@ -336,11 +367,11 @@ int main(int argc __attribute__((unused)), throw std::runtime_error( "ERROR: Could not create thread for sendStream"); - // std::cout << "Waiting for stream\n" << std::flush; + // std::cout << "Waiting for stream\n" << std::flush; testListenerArrayRelative.waitStream(); pthread_join(thread, NULL); int retTimesSize, retSamplesSize; - float *retTimes = testListenerArrayRelative.getTimes(&retTimesSize); + float *retTimes = testListenerArrayRelative.getTimes(&retTimesSize); float *retSamples = testListenerArrayRelative.getSamples(&retSamplesSize); int retShot = testListenerArrayRelative.getShot(); TEST1(retTimesSize == 2); @@ -349,7 +380,7 @@ int main(int argc __attribute__((unused)), TEST1(retSamples[0] == 10. && retSamples[1] == 11.) TEST1(retShot == 1); delete[] retTimes; - delete [] retSamples; + delete[] retSamples; } { // STREAM ARRAY ABSOLUTE TIME pthread_t thread; @@ -357,11 +388,11 @@ int main(int argc __attribute__((unused)), throw std::runtime_error( "ERROR: Could not create thread for sendStream"); - // std::cout << "Waiting for stream\n" << std::flush; + // std::cout << "Waiting for stream\n" << std::flush; testListenerArrayAbsolute.waitStream(); pthread_join(thread, NULL); int retTimesSize, retSamplesSize; - uint64_t *retTimes = testListenerArrayAbsolute.getTimes(&retTimesSize); + uint64_t *retTimes = testListenerArrayAbsolute.getTimes(&retTimesSize); float *retSamples = testListenerArrayAbsolute.getSamples(&retSamplesSize); int retShot = testListenerArrayAbsolute.getShot(); TEST1(retTimesSize == 2); @@ -370,11 +401,11 @@ int main(int argc __attribute__((unused)), TEST1(retSamples[0] == 10. && retSamples[1] == 11.) TEST1(retShot == 1); delete[] retTimes; - delete [] retSamples; + delete[] retSamples; } - - - } catch (...) { + } + catch (...) + { if (attrp) pthread_attr_destroy(attrp); throw; diff --git a/mdsobjects/cpp/testing/MdsExceptionTest.cpp b/mdsobjects/cpp/testing/MdsExceptionTest.cpp index 01076e54cf..ef9840afc2 100644 --- a/mdsobjects/cpp/testing/MdsExceptionTest.cpp +++ b/mdsobjects/cpp/testing/MdsExceptionTest.cpp @@ -32,18 +32,25 @@ void throw_exception_msg() { throw mds::MdsException("test message"); } void throw_exception_status() { throw mds::MdsException(5552368); } -int main() { +int main() +{ BEGIN_TESTING(MdsException); - try { + try + { throw_exception_msg(); - } catch (mds::MdsException e) { + } + catch (mds::MdsException e) + { TEST1(std::string(e.what()) == "test message"); } - try { + try + { throw_exception_status(); - } catch (mds::MdsException e) { + } + catch (mds::MdsException e) + { TEST1(std::string(e.what()) == std::string(MdsGetMsg(5552368))); } diff --git a/mdsobjects/cpp/testing/MdsExpressionCompileTest.cpp b/mdsobjects/cpp/testing/MdsExpressionCompileTest.cpp index e896246a33..f72862ef91 100644 --- a/mdsobjects/cpp/testing/MdsExpressionCompileTest.cpp +++ b/mdsobjects/cpp/testing/MdsExpressionCompileTest.cpp @@ -60,28 +60,34 @@ const char *PyCmds[] = { }; const int PyNCmd = sizeof(PyCmds) / sizeof(*PyCmds); -void *Test(void *args) { +void *Test(void *args) +{ int ii = 0, ic = 0; int ncmd = *(int *)((void **)args)[0]; char **cmds = (char **)((void **)args)[1]; delete MDSplus::execute("TreeShr->TreeUsePrivateCtx(1)"); - try { + try + { for (; ii < NUM_REPEATS; ii++) for (; ic < ncmd; ic++) delete MDSplus::execute(cmds[ic]); - } catch (MDSplus::MdsException) { + } + catch (MDSplus::MdsException) + { std::cerr << "ERROR in cycle " << ii << " >> " << cmds[ic] << "\n"; throw; } return NULL; } -void MultiThreadTest(int ncmd, const char *cmds[]) { +void MultiThreadTest(int ncmd, const char *cmds[]) +{ pthread_t threads[NUM_THREADS]; pthread_attr_t attr, *attrp; if (pthread_attr_init(&attr)) attrp = NULL; - else { + else + { attrp = &attr; pthread_attr_setstacksize(&attr, 0x80000); } @@ -98,14 +104,16 @@ void MultiThreadTest(int ncmd, const char *cmds[]) { pthread_join(threads[nt], NULL); } -#define TEST_INT(cmd, value) \ - do { \ - MDSplus::Data *d = MDSplus::execute(cmd); \ - TEST1(d->getInt() == value); \ - delete d; \ +#define TEST_INT(cmd, value) \ + do \ + { \ + MDSplus::Data *d = MDSplus::execute(cmd); \ + TEST1(d->getInt() == value); \ + delete d; \ } while (0) int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(ExpressionCompile); delete MDSplus::execute("_s=[1,2,3]"); TEST_INT("public _s = 3", 3); @@ -125,7 +133,8 @@ int main(int argc __attribute__((unused)), MultiThreadTest(TreeNCmd, TreeCmds); END_TESTING; // python tests will not pass any test - if (getenv("PyLib") && getenv("TEST_PYTHON")) { + if (getenv("PyLib") && getenv("TEST_PYTHON")) + { BEGIN_TESTING(MultiThreadPython); MultiThreadTest(PyNCmd, PyCmds); END_TESTING; diff --git a/mdsobjects/cpp/testing/MdsFunctionTest.cpp b/mdsobjects/cpp/testing/MdsFunctionTest.cpp index f60586a129..069a7eca08 100644 --- a/mdsobjects/cpp/testing/MdsFunctionTest.cpp +++ b/mdsobjects/cpp/testing/MdsFunctionTest.cpp @@ -35,17 +35,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace MDSplus; using namespace testing; -void PrintOpcodes() { +void PrintOpcodes() +{ for (int i = 0; i < 456 /*std::numeric_limits::max()*/; ++i) std::cout << "opcode: " << i << " = " << (Function *)unique_ptr(new Function(i, 0, NULL)) << "\n"; } -int main(int argc __attribute__((unused)), char **argv) { +int main(int argc __attribute__((unused)), char **argv) +{ BEGIN_TESTING(Function); - if (argc > 1 && std::string(argv[1]) == std::string("print")) { + if (argc > 1 && std::string(argv[1]) == std::string("print")) + { PrintOpcodes(); exit(0); } diff --git a/mdsobjects/cpp/testing/MdsRangeTest.cpp b/mdsobjects/cpp/testing/MdsRangeTest.cpp index 1b8b6b6484..8d097a2186 100644 --- a/mdsobjects/cpp/testing/MdsRangeTest.cpp +++ b/mdsobjects/cpp/testing/MdsRangeTest.cpp @@ -35,7 +35,8 @@ using namespace testing; // Range COMPOUND /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int main() { +int main() +{ BEGIN_TESTING(Range); { // CTR diff --git a/mdsobjects/cpp/testing/MdsScalarTest_NumericConversion.cpp b/mdsobjects/cpp/testing/MdsScalarTest_NumericConversion.cpp index 228dd04a9d..1595203430 100644 --- a/mdsobjects/cpp/testing/MdsScalarTest_NumericConversion.cpp +++ b/mdsobjects/cpp/testing/MdsScalarTest_NumericConversion.cpp @@ -45,7 +45,8 @@ using namespace testing; // SIGNED //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void test_Int8() { +void test_Int8() +{ signed char value = 123; Data *data = new Int8(value); @@ -54,7 +55,8 @@ void test_Int8() { deleteData(data); } -void test_Int8Array() { +void test_Int8Array() +{ std::vector value; value << (char)1, 2, 3, 123; @@ -66,7 +68,8 @@ void test_Int8Array() { deleteData(data); } -void test_Int16() { +void test_Int16() +{ signed short value = 123; Data *data = new Int16(value); @@ -75,7 +78,8 @@ void test_Int16() { deleteData(data); } -void test_Int16Array() { +void test_Int16Array() +{ std::vector value; value << (short)1, 2, 3, 123; @@ -87,7 +91,8 @@ void test_Int16Array() { deleteData(data); } -void test_Int32() { +void test_Int32() +{ signed int value = 123; Data *data = new Int32(value); @@ -96,7 +101,8 @@ void test_Int32() { deleteData(data); } -void test_Int32Array() { +void test_Int32Array() +{ std::vector value; value << (int)1, 2, 3, 123; @@ -108,7 +114,8 @@ void test_Int32Array() { deleteData(data); } -void test_Int64() { +void test_Int64() +{ int64_t value = 123; Data *data = new Int64(value); @@ -117,7 +124,8 @@ void test_Int64() { deleteData(data); } -void test_Int64Array() { +void test_Int64Array() +{ std::vector value; value << (int64_t)1, 2, 3, 123; @@ -133,7 +141,8 @@ void test_Int64Array() { // UNSIGED /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void test_Uint8() { +void test_Uint8() +{ unsigned char value = 123; Data *data = new Uint8(value); @@ -142,7 +151,8 @@ void test_Uint8() { deleteData(data); } -void test_Uint8Array() { +void test_Uint8Array() +{ std::vector value; value << (unsigned char)1, 2, 3, 123; @@ -154,7 +164,8 @@ void test_Uint8Array() { deleteData(data); } -void test_Uint16() { +void test_Uint16() +{ unsigned short value = 123; Data *data = new Uint16(value); @@ -163,7 +174,8 @@ void test_Uint16() { deleteData(data); } -void test_Uint16Array() { +void test_Uint16Array() +{ std::vector value; value << (unsigned short)1, 2, 3, 123; @@ -175,7 +187,8 @@ void test_Uint16Array() { deleteData(data); } -void test_Uint32() { +void test_Uint32() +{ unsigned int value = 123; Data *data = new Uint32(value); @@ -184,7 +197,8 @@ void test_Uint32() { deleteData(data); } -void test_Uint32Array() { +void test_Uint32Array() +{ std::vector value; value << (unsigned int)1, 2, 3, 123; @@ -196,7 +210,8 @@ void test_Uint32Array() { deleteData(data); } -void test_Uint64() { +void test_Uint64() +{ uint64_t value = 123; Data *data = new Uint64(value); @@ -205,7 +220,8 @@ void test_Uint64() { deleteData(data); } -void test_Uint64Array() { +void test_Uint64Array() +{ std::vector value; value << (uint64_t)1, 2, 3, 123; @@ -221,7 +237,8 @@ void test_Uint64Array() { // FLOATS //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void test_Float32() { +void test_Float32() +{ float value = 123.2368; @@ -231,7 +248,8 @@ void test_Float32() { deleteData(data); } -void test_Float32Array() { +void test_Float32Array() +{ std::vector value; value << (float)1, 2, 3, 123.2368; @@ -242,7 +260,8 @@ void test_Float32Array() { deleteData(data); } -void test_Float64() { +void test_Float64() +{ double value = 123.2368; @@ -252,7 +271,8 @@ void test_Float64() { deleteData(data); } -void test_Float64Array() { +void test_Float64Array() +{ std::vector value; value << (double)1, 2, 3, 123.2368; @@ -268,7 +288,8 @@ void test_Float64Array() { // COMPLEX /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void test_Complex32() { +void test_Complex32() +{ std::complex value(1.23, 123.2368); Data *data = new Complex32(value.real(), value.imag()); @@ -277,7 +298,8 @@ void test_Complex32() { deleteData(data); } -void test_Complex32Array() { +void test_Complex32Array() +{ typedef std::complex Cf; TEST1(sizeof(Cf) == sizeof(float) * 2); @@ -293,7 +315,8 @@ void test_Complex32Array() { deleteData(data); } -void test_Complex64() { +void test_Complex64() +{ std::complex value(1.23, 123.2368); Data *data = new Complex64(value.real(), value.imag()); @@ -302,7 +325,8 @@ void test_Complex64() { deleteData(data); } -void test_Complex64Array() { +void test_Complex64Array() +{ typedef std::complex Cf; TEST1(sizeof(Cf) == sizeof(double) * 2); @@ -323,7 +347,8 @@ void test_Complex64Array() { //////////////////////////////////////////////////////////////////////////////// int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Data); test_Int8(); diff --git a/mdsobjects/cpp/testing/MdsScalarTest_NumericLimits.cpp b/mdsobjects/cpp/testing/MdsScalarTest_NumericLimits.cpp index 1c8ef5b1df..b2697a2c55 100644 --- a/mdsobjects/cpp/testing/MdsScalarTest_NumericLimits.cpp +++ b/mdsobjects/cpp/testing/MdsScalarTest_NumericLimits.cpp @@ -40,103 +40,107 @@ using namespace testing; // NumericLimits Test //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace testing { - -/// -/// \brief The TestLimits class -/// -/// This tests numeric conversion of Data object with numerical limits .. - -/// -class TestLimits { -public: - template - static void print_type_conversion_test(const std::string &type_name) { - typedef typename detail::mds2cpp_typemap<_MdsT>::type c_type; - c_type min = numeric_limits::lowest(); - c_type eps = numeric_limits::epsilon(); - c_type max = numeric_limits::highest(); - - Data *mds_min = new _MdsT(min); - Data *mds_eps = new _MdsT(eps); - Data *mds_max = new _MdsT(max); - - std::cout << "testing::TestLimits::test_conversion_limits<" << type_name - << ">(" - << "\"" << mdsdata_to_string(mds_min) << "\"," - << "\"" << mdsdata_to_string(mds_eps) << "\"," - << "\"" << mdsdata_to_string(mds_max) << "\");\n"; - - deleteData(mds_min); - deleteData(mds_eps); - deleteData(mds_max); - } - - template - static void test_conversion_limits(const std::string &tmin = "", - const std::string &teps = "", - const std::string &tmax = "") { - typedef typename detail::mds2cpp_typemap<_MdsT>::type c_type; - c_type min = numeric_limits::lowest(); - c_type eps = numeric_limits::epsilon(); - c_type max = numeric_limits::highest(); - - { // MIN // - c_type &value = min; - const std::string &str = tmin; - - Data *data = new _MdsT(value); - print_type_encoded(data); - MdsDataTest::test_data_numerics(data, value); - if (!str.empty()) - MdsDataTest::test_data_string(data, str.c_str()); - deleteData(data); - } - { // 0 + EPSILON // - c_type &value = eps; - const std::string &str = teps; - - Data *data = new _MdsT(value); - print_type_encoded(data); - MdsDataTest::test_data_numerics(data, value); - if (!str.empty()) - MdsDataTest::test_data_string(data, str.c_str()); - deleteData(data); +namespace testing +{ + + /// + /// \brief The TestLimits class + /// + /// This tests numeric conversion of Data object with numerical limits .. + + /// + class TestLimits + { + public: + template + static void print_type_conversion_test(const std::string &type_name) + { + typedef typename detail::mds2cpp_typemap<_MdsT>::type c_type; + c_type min = numeric_limits::lowest(); + c_type eps = numeric_limits::epsilon(); + c_type max = numeric_limits::highest(); + + Data *mds_min = new _MdsT(min); + Data *mds_eps = new _MdsT(eps); + Data *mds_max = new _MdsT(max); + + std::cout << "testing::TestLimits::test_conversion_limits<" << type_name + << ">(" + << "\"" << mdsdata_to_string(mds_min) << "\"," + << "\"" << mdsdata_to_string(mds_eps) << "\"," + << "\"" << mdsdata_to_string(mds_max) << "\");\n"; + + deleteData(mds_min); + deleteData(mds_eps); + deleteData(mds_max); } - { // MAX // - c_type &value = max; - const std::string &str = tmax; - - Data *data = new _MdsT(value); - print_type_encoded(data); - MdsDataTest::test_data_numerics(data, value); - if (!str.empty()) - MdsDataTest::test_data_string(data, str.c_str()); - deleteData(data); + + template + static void test_conversion_limits(const std::string &tmin = "", + const std::string &teps = "", + const std::string &tmax = "") + { + typedef typename detail::mds2cpp_typemap<_MdsT>::type c_type; + c_type min = numeric_limits::lowest(); + c_type eps = numeric_limits::epsilon(); + c_type max = numeric_limits::highest(); + + { // MIN // + c_type &value = min; + const std::string &str = tmin; + + Data *data = new _MdsT(value); + print_type_encoded(data); + MdsDataTest::test_data_numerics(data, value); + if (!str.empty()) + MdsDataTest::test_data_string(data, str.c_str()); + deleteData(data); + } + { // 0 + EPSILON // + c_type &value = eps; + const std::string &str = teps; + + Data *data = new _MdsT(value); + print_type_encoded(data); + MdsDataTest::test_data_numerics(data, value); + if (!str.empty()) + MdsDataTest::test_data_string(data, str.c_str()); + deleteData(data); + } + { // MAX // + c_type &value = max; + const std::string &str = tmax; + + Data *data = new _MdsT(value); + print_type_encoded(data); + MdsDataTest::test_data_numerics(data, value); + if (!str.empty()) + MdsDataTest::test_data_string(data, str.c_str()); + deleteData(data); + } } - } - // TODO: check limits for arrays // - template - static void test_type_conversion_array(const std::string &tmin = "", - const std::string &teps = "", - const std::string &tmax = "") {} -}; - -// SPECIAL TRAIT FOR FLOAT .. // -// template <> -// void TestLimits::test_conversion_limits(const std::string &tmin, -// const std::string &teps, -// const std::string &tmax) -//{ -// typedef typename detail::mds2cpp_typemap::type c_type; -// c_type max = std::numeric_limits::max(); -// std::cout << " TESTING TRAIT FOR FLOAT: \n" -// << " max = " << max << "\n" -// << " static_cast(max) = " << static_cast(max) << "\n" -// << " numeric_cast(max) = " << -// Scalar::numeric_cast(max) << "\n"; -//} + // TODO: check limits for arrays // + template + static void test_type_conversion_array(const std::string &tmin = "", + const std::string &teps = "", + const std::string &tmax = "") {} + }; + + // SPECIAL TRAIT FOR FLOAT .. // + // template <> + // void TestLimits::test_conversion_limits(const std::string &tmin, + // const std::string &teps, + // const std::string &tmax) + //{ + // typedef typename detail::mds2cpp_typemap::type c_type; + // c_type max = std::numeric_limits::max(); + // std::cout << " TESTING TRAIT FOR FLOAT: \n" + // << " max = " << max << "\n" + // << " static_cast(max) = " << static_cast(max) << "\n" + // << " numeric_cast(max) = " << + // Scalar::numeric_cast(max) << "\n"; + //} } // namespace testing @@ -148,14 +152,16 @@ class TestLimits { /// This is a simple print of the test line to automatically compute type /// limits if the print argument is passed to the test execution. /// -#define MDS_TEST_PRINT_TESTLINE(type) \ +#define MDS_TEST_PRINT_TESTLINE(type) \ testing::TestLimits::print_type_conversion_test(#type); int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Data); - if (argc > 1 && !strcmp(argv[1], "print")) { + if (argc > 1 && !strcmp(argv[1], "print")) + { std::cout << "--- CUT FROM HERE ------------------------------------\n"; MDS_TEST_PRINT_TESTLINE(Int8); diff --git a/mdsobjects/cpp/testing/MdsScalarTest_ScalarCast.cpp b/mdsobjects/cpp/testing/MdsScalarTest_ScalarCast.cpp index c0e9fe2ba4..2dd2a42a25 100644 --- a/mdsobjects/cpp/testing/MdsScalarTest_ScalarCast.cpp +++ b/mdsobjects/cpp/testing/MdsScalarTest_ScalarCast.cpp @@ -46,7 +46,8 @@ using namespace testing; // INTEGER // template typename enable_if::is_integer, void>::type -numeric_cast_test() { +numeric_cast_test() +{ unsigned long long int max = numeric_limits::highest(); long long int min = numeric_limits::lowest(); @@ -61,7 +62,8 @@ numeric_cast_test() { TEST_EXCEPTION(numeric_cast(max + 1), std::overflow_error); TEST_EXCEPTION(numeric_cast(min - 1), std::underflow_error); - if (numeric_limits::digits < numeric_limits::digits) { + if (numeric_limits::digits < numeric_limits::digits) + { // IS A COERCION so we can check next of max_f // TEST_EXCEPTION(numeric_cast(max_f + 1), std::overflow_error); TEST_EXCEPTION(numeric_cast(min_f - 1), std::underflow_error); @@ -76,7 +78,8 @@ numeric_cast_test() {} /// this may trigger an exception where overflow should be thrown by /// numeric_cast int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(ScalarCast); // TEST IF ISNAN WORKS // diff --git a/mdsobjects/cpp/testing/MdsSignalTest.cpp b/mdsobjects/cpp/testing/MdsSignalTest.cpp index ee3cf3513a..223307f9eb 100644 --- a/mdsobjects/cpp/testing/MdsSignalTest.cpp +++ b/mdsobjects/cpp/testing/MdsSignalTest.cpp @@ -65,7 +65,8 @@ using namespace testing; //}; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Signal); Data *raw[200]; diff --git a/mdsobjects/cpp/testing/MdsStringTest.cpp b/mdsobjects/cpp/testing/MdsStringTest.cpp index 6fcce68a51..7ede014cd0 100644 --- a/mdsobjects/cpp/testing/MdsStringTest.cpp +++ b/mdsobjects/cpp/testing/MdsStringTest.cpp @@ -58,7 +58,8 @@ using namespace testing; //}; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(String); { @@ -80,8 +81,11 @@ int main(int argc __attribute__((unused)), { char *string[] = { - (char *)"str1", (char *)"str2", (char *)"str3", - (char *)"str4", (char *)"str5", + (char *)"str1", + (char *)"str2", + (char *)"str3", + (char *)"str4", + (char *)"str5", }; Array *sactr1 = new StringArray(string, 5); diff --git a/mdsobjects/cpp/testing/MdsTdiTest.cpp b/mdsobjects/cpp/testing/MdsTdiTest.cpp index 034d91554e..f35c0bdbc3 100644 --- a/mdsobjects/cpp/testing/MdsTdiTest.cpp +++ b/mdsobjects/cpp/testing/MdsTdiTest.cpp @@ -42,9 +42,11 @@ using namespace testing; static char **cmds; static int ncmd; -void loadCmds(const char *filename) { +void loadCmds(const char *filename) +{ std::ifstream file(filename); - if (!file.is_open()) { + if (!file.is_open()) + { std::cerr << "File not found: " << filename << "\n"; exit(1); } @@ -52,10 +54,12 @@ void loadCmds(const char *filename) { int memlen = MEM_ALLOC; cmds = (char **)malloc(memlen * sizeof(char *)); ncmd = 0; - while (std::getline(file, str)) { + while (std::getline(file, str)) + { if (str[0] == '!' || str.length() == 0) continue; - if ((ncmd + 1) > memlen) { + if ((ncmd + 1) > memlen) + { memlen += MEM_ALLOC; cmds = (char **)realloc(cmds, memlen * sizeof(char *)); } @@ -64,7 +68,8 @@ void loadCmds(const char *filename) { } } -int SingleThreadTest(int idx, int repeats) { +int SingleThreadTest(int idx, int repeats) +{ int ii = 0, ic = 0; setenv("t_tdi_path", ".", 1); delete MDSplus::execute("TreeShr->TreeUsePrivateCtx(1)"); @@ -73,22 +78,30 @@ int SingleThreadTest(int idx, int repeats) { delete shot; delete MDSplus::execute("_EXPT='T_TDI'"); int status = -1, err = 0; - for (; ii < repeats; ii++) { + for (; ii < repeats; ii++) + { for (; ic < ncmd; ic++) - try { + try + { if (strlen(cmds[ic]) == 0 || *cmds[ic] == '#') continue; status = AutoPointer(MDSplus::execute(cmds[ic]))->getInt(); - if (!status) { + if (!status) + { std::cerr << "FAILED in cycle " << ii << " >> " << cmds[ic] << "\n"; err = 1; - } else if (!(status & 1)) + } + else if (!(status & 1)) throw MDSplus::MdsException(status); - } catch (MDSplus::MdsException e) { + } + catch (MDSplus::MdsException e) + { std::cerr << "ERROR in cycle " << ii << ":=" << status << " >> " << cmds[ic] << "\n"; err = 1; - } catch (...) { + } + catch (...) + { std::cerr << "Exception in cycle " << ii << " >> " << cmds[ic] << "\n"; err = 1; } @@ -98,23 +111,27 @@ int SingleThreadTest(int idx, int repeats) { return err; } -void *ThreadTest(void *args) { +void *ThreadTest(void *args) +{ int *err = (int *)args; *err = SingleThreadTest(*(int *)args, NUM_REPEATS); return NULL; } -void MultiThreadTest() { +void MultiThreadTest() +{ pthread_t threads[NUM_THREADS]; pthread_attr_t attr, *attrp; if (pthread_attr_init(&attr)) attrp = NULL; - else { + else + { attrp = &attr; pthread_attr_setstacksize(&attr, 0x40000); } int thread_idx, results[NUM_THREADS]; - for (thread_idx = 0; thread_idx < NUM_THREADS; thread_idx++) { + for (thread_idx = 0; thread_idx < NUM_THREADS; thread_idx++) + { results[thread_idx] = thread_idx; if (pthread_create(&threads[thread_idx], attrp, ThreadTest, &results[thread_idx])) @@ -130,22 +147,26 @@ void MultiThreadTest() { TEST0(results[thread_idx]); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ size_t stksize = -1; { pthread_attr_t attr; - if (!pthread_attr_init(&attr)) { + if (!pthread_attr_init(&attr)) + { pthread_attr_getstacksize(&attr, &stksize); pthread_attr_destroy(&attr); } } if (argc > 1) loadCmds(argv[1]); - else { + else + { char *srcdir = std::getenv("srcdir"); if (!srcdir) loadCmds("./MdsTdiTest.tdi"); - else { + else + { char *filename = (char *)malloc(strlen(srcdir) + 16); memcpy(filename, srcdir, strlen(srcdir)); strcpy(filename + strlen(srcdir), "/MdsTdiTest.tdi"); @@ -163,11 +184,14 @@ int main(int argc, char *argv[]) { TEST_TIMEOUT(100); - if (stksize < 0x40000) { + if (stksize < 0x40000) + { std::cout << " -- [MultiThread] -- Skipped because the default thread " "stack size is too small (" << stksize / 1024 << "kB < 256kB)." << std::flush; - } else { + } + else + { BEGIN_TESTING(MultiThread); MultiThreadTest(); END_TESTING; diff --git a/mdsobjects/cpp/testing/MdsTreeNodeTest.cpp b/mdsobjects/cpp/testing/MdsTreeNodeTest.cpp index cd942720a1..92717ac9a1 100644 --- a/mdsobjects/cpp/testing/MdsTreeNodeTest.cpp +++ b/mdsobjects/cpp/testing/MdsTreeNodeTest.cpp @@ -35,64 +35,72 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace MDSplus; using namespace testing; -namespace testing { -class TestTreeNodePotected : public MDSplus::TreeNode { -public: - TestTreeNodePotected(TreeNode *node) - : TreeNode(node->getNid(), node->getTree()) {} - - using TreeNode::getFlag; - using TreeNode::isImmutable; - using TreeNode::setFlag; -}; +namespace testing +{ + class TestTreeNodePotected : public MDSplus::TreeNode + { + public: + TestTreeNodePotected(TreeNode *node) + : TreeNode(node->getNid(), node->getTree()) {} + + using TreeNode::getFlag; + using TreeNode::isImmutable; + using TreeNode::setFlag; + }; } // namespace testing -namespace testing { -class TestNode { -public: - TreeNode *node; - - TestNode(TreeNode *node) : node(node) {} - - friend std::ostream &operator<<(std::ostream &o, const TestNode &n) { - o << " -- test node -- \n" - << "name: " << n.node->getNodeNameStr() << "\n" - << "usage: " << n.node->getUsage() << "\n" - << "parent: " - << unique_ptr(n.node->getParent())->getNodeNameStr() << "\n" - << "tree: " << n.node->getTree()->getName() << "\n"; - return o; - } +namespace testing +{ + class TestNode + { + public: + TreeNode *node; + + TestNode(TreeNode *node) : node(node) {} + + friend std::ostream &operator<<(std::ostream &o, const TestNode &n) + { + o << " -- test node -- \n" + << "name: " << n.node->getNodeNameStr() << "\n" + << "usage: " << n.node->getUsage() << "\n" + << "parent: " + << unique_ptr(n.node->getParent())->getNodeNameStr() << "\n" + << "tree: " << n.node->getTree()->getName() << "\n"; + return o; + } - bool operator==(const TestNode &other) { - return this->node->getNid() == other.node->getNid(); - } + bool operator==(const TestNode &other) + { + return this->node->getNid() == other.node->getNid(); + } - void operator()(std::string name, std::string usage, std::string parent, - std::string tree) { - TEST1(node->getNodeNameStr() == toupper(name)); - TEST1(std::string(node->getUsage()) == toupper(usage)); - TEST1(unique_ptr(node->getParent())->getNodeNameStr() == - toupper(parent)); - TEST1(node->getTree()->getName() == tree); + void operator()(std::string name, std::string usage, std::string parent, + std::string tree) + { + TEST1(node->getNodeNameStr() == toupper(name)); + TEST1(std::string(node->getUsage()) == toupper(usage)); + TEST1(unique_ptr(node->getParent())->getNodeNameStr() == + toupper(parent)); + TEST1(node->getTree()->getName() == tree); + } + }; + + void print_segment_info(TreeNode *node, int segment = -1) + { + char dtype, dimct; + int dims[8], next; + std::cout << "info> " << node->getPathStr() << " "; + node->getSegmentInfo(segment, &dtype, &dimct, dims, &next); + std::cout << "dtype: " << (int)dtype << " "; + std::cout << "dims:" + << AutoString( + unique_ptr(new Int32Array(dims, dimct))->decompile()) + .string; + if (next == dims[dimct - 1]) + std::cout << " fullfilled\n"; + else + std::cout << " next empty element: " << next << "\n"; } -}; - -void print_segment_info(TreeNode *node, int segment = -1) { - char dtype, dimct; - int dims[8], next; - std::cout << "info> " << node->getPathStr() << " "; - node->getSegmentInfo(segment, &dtype, &dimct, dims, &next); - std::cout << "dtype: " << (int)dtype << " "; - std::cout << "dims:" - << AutoString( - unique_ptr(new Int32Array(dims, dimct))->decompile()) - .string; - if (next == dims[dimct - 1]) - std::cout << " fullfilled\n"; - else - std::cout << " next empty element: " << next << "\n"; -} } // namespace testing #ifdef _WIN32 @@ -100,7 +108,8 @@ void print_segment_info(TreeNode *node, int segment = -1) { #define setenv(name, val, extra) _putenv_s(name, val) #endif -void main_test() { +void main_test() +{ TEST_TIMEOUT(100); BEGIN_TESTING(TreeNode); @@ -368,7 +377,8 @@ void main_test() { TEST1(children[0]->getNodeNameStr() == "BROTHER"); TEST1(children[1]->getNodeNameStr() == "BROTHER2"); TEST1(children[2]->getNodeNameStr() == "CHILD"); - for (int i = 0; i < num_children; ++i) { + for (int i = 0; i < num_children; ++i) + { deleteData(children[i]); } delete[] children; @@ -381,7 +391,8 @@ void main_test() { // nodes are alphabetically ordered // TEST1(members[0]->getNodeNameStr() == "MEM1"); TEST1(members[1]->getNodeNameStr() == "MEM2"); - for (int i = 0; i < num_members; ++i) { + for (int i = 0; i < num_members; ++i) + { deleteData(members[i]); } delete[] members; @@ -392,7 +403,8 @@ void main_test() { TEST1(num_desc == 5); parmem1->putData(unique_ptr(new Int32(5552368))); parmem2->putData(unique_ptr(new String("lorem ipsum"))); - for (int i = 0; i < num_desc; ++i) { + for (int i = 0; i < num_desc; ++i) + { deleteData(desc[i]); } delete[] desc; @@ -652,7 +664,8 @@ void main_test() { ts_node->beginTimestampedSegment(array_data); TEST1(ts_node->getNumSegments() == 1); int64_t times[10]; - for (int i = 0; i < 10; ++i) { + for (int i = 0; i < 10; ++i) + { times[i] = (int64_t)array[i]; } @@ -891,16 +904,20 @@ void main_test() { } int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { - std::cout << "START NORMAL TEST\n" << std::flush; + char *argv[] __attribute__((unused))) +{ + std::cout << "START NORMAL TEST\n" + << std::flush; setenv("t_treenode_path", ".", 1); setenv("t_treenode2_path", ".", 1); main_test(); - std::cout << "START THREAD TEST\n" << std::flush; + std::cout << "START THREAD TEST\n" + << std::flush; setenv("t_treenode_path", "thread://1::.", 1); setenv("t_treenode2_path", "thread://2::.", 1); main_test(); - std::cout << "START LOCAL TEST\n" << std::flush; + std::cout << "START LOCAL TEST\n" + << std::flush; setenv("t_treenode_path", "local://1::.", 1); setenv("t_treenode2_path", "local://2::.", 1); main_test(); diff --git a/mdsobjects/cpp/testing/MdsTreeSegments.cpp b/mdsobjects/cpp/testing/MdsTreeSegments.cpp index 2e4709bc2a..3217d9d950 100644 --- a/mdsobjects/cpp/testing/MdsTreeSegments.cpp +++ b/mdsobjects/cpp/testing/MdsTreeSegments.cpp @@ -39,26 +39,32 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace testing; using namespace MDSplus; -#define TEST_SEGMENT_FLOAT(node, seg, test) \ - do { \ - unique_ptr signal = node->getSegment(seg); \ - int length = 0; \ - float *array = signal->getFloatArray(&length); \ - try { \ - for (int i = 0; i < length; i++) \ - if (!(test)) \ - TEST1(test); \ - } catch (MDSplus::MdsException) { \ - delete[] array; \ - throw; \ - } \ - delete[] array; \ +#define TEST_SEGMENT_FLOAT(node, seg, test) \ + do \ + { \ + unique_ptr signal = node->getSegment(seg); \ + int length = 0; \ + float *array = signal->getFloatArray(&length); \ + try \ + { \ + for (int i = 0; i < length; i++) \ + if (!(test)) \ + TEST1(test); \ + } \ + catch (MDSplus::MdsException) \ + { \ + delete[] array; \ + throw; \ + } \ + delete[] array; \ } while (0); -void putSegment() { +void putSegment() +{ float times[1000]; float data[1000]; - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < 1000; i++) + { times[i] = i * 100; data[i] = i * 10; } @@ -77,7 +83,8 @@ void putSegment() { } TEST_SEGMENT_FLOAT(n[0], 0, array[i] == 0.); TEST_SEGMENT_FLOAT(n[1], 0, array[i] == 0.); - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { unique_ptr chunk = new MDSplus::Float32Array(&data[i * 100], 100); n[0]->putSegment(chunk, -1); @@ -88,7 +95,8 @@ void putSegment() { } } -void BlockAndRows() { +void BlockAndRows() +{ unique_ptr t = new MDSplus::Tree("t_treeseg", 1, "NEW"); unique_ptr n = t->addNode("BAR", "SIGNAL"); t->write(); @@ -138,7 +146,8 @@ void BlockAndRows() { #define NUM_SEGMENTS 10 #define SEG_SAMPLES 1000000 -void makeSegment() { +void makeSegment() +{ MDSplus::Tree *t = new MDSplus::Tree("t_treeseg", -1, "NEW"); MDSplus::TreeNode *na = t->addNode("SEG", "SIGNAL"); @@ -177,7 +186,8 @@ void makeSegment() { MDSplus::TreeNode *mmnRes = t->getNode("MMSEG_RES"); MDSplus::TreeNode *mmpn = t->getNode("MMPSEG"); MDSplus::TreeNode *mmpnRes = t->getNode("MMPSEG_RES"); - for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) { + for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) + { float *segData = new float[SEG_SAMPLES]; for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = i; @@ -196,7 +206,8 @@ void makeSegment() { deleteData(data); delete[] segData; } - for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) { + for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) + { float *segData = new float[SEG_SAMPLES]; for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = 0; @@ -210,7 +221,8 @@ void makeSegment() { pn1->beginSegment(start, end, dim, data); for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = i; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { MDSplus::Float32Array *putData = new MDSplus::Float32Array( &segData[i * SEG_SAMPLES / 10], SEG_SAMPLES / 10); pn1->putSegment(putData, -1); @@ -224,7 +236,8 @@ void makeSegment() { deleteData(data); delete[] segData; } - for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) { + for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) + { float *segData = new float[SEG_SAMPLES]; for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = i; @@ -242,7 +255,8 @@ void makeSegment() { deleteData(data); delete[] segData; } - for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) { + for (int segIdx = 0; segIdx < NUM_SEGMENTS; segIdx++) + { float *segData = new float[SEG_SAMPLES]; for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = 0; @@ -255,7 +269,8 @@ void makeSegment() { mmpn->beginSegmentMinMax(start, end, dim, data, mmpnRes, 1000); for (int i = 0; i < SEG_SAMPLES; i++) segData[i] = i; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { MDSplus::Float32Array *putData = new MDSplus::Float32Array( &segData[i * SEG_SAMPLES / 10], SEG_SAMPLES / 10); mmpn->putSegmentMinMax(putData, -1, mmpnRes, 1000); @@ -324,14 +339,16 @@ void makeSegment() { delete t; } -#define TEST(prcedure) \ - do { \ - BEGIN_TESTING(prcedure); \ - prcedure(); \ - END_TESTING; \ +#define TEST(prcedure) \ + do \ + { \ + BEGIN_TESTING(prcedure); \ + prcedure(); \ + END_TESTING; \ } while (0) int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ setenv("t_treeseg_path", ".", 1); TEST(putSegment); TEST(BlockAndRows); diff --git a/mdsobjects/cpp/testing/MdsTreeSuppression.cpp b/mdsobjects/cpp/testing/MdsTreeSuppression.cpp index 7d9f02690a..9cbce9b277 100644 --- a/mdsobjects/cpp/testing/MdsTreeSuppression.cpp +++ b/mdsobjects/cpp/testing/MdsTreeSuppression.cpp @@ -45,7 +45,8 @@ using namespace testing; // this seems to catch a leak in treeshr int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(MDSTreeSuppression); #ifdef _WIN32 #define setenv(name, val, extra) _putenv_s(name, val) diff --git a/mdsobjects/cpp/testing/MdsTreeTest.cpp b/mdsobjects/cpp/testing/MdsTreeTest.cpp index 625a9016d5..a61b3e917f 100644 --- a/mdsobjects/cpp/testing/MdsTreeTest.cpp +++ b/mdsobjects/cpp/testing/MdsTreeTest.cpp @@ -107,7 +107,8 @@ using namespace testing; //#define TreeUSAGE_SUBTREE_TOP 15 /* Runtime only special usage */ int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ TEST_TIMEOUT(100); BEGIN_TESTING(Tree); diff --git a/mdsobjects/cpp/testing/MdsWindowTest.cpp b/mdsobjects/cpp/testing/MdsWindowTest.cpp index e0a32124de..c4ed3aedad 100644 --- a/mdsobjects/cpp/testing/MdsWindowTest.cpp +++ b/mdsobjects/cpp/testing/MdsWindowTest.cpp @@ -52,7 +52,8 @@ using namespace testing; //}; -int main() { +int main() +{ BEGIN_TESTING(Window); { // CTR diff --git a/mdsobjects/cpp/testing/buildtest.cpp b/mdsobjects/cpp/testing/buildtest.cpp index 95511f8f86..6822f35293 100644 --- a/mdsobjects/cpp/testing/buildtest.cpp +++ b/mdsobjects/cpp/testing/buildtest.cpp @@ -30,7 +30,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(build); TEST1(1); diff --git a/mdsobjects/cpp/testing/testutils/CommaInit.h b/mdsobjects/cpp/testing/testutils/CommaInit.h index a714e0731b..8976ac214d 100644 --- a/mdsobjects/cpp/testing/testutils/CommaInit.h +++ b/mdsobjects/cpp/testing/testutils/CommaInit.h @@ -10,30 +10,35 @@ // Comma Initializer template ... // ContentT should provide operator[] and resize() methods. -namespace testing { - -template struct CommaInitializer { - typedef ContentT &(ContainerT::*OpType)(const size_t); - - inline explicit CommaInitializer(ContainerT *container, ContentT s, - OpType op = &ContainerT::operator()) - : container(container), operation(op) { - this->index = 0; - container->resize(1); - (container->*operation)(0) = s; - } - - inline CommaInitializer &operator,(ContentT s) { - this->index++; - container->resize(index + 1); - (container->*operation)(this->index) = s; - return *this; - } - - ContainerT *container; - OpType operation; - unsigned int index; -}; +namespace testing +{ + + template + struct CommaInitializer + { + typedef ContentT &(ContainerT::*OpType)(const size_t); + + inline explicit CommaInitializer(ContainerT *container, ContentT s, + OpType op = &ContainerT::operator()) + : container(container), operation(op) + { + this->index = 0; + container->resize(1); + (container->*operation)(0) = s; + } + + inline CommaInitializer &operator,(ContentT s) + { + this->index++; + container->resize(index + 1); + (container->*operation)(this->index) = s; + return *this; + } + + ContainerT *container; + OpType operation; + unsigned int index; + }; } // namespace testing @@ -41,13 +46,15 @@ template struct CommaInitializer { // COMMA INIT FOR STD CONTAINERS ///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace std { -template -inline testing::CommaInitializer, _T> -operator<<(std::vector<_T> &cnt, _T scalar) { - return testing::CommaInitializer, _T>( - &cnt, scalar, &std::vector<_T>::operator[]); -} +namespace std +{ + template + inline testing::CommaInitializer, _T> + operator<<(std::vector<_T> &cnt, _T scalar) + { + return testing::CommaInitializer, _T>( + &cnt, scalar, &std::vector<_T>::operator[]); + } } // namespace std #endif // COMMAINIT_H diff --git a/mdsobjects/cpp/testing/testutils/FunctionTypes.h b/mdsobjects/cpp/testing/testutils/FunctionTypes.h index aa9766bac9..a9849d0c7a 100644 --- a/mdsobjects/cpp/testing/testutils/FunctionTypes.h +++ b/mdsobjects/cpp/testing/testutils/FunctionTypes.h @@ -1,47 +1,58 @@ #ifndef MDSTESTUTILS_FUNCTIONTYPES_H #define MDSTESTUTILS_FUNCTIONTYPES_H -namespace testing { - -namespace detail { - -//////////////////////////////////////////////////////////////////////////////// -// type synthesize ( please read: boost implementation ) // -//////////////////////////////////////////////////////////////////////////////// - -template struct FunctionTypes {}; - -template struct FunctionTypes { - typedef R ref(); - typedef R(ptr)(); - typedef O obj; - typedef R ReturnType; -}; - -template struct FunctionTypes { - typedef R ref(T0); - typedef R(ptr)(T0); - typedef O obj; - typedef R ReturnType; -}; - -template -struct FunctionTypes { - typedef R ref(T0, T1); - typedef R(ptr)(T0, T1); - typedef O obj; - typedef R ReturnType; -}; - -template -struct FunctionTypes { - typedef R ref(T0, T1, T2); - typedef R(ptr)(T0, T1, T2); - typedef O obj; - typedef R ReturnType; -}; - -} // namespace detail +namespace testing +{ + + namespace detail + { + + //////////////////////////////////////////////////////////////////////////////// + // type synthesize ( please read: boost implementation ) // + //////////////////////////////////////////////////////////////////////////////// + + template + struct FunctionTypes + { + }; + + template + struct FunctionTypes + { + typedef R ref(); + typedef R(ptr)(); + typedef O obj; + typedef R ReturnType; + }; + + template + struct FunctionTypes + { + typedef R ref(T0); + typedef R(ptr)(T0); + typedef O obj; + typedef R ReturnType; + }; + + template + struct FunctionTypes + { + typedef R ref(T0, T1); + typedef R(ptr)(T0, T1); + typedef O obj; + typedef R ReturnType; + }; + + template + struct FunctionTypes + { + typedef R ref(T0, T1, T2); + typedef R(ptr)(T0, T1, T2); + typedef O obj; + typedef R ReturnType; + }; + + } // namespace detail } // namespace testing #endif // FUNCTIONTYPES_H diff --git a/mdsobjects/cpp/testing/testutils/MdsIpInstancer.h b/mdsobjects/cpp/testing/testutils/MdsIpInstancer.h index c9566ef5f1..edbacbfd8d 100644 --- a/mdsobjects/cpp/testing/testutils/MdsIpInstancer.h +++ b/mdsobjects/cpp/testing/testutils/MdsIpInstancer.h @@ -34,39 +34,44 @@ extern char **environ; namespace mds = MDSplus; -namespace testing { -class MdsIpInstancer { - struct HostFile { - HostFile() { - std::string hosts_default = "* | MAP_TO_LOCAL \n" - "* | nobody \n"; +namespace testing +{ + class MdsIpInstancer + { + struct HostFile + { + HostFile() + { + std::string hosts_default = "* | MAP_TO_LOCAL \n" + "* | nobody \n"; - std::ofstream hosts_file; - hosts_file.open("testing.hosts"); - hosts_file << hosts_default << "\n"; - hosts_file.close(); - } - ~HostFile() { remove("testing.hosts"); } - const char *name() const { return "testing.hosts"; } - }; + std::ofstream hosts_file; + hosts_file.open("testing.hosts"); + hosts_file << hosts_default << "\n"; + hosts_file.close(); + } + ~HostFile() { remove("testing.hosts"); } + const char *name() const { return "testing.hosts"; } + }; - Singleton m_host_file; - unsigned short m_port; - std::string m_protocol; + Singleton m_host_file; + unsigned short m_port; + std::string m_protocol; #ifdef _WIN32 - HANDLE m_process; + HANDLE m_process; #else - pid_t m_process; + pid_t m_process; #endif -public: - MdsIpInstancer(const char *protocol, unsigned short port, const char *mode) - : m_port(port), m_protocol(protocol) { - m_process = 0; - if (port == 0) - return; - m_host_file.get_instance(); - // get first available port // - /* + public: + MdsIpInstancer(const char *protocol, unsigned short port, const char *mode) + : m_port(port), m_protocol(protocol) + { + m_process = 0; + if (port == 0) + return; + m_host_file.get_instance(); + // get first available port // + /* int offset = 0; while(!available(m_port,m_protocol) && offset<100 ) m_port += offset++; @@ -74,172 +79,199 @@ class MdsIpInstancer { throw std::out_of_range("any port found within 100 tries"); */ #ifdef _WIN32 - char *hostfile = (char *)m_host_file->name(); - size_t len = strlen(protocol) + strlen(hostfile) + 128; - char *cmd = (char *)malloc(len); - _snprintf_s(cmd, len, len - 1, "mdsip.exe %s -P %s -p %u -h %s", mode, - protocol, port, hostfile); - fprintf(stdout, "spawning \"%s\"\n", cmd); - PROCESS_INFORMATION piProcInfo; - STARTUPINFO siStartInfo; - memset(&siStartInfo, 0, sizeof(siStartInfo)); - siStartInfo.cb = sizeof(siStartInfo); - siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); - siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); - siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - siStartInfo.dwFlags |= STARTF_USESTDHANDLES; - BOOL bSuccess = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, - NULL, NULL, &siStartInfo, &piProcInfo); - free(cmd); - if (bSuccess) { - m_process = piProcInfo.hProcess; - CloseHandle(piProcInfo.hThread); - DWORD pid = piProcInfo.dwProcessId; + char *hostfile = (char *)m_host_file->name(); + size_t len = strlen(protocol) + strlen(hostfile) + 128; + char *cmd = (char *)malloc(len); + _snprintf_s(cmd, len, len - 1, "mdsip.exe %s -P %s -p %u -h %s", mode, + protocol, port, hostfile); + fprintf(stdout, "spawning \"%s\"\n", cmd); + PROCESS_INFORMATION piProcInfo; + STARTUPINFO siStartInfo; + memset(&siStartInfo, 0, sizeof(siStartInfo)); + siStartInfo.cb = sizeof(siStartInfo); + siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); + siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + siStartInfo.dwFlags |= STARTF_USESTDHANDLES; + BOOL bSuccess = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, + NULL, NULL, &siStartInfo, &piProcInfo); + free(cmd); + if (bSuccess) + { + m_process = piProcInfo.hProcess; + CloseHandle(piProcInfo.hThread); + DWORD pid = piProcInfo.dwProcessId; #else - pid_t pid; - char port_str[20]; - sprintf(port_str, "%i", m_port); - char *argv[] = {(char *)"mdsip", - (char *)"-P", - (char *)m_protocol.c_str(), - (char *)"-h", - (char *)m_host_file->name(), - (char *)"-p", - port_str, - (char *)mode, - NULL}; + pid_t pid; + char port_str[20]; + sprintf(port_str, "%i", m_port); + char *argv[] = {(char *)"mdsip", + (char *)"-P", + (char *)m_protocol.c_str(), + (char *)"-h", + (char *)m_host_file->name(), + (char *)"-p", + port_str, + (char *)mode, + NULL}; #ifdef USE_FORK - std::cout << "forking process!\n" << std::flush; - pid = fork(); - if (pid == 0) // child process - // exit(execvpe(argv[0], argv, environ)); - exit(execvp(argv[0], argv) ? errno : 0); - else if (pid > 0) { // spawned ok + std::cout << "forking process!\n" + << std::flush; + pid = fork(); + if (pid == 0) // child process + // exit(execvpe(argv[0], argv, environ)); + exit(execvp(argv[0], argv) ? errno : 0); + else if (pid > 0) + { // spawned ok #else - if (!posix_spawnp(&pid, argv[0], NULL, NULL, argv, environ)) { + if (!posix_spawnp(&pid, argv[0], NULL, NULL, argv, environ)) + { #endif - m_process = pid; + m_process = pid; #endif - std::cout << "started mdsip server for " << m_protocol - << " on port: " << m_port << " pid: " << pid << "\n" - << std::flush; - } else - throw std::runtime_error("Could not start mdsip server"); - } + std::cout << "started mdsip server for " << m_protocol + << " on port: " << m_port << " pid: " << pid << "\n" + << std::flush; + } + else + throw std::runtime_error("Could not start mdsip server"); + } - ~MdsIpInstancer() { - if (m_process) { - std::cout << "removing mdsip for " << m_protocol << ".." << std::flush; + ~MdsIpInstancer() + { + if (m_process) + { + std::cout << "removing mdsip for " << m_protocol << ".." << std::flush; #ifdef _WIN32 - BOOL ok = TerminateProcess(m_process, 0); - CloseHandle(m_process); - if (ok) + BOOL ok = TerminateProcess(m_process, 0); + CloseHandle(m_process); + if (ok) #else - if (!kill(m_process, SIGKILL)) + if (!kill(m_process, SIGKILL)) #endif - std::cout << "success\n" << std::flush; - else - std::cout << "FAILED\n" << std::flush; + std::cout << "success\n" + << std::flush; + else + std::cout << "FAILED\n" + << std::flush; + } } - } - int getPort() const { return m_port; } + int getPort() const { return m_port; } - std::string getAddress() const { - std::stringstream ss; - if (m_port == 0) - ss << m_protocol << "://tunnel"; - else if (m_protocol == "tcp") - ss << "tcp://127.0.0.1:" << m_port; - else if (m_protocol == "udt") - ss << "udt://127.0.0.1:" << m_port; - else if (m_protocol == "tcpv6") - ss << "tcpv6://::1#" << m_port; - else if (m_protocol == "udtv6") - ss << "udtv6://::1#" << m_port; - else if (m_protocol == "gsi") - ss << "gsi://localhost:" << m_port; - else - ss << m_protocol << "://localhost:" << m_port; - return ss.str(); - } + std::string getAddress() const + { + std::stringstream ss; + if (m_port == 0) + ss << m_protocol << "://tunnel"; + else if (m_protocol == "tcp") + ss << "tcp://127.0.0.1:" << m_port; + else if (m_protocol == "udt") + ss << "udt://127.0.0.1:" << m_port; + else if (m_protocol == "tcpv6") + ss << "tcpv6://::1#" << m_port; + else if (m_protocol == "udtv6") + ss << "udtv6://::1#" << m_port; + else if (m_protocol == "gsi") + ss << "gsi://localhost:" << m_port; + else + ss << m_protocol << "://localhost:" << m_port; + return ss.str(); + } - bool waitForServer(int retries = 5, int usec = 500000) const { - if (m_process) { // only parent can wait // - for (int retry = 0; retry < retries; ++retry) { - try { - mds::Connection cnx((char *)this->getAddress().c_str()); - (void)cnx; - return true; - } catch (mds::MdsException &e) { - (void)e; - usleep(usec); + bool waitForServer(int retries = 5, int usec = 500000) const + { + if (m_process) + { // only parent can wait // + for (int retry = 0; retry < retries; ++retry) + { + try + { + mds::Connection cnx((char *)this->getAddress().c_str()); + (void)cnx; + return true; + } + catch (mds::MdsException &e) + { + (void)e; + usleep(usec); + } } } + return false; } - return false; - } -private: - // Allocate a new TCP server socket, and return - // its handler - int allocate(const std::string &protocol) { - SOCKET sock = INVALID_SOCKET; - int addr, data, proto; - if (protocol == "tcpv6" || protocol == "udtv6") - addr = AF_INET6; - else - addr = AF_INET; - if (protocol == "udt" || protocol == "udt6") { - data = SOCK_DGRAM; - proto = IPPROTO_UDP; - } else { - data = SOCK_DGRAM; - proto = IPPROTO_UDP; - } - sock = socket(addr, data, proto); - if (sock == INVALID_SOCKET) { - if (errno == EMFILE) { - /* too many open files */ - return 0; + private: + // Allocate a new TCP server socket, and return + // its handler + int allocate(const std::string &protocol) + { + SOCKET sock = INVALID_SOCKET; + int addr, data, proto; + if (protocol == "tcpv6" || protocol == "udtv6") + addr = AF_INET6; + else + addr = AF_INET; + if (protocol == "udt" || protocol == "udt6") + { + data = SOCK_DGRAM; + proto = IPPROTO_UDP; + } + else + { + data = SOCK_DGRAM; + proto = IPPROTO_UDP; + } + sock = socket(addr, data, proto); + if (sock == INVALID_SOCKET) + { + if (errno == EMFILE) + { + /* too many open files */ + return 0; + } + fprintf(stderr, "error allocating socket '%s': ", protocol.c_str()); + perror(""); + exit(1); } - fprintf(stderr, "error allocating socket '%s': ", protocol.c_str()); - perror(""); - exit(1); + REUSEADDR_TYPE optval = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); + return sock; } - REUSEADDR_TYPE optval = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); - return sock; - } - // Check whether the provided TCP port is available - // at the moment and return 1 if it's avaiable, zero otherwise - int available(int port, const std::string protocol) { - int sock = allocate(protocol); - int error; - if (protocol == "tcpv6" || protocol == "udtv6") { - const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; - struct sockaddr_in6 addr; - memset(&addr, 0, sizeof(addr)); - addr.sin6_family = AF_INET6; - addr.sin6_port = htons(port); - addr.sin6_addr = in6addr_any; - error = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); - } else { - struct sockaddr_in addr; - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - error = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); - } - if (!error) { - shutdown(sock, 2); - close(sock); + // Check whether the provided TCP port is available + // at the moment and return 1 if it's avaiable, zero otherwise + int available(int port, const std::string protocol) + { + int sock = allocate(protocol); + int error; + if (protocol == "tcpv6" || protocol == "udtv6") + { + const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; + struct sockaddr_in6 addr; + memset(&addr, 0, sizeof(addr)); + addr.sin6_family = AF_INET6; + addr.sin6_port = htons(port); + addr.sin6_addr = in6addr_any; + error = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); + } + else + { + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = htonl(INADDR_ANY); + error = bind(sock, (struct sockaddr *)&addr, sizeof(addr)); + } + if (!error) + { + shutdown(sock, 2); + close(sock); + } + return error == 0; } - return error == 0; - } -}; + }; } // namespace testing #endif // MDSIPMAIN_H diff --git a/mdsobjects/cpp/testing/testutils/Singleton.h b/mdsobjects/cpp/testing/testutils/Singleton.h index 66604a1639..15115d823b 100644 --- a/mdsobjects/cpp/testing/testutils/Singleton.h +++ b/mdsobjects/cpp/testing/testutils/Singleton.h @@ -1,36 +1,41 @@ #ifndef MDSTESTUTILS_SINGLETON_H #define MDSTESTUTILS_SINGLETON_H -namespace testing { - -//////////////////////////////////////////////////////////////////////////////// -// Singleton ///////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// -/// Single instance within the same linked module -/// -template class Singleton { -public: - Singleton() {} - Singleton(const T ©) { this->get_instance() = copy; } - - inline T *operator->() { return &get_instance(); } - inline const T *operator->() const { return &get_instance(); } - - static T &get_instance() { - static T instance; - return instance; - } - - static const T &get_const_instance() { - return const_cast(get_instance()); - } - -private: - // Singleton(Singleton const&); // Don't Implement - void operator=(Singleton const &); // Don't implement -}; +namespace testing +{ + + //////////////////////////////////////////////////////////////////////////////// + // Singleton ///////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /// + /// Single instance within the same linked module + /// + template + class Singleton + { + public: + Singleton() {} + Singleton(const T ©) { this->get_instance() = copy; } + + inline T *operator->() { return &get_instance(); } + inline const T *operator->() const { return &get_instance(); } + + static T &get_instance() + { + static T instance; + return instance; + } + + static const T &get_const_instance() + { + return const_cast(get_instance()); + } + + private: + // Singleton(Singleton const&); // Don't Implement + void operator=(Singleton const &); // Don't implement + }; } // namespace testing diff --git a/mdsobjects/cpp/testing/testutils/String.h b/mdsobjects/cpp/testing/testutils/String.h index 2d682bac26..01a0e3bfa6 100644 --- a/mdsobjects/cpp/testing/testutils/String.h +++ b/mdsobjects/cpp/testing/testutils/String.h @@ -4,11 +4,13 @@ #include #include -namespace testing { -std::string toupper(std::string str) { - std::transform(str.begin(), str.end(), str.begin(), ::toupper); - return str; -} +namespace testing +{ + std::string toupper(std::string str) + { + std::transform(str.begin(), str.end(), str.begin(), ::toupper); + return str; + } } // namespace testing diff --git a/mdsobjects/cpp/testing/testutils/Threads.h b/mdsobjects/cpp/testing/testutils/Threads.h index 0f0e7f488c..80e63ece0f 100644 --- a/mdsobjects/cpp/testing/testutils/Threads.h +++ b/mdsobjects/cpp/testing/testutils/Threads.h @@ -7,31 +7,35 @@ // THREAD BASE //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace testing { -class Thread { -public: - Thread() {} - virtual ~Thread() {} - - bool StartThread() { - return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0); - } - - void StopThread() { pthread_cancel(_thread); } - - void WaitForThreadToExit() { (void)pthread_join(_thread, NULL); } - -protected: - virtual void InternalThreadEntry() = 0; - -private: - static void *InternalThreadEntryFunc(void *This) { - ((Thread *)This)->InternalThreadEntry(); - return NULL; - } - - pthread_t _thread; -}; +namespace testing +{ + class Thread + { + public: + Thread() {} + virtual ~Thread() {} + + bool StartThread() + { + return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0); + } + + void StopThread() { pthread_cancel(_thread); } + + void WaitForThreadToExit() { (void)pthread_join(_thread, NULL); } + + protected: + virtual void InternalThreadEntry() = 0; + + private: + static void *InternalThreadEntryFunc(void *This) + { + ((Thread *)This)->InternalThreadEntry(); + return NULL; + } + + pthread_t _thread; + }; } // namespace testing #endif // THREADS_H diff --git a/mdsobjects/cpp/testing/testutils/mdsipmain.c b/mdsobjects/cpp/testing/testutils/mdsipmain.c index 83f275a661..3b55579c22 100644 --- a/mdsobjects/cpp/testing/testutils/mdsipmain.c +++ b/mdsobjects/cpp/testing/testutils/mdsipmain.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // here to provide the main anchor to tests programs that want to launch a // server instance. (obviously MdsIpShr.so must be linked too..) -int mdsip_main(int argc, char **argv) { +int mdsip_main(int argc, char **argv) +{ IoRoutines *io; int extra_argc; char **extra_argv; @@ -41,7 +42,8 @@ int mdsip_main(int argc, char **argv) { io = LoadIo(GetProtocol()); if (io && io->listen) io->listen(extra_argc, extra_argv); - else { + else + { fprintf(stderr, "Protocol %s does not support servers\n", GetProtocol()); return 1; } diff --git a/mdsobjects/cpp/testing/testutils/testutils.cpp b/mdsobjects/cpp/testing/testutils/testutils.cpp index 66c6bf0aab..32b59f429f 100644 --- a/mdsobjects/cpp/testing/testutils/testutils.cpp +++ b/mdsobjects/cpp/testing/testutils/testutils.cpp @@ -32,10 +32,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Dummy Test Funtions /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -extern "C" { +extern "C" +{ -EXPORT int get_ghostbusters_phone() { return 5552368; } + EXPORT int get_ghostbusters_phone() { return 5552368; } -EXPORT int test_nextint(int *x) { return ++(*x); } -EXPORT int test_addint(int *a, int *b) { return (*a) + (*b); } + EXPORT int test_nextint(int *x) { return ++(*x); } + EXPORT int test_addint(int *a, int *b) { return (*a) + (*b); } } diff --git a/mdsobjects/cpp/testing/testutils/testutils.h b/mdsobjects/cpp/testing/testutils/testutils.h index 5cdd917122..1f221cf2a9 100644 --- a/mdsobjects/cpp/testing/testutils/testutils.h +++ b/mdsobjects/cpp/testing/testutils/testutils.h @@ -6,11 +6,14 @@ #include #include -namespace testing { +namespace testing +{ -template bool areSame(T a, T b) { - return std::fabs(a - b) < std::numeric_limits::epsilon(); -} + template + bool areSame(T a, T b) + { + return std::fabs(a - b) < std::numeric_limits::epsilon(); + } } // namespace testing diff --git a/mdsobjects/cpp/testing/testutils/type_traits.h b/mdsobjects/cpp/testing/testutils/type_traits.h index bce0d34b5a..4a63d62f61 100644 --- a/mdsobjects/cpp/testing/testutils/type_traits.h +++ b/mdsobjects/cpp/testing/testutils/type_traits.h @@ -1,64 +1,87 @@ #ifndef MDSTESTUTILS_TYPE_TRAITS_H #define MDSTESTUTILS_TYPE_TRAITS_H -namespace testing { - -//////////////////////////////////////////////////////////////////////////////// -// REMOVE PTR /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace detail { - -template struct remove_pointer { typedef T type; }; - -#define _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(param, trait, spec, result) \ - template struct trait { typedef result type; }; - -_MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *, T) -_MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *const, T) -_MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *volatile, - T) -_MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, - T *const volatile, T) +namespace testing +{ + + //////////////////////////////////////////////////////////////////////////////// + // REMOVE PTR /////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + namespace detail + { + + template + struct remove_pointer + { + typedef T type; + }; + +#define _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(param, trait, spec, result) \ + template \ + struct trait \ + { \ + typedef result type; \ + }; + + _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *, T) + _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *const, T) + _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, T *volatile, + T) + _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1(typename T, remove_pointer, + T *const volatile, T) #undef _MDS_TESTING_TYPE_TRAIT_IMPL_PARTIAL1 -} // namespace detail - -//////////////////////////////////////////////////////////////////////////////// -// MDS to CPP TYPE TRAIT MAP ///////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace detail { - -#define _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(trait, spec, result) \ - template <> struct trait { typedef result type; }; \ - template <> struct trait { typedef std::vector type; }; \ + } // namespace detail + + //////////////////////////////////////////////////////////////////////////////// + // MDS to CPP TYPE TRAIT MAP ///////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + namespace detail + { + +#define _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(trait, spec, result) \ + template <> \ + struct trait \ + { \ + typedef result type; \ + }; \ + template <> \ + struct trait \ + { \ + typedef std::vector type; \ + }; \ /**/ -template struct mds2cpp_typemap { typedef T type; }; + template + struct mds2cpp_typemap + { + typedef T type; + }; -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int8, char) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int16, short) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int32, int) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int64, int64_t) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int8, char) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int16, short) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int32, int) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Int64, int64_t) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint8, unsigned char) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint16, - unsigned short) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint32, unsigned int) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint64, uint64_t) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint8, unsigned char) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint16, + unsigned short) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint32, unsigned int) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Uint64, uint64_t) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Float32, float) -_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Float64, double) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Float32, float) + _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Float64, double) -//_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Complex32, -//std::complex) _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, -//MDSplus::Complex64, std::complex) + //_MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, MDSplus::Complex32, + //std::complex) _MDS_TESTING_TYPE_TRAIT_IMPL_SP1(mds2cpp_typemap, + //MDSplus::Complex64, std::complex) #undef _MDS_TESTING_TYPE_TRAIT_IMPL_SP1 -} // namespace detail + } // namespace detail } // namespace testing #endif // TYPE_TRAITS_H diff --git a/mdsobjects/cpp/testing/testutils/unique_ptr.h b/mdsobjects/cpp/testing/testutils/unique_ptr.h index 1f98058354..9fac322ced 100644 --- a/mdsobjects/cpp/testing/testutils/unique_ptr.h +++ b/mdsobjects/cpp/testing/testutils/unique_ptr.h @@ -3,68 +3,77 @@ #include -namespace testing { +namespace testing +{ -//////////////////////////////////////////////////////////////////////////////// -// Unique Ptr //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + // Unique Ptr //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// -template class Deleter { -public: - static void _delete(MDSplus::Data *ptr) { MDSplus::deleteData(ptr); } + template + class Deleter + { + public: + static void _delete(MDSplus::Data *ptr) { MDSplus::deleteData(ptr); } - static void _delete(void *ptr) { delete (T *)(ptr); } -}; + static void _delete(void *ptr) { delete (T *)(ptr); } + }; -template > class unique_ptr { - unique_ptr(const T &ref) : ptr(new T(ref)) {} - T *ptr; + template > + class unique_ptr + { + unique_ptr(const T &ref) : ptr(new T(ref)) {} + T *ptr; -public: - unique_ptr() : ptr(NULL) {} + public: + unique_ptr() : ptr(NULL) {} - unique_ptr(unique_ptr &other) : ptr(other.ptr) { other.ptr = NULL; } + unique_ptr(unique_ptr &other) : ptr(other.ptr) { other.ptr = NULL; } - unique_ptr(const unique_ptr &other) : ptr(other.ptr) { - const_cast(other).ptr = NULL; - } + unique_ptr(const unique_ptr &other) : ptr(other.ptr) + { + const_cast(other).ptr = NULL; + } - unique_ptr(T *ref) : ptr(ref) {} + unique_ptr(T *ref) : ptr(ref) {} - ~unique_ptr() { _delete(); } + ~unique_ptr() { _delete(); } - unique_ptr &operator=(T *ref) { - _delete(); - ptr = ref; - return *this; - } + unique_ptr &operator=(T *ref) + { + _delete(); + ptr = ref; + return *this; + } - unique_ptr &operator=(unique_ptr other) { - ptr = other.ptr; - other.ptr = NULL; - return *this; - } + unique_ptr &operator=(unique_ptr other) + { + ptr = other.ptr; + other.ptr = NULL; + return *this; + } - void _delete() { - if (ptr) - D::_delete(ptr); - ptr = NULL; - } + void _delete() + { + if (ptr) + D::_delete(ptr); + ptr = NULL; + } - operator bool() { return ptr; } + operator bool() { return ptr; } - operator T *() { return ptr; } - operator const T *() const { return ptr; } + operator T *() { return ptr; } + operator const T *() const { return ptr; } - // operator T *&() { return ptr; } - // operator const T *&() const { return ptr; } + // operator T *&() { return ptr; } + // operator const T *&() const { return ptr; } - T *operator->() { return ptr; } - const T *operator->() const { return ptr; } + T *operator->() { return ptr; } + const T *operator->() const { return ptr; } - T *&base() { return ptr; } - const T *&base() const { return ptr; } -}; + T *&base() { return ptr; } + const T *&base() const { return ptr; } + }; } // namespace testing diff --git a/mdsobjects/cpp/testing/testutils/vector_test.h b/mdsobjects/cpp/testing/testutils/vector_test.h index 05f26b9386..a71bf5fa10 100644 --- a/mdsobjects/cpp/testing/testutils/vector_test.h +++ b/mdsobjects/cpp/testing/testutils/vector_test.h @@ -7,42 +7,48 @@ // Vector Utils /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -namespace std { -template -inline ostream &operator<<(ostream &o, const vector &v) { - typedef typename vector::const_iterator iterator; - for (iterator it = v.begin(); it < v.end(); ++it) { - o << *it << " "; +namespace std +{ + template + inline ostream &operator<<(ostream &o, const vector &v) + { + typedef typename vector::const_iterator iterator; + for (iterator it = v.begin(); it < v.end(); ++it) + { + o << *it << " "; + } + return o; } - return o; -} -template inline istream &operator>>(istream &is, vector &v) { - T value; - v.clear(); - while (!(is >> value).fail()) - v.push_back(value); - return is; -} + template + inline istream &operator>>(istream &is, vector &v) + { + T value; + v.clear(); + while (!(is >> value).fail()) + v.push_back(value); + return is; + } -// std implementation only for the same type // -// template -// inline bool -// operator==(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) -// { return (__x.size() == __y.size() -// && std::equal(__x.begin(), __x.end(), __y.begin())); } + // std implementation only for the same type // + // template + // inline bool + // operator==(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) + // { return (__x.size() == __y.size() + // && std::equal(__x.begin(), __x.end(), __y.begin())); } -// std implementation for different types // -template -inline bool operator==(const std::vector<_T1, _Alloc1> &v1, - const std::vector<_T2, _Alloc2> &v2) { - if (v1.size() != v2.size()) - return false; - for (size_t i = 0; i < v1.size(); ++i) - if (!(v1[i] == static_cast<_T1>(v2[i]))) + // std implementation for different types // + template + inline bool operator==(const std::vector<_T1, _Alloc1> &v1, + const std::vector<_T2, _Alloc2> &v2) + { + if (v1.size() != v2.size()) return false; - return true; -} + for (size_t i = 0; i < v1.size(); ++i) + if (!(v1[i] == static_cast<_T1>(v2[i]))) + return false; + return true; + } } // namespace std #endif // VECTOR_TEST_H diff --git a/mdsobjects/labview/lv.c b/mdsobjects/labview/lv.c index 249896ee0e..49bd4cdb4d 100644 --- a/mdsobjects/labview/lv.c +++ b/mdsobjects/labview/lv.c @@ -45,14 +45,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma pack(1) -EXPORT extern void MoveBlock(const void *src, void *dest, size_t siz) { +EXPORT extern void MoveBlock(const void *src, void *dest, size_t siz) +{ void (*LVMoveBlock)() = NULL; LibFindImageSymbol_C("LVRT_10", "MoveBlock", &LVMoveBlock); if (LVMoveBlock) LVMoveBlock(src, dest, siz); } -EXPORT extern UHandle DSNewHandle(size_t siz) { +EXPORT extern UHandle DSNewHandle(size_t siz) +{ static UHandle (*LVDSNewHandle)() = NULL; LibFindImageSymbol_C("LVMemoryManager_10", "DSNewHandle", &LVDSNewHandle); if (LVDSNewHandle) @@ -60,7 +62,8 @@ EXPORT extern UHandle DSNewHandle(size_t siz) { return (UHandle)-1; } -EXPORT MgErr NumericArrayResize(int32 a, int32 b, UHandle *h, size_t siz) { +EXPORT MgErr NumericArrayResize(int32 a, int32 b, UHandle *h, size_t siz) +{ static MgErr (*LVNumericArrayResize)() = NULL; LibFindImageSymbol_C("LVRT_10", "NumericArrayResize", &LVNumericArrayResize); if (LVNumericArrayResize) @@ -68,6 +71,7 @@ EXPORT MgErr NumericArrayResize(int32 a, int32 b, UHandle *h, size_t siz) { return -1; } -EXPORT MgErr NumericArrayResizeCACCA(int32 a, int32 b, UHandle *h, size_t siz) { +EXPORT MgErr NumericArrayResizeCACCA(int32 a, int32 b, UHandle *h, size_t siz) +{ return NumericArrayResize(a, b, h, siz); } diff --git a/mdsobjects/labview/mdsdataobjectswrp.cpp b/mdsobjects/labview/mdsdataobjectswrp.cpp index 078e208292..e681e60f45 100644 --- a/mdsobjects/labview/mdsdataobjectswrp.cpp +++ b/mdsobjects/labview/mdsdataobjectswrp.cpp @@ -27,8 +27,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include void fillErrorCluster(MgErr code, const char *source, const char *message, - ErrorCluster *error) { - if (code) { + ErrorCluster *error) +{ + if (code) + { std::string errMsg(source); errMsg += ".."; errMsg += message; @@ -40,7 +42,8 @@ void fillErrorCluster(MgErr code, const char *source, const char *message, error->code = static_cast(code); if (NumericArrayResize((int32)uB, (int32)1, reinterpret_cast(&(error->source)), - errMsgLen + sizeof(int32)) == noErr) { + errMsgLen + sizeof(int32)) == noErr) + { MoveBlock(errMsg.c_str(), LStrBuf(*error->source), errMsgLen); (*error->source)->cnt = errMsgLen; } @@ -84,6623 +87,6681 @@ typedef struct { } ErrorCluster; */ -namespace MDSplus { +namespace MDSplus +{ + + template + static void safeCall(char const *src, ErrorCluster *error, T f) + { + MgErr errorCode = noErr; + char const *errorMessage = (char *)""; -template -static void safeCall(char const *src, ErrorCluster *error, T f) { - MgErr errorCode = noErr; - char const *errorMessage = (char *)""; + try + { + f(); + fillErrorCluster(errorCode, src, errorMessage, error); + } + catch (MdsException const &e) + { + errorCode = bogusError; + errorMessage = e.what(); + fillErrorCluster(errorCode, src, errorMessage, error); + } - try { - f(); - fillErrorCluster(errorCode, src, errorMessage, error); - } catch (MdsException const &e) { - errorCode = bogusError; - errorMessage = e.what(); - fillErrorCluster(errorCode, src, errorMessage, error); + // fillErrorCluster(errorCode, src, errorMessage, error); errorMessage + //reters to an exception out of scope??? } - // fillErrorCluster(errorCode, src, errorMessage, error); errorMessage - //reters to an exception out of scope??? -} + struct Lambda + { + virtual void operator()() = 0; + virtual ~Lambda() {} + }; -struct Lambda { - virtual void operator()() = 0; - virtual ~Lambda() {} -}; + static void deleteLvData(void **data) + { + deleteData(reinterpret_cast(*data)); + } -static void deleteLvData(void **data) { - deleteData(reinterpret_cast(*data)); -} + template + struct Constructor : public Lambda + { + Constructor(void **ptr) : ptr(*ptr) {} + void *&ptr; + void operator()() { ptr = reinterpret_cast(new T()); } + }; -template struct Constructor : public Lambda { - Constructor(void **ptr) : ptr(*ptr) {} - void *&ptr; - void operator()() { ptr = reinterpret_cast(new T()); } -}; - -template -struct ScalarConstructor : public Constructor { - ScalarConstructor(void **ptr, V value) : Constructor(ptr), value(value) {} - V value; - void operator()() { ptr = reinterpret_cast(new T(value)); } -}; - -template -static void scalarConstructor(char const *src, ErrorCluster *error, void **ptr, - V value) { - safeCall(src, error, ScalarConstructor(ptr, value)); -} + template + struct ScalarConstructor : public Constructor + { + ScalarConstructor(void **ptr, V value) : Constructor(ptr), value(value) {} + V value; + void operator()() { ptr = reinterpret_cast(new T(value)); } + }; -template -struct ArrayConstructor : public Constructor { - ArrayConstructor(void **ptr, V inPtr, const LIntArrHdl dims) - : Constructor(ptr), inPtr(inPtr), dims(dims) {} - V inPtr; - const LIntArrHdl dims; - void operator()() { - // WRONG. Make LabVIEW crash!!!! ptr = reinterpret_cast(new - // T((*inPtr)->elt, (*dims)->dimSize), (*dims)->elt); - ptr = - reinterpret_cast(new T((*inPtr)->elt, (*dims)->dimSize, - reinterpret_cast((*dims)->elt))); + template + static void scalarConstructor(char const *src, ErrorCluster *error, void **ptr, + V value) + { + safeCall(src, error, ScalarConstructor(ptr, value)); } -}; -template -static void arrayConstructor(char const *src, ErrorCluster *error, void **ptr, - V inPtr, const LIntArrHdl dims) { - safeCall(src, error, ArrayConstructor(ptr, inPtr, dims)); -} + template + struct ArrayConstructor : public Constructor + { + ArrayConstructor(void **ptr, V inPtr, const LIntArrHdl dims) + : Constructor(ptr), inPtr(inPtr), dims(dims) {} + V inPtr; + const LIntArrHdl dims; + void operator()() + { + // WRONG. Make LabVIEW crash!!!! ptr = reinterpret_cast(new + // T((*inPtr)->elt, (*dims)->dimSize), (*dims)->elt); + ptr = + reinterpret_cast(new T((*inPtr)->elt, (*dims)->dimSize, + reinterpret_cast((*dims)->elt))); + } + }; -template -static void arrayConstructor(char const *src, ErrorCluster *error, void **ptr, - V inPtr) { - LIntArr dims; - dims.dimSize = 1; - // WRONG. make labVIEW crash!!! dims.elt[1] = (*inPtr)->dimSize; - dims.elt[0] = (*inPtr)->dimSize; - // WRONG. make LabVIEW crash !!! LIntArr * dimPtr; - LIntArr *dimPtr = &dims; - safeCall(src, error, ArrayConstructor(ptr, inPtr, &dimPtr)); -} + template + static void arrayConstructor(char const *src, ErrorCluster *error, void **ptr, + V inPtr, const LIntArrHdl dims) + { + safeCall(src, error, ArrayConstructor(ptr, inPtr, dims)); + } -// FIXME: If this doesn't work, add in another template param to cast to instead -// of -// FIXME: casting to Data directly (like Float32) -// FIXME: If this does work, then every derived type can just call the data -// function -// FIXME: for instance, mdsplus_float32_getInt can just call mdsplus_data_getInt -template -static T getScalar(void const *b, T (Data::*getX)(), char const *src, - ErrorCluster *error) { - MgErr errorCode = noErr; - char const *errorMessage = (char *)""; - - T x = 0; - try { - Data *data = reinterpret_cast(const_cast(b)); - x = (data->*getX)(); - fillErrorCluster(errorCode, src, errorMessage, error); - } catch (const MdsException &e) { - errorCode = bogusError; - errorMessage = e.what(); - fillErrorCluster(errorCode, src, errorMessage, error); + template + static void arrayConstructor(char const *src, ErrorCluster *error, void **ptr, + V inPtr) + { + LIntArr dims; + dims.dimSize = 1; + // WRONG. make labVIEW crash!!! dims.elt[1] = (*inPtr)->dimSize; + dims.elt[0] = (*inPtr)->dimSize; + // WRONG. make LabVIEW crash !!! LIntArr * dimPtr; + LIntArr *dimPtr = &dims; + safeCall(src, error, ArrayConstructor(ptr, inPtr, &dimPtr)); } - // fillErrorCluster(errorCode, src, errorMessage, error); - return x; -} + // FIXME: If this doesn't work, add in another template param to cast to instead + // of + // FIXME: casting to Data directly (like Float32) + // FIXME: If this does work, then every derived type can just call the data + // function + // FIXME: for instance, mdsplus_float32_getInt can just call mdsplus_data_getInt + template + static T getScalar(void const *b, T (Data::*getX)(), char const *src, + ErrorCluster *error) + { + MgErr errorCode = noErr; + char const *errorMessage = (char *)""; + + T x = 0; + try + { + Data *data = reinterpret_cast(const_cast(b)); + x = (data->*getX)(); + fillErrorCluster(errorCode, src, errorMessage, error); + } + catch (const MdsException &e) + { + errorCode = bogusError; + errorMessage = e.what(); + fillErrorCluster(errorCode, src, errorMessage, error); + } + // fillErrorCluster(errorCode, src, errorMessage, error); + + return x; + } -/******************************************************************************************************** + /******************************************************************************************************** ARRAY ********************************************************************************************************/ -extern "C" { + extern "C" + { -EXPORT void mdsplus_array_constructor(void **lvArrayPtrOut, - ErrorCluster *error) { - safeCall(__func__, error, Constructor(lvArrayPtrOut)); -} + EXPORT void mdsplus_array_constructor(void **lvArrayPtrOut, + ErrorCluster *error) + { + safeCall(__func__, error, Constructor(lvArrayPtrOut)); + } -EXPORT void mdsplus_array_destructor(void **lvArrayPtr) { - deleteLvData(lvArrayPtr); -} + EXPORT void mdsplus_array_destructor(void **lvArrayPtr) + { + deleteLvData(lvArrayPtr); + } -EXPORT void mdsplus_array_getByteArray(const void *lvArrayPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error) + EXPORT void mdsplus_array_getByteArray(const void *lvArrayPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error) -{ + { - Array *arrayPtr = NULL; + Array *arrayPtr = NULL; - char *byteArrOut = NULL; + char *byteArrOut = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = (char *)""; + char const *errorMessage = (char *)""; - try + try - { + { - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - int byteArrLen = 0; + int byteArrLen = 0; - byteArrOut = arrayPtr->getByteArray(&byteArrLen); + byteArrOut = arrayPtr->getByteArray(&byteArrLen); - errorCode = - NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), - static_cast(byteArrLen)); + errorCode = + NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), + static_cast(byteArrLen)); - if (!errorCode) { + if (!errorCode) + { - for (int i = 0; i < byteArrLen; i++) + for (int i = 0; i < byteArrLen; i++) - (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); + (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); - (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + } - } + else - else + errorMessage = (char *)"NumericArrayResize error"; - errorMessage = (char *)"NumericArrayResize error"; + deleteNativeArray(byteArrOut); - deleteNativeArray(byteArrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + catch (const MdsException &e) - catch (const MdsException &e) + { - { + errorCode = bogusError; - errorCode = bogusError; + errorMessage = e.what(); - errorMessage = e.what(); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + // fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - // fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void mdsplus_array_getDoubleArray(const void *lvArrayPtr, + LDblArrHdl lvDblArrHdlOut, + ErrorCluster *error) -EXPORT void mdsplus_array_getDoubleArray(const void *lvArrayPtr, - LDblArrHdl lvDblArrHdlOut, - ErrorCluster *error) + { -{ + Array *arrayPtr = NULL; - Array *arrayPtr = NULL; + double *doubleArrOut = NULL; - double *doubleArrOut = NULL; + MgErr errorCode = noErr; - MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; - const char *errorSource = __FUNCTION__; + char const *errorMessage = (char *)""; - char const *errorMessage = (char *)""; + try - try + { - { + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + int doubleArrLen = 0; - int doubleArrLen = 0; + doubleArrOut = arrayPtr->getDoubleArray(&doubleArrLen); - doubleArrOut = arrayPtr->getDoubleArray(&doubleArrLen); + errorCode = + NumericArrayResize(fD, 1, reinterpret_cast(&lvDblArrHdlOut), + static_cast(doubleArrLen)); - errorCode = - NumericArrayResize(fD, 1, reinterpret_cast(&lvDblArrHdlOut), - static_cast(doubleArrLen)); + if (!errorCode) + { - if (!errorCode) { + for (int i = 0; i < doubleArrLen; i++) - for (int i = 0; i < doubleArrLen; i++) + (*lvDblArrHdlOut)->elt[i] = doubleArrOut[i]; - (*lvDblArrHdlOut)->elt[i] = doubleArrOut[i]; + (*lvDblArrHdlOut)->dimSize = static_cast(doubleArrLen); + } - (*lvDblArrHdlOut)->dimSize = static_cast(doubleArrLen); + else - } + errorMessage = (char *)"NumericArrayResize error"; - else + deleteNativeArray(doubleArrOut); + } - errorMessage = (char *)"NumericArrayResize error"; + catch (const MdsException &e) - deleteNativeArray(doubleArrOut); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = e.what(); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); - errorCode = bogusError; + return; + } + } - errorMessage = e.what(); + EXPORT void mdsplus_array_getElementAt(const void *lvArrayPtr, + void **lvDataPtrOut, int dimIn, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); + { - return; - } -} + Array *arrayPtr = NULL; -EXPORT void mdsplus_array_getElementAt(const void *lvArrayPtr, - void **lvDataPtrOut, int dimIn, - ErrorCluster *error) + Data *dataPtrOut = NULL; -{ + MgErr errorCode = noErr; - Array *arrayPtr = NULL; + const char *errorSource = __FUNCTION__; - Data *dataPtrOut = NULL; + char const *errorMessage = (char *)""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = (char *)""; + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - try + dataPtrOut = arrayPtr->getElementAt(dimIn); - { + *lvDataPtrOut = reinterpret_cast(dataPtrOut); - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - dataPtrOut = arrayPtr->getElementAt(dimIn); + catch (const MdsException &e) - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = e.what(); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + // fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_array_getElementAt_dims(const void *lvArrayPtr, + void **lvDataPtrOut, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error) - errorMessage = e.what(); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + { - // fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Array *arrayPtr = NULL; -EXPORT void mdsplus_array_getElementAt_dims(const void *lvArrayPtr, - void **lvDataPtrOut, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error) + Data *dataPtrOut = NULL; -{ + int *intArr = NULL; - Array *arrayPtr = NULL; + MgErr errorCode = noErr; - Data *dataPtrOut = NULL; + const char *errorSource = __FUNCTION__; - int *intArr = NULL; + char const *errorMessage = (char *)""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = (char *)""; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - try + intArr = new int[intArrLen]; - { + for (int i = 0; i < intArrLen; i++) - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - intArr = new int[intArrLen]; + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - for (int i = 0; i < intArrLen; i++) + dataPtrOut = arrayPtr->getElementAt(intArr, intArrLen); - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + delete[] intArr; - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + *lvDataPtrOut = reinterpret_cast(dataPtrOut); - dataPtrOut = arrayPtr->getElementAt(intArr, intArrLen); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - delete[] intArr; + catch (const MdsException &e) - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = e.what(); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + // fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_array_getFloatArray(const void *lvArrayPtr, + LFltArrHdl lvFltArrHdlOut, + ErrorCluster *error) - errorMessage = e.what(); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + { - // fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Array *arrayPtr = NULL; -EXPORT void mdsplus_array_getFloatArray(const void *lvArrayPtr, - LFltArrHdl lvFltArrHdlOut, - ErrorCluster *error) + float *floatArrOut = NULL; -{ + MgErr errorCode = noErr; - Array *arrayPtr = NULL; + const char *errorSource = __FUNCTION__; - float *floatArrOut = NULL; + char const *errorMessage = (char *)""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = (char *)""; + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - try + int floatArrLen = 0; - { + floatArrOut = arrayPtr->getFloatArray(&floatArrLen); - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + errorCode = + NumericArrayResize(fS, 1, reinterpret_cast(&lvFltArrHdlOut), + static_cast(floatArrLen)); - int floatArrLen = 0; + if (!errorCode) + { - floatArrOut = arrayPtr->getFloatArray(&floatArrLen); + for (int i = 0; i < floatArrLen; i++) - errorCode = - NumericArrayResize(fS, 1, reinterpret_cast(&lvFltArrHdlOut), - static_cast(floatArrLen)); + (*lvFltArrHdlOut)->elt[i] = floatArrOut[i]; - if (!errorCode) { + (*lvFltArrHdlOut)->dimSize = static_cast(floatArrLen); + } - for (int i = 0; i < floatArrLen; i++) + else - (*lvFltArrHdlOut)->elt[i] = floatArrOut[i]; + errorMessage = (char *)"NumericArrayResize error"; - (*lvFltArrHdlOut)->dimSize = static_cast(floatArrLen); + deleteNativeArray(floatArrOut); + } - } + catch (const MdsException &e) - else + { - errorMessage = (char *)"NumericArrayResize error"; + errorCode = bogusError; - deleteNativeArray(floatArrOut); + errorMessage = e.what(); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); - catch (const MdsException &e) + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_array_getInfo(const void *lvArrayPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - errorMessage = e.what(); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); + Array *arrayPtr = NULL; - return; - } + char nDims = 0; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int *dims = NULL; -EXPORT void mdsplus_array_getInfo(const void *lvArrayPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + void *ptr = NULL; -{ + MgErr errorCode = noErr; - Array *arrayPtr = NULL; + const char *errorSource = __FUNCTION__; - char nDims = 0; + char const *errorMessage = ""; - int *dims = NULL; + try - void *ptr = NULL; + { - MgErr errorCode = noErr; + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - const char *errorSource = __FUNCTION__; + arrayPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); - char const *errorMessage = ""; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(nDims)); - try + if (!errorCode) + { - { + for (int i = 0; i < nDims; i++) - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); - arrayPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); + (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + } - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(nDims)); + else - if (!errorCode) { + errorMessage = (char *)"NumericArrayResize error"; - for (int i = 0; i < nDims; i++) + // ptr is not returned - (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); + deleteNativeArray(dims); + } - (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + catch (const MdsException &mdsE) - } + { - else + errorCode = bogusError; - errorMessage = (char *)"NumericArrayResize error"; + errorMessage = const_cast(mdsE.what()); - // ptr is not returned + fillErrorCluster(errorCode, errorSource, errorMessage, error); - deleteNativeArray(dims); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &mdsE) + EXPORT void mdsplus_array_getIntArray(const void *lvArrayPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - { + { - errorCode = bogusError; + Array *arrayPtr = NULL; - errorMessage = const_cast(mdsE.what()); + int *intArrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + MgErr errorCode = noErr; - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = ""; -EXPORT void mdsplus_array_getIntArray(const void *lvArrayPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + try -{ + { - Array *arrayPtr = NULL; + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - int *intArrOut = NULL; + int intArrLen = 0; - MgErr errorCode = noErr; + intArrOut = arrayPtr->getIntArray(&intArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(intArrLen)); - char const *errorMessage = ""; + if (!errorCode) + { - try + for (int i = 0; i < intArrLen; i++) - { + (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + } - int intArrLen = 0; + else - intArrOut = arrayPtr->getIntArray(&intArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(intArrLen)); + deleteNativeArray(intArrOut); + } - if (!errorCode) { + catch (const MdsException &mdsE) - for (int i = 0; i < intArrLen; i++) + { - (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); + errorCode = bogusError; - (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + errorMessage = const_cast(mdsE.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); - else + return; + } - errorMessage = (char *)"NumericArrayResize error"; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - deleteNativeArray(intArrOut); + EXPORT void mdsplus_array_getLongArray(const void *lvArrayPtr, + LLngArrHdl lvLngArrHdlOut, + ErrorCluster *error) - } + { - catch (const MdsException &mdsE) + Array *arrayPtr = NULL; - { + int64_t *longArrOut = NULL; - errorCode = bogusError; + MgErr errorCode = noErr; - errorMessage = const_cast(mdsE.what()); + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + char const *errorMessage = ""; - return; - } + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_array_getLongArray(const void *lvArrayPtr, - LLngArrHdl lvLngArrHdlOut, - ErrorCluster *error) + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); -{ + int longArrLen = 0; - Array *arrayPtr = NULL; + longArrOut = arrayPtr->getLongArray(&longArrLen); - int64_t *longArrOut = NULL; + errorCode = + NumericArrayResize(iQ, 1, reinterpret_cast(&lvLngArrHdlOut), + static_cast(longArrLen)); - MgErr errorCode = noErr; + if (!errorCode) + { - const char *errorSource = __FUNCTION__; + for (int i = 0; i < longArrLen; i++) - char const *errorMessage = ""; + (*lvLngArrHdlOut)->elt[i] = static_cast(longArrOut[i]); - try + (*lvLngArrHdlOut)->dimSize = static_cast(longArrLen); + } - { + else - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + errorMessage = (char *)"NumericArrayResize error"; - int longArrLen = 0; + deleteNativeArray(longArrOut); + } - longArrOut = arrayPtr->getLongArray(&longArrLen); + catch (const MdsException &mdsE) - errorCode = - NumericArrayResize(iQ, 1, reinterpret_cast(&lvLngArrHdlOut), - static_cast(longArrLen)); + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < longArrLen; i++) + errorMessage = const_cast(mdsE.what()); - (*lvLngArrHdlOut)->elt[i] = static_cast(longArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvLngArrHdlOut)->dimSize = static_cast(longArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(longArrOut); + EXPORT void mdsplus_array_getShape(const void *lvArrayPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - } + { - catch (const MdsException &mdsE) + Array *arrayPtr = NULL; - { + int *intArrOut = NULL; - errorCode = bogusError; + MgErr errorCode = noErr; - errorMessage = const_cast(mdsE.what()); + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + char const *errorMessage = ""; - return; - } + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_array_getShape(const void *lvArrayPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); -{ + int intArrLen = 0; - Array *arrayPtr = NULL; + intArrOut = arrayPtr->getShape(&intArrLen); - int *intArrOut = NULL; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(intArrLen)); - MgErr errorCode = noErr; + if (!errorCode) + { - const char *errorSource = __FUNCTION__; + for (int i = 0; i < intArrLen; i++) - char const *errorMessage = ""; + (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); - try + (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + } - { + else - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + errorMessage = (char *)"NumericArrayResize error"; - int intArrLen = 0; + deleteNativeArray(intArrOut); + } - intArrOut = arrayPtr->getShape(&intArrLen); + catch (const MdsException &mdsE) - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(intArrLen)); + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < intArrLen; i++) + errorMessage = const_cast(mdsE.what()); - (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(intArrOut); + EXPORT void mdsplus_array_getShortArray(const void *lvArrayPtr, + LShtArrHdl lvShtArrHdlOut, + ErrorCluster *error) - } + { - catch (const MdsException &mdsE) + Array *arrayPtr = NULL; - { + short *shortArrOut = NULL; - errorCode = bogusError; + MgErr errorCode = noErr; - errorMessage = const_cast(mdsE.what()); + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + char const *errorMessage = ""; - return; - } + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_array_getShortArray(const void *lvArrayPtr, - LShtArrHdl lvShtArrHdlOut, - ErrorCluster *error) + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); -{ + int shortArrLen = 0; - Array *arrayPtr = NULL; + shortArrOut = arrayPtr->getShortArray(&shortArrLen); - short *shortArrOut = NULL; + errorCode = + NumericArrayResize(iW, 1, reinterpret_cast(&lvShtArrHdlOut), + static_cast(shortArrLen)); - MgErr errorCode = noErr; + if (!errorCode) + { - const char *errorSource = __FUNCTION__; + for (int i = 0; i < shortArrLen; i++) - char const *errorMessage = ""; + (*lvShtArrHdlOut)->elt[i] = static_cast(shortArrOut[i]); - try + (*lvShtArrHdlOut)->dimSize = static_cast(shortArrLen); + } - { + else - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + errorMessage = (char *)"NumericArrayResize error"; - int shortArrLen = 0; + deleteNativeArray(shortArrOut); + } - shortArrOut = arrayPtr->getShortArray(&shortArrLen); + catch (const MdsException &mdsE) - errorCode = - NumericArrayResize(iW, 1, reinterpret_cast(&lvShtArrHdlOut), - static_cast(shortArrLen)); + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < shortArrLen; i++) + errorMessage = const_cast(mdsE.what()); - (*lvShtArrHdlOut)->elt[i] = static_cast(shortArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvShtArrHdlOut)->dimSize = static_cast(shortArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else + EXPORT void mdsplus_array_getSize(const void *lvArrayPtr, int *sizeOut, + ErrorCluster *error) - errorMessage = (char *)"NumericArrayResize error"; + { - deleteNativeArray(shortArrOut); + Array *arrayPtr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &mdsE) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(mdsE.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - return; - } + *sizeOut = arrayPtr->getSize(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &mdsE) -EXPORT void mdsplus_array_getSize(const void *lvArrayPtr, int *sizeOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Array *arrayPtr = NULL; + errorMessage = const_cast(mdsE.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); - const char *errorSource = __FUNCTION__; + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_array_getStringArray(const void *lvArrayPtr, + LStrArrHdl lvStrArrHdlOut, + ErrorCluster *error) + { + MgErr errorCode = noErr; + char const *errorSource = __func__; + char const *errorMessage = (char *)""; - { + char **stringArrOut = NULL; + int stringArrLen = 0; - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + try + { + Array *arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + stringArrOut = arrayPtr->getStringArray(&stringArrLen); - *sizeOut = arrayPtr->getSize(); + // checks whether the size of a pointer is 32 bit or 64 bit depending upon + // the system architecture + int32 typeCode = (sizeof(LStrHandle) > sizeof(int32)) ? iQ : iL; - } + // resizes string array + errorCode = NumericArrayResize(typeCode, 1, + reinterpret_cast(&lvStrArrHdlOut), + static_cast(stringArrLen)); - catch (const MdsException &mdsE) + if (!errorCode) + { + int i = 0; - { + // creates LStrHandle strings and fills them with the stringArrOut + // corrispondent strings + while (!errorCode && i < stringArrLen) + { + LStrHandle currLStrHdl = + reinterpret_cast(DSNewHandle(sizeof(LStrHandle))); + + errorCode = currLStrHdl == NULL; + + if (!errorCode) + { + std::string currStr(stringArrOut[i]); + + errorCode = NumericArrayResize( + uB, 1, reinterpret_cast(&currLStrHdl), + currStr.size() + sizeof(int32)); + + if (!errorCode) + { + MoveBlock(currStr.c_str(), LStrBuf(*currLStrHdl), currStr.size()); + (*currLStrHdl)->cnt = currStr.size(); + (*lvStrArrHdlOut)->elm[i++] = currLStrHdl; + } + else + errorMessage = (char *)"NumericArrayResize error"; + } + else + errorMessage = (char *)"DSNewHandle error"; + } - errorCode = bogusError; + // keeps only well allocated string handles, till the ith string + (*lvStrArrHdlOut)->dimSize = static_cast(i); + } + else + errorMessage = (char *)"NumericArrayResize error"; + } + catch (const MdsException &e) + { + errorCode = bogusError; + errorMessage = e.what(); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorMessage = const_cast(mdsE.what()); + // free memory + for (int i = 0; i < stringArrLen; ++i) + deleteNativeArray(stringArrOut[i]); + deleteNativeArray(stringArrOut); - fillErrorCluster(errorCode, errorSource, errorMessage, error); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - return; - } + EXPORT void mdsplus_array_setElementAt(const void *lvArrayPtr, int dimIn, + const void *lvDataPtrIn, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_array_getStringArray(const void *lvArrayPtr, - LStrArrHdl lvStrArrHdlOut, - ErrorCluster *error) { - MgErr errorCode = noErr; - char const *errorSource = __func__; - char const *errorMessage = (char *)""; - - char **stringArrOut = NULL; - int stringArrLen = 0; - - try { - Array *arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - stringArrOut = arrayPtr->getStringArray(&stringArrLen); - - // checks whether the size of a pointer is 32 bit or 64 bit depending upon - // the system architecture - int32 typeCode = (sizeof(LStrHandle) > sizeof(int32)) ? iQ : iL; - - // resizes string array - errorCode = NumericArrayResize(typeCode, 1, - reinterpret_cast(&lvStrArrHdlOut), - static_cast(stringArrLen)); - - if (!errorCode) { - int i = 0; - - // creates LStrHandle strings and fills them with the stringArrOut - // corrispondent strings - while (!errorCode && i < stringArrLen) { - LStrHandle currLStrHdl = - reinterpret_cast(DSNewHandle(sizeof(LStrHandle))); - - errorCode = currLStrHdl == NULL; - - if (!errorCode) { - std::string currStr(stringArrOut[i]); - - errorCode = NumericArrayResize( - uB, 1, reinterpret_cast(&currLStrHdl), - currStr.size() + sizeof(int32)); - - if (!errorCode) { - MoveBlock(currStr.c_str(), LStrBuf(*currLStrHdl), currStr.size()); - (*currLStrHdl)->cnt = currStr.size(); - (*lvStrArrHdlOut)->elm[i++] = currLStrHdl; - } else - errorMessage = (char *)"NumericArrayResize error"; - } else - errorMessage = (char *)"DSNewHandle error"; - } - - // keeps only well allocated string handles, till the ith string - (*lvStrArrHdlOut)->dimSize = static_cast(i); - } else - errorMessage = (char *)"NumericArrayResize error"; - - } catch (const MdsException &e) { - errorCode = bogusError; - errorMessage = e.what(); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Array *arrayPtr = NULL; - // free memory - for (int i = 0; i < stringArrLen; ++i) - deleteNativeArray(stringArrOut[i]); - deleteNativeArray(stringArrOut); + Data *dataPtrIn = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_array_setElementAt(const void *lvArrayPtr, int dimIn, - const void *lvDataPtrIn, - ErrorCluster *error) + const char *errorSource = __FUNCTION__; -{ + char const *errorMessage = ""; - Array *arrayPtr = NULL; + try - Data *dataPtrIn = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; - - char const *errorMessage = ""; - - try - - { - - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + { - arrayPtr->setElementAt(dimIn, dataPtrIn); + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - } + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - catch (const MdsException &mdsE) + arrayPtr->setElementAt(dimIn, dataPtrIn); + } - { + catch (const MdsException &mdsE) - errorCode = bogusError; + { - errorMessage = const_cast(mdsE.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + errorMessage = const_cast(mdsE.what()); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + return; + } -EXPORT void mdsplus_array_setElementAt_dims(const void *lvArrayPtr, - const LIntArrHdl lvIntArrHdlIn, - const void *lvDataPtrIn, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_array_setElementAt_dims(const void *lvArrayPtr, + const LIntArrHdl lvIntArrHdlIn, + const void *lvDataPtrIn, + ErrorCluster *error) - Array *arrayPtr = NULL; + { - Data *dataPtrIn = NULL; + Array *arrayPtr = NULL; - int *intArr = NULL; + Data *dataPtrIn = NULL; - MgErr errorCode = noErr; + int *intArr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + { - intArr = new int[intArrLen]; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - for (int i = 0; i < intArrLen; i++) + intArr = new int[intArrLen]; - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + for (int i = 0; i < intArrLen; i++) - arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + arrayPtr = reinterpret_cast(const_cast(lvArrayPtr)); - arrayPtr->setElementAt(intArr, intArrLen, dataPtrIn); + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - delete[] intArr; + arrayPtr->setElementAt(intArr, intArrLen, dataPtrIn); - } + delete[] intArr; + } - catch (const MdsException &mdsE) + catch (const MdsException &mdsE) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(mdsE.what()); + errorMessage = const_cast(mdsE.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -/******************************************************************************************************** + /******************************************************************************************************** COMPOUND ********************************************************************************************************/ -EXPORT void mdsplus_compound_constructor(void **lvCompoundPtrOut, - ErrorCluster *error) { - safeCall(__func__, error, Constructor(lvCompoundPtrOut)); -} + EXPORT void mdsplus_compound_constructor(void **lvCompoundPtrOut, + ErrorCluster *error) + { + safeCall(__func__, error, Constructor(lvCompoundPtrOut)); + } -EXPORT void mdsplus_compound_destructor(void **lvCompoundPtr) { - deleteLvData(lvCompoundPtr); -} + EXPORT void mdsplus_compound_destructor(void **lvCompoundPtr) + { + deleteLvData(lvCompoundPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** DATA ********************************************************************************************************/ -EXPORT void mdsplus_data_compile(void **lvDataPtrOut, const char *exprIn, - ErrorCluster *error) - -{ - - Data *dataPtrOut = NULL; - - MgErr errorCode = noErr; + EXPORT void mdsplus_data_compile(void **lvDataPtrOut, const char *exprIn, + ErrorCluster *error) - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + Data *dataPtrOut = NULL; - try + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - dataPtrOut = compile(const_cast(exprIn)); + char const *errorMessage = ""; - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + try - } + { - catch (const MdsException &mdsE) + dataPtrOut = compile(const_cast(exprIn)); - { + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - errorCode = bogusError; + catch (const MdsException &mdsE) - errorMessage = const_cast(mdsE.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); + errorCode = bogusError; - return; - } + errorMessage = const_cast(mdsE.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); -EXPORT void mdsplus_data_compile_tree(void **lvDataPtrOut, const char *exprIn, - const void *lvTreePtrIn, - ErrorCluster *error) + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Data *dataPtrOut = NULL; + EXPORT void mdsplus_data_compile_tree(void **lvDataPtrOut, const char *exprIn, + const void *lvTreePtrIn, + ErrorCluster *error) - Tree *treePtrIn = NULL; + { - MgErr errorCode = noErr; + Data *dataPtrOut = NULL; - const char *errorSource = __FUNCTION__; + Tree *treePtrIn = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); + try - dataPtrOut = compile(const_cast(exprIn), treePtrIn); + { - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); - } + dataPtrOut = compile(const_cast(exprIn), treePtrIn); - catch (const MdsException &mdsE) + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - { + catch (const MdsException &mdsE) - errorCode = bogusError; + { - errorMessage = const_cast(mdsE.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + errorMessage = const_cast(mdsE.what()); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + return; + } -EXPORT void mdsplus_data_data(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_data_data(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error) - Data *dataPtr = NULL; + { - Data *dataPtrOut = NULL; + Data *dataPtr = NULL; - MgErr errorCode = noErr; + Data *dataPtrOut = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + { - dataPtrOut = dataPtr->data(); + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + dataPtrOut = dataPtr->data(); - } + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - catch (const MdsException &mdsE) + catch (const MdsException &mdsE) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(mdsE.what()); + errorMessage = const_cast(mdsE.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_data_decompile(const void *lvDataPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error) + EXPORT void mdsplus_data_decompile(const void *lvDataPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error) -{ + { - Data *dataPtr = NULL; + Data *dataPtr = NULL; - char *strOut = NULL; + char *strOut = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - strOut = dataPtr->decompile(); + strOut = dataPtr->decompile(); - std::size_t strOutLen = std::strlen(strOut); + std::size_t strOutLen = std::strlen(strOut); - errorCode = - NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), - strOutLen + sizeof(int32)); + errorCode = + NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), + strOutLen + sizeof(int32)); - if (!errorCode) + if (!errorCode) - { + { - MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), - strOutLen); + MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), + strOutLen); - (*lvStrHdlOut)->cnt = static_cast(strOutLen); + (*lvStrHdlOut)->cnt = static_cast(strOutLen); + } - } + else - else + errorMessage = (char *)"NumericArrayResize error"; - errorMessage = (char *)"NumericArrayResize error"; + deleteNativeArray(strOut); + } - deleteNativeArray(strOut); + catch (const MdsException &mdsE) - } + { - catch (const MdsException &mdsE) + errorCode = bogusError; - { + errorMessage = const_cast(mdsE.what()); - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); - errorMessage = const_cast(mdsE.what()); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - return; - } + EXPORT void mdsplus_data_deserialize(void **lvDataPtrOut, + const char *serializedIn, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_data_deserialize(void **lvDataPtrOut, - const char *serializedIn, - ErrorCluster *error) + Data *dataPtrOut = NULL; -{ + MgErr errorCode = noErr; - Data *dataPtrOut = NULL; + const char *errorSource = __FUNCTION__; - MgErr errorCode = noErr; + char const *errorMessage = ""; - const char *errorSource = __FUNCTION__; + try - char const *errorMessage = ""; + { - try + dataPtrOut = deserialize(const_cast(serializedIn)); - { + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - dataPtrOut = deserialize(const_cast(serializedIn)); + catch (const MdsException &mdsE) - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + { - } + errorCode = bogusError; - catch (const MdsException &mdsE) + errorMessage = const_cast(mdsE.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); - errorCode = bogusError; + return; + } - errorMessage = const_cast(mdsE.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); + EXPORT void mdsplus_data_deserialize_data(void **lvDataPtrOut, + const void *lvDataPtrIn, + ErrorCluster *error) - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Data *dataPtrOut = NULL; -EXPORT void mdsplus_data_deserialize_data(void **lvDataPtrOut, - const void *lvDataPtrIn, - ErrorCluster *error) + Data *dataPtrIn = NULL; -{ + MgErr errorCode = noErr; - Data *dataPtrOut = NULL; + const char *errorSource = __FUNCTION__; - Data *dataPtrIn = NULL; + char const *errorMessage = ""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - try + dataPtrOut = deserialize(dataPtrIn); - { + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + catch (const MdsException &mdsE) - dataPtrOut = deserialize(dataPtrIn); + { - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + errorCode = bogusError; - } + errorMessage = const_cast(mdsE.what()); - catch (const MdsException &mdsE) + fillErrorCluster(errorCode, errorSource, errorMessage, error); - { + return; + } - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorMessage = const_cast(mdsE.what()); + EXPORT void mdsplus_data_destructor(void **lvDataPtr) + { + deleteLvData(lvDataPtr); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); + EXPORT void mdsplus_data_evaluate(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error) - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Data *dataPtr = NULL; -EXPORT void mdsplus_data_destructor(void **lvDataPtr) { - deleteLvData(lvDataPtr); -} + Data *dataPtrOut = NULL; -EXPORT void mdsplus_data_evaluate(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error) + MgErr errorCode = noErr; -{ + const char *errorSource = __FUNCTION__; - Data *dataPtr = NULL; + char const *errorMessage = ""; - Data *dataPtrOut = NULL; + try - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - char const *errorMessage = ""; + dataPtrOut = dataPtr->evaluate(); - try + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - { + catch (const MdsException &mdsE) - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + { - dataPtrOut = dataPtr->evaluate(); + errorCode = bogusError; - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + errorMessage = const_cast(mdsE.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); - catch (const MdsException &mdsE) + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_data_execute(void **lvDataPtrOut, const char *exprIn, + ErrorCluster *error) - errorMessage = const_cast(mdsE.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); + Data *dataPtrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_execute(void **lvDataPtrOut, const char *exprIn, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Data *dataPtrOut = NULL; + { - MgErr errorCode = noErr; + dataPtrOut = execute(const_cast(exprIn)); - const char *errorSource = __FUNCTION__; + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - char const *errorMessage = ""; + catch (const MdsException &mdsE) - try + { - { + errorCode = bogusError; - dataPtrOut = execute(const_cast(exprIn)); + errorMessage = const_cast(mdsE.what()); - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - } + return; + } - catch (const MdsException &mdsE) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_data_execute_tree(void **lvDataPtrOut, const char *exprIn, + const void *lvTreePtrIn, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(mdsE.what()); + Data *dataPtrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + Tree *treePtrIn = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_execute_tree(void **lvDataPtrOut, const char *exprIn, - const void *lvTreePtrIn, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Data *dataPtrOut = NULL; + { - Tree *treePtrIn = NULL; + treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); - MgErr errorCode = noErr; + dataPtrOut = execute(const_cast(exprIn), treePtrIn); - const char *errorSource = __FUNCTION__; + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - char const *errorMessage = ""; + catch (const MdsException &mdsE) - try + { - { + errorCode = bogusError; - treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); + errorMessage = const_cast(mdsE.what()); - dataPtrOut = execute(const_cast(exprIn), treePtrIn); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &mdsE) + EXPORT void mdsplus_data_getByte(const void *lvDataPtr, char *byteOut, + ErrorCluster *error) + { + *byteOut = getScalar(lvDataPtr, &Data::getByte, __func__, error); + } - { + EXPORT void mdsplus_data_getByteArray(const void *lvDataPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(mdsE.what()); + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + char *byteArrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getByte(const void *lvDataPtr, char *byteOut, - ErrorCluster *error) { - *byteOut = getScalar(lvDataPtr, &Data::getByte, __func__, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getByteArray(const void *lvDataPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - char *byteArrOut = NULL; + int byteArrLen = 0; - MgErr errorCode = noErr; + byteArrOut = dataPtr->getByteArray(&byteArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), + static_cast(byteArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < byteArrLen; i++) - { + (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + } - int byteArrLen = 0; + else - byteArrOut = dataPtr->getByteArray(&byteArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), - static_cast(byteArrLen)); + deleteNativeArray(byteArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < byteArrLen; i++) + errorMessage = e.what(); - (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(byteArrOut); + EXPORT void mdsplus_data_getDouble(const void *lvDataPtr, double *doubleOut, + ErrorCluster *error) + { + *doubleOut = getScalar(lvDataPtr, &Data::getDouble, __func__, error); + } - } catch (const MdsException &e) { + EXPORT void mdsplus_data_getDoubleArray(const void *lvDataPtr, + LDblArrHdl lvDblArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = e.what(); + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + double *doubleArrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getDouble(const void *lvDataPtr, double *doubleOut, - ErrorCluster *error) { - *doubleOut = getScalar(lvDataPtr, &Data::getDouble, __func__, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getDoubleArray(const void *lvDataPtr, - LDblArrHdl lvDblArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - double *doubleArrOut = NULL; + int doubleArrLen = 0; - MgErr errorCode = noErr; + doubleArrOut = dataPtr->getDoubleArray(&doubleArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(fD, 1, reinterpret_cast(&lvDblArrHdlOut), + static_cast(doubleArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < doubleArrLen; i++) - { + (*lvDblArrHdlOut)->elt[i] = doubleArrOut[i]; - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvDblArrHdlOut)->dimSize = static_cast(doubleArrLen); + } - int doubleArrLen = 0; + else - doubleArrOut = dataPtr->getDoubleArray(&doubleArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(fD, 1, reinterpret_cast(&lvDblArrHdlOut), - static_cast(doubleArrLen)); + deleteNativeArray(doubleArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < doubleArrLen; i++) + errorMessage = e.what(); - (*lvDblArrHdlOut)->elt[i] = doubleArrOut[i]; + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvDblArrHdlOut)->dimSize = static_cast(doubleArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; + EXPORT void mdsplus_data_getError(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error) + { + *lvDataPtrOut = reinterpret_cast( + getScalar(lvDataPtr, &Data::getError, __func__, error)); + } - deleteNativeArray(doubleArrOut); + EXPORT void mdsplus_data_getFloat(const void *lvDataPtr, float *floatOut, + ErrorCluster *error) + { + *floatOut = getScalar(lvDataPtr, &Data::getFloat, __func__, error); + } - } catch (const MdsException &e) { + EXPORT void mdsplus_data_getFloatArray(const void *lvDataPtr, + LFltArrHdl lvFltArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = e.what(); + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + float *floatArrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getError(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error) { - *lvDataPtrOut = reinterpret_cast( - getScalar(lvDataPtr, &Data::getError, __func__, error)); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getFloat(const void *lvDataPtr, float *floatOut, - ErrorCluster *error) { - *floatOut = getScalar(lvDataPtr, &Data::getFloat, __func__, error); -} + try -EXPORT void mdsplus_data_getFloatArray(const void *lvDataPtr, - LFltArrHdl lvFltArrHdlOut, - ErrorCluster *error) + { -{ + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - Data *dataPtr = NULL; + int floatArrLen = 0; - float *floatArrOut = NULL; + floatArrOut = dataPtr->getFloatArray(&floatArrLen); - MgErr errorCode = noErr; + errorCode = + NumericArrayResize(fS, 1, reinterpret_cast(&lvFltArrHdlOut), + static_cast(floatArrLen)); - const char *errorSource = __FUNCTION__; + if (!errorCode) + { - char const *errorMessage = (char *)""; + for (int i = 0; i < floatArrLen; i++) - try + (*lvFltArrHdlOut)->elt[i] = floatArrOut[i]; - { + (*lvFltArrHdlOut)->dimSize = static_cast(floatArrLen); + } - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + else - int floatArrLen = 0; + errorMessage = (char *)"NumericArrayResize error"; - floatArrOut = dataPtr->getFloatArray(&floatArrLen); + deleteNativeArray(floatArrOut); + } + catch (const MdsException &e) + { - errorCode = - NumericArrayResize(fS, 1, reinterpret_cast(&lvFltArrHdlOut), - static_cast(floatArrLen)); + errorCode = bogusError; - if (!errorCode) { + errorMessage = e.what(); - for (int i = 0; i < floatArrLen; i++) + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvFltArrHdlOut)->elt[i] = floatArrOut[i]; + return; + } - (*lvFltArrHdlOut)->dimSize = static_cast(floatArrLen); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void mdsplus_data_getHelp(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error) + { + *lvDataPtrOut = reinterpret_cast( + getScalar(lvDataPtr, &Data::getHelp, __func__, error)); } - else + EXPORT void mdsplus_data_getInfo(const void *lvDataPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, ErrorCluster *error) - errorMessage = (char *)"NumericArrayResize error"; + { - deleteNativeArray(floatArrOut); + Data *dataPtr = NULL; - } catch (const MdsException &e) { + char nDims = 0; - errorCode = bogusError; + int *dims = NULL; - errorMessage = e.what(); + void *ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + MgErr errorCode = noErr; - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getHelp(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error) { - *lvDataPtrOut = reinterpret_cast( - getScalar(lvDataPtr, &Data::getHelp, __func__, error)); -} + try -EXPORT void mdsplus_data_getInfo(const void *lvDataPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, ErrorCluster *error) + { -{ + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - Data *dataPtr = NULL; + dataPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); - char nDims = 0; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(nDims)); - int *dims = NULL; + if (!errorCode) + { - void *ptr = NULL; + for (int i = 0; i < nDims; i++) - MgErr errorCode = noErr; + (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); - const char *errorSource = __FUNCTION__; + (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + } - char const *errorMessage = (char *)""; + else - try + errorMessage = (char *)"NumericArrayResize error"; - { + // ptr is not returned - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + deleteNativeArray(dims); + } - dataPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); + catch (const MdsException &e) - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(nDims)); + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < nDims; i++) + errorMessage = e.what(); - (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void mdsplus_data_getInt(const void *lvDataPtr, int *intOut, + ErrorCluster *error) + { + *intOut = getScalar(lvDataPtr, &Data::getInt, __func__, error); } - else + EXPORT void mdsplus_data_getIntArray(const void *lvDataPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - errorMessage = (char *)"NumericArrayResize error"; + { - // ptr is not returned + Data *dataPtr = NULL; - deleteNativeArray(dims); + int *intArrOut = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { - - errorCode = bogusError; - - errorMessage = e.what(); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} - -EXPORT void mdsplus_data_getInt(const void *lvDataPtr, int *intOut, - ErrorCluster *error) { - *intOut = getScalar(lvDataPtr, &Data::getInt, __func__, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getIntArray(const void *lvDataPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - int *intArrOut = NULL; + int intArrLen = 0; - MgErr errorCode = noErr; + intArrOut = dataPtr->getIntArray(&intArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(intArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < intArrLen; i++) - { + (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + } - int intArrLen = 0; + else - intArrOut = dataPtr->getIntArray(&intArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(intArrLen)); + deleteNativeArray(intArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < intArrLen; i++) + errorMessage = e.what(); - (*lvIntArrHdlOut)->elt[i] = static_cast(intArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(intArrOut); + EXPORT void mdsplus_data_getLong(const void *lvDataPtr, int64_t *longOut, + ErrorCluster *error) + { + *longOut = getScalar(lvDataPtr, &Data::getLong, __func__, error); + } - } catch (const MdsException &e) { + EXPORT void mdsplus_data_getLongArray(const void *lvDataPtr, + LLngArrHdl lvLngArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = e.what(); + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + int64_t *longArrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getLong(const void *lvDataPtr, int64_t *longOut, - ErrorCluster *error) { - *longOut = getScalar(lvDataPtr, &Data::getLong, __func__, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getLongArray(const void *lvDataPtr, - LLngArrHdl lvLngArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - int64_t *longArrOut = NULL; + int longArrLen = 0; - MgErr errorCode = noErr; + longArrOut = dataPtr->getLongArray(&longArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iQ, 1, reinterpret_cast(&lvLngArrHdlOut), + static_cast(longArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < longArrLen; i++) - { + (*lvLngArrHdlOut)->elt[i] = static_cast(longArrOut[i]); - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvLngArrHdlOut)->dimSize = static_cast(longArrLen); + } - int longArrLen = 0; + else - longArrOut = dataPtr->getLongArray(&longArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iQ, 1, reinterpret_cast(&lvLngArrHdlOut), - static_cast(longArrLen)); + deleteNativeArray(longArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < longArrLen; i++) + errorMessage = e.what(); - (*lvLngArrHdlOut)->elt[i] = static_cast(longArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvLngArrHdlOut)->dimSize = static_cast(longArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(longArrOut); + EXPORT void mdsplus_data_getShape(const void *lvDataPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - } catch (const MdsException &e) { + { - errorCode = bogusError; + Data *dataPtr = NULL; - errorMessage = e.what(); + int *intArrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + MgErr errorCode = noErr; - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getShape(const void *lvDataPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - int *intArrOut = NULL; + int intArrLen = 0; - MgErr errorCode = noErr; + intArrOut = dataPtr->getShape(&intArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(intArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < intArrLen; i++) - { + (*lvIntArrHdlOut)->elt[i] = intArrOut[i]; - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + } - int intArrLen = 0; + else - intArrOut = dataPtr->getShape(&intArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(intArrLen)); + deleteNativeArray(intArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < intArrLen; i++) + errorMessage = e.what(); - (*lvIntArrHdlOut)->elt[i] = intArrOut[i]; + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvIntArrHdlOut)->dimSize = static_cast(intArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(intArrOut); + EXPORT void mdsplus_data_getShort(const void *lvDataPtr, short *shortOut, + ErrorCluster *error) + { + *shortOut = getScalar(lvDataPtr, &Data::getShort, __func__, error); + } - } catch (const MdsException &e) { + EXPORT void mdsplus_data_getShortArray(const void *lvDataPtr, + LShtArrHdl lvShtArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = e.what(); + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + short *shortArrOut = NULL; - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getShort(const void *lvDataPtr, short *shortOut, - ErrorCluster *error) { - *shortOut = getScalar(lvDataPtr, &Data::getShort, __func__, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getShortArray(const void *lvDataPtr, - LShtArrHdl lvShtArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - short *shortArrOut = NULL; + int shortArrLen = 0; - MgErr errorCode = noErr; + shortArrOut = dataPtr->getShortArray(&shortArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iW, 1, reinterpret_cast(&lvShtArrHdlOut), + static_cast(shortArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) - try + { - { + for (int i = 0; i < shortArrLen; i++) - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvShtArrHdlOut)->elt[i] = static_cast(shortArrOut[i]); - int shortArrLen = 0; + (*lvShtArrHdlOut)->dimSize = static_cast(shortArrLen); + } - shortArrOut = dataPtr->getShortArray(&shortArrLen); + else - errorCode = - NumericArrayResize(iW, 1, reinterpret_cast(&lvShtArrHdlOut), - static_cast(shortArrLen)); + errorMessage = (char *)"NumericArrayResize error"; - if (!errorCode) + deleteNativeArray(shortArrOut); + } + catch (const MdsException &e) + { - { + errorCode = bogusError; - for (int i = 0; i < shortArrLen; i++) + errorMessage = e.what(); - (*lvShtArrHdlOut)->elt[i] = static_cast(shortArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvShtArrHdlOut)->dimSize = static_cast(shortArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; + EXPORT void mdsplus_data_getSize(const void *lvDataPtr, int *sizeOut, + ErrorCluster *error) + { + *sizeOut = getScalar(lvDataPtr, &Data::getSize, __func__, error); + } - deleteNativeArray(shortArrOut); + EXPORT void mdsplus_data_getString(const void *lvDataPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error) - } catch (const MdsException &e) { + { - errorCode = bogusError; + Data *dataPtr = NULL; - errorMessage = e.what(); + char *strOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + MgErr errorCode = noErr; - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_getSize(const void *lvDataPtr, int *sizeOut, - ErrorCluster *error) { - *sizeOut = getScalar(lvDataPtr, &Data::getSize, __func__, error); -} + try -EXPORT void mdsplus_data_getString(const void *lvDataPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error) + { -{ + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - Data *dataPtr = NULL; + strOut = dataPtr->getString(); - char *strOut = NULL; + std::size_t strOutLen = std::strlen(strOut); - MgErr errorCode = noErr; + errorCode = + NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), + strOutLen + sizeof(int32)); - const char *errorSource = __FUNCTION__; + if (!errorCode) - char const *errorMessage = (char *)""; + { - try + MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), + strOutLen); - { + (*lvStrHdlOut)->cnt = strOutLen; + } - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + else - strOut = dataPtr->getString(); + errorMessage = (char *)"NumericArrayResize error"; - std::size_t strOutLen = std::strlen(strOut); + deleteNativeArray(strOut); + } - errorCode = - NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), - strOutLen + sizeof(int32)); + catch (const MdsException &e) - if (!errorCode) + { - { + errorCode = bogusError; - MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), - strOutLen); + errorMessage = e.what(); - (*lvStrHdlOut)->cnt = strOutLen; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(strOut); - - } - - catch (const MdsException &e) - - { - - errorCode = bogusError; - - errorMessage = e.what(); + EXPORT void mdsplus_data_getStringArray(const void *lvDataPtr, + LStrArrHdl lvStrArrHdlOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Data *dataPtr = NULL; -EXPORT void mdsplus_data_getStringArray(const void *lvDataPtr, - LStrArrHdl lvStrArrHdlOut, - ErrorCluster *error) + char **stringArrOut = NULL; -{ + int stringArrLen = 0; - Data *dataPtr = NULL; + MgErr errorCode = noErr; - char **stringArrOut = NULL; + const char *errorSource = __FUNCTION__; - int stringArrLen = 0; + char const *errorMessage = (char *)""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = (char *)""; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - try + stringArrOut = dataPtr->getStringArray(&stringArrLen); - { + // checks whether the size of a pointer is 32 bit or 64 bit depending upon + // the system architecture - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + int32 typeCode = (sizeof(LStrHandle) > sizeof(int32)) ? iQ : iL; - stringArrOut = dataPtr->getStringArray(&stringArrLen); + // resizes string array - // checks whether the size of a pointer is 32 bit or 64 bit depending upon - // the system architecture + errorCode = NumericArrayResize(typeCode, 1, + reinterpret_cast(&lvStrArrHdlOut), + static_cast(stringArrLen)); - int32 typeCode = (sizeof(LStrHandle) > sizeof(int32)) ? iQ : iL; + if (!errorCode) - // resizes string array + { - errorCode = NumericArrayResize(typeCode, 1, - reinterpret_cast(&lvStrArrHdlOut), - static_cast(stringArrLen)); + int i = 0; - if (!errorCode) + // creates LStrHandle strings and fills them with the stringArrOut + // corrispondent strings - { + while (!errorCode && i < stringArrLen) - int i = 0; + { - // creates LStrHandle strings and fills them with the stringArrOut - // corrispondent strings + char *currStr = stringArrOut[i]; - while (!errorCode && i < stringArrLen) + std::size_t currStrLen = std::strlen(currStr); - { + LStrHandle currLStrHdl = + reinterpret_cast(DSNewHandle(sizeof(LStrHandle))); - char *currStr = stringArrOut[i]; + errorCode = currLStrHdl == NULL; - std::size_t currStrLen = std::strlen(currStr); + if (!errorCode) - LStrHandle currLStrHdl = - reinterpret_cast(DSNewHandle(sizeof(LStrHandle))); + { - errorCode = currLStrHdl == NULL; + errorCode = NumericArrayResize( + uB, 1, reinterpret_cast(&currLStrHdl), + currStrLen + sizeof(int32)); - if (!errorCode) + if (!errorCode) - { + { - errorCode = NumericArrayResize( - uB, 1, reinterpret_cast(&currLStrHdl), - currStrLen + sizeof(int32)); + MoveBlock(reinterpret_cast(currStr), LStrBuf(*currLStrHdl), + currStrLen); - if (!errorCode) + (*currLStrHdl)->cnt = currStrLen; - { + (*lvStrArrHdlOut)->elm[i++] = currLStrHdl; + } - MoveBlock(reinterpret_cast(currStr), LStrBuf(*currLStrHdl), - currStrLen); + else - (*currLStrHdl)->cnt = currStrLen; + errorMessage = (char *)"NumericArrayResize error"; + } - (*lvStrArrHdlOut)->elm[i++] = currLStrHdl; + else + errorMessage = (char *)"DSNewHandle error"; } - else - - errorMessage = (char *)"NumericArrayResize error"; + // keeps only well allocated string handles, till the ith string + (*lvStrArrHdlOut)->dimSize = static_cast(i); } else - errorMessage = (char *)"DSNewHandle error"; - } + errorMessage = (char *)"NumericArrayResize error"; - // keeps only well allocated string handles, till the ith string + // frees memory - (*lvStrArrHdlOut)->dimSize = static_cast(i); + for (int i = 0; i < stringArrLen; i++) - } + deleteNativeArray(stringArrOut[i]); - else + deleteNativeArray(stringArrOut); + } + catch (const MdsException &e) + { - errorMessage = (char *)"NumericArrayResize error"; + errorCode = bogusError; - // frees memory + errorMessage = e.what(); - for (int i = 0; i < stringArrLen; i++) + fillErrorCluster(errorCode, errorSource, errorMessage, error); - deleteNativeArray(stringArrOut[i]); + return; + } - deleteNativeArray(stringArrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - } catch (const MdsException &e) { + EXPORT void mdsplus_data_getUnits(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error) + { + *lvDataPtrOut = reinterpret_cast( + getScalar(lvDataPtr, &Data::getUnits, __func__, error)); + } - errorCode = bogusError; + EXPORT void mdsplus_data_getValidation(const void *lvDataPtr, + void **lvDataPtrOut, + ErrorCluster *error) + { + *lvDataPtrOut = reinterpret_cast( + getScalar(lvDataPtr, &Data::getValidation, __func__, error)); + } - errorMessage = e.what(); + EXPORT void mdsplus_data_plot(const void *lvDataPtr, ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); + { - return; - } + Data *dataPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_data_getUnits(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error) { - *lvDataPtrOut = reinterpret_cast( - getScalar(lvDataPtr, &Data::getUnits, __func__, error)); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_data_getValidation(const void *lvDataPtr, - void **lvDataPtrOut, - ErrorCluster *error) { - *lvDataPtrOut = reinterpret_cast( - getScalar(lvDataPtr, &Data::getValidation, __func__, error)); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_plot(const void *lvDataPtr, ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - MgErr errorCode = noErr; + dataPtr->plot(); + } + catch (const MdsException &e) + { - const char *errorSource = __FUNCTION__; + errorCode = bogusError; - char const *errorMessage = (char *)""; + errorMessage = e.what(); - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); - { + return; + } - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - dataPtr->plot(); + EXPORT void mdsplus_data_serialize(const void *lvDataPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error) - } catch (const MdsException &e) { + { - errorCode = bogusError; + Data *dataPtr = NULL; - errorMessage = e.what(); + char *byteArrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); + MgErr errorCode = noErr; - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = (char *)""; -EXPORT void mdsplus_data_serialize(const void *lvDataPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error) + try -{ + { - Data *dataPtr = NULL; + dataPtr = reinterpret_cast(const_cast(lvDataPtr)); - char *byteArrOut = NULL; + int byteArrLen = 0; - MgErr errorCode = noErr; + byteArrOut = dataPtr->serialize(&byteArrLen); - const char *errorSource = __FUNCTION__; + errorCode = + NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), + static_cast(byteArrLen)); - char const *errorMessage = (char *)""; + if (!errorCode) + { - try + for (int i = 0; i < byteArrLen; i++) - { + (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); - dataPtr = reinterpret_cast(const_cast(lvDataPtr)); + (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + } - int byteArrLen = 0; + else - byteArrOut = dataPtr->serialize(&byteArrLen); + errorMessage = (char *)"NumericArrayResize error"; - errorCode = - NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), - static_cast(byteArrLen)); + deleteNativeArray(byteArrOut); + } + catch (const MdsException &e) + { - if (!errorCode) { + errorCode = bogusError; - for (int i = 0; i < byteArrLen; i++) + errorMessage = e.what(); - (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); - (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; - - deleteNativeArray(byteArrOut); - - } catch (const MdsException &e) { - - errorCode = bogusError; - - errorMessage = e.what(); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + static void setAccessory(char const *src, ErrorCluster *error, void *outPtr, + void const *inPtr, void (Data::*setX)(Data *)) + { + MgErr errorCode = noErr; + char const *errorMessage = (char *)""; -static void setAccessory(char const *src, ErrorCluster *error, void *outPtr, - void const *inPtr, void (Data::*setX)(Data *)) { - MgErr errorCode = noErr; - char const *errorMessage = (char *)""; - - try { - Data *data = reinterpret_cast(outPtr); - (data->*setX)(reinterpret_cast(const_cast(inPtr))); - } catch (const MdsException &e) { - errorCode = bogusError; - errorMessage = e.what(); - fillErrorCluster(errorCode, src, errorMessage, error); - return; - } + try + { + Data *data = reinterpret_cast(outPtr); + (data->*setX)(reinterpret_cast(const_cast(inPtr))); + } + catch (const MdsException &e) + { + errorCode = bogusError; + errorMessage = e.what(); + fillErrorCluster(errorCode, src, errorMessage, error); + return; + } - fillErrorCluster(errorCode, src, errorMessage, error); -} + fillErrorCluster(errorCode, src, errorMessage, error); + } -EXPORT void mdsplus_data_setError(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error) { - setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setError); -} + EXPORT void mdsplus_data_setError(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error) + { + setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setError); + } -EXPORT void mdsplus_data_setHelp(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error) { - setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setHelp); -} + EXPORT void mdsplus_data_setHelp(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error) + { + setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setHelp); + } -EXPORT void mdsplus_data_setUnits(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error) { - setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setUnits); -} + EXPORT void mdsplus_data_setUnits(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error) + { + setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setUnits); + } -EXPORT void mdsplus_data_setValidation(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error) { - setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setValidation); -} + EXPORT void mdsplus_data_setValidation(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error) + { + setAccessory(__func__, error, lvDataPtr, lvDataPtrIn, &Data::setValidation); + } -/******************************************************************************************************** + /******************************************************************************************************** EMPTY ********************************************************************************************************/ -EXPORT void mdsplus_empty_destructor(void **lvEmptyPtr) { - deleteLvData(lvEmptyPtr); -} + EXPORT void mdsplus_empty_destructor(void **lvEmptyPtr) + { + deleteLvData(lvEmptyPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** FLOAT32 ********************************************************************************************************/ -EXPORT void mdsplus_float32_constructor(void **lvFloat32PtrOut, float valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvFloat32PtrOut, valIn); -} + EXPORT void mdsplus_float32_constructor(void **lvFloat32PtrOut, float valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvFloat32PtrOut, valIn); + } -EXPORT void mdsplus_float32_destructor(void **lvFloat32Ptr) { - deleteLvData(lvFloat32Ptr); -} + EXPORT void mdsplus_float32_destructor(void **lvFloat32Ptr) + { + deleteLvData(lvFloat32Ptr); + } -EXPORT void mdsplus_float32_getByte(const void *lvFloat32Ptr, char *byteOut, - ErrorCluster *error) { - *byteOut = getScalar(lvFloat32Ptr, &Data::getByte, __func__, error); -} + EXPORT void mdsplus_float32_getByte(const void *lvFloat32Ptr, char *byteOut, + ErrorCluster *error) + { + *byteOut = getScalar(lvFloat32Ptr, &Data::getByte, __func__, error); + } -EXPORT void mdsplus_float32_getDouble(const void *lvFloat32Ptr, - double *doubleOut, ErrorCluster *error) { - *doubleOut = - getScalar(lvFloat32Ptr, &Data::getDouble, __func__, error); -} + EXPORT void mdsplus_float32_getDouble(const void *lvFloat32Ptr, + double *doubleOut, ErrorCluster *error) + { + *doubleOut = + getScalar(lvFloat32Ptr, &Data::getDouble, __func__, error); + } -EXPORT void mdsplus_float32_getFloat(const void *lvFloat32Ptr, float *floatOut, - ErrorCluster *error) { - *floatOut = getScalar(lvFloat32Ptr, &Data::getFloat, __func__, error); -} + EXPORT void mdsplus_float32_getFloat(const void *lvFloat32Ptr, float *floatOut, + ErrorCluster *error) + { + *floatOut = getScalar(lvFloat32Ptr, &Data::getFloat, __func__, error); + } -EXPORT void mdsplus_float32_getInt(const void *lvFloat32Ptr, int *intOut, - ErrorCluster *error) { - *intOut = getScalar(lvFloat32Ptr, &Data::getInt, __func__, error); -} + EXPORT void mdsplus_float32_getInt(const void *lvFloat32Ptr, int *intOut, + ErrorCluster *error) + { + *intOut = getScalar(lvFloat32Ptr, &Data::getInt, __func__, error); + } -EXPORT void mdsplus_float32_getLong(const void *lvFloat32Ptr, int64_t *longOut, - ErrorCluster *error) { - *longOut = getScalar(lvFloat32Ptr, &Data::getLong, __func__, error); -} + EXPORT void mdsplus_float32_getLong(const void *lvFloat32Ptr, int64_t *longOut, + ErrorCluster *error) + { + *longOut = getScalar(lvFloat32Ptr, &Data::getLong, __func__, error); + } -EXPORT void mdsplus_float32_getShort(const void *lvFloat32Ptr, short *shortOut, - ErrorCluster *error) { - *shortOut = getScalar(lvFloat32Ptr, &Data::getShort, __func__, error); -} + EXPORT void mdsplus_float32_getShort(const void *lvFloat32Ptr, short *shortOut, + ErrorCluster *error) + { + *shortOut = getScalar(lvFloat32Ptr, &Data::getShort, __func__, error); + } -/******************************************************************************************************** + /******************************************************************************************************** FLOAT32ARRAY ********************************************************************************************************/ -EXPORT void mdsplus_float32array_constructor(void **lvFloat32ArrayPtrOut, - const LFltArrHdl lvFltArrHdlIn, - ErrorCluster *error) { - arrayConstructor(__func__, error, lvFloat32ArrayPtrOut, - lvFltArrHdlIn); -} + EXPORT void mdsplus_float32array_constructor(void **lvFloat32ArrayPtrOut, + const LFltArrHdl lvFltArrHdlIn, + ErrorCluster *error) + { + arrayConstructor(__func__, error, lvFloat32ArrayPtrOut, + lvFltArrHdlIn); + } -EXPORT void mdsplus_float32array_constructor_dims( - void **lvFloat32ArrayPtrOut, const LFltArrHdl lvFltArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) { - arrayConstructor(__func__, error, lvFloat32ArrayPtrOut, - lvFltArrHdlIn, lvIntArrHdlIn); -} + EXPORT void mdsplus_float32array_constructor_dims( + void **lvFloat32ArrayPtrOut, const LFltArrHdl lvFltArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) + { + arrayConstructor(__func__, error, lvFloat32ArrayPtrOut, + lvFltArrHdlIn, lvIntArrHdlIn); + } -EXPORT void mdsplus_float32array_destructor(void **lvFloat32ArrayPtr) { - deleteLvData(lvFloat32ArrayPtr); -} + EXPORT void mdsplus_float32array_destructor(void **lvFloat32ArrayPtr) + { + deleteLvData(lvFloat32ArrayPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** FLOAT64 ********************************************************************************************************/ -EXPORT void mdsplus_float64_constructor(void **lvFloat64PtrOut, double valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvFloat64PtrOut, valIn); -} + EXPORT void mdsplus_float64_constructor(void **lvFloat64PtrOut, double valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvFloat64PtrOut, valIn); + } -EXPORT void mdsplus_float64_destructor(void **lvFloat64Ptr) { - deleteLvData(lvFloat64Ptr); -} + EXPORT void mdsplus_float64_destructor(void **lvFloat64Ptr) + { + deleteLvData(lvFloat64Ptr); + } -EXPORT void mdsplus_float64_getByte(const void *lvFloat64Ptr, char *byteOut, - ErrorCluster *error) { - *byteOut = getScalar(lvFloat64Ptr, &Data::getByte, __func__, error); -} + EXPORT void mdsplus_float64_getByte(const void *lvFloat64Ptr, char *byteOut, + ErrorCluster *error) + { + *byteOut = getScalar(lvFloat64Ptr, &Data::getByte, __func__, error); + } -EXPORT void mdsplus_float64_getDouble(const void *lvFloat64Ptr, - double *doubleOut, ErrorCluster *error) { - *doubleOut = - getScalar(lvFloat64Ptr, &Data::getDouble, __func__, error); -} + EXPORT void mdsplus_float64_getDouble(const void *lvFloat64Ptr, + double *doubleOut, ErrorCluster *error) + { + *doubleOut = + getScalar(lvFloat64Ptr, &Data::getDouble, __func__, error); + } -EXPORT void mdsplus_float64_getFloat(const void *lvFloat64Ptr, float *floatOut, - ErrorCluster *error) { - *floatOut = getScalar(lvFloat64Ptr, &Data::getFloat, __func__, error); -} + EXPORT void mdsplus_float64_getFloat(const void *lvFloat64Ptr, float *floatOut, + ErrorCluster *error) + { + *floatOut = getScalar(lvFloat64Ptr, &Data::getFloat, __func__, error); + } -EXPORT void mdsplus_float64_getInt(const void *lvFloat64Ptr, int *intOut, - ErrorCluster *error) { - *intOut = getScalar(lvFloat64Ptr, &Data::getInt, __func__, error); -} + EXPORT void mdsplus_float64_getInt(const void *lvFloat64Ptr, int *intOut, + ErrorCluster *error) + { + *intOut = getScalar(lvFloat64Ptr, &Data::getInt, __func__, error); + } -EXPORT void mdsplus_float64_getLong(const void *lvFloat64Ptr, int64_t *longOut, - ErrorCluster *error) { - *longOut = getScalar(lvFloat64Ptr, &Data::getLong, __func__, error); -} + EXPORT void mdsplus_float64_getLong(const void *lvFloat64Ptr, int64_t *longOut, + ErrorCluster *error) + { + *longOut = getScalar(lvFloat64Ptr, &Data::getLong, __func__, error); + } -EXPORT void mdsplus_float64_getShort(const void *lvFloat64Ptr, short *shortOut, - ErrorCluster *error) { - *shortOut = getScalar(lvFloat64Ptr, &Data::getShort, __func__, error); -} + EXPORT void mdsplus_float64_getShort(const void *lvFloat64Ptr, short *shortOut, + ErrorCluster *error) + { + *shortOut = getScalar(lvFloat64Ptr, &Data::getShort, __func__, error); + } -/******************************************************************************************************** + /******************************************************************************************************** FLOAT64ARRAY ********************************************************************************************************/ -EXPORT void mdsplus_float64array_constructor(void **lvFloat64ArrayPtrOut, - const LDblArrHdl lvDblArrHdlIn, - ErrorCluster *error) { - arrayConstructor(__func__, error, lvFloat64ArrayPtrOut, - lvDblArrHdlIn); -} + EXPORT void mdsplus_float64array_constructor(void **lvFloat64ArrayPtrOut, + const LDblArrHdl lvDblArrHdlIn, + ErrorCluster *error) + { + arrayConstructor(__func__, error, lvFloat64ArrayPtrOut, + lvDblArrHdlIn); + } -EXPORT void mdsplus_float64array_constructor_dims( - void **lvFloat64ArrayPtrOut, const LDblArrHdl lvDblArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) { - arrayConstructor(__func__, error, lvFloat64ArrayPtrOut, - lvDblArrHdlIn, lvIntArrHdlIn); -} + EXPORT void mdsplus_float64array_constructor_dims( + void **lvFloat64ArrayPtrOut, const LDblArrHdl lvDblArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) + { + arrayConstructor(__func__, error, lvFloat64ArrayPtrOut, + lvDblArrHdlIn, lvIntArrHdlIn); + } -EXPORT void mdsplus_float64array_destructor(void **lvFloat64ArrayPtr) { - deleteLvData(lvFloat64ArrayPtr); -} + EXPORT void mdsplus_float64array_destructor(void **lvFloat64ArrayPtr) + { + deleteLvData(lvFloat64ArrayPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** INT16 ********************************************************************************************************/ -EXPORT void mdsplus_int16_constructor(void **lvInt16PtrOut, short valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvInt16PtrOut, valIn); -} + EXPORT void mdsplus_int16_constructor(void **lvInt16PtrOut, short valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvInt16PtrOut, valIn); + } -EXPORT void mdsplus_int16_destructor(void **lvInt16Ptr) { - deleteLvData(lvInt16Ptr); -} + EXPORT void mdsplus_int16_destructor(void **lvInt16Ptr) + { + deleteLvData(lvInt16Ptr); + } -EXPORT void mdsplus_int16_getByte(const void *lvInt16Ptr, char *byteOut, - ErrorCluster *error) + EXPORT void mdsplus_int16_getByte(const void *lvInt16Ptr, char *byteOut, + ErrorCluster *error) -{ + { - Int16 *int16Ptr = NULL; + Int16 *int16Ptr = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - *byteOut = int16Ptr->getByte(); + *byteOut = int16Ptr->getByte(); + } - } + catch (const MdsException &e) - catch (const MdsException &e) + { - { + errorCode = bogusError; - errorCode = bogusError; + errorMessage = const_cast(e.what()); - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void mdsplus_int16_getDouble(const void *lvInt16Ptr, double *doubleOut, + ErrorCluster *error) -EXPORT void mdsplus_int16_getDouble(const void *lvInt16Ptr, double *doubleOut, - ErrorCluster *error) + { -{ + Int16 *int16Ptr = NULL; - Int16 *int16Ptr = NULL; + MgErr errorCode = noErr; - MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; - const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; - char const *errorMessage = ""; + try - try + { - { + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + *doubleOut = int16Ptr->getDouble(); + } - *doubleOut = int16Ptr->getDouble(); + catch (const MdsException &e) - } + { - catch (const MdsException &e) + errorCode = bogusError; - { + errorMessage = const_cast(e.what()); - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + EXPORT void mdsplus_int16_getFloat(const void *lvInt16Ptr, float *floatOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int16_getFloat(const void *lvInt16Ptr, float *floatOut, - ErrorCluster *error) + Int16 *int16Ptr = NULL; -{ + MgErr errorCode = noErr; - Int16 *int16Ptr = NULL; + const char *errorSource = __FUNCTION__; - MgErr errorCode = noErr; + char const *errorMessage = ""; - const char *errorSource = __FUNCTION__; + try - char const *errorMessage = ""; + { - try + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - { + *floatOut = int16Ptr->getFloat(); + } - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + catch (const MdsException &e) - *floatOut = int16Ptr->getFloat(); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = const_cast(e.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorMessage = const_cast(e.what()); + EXPORT void mdsplus_int16_getInt(const void *lvInt16Ptr, int *intOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Int16 *int16Ptr = NULL; -EXPORT void mdsplus_int16_getInt(const void *lvInt16Ptr, int *intOut, - ErrorCluster *error) + MgErr errorCode = noErr; -{ + const char *errorSource = __FUNCTION__; - Int16 *int16Ptr = NULL; + char const *errorMessage = ""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - try + *intOut = int16Ptr->getInt(); + } - { + catch (const MdsException &e) - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + { - *intOut = int16Ptr->getInt(); + errorCode = bogusError; - } + errorMessage = const_cast(e.what()); - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_int16_getLong(const void *lvInt16Ptr, int64_t *longOut, + ErrorCluster *error) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Int16 *int16Ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_int16_getLong(const void *lvInt16Ptr, int64_t *longOut, - ErrorCluster *error) + const char *errorSource = __FUNCTION__; -{ + char const *errorMessage = ""; - Int16 *int16Ptr = NULL; + try - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - char const *errorMessage = ""; + *longOut = int16Ptr->getLong(); + } - try + catch (const MdsException &e) - { + { - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + errorCode = bogusError; - *longOut = int16Ptr->getLong(); + errorMessage = const_cast(e.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_int16_getShort(const void *lvInt16Ptr, short *shortOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + Int16 *int16Ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_int16_getShort(const void *lvInt16Ptr, short *shortOut, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Int16 *int16Ptr = NULL; + { - MgErr errorCode = noErr; + int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); - const char *errorSource = __FUNCTION__; + *shortOut = int16Ptr->getShort(); + } - char const *errorMessage = ""; + catch (const MdsException &e) - try + { - { + errorCode = bogusError; - int16Ptr = reinterpret_cast(const_cast(lvInt16Ptr)); + errorMessage = const_cast(e.what()); - *shortOut = int16Ptr->getShort(); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &e) + /******************************************************************************************************** - { + INT16ARRAY - errorCode = bogusError; + ********************************************************************************************************/ - errorMessage = const_cast(e.what()); + EXPORT void mdsplus_int16array_constructor(void **lvInt16ArrayPtrOut, + const LShtArrHdl lvShtArrHdlIn, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Int16Array *int16ArrayPtrOut = NULL; -/******************************************************************************************************** + short *int16Arr = NULL; - INT16ARRAY + MgErr errorCode = noErr; - ********************************************************************************************************/ + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_int16array_constructor(void **lvInt16ArrayPtrOut, - const LShtArrHdl lvShtArrHdlIn, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Int16Array *int16ArrayPtrOut = NULL; + { - short *int16Arr = NULL; + int int16ArrLen = static_cast((*lvShtArrHdlIn)->dimSize); - MgErr errorCode = noErr; + int16Arr = new short[int16ArrLen]; - const char *errorSource = __FUNCTION__; + for (int i = 0; i < int16ArrLen; i++) - char const *errorMessage = ""; + int16Arr[i] = static_cast((*lvShtArrHdlIn)->elt[i]); - try + int16ArrayPtrOut = new Int16Array(int16Arr, int16ArrLen); - { + delete[] int16Arr; - int int16ArrLen = static_cast((*lvShtArrHdlIn)->dimSize); + *lvInt16ArrayPtrOut = reinterpret_cast(int16ArrayPtrOut); + } - int16Arr = new short[int16ArrLen]; + catch (const MdsException &e) - for (int i = 0; i < int16ArrLen; i++) + { - int16Arr[i] = static_cast((*lvShtArrHdlIn)->elt[i]); + delete[] int16Arr; - int16ArrayPtrOut = new Int16Array(int16Arr, int16ArrLen); + errorCode = bogusError; - delete[] int16Arr; + errorMessage = const_cast(e.what()); - *lvInt16ArrayPtrOut = reinterpret_cast(int16ArrayPtrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &e) + EXPORT void mdsplus_int16array_constructor_dims(void **lvInt16ArrayPtrOut, + const LShtArrHdl lvShtArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error) - { + { - delete[] int16Arr; + Int16Array *int16ArrayPtrOut = NULL; - errorCode = bogusError; + short *int16Arr = NULL; - errorMessage = const_cast(e.what()); + int *intArr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_int16array_constructor_dims(void **lvInt16ArrayPtrOut, - const LShtArrHdl lvShtArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Int16Array *int16ArrayPtrOut = NULL; + { - short *int16Arr = NULL; + int int16ArrLen = static_cast((*lvShtArrHdlIn)->dimSize); - int *intArr = NULL; + int16Arr = new short[int16ArrLen]; - MgErr errorCode = noErr; + for (int i = 0; i < int16ArrLen; i++) - const char *errorSource = __FUNCTION__; + int16Arr[i] = static_cast((*lvShtArrHdlIn)->elt[i]); - char const *errorMessage = ""; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - try + intArr = new int[intArrLen]; - { + for (int i = 0; i < intArrLen; i++) - int int16ArrLen = static_cast((*lvShtArrHdlIn)->dimSize); + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - int16Arr = new short[int16ArrLen]; + int16ArrayPtrOut = new Int16Array(int16Arr, intArrLen, intArr); - for (int i = 0; i < int16ArrLen; i++) + delete[] int16Arr; - int16Arr[i] = static_cast((*lvShtArrHdlIn)->elt[i]); + delete[] intArr; - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + *lvInt16ArrayPtrOut = reinterpret_cast(int16ArrayPtrOut); + } - intArr = new int[intArrLen]; + catch (const MdsException &e) - for (int i = 0; i < intArrLen; i++) + { - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + delete[] int16Arr; - int16ArrayPtrOut = new Int16Array(int16Arr, intArrLen, intArr); + delete[] intArr; - delete[] int16Arr; + errorCode = bogusError; - delete[] intArr; + errorMessage = const_cast(e.what()); - *lvInt16ArrayPtrOut = reinterpret_cast(int16ArrayPtrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &e) + EXPORT void mdsplus_int16array_destructor(void **lvInt16ArrayPtr) + { + deleteLvData(lvInt16ArrayPtr); + } - { + /******************************************************************************************************** + INT32 + ********************************************************************************************************/ - delete[] int16Arr; + EXPORT void mdsplus_int32_constructor(void **lvInt32PtrOut, int valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvInt32PtrOut, valIn); + } - delete[] intArr; + EXPORT void mdsplus_int32_destructor(void **lvInt32Ptr) + { + deleteLvData(lvInt32Ptr); + } - errorCode = bogusError; + EXPORT void mdsplus_int32_getByte(const void *lvInt32Ptr, char *byteOut, + ErrorCluster *error) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Int32 *int32Ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_int16array_destructor(void **lvInt16ArrayPtr) { - deleteLvData(lvInt16ArrayPtr); -} + const char *errorSource = __FUNCTION__; -/******************************************************************************************************** - INT32 - ********************************************************************************************************/ + char const *errorMessage = ""; -EXPORT void mdsplus_int32_constructor(void **lvInt32PtrOut, int valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvInt32PtrOut, valIn); -} + try -EXPORT void mdsplus_int32_destructor(void **lvInt32Ptr) { - deleteLvData(lvInt32Ptr); -} + { -EXPORT void mdsplus_int32_getByte(const void *lvInt32Ptr, char *byteOut, - ErrorCluster *error) + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); -{ + *byteOut = int32Ptr->getByte(); + } - Int32 *int32Ptr = NULL; + catch (const MdsException &e) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + errorCode = bogusError; - char const *errorMessage = ""; + errorMessage = const_cast(e.what()); - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + EXPORT void mdsplus_int32_getDouble(const void *lvInt32Ptr, double *doubleOut, + ErrorCluster *error) - *byteOut = int32Ptr->getByte(); + { - } + Int32 *int32Ptr = NULL; - catch (const MdsException &e) + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - errorCode = bogusError; + char const *errorMessage = ""; - errorMessage = const_cast(e.what()); + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); -EXPORT void mdsplus_int32_getDouble(const void *lvInt32Ptr, double *doubleOut, - ErrorCluster *error) + *doubleOut = int32Ptr->getDouble(); + } -{ + catch (const MdsException &e) - Int32 *int32Ptr = NULL; + { - MgErr errorCode = noErr; + errorCode = bogusError; - const char *errorSource = __FUNCTION__; + errorMessage = const_cast(e.what()); - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_int32_getFloat(const void *lvInt32Ptr, float *floatOut, + ErrorCluster *error) - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + { - *doubleOut = int32Ptr->getDouble(); + Int32 *int32Ptr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *floatOut = int32Ptr->getFloat(); + } -EXPORT void mdsplus_int32_getFloat(const void *lvInt32Ptr, float *floatOut, - ErrorCluster *error) + catch (const MdsException &e) -{ + { - Int32 *int32Ptr = NULL; + errorCode = bogusError; - MgErr errorCode = noErr; + errorMessage = const_cast(e.what()); - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_int32_getInt(const void *lvInt32Ptr, int *intOut, + ErrorCluster *error) - { + { - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + Int32 *int32Ptr = NULL; - *floatOut = int32Ptr->getFloat(); + MgErr errorCode = noErr; - } + const char *errorSource = __FUNCTION__; - catch (const MdsException &e) + char const *errorMessage = ""; - { + try - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *intOut = int32Ptr->getInt(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_int32_getInt(const void *lvInt32Ptr, int *intOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Int32 *int32Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_int32_getLong(const void *lvInt32Ptr, int64_t *longOut, + ErrorCluster *error) - try + { - { + Int32 *int32Ptr = NULL; - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + MgErr errorCode = noErr; - *intOut = int32Ptr->getInt(); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); - errorMessage = const_cast(e.what()); + *longOut = int32Ptr->getLong(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int32_getLong(const void *lvInt32Ptr, int64_t *longOut, - ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - Int32 *int32Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_int32_getShort(const void *lvInt32Ptr, short *shortOut, + ErrorCluster *error) - char const *errorMessage = ""; + { - try + Int32 *int32Ptr = NULL; - { + MgErr errorCode = noErr; - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + const char *errorSource = __FUNCTION__; - *longOut = int32Ptr->getLong(); + char const *errorMessage = ""; - } + try - catch (const MdsException &e) + { - { + int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); - errorCode = bogusError; + *shortOut = int32Ptr->getShort(); + } - errorMessage = const_cast(e.what()); + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorCode = bogusError; -EXPORT void mdsplus_int32_getShort(const void *lvInt32Ptr, short *shortOut, - ErrorCluster *error) + errorMessage = const_cast(e.what()); -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - Int32 *int32Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - MgErr errorCode = noErr; + /******************************************************************************************************** - const char *errorSource = __FUNCTION__; + INT32ARRAY - char const *errorMessage = ""; + ********************************************************************************************************/ - try + EXPORT void mdsplus_int32array_constructor(void **lvInt32ArrayPtrOut, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error) - { + { - int32Ptr = reinterpret_cast(const_cast(lvInt32Ptr)); + Int32Array *int32ArrayPtrOut = NULL; - *shortOut = int32Ptr->getShort(); + int *int32Arr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + int int32ArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int32Arr = new int[int32ArrLen]; -/******************************************************************************************************** + for (int i = 0; i < int32ArrLen; i++) - INT32ARRAY + int32Arr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - ********************************************************************************************************/ + int32ArrayPtrOut = new Int32Array(int32Arr, int32ArrLen); -EXPORT void mdsplus_int32array_constructor(void **lvInt32ArrayPtrOut, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error) + delete[] int32Arr; -{ + *lvInt32ArrayPtrOut = reinterpret_cast(int32ArrayPtrOut); + } - Int32Array *int32ArrayPtrOut = NULL; + catch (const MdsException &e) - int *int32Arr = NULL; + { - MgErr errorCode = noErr; + delete[] int32Arr; - const char *errorSource = __FUNCTION__; + errorCode = bogusError; - char const *errorMessage = ""; + errorMessage = const_cast(e.what()); - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - int int32ArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + EXPORT void mdsplus_int32array_constructor_dims( + void **lvInt32ArrayPtrOut, const LIntArrHdl lvIntArrHdlIn, + const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error) - int32Arr = new int[int32ArrLen]; + { - for (int i = 0; i < int32ArrLen; i++) + Int32Array *int32ArrayPtrOut = NULL; - int32Arr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + int *int32Arr = NULL; - int32ArrayPtrOut = new Int32Array(int32Arr, int32ArrLen); + int *intArr = NULL; - delete[] int32Arr; + MgErr errorCode = noErr; - *lvInt32ArrayPtrOut = reinterpret_cast(int32ArrayPtrOut); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - delete[] int32Arr; + int int32ArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - errorCode = bogusError; + int32Arr = new int[int32ArrLen]; - errorMessage = const_cast(e.what()); + for (int i = 0; i < int32ArrLen; i++) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + int32Arr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int intArrLen = static_cast((*lvIntArrHdlDimIn)->dimSize); -EXPORT void mdsplus_int32array_constructor_dims( - void **lvInt32ArrayPtrOut, const LIntArrHdl lvIntArrHdlIn, - const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error) + intArr = new int[intArrLen]; -{ + for (int i = 0; i < intArrLen; i++) - Int32Array *int32ArrayPtrOut = NULL; + intArr[i] = static_cast((*lvIntArrHdlDimIn)->elt[i]); - int *int32Arr = NULL; + int32ArrayPtrOut = new Int32Array(int32Arr, intArrLen, intArr); - int *intArr = NULL; + delete[] int32Arr; - MgErr errorCode = noErr; + delete[] intArr; - const char *errorSource = __FUNCTION__; + *lvInt32ArrayPtrOut = reinterpret_cast(int32ArrayPtrOut); + } - char const *errorMessage = ""; + catch (const MdsException &e) - try + { - { + delete[] int32Arr; - int int32ArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + delete[] intArr; - int32Arr = new int[int32ArrLen]; + errorCode = bogusError; - for (int i = 0; i < int32ArrLen; i++) + errorMessage = const_cast(e.what()); - int32Arr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - int intArrLen = static_cast((*lvIntArrHdlDimIn)->dimSize); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - intArr = new int[intArrLen]; + EXPORT void mdsplus_int32array_destructor(void **lvInt32ArrayPtr) + { + deleteLvData(lvInt32ArrayPtr); + } - for (int i = 0; i < intArrLen; i++) + /******************************************************************************************************** + INT64 + ********************************************************************************************************/ - intArr[i] = static_cast((*lvIntArrHdlDimIn)->elt[i]); + EXPORT void mdsplus_int64_constructor(void **lvInt64PtrOut, int64_t valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvInt64PtrOut, valIn); + } - int32ArrayPtrOut = new Int32Array(int32Arr, intArrLen, intArr); + EXPORT void mdsplus_int64_destructor(void **lvInt64Ptr) + { + deleteLvData(lvInt64Ptr); + } - delete[] int32Arr; + EXPORT void mdsplus_int64_getByte(const void *lvInt64Ptr, char *byteOut, + ErrorCluster *error) - delete[] intArr; + { - *lvInt32ArrayPtrOut = reinterpret_cast(int32ArrayPtrOut); + Int64 *int64Ptr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - delete[] int32Arr; + try - delete[] intArr; + { - errorCode = bogusError; + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - errorMessage = const_cast(e.what()); + *byteOut = int64Ptr->getByte(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int32array_destructor(void **lvInt32ArrayPtr) { - deleteLvData(lvInt32ArrayPtr); -} + errorCode = bogusError; -/******************************************************************************************************** - INT64 - ********************************************************************************************************/ + errorMessage = const_cast(e.what()); -EXPORT void mdsplus_int64_constructor(void **lvInt64PtrOut, int64_t valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvInt64PtrOut, valIn); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_int64_destructor(void **lvInt64Ptr) { - deleteLvData(lvInt64Ptr); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_int64_getByte(const void *lvInt64Ptr, char *byteOut, - ErrorCluster *error) + EXPORT void mdsplus_int64_getDouble(const void *lvInt64Ptr, double *doubleOut, + ErrorCluster *error) -{ + { - Int64 *int64Ptr = NULL; + Int64 *int64Ptr = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - *byteOut = int64Ptr->getByte(); + *doubleOut = int64Ptr->getDouble(); + } - } + catch (const MdsException &e) - catch (const MdsException &e) + { - { + errorCode = bogusError; - errorCode = bogusError; + errorMessage = const_cast(e.what()); - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void mdsplus_int64_getFloat(const void *lvInt64Ptr, float *floatOut, + ErrorCluster *error) -EXPORT void mdsplus_int64_getDouble(const void *lvInt64Ptr, double *doubleOut, - ErrorCluster *error) + { -{ + Int64 *int64Ptr = NULL; - Int64 *int64Ptr = NULL; + MgErr errorCode = noErr; - MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; - const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; - char const *errorMessage = ""; + try - try + { - { + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + *floatOut = int64Ptr->getFloat(); + } - *doubleOut = int64Ptr->getDouble(); + catch (const MdsException &e) - } + { - catch (const MdsException &e) + errorCode = bogusError; - { + errorMessage = const_cast(e.what()); - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + EXPORT void mdsplus_int64_getInt(const void *lvInt64Ptr, int *intOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int64_getFloat(const void *lvInt64Ptr, float *floatOut, - ErrorCluster *error) + Int64 *int64Ptr = NULL; -{ + MgErr errorCode = noErr; - Int64 *int64Ptr = NULL; + const char *errorSource = __FUNCTION__; - MgErr errorCode = noErr; + char const *errorMessage = ""; - const char *errorSource = __FUNCTION__; + try - char const *errorMessage = ""; + { - try + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - { + *intOut = int64Ptr->getInt(); + } - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + catch (const MdsException &e) - *floatOut = int64Ptr->getFloat(); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = const_cast(e.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorMessage = const_cast(e.what()); + EXPORT void mdsplus_int64_getLong(const void *lvInt64Ptr, int64_t *longOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Int64 *int64Ptr = NULL; -EXPORT void mdsplus_int64_getInt(const void *lvInt64Ptr, int *intOut, - ErrorCluster *error) + MgErr errorCode = noErr; -{ + const char *errorSource = __FUNCTION__; - Int64 *int64Ptr = NULL; + char const *errorMessage = ""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - try + *longOut = int64Ptr->getLong(); + } - { + catch (const MdsException &e) - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + { - *intOut = int64Ptr->getInt(); + errorCode = bogusError; - } + errorMessage = const_cast(e.what()); - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_int64_getShort(const void *lvInt64Ptr, short *shortOut, + ErrorCluster *error) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Int64 *int64Ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_int64_getLong(const void *lvInt64Ptr, int64_t *longOut, - ErrorCluster *error) + const char *errorSource = __FUNCTION__; -{ + char const *errorMessage = ""; - Int64 *int64Ptr = NULL; + try - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); - char const *errorMessage = ""; + *shortOut = int64Ptr->getShort(); + } - try + catch (const MdsException &e) - { + { - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + errorCode = bogusError; - *longOut = int64Ptr->getLong(); + errorMessage = const_cast(e.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + /******************************************************************************************************** - errorCode = bogusError; + INT64ARRAY - errorMessage = const_cast(e.what()); + ********************************************************************************************************/ - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + EXPORT void mdsplus_int64array_constructor(void **lvInt64ArrayPtrOut, + const LLngArrHdl lvLngArrHdlIn, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int64_getShort(const void *lvInt64Ptr, short *shortOut, - ErrorCluster *error) + Int64Array *int64ArrayPtrOut = NULL; -{ + int64_t *int64Arr = NULL; - Int64 *int64Ptr = NULL; + MgErr errorCode = noErr; - MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; - const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; - char const *errorMessage = ""; + try - try + { - { + int int64ArrLen = static_cast((*lvLngArrHdlIn)->dimSize); - int64Ptr = reinterpret_cast(const_cast(lvInt64Ptr)); + int64Arr = new int64_t[int64ArrLen]; - *shortOut = int64Ptr->getShort(); + for (int i = 0; i < int64ArrLen; i++) - } + int64Arr[i] = static_cast((*lvLngArrHdlIn)->elt[i]); - catch (const MdsException &e) + int64ArrayPtrOut = new Int64Array(int64Arr, int64ArrLen); - { + delete[] int64Arr; - errorCode = bogusError; + *lvInt64ArrayPtrOut = reinterpret_cast(int64ArrayPtrOut); + } - errorMessage = const_cast(e.what()); + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + delete[] int64Arr; -/******************************************************************************************************** + errorCode = bogusError; - INT64ARRAY + errorMessage = const_cast(e.what()); + } - ********************************************************************************************************/ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_int64array_constructor(void **lvInt64ArrayPtrOut, - const LLngArrHdl lvLngArrHdlIn, - ErrorCluster *error) + EXPORT void mdsplus_int64array_constructor_dims(void **lvInt64ArrayPtrOut, + const LLngArrHdl lvLngArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error) -{ + { - Int64Array *int64ArrayPtrOut = NULL; + Int64Array *int64ArrayPtrOut = NULL; - int64_t *int64Arr = NULL; + int64_t *int64Arr = NULL; - MgErr errorCode = noErr; + int *intArr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int int64ArrLen = static_cast((*lvLngArrHdlIn)->dimSize); + { - int64Arr = new int64_t[int64ArrLen]; + int int64ArrLen = static_cast((*lvLngArrHdlIn)->dimSize); - for (int i = 0; i < int64ArrLen; i++) + int64Arr = new int64_t[int64ArrLen]; - int64Arr[i] = static_cast((*lvLngArrHdlIn)->elt[i]); + for (int i = 0; i < int64ArrLen; i++) - int64ArrayPtrOut = new Int64Array(int64Arr, int64ArrLen); + int64Arr[i] = static_cast((*lvLngArrHdlIn)->elt[i]); - delete[] int64Arr; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - *lvInt64ArrayPtrOut = reinterpret_cast(int64ArrayPtrOut); + intArr = new int[intArrLen]; - } + for (int i = 0; i < intArrLen; i++) - catch (const MdsException &e) + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - { + int64ArrayPtrOut = new Int64Array(int64Arr, intArrLen, intArr); - delete[] int64Arr; + delete[] int64Arr; - errorCode = bogusError; + delete[] intArr; - errorMessage = const_cast(e.what()); - } + *lvInt64ArrayPtrOut = reinterpret_cast(int64ArrayPtrOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_int64array_constructor_dims(void **lvInt64ArrayPtrOut, - const LLngArrHdl lvLngArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error) + { -{ + delete[] int64Arr; - Int64Array *int64ArrayPtrOut = NULL; + delete[] intArr; - int64_t *int64Arr = NULL; + errorCode = bogusError; - int *intArr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_int64array_destructor(void **lvInt64ArrayPtr) + { + deleteLvData(lvInt64ArrayPtr); + } - try + /******************************************************************************************************** - { + INT8 - int int64ArrLen = static_cast((*lvLngArrHdlIn)->dimSize); + ********************************************************************************************************/ - int64Arr = new int64_t[int64ArrLen]; + EXPORT void mdsplus_int8_constructor(void **lvInt8PtrOut, char valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvInt8PtrOut, valIn); + } - for (int i = 0; i < int64ArrLen; i++) + EXPORT void mdsplus_int8_destructor(void **lvInt8Ptr) + { + deleteLvData(lvInt8Ptr); + } - int64Arr[i] = static_cast((*lvLngArrHdlIn)->elt[i]); + EXPORT void mdsplus_int8_getByte(const void *lvInt8Ptr, char *byteOut, + ErrorCluster *error) - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + { - intArr = new int[intArrLen]; + Int8 *int8Ptr = NULL; - for (int i = 0; i < intArrLen; i++) + MgErr errorCode = noErr; - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + const char *errorSource = __FUNCTION__; - int64ArrayPtrOut = new Int64Array(int64Arr, intArrLen, intArr); + char const *errorMessage = ""; - delete[] int64Arr; + try - delete[] intArr; + { - *lvInt64ArrayPtrOut = reinterpret_cast(int64ArrayPtrOut); + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); - } + *byteOut = int8Ptr->getByte(); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - delete[] int64Arr; + errorCode = bogusError; - delete[] intArr; + errorMessage = const_cast(e.what()); - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + EXPORT void mdsplus_int8_getDouble(const void *lvInt8Ptr, double *doubleOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int64array_destructor(void **lvInt64ArrayPtr) { - deleteLvData(lvInt64ArrayPtr); -} + Int8 *int8Ptr = NULL; -/******************************************************************************************************** + MgErr errorCode = noErr; - INT8 + const char *errorSource = __FUNCTION__; - ********************************************************************************************************/ + char const *errorMessage = ""; -EXPORT void mdsplus_int8_constructor(void **lvInt8PtrOut, char valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvInt8PtrOut, valIn); -} + try -EXPORT void mdsplus_int8_destructor(void **lvInt8Ptr) { - deleteLvData(lvInt8Ptr); -} + { -EXPORT void mdsplus_int8_getByte(const void *lvInt8Ptr, char *byteOut, - ErrorCluster *error) + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); -{ + *doubleOut = int8Ptr->getDouble(); + } - Int8 *int8Ptr = NULL; + catch (const MdsException &e) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + errorCode = bogusError; - char const *errorMessage = ""; + errorMessage = const_cast(e.what()); - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + EXPORT void mdsplus_int8_getFloat(const void *lvInt8Ptr, float *floatOut, + ErrorCluster *error) - *byteOut = int8Ptr->getByte(); + { - } + Int8 *int8Ptr = NULL; - catch (const MdsException &e) + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - errorCode = bogusError; + char const *errorMessage = ""; - errorMessage = const_cast(e.what()); + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); -EXPORT void mdsplus_int8_getDouble(const void *lvInt8Ptr, double *doubleOut, - ErrorCluster *error) + *floatOut = int8Ptr->getFloat(); + } -{ + catch (const MdsException &e) - Int8 *int8Ptr = NULL; + { - MgErr errorCode = noErr; + errorCode = bogusError; - const char *errorSource = __FUNCTION__; + errorMessage = const_cast(e.what()); - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_int8_getInt(const void *lvInt8Ptr, int *intOut, + ErrorCluster *error) - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + { - *doubleOut = int8Ptr->getDouble(); + Int8 *int8Ptr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *intOut = int8Ptr->getInt(); + } -EXPORT void mdsplus_int8_getFloat(const void *lvInt8Ptr, float *floatOut, - ErrorCluster *error) + catch (const MdsException &e) -{ + { - Int8 *int8Ptr = NULL; + errorCode = bogusError; - MgErr errorCode = noErr; + errorMessage = const_cast(e.what()); - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_int8_getLong(const void *lvInt8Ptr, int64_t *longOut, + ErrorCluster *error) - { + { - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + Int8 *int8Ptr = NULL; - *floatOut = int8Ptr->getFloat(); + MgErr errorCode = noErr; - } + const char *errorSource = __FUNCTION__; - catch (const MdsException &e) + char const *errorMessage = ""; - { + try - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *longOut = int8Ptr->getLong(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_int8_getInt(const void *lvInt8Ptr, int *intOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Int8 *int8Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_int8_getShort(const void *lvInt8Ptr, short *shortOut, + ErrorCluster *error) - try + { - { + Int8 *int8Ptr = NULL; - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + MgErr errorCode = noErr; - *intOut = int8Ptr->getInt(); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); - errorMessage = const_cast(e.what()); + *shortOut = int8Ptr->getShort(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_int8_getLong(const void *lvInt8Ptr, int64_t *longOut, - ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - Int8 *int8Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + /******************************************************************************************************** - char const *errorMessage = ""; + INT8ARRAY - try + ********************************************************************************************************/ - { + EXPORT void mdsplus_int8array_constructor(void **lvInt8ArrayPtrOut, + const LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error) - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + { - *longOut = int8Ptr->getLong(); + Int8Array *int8ArrayPtrOut = NULL; - } + char *int8Arr = NULL; - catch (const MdsException &e) + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - errorCode = bogusError; + char const *errorMessage = ""; - errorMessage = const_cast(e.what()); + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int int8ArrLen = static_cast((*lvByteArrHdlIn)->dimSize); -EXPORT void mdsplus_int8_getShort(const void *lvInt8Ptr, short *shortOut, - ErrorCluster *error) + int8Arr = new char[int8ArrLen]; -{ + for (int i = 0; i < int8ArrLen; i++) - Int8 *int8Ptr = NULL; + int8Arr[i] = static_cast((*lvByteArrHdlIn)->elt[i]); - MgErr errorCode = noErr; + int8ArrayPtrOut = new Int8Array(int8Arr, int8ArrLen); - const char *errorSource = __FUNCTION__; + delete[] int8Arr; - char const *errorMessage = ""; + *lvInt8ArrayPtrOut = reinterpret_cast(int8ArrayPtrOut); + } - try + catch (const MdsException &e) - { + { - int8Ptr = reinterpret_cast(const_cast(lvInt8Ptr)); + delete[] int8Arr; - *shortOut = int8Ptr->getShort(); + errorCode = bogusError; - } + errorMessage = const_cast(e.what()); - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + EXPORT void mdsplus_int8array_constructor_dims(void **lvInt8ArrayPtrOut, + const LByteArrHdl lvByteArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Int8Array *int8ArrayPtrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char *int8Arr = NULL; -/******************************************************************************************************** + int *intArr = NULL; - INT8ARRAY + MgErr errorCode = noErr; - ********************************************************************************************************/ + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_int8array_constructor(void **lvInt8ArrayPtrOut, - const LByteArrHdl lvByteArrHdlIn, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Int8Array *int8ArrayPtrOut = NULL; + { - char *int8Arr = NULL; + int int8ArrLen = static_cast((*lvByteArrHdlIn)->dimSize); - MgErr errorCode = noErr; + int8Arr = new char[int8ArrLen]; - const char *errorSource = __FUNCTION__; + for (int i = 0; i < int8ArrLen; i++) - char const *errorMessage = ""; + int8Arr[i] = static_cast((*lvByteArrHdlIn)->elt[i]); - try + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - { + intArr = new int[intArrLen]; - int int8ArrLen = static_cast((*lvByteArrHdlIn)->dimSize); + for (int i = 0; i < intArrLen; i++) - int8Arr = new char[int8ArrLen]; + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - for (int i = 0; i < int8ArrLen; i++) + int8ArrayPtrOut = new Int8Array(int8Arr, intArrLen, intArr); - int8Arr[i] = static_cast((*lvByteArrHdlIn)->elt[i]); + delete[] int8Arr; - int8ArrayPtrOut = new Int8Array(int8Arr, int8ArrLen); + delete[] intArr; - delete[] int8Arr; + *lvInt8ArrayPtrOut = reinterpret_cast(int8ArrayPtrOut); + } - *lvInt8ArrayPtrOut = reinterpret_cast(int8ArrayPtrOut); + catch (const MdsException &e) - } + { - catch (const MdsException &e) + delete[] int8Arr; - { + delete[] intArr; - delete[] int8Arr; + errorCode = bogusError; - errorCode = bogusError; + errorMessage = const_cast(e.what()); - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void mdsplus_int8array_destructor(void **lvInt8ArrayPtr) + { + deleteLvData(lvInt8ArrayPtr); + } -EXPORT void mdsplus_int8array_constructor_dims(void **lvInt8ArrayPtrOut, - const LByteArrHdl lvByteArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error) + /******************************************************************************************************** -{ + RANGE - Int8Array *int8ArrayPtrOut = NULL; + ********************************************************************************************************/ - char *int8Arr = NULL; + EXPORT void + mdsplus_range_constructor(void **lvRangePtrOut, const void *lvBeginDataPtrIn, + const void *lvEndingDataPtrIn, + const void *lvDeltaValDataPtrIn, ErrorCluster *error) - int *intArr = NULL; + { - MgErr errorCode = noErr; + Range *rangePtrOut = NULL; - const char *errorSource = __FUNCTION__; + Data *beginDataPtrIn = NULL; - char const *errorMessage = ""; + Data *endingDataPtrIn = NULL; - try + Data *deltaValDataPtrIn = NULL; - { + MgErr errorCode = noErr; - int int8ArrLen = static_cast((*lvByteArrHdlIn)->dimSize); + const char *errorSource = __FUNCTION__; - int8Arr = new char[int8ArrLen]; + char const *errorMessage = ""; - for (int i = 0; i < int8ArrLen; i++) + try - int8Arr[i] = static_cast((*lvByteArrHdlIn)->elt[i]); + { - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + beginDataPtrIn = + reinterpret_cast(const_cast(lvBeginDataPtrIn)); - intArr = new int[intArrLen]; + endingDataPtrIn = + reinterpret_cast(const_cast(lvEndingDataPtrIn)); - for (int i = 0; i < intArrLen; i++) + deltaValDataPtrIn = + reinterpret_cast(const_cast(lvDeltaValDataPtrIn)); - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + rangePtrOut = new Range(beginDataPtrIn, endingDataPtrIn, deltaValDataPtrIn); - int8ArrayPtrOut = new Int8Array(int8Arr, intArrLen, intArr); + *lvRangePtrOut = reinterpret_cast(rangePtrOut); + } - delete[] int8Arr; + catch (const MdsException &e) - delete[] intArr; + { - *lvInt8ArrayPtrOut = reinterpret_cast(int8ArrayPtrOut); + errorCode = bogusError; - } + errorMessage = const_cast(e.what()); - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - delete[] int8Arr; + EXPORT void mdsplus_range_destructor(void **lvRangePtr, ErrorCluster *error) + { + deleteLvData(lvRangePtr); + } - delete[] intArr; + EXPORT void mdsplus_range_getBegin(const void *lvRangePtr, void **lvDataPtrOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + Range *rangePtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Data *dataPtrOut = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_int8array_destructor(void **lvInt8ArrayPtr) { - deleteLvData(lvInt8ArrayPtr); -} + const char *errorSource = __FUNCTION__; -/******************************************************************************************************** + char const *errorMessage = ""; - RANGE + try - ********************************************************************************************************/ + { -EXPORT void -mdsplus_range_constructor(void **lvRangePtrOut, const void *lvBeginDataPtrIn, - const void *lvEndingDataPtrIn, - const void *lvDeltaValDataPtrIn, ErrorCluster *error) + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); -{ + dataPtrOut = rangePtr->getBegin(); - Range *rangePtrOut = NULL; + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - Data *beginDataPtrIn = NULL; + catch (const MdsException &e) - Data *endingDataPtrIn = NULL; + { - Data *deltaValDataPtrIn = NULL; + errorCode = bogusError; - MgErr errorCode = noErr; + errorMessage = const_cast(e.what()); - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_range_getEnding(const void *lvRangePtr, void **lvDataPtrOut, + ErrorCluster *error) - { + { - beginDataPtrIn = - reinterpret_cast(const_cast(lvBeginDataPtrIn)); + Range *rangePtr = NULL; - endingDataPtrIn = - reinterpret_cast(const_cast(lvEndingDataPtrIn)); + Data *dataPtrOut = NULL; - deltaValDataPtrIn = - reinterpret_cast(const_cast(lvDeltaValDataPtrIn)); + MgErr errorCode = noErr; - rangePtrOut = new Range(beginDataPtrIn, endingDataPtrIn, deltaValDataPtrIn); + const char *errorSource = __FUNCTION__; - *lvRangePtrOut = reinterpret_cast(rangePtrOut); + char const *errorMessage = ""; - } + try - catch (const MdsException &e) + { - { + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); - errorCode = bogusError; + dataPtrOut = rangePtr->getEnding(); - errorMessage = const_cast(e.what()); + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_range_destructor(void **lvRangePtr, ErrorCluster *error) { - deleteLvData(lvRangePtr); -} + errorCode = bogusError; -EXPORT void mdsplus_range_getBegin(const void *lvRangePtr, void **lvDataPtrOut, - ErrorCluster *error) + errorMessage = const_cast(e.what()); -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - Range *rangePtr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Data *dataPtrOut = NULL; + EXPORT void mdsplus_range_getDeltaVal(const void *lvRangePtr, + void **lvDataPtrOut, ErrorCluster *error) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + Range *rangePtr = NULL; - char const *errorMessage = ""; + Data *dataPtrOut = NULL; - try + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + char const *errorMessage = ""; - dataPtrOut = rangePtr->getBegin(); + try - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + { - } + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); - catch (const MdsException &e) + dataPtrOut = rangePtr->getDeltaVal(); - { + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - errorCode = bogusError; + catch (const MdsException &e) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorMessage = const_cast(e.what()); -EXPORT void mdsplus_range_getEnding(const void *lvRangePtr, void **lvDataPtrOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Range *rangePtr = NULL; + EXPORT void mdsplus_range_setBegin(const void *lvRangePtr, + const void *lvDataPtrIn, ErrorCluster *error) - Data *dataPtrOut = NULL; + { - MgErr errorCode = noErr; + Range *rangePtr = NULL; - const char *errorSource = __FUNCTION__; + Data *dataPtrIn = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + try - dataPtrOut = rangePtr->getEnding(); + { - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); - } + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - catch (const MdsException &e) + rangePtr->setBegin(dataPtrIn); + } - { + catch (const MdsException &e) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_range_getDeltaVal(const void *lvRangePtr, - void **lvDataPtrOut, ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_range_setEnding(const void *lvRangePtr, + const void *lvDataPtrIn, + ErrorCluster *error) - Range *rangePtr = NULL; + { - Data *dataPtrOut = NULL; + Range *rangePtr = NULL; - MgErr errorCode = noErr; + Data *dataPtrIn = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + { - dataPtrOut = rangePtr->getDeltaVal(); + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - } + rangePtr->setEnding(dataPtrIn); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_range_setBegin(const void *lvRangePtr, - const void *lvDataPtrIn, ErrorCluster *error) + EXPORT void mdsplus_range_setDeltaVal(const void *lvRangePtr, + const void *lvDataPtrIn, + ErrorCluster *error) -{ + { - Range *rangePtr = NULL; + Range *rangePtr = NULL; - Data *dataPtrIn = NULL; + Data *dataPtrIn = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + rangePtr = reinterpret_cast(const_cast(lvRangePtr)); - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - rangePtr->setBegin(dataPtrIn); + rangePtr->setDeltaVal(dataPtrIn); + } - } + catch (const MdsException &e) - catch (const MdsException &e) + { - { + errorCode = bogusError; - errorCode = bogusError; + errorMessage = const_cast(e.what()); - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + /******************************************************************************************************** -EXPORT void mdsplus_range_setEnding(const void *lvRangePtr, - const void *lvDataPtrIn, - ErrorCluster *error) + SIGNAL -{ + ********************************************************************************************************/ - Range *rangePtr = NULL; + EXPORT void + mdsplus_signal_constructor(void **lvSignalPtrOut, const void *lvDataPtrIn, + const void *lvRawPtrIn, const void *lvDim0PtrIn, + ErrorCluster *error) - Data *dataPtrIn = NULL; + { - MgErr errorCode = noErr; + Signal *signalPtrOut = NULL; - const char *errorSource = __FUNCTION__; + Data *dataPtrIn = NULL; - char const *errorMessage = ""; + Data *rawPtrIn = NULL; - try + Data *dim0PtrIn = NULL; - { + MgErr errorCode = noErr; - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + const char *errorSource = __FUNCTION__; - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + char const *errorMessage = ""; - rangePtr->setEnding(dataPtrIn); + try - } + { - catch (const MdsException &e) + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - { + rawPtrIn = reinterpret_cast(const_cast(lvRawPtrIn)); - errorCode = bogusError; + dim0PtrIn = reinterpret_cast(const_cast(lvDim0PtrIn)); - errorMessage = const_cast(e.what()); + signalPtrOut = new Signal(dataPtrIn, rawPtrIn, dim0PtrIn); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *lvSignalPtrOut = reinterpret_cast(signalPtrOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_range_setDeltaVal(const void *lvRangePtr, - const void *lvDataPtrIn, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Range *rangePtr = NULL; + errorMessage = const_cast(e.what()); - Data *dataPtrIn = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_signal_destructor(void **lvSignalPtr, ErrorCluster *error) + { + deleteLvData(lvSignalPtr); + } - char const *errorMessage = ""; + EXPORT void mdsplus_signal_getData(const void *lvSignalPtr, void **lvDataPtrOut, + ErrorCluster *error) - try + { - { + Signal *signalPtr = NULL; - rangePtr = reinterpret_cast(const_cast(lvRangePtr)); + Data *dataPtrOut = NULL; - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + MgErr errorCode = noErr; - rangePtr->setDeltaVal(dataPtrIn); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - errorMessage = const_cast(e.what()); + dataPtrOut = signalPtr->getData(); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -/******************************************************************************************************** + { - SIGNAL + errorCode = bogusError; - ********************************************************************************************************/ + errorMessage = const_cast(e.what()); -EXPORT void -mdsplus_signal_constructor(void **lvSignalPtrOut, const void *lvDataPtrIn, - const void *lvRawPtrIn, const void *lvDim0PtrIn, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Signal *signalPtrOut = NULL; + EXPORT void mdsplus_signal_getRaw(const void *lvSignalPtr, void **lvRawPtrOut, + ErrorCluster *error) - Data *dataPtrIn = NULL; + { - Data *rawPtrIn = NULL; + Signal *signalPtr = NULL; - Data *dim0PtrIn = NULL; + Data *rawPtrOut = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - rawPtrIn = reinterpret_cast(const_cast(lvRawPtrIn)); + rawPtrOut = signalPtr->getRaw(); - dim0PtrIn = reinterpret_cast(const_cast(lvDim0PtrIn)); + *lvRawPtrOut = reinterpret_cast(rawPtrOut); + } - signalPtrOut = new Signal(dataPtrIn, rawPtrIn, dim0PtrIn); + catch (const MdsException &e) - *lvSignalPtrOut = reinterpret_cast(signalPtrOut); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = const_cast(e.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorMessage = const_cast(e.what()); + EXPORT void mdsplus_signal_getDim(const void *lvSignalPtr, void **lvDim0PtrOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Signal *signalPtr = NULL; -EXPORT void mdsplus_signal_destructor(void **lvSignalPtr, ErrorCluster *error) { - deleteLvData(lvSignalPtr); -} + Data *dim0PtrOut = NULL; -EXPORT void mdsplus_signal_getData(const void *lvSignalPtr, void **lvDataPtrOut, - ErrorCluster *error) + MgErr errorCode = noErr; -{ + const char *errorSource = __FUNCTION__; - Signal *signalPtr = NULL; + char const *errorMessage = ""; - Data *dataPtrOut = NULL; + try - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - char const *errorMessage = ""; + dim0PtrOut = signalPtr->getDimensionAt(0); - try + *lvDim0PtrOut = reinterpret_cast(dim0PtrOut); + } - { + catch (const MdsException &e) - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + { - dataPtrOut = signalPtr->getData(); + errorCode = bogusError; - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + errorMessage = const_cast(e.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_signal_setData(const void *lvSignalPtr, + const void *lvDataPtrIn, ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + Signal *signalPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + Data *dataPtrIn = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + MgErr errorCode = noErr; -EXPORT void mdsplus_signal_getRaw(const void *lvSignalPtr, void **lvRawPtrOut, - ErrorCluster *error) + const char *errorSource = __FUNCTION__; -{ + char const *errorMessage = ""; - Signal *signalPtr = NULL; + try - Data *rawPtrOut = NULL; + { - MgErr errorCode = noErr; + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - const char *errorSource = __FUNCTION__; + dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); - char const *errorMessage = ""; + signalPtr->setData(dataPtrIn); + } - try + catch (const MdsException &e) - { + { - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + errorCode = bogusError; - rawPtrOut = signalPtr->getRaw(); + errorMessage = const_cast(e.what()); - *lvRawPtrOut = reinterpret_cast(rawPtrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - catch (const MdsException &e) + EXPORT void mdsplus_signal_setRaw(const void *lvSignalPtr, + const void *lvRawPtrIn, ErrorCluster *error) - { + { - errorCode = bogusError; + Signal *signalPtr = NULL; - errorMessage = const_cast(e.what()); + Data *rawPtrIn = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_signal_getDim(const void *lvSignalPtr, void **lvDim0PtrOut, - ErrorCluster *error) + char const *errorMessage = ""; -{ + try - Signal *signalPtr = NULL; + { - Data *dim0PtrOut = NULL; + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - MgErr errorCode = noErr; + rawPtrIn = reinterpret_cast(const_cast(lvRawPtrIn)); - const char *errorSource = __FUNCTION__; + signalPtr->setRaw(rawPtrIn); + } - char const *errorMessage = ""; + catch (const MdsException &e) - try + { - { + errorCode = bogusError; - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + errorMessage = const_cast(e.what()); - dim0PtrOut = signalPtr->getDimensionAt(0); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - *lvDim0PtrOut = reinterpret_cast(dim0PtrOut); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - } + EXPORT void mdsplus_signal_setDim(const void *lvSignalPtr, + const void *lvDim0PtrIn, ErrorCluster *error) - catch (const MdsException &e) + { - { + Signal *signalPtr = NULL; - errorCode = bogusError; + Data *dim0PtrIn = NULL; - errorMessage = const_cast(e.what()); + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = ""; -EXPORT void mdsplus_signal_setData(const void *lvSignalPtr, - const void *lvDataPtrIn, ErrorCluster *error) + try -{ + { - Signal *signalPtr = NULL; + signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); - Data *dataPtrIn = NULL; + dim0PtrIn = reinterpret_cast(const_cast(lvDim0PtrIn)); - MgErr errorCode = noErr; + signalPtr->setDimensionAt(dim0PtrIn, 0); + } - const char *errorSource = __FUNCTION__; + catch (const MdsException &e) - char const *errorMessage = ""; + { - try + errorCode = bogusError; - { + errorMessage = const_cast(e.what()); - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - signalPtr->setData(dataPtrIn); + /******************************************************************************************************** + SCALAR + ********************************************************************************************************/ - } + EXPORT void mdsplus_scalar_constructor(void **lvScalarPtrOut, + ErrorCluster *error) + { + safeCall(__func__, error, Constructor(lvScalarPtrOut)); + } - catch (const MdsException &e) + EXPORT void mdsplus_scalar_destructor(void **lvScalarPtr) + { + deleteLvData(lvScalarPtr); + } - { + EXPORT void mdsplus_scalar_getInfo(const void *lvScalarPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + Scalar *scalarPtr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + char nDims = 0; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + int *dims = NULL; -EXPORT void mdsplus_signal_setRaw(const void *lvSignalPtr, - const void *lvRawPtrIn, ErrorCluster *error) + void *ptr = NULL; -{ + MgErr errorCode = noErr; - Signal *signalPtr = NULL; + const char *errorSource = __FUNCTION__; - Data *rawPtrIn = NULL; + char const *errorMessage = ""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + scalarPtr = reinterpret_cast(const_cast(lvScalarPtr)); - try + scalarPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); - { + errorCode = + NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), + static_cast(nDims)); - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + if (!errorCode) + { - rawPtrIn = reinterpret_cast(const_cast(lvRawPtrIn)); + for (int i = 0; i < nDims; i++) - signalPtr->setRaw(rawPtrIn); + (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); - } + (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + } - catch (const MdsException &e) + else - { + errorMessage = (char *)"NumericArrayResize error"; - errorCode = bogusError; + // ptr is not returned - errorMessage = const_cast(e.what()); + deleteNativeArray(dims); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_signal_setDim(const void *lvSignalPtr, - const void *lvDim0PtrIn, ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - Signal *signalPtr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - Data *dim0PtrIn = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - MgErr errorCode = noErr; + /******************************************************************************************************** + STRING + ********************************************************************************************************/ - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_string_constructor(void **lvStringPtrOut, const char *valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvStringPtrOut, valIn); + } - char const *errorMessage = ""; + EXPORT void mdsplus_string_constructor_len(void **lvStringPtrOut, + const LUByteArrHdl lvUByteArrHdlIn, + ErrorCluster *error) + { + arrayConstructor(__func__, error, lvStringPtrOut, lvUByteArrHdlIn); + } - try + EXPORT void mdsplus_string_destructor(void **lvStringPtr) + { + deleteLvData(lvStringPtr); + } - { + struct StringEquals : public Lambda + { + StringEquals(void *in1Ptr, void *in2Ptr, LVBoolean *&outPtr) + : in1Ptr(in1Ptr), in2Ptr(in2Ptr), outPtr(outPtr) {} + void *in1Ptr; + void *in2Ptr; + LVBoolean *&outPtr; - signalPtr = reinterpret_cast(const_cast(lvSignalPtr)); + void operator()() + { + if (reinterpret_cast(in1Ptr)->equals( + reinterpret_cast(in2Ptr))) + *outPtr = TRUE; + else + *outPtr = FALSE; + } + }; - dim0PtrIn = reinterpret_cast(const_cast(lvDim0PtrIn)); + EXPORT void mdsplus_string_equals(const void *lvStringPtr, LVBoolean *equalsOut, + const void *lvDataPtrIn, + ErrorCluster *error) + { + safeCall(__func__, error, + StringEquals(const_cast(lvStringPtr), + const_cast(lvDataPtrIn), equalsOut)); + } - signalPtr->setDimensionAt(dim0PtrIn, 0); + EXPORT void mdsplus_string_getString(const void *lvStringPtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error) - } + { - catch (const MdsException &e) + String *stringPtr = NULL; - { + char *strOut = NULL; - errorCode = bogusError; + MgErr errorCode = noErr; - errorMessage = const_cast(e.what()); + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + char const *errorMessage = ""; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + try -/******************************************************************************************************** - SCALAR - ********************************************************************************************************/ + { -EXPORT void mdsplus_scalar_constructor(void **lvScalarPtrOut, - ErrorCluster *error) { - safeCall(__func__, error, Constructor(lvScalarPtrOut)); -} + stringPtr = reinterpret_cast(const_cast(lvStringPtr)); -EXPORT void mdsplus_scalar_destructor(void **lvScalarPtr) { - deleteLvData(lvScalarPtr); -} + strOut = stringPtr->getString(); -EXPORT void mdsplus_scalar_getInfo(const void *lvScalarPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error) + std::size_t strOutLen = std::strlen(strOut); -{ + errorCode = + NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), + strOutLen + sizeof(int32)); - Scalar *scalarPtr = NULL; + if (!errorCode) - char nDims = 0; + { - int *dims = NULL; + MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), + strOutLen); - void *ptr = NULL; + (*lvStrHdlOut)->cnt = strOutLen; + } - MgErr errorCode = noErr; + else - const char *errorSource = __FUNCTION__; + errorMessage = (char *)"NumericArrayResize error"; - char const *errorMessage = ""; + deleteNativeArray(strOut); + } - try + catch (const MdsException &e) - { + { - scalarPtr = reinterpret_cast(const_cast(lvScalarPtr)); + errorCode = bogusError; - scalarPtr->getInfo(clazzOut, dtypeOut, lengthOut, &nDims, &dims, &ptr); + errorMessage = const_cast(e.what()); - errorCode = - NumericArrayResize(iL, 1, reinterpret_cast(&lvIntArrHdlOut), - static_cast(nDims)); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - if (!errorCode) { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - for (int i = 0; i < nDims; i++) + /******************************************************************************************************** - (*lvIntArrHdlOut)->elt[i] = static_cast(dims[i]); + STRINGARRAY - (*lvIntArrHdlOut)->dimSize = static_cast(nDims); + ********************************************************************************************************/ - } + EXPORT void mdsplus_stringarray_constructor(void **lvStringArrayPtrOut, + const LStrArrHdl lvLStrArrHdlIn, + ErrorCluster *error) - else + { - errorMessage = (char *)"NumericArrayResize error"; + StringArray *stringArrayPtrOut = NULL; - // ptr is not returned + char **stringArr = NULL; - deleteNativeArray(dims); + int stringArrLen = 0; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + stringArrLen = static_cast((*lvLStrArrHdlIn)->dimSize); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + stringArr = new char *[stringArrLen]; -/******************************************************************************************************** - STRING - ********************************************************************************************************/ + LStrHandle currLStrHdl = NULL; -EXPORT void mdsplus_string_constructor(void **lvStringPtrOut, const char *valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvStringPtrOut, valIn); -} + char *currStr = NULL; -EXPORT void mdsplus_string_constructor_len(void **lvStringPtrOut, - const LUByteArrHdl lvUByteArrHdlIn, - ErrorCluster *error) { - arrayConstructor(__func__, error, lvStringPtrOut, lvUByteArrHdlIn); -} + int currStrLen = 0; -EXPORT void mdsplus_string_destructor(void **lvStringPtr) { - deleteLvData(lvStringPtr); -} + for (int i = 0; i < stringArrLen; i++) -struct StringEquals : public Lambda { - StringEquals(void *in1Ptr, void *in2Ptr, LVBoolean *&outPtr) - : in1Ptr(in1Ptr), in2Ptr(in2Ptr), outPtr(outPtr) {} - void *in1Ptr; - void *in2Ptr; - LVBoolean *&outPtr; - - void operator()() { - if (reinterpret_cast(in1Ptr)->equals( - reinterpret_cast(in2Ptr))) - *outPtr = TRUE; - else - *outPtr = FALSE; - } -}; - -EXPORT void mdsplus_string_equals(const void *lvStringPtr, LVBoolean *equalsOut, - const void *lvDataPtrIn, - ErrorCluster *error) { - safeCall(__func__, error, - StringEquals(const_cast(lvStringPtr), - const_cast(lvDataPtrIn), equalsOut)); -} + { -EXPORT void mdsplus_string_getString(const void *lvStringPtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error) + currLStrHdl = (*lvLStrArrHdlIn)->elm[i]; -{ + currStrLen = static_cast((*currLStrHdl)->cnt); - String *stringPtr = NULL; + currStr = new char[currStrLen + 1]; - char *strOut = NULL; + for (int j = 0; j < currStrLen; j++) - MgErr errorCode = noErr; + currStr[j] = static_cast((*currLStrHdl)->str[j]); - const char *errorSource = __FUNCTION__; + currStr[currStrLen] = 0; - char const *errorMessage = ""; + stringArr[i] = currStr; + } - try + stringArrayPtrOut = new StringArray(stringArr, stringArrLen); - { + for (int i = 0; i < stringArrLen; i++) - stringPtr = reinterpret_cast(const_cast(lvStringPtr)); + delete[] stringArr[i]; - strOut = stringPtr->getString(); + delete[] stringArr; - std::size_t strOutLen = std::strlen(strOut); + *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); + } - errorCode = - NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), - strOutLen + sizeof(int32)); + catch (const MdsException &e) - if (!errorCode) + { - { + errorCode = bogusError; - MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), - strOutLen); + errorMessage = const_cast(e.what()); - (*lvStrHdlOut)->cnt = strOutLen; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - else - - errorMessage = (char *)"NumericArrayResize error"; + EXPORT void + mdsplus_stringarray_constructor_stringLen(void **lvStringArrayPtrOut, + const char *dataIn, int nStringsIn, + int stringLenIn, ErrorCluster *error) - deleteNativeArray(strOut); + { - } + StringArray *stringArrayPtrOut = NULL; - catch (const MdsException &e) + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - errorCode = bogusError; + char const *errorMessage = ""; - errorMessage = const_cast(e.what()); + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + stringArrayPtrOut = + new StringArray(const_cast(dataIn), nStringsIn, stringLenIn); -/******************************************************************************************************** + *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); + } - STRINGARRAY + catch (const MdsException &e) - ********************************************************************************************************/ + { -EXPORT void mdsplus_stringarray_constructor(void **lvStringArrayPtrOut, - const LStrArrHdl lvLStrArrHdlIn, - ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - StringArray *stringArrayPtrOut = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char **stringArr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - int stringArrLen = 0; + EXPORT void mdsplus_stringarray_destructor(void **lvStringArrayPtr) + { + deleteLvData(lvStringArrayPtr); + } - MgErr errorCode = noErr; + /******************************************************************************************************** + UINT16 + ********************************************************************************************************/ - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_uint16_constructor(void **lvUint16PtrOut, + unsigned short valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvUint16PtrOut, valIn); + } - char const *errorMessage = ""; + EXPORT void mdsplus_uint16_destructor(void **lvUint16Ptr) + { + deleteLvData(lvUint16Ptr); + } - try + EXPORT void mdsplus_uint16_getByte(const void *lvUint16Ptr, char *byteOut, + ErrorCluster *error) - { + { - stringArrLen = static_cast((*lvLStrArrHdlIn)->dimSize); + Uint16 *uint16Ptr = NULL; - stringArr = new char *[stringArrLen]; + MgErr errorCode = noErr; - LStrHandle currLStrHdl = NULL; + const char *errorSource = __FUNCTION__; - char *currStr = NULL; + char const *errorMessage = ""; - int currStrLen = 0; + try - for (int i = 0; i < stringArrLen; i++) + { - { + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - currLStrHdl = (*lvLStrArrHdlIn)->elm[i]; + *byteOut = uint16Ptr->getByte(); + } - currStrLen = static_cast((*currLStrHdl)->cnt); + catch (const MdsException &e) - currStr = new char[currStrLen + 1]; + { - for (int j = 0; j < currStrLen; j++) + errorCode = bogusError; - currStr[j] = static_cast((*currLStrHdl)->str[j]); + errorMessage = const_cast(e.what()); - currStr[currStrLen] = 0; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - stringArr[i] = currStr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); } - stringArrayPtrOut = new StringArray(stringArr, stringArrLen); + EXPORT void mdsplus_uint16_getDouble(const void *lvUint16Ptr, double *doubleOut, + ErrorCluster *error) - for (int i = 0; i < stringArrLen; i++) + { - delete[] stringArr[i]; + Uint16 *uint16Ptr = NULL; - delete[] stringArr; + MgErr errorCode = noErr; - *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - errorMessage = const_cast(e.what()); + *doubleOut = uint16Ptr->getDouble(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void -mdsplus_stringarray_constructor_stringLen(void **lvStringArrayPtrOut, - const char *dataIn, int nStringsIn, - int stringLenIn, ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - StringArray *stringArrayPtrOut = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_uint16_getFloat(const void *lvUint16Ptr, float *floatOut, + ErrorCluster *error) - char const *errorMessage = ""; + { - try + Uint16 *uint16Ptr = NULL; - { + MgErr errorCode = noErr; - stringArrayPtrOut = - new StringArray(const_cast(dataIn), nStringsIn, stringLenIn); + const char *errorSource = __FUNCTION__; - *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); + char const *errorMessage = ""; - } + try - catch (const MdsException &e) + { - { + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - errorCode = bogusError; + *floatOut = uint16Ptr->getFloat(); + } - errorMessage = const_cast(e.what()); + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorCode = bogusError; -EXPORT void mdsplus_stringarray_destructor(void **lvStringArrayPtr) { - deleteLvData(lvStringArrayPtr); -} + errorMessage = const_cast(e.what()); -/******************************************************************************************************** - UINT16 - ********************************************************************************************************/ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint16_constructor(void **lvUint16PtrOut, - unsigned short valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvUint16PtrOut, valIn); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_uint16_destructor(void **lvUint16Ptr) { - deleteLvData(lvUint16Ptr); -} + EXPORT void mdsplus_uint16_getInt(const void *lvUint16Ptr, int *intOut, + ErrorCluster *error) -EXPORT void mdsplus_uint16_getByte(const void *lvUint16Ptr, char *byteOut, - ErrorCluster *error) + { -{ + Uint16 *uint16Ptr = NULL; - Uint16 *uint16Ptr = NULL; + MgErr errorCode = noErr; - MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; - const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; - char const *errorMessage = ""; + try - try + { - { + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + *intOut = uint16Ptr->getInt(); + } - *byteOut = uint16Ptr->getByte(); + catch (const MdsException &e) - } + { - catch (const MdsException &e) + errorCode = bogusError; - { + errorMessage = const_cast(e.what()); - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorMessage = const_cast(e.what()); + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + EXPORT void mdsplus_uint16_getLong(const void *lvUint16Ptr, int64_t *longOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_uint16_getDouble(const void *lvUint16Ptr, double *doubleOut, - ErrorCluster *error) + Uint16 *uint16Ptr = NULL; -{ + MgErr errorCode = noErr; - Uint16 *uint16Ptr = NULL; + const char *errorSource = __FUNCTION__; - MgErr errorCode = noErr; + char const *errorMessage = ""; - const char *errorSource = __FUNCTION__; + try - char const *errorMessage = ""; + { - try + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - { + *longOut = uint16Ptr->getLong(); + } - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + catch (const MdsException &e) - *doubleOut = uint16Ptr->getDouble(); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = const_cast(e.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorMessage = const_cast(e.what()); + EXPORT void mdsplus_uint16_getShort(const void *lvUint16Ptr, short *shortOut, + ErrorCluster *error) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + Uint16 *uint16Ptr = NULL; -EXPORT void mdsplus_uint16_getFloat(const void *lvUint16Ptr, float *floatOut, - ErrorCluster *error) + MgErr errorCode = noErr; -{ + const char *errorSource = __FUNCTION__; - Uint16 *uint16Ptr = NULL; + char const *errorMessage = ""; - MgErr errorCode = noErr; + try - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); - try + *shortOut = uint16Ptr->getShort(); + } - { + catch (const MdsException &e) - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + { - *floatOut = uint16Ptr->getFloat(); + errorCode = bogusError; - } + errorMessage = const_cast(e.what()); - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - errorCode = bogusError; + /******************************************************************************************************** - errorMessage = const_cast(e.what()); + UINT16ARRAY - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + ********************************************************************************************************/ - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void mdsplus_uint16array_constructor(void **lvUint16ArrayPtrOut, + const LUShtArrHdl lvUShtArrHdlIn, + ErrorCluster *error) -EXPORT void mdsplus_uint16_getInt(const void *lvUint16Ptr, int *intOut, - ErrorCluster *error) + { -{ + Uint16Array *uint16ArrayPtrOut = NULL; - Uint16 *uint16Ptr = NULL; + unsigned short *uint16Arr = NULL; - MgErr errorCode = noErr; + MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; + const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; + char const *errorMessage = ""; - try + try - { + { - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + int uint16ArrLen = static_cast((*lvUShtArrHdlIn)->dimSize); - *intOut = uint16Ptr->getInt(); + uint16Arr = new unsigned short[uint16ArrLen]; - } + for (int i = 0; i < uint16ArrLen; i++) - catch (const MdsException &e) + uint16Arr[i] = static_cast((*lvUShtArrHdlIn)->elt[i]); - { + uint16ArrayPtrOut = new Uint16Array(uint16Arr, uint16ArrLen); - errorCode = bogusError; + delete[] uint16Arr; - errorMessage = const_cast(e.what()); + *lvUint16ArrayPtrOut = reinterpret_cast(uint16ArrayPtrOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_uint16_getLong(const void *lvUint16Ptr, int64_t *longOut, - ErrorCluster *error) + delete[] uint16Arr; -{ + errorCode = bogusError; - Uint16 *uint16Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_uint16array_constructor_dims( + void **lvUint16ArrayPtrOut, const LUShtArrHdl lvUShtArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) - try + { - { + Uint16Array *uint16ArrayPtrOut = NULL; - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + unsigned short *uint16Arr = NULL; - *longOut = uint16Ptr->getLong(); + int *intArr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + int uint16ArrLen = static_cast((*lvUShtArrHdlIn)->dimSize); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + uint16Arr = new unsigned short[uint16ArrLen]; -EXPORT void mdsplus_uint16_getShort(const void *lvUint16Ptr, short *shortOut, - ErrorCluster *error) + for (int i = 0; i < uint16ArrLen; i++) -{ + uint16Arr[i] = static_cast((*lvUShtArrHdlIn)->elt[i]); - Uint16 *uint16Ptr = NULL; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - MgErr errorCode = noErr; + intArr = new int[intArrLen]; - const char *errorSource = __FUNCTION__; + for (int i = 0; i < intArrLen; i++) - char const *errorMessage = ""; + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - try + uint16ArrayPtrOut = new Uint16Array(uint16Arr, intArrLen, intArr); - { + delete[] uint16Arr; - uint16Ptr = reinterpret_cast(const_cast(lvUint16Ptr)); + delete[] intArr; - *shortOut = uint16Ptr->getShort(); + *lvUint16ArrayPtrOut = reinterpret_cast(uint16ArrayPtrOut); + } - } + catch (const MdsException &e) - catch (const MdsException &e) + { - { + delete[] uint16Arr; - errorCode = bogusError; + delete[] intArr; - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -/******************************************************************************************************** + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - UINT16ARRAY + EXPORT void mdsplus_uint16array_destructor(void **lvUint16ArrayPtr) + { + deleteLvData(lvUint16ArrayPtr); + } + /******************************************************************************************************** + UINT32 ********************************************************************************************************/ -EXPORT void mdsplus_uint16array_constructor(void **lvUint16ArrayPtrOut, - const LUShtArrHdl lvUShtArrHdlIn, - ErrorCluster *error) + EXPORT void mdsplus_uint32_constructor(void **lvUint32PtrOut, + unsigned int valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvUint32PtrOut, valIn); + } -{ + EXPORT void mdsplus_uint32_destructor(void **lvUint32Ptr) + { + deleteLvData(lvUint32Ptr); + } - Uint16Array *uint16ArrayPtrOut = NULL; + EXPORT void mdsplus_uint32_getByte(const void *lvUint32Ptr, char *byteOut, + ErrorCluster *error) - unsigned short *uint16Arr = NULL; + { - MgErr errorCode = noErr; + Uint32 *uint32Ptr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int uint16ArrLen = static_cast((*lvUShtArrHdlIn)->dimSize); + { - uint16Arr = new unsigned short[uint16ArrLen]; + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - for (int i = 0; i < uint16ArrLen; i++) + *byteOut = uint32Ptr->getByte(); + } - uint16Arr[i] = static_cast((*lvUShtArrHdlIn)->elt[i]); + catch (const MdsException &e) - uint16ArrayPtrOut = new Uint16Array(uint16Arr, uint16ArrLen); + { - delete[] uint16Arr; + errorCode = bogusError; - *lvUint16ArrayPtrOut = reinterpret_cast(uint16ArrayPtrOut); + errorMessage = const_cast(e.what()); - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - catch (const MdsException &e) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_uint32_getDouble(const void *lvUint32Ptr, double *doubleOut, + ErrorCluster *error) - delete[] uint16Arr; + { - errorCode = bogusError; + Uint32 *uint32Ptr = NULL; - errorMessage = const_cast(e.what()); + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + const char *errorSource = __FUNCTION__; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + char const *errorMessage = ""; -EXPORT void mdsplus_uint16array_constructor_dims( - void **lvUint16ArrayPtrOut, const LUShtArrHdl lvUShtArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) + try -{ + { - Uint16Array *uint16ArrayPtrOut = NULL; + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - unsigned short *uint16Arr = NULL; + *doubleOut = uint32Ptr->getDouble(); + } - int *intArr = NULL; + catch (const MdsException &e) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + errorCode = bogusError; - char const *errorMessage = ""; + errorMessage = const_cast(e.what()); - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - int uint16ArrLen = static_cast((*lvUShtArrHdlIn)->dimSize); + EXPORT void mdsplus_uint32_getFloat(const void *lvUint32Ptr, float *floatOut, + ErrorCluster *error) - uint16Arr = new unsigned short[uint16ArrLen]; + { - for (int i = 0; i < uint16ArrLen; i++) + Uint32 *uint32Ptr = NULL; - uint16Arr[i] = static_cast((*lvUShtArrHdlIn)->elt[i]); + MgErr errorCode = noErr; - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + const char *errorSource = __FUNCTION__; - intArr = new int[intArrLen]; + char const *errorMessage = ""; - for (int i = 0; i < intArrLen; i++) + try - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + { - uint16ArrayPtrOut = new Uint16Array(uint16Arr, intArrLen, intArr); + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - delete[] uint16Arr; + *floatOut = uint32Ptr->getFloat(); + } - delete[] intArr; + catch (const MdsException &e) - *lvUint16ArrayPtrOut = reinterpret_cast(uint16ArrayPtrOut); + { - } + errorCode = bogusError; - catch (const MdsException &e) + errorMessage = const_cast(e.what()); - { + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - delete[] uint16Arr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - delete[] intArr; + EXPORT void mdsplus_uint32_getInt(const void *lvUint32Ptr, int *intOut, + ErrorCluster *error) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + Uint32 *uint32Ptr = NULL; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + MgErr errorCode = noErr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + const char *errorSource = __FUNCTION__; -EXPORT void mdsplus_uint16array_destructor(void **lvUint16ArrayPtr) { - deleteLvData(lvUint16ArrayPtr); -} + char const *errorMessage = ""; -/******************************************************************************************************** - UINT32 - ********************************************************************************************************/ + try -EXPORT void mdsplus_uint32_constructor(void **lvUint32PtrOut, - unsigned int valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvUint32PtrOut, valIn); -} + { -EXPORT void mdsplus_uint32_destructor(void **lvUint32Ptr) { - deleteLvData(lvUint32Ptr); -} + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); -EXPORT void mdsplus_uint32_getByte(const void *lvUint32Ptr, char *byteOut, - ErrorCluster *error) + *intOut = uint32Ptr->getInt(); + } -{ + catch (const MdsException &e) - Uint32 *uint32Ptr = NULL; + { - MgErr errorCode = noErr; + errorCode = bogusError; - const char *errorSource = __FUNCTION__; + errorMessage = const_cast(e.what()); - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - try + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - { + EXPORT void mdsplus_uint32_getLong(const void *lvUint32Ptr, int64_t *longOut, + ErrorCluster *error) - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); + { - *byteOut = uint32Ptr->getByte(); + Uint32 *uint32Ptr = NULL; - } + MgErr errorCode = noErr; - catch (const MdsException &e) + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - errorCode = bogusError; + try - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *longOut = uint32Ptr->getLong(); + } -EXPORT void mdsplus_uint32_getDouble(const void *lvUint32Ptr, double *doubleOut, - ErrorCluster *error) + catch (const MdsException &e) -{ + { - Uint32 *uint32Ptr = NULL; + errorCode = bogusError; - MgErr errorCode = noErr; + errorMessage = const_cast(e.what()); - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_uint32_getShort(const void *lvUint32Ptr, short *shortOut, + ErrorCluster *error) - { + { - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); + Uint32 *uint32Ptr = NULL; - *doubleOut = uint32Ptr->getDouble(); + MgErr errorCode = noErr; - } + const char *errorSource = __FUNCTION__; - catch (const MdsException &e) + char const *errorMessage = ""; - { + try - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *shortOut = uint32Ptr->getShort(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_uint32_getFloat(const void *lvUint32Ptr, float *floatOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Uint32 *uint32Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + /******************************************************************************************************** - try - - { - - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - - *floatOut = uint32Ptr->getFloat(); - - } - - catch (const MdsException &e) - - { - - errorCode = bogusError; - - errorMessage = const_cast(e.what()); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} - -EXPORT void mdsplus_uint32_getInt(const void *lvUint32Ptr, int *intOut, - ErrorCluster *error) - -{ - - Uint32 *uint32Ptr = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; - - char const *errorMessage = ""; - - try - - { - - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - - *intOut = uint32Ptr->getInt(); - - } - - catch (const MdsException &e) - - { - - errorCode = bogusError; - - errorMessage = const_cast(e.what()); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} - -EXPORT void mdsplus_uint32_getLong(const void *lvUint32Ptr, int64_t *longOut, - ErrorCluster *error) - -{ - - Uint32 *uint32Ptr = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; - - char const *errorMessage = ""; - - try - - { - - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - - *longOut = uint32Ptr->getLong(); - - } - - catch (const MdsException &e) - - { - - errorCode = bogusError; - - errorMessage = const_cast(e.what()); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} - -EXPORT void mdsplus_uint32_getShort(const void *lvUint32Ptr, short *shortOut, - ErrorCluster *error) - -{ - - Uint32 *uint32Ptr = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; - - char const *errorMessage = ""; - - try - - { - - uint32Ptr = reinterpret_cast(const_cast(lvUint32Ptr)); - - *shortOut = uint32Ptr->getShort(); - - } - - catch (const MdsException &e) - - { - - errorCode = bogusError; - - errorMessage = const_cast(e.what()); - - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } - - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} - -/******************************************************************************************************** - - UINT32ARRAY + UINT32ARRAY ********************************************************************************************************/ -EXPORT void mdsplus_uint32array_constructor(void **lvUint32ArrayPtrOut, - const LUIntArrHdl lvUIntArrHdlIn, - ErrorCluster *error) - -{ - - Uint32Array *uint32ArrayPtrOut = NULL; + EXPORT void mdsplus_uint32array_constructor(void **lvUint32ArrayPtrOut, + const LUIntArrHdl lvUIntArrHdlIn, + ErrorCluster *error) - unsigned int *uint32Arr = NULL; + { - MgErr errorCode = noErr; + Uint32Array *uint32ArrayPtrOut = NULL; - const char *errorSource = __FUNCTION__; + unsigned int *uint32Arr = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - int uint32ArrLen = static_cast((*lvUIntArrHdlIn)->dimSize); + try - uint32Arr = new unsigned int[uint32ArrLen]; + { - for (int i = 0; i < uint32ArrLen; i++) + int uint32ArrLen = static_cast((*lvUIntArrHdlIn)->dimSize); - uint32Arr[i] = static_cast((*lvUIntArrHdlIn)->elt[i]); + uint32Arr = new unsigned int[uint32ArrLen]; - uint32ArrayPtrOut = new Uint32Array(uint32Arr, uint32ArrLen); + for (int i = 0; i < uint32ArrLen; i++) - delete[] uint32Arr; + uint32Arr[i] = static_cast((*lvUIntArrHdlIn)->elt[i]); - *lvUint32ArrayPtrOut = reinterpret_cast(uint32ArrayPtrOut); + uint32ArrayPtrOut = new Uint32Array(uint32Arr, uint32ArrLen); - } + delete[] uint32Arr; - catch (const MdsException &e) + *lvUint32ArrayPtrOut = reinterpret_cast(uint32ArrayPtrOut); + } - { + catch (const MdsException &e) - delete[] uint32Arr; + { - errorCode = bogusError; + delete[] uint32Arr; - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint32array_constructor_dims( - void **lvUint32ArrayPtrOut, const LUIntArrHdl lvUIntArrHdlIn, - const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_uint32array_constructor_dims( + void **lvUint32ArrayPtrOut, const LUIntArrHdl lvUIntArrHdlIn, + const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error) - Uint32Array *uint32ArrayPtrOut = NULL; + { - unsigned int *uint32Arr = NULL; + Uint32Array *uint32ArrayPtrOut = NULL; - int *intArr = NULL; + unsigned int *uint32Arr = NULL; - MgErr errorCode = noErr; + int *intArr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int uint32ArrLen = static_cast((*lvUIntArrHdlIn)->dimSize); + { - uint32Arr = new unsigned int[uint32ArrLen]; + int uint32ArrLen = static_cast((*lvUIntArrHdlIn)->dimSize); - for (int i = 0; i < uint32ArrLen; i++) + uint32Arr = new unsigned int[uint32ArrLen]; - uint32Arr[i] = static_cast((*lvUIntArrHdlIn)->elt[i]); + for (int i = 0; i < uint32ArrLen; i++) - int intArrLen = static_cast((*lvIntArrHdlDimIn)->dimSize); + uint32Arr[i] = static_cast((*lvUIntArrHdlIn)->elt[i]); - intArr = new int[intArrLen]; + int intArrLen = static_cast((*lvIntArrHdlDimIn)->dimSize); - for (int i = 0; i < intArrLen; i++) + intArr = new int[intArrLen]; - intArr[i] = static_cast((*lvIntArrHdlDimIn)->elt[i]); + for (int i = 0; i < intArrLen; i++) - uint32ArrayPtrOut = new Uint32Array(uint32Arr, intArrLen, intArr); + intArr[i] = static_cast((*lvIntArrHdlDimIn)->elt[i]); - delete[] uint32Arr; + uint32ArrayPtrOut = new Uint32Array(uint32Arr, intArrLen, intArr); - delete[] intArr; + delete[] uint32Arr; - *lvUint32ArrayPtrOut = reinterpret_cast(uint32ArrayPtrOut); + delete[] intArr; - } + *lvUint32ArrayPtrOut = reinterpret_cast(uint32ArrayPtrOut); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - delete[] uint32Arr; + delete[] uint32Arr; - delete[] intArr; + delete[] intArr; - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_uint32array_destructor(void **lvUint32ArrayPtr) { - deleteLvData(lvUint32ArrayPtr); -} + EXPORT void mdsplus_uint32array_destructor(void **lvUint32ArrayPtr) + { + deleteLvData(lvUint32ArrayPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** UINT64 ********************************************************************************************************/ -EXPORT void mdsplus_uint64_constructor(void **lvUint64PtrOut, uint64_t valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvUint64PtrOut, valIn); -} - -EXPORT void mdsplus_uint64_destructor(void **lvUint64Ptr) { - deleteLvData(lvUint64Ptr); -} - -EXPORT void mdsplus_uint64_getByte(const void *lvUint64Ptr, char *byteOut, - ErrorCluster *error) - -{ - - Uint64 *uint64Ptr = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; - - char const *errorMessage = ""; - - try + EXPORT void mdsplus_uint64_constructor(void **lvUint64PtrOut, uint64_t valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvUint64PtrOut, valIn); + } - { + EXPORT void mdsplus_uint64_destructor(void **lvUint64Ptr) + { + deleteLvData(lvUint64Ptr); + } - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + EXPORT void mdsplus_uint64_getByte(const void *lvUint64Ptr, char *byteOut, + ErrorCluster *error) - *byteOut = uint64Ptr->getByte(); + { - } + Uint64 *uint64Ptr = NULL; - catch (const MdsException &e) + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - errorCode = bogusError; + char const *errorMessage = ""; - errorMessage = const_cast(e.what()); + try - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); -EXPORT void mdsplus_uint64_getDate(const void *lvUint64Ptr, - LStrHandle lvStrHdlOut, ErrorCluster *error) + *byteOut = uint64Ptr->getByte(); + } -{ + catch (const MdsException &e) - Uint64 *uint64Ptr = NULL; + { - char *strOut = NULL; + errorCode = bogusError; - MgErr errorCode = noErr; + errorMessage = const_cast(e.what()); - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - char const *errorMessage = ""; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - try + EXPORT void mdsplus_uint64_getDate(const void *lvUint64Ptr, + LStrHandle lvStrHdlOut, ErrorCluster *error) - { + { - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + Uint64 *uint64Ptr = NULL; - strOut = uint64Ptr->getDate(); + char *strOut = NULL; - std::size_t strOutLen = std::strlen(strOut); + MgErr errorCode = noErr; - errorCode = - NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), - strOutLen + sizeof(int32)); + const char *errorSource = __FUNCTION__; - if (!errorCode) + char const *errorMessage = ""; - { + try - MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), - strOutLen); + { - (*lvStrHdlOut)->cnt = strOutLen; + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - } + strOut = uint64Ptr->getDate(); - else + std::size_t strOutLen = std::strlen(strOut); - errorMessage = (char *)"NumericArrayResize error"; + errorCode = + NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), + strOutLen + sizeof(int32)); - deleteNativeArray(strOut); + if (!errorCode) - } + { - catch (const MdsException &e) + MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), + strOutLen); - { + (*lvStrHdlOut)->cnt = strOutLen; + } - errorCode = bogusError; + else - errorMessage = const_cast(e.what()); + errorMessage = (char *)"NumericArrayResize error"; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + deleteNativeArray(strOut); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_uint64_getDouble(const void *lvUint64Ptr, double *doubleOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Uint64 *uint64Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_uint64_getDouble(const void *lvUint64Ptr, double *doubleOut, + ErrorCluster *error) - try + { - { + Uint64 *uint64Ptr = NULL; - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + MgErr errorCode = noErr; - *doubleOut = uint64Ptr->getDouble(); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - errorMessage = const_cast(e.what()); + *doubleOut = uint64Ptr->getDouble(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_uint64_getFloat(const void *lvUint64Ptr, float *floatOut, - ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - Uint64 *uint64Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_uint64_getFloat(const void *lvUint64Ptr, float *floatOut, + ErrorCluster *error) - char const *errorMessage = ""; + { - try + Uint64 *uint64Ptr = NULL; - { + MgErr errorCode = noErr; - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + const char *errorSource = __FUNCTION__; - *floatOut = uint64Ptr->getFloat(); + char const *errorMessage = ""; - } + try - catch (const MdsException &e) + { - { + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - errorCode = bogusError; + *floatOut = uint64Ptr->getFloat(); + } - errorMessage = const_cast(e.what()); + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorCode = bogusError; -EXPORT void mdsplus_uint64_getInt(const void *lvUint64Ptr, int *intOut, - ErrorCluster *error) + errorMessage = const_cast(e.what()); -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - Uint64 *uint64Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - MgErr errorCode = noErr; + EXPORT void mdsplus_uint64_getInt(const void *lvUint64Ptr, int *intOut, + ErrorCluster *error) - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + Uint64 *uint64Ptr = NULL; - try + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + char const *errorMessage = ""; - *intOut = uint64Ptr->getInt(); + try - } + { - catch (const MdsException &e) + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - { + *intOut = uint64Ptr->getInt(); + } - errorCode = bogusError; + catch (const MdsException &e) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorMessage = const_cast(e.what()); -EXPORT void mdsplus_uint64_getLong(const void *lvUint64Ptr, int64_t *longOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Uint64 *uint64Ptr = NULL; + EXPORT void mdsplus_uint64_getLong(const void *lvUint64Ptr, int64_t *longOut, + ErrorCluster *error) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + Uint64 *uint64Ptr = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + try - *longOut = uint64Ptr->getLong(); + { - } + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - catch (const MdsException &e) + *longOut = uint64Ptr->getLong(); + } - { + catch (const MdsException &e) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint64_getShort(const void *lvUint64Ptr, short *shortOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_uint64_getShort(const void *lvUint64Ptr, short *shortOut, + ErrorCluster *error) - Uint64 *uint64Ptr = NULL; + { - MgErr errorCode = noErr; + Uint64 *uint64Ptr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); + { - *shortOut = uint64Ptr->getShort(); + uint64Ptr = reinterpret_cast(const_cast(lvUint64Ptr)); - } + *shortOut = uint64Ptr->getShort(); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -/******************************************************************************************************** + /******************************************************************************************************** UINT64ARRAY ********************************************************************************************************/ -EXPORT void mdsplus_uint64array_constructor(void **lvUint64ArrayPtrOut, - const LULngArrHdl lvULngArrHdlIn, - ErrorCluster *error) - -{ + EXPORT void mdsplus_uint64array_constructor(void **lvUint64ArrayPtrOut, + const LULngArrHdl lvULngArrHdlIn, + ErrorCluster *error) - Uint64Array *uint64ArrayPtrOut = NULL; + { - uint64_t *uint64Arr = NULL; + Uint64Array *uint64ArrayPtrOut = NULL; - MgErr errorCode = noErr; + uint64_t *uint64Arr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int uint64ArrLen = static_cast((*lvULngArrHdlIn)->dimSize); - - uint64Arr = new uint64_t[uint64ArrLen]; + { - for (int i = 0; i < uint64ArrLen; i++) + int uint64ArrLen = static_cast((*lvULngArrHdlIn)->dimSize); - uint64Arr[i] = static_cast((*lvULngArrHdlIn)->elt[i]); + uint64Arr = new uint64_t[uint64ArrLen]; - uint64ArrayPtrOut = new Uint64Array(uint64Arr, uint64ArrLen); + for (int i = 0; i < uint64ArrLen; i++) - delete[] uint64Arr; + uint64Arr[i] = static_cast((*lvULngArrHdlIn)->elt[i]); - *lvUint64ArrayPtrOut = reinterpret_cast(uint64ArrayPtrOut); + uint64ArrayPtrOut = new Uint64Array(uint64Arr, uint64ArrLen); - } + delete[] uint64Arr; - catch (const MdsException &e) + *lvUint64ArrayPtrOut = reinterpret_cast(uint64ArrayPtrOut); + } - { + catch (const MdsException &e) - delete[] uint64Arr; + { - errorCode = bogusError; + delete[] uint64Arr; - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint64array_constructor_dims( - void **lvUint64ArrayPtrOut, const LULngArrHdl lvULngArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_uint64array_constructor_dims( + void **lvUint64ArrayPtrOut, const LULngArrHdl lvULngArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) - Uint64Array *uint64ArrayPtrOut = NULL; + { - uint64_t *uint64Arr = NULL; + Uint64Array *uint64ArrayPtrOut = NULL; - int *intArr = NULL; + uint64_t *uint64Arr = NULL; - MgErr errorCode = noErr; + int *intArr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - int uint64ArrLen = static_cast((*lvULngArrHdlIn)->dimSize); + { - uint64Arr = new uint64_t[uint64ArrLen]; + int uint64ArrLen = static_cast((*lvULngArrHdlIn)->dimSize); - for (int i = 0; i < uint64ArrLen; i++) + uint64Arr = new uint64_t[uint64ArrLen]; - uint64Arr[i] = static_cast((*lvULngArrHdlIn)->elt[i]); + for (int i = 0; i < uint64ArrLen; i++) - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + uint64Arr[i] = static_cast((*lvULngArrHdlIn)->elt[i]); - intArr = new int[intArrLen]; + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - for (int i = 0; i < intArrLen; i++) + intArr = new int[intArrLen]; - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + for (int i = 0; i < intArrLen; i++) - uint64ArrayPtrOut = new Uint64Array(uint64Arr, intArrLen, intArr); + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - delete[] uint64Arr; + uint64ArrayPtrOut = new Uint64Array(uint64Arr, intArrLen, intArr); - delete[] intArr; + delete[] uint64Arr; - *lvUint64ArrayPtrOut = reinterpret_cast(uint64ArrayPtrOut); + delete[] intArr; - } + *lvUint64ArrayPtrOut = reinterpret_cast(uint64ArrayPtrOut); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - delete[] uint64Arr; + delete[] uint64Arr; - delete[] intArr; + delete[] intArr; - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_uint64array_destructor(void **lvUint64ArrayPtr) { - deleteLvData(lvUint64ArrayPtr); -} + EXPORT void mdsplus_uint64array_destructor(void **lvUint64ArrayPtr) + { + deleteLvData(lvUint64ArrayPtr); + } -/******************************************************************************************************** + /******************************************************************************************************** UINT8 ********************************************************************************************************/ -EXPORT void mdsplus_uint8_constructor(void **lvUint8PtrOut, unsigned char valIn, - ErrorCluster *error) { - scalarConstructor(__func__, error, lvUint8PtrOut, valIn); -} - -EXPORT void mdsplus_uint8_destructor(void **lvUint8Ptr) { - deleteLvData(lvUint8Ptr); -} - -EXPORT void mdsplus_uint8_getByte(const void *lvUint8Ptr, char *byteOut, - ErrorCluster *error) - -{ - - Uint8 *uint8Ptr = NULL; - - MgErr errorCode = noErr; - - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_uint8_constructor(void **lvUint8PtrOut, unsigned char valIn, + ErrorCluster *error) + { + scalarConstructor(__func__, error, lvUint8PtrOut, valIn); + } - char const *errorMessage = ""; + EXPORT void mdsplus_uint8_destructor(void **lvUint8Ptr) + { + deleteLvData(lvUint8Ptr); + } - try + EXPORT void mdsplus_uint8_getByte(const void *lvUint8Ptr, char *byteOut, + ErrorCluster *error) - { + { - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + Uint8 *uint8Ptr = NULL; - *byteOut = uint8Ptr->getByte(); + MgErr errorCode = noErr; - } + const char *errorSource = __FUNCTION__; - catch (const MdsException &e) + char const *errorMessage = ""; - { + try - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + *byteOut = uint8Ptr->getByte(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + catch (const MdsException &e) -EXPORT void mdsplus_uint8_getDouble(const void *lvUint8Ptr, double *doubleOut, - ErrorCluster *error) + { -{ + errorCode = bogusError; - Uint8 *uint8Ptr = NULL; + errorMessage = const_cast(e.what()); - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - const char *errorSource = __FUNCTION__; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - char const *errorMessage = ""; + EXPORT void mdsplus_uint8_getDouble(const void *lvUint8Ptr, double *doubleOut, + ErrorCluster *error) - try + { - { + Uint8 *uint8Ptr = NULL; - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + MgErr errorCode = noErr; - *doubleOut = uint8Ptr->getDouble(); + const char *errorSource = __FUNCTION__; - } + char const *errorMessage = ""; - catch (const MdsException &e) + try - { + { - errorCode = bogusError; + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - errorMessage = const_cast(e.what()); + *doubleOut = uint8Ptr->getDouble(); + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + { -EXPORT void mdsplus_uint8_getFloat(const void *lvUint8Ptr, float *floatOut, - ErrorCluster *error) + errorCode = bogusError; -{ + errorMessage = const_cast(e.what()); - Uint8 *uint8Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - MgErr errorCode = noErr; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - const char *errorSource = __FUNCTION__; + EXPORT void mdsplus_uint8_getFloat(const void *lvUint8Ptr, float *floatOut, + ErrorCluster *error) - char const *errorMessage = ""; + { - try + Uint8 *uint8Ptr = NULL; - { + MgErr errorCode = noErr; - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + const char *errorSource = __FUNCTION__; - *floatOut = uint8Ptr->getFloat(); + char const *errorMessage = ""; - } + try - catch (const MdsException &e) + { - { + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - errorCode = bogusError; + *floatOut = uint8Ptr->getFloat(); + } - errorMessage = const_cast(e.what()); + catch (const MdsException &e) - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorCode = bogusError; -EXPORT void mdsplus_uint8_getInt(const void *lvUint8Ptr, int *intOut, - ErrorCluster *error) + errorMessage = const_cast(e.what()); -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - Uint8 *uint8Ptr = NULL; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - MgErr errorCode = noErr; + EXPORT void mdsplus_uint8_getInt(const void *lvUint8Ptr, int *intOut, + ErrorCluster *error) - const char *errorSource = __FUNCTION__; + { - char const *errorMessage = ""; + Uint8 *uint8Ptr = NULL; - try + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + char const *errorMessage = ""; - *intOut = uint8Ptr->getInt(); + try - } + { - catch (const MdsException &e) + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - { + *intOut = uint8Ptr->getInt(); + } - errorCode = bogusError; + catch (const MdsException &e) - errorMessage = const_cast(e.what()); + { - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorMessage = const_cast(e.what()); -EXPORT void mdsplus_uint8_getLong(const void *lvUint8Ptr, int64_t *longOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Uint8 *uint8Ptr = NULL; + EXPORT void mdsplus_uint8_getLong(const void *lvUint8Ptr, int64_t *longOut, + ErrorCluster *error) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + Uint8 *uint8Ptr = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + try - *longOut = uint8Ptr->getLong(); + { - } + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - catch (const MdsException &e) + *longOut = uint8Ptr->getLong(); + } - { + catch (const MdsException &e) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint8_getShort(const void *lvUint8Ptr, short *shortOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_uint8_getShort(const void *lvUint8Ptr, short *shortOut, + ErrorCluster *error) - Uint8 *uint8Ptr = NULL; + { - MgErr errorCode = noErr; + Uint8 *uint8Ptr = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); + { - *shortOut = uint8Ptr->getShort(); + uint8Ptr = reinterpret_cast(const_cast(lvUint8Ptr)); - } + *shortOut = uint8Ptr->getShort(); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -/******************************************************************************************************** + /******************************************************************************************************** UINT8ARRAY ********************************************************************************************************/ -EXPORT void mdsplus_uint8array_constructor(void **lvUint8ArrayPtrOut, - const LUByteArrHdl lvUByteArrHdlIn, - ErrorCluster *error) - -{ - - Uint8Array *uint8ArrayPtrOut = NULL; - - unsigned char *uint8Arr = NULL; + EXPORT void mdsplus_uint8array_constructor(void **lvUint8ArrayPtrOut, + const LUByteArrHdl lvUByteArrHdlIn, + ErrorCluster *error) - MgErr errorCode = noErr; + { - const char *errorSource = __FUNCTION__; + Uint8Array *uint8ArrayPtrOut = NULL; - char const *errorMessage = ""; + unsigned char *uint8Arr = NULL; - try + MgErr errorCode = noErr; - { + const char *errorSource = __FUNCTION__; - int uint8ArrLen = static_cast((*lvUByteArrHdlIn)->dimSize); + char const *errorMessage = ""; - uint8Arr = new unsigned char[uint8ArrLen]; + try - for (int i = 0; i < uint8ArrLen; i++) + { - uint8Arr[i] = static_cast((*lvUByteArrHdlIn)->elt[i]); + int uint8ArrLen = static_cast((*lvUByteArrHdlIn)->dimSize); - uint8ArrayPtrOut = new Uint8Array(uint8Arr, uint8ArrLen); + uint8Arr = new unsigned char[uint8ArrLen]; - delete[] uint8Arr; + for (int i = 0; i < uint8ArrLen; i++) - *lvUint8ArrayPtrOut = reinterpret_cast(uint8ArrayPtrOut); + uint8Arr[i] = static_cast((*lvUByteArrHdlIn)->elt[i]); - } + uint8ArrayPtrOut = new Uint8Array(uint8Arr, uint8ArrLen); - catch (const MdsException &e) + delete[] uint8Arr; - { + *lvUint8ArrayPtrOut = reinterpret_cast(uint8ArrayPtrOut); + } - delete[] uint8Arr; + catch (const MdsException &e) - errorCode = bogusError; + { - errorMessage = const_cast(e.what()); + delete[] uint8Arr; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + errorMessage = const_cast(e.what()); -EXPORT void mdsplus_uint8array_constructor_dims( - void **lvUint8ArrayPtrOut, const LUByteArrHdl lvUByteArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -{ + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } - Uint8Array *uint8ArrayPtrOut = NULL; + EXPORT void mdsplus_uint8array_constructor_dims( + void **lvUint8ArrayPtrOut, const LUByteArrHdl lvUByteArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error) - unsigned char *uint8Arr = NULL; + { - int *intArr = NULL; + Uint8Array *uint8ArrayPtrOut = NULL; - MgErr errorCode = noErr; + unsigned char *uint8Arr = NULL; - const char *errorSource = __FUNCTION__; + int *intArr = NULL; - char const *errorMessage = ""; + MgErr errorCode = noErr; - try + const char *errorSource = __FUNCTION__; - { + char const *errorMessage = ""; - int uint8ArrLen = static_cast((*lvUByteArrHdlIn)->dimSize); + try - uint8Arr = new unsigned char[uint8ArrLen]; + { - for (int i = 0; i < uint8ArrLen; i++) + int uint8ArrLen = static_cast((*lvUByteArrHdlIn)->dimSize); - uint8Arr[i] = static_cast((*lvUByteArrHdlIn)->elt[i]); + uint8Arr = new unsigned char[uint8ArrLen]; - int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); + for (int i = 0; i < uint8ArrLen; i++) - intArr = new int[intArrLen]; + uint8Arr[i] = static_cast((*lvUByteArrHdlIn)->elt[i]); - for (int i = 0; i < intArrLen; i++) + int intArrLen = static_cast((*lvIntArrHdlIn)->dimSize); - intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); + intArr = new int[intArrLen]; - uint8ArrayPtrOut = new Uint8Array(uint8Arr, intArrLen, intArr); + for (int i = 0; i < intArrLen; i++) - delete[] uint8Arr; + intArr[i] = static_cast((*lvIntArrHdlIn)->elt[i]); - delete[] intArr; + uint8ArrayPtrOut = new Uint8Array(uint8Arr, intArrLen, intArr); - *lvUint8ArrayPtrOut = reinterpret_cast(uint8ArrayPtrOut); + delete[] uint8Arr; - } + delete[] intArr; - catch (const MdsException &e) + *lvUint8ArrayPtrOut = reinterpret_cast(uint8ArrayPtrOut); + } - { + catch (const MdsException &e) - delete[] uint8Arr; + { - delete[] intArr; + delete[] uint8Arr; - errorCode = bogusError; + delete[] intArr; - errorMessage = const_cast(e.what()); + errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } -EXPORT void mdsplus_uint8array_deserialize(const void *lvUint8ArrayPtr, - void **lvDataPtrOut, - ErrorCluster *error) + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -{ + EXPORT void mdsplus_uint8array_deserialize(const void *lvUint8ArrayPtr, + void **lvDataPtrOut, + ErrorCluster *error) - Uint8Array *uint8ArrayPtr = NULL; + { - Data *dataPtrOut = NULL; + Uint8Array *uint8ArrayPtr = NULL; - MgErr errorCode = noErr; + Data *dataPtrOut = NULL; - const char *errorSource = __FUNCTION__; + MgErr errorCode = noErr; - char const *errorMessage = ""; + const char *errorSource = __FUNCTION__; - try + char const *errorMessage = ""; - { + try - uint8ArrayPtr = - reinterpret_cast(const_cast(lvUint8ArrayPtr)); + { - dataPtrOut = uint8ArrayPtr->deserialize(); + uint8ArrayPtr = + reinterpret_cast(const_cast(lvUint8ArrayPtr)); - *lvDataPtrOut = reinterpret_cast(dataPtrOut); + dataPtrOut = uint8ArrayPtr->deserialize(); - } + *lvDataPtrOut = reinterpret_cast(dataPtrOut); + } - catch (const MdsException &e) + catch (const MdsException &e) - { + { - errorCode = bogusError; + errorCode = bogusError; - errorMessage = const_cast(e.what()); + errorMessage = const_cast(e.what()); - fillErrorCluster(errorCode, errorSource, errorMessage, error); - return; - } + fillErrorCluster(errorCode, errorSource, errorMessage, error); + return; + } - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void mdsplus_uint8array_destructor(void **lvUint8ArrayPtr) { - deleteLvData(lvUint8ArrayPtr); -} + EXPORT void mdsplus_uint8array_destructor(void **lvUint8ArrayPtr) + { + deleteLvData(lvUint8ArrayPtr); + } -////////////////////////////////TEMPORARY TEST -///ROUTINES/////////////////////////// + ////////////////////////////////TEMPORARY TEST + ///ROUTINES/////////////////////////// -EXPORT void prova1() { std::cout << "CIAO SONO PROVA1\n"; } + EXPORT void prova1() { std::cout << "CIAO SONO PROVA1\n"; } -EXPORT void prova2() { - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (MdsException &exc) { - std::cout << exc.what() << std::endl; - } - std::cout << "CIAO SONO PROVA2\n"; -} + EXPORT void prova2() + { + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (MdsException &exc) + { + std::cout << exc.what() << std::endl; + } + std::cout << "CIAO SONO PROVA2\n"; + } -EXPORT void prova3(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + EXPORT void prova3(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void prova4(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - i = 0; - } + EXPORT void prova4(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + i = 0; + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} -EXPORT void prova41(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - i = 0; - } + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void prova41(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + i = 0; + } - *outInt = inInt; - errorMessage = (char *)"CAZZACICCIA"; - errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} -EXPORT void prova40(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - *outInt = inInt; - errorMessage = (char *)"CAZZACICCIA"; - errorCode = bogusError; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} -EXPORT void prova42(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - errorMessage = (char *)"CAZZACICCIA"; - errorCode = bogusError; - } + *outInt = inInt; + errorMessage = (char *)"CAZZACICCIA"; + errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void prova40(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + *outInt = inInt; + errorMessage = (char *)"CAZZACICCIA"; + errorCode = bogusError; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void prova42(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + errorMessage = (char *)"CAZZACICCIA"; + errorCode = bogusError; + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} -EXPORT void prova43(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - char *currErr = (char *)exc.what(); - errorMessage = (char *)"CAZZACICCIA"; - errorCode = bogusError; - } + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void prova43(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + char *currErr = (char *)exc.what(); + errorMessage = (char *)"CAZZACICCIA"; + errorCode = bogusError; + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} -EXPORT void prova44(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - // - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - // char *currErr = (char *)exc.what(); - // errorMessage = strdup(currErr); - errorCode = bogusError; - } + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } + EXPORT void prova44(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + // + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + // char *currErr = (char *)exc.what(); + // errorMessage = strdup(currErr); + errorCode = bogusError; + } - *outInt = inInt; - // fillErrorCluster(errorCode, errorSource, errorMessage, error); - fillErrorCluster(errorCode, errorSource, "", error); -} + *outInt = inInt; + // fillErrorCluster(errorCode, errorSource, errorMessage, error); + fillErrorCluster(errorCode, errorSource, "", error); + } -EXPORT void prova45(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - char *currErr = (char *)exc.what(); - errorMessage = strdup(currErr); - errorCode = bogusError; - } + EXPORT void prova45(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + char *currErr = (char *)exc.what(); + errorMessage = strdup(currErr); + errorCode = bogusError; + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void prova5(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - int i; - try { - MDSplus::Tree *tree = new Tree("CACCA", -1); - } catch (const MdsException &exc) { - fillErrorCluster(bogusError, errorSource, exc.what(), error); - return; - } + EXPORT void prova5(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + int i; + try + { + MDSplus::Tree *tree = new Tree("CACCA", -1); + } + catch (const MdsException &exc) + { + fillErrorCluster(bogusError, errorSource, exc.what(), error); + return; + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void prova6(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - try { - MDSplus::Data *d = new Int32(123); - } catch (const MdsException &exc) { - errorCode = bogusError; - errorMessage = const_cast(exc.what()); - } -} + EXPORT void prova6(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + try + { + MDSplus::Data *d = new Int32(123); + } + catch (const MdsException &exc) + { + errorCode = bogusError; + errorMessage = const_cast(exc.what()); + } + } -EXPORT void prova7(int inInt, int *outInt, ErrorCluster *error) { - MgErr errorCode = noErr; - const char *errorSource = __FUNCTION__; - char const *errorMessage = ""; - try { - MDSplus::Tree *tree = new Tree("test", -1); - } catch (const MdsException &exc) { - errorCode = bogusError; - errorMessage = const_cast(exc.what()); - } + EXPORT void prova7(int inInt, int *outInt, ErrorCluster *error) + { + MgErr errorCode = noErr; + const char *errorSource = __FUNCTION__; + char const *errorMessage = ""; + try + { + MDSplus::Tree *tree = new Tree("test", -1); + } + catch (const MdsException &exc) + { + errorCode = bogusError; + errorMessage = const_cast(exc.what()); + } - *outInt = inInt; - fillErrorCluster(errorCode, errorSource, errorMessage, error); -} + *outInt = inInt; + fillErrorCluster(errorCode, errorSource, errorMessage, error); + } -EXPORT void prova8() { - Int64 *timeInsertedData = new Int64(0); - Data *retTimeStr = executeWithArgs("date_time(0)", 0); - std::cout << "FATTO EXECUTE WITH ARGS" << std::endl; - std::cout << "FATTO EXECUTE WITH ARGS" << (void *)retTimeStr << std::endl; + EXPORT void prova8() + { + Int64 *timeInsertedData = new Int64(0); + Data *retTimeStr = executeWithArgs("date_time(0)", 0); + std::cout << "FATTO EXECUTE WITH ARGS" << std::endl; + std::cout << "FATTO EXECUTE WITH ARGS" << (void *)retTimeStr << std::endl; - std::cout << retTimeStr->getString() << std::endl; -} + std::cout << retTimeStr->getString() << std::endl; + } -EXPORT void prova9() { - Int64 *timeInsertedData = new Int64(0); - Data *retTimeStr = executeWithArgs("date_time($)", 1, timeInsertedData); - std::cout << "FATTO EXECUTE WITH ARGS" << std::endl; + EXPORT void prova9() + { + Int64 *timeInsertedData = new Int64(0); + Data *retTimeStr = executeWithArgs("date_time($)", 1, timeInsertedData); + std::cout << "FATTO EXECUTE WITH ARGS" << std::endl; - std::cout << retTimeStr->getString() << std::endl; -} -EXPORT void prova10() { - Int32 *timeInsertedData = new Int32(0); - Data *retTimeStr = executeWithArgs("date_time($)", 1, timeInsertedData); + std::cout << retTimeStr->getString() << std::endl; + } + EXPORT void prova10() + { + Int32 *timeInsertedData = new Int32(0); + Data *retTimeStr = executeWithArgs("date_time($)", 1, timeInsertedData); - std::cout << retTimeStr->getString() << std::endl; -} + std::cout << retTimeStr->getString() << std::endl; + } -EXPORT void prova11() { - try { - Tree *tree = new Tree("test", 1); - TreeNode *n = tree->getNode("SIG"); - n->deleteData(); - Data *start = new Float32(0); - Data *end = new Float32(9); - Data *delta = new Float32(1); - Data *dim = new Range(start, end, delta); - float *floatArr = new float[10]; - for (int i = 0; i < 10; i++) - floatArr[i] = i; - Data *arrD = new Float32Array(floatArr, 10); - n->makeSegment(start, end, dim, (Array *)arrD); - } catch (MdsException &exc) { - std::cout << "ERRORE: " << exc.what() << std::endl; - } - std::cout << "FINITO CACCONA www\n"; -} + EXPORT void prova11() + { + try + { + Tree *tree = new Tree("test", 1); + TreeNode *n = tree->getNode("SIG"); + n->deleteData(); + Data *start = new Float32(0); + Data *end = new Float32(9); + Data *delta = new Float32(1); + Data *dim = new Range(start, end, delta); + float *floatArr = new float[10]; + for (int i = 0; i < 10; i++) + floatArr[i] = i; + Data *arrD = new Float32Array(floatArr, 10); + n->makeSegment(start, end, dim, (Array *)arrD); + } + catch (MdsException &exc) + { + std::cout << "ERRORE: " << exc.what() << std::endl; + } + std::cout << "FINITO CACCONA www\n"; + } -} // End Extern "C" + } // End Extern "C" } // End Namespace MDSplus diff --git a/mdsobjects/labview/mdseventobjectswrp.cpp b/mdsobjects/labview/mdseventobjectswrp.cpp index 491dfec478..9c8817692f 100644 --- a/mdsobjects/labview/mdseventobjectswrp.cpp +++ b/mdsobjects/labview/mdseventobjectswrp.cpp @@ -34,15 +34,19 @@ using namespace std; EXPORT void mdsplus_event_constructor(void **lvEventPtrOut, const char *evNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Event *eventPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { eventPtrOut = new Event(const_cast(evNameIn)); *lvEventPtrOut = reinterpret_cast(eventPtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { delete eventPtrOut; errorCode = bogusError; errorMessage = e.what(); @@ -52,7 +56,8 @@ EXPORT void mdsplus_event_constructor(void **lvEventPtrOut, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_event_destructor(void **lvEventPtr) { +EXPORT void mdsplus_event_destructor(void **lvEventPtr) +{ Event *eventPtr = reinterpret_cast(*lvEventPtr); delete eventPtr; *lvEventPtr = NULL; @@ -80,17 +85,21 @@ EXPORT void mdsplus_event_abort(const void *lvEventPtr, ErrorCluster *error) } */ EXPORT void mdsplus_event_waitData(const void *lvEventPtr, void **lvDataPtrOut, - int *timeoutOccurred, ErrorCluster *error) { + int *timeoutOccurred, ErrorCluster *error) +{ MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { *timeoutOccurred = 0; Event *eventPtr = reinterpret_cast(const_cast(lvEventPtr)); // 1 Second timeout Data *dataPtrOut = eventPtr->waitData(1); *lvDataPtrOut = reinterpret_cast(dataPtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { *timeoutOccurred = 1; // errorCode = bogusError; // errorMessage = e.what(); @@ -99,13 +108,15 @@ EXPORT void mdsplus_event_waitData(const void *lvEventPtr, void **lvDataPtrOut, } EXPORT void mdsplus_event_wait(const void *lvEventPtr, int *timeoutOccurred, - ErrorCluster *error) { + ErrorCluster *error) +{ Event *eventPtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; *timeoutOccurred = 0; - try { + try + { eventPtr = reinterpret_cast(const_cast(lvEventPtr)); // 1 Sec timeout @@ -113,7 +124,9 @@ EXPORT void mdsplus_event_wait(const void *lvEventPtr, int *timeoutOccurred, eventPtr->wait(1); std::cout << "EVENTO ARRIVATO....\n"; - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { *timeoutOccurred = 1; // errorCode = bogusError; // errorMessage = e.what(); @@ -122,27 +135,33 @@ EXPORT void mdsplus_event_wait(const void *lvEventPtr, int *timeoutOccurred, } EXPORT void mdsplus_event_getName(const void *lvEventPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error) { + LStrHandle lvStrHdlOut, ErrorCluster *error) +{ Event *eventPtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { eventPtr = reinterpret_cast(const_cast(lvEventPtr)); strOut = strdup(eventPtr->getName()); std::size_t strOutLen = std::strlen(strOut); errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { deleteNativeArray(strOut); errorCode = bogusError; errorMessage = e.what(); @@ -154,13 +173,15 @@ EXPORT void mdsplus_event_getName(const void *lvEventPtr, EXPORT void mdsplus_event_waitRaw(const void *lvEventPtr, LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Event *eventPtr = NULL; char const *byteArrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { eventPtr = reinterpret_cast(const_cast(lvEventPtr)); size_t byteArrLen = 0; std::cout << "ASPETTO EVENTO RAW ....\n"; @@ -169,13 +190,17 @@ EXPORT void mdsplus_event_waitRaw(const void *lvEventPtr, errorCode = NumericArrayResize(iB, 1, reinterpret_cast(&lvByteArrHdlOut), static_cast(byteArrLen)); - if (!errorCode) { + if (!errorCode) + { for (size_t i = 0; i < byteArrLen; i++) (*lvByteArrHdlOut)->elt[i] = static_cast(byteArrOut[i]); (*lvByteArrHdlOut)->dimSize = static_cast(byteArrLen); - } else + } + else errorMessage = (char *)"NumericArrayResize error"; - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -184,13 +209,17 @@ EXPORT void mdsplus_event_waitRaw(const void *lvEventPtr, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_event_setEvent(const char *evNameIn, ErrorCluster *error) { +EXPORT void mdsplus_event_setEvent(const char *evNameIn, ErrorCluster *error) +{ MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { Event::setEvent(const_cast(evNameIn)); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -201,15 +230,19 @@ EXPORT void mdsplus_event_setEvent(const char *evNameIn, ErrorCluster *error) { EXPORT void mdsplus_event_setEvent_data(const char *evNameIn, const void *lvDataPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Data *dataPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); Event::setEvent(const_cast(evNameIn), dataPtrIn); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -220,19 +253,23 @@ EXPORT void mdsplus_event_setEvent_data(const char *evNameIn, EXPORT void mdsplus_event_setEventRaw(const char *evNameIn, LByteArrHdl lvByteArrHdlIn, - ErrorCluster *error) { + ErrorCluster *error) +{ char *int8Arr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { int int8ArrLen = static_cast((*lvByteArrHdlIn)->dimSize); int8Arr = new char[int8ArrLen]; for (int i = 0; i < int8ArrLen; i++) int8Arr[i] = static_cast((*lvByteArrHdlIn)->elt[i]); Event::setEventRaw(const_cast(evNameIn), int8ArrLen, int8Arr); delete[] int8Arr; - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { delete[] int8Arr; errorCode = bogusError; errorMessage = e.what(); diff --git a/mdsobjects/labview/mdsipobjectswrp.cpp b/mdsobjects/labview/mdsipobjectswrp.cpp index 9462f1ed69..d89ca9c902 100644 --- a/mdsobjects/labview/mdsipobjectswrp.cpp +++ b/mdsobjects/labview/mdsipobjectswrp.cpp @@ -26,16 +26,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EXPORT void mdsplus_connection_constructor(void **lvConnectionPtrOut, const char *ipPortIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MDSplus::Connection *connectionPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { MDSplus::Connection *connectionPtrOut = new MDSplus::Connection(const_cast(ipPortIn)); *lvConnectionPtrOut = reinterpret_cast(connectionPtrOut); - } catch (const MDSplus::MdsException &e) { + } + catch (const MDSplus::MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -44,7 +48,8 @@ EXPORT void mdsplus_connection_constructor(void **lvConnectionPtrOut, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_connection_destructor(void **lvConnectionPtr) { +EXPORT void mdsplus_connection_destructor(void **lvConnectionPtr) +{ MDSplus::Connection *connectionPtr = reinterpret_cast(*lvConnectionPtr); delete connectionPtr; @@ -54,17 +59,21 @@ EXPORT void mdsplus_connection_destructor(void **lvConnectionPtr) { EXPORT void mdsplus_connection_getData(const void *lvConnectionPtr, void **lvDataPtrOut, const char *expressionIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { MDSplus::Connection *connectionPtr = reinterpret_cast( const_cast(lvConnectionPtr)); MDSplus::Data *dataPtrOut = connectionPtr->get((char *)expressionIn); *lvDataPtrOut = reinterpret_cast(dataPtrOut); - } catch (const MDSplus::MdsException &e) { + } + catch (const MDSplus::MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); } @@ -74,12 +83,14 @@ EXPORT void mdsplus_connection_getData(const void *lvConnectionPtr, EXPORT void mdsplus_connection_putData(const void *lvConnectionPtr, const void *lvDataPtrIn, const char *pathIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MDSplus::Data *dataPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; - try { + try + { MDSplus::Connection *connectionPtr = reinterpret_cast( const_cast(lvConnectionPtr)); @@ -87,7 +98,9 @@ EXPORT void mdsplus_connection_putData(const void *lvConnectionPtr, reinterpret_cast(const_cast(lvDataPtrIn)); if (connectionPtr) connectionPtr->put(pathIn, (char *)"$", &dataPtrIn, 1); - } catch (const MDSplus::MdsException &e) { + } + catch (const MDSplus::MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -98,16 +111,20 @@ EXPORT void mdsplus_connection_putData(const void *lvConnectionPtr, EXPORT void mdsplus_connection_openTree(const void *lvConnectionPtr, const char *tree, int shot, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { MDSplus::Connection *connectionPtr = reinterpret_cast( const_cast(lvConnectionPtr)); connectionPtr->openTree((char *)tree, shot); - } catch (const MDSplus::MdsException &e) { + } + catch (const MDSplus::MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); } @@ -115,16 +132,20 @@ EXPORT void mdsplus_connection_openTree(const void *lvConnectionPtr, } EXPORT void mdsplus_connection_closeTree(const void *lvConnectionPtr, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { MDSplus::Connection *connectionPtr = reinterpret_cast( const_cast(lvConnectionPtr)); connectionPtr->closeAllTrees(); - } catch (const MDSplus::MdsException &e) { + } + catch (const MDSplus::MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); } @@ -134,19 +155,23 @@ EXPORT void mdsplus_connection_closeTree(const void *lvConnectionPtr, EXPORT void mdsplus_connection_getNode(const void *lvConnectionPtr, void **lvTreeNodePtrOut, const char *pathIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MDSplus::TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { MDSplus::Connection *connectionPtr = reinterpret_cast( const_cast(lvConnectionPtr)); treeNodePtrOut = connectionPtr->getNode(const_cast(pathIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); fillErrorCluster(errorCode, errorSource, errorMessage, error); - } catch (const MDSplus::MdsException &mdsE) { + } + catch (const MDSplus::MdsException &mdsE) + { errorCode = bogusError; *lvTreeNodePtrOut = 0; fillErrorCluster(errorCode, errorSource, const_cast(mdsE.what()), diff --git a/mdsobjects/labview/mdsobjectswrp.h b/mdsobjects/labview/mdsobjectswrp.h index e7dc3e4dc8..b6831f191f 100644 --- a/mdsobjects/labview/mdsobjectswrp.h +++ b/mdsobjects/labview/mdsobjectswrp.h @@ -19,7 +19,7 @@ typedef float float32; typedef double float64; typedef uint32_t Bool32; #ifndef __MINGW64__ -#pragma pack( \ +#pragma pack( \ 1) //!!! Possible origin of memory misalignments in 64 bit architectures? #endif @@ -32,79 +32,92 @@ typedef uint32_t Bool32; /* lv_prolog.h and lv_epilog.h set up the correct alignment for LabVIEW data. */ #include -typedef struct { +typedef struct +{ LVBoolean status; int32 code; LStrHandle source; } ErrorCluster; -typedef struct { +typedef struct +{ int32 dimSize; int8 elt[1]; } LByteArr; typedef LByteArr **LByteArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; uInt8 elt[1]; } LUByteArr; typedef LUByteArr **LUByteArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; double elt[1]; } LDblArr; typedef LDblArr **LDblArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; float elt[1]; } LFltArr; typedef LFltArr **LFltArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; int32 elt[1]; } LIntArr; typedef LIntArr **LIntArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; uInt32 elt[1]; } LUIntArr; typedef LUIntArr **LUIntArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; int64 elt[1]; } LLngArr; typedef LLngArr **LLngArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; uInt64 elt[1]; } LULngArr; typedef LULngArr **LULngArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; int16 elt[1]; } LShtArr; typedef LShtArr **LShtArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; uInt16 elt[1]; } LUShtArr; typedef LUShtArr **LUShtArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; LStrHandle elm[]; } LStrArr; typedef LStrArr **LStrArrHdl; -typedef struct { +typedef struct +{ int32 dimSize; void *elt[1]; } LPtrArr; @@ -116,936 +129,937 @@ void fillErrorCluster(MgErr code, const char *source, const char *message, ErrorCluster *error); #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/********** ARRAY **********/ -EXPORT void mdsplus_array_constructor(void **lvArrayPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_array_destructor(void **lvArrayPtr); -EXPORT void mdsplus_array_getByteArray(const void *lvArrayPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_array_getDoubleArray(const void *lvArrayPtr, - LDblArrHdl lvDblArrHdlOut, + /********** ARRAY **********/ + EXPORT void mdsplus_array_constructor(void **lvArrayPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_array_destructor(void **lvArrayPtr); + EXPORT void mdsplus_array_getByteArray(const void *lvArrayPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getDoubleArray(const void *lvArrayPtr, + LDblArrHdl lvDblArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getElementAt(const void *lvArrayPtr, + void **lvDataPtrOut, int dimIn, + ErrorCluster *error); + EXPORT void mdsplus_array_getElementAt_dims(const void *lvArrayPtr, + void **lvDataPtrOut, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_array_getFloatArray(const void *lvArrayPtr, + LFltArrHdl lvFltArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getIntArray(const void *lvArrayPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getInfo(const void *lvArrayPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getLongArray(const void *lvArrayPtr, + LLngArrHdl lvLngArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getShape(const void *lvArrayPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getShortArray(const void *lvArrayPtr, + LShtArrHdl lvShtArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getSize(const void *lvArrayPtr, int *sizeOut, + ErrorCluster *error); + EXPORT void mdsplus_array_getStringArray(const void *lvArrayPtr, + LStrArrHdl lvStrArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_array_setElementAt(const void *lvArrayPtr, int dimIn, + const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_array_getElementAt(const void *lvArrayPtr, - void **lvDataPtrOut, int dimIn, + EXPORT void mdsplus_array_setElementAt_dims(const void *lvArrayPtr, + const LIntArrHdl lvIntArrHdlIn, + const void *lvDataPtrIn, + ErrorCluster *error); + + /********** COMPOUND **********/ + EXPORT void mdsplus_compound_constructor(void **lvCompoundPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_compound_destructor(void **lvCompoundPtr); + + /********** DATA **********/ + EXPORT void mdsplus_data_compile(void **lvDataPtrOut, const char *exprIn, + ErrorCluster *error); + EXPORT void mdsplus_data_compile_tree(void **lvDataPtrOut, const char *exprIn, + const void *lvTreePtrIn, + ErrorCluster *error); + EXPORT void mdsplus_data_data(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_decompile(const void *lvDataPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + EXPORT void mdsplus_data_deserialize(void **lvDataPtrOut, + const char *serializedIn, ErrorCluster *error); -EXPORT void mdsplus_array_getElementAt_dims(const void *lvArrayPtr, - void **lvDataPtrOut, - const LIntArrHdl lvIntArrHdlIn, + EXPORT void mdsplus_data_deserialize_data(void **lvDataPtrOut, + const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_array_getFloatArray(const void *lvArrayPtr, - LFltArrHdl lvFltArrHdlOut, + EXPORT void mdsplus_data_destructor(void **lvDataPtr); + EXPORT void mdsplus_data_evaluate(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_execute(void **lvDataPtrOut, const char *exprIn, + ErrorCluster *error); + EXPORT void mdsplus_data_execute_tree(void **lvDataPtrOut, const char *exprIn, + const void *lvTreePtrIn, ErrorCluster *error); -EXPORT void mdsplus_array_getIntArray(const void *lvArrayPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_array_getInfo(const void *lvArrayPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, + EXPORT void mdsplus_data_getByte(const void *lvDataPtr, char *byteOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getByteArray(const void *lvDataPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getDouble(const void *lvDataPtr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getDoubleArray(const void *lvDataPtr, + LDblArrHdl lvDblArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getError(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getFloat(const void *lvDataPtr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getFloatArray(const void *lvDataPtr, + LFltArrHdl lvFltArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getHelp(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getInfo(const void *lvDataPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getInt(const void *lvDataPtr, int *intOut, ErrorCluster *error); -EXPORT void mdsplus_array_getLongArray(const void *lvArrayPtr, - LLngArrHdl lvLngArrHdlOut, + EXPORT void mdsplus_data_getIntArray(const void *lvDataPtr, + LIntArrHdl lvIntArrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_array_getShape(const void *lvArrayPtr, - LIntArrHdl lvIntArrHdlOut, + EXPORT void mdsplus_data_getLong(const void *lvDataPtr, int64_t *longOut, ErrorCluster *error); -EXPORT void mdsplus_array_getShortArray(const void *lvArrayPtr, - LShtArrHdl lvShtArrHdlOut, + EXPORT void mdsplus_data_getLongArray(const void *lvDataPtr, + LLngArrHdl lvLngArrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_array_getSize(const void *lvArrayPtr, int *sizeOut, - ErrorCluster *error); -EXPORT void mdsplus_array_getStringArray(const void *lvArrayPtr, - LStrArrHdl lvStrArrHdlOut, + EXPORT void mdsplus_data_getShape(const void *lvDataPtr, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getShort(const void *lvDataPtr, short *shortOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getShortArray(const void *lvDataPtr, + LShtArrHdl lvShtArrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_array_setElementAt(const void *lvArrayPtr, int dimIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_array_setElementAt_dims(const void *lvArrayPtr, - const LIntArrHdl lvIntArrHdlIn, - const void *lvDataPtrIn, - ErrorCluster *error); - -/********** COMPOUND **********/ -EXPORT void mdsplus_compound_constructor(void **lvCompoundPtrOut, + EXPORT void mdsplus_data_getSize(const void *lvDataPtr, int *sizeOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getString(const void *lvDataPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + EXPORT void mdsplus_data_getStringArray(const void *lvDataPtr, + LStrArrHdl lvStrArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getUnits(const void *lvDataPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_getValidation(const void *lvDataPtr, + void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_data_plot(const void *lvDataPtr, ErrorCluster *error); + EXPORT void mdsplus_data_serialize(const void *lvDataPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_data_setError(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_data_setHelp(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_data_setUnits(void *lvDataPtr, const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_data_setValidation(void *lvDataPtr, const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_compound_destructor(void **lvCompoundPtr); -/********** DATA **********/ -EXPORT void mdsplus_data_compile(void **lvDataPtrOut, const char *exprIn, + /********** EMPTY **********/ + EXPORT void mdsplus_empty_destructor(void **lvEmptyPtr); + + /********** EVENT **********/ + EXPORT void mdsplus_event_constructor(void **lvEventPtrOut, + const char *evNameIn, + ErrorCluster *error); + EXPORT void mdsplus_event_destructor(void **lvEventPtr); + EXPORT void mdsplus_event_waitData(const void *lvEventPtr, void **lvDataPtrOut, + int *timeoutOccurred, ErrorCluster *error); + EXPORT void mdsplus_event_wait(const void *lvEventPtr, int *timeoutOccurred, ErrorCluster *error); -EXPORT void mdsplus_data_compile_tree(void **lvDataPtrOut, const char *exprIn, - const void *lvTreePtrIn, - ErrorCluster *error); -EXPORT void mdsplus_data_data(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_decompile(const void *lvDataPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_data_deserialize(void **lvDataPtrOut, - const char *serializedIn, - ErrorCluster *error); -EXPORT void mdsplus_data_deserialize_data(void **lvDataPtrOut, + // EXPORT void mdsplus_event_abort(const void *lvEventPtr, ErrorCluster * + // error); + EXPORT void mdsplus_event_getName(const void *lvEventPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + EXPORT void mdsplus_event_waitRaw(const void *lvEventPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_event_setEvent(const char *evNameIn, ErrorCluster *error); + EXPORT void mdsplus_event_setEvent_data(const char *evNameIn, const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_data_destructor(void **lvDataPtr); -EXPORT void mdsplus_data_evaluate(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_execute(void **lvDataPtrOut, const char *exprIn, - ErrorCluster *error); -EXPORT void mdsplus_data_execute_tree(void **lvDataPtrOut, const char *exprIn, - const void *lvTreePtrIn, + EXPORT void mdsplus_event_setEventRaw(const char *evNameIn, + LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_constructor(void **lvREventPtrOut, + const char *evNameIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_destructor(void **lvREventPtr); + EXPORT void mdsplus_revent_getData(const void *lvREventPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_revent_getName(const void *lvREventPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + EXPORT void mdsplus_revent_getRaw(const void *lvREventPtr, + LByteArrHdl lvByteArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_revent_getTime(const void *lvREventPtr, + void **lvUint64PtrOut, ErrorCluster *error); + EXPORT void mdsplus_revent_run(const void *lvREventPtr, ErrorCluster *error); + EXPORT void mdsplus_revent_setEvent(const char *evNameIn, + const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_data_getByte(const void *lvDataPtr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getByteArray(const void *lvDataPtr, - LByteArrHdl lvByteArrHdlOut, + EXPORT void mdsplus_revent_setEventAndWait(const char *evNameIn, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_setEventRaw(const char *evNameIn, + LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_setEventRawAndWait(const char *evNameIn, + LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); + + /********** FLOAT32 **********/ + EXPORT void mdsplus_float32_constructor(void **lvFloat32PtrOut, float valIn, + ErrorCluster *error); + EXPORT void mdsplus_float32_destructor(void **lvFloat32Ptr); + EXPORT void mdsplus_float32_getByte(const void *lvFloat32Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_data_getDouble(const void *lvDataPtr, double *doubleOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getDoubleArray(const void *lvDataPtr, - LDblArrHdl lvDblArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getError(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getFloat(const void *lvDataPtr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getFloatArray(const void *lvDataPtr, - LFltArrHdl lvFltArrHdlOut, + EXPORT void mdsplus_float32_getDouble(const void *lvFloat32Ptr, + double *doubleOut, ErrorCluster *error); + EXPORT void mdsplus_float32_getFloat(const void *lvFloat32Ptr, float *floatOut, ErrorCluster *error); -EXPORT void mdsplus_data_getHelp(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getInfo(const void *lvDataPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getInt(const void *lvDataPtr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getIntArray(const void *lvDataPtr, - LIntArrHdl lvIntArrHdlOut, + EXPORT void mdsplus_float32_getInt(const void *lvFloat32Ptr, int *intOut, ErrorCluster *error); -EXPORT void mdsplus_data_getLong(const void *lvDataPtr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getLongArray(const void *lvDataPtr, - LLngArrHdl lvLngArrHdlOut, + EXPORT void mdsplus_float32_getLong(const void *lvFloat32Ptr, int64_t *longOut, ErrorCluster *error); -EXPORT void mdsplus_data_getShape(const void *lvDataPtr, - LIntArrHdl lvIntArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getShort(const void *lvDataPtr, short *shortOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getShortArray(const void *lvDataPtr, - LShtArrHdl lvShtArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getSize(const void *lvDataPtr, int *sizeOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getString(const void *lvDataPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_data_getStringArray(const void *lvDataPtr, - LStrArrHdl lvStrArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getUnits(const void *lvDataPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_getValidation(const void *lvDataPtr, - void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_data_plot(const void *lvDataPtr, ErrorCluster *error); -EXPORT void mdsplus_data_serialize(const void *lvDataPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_data_setError(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_data_setHelp(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_data_setUnits(void *lvDataPtr, const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_data_setValidation(void *lvDataPtr, const void *lvDataPtrIn, + EXPORT void mdsplus_float32_getShort(const void *lvFloat32Ptr, short *shortOut, ErrorCluster *error); -/********** EMPTY **********/ -EXPORT void mdsplus_empty_destructor(void **lvEmptyPtr); + /********** FLOAT32ARRAY **********/ + EXPORT void mdsplus_float32array_constructor(void **lvFloat32ArrayPtrOut, + const LFltArrHdl lvFltArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_float32array_constructor_dims( + void **lvFloat32ArrayPtrOut, const LFltArrHdl lvFltArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_float32array_destructor(void **lvFloat32ArrayPtr); -/********** EVENT **********/ -EXPORT void mdsplus_event_constructor(void **lvEventPtrOut, - const char *evNameIn, - ErrorCluster *error); -EXPORT void mdsplus_event_destructor(void **lvEventPtr); -EXPORT void mdsplus_event_waitData(const void *lvEventPtr, void **lvDataPtrOut, - int *timeoutOccurred, ErrorCluster *error); -EXPORT void mdsplus_event_wait(const void *lvEventPtr, int *timeoutOccurred, - ErrorCluster *error); -// EXPORT void mdsplus_event_abort(const void *lvEventPtr, ErrorCluster * -// error); -EXPORT void mdsplus_event_getName(const void *lvEventPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_event_waitRaw(const void *lvEventPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_event_setEvent(const char *evNameIn, ErrorCluster *error); -EXPORT void mdsplus_event_setEvent_data(const char *evNameIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_event_setEventRaw(const char *evNameIn, - LByteArrHdl lvByteArrHdlIn, + /********** FLOAT64 **********/ + EXPORT void mdsplus_float64_constructor(void **lvFloat64PtrOut, double valIn, + ErrorCluster *error); + EXPORT void mdsplus_float64_destructor(void **lvFloat64Ptr); + EXPORT void mdsplus_float64_getByte(const void *lvFloat64Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_revent_constructor(void **lvREventPtrOut, - const char *evNameIn, + EXPORT void mdsplus_float64_getDouble(const void *lvFloat64Ptr, + double *doubleOut, ErrorCluster *error); + EXPORT void mdsplus_float64_getFloat(const void *lvFloat64Ptr, float *floatOut, ErrorCluster *error); -EXPORT void mdsplus_revent_destructor(void **lvREventPtr); -EXPORT void mdsplus_revent_getData(const void *lvREventPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_revent_getName(const void *lvREventPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_revent_getRaw(const void *lvREventPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_revent_getTime(const void *lvREventPtr, - void **lvUint64PtrOut, ErrorCluster *error); -EXPORT void mdsplus_revent_run(const void *lvREventPtr, ErrorCluster *error); -EXPORT void mdsplus_revent_setEvent(const char *evNameIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_revent_setEventAndWait(const char *evNameIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_revent_setEventRaw(const char *evNameIn, - LByteArrHdl lvByteArrHdlIn, + EXPORT void mdsplus_float64_getInt(const void *lvFloat64Ptr, int *intOut, + ErrorCluster *error); + EXPORT void mdsplus_float64_getLong(const void *lvFloat64Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_float64_getShort(const void *lvFloat64Ptr, short *shortOut, ErrorCluster *error); -EXPORT void mdsplus_revent_setEventRawAndWait(const char *evNameIn, - LByteArrHdl lvByteArrHdlIn, - ErrorCluster *error); -/********** FLOAT32 **********/ -EXPORT void mdsplus_float32_constructor(void **lvFloat32PtrOut, float valIn, + /********** FLOAT64ARRAY **********/ + EXPORT void mdsplus_float64array_constructor(void **lvFloat64ArrayPtrOut, + const LDblArrHdl lvDblArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_float64array_constructor_dims( + void **lvFloat64ArrayPtrOut, const LDblArrHdl lvDblArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_float64array_destructor(void **lvFloat64ArrayPtr); + + /********** INT16 **********/ + EXPORT void mdsplus_int16_constructor(void **lvInt16PtrOut, short valIn, ErrorCluster *error); -EXPORT void mdsplus_float32_destructor(void **lvFloat32Ptr); -EXPORT void mdsplus_float32_getByte(const void *lvFloat32Ptr, char *byteOut, + EXPORT void mdsplus_int16_destructor(void **lvInt16Ptr); + EXPORT void mdsplus_int16_getByte(const void *lvInt16Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_float32_getDouble(const void *lvFloat32Ptr, - double *doubleOut, ErrorCluster *error); -EXPORT void mdsplus_float32_getFloat(const void *lvFloat32Ptr, float *floatOut, + EXPORT void mdsplus_int16_getDouble(const void *lvInt16Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_int16_getFloat(const void *lvInt16Ptr, float *floatOut, ErrorCluster *error); -EXPORT void mdsplus_float32_getInt(const void *lvFloat32Ptr, int *intOut, + EXPORT void mdsplus_int16_getInt(const void *lvInt16Ptr, int *intOut, ErrorCluster *error); -EXPORT void mdsplus_float32_getLong(const void *lvFloat32Ptr, int64_t *longOut, + EXPORT void mdsplus_int16_getLong(const void *lvInt16Ptr, int64_t *longOut, ErrorCluster *error); -EXPORT void mdsplus_float32_getShort(const void *lvFloat32Ptr, short *shortOut, + EXPORT void mdsplus_int16_getShort(const void *lvInt16Ptr, short *shortOut, ErrorCluster *error); -/********** FLOAT32ARRAY **********/ -EXPORT void mdsplus_float32array_constructor(void **lvFloat32ArrayPtrOut, - const LFltArrHdl lvFltArrHdlIn, + /********** INT16ARRAY **********/ + EXPORT void mdsplus_int16array_constructor(void **lvInt16ArrayPtrOut, + const LShtArrHdl lvShtArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_float32array_constructor_dims( - void **lvFloat32ArrayPtrOut, const LFltArrHdl lvFltArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_float32array_destructor(void **lvFloat32ArrayPtr); + EXPORT void mdsplus_int16array_constructor_dims(void **lvInt16ArrayPtrOut, + const LShtArrHdl lvShtArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_int16array_destructor(void **lvInt16ArrayPtr); -/********** FLOAT64 **********/ -EXPORT void mdsplus_float64_constructor(void **lvFloat64PtrOut, double valIn, + /********** INT32 **********/ + EXPORT void mdsplus_int32_constructor(void **lvInt32PtrOut, int valIn, ErrorCluster *error); -EXPORT void mdsplus_float64_destructor(void **lvFloat64Ptr); -EXPORT void mdsplus_float64_getByte(const void *lvFloat64Ptr, char *byteOut, + EXPORT void mdsplus_int32_destructor(void **lvInt32Ptr); + EXPORT void mdsplus_int32_getByte(const void *lvInt32Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_float64_getDouble(const void *lvFloat64Ptr, - double *doubleOut, ErrorCluster *error); -EXPORT void mdsplus_float64_getFloat(const void *lvFloat64Ptr, float *floatOut, + EXPORT void mdsplus_int32_getDouble(const void *lvInt32Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_int32_getFloat(const void *lvInt32Ptr, float *floatOut, ErrorCluster *error); -EXPORT void mdsplus_float64_getInt(const void *lvFloat64Ptr, int *intOut, + EXPORT void mdsplus_int32_getInt(const void *lvInt32Ptr, int *intOut, ErrorCluster *error); -EXPORT void mdsplus_float64_getLong(const void *lvFloat64Ptr, int64_t *longOut, + EXPORT void mdsplus_int32_getLong(const void *lvInt32Ptr, int64_t *longOut, ErrorCluster *error); -EXPORT void mdsplus_float64_getShort(const void *lvFloat64Ptr, short *shortOut, + EXPORT void mdsplus_int32_getShort(const void *lvInt32Ptr, short *shortOut, ErrorCluster *error); -/********** FLOAT64ARRAY **********/ -EXPORT void mdsplus_float64array_constructor(void **lvFloat64ArrayPtrOut, - const LDblArrHdl lvDblArrHdlIn, + /********** INT32ARRAY **********/ + EXPORT void mdsplus_int32array_constructor(void **lvInt32ArrayPtrOut, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_float64array_constructor_dims( - void **lvFloat64ArrayPtrOut, const LDblArrHdl lvDblArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_float64array_destructor(void **lvFloat64ArrayPtr); + EXPORT void mdsplus_int32array_constructor_dims( + void **lvInt32ArrayPtrOut, const LIntArrHdl lvIntArrHdlIn, + const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error); + EXPORT void mdsplus_int32array_destructor(void **lvInt32ArrayPtr); -/********** INT16 **********/ -EXPORT void mdsplus_int16_constructor(void **lvInt16PtrOut, short valIn, - ErrorCluster *error); -EXPORT void mdsplus_int16_destructor(void **lvInt16Ptr); -EXPORT void mdsplus_int16_getByte(const void *lvInt16Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_int16_getDouble(const void *lvInt16Ptr, double *doubleOut, + /********** INT64 **********/ + EXPORT void mdsplus_int64_constructor(void **lvInt64PtrOut, int64_t valIn, + ErrorCluster *error); + EXPORT void mdsplus_int64_destructor(void **lvInt64Ptr); + EXPORT void mdsplus_int64_getByte(const void *lvInt64Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_int16_getFloat(const void *lvInt16Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_int16_getInt(const void *lvInt16Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_int16_getLong(const void *lvInt16Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_int16_getShort(const void *lvInt16Ptr, short *shortOut, - ErrorCluster *error); - -/********** INT16ARRAY **********/ -EXPORT void mdsplus_int16array_constructor(void **lvInt16ArrayPtrOut, - const LShtArrHdl lvShtArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int16array_constructor_dims(void **lvInt16ArrayPtrOut, - const LShtArrHdl lvShtArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int16array_destructor(void **lvInt16ArrayPtr); - -/********** INT32 **********/ -EXPORT void mdsplus_int32_constructor(void **lvInt32PtrOut, int valIn, + EXPORT void mdsplus_int64_getDouble(const void *lvInt64Ptr, double *doubleOut, ErrorCluster *error); -EXPORT void mdsplus_int32_destructor(void **lvInt32Ptr); -EXPORT void mdsplus_int32_getByte(const void *lvInt32Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_int32_getDouble(const void *lvInt32Ptr, double *doubleOut, - ErrorCluster *error); -EXPORT void mdsplus_int32_getFloat(const void *lvInt32Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_int32_getInt(const void *lvInt32Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_int32_getLong(const void *lvInt32Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_int32_getShort(const void *lvInt32Ptr, short *shortOut, + EXPORT void mdsplus_int64_getFloat(const void *lvInt64Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_int64_getInt(const void *lvInt64Ptr, int *intOut, ErrorCluster *error); + EXPORT void mdsplus_int64_getLong(const void *lvInt64Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_int64_getShort(const void *lvInt64Ptr, short *shortOut, + ErrorCluster *error); -/********** INT32ARRAY **********/ -EXPORT void mdsplus_int32array_constructor(void **lvInt32ArrayPtrOut, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int32array_constructor_dims( - void **lvInt32ArrayPtrOut, const LIntArrHdl lvIntArrHdlIn, - const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error); -EXPORT void mdsplus_int32array_destructor(void **lvInt32ArrayPtr); + /********** INT64ARRAY **********/ + EXPORT void mdsplus_int64array_constructor(void **lvInt64ArrayPtrOut, + const LLngArrHdl lvLngArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_int64array_constructor_dims(void **lvInt64ArrayPtrOut, + const LLngArrHdl lvLngArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_int64array_destructor(void **lvInt64ArrayPtr); -/********** INT64 **********/ -EXPORT void mdsplus_int64_constructor(void **lvInt64PtrOut, int64_t valIn, - ErrorCluster *error); -EXPORT void mdsplus_int64_destructor(void **lvInt64Ptr); -EXPORT void mdsplus_int64_getByte(const void *lvInt64Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_int64_getDouble(const void *lvInt64Ptr, double *doubleOut, - ErrorCluster *error); -EXPORT void mdsplus_int64_getFloat(const void *lvInt64Ptr, float *floatOut, + /********** INT8 **********/ + EXPORT void mdsplus_int8_constructor(void **lvInt8PtrOut, char valIn, + ErrorCluster *error); + EXPORT void mdsplus_int8_destructor(void **lvInt8Ptr); + EXPORT void mdsplus_int8_getByte(const void *lvInt8Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_int64_getInt(const void *lvInt64Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_int64_getLong(const void *lvInt64Ptr, int64_t *longOut, + EXPORT void mdsplus_int8_getDouble(const void *lvInt8Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_int8_getFloat(const void *lvInt8Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_int8_getInt(const void *lvInt8Ptr, int *intOut, ErrorCluster *error); -EXPORT void mdsplus_int64_getShort(const void *lvInt64Ptr, short *shortOut, + EXPORT void mdsplus_int8_getLong(const void *lvInt8Ptr, int64_t *longOut, ErrorCluster *error); + EXPORT void mdsplus_int8_getShort(const void *lvInt8Ptr, short *shortOut, + ErrorCluster *error); -/********** INT64ARRAY **********/ -EXPORT void mdsplus_int64array_constructor(void **lvInt64ArrayPtrOut, - const LLngArrHdl lvLngArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int64array_constructor_dims(void **lvInt64ArrayPtrOut, - const LLngArrHdl lvLngArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int64array_destructor(void **lvInt64ArrayPtr); + /********** INT8ARRAY **********/ + EXPORT void mdsplus_int8array_constructor(void **lvInt8ArrayPtrOut, + const LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_int8array_constructor_dims(void **lvInt8ArrayPtrOut, + const LByteArrHdl lvByteArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_int8array_destructor(void **lvInt8ArrayPtr); -/********** INT8 **********/ -EXPORT void mdsplus_int8_constructor(void **lvInt8PtrOut, char valIn, + /********** RANGE **********/ + EXPORT void mdsplus_range_constructor(void **lvRangePtrOut, + const void *lvBeginDataPtrIn, + const void *lvEndingDataPtrIn, + const void *lvDeltaValDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_range_destructor(void **lvRangePtr, ErrorCluster *error); + EXPORT void mdsplus_range_getBegin(const void *lvRangePtr, void **lvDataPtrOut, ErrorCluster *error); -EXPORT void mdsplus_int8_destructor(void **lvInt8Ptr); -EXPORT void mdsplus_int8_getByte(const void *lvInt8Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_int8_getDouble(const void *lvInt8Ptr, double *doubleOut, - ErrorCluster *error); -EXPORT void mdsplus_int8_getFloat(const void *lvInt8Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_int8_getInt(const void *lvInt8Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_int8_getLong(const void *lvInt8Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_int8_getShort(const void *lvInt8Ptr, short *shortOut, - ErrorCluster *error); - -/********** INT8ARRAY **********/ -EXPORT void mdsplus_int8array_constructor(void **lvInt8ArrayPtrOut, - const LByteArrHdl lvByteArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int8array_constructor_dims(void **lvInt8ArrayPtrOut, - const LByteArrHdl lvByteArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_int8array_destructor(void **lvInt8ArrayPtr); - -/********** RANGE **********/ -EXPORT void mdsplus_range_constructor(void **lvRangePtrOut, - const void *lvBeginDataPtrIn, - const void *lvEndingDataPtrIn, - const void *lvDeltaValDataPtrIn, + EXPORT void mdsplus_range_getEnding(const void *lvRangePtr, void **lvDataPtrOut, ErrorCluster *error); -EXPORT void mdsplus_range_destructor(void **lvRangePtr, ErrorCluster *error); -EXPORT void mdsplus_range_getBegin(const void *lvRangePtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_range_getEnding(const void *lvRangePtr, void **lvDataPtrOut, + EXPORT void mdsplus_range_getDeltaVal(const void *lvRangePtr, + void **lvDataPtrOut, ErrorCluster *error); + EXPORT void mdsplus_range_setBegin(const void *lvRangePtr, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_range_setEnding(const void *lvRangePtr, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_range_setDeltaVal(const void *lvRangePtr, + const void *lvDataPtrIn, + ErrorCluster *error); + + /********** SIGNAL **********/ + EXPORT void mdsplus_signal_constructor(void **lvSignalPtrOut, + const void *lvDataPtrIn, + const void *lvRawDataPtrIn, + const void *lvDim0DataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_signal_destructor(void **lvSignalPtr, ErrorCluster *error); + EXPORT void mdsplus_signal_getData(const void *lvSignalPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_signal_getRaw(const void *lvSignalPtr, void **lvRawPtrOut, ErrorCluster *error); -EXPORT void mdsplus_range_getDeltaVal(const void *lvRangePtr, - void **lvDataPtrOut, ErrorCluster *error); -EXPORT void mdsplus_range_setBegin(const void *lvRangePtr, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_range_setEnding(const void *lvRangePtr, - const void *lvDataPtrIn, + EXPORT void mdsplus_signal_getDim(const void *lvSignalPtr, void **lvDimPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_signal_setData(const void *lvSignalPtr, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_signal_setRaw(const void *lvSignalPtr, + const void *lvRawPtrIn, ErrorCluster *error); + EXPORT void mdsplus_signal_setDim(const void *lvSignalPtr, + const void *lvDimPtrIn, ErrorCluster *error); + + /********** REVENT **********/ + EXPORT void mdsplus_revent_constructor(void **lvREventPtrOut, + const char *evNameIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_destructor(void **lvREventPtr); + EXPORT void mdsplus_revent_getData(const void *lvREventPtr, void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_revent_getName(const void *lvREventPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + EXPORT void mdsplus_revent_getRaw(const void *lvREventPtr, + LByteArrHdl lvByteArrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_range_setDeltaVal(const void *lvRangePtr, + EXPORT void mdsplus_revent_getTime(const void *lvREventPtr, + void **lvUint64PtrOut, ErrorCluster *error); + EXPORT void mdsplus_revent_run(const void *lvREventPtr, ErrorCluster *error); + EXPORT void mdsplus_revent_setEvent(const char *evNameIn, const void *lvDataPtrIn, ErrorCluster *error); + EXPORT void mdsplus_revent_setEventAndWait(const char *evNameIn, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_setEventRaw(const char *evNameIn, + LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_revent_setEventRawAndWait(const char *evNameIn, + LByteArrHdl lvByteArrHdlIn, + ErrorCluster *error); -/********** SIGNAL **********/ -EXPORT void mdsplus_signal_constructor(void **lvSignalPtrOut, - const void *lvDataPtrIn, - const void *lvRawDataPtrIn, - const void *lvDim0DataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_signal_destructor(void **lvSignalPtr, ErrorCluster *error); -EXPORT void mdsplus_signal_getData(const void *lvSignalPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_signal_getRaw(const void *lvSignalPtr, void **lvRawPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_signal_getDim(const void *lvSignalPtr, void **lvDimPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_signal_setData(const void *lvSignalPtr, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_signal_setRaw(const void *lvSignalPtr, - const void *lvRawPtrIn, ErrorCluster *error); -EXPORT void mdsplus_signal_setDim(const void *lvSignalPtr, - const void *lvDimPtrIn, ErrorCluster *error); + /********** SCALAR **********/ + EXPORT void mdsplus_scalar_constructor(void **lvScalarPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_scalar_destructor(void **lvScalarPtr); + EXPORT void mdsplus_scalar_getInfo(const void *lvScalarPtr, char *clazzOut, + char *dtypeOut, short *lengthOut, + LIntArrHdl lvIntArrHdlOut, + ErrorCluster *error); -/********** REVENT **********/ -EXPORT void mdsplus_revent_constructor(void **lvREventPtrOut, - const char *evNameIn, - ErrorCluster *error); -EXPORT void mdsplus_revent_destructor(void **lvREventPtr); -EXPORT void mdsplus_revent_getData(const void *lvREventPtr, void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_revent_getName(const void *lvREventPtr, - LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_revent_getRaw(const void *lvREventPtr, - LByteArrHdl lvByteArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_revent_getTime(const void *lvREventPtr, - void **lvUint64PtrOut, ErrorCluster *error); -EXPORT void mdsplus_revent_run(const void *lvREventPtr, ErrorCluster *error); -EXPORT void mdsplus_revent_setEvent(const char *evNameIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_revent_setEventAndWait(const char *evNameIn, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_revent_setEventRaw(const char *evNameIn, - LByteArrHdl lvByteArrHdlIn, + /********** STRING **********/ + EXPORT void mdsplus_string_constructor(void **lvStringPtrOut, const char *valIn, + ErrorCluster *error); + EXPORT void mdsplus_string_constructor_len(void **lvStringPtrOut, + const LUByteArrHdl lvUByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_string_destructor(void **lvStringPtr); + EXPORT void mdsplus_string_equals(const void *lvStringPtr, LVBoolean *equalsOut, + const void *lvDataPtrIn, ErrorCluster *error); + EXPORT void mdsplus_string_getString(const void *lvStringPtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_revent_setEventRawAndWait(const char *evNameIn, - LByteArrHdl lvByteArrHdlIn, + + /********** STRINGARRAY **********/ + EXPORT void mdsplus_stringarray_constructor(void **lvStringArrayPtrOut, + const LStrArrHdl lvLStrArrHdlIn, ErrorCluster *error); + EXPORT void + mdsplus_stringarray_constructor_stringLen(void **lvStringArrayPtrOut, + const char *dataIn, int nStringsIn, + int stringLenIn, ErrorCluster *error); + EXPORT void mdsplus_stringarray_destructor(void **lvStringArrayPtr); -/********** SCALAR **********/ -EXPORT void mdsplus_scalar_constructor(void **lvScalarPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_scalar_destructor(void **lvScalarPtr); -EXPORT void mdsplus_scalar_getInfo(const void *lvScalarPtr, char *clazzOut, - char *dtypeOut, short *lengthOut, - LIntArrHdl lvIntArrHdlOut, + /********** TREE **********/ + EXPORT void mdsplus_tree_addDevice(const void *lvTreePtr, + void **lvTreeNodePtrOut, const char *nameIn, + const char *typeIn, ErrorCluster *error); + EXPORT void mdsplus_tree_addNode(const void *lvTreePtr, void **lvTreeNodePtrOut, + const char *nameIn, const char *usageIn, ErrorCluster *error); - -/********** STRING **********/ -EXPORT void mdsplus_string_constructor(void **lvStringPtrOut, const char *valIn, - ErrorCluster *error); -EXPORT void mdsplus_string_constructor_len(void **lvStringPtrOut, - const LUByteArrHdl lvUByteArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_string_destructor(void **lvStringPtr); -EXPORT void mdsplus_string_equals(const void *lvStringPtr, LVBoolean *equalsOut, - const void *lvDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_string_getString(const void *lvStringPtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); - -/********** STRINGARRAY **********/ -EXPORT void mdsplus_stringarray_constructor(void **lvStringArrayPtrOut, - const LStrArrHdl lvLStrArrHdlIn, + EXPORT void mdsplus_tree_constructor(void **lvTreePtrOut, const char *nameIn, + int shotIn, ErrorCluster *error); + EXPORT void mdsplus_tree_constructor_mode(void **lvTreePtrOut, + const char *nameIn, int shotIn, + const char *modeIn, ErrorCluster *error); -EXPORT void -mdsplus_stringarray_constructor_stringLen(void **lvStringArrayPtrOut, - const char *dataIn, int nStringsIn, - int stringLenIn, ErrorCluster *error); -EXPORT void mdsplus_stringarray_destructor(void **lvStringArrayPtr); - -/********** TREE **********/ -EXPORT void mdsplus_tree_addDevice(const void *lvTreePtr, - void **lvTreeNodePtrOut, const char *nameIn, - const char *typeIn, ErrorCluster *error); -EXPORT void mdsplus_tree_addNode(const void *lvTreePtr, void **lvTreeNodePtrOut, - const char *nameIn, const char *usageIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_constructor(void **lvTreePtrOut, const char *nameIn, - int shotIn, ErrorCluster *error); -EXPORT void mdsplus_tree_constructor_mode(void **lvTreePtrOut, - const char *nameIn, int shotIn, - const char *modeIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_createPulse(const void *lvTreePtr, int shotIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_deletePulse(const void *lvTreePtr, int shotIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_destructor(void **lvTreePtr); -EXPORT void mdsplus_tree_edit(const void *lvTreePtr, ErrorCluster *error); -EXPORT void mdsplus_tree_findTags(const void *lvTreePtr, - void **lvStringArrayPtrOut, - const char *wildIn, ErrorCluster *error); -EXPORT void mdsplus_tree_getActiveTree(void **lvTreePtrOut, + EXPORT void mdsplus_tree_createPulse(const void *lvTreePtr, int shotIn, ErrorCluster *error); -EXPORT void mdsplus_tree_getCurrent(int *currentOut, const char *treeNameIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_getDatafileSize(const void *lvTreePtr, - int64_t *sizeOut, ErrorCluster *error); -EXPORT void mdsplus_tree_getDefault(const void *lvTreePtr, - void **lvTreeNodePtrOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_getNode(const void *lvTreePtr, void **lvTreeNodePtrOut, - const char *pathIn, ErrorCluster *error); -EXPORT void mdsplus_tree_hasNode(const void *lvTreePtr, LVBoolean *lvhasNodeOut, - const char *pathIn, ErrorCluster *error); -EXPORT void mdsplus_tree_getNode_string(const void *lvTreePtr, - void **lvTreeNodePtrOut, - const void *lvStringPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_getNode_treepath(const void *lvTreePtr, + EXPORT void mdsplus_tree_deletePulse(const void *lvTreePtr, int shotIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_destructor(void **lvTreePtr); + EXPORT void mdsplus_tree_edit(const void *lvTreePtr, ErrorCluster *error); + EXPORT void mdsplus_tree_findTags(const void *lvTreePtr, + void **lvStringArrayPtrOut, + const char *wildIn, ErrorCluster *error); + EXPORT void mdsplus_tree_getActiveTree(void **lvTreePtrOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_getCurrent(int *currentOut, const char *treeNameIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_getDatafileSize(const void *lvTreePtr, + int64_t *sizeOut, ErrorCluster *error); + EXPORT void mdsplus_tree_getDefault(const void *lvTreePtr, + void **lvTreeNodePtrOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_getNode(const void *lvTreePtr, void **lvTreeNodePtrOut, + const char *pathIn, ErrorCluster *error); + EXPORT void mdsplus_tree_hasNode(const void *lvTreePtr, LVBoolean *lvhasNodeOut, + const char *pathIn, ErrorCluster *error); + EXPORT void mdsplus_tree_getNode_string(const void *lvTreePtr, void **lvTreeNodePtrOut, - const void *lvTreePathPtrIn, + const void *lvStringPtrIn, ErrorCluster *error); -EXPORT void mdsplus_tree_getNodeWild(const void *lvTreePtr, - void **lvTreeNodeArrayPtrOut, - const char *pathIn, ErrorCluster *error); -EXPORT void mdsplus_tree_getNodeWild_usageMask(const void *lvTreePtr, - void **lvTreeNodeArrayPtrOut, - const char *pathIn, - int usageMaskIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_isModified(const void *lvTreePtr, - LVBoolean *lvIsModifiedOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_isOpenForEdit(const void *lvTreePtr, - LVBoolean *lvIsOpenForEditOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_isReadOnly(const void *lvTreePtr, - LVBoolean *lvIsReadOnlyOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_quit(const void *lvTreePtr, ErrorCluster *error); -EXPORT void mdsplus_tree_remove(const void *lvTreePtr, const char *nameIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_removeTag(const void *lvTreePtr, const char *tagNameIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setActiveTree(const void *lvTreePtrIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setCurrent(const char *treeNameIn, int shotIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setDefault(const void *lvTreePtr, - const void *lvTreeNodePtrIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, - const void *lvStartDataPtrIn, - const void *lvEndDataPtrIn, - const void *lvDeltaDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setVersionsInModel(const void *lvTreePtr, - LVBoolean *lvVerEnabledIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_setVersionsInPulse(const void *lvTreePtr, - LVBoolean *lvVerEnabledIn, + EXPORT void mdsplus_tree_getNode_treepath(const void *lvTreePtr, + void **lvTreeNodePtrOut, + const void *lvTreePathPtrIn, ErrorCluster *error); -EXPORT void mdsplus_tree_setViewDate(const void *lvTreePtr, const char *dateIn, - ErrorCluster *error); -EXPORT void mdsplus_tree_versionsInModelEnabled(const void *lvTreePtr, - LVBoolean *lvVerEnabledOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_versionsInPulseEnabled(const void *lvTreePtr, - LVBoolean *lvVerEnabledOut, - ErrorCluster *error); -EXPORT void mdsplus_tree_write(const void *lvTreePtr, ErrorCluster *error); - -/********** TREENODE **********/ -EXPORT void mdsplus_treenode_addDevice(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - const char *nameIn, const char *typeIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_addNode(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - const char *nameIn, const char *usageIn, + EXPORT void mdsplus_tree_getNodeWild(const void *lvTreePtr, + void **lvTreeNodeArrayPtrOut, + const char *pathIn, ErrorCluster *error); + EXPORT void mdsplus_tree_getNodeWild_usageMask(const void *lvTreePtr, + void **lvTreeNodeArrayPtrOut, + const char *pathIn, + int usageMaskIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_isModified(const void *lvTreePtr, + LVBoolean *lvIsModifiedOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_isOpenForEdit(const void *lvTreePtr, + LVBoolean *lvIsOpenForEditOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_isReadOnly(const void *lvTreePtr, + LVBoolean *lvIsReadOnlyOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_quit(const void *lvTreePtr, ErrorCluster *error); + EXPORT void mdsplus_tree_remove(const void *lvTreePtr, const char *nameIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_removeTag(const void *lvTreePtr, const char *tagNameIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_addTag(const void *lvTreeNodePtr, - const char *tagNameIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, + EXPORT void mdsplus_tree_setActiveTree(const void *lvTreePtrIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_setCurrent(const char *treeNameIn, int shotIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_setDefault(const void *lvTreePtr, + const void *lvTreeNodePtrIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, const void *lvStartDataPtrIn, const void *lvEndDataPtrIn, - const void *lvTimeDataPtrIn, - const void *lvArrayPtrIn, + const void *lvDeltaDataPtrIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_beginTimestampedSegment(const void *lvTreeNodePtr, - const void *lvArrayPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_containsVersions(const void *lvTreeNodePtr, - LVBoolean *lvContainsVersionsOut, + EXPORT void mdsplus_tree_setVersionsInModel(const void *lvTreePtr, + LVBoolean *lvVerEnabledIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_deleteData(const void *lvTreeNodePtr, - ErrorCluster *error); -EXPORT void mdsplus_treenode_doMethod(const void *lvTreeNodePtr, - const char *methodIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_destructor(void **lvTreeNodePtr); -EXPORT void mdsplus_treenode_findTags(const void *lvTreeNodePtr, - void **lvStringArrayPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getBrother(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getChild(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getChildren(const void *lvTreeNodePtr, - LPtrArrHdl lvPtrArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getClass(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getCompressedLength(const void *lvTreeNodePtr, - int *compressedLengthOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getConglomerateElt(const void *lvTreeNodePtr, - int *conglomerateEltOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getConglomerateNodes(const void *lvTreeNodePtr, - void **lvTreeNodeArrayPtrOut, + EXPORT void mdsplus_tree_setVersionsInPulse(const void *lvTreePtr, + LVBoolean *lvVerEnabledIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_setViewDate(const void *lvTreePtr, const char *dateIn, + ErrorCluster *error); + EXPORT void mdsplus_tree_versionsInModelEnabled(const void *lvTreePtr, + LVBoolean *lvVerEnabledOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getDepth(const void *lvTreeNodePtr, int *depthOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getData(const void *lvTreeNodePtr, - void **lvDataPtrOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getDescendants(const void *lvTreeNodePtr, - LPtrArrHdl lvPtrArrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getDType(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getFullPath(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, + EXPORT void mdsplus_tree_versionsInPulseEnabled(const void *lvTreePtr, + LVBoolean *lvVerEnabledOut, + ErrorCluster *error); + EXPORT void mdsplus_tree_write(const void *lvTreePtr, ErrorCluster *error); + + /********** TREENODE **********/ + EXPORT void mdsplus_treenode_addDevice(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, + const char *nameIn, const char *typeIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_getLength(const void *lvTreeNodePtr, - int *lengthOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getMember(const void *lvTreeNodePtr, + EXPORT void mdsplus_treenode_addNode(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, + const char *nameIn, const char *usageIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_getMembers(const void *lvTreeNodePtr, - LPtrArrHdl lvPtrArrHdlOut, + EXPORT void mdsplus_treenode_addTag(const void *lvTreeNodePtr, + const char *tagNameIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, + const void *lvStartDataPtrIn, + const void *lvEndDataPtrIn, + const void *lvTimeDataPtrIn, + const void *lvArrayPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_beginTimestampedSegment(const void *lvTreeNodePtr, + const void *lvArrayPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_containsVersions(const void *lvTreeNodePtr, + LVBoolean *lvContainsVersionsOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_deleteData(const void *lvTreeNodePtr, + ErrorCluster *error); + EXPORT void mdsplus_treenode_doMethod(const void *lvTreeNodePtr, + const char *methodIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_getMinPath(const void *lvTreeNodePtr, + EXPORT void mdsplus_treenode_destructor(void **lvTreeNodePtr); + EXPORT void mdsplus_treenode_findTags(const void *lvTreeNodePtr, + void **lvStringArrayPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getBrother(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getChild(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getChildren(const void *lvTreeNodePtr, + LPtrArrHdl lvPtrArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getClass(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getNid(const void *lvTreeNodePtr, int *nidOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNode(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - const char *relPathIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNode_string(const void *lvTreeNodePtr, - void **lvTreeNodePtrOut, - const void *lvStringPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNodeName(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNumChildren(const void *lvTreeNodePtr, - int *numChildrenOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNumDescendants(const void *lvTreeNodePtr, - int *numDescendantsOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getNumElts(const void *lvTreeNodePtr, - int *numEltsOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getNumMembers(const void *lvTreeNodePtr, - int *numMembersOut, + EXPORT void mdsplus_treenode_getCompressedLength(const void *lvTreeNodePtr, + int *compressedLengthOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getConglomerateElt(const void *lvTreeNodePtr, + int *conglomerateEltOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getConglomerateNodes(const void *lvTreeNodePtr, + void **lvTreeNodeArrayPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getDepth(const void *lvTreeNodePtr, int *depthOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getData(const void *lvTreeNodePtr, + void **lvDataPtrOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getDescendants(const void *lvTreeNodePtr, + LPtrArrHdl lvPtrArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getDType(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getFullPath(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getNumSegments(const void *lvTreeNodePtr, - int *numSegmentsOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getOriginalPartName(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getOwnerId(const void *lvTreeNodePtr, - int *ownerIdOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getParent(const void *lvTreeNodePtr, + EXPORT void mdsplus_treenode_getLength(const void *lvTreeNodePtr, + int *lengthOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getMember(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getMembers(const void *lvTreeNodePtr, + LPtrArrHdl lvPtrArrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getMinPath(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getNid(const void *lvTreeNodePtr, int *nidOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getNode(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, + const char *relPathIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_getPath(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getSegment(const void *lvTreeNodePtr, - void **lvArrayPtrOut, int segIdxIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getSegmentLimits(const void *lvTreeNodePtr, - int segmentIdxIn, - void **lvStartDataPtrOut, - void **lvEndDataPtrOut, + EXPORT void mdsplus_treenode_getNode_string(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, + const void *lvStringPtrIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_getStatus(const void *lvTreeNodePtr, - int *statusOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, - int64_t *timeInsertedOut, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_getTree(const void *lvTreeNodePtr, - void **lvTreePtrOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_getUsage(const void *lvTreeNodePtr, - LStrHandle lvStrHdlOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isChild(const void *lvTreeNodePtr, - LVBoolean *lvIsChildOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isCompressOnPut(const void *lvTreeNodePtr, - LVBoolean *lvIsCompressOnPutOut, + EXPORT void mdsplus_treenode_getNodeName(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getNumChildren(const void *lvTreeNodePtr, + int *numChildrenOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getNumDescendants(const void *lvTreeNodePtr, + int *numDescendantsOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getNumElts(const void *lvTreeNodePtr, + int *numEltsOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getNumMembers(const void *lvTreeNodePtr, + int *numMembersOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_isEssential(const void *lvTreeNodePtr, - LVBoolean *lvIsEssentialOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isIncludeInPulse(const void *lvTreeNodePtr, - LVBoolean *lvisIncludeInPulseOut, + EXPORT void mdsplus_treenode_getNumSegments(const void *lvTreeNodePtr, + int *numSegmentsOut, ErrorCluster *error); -EXPORT void -mdsplus_treenode_isIncludedInPulse(const void *lvTreeNodePtr, - LVBoolean *lvIsIncludedInPulseOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isMember(const void *lvTreeNodePtr, - LVBoolean *lvIsMemberOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isNoWriteModel(const void *lvTreeNodePtr, - LVBoolean *lvIsNoWriteModelOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isNoWriteShot(const void *lvTreeNodePtr, - LVBoolean *lvIsNoWriteShotOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isOn(const void *lvTreeNodePtr, - LVBoolean *lvIsOnOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_isSetup(const void *lvTreeNodePtr, - LVBoolean *lvIsSetupOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_isWriteOnce(const void *lvTreeNodePtr, - LVBoolean *lvIsWriteOnceOut, - ErrorCluster *error); -EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, - const void *lvStartDataPtrIn, - const void *lvEndDataPtrIn, - const void *lvTimeDataPtrIn, - const void *lvArrayPtrIn, + EXPORT void mdsplus_treenode_getOriginalPartName(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getOwnerId(const void *lvTreeNodePtr, + int *ownerIdOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getParent(const void *lvTreeNodePtr, + void **lvTreeNodePtrOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_makeTimestampedSegment( - const void *lvTreeNodePtr, const void *lvArrayPtrIn, - const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_move(const void *lvTreeNodePtr, - const void *lvTreeNodePtrIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_move_newName(const void *lvTreeNodePtr, - const void *lvTreeNodePtrIn, - const char *newNameIn, + EXPORT void mdsplus_treenode_getPath(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getSegment(const void *lvTreeNodePtr, + void **lvArrayPtrOut, int segIdxIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_putData(const void *lvTreeNodePtr, - const void *lvDataPtrIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_putRow(const void *lvTreeNodePtr, - const void *lvDataPtrIn, int64_t *timeIn, - int sizeIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_putSegment(const void *lvTreeNodePtr, - const void *lvArrayPtrIn, int ofsIn, + EXPORT void mdsplus_treenode_getSegmentLimits(const void *lvTreeNodePtr, + int segmentIdxIn, + void **lvStartDataPtrOut, + void **lvEndDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getStatus(const void *lvTreeNodePtr, + int *statusOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, + int64_t *timeInsertedOut, + LStrHandle lvStrHdlOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_getTree(const void *lvTreeNodePtr, + void **lvTreePtrOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_getUsage(const void *lvTreeNodePtr, + LStrHandle lvStrHdlOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_putTimestampedSegment( - const void *lvTreeNodePtr, const void *lvArrayPtrIn, - const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_remove(const void *lvTreeNodePtr, - const char *nameIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_removeTag(const void *lvTreeNodePtr, - const char *tagNameIn, + EXPORT void mdsplus_treenode_isChild(const void *lvTreeNodePtr, + LVBoolean *lvIsChildOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_rename(const void *lvTreeNodePtr, - const char *newNameIn, ErrorCluster *error); -EXPORT void mdsplus_treenode_setCompressOnPut(const void *lvTreeNodePtr, - LVBoolean *lvCompressOnPutIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setEssential(const void *lvTreeNodePtr, - LVBoolean *lvEssentialIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setIncludeInPulse(const void *lvTreeNodePtr, - LVBoolean *lvIncludeInPulseIn, + EXPORT void mdsplus_treenode_isCompressOnPut(const void *lvTreeNodePtr, + LVBoolean *lvIsCompressOnPutOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_setIncludedInPulse(const void *lvTreeNodePtr, - LVBoolean *lvIncludedInPulseIn, + EXPORT void mdsplus_treenode_isEssential(const void *lvTreeNodePtr, + LVBoolean *lvIsEssentialOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_isIncludeInPulse(const void *lvTreeNodePtr, + LVBoolean *lvisIncludeInPulseOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_setNoWriteModel(const void *lvTreeNodePtr, - LVBoolean *lvSetNoWriteModelIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setNoWriteShot(const void *lvTreeNodePtr, - LVBoolean *lvNoWriteShotIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setOn(const void *lvTreeNodePtr, LVBoolean *lvOnIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setSubTree(const void *lvTreeNodePtr, - LVBoolean *lvSubTreeIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_setTree(const void *lvTreeNodePtr, - const void *lvTreePtrIn, + EXPORT void + mdsplus_treenode_isIncludedInPulse(const void *lvTreeNodePtr, + LVBoolean *lvIsIncludedInPulseOut, ErrorCluster *error); -EXPORT void mdsplus_treenode_setWriteOnce(const void *lvTreeNodePtr, - LVBoolean *lvWriteOnceIn, - ErrorCluster *error); -EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, + EXPORT void mdsplus_treenode_isMember(const void *lvTreeNodePtr, + LVBoolean *lvIsMemberOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_isNoWriteModel(const void *lvTreeNodePtr, + LVBoolean *lvIsNoWriteModelOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_isNoWriteShot(const void *lvTreeNodePtr, + LVBoolean *lvIsNoWriteShotOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_isOn(const void *lvTreeNodePtr, + LVBoolean *lvIsOnOut, ErrorCluster *error); + EXPORT void mdsplus_treenode_isSetup(const void *lvTreeNodePtr, + LVBoolean *lvIsSetupOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_isWriteOnce(const void *lvTreeNodePtr, + LVBoolean *lvIsWriteOnceOut, + ErrorCluster *error); + EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, const void *lvStartDataPtrIn, const void *lvEndDataPtrIn, const void *lvTimeDataPtrIn, + const void *lvArrayPtrIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_makeTimestampedSegment( + const void *lvTreeNodePtr, const void *lvArrayPtrIn, + const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_move(const void *lvTreeNodePtr, + const void *lvTreeNodePtrIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_move_newName(const void *lvTreeNodePtr, + const void *lvTreeNodePtrIn, + const char *newNameIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_putData(const void *lvTreeNodePtr, + const void *lvDataPtrIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_putRow(const void *lvTreeNodePtr, + const void *lvDataPtrIn, int64_t *timeIn, + int sizeIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_putSegment(const void *lvTreeNodePtr, + const void *lvArrayPtrIn, int ofsIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_putTimestampedSegment( + const void *lvTreeNodePtr, const void *lvArrayPtrIn, + const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_remove(const void *lvTreeNodePtr, + const char *nameIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_removeTag(const void *lvTreeNodePtr, + const char *tagNameIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_rename(const void *lvTreeNodePtr, + const char *newNameIn, ErrorCluster *error); + EXPORT void mdsplus_treenode_setCompressOnPut(const void *lvTreeNodePtr, + LVBoolean *lvCompressOnPutIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setEssential(const void *lvTreeNodePtr, + LVBoolean *lvEssentialIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setIncludeInPulse(const void *lvTreeNodePtr, + LVBoolean *lvIncludeInPulseIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setIncludedInPulse(const void *lvTreeNodePtr, + LVBoolean *lvIncludedInPulseIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setNoWriteModel(const void *lvTreeNodePtr, + LVBoolean *lvSetNoWriteModelIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setNoWriteShot(const void *lvTreeNodePtr, + LVBoolean *lvNoWriteShotIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setOn(const void *lvTreeNodePtr, LVBoolean *lvOnIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setSubTree(const void *lvTreeNodePtr, + LVBoolean *lvSubTreeIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setTree(const void *lvTreeNodePtr, + const void *lvTreePtrIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_setWriteOnce(const void *lvTreeNodePtr, + LVBoolean *lvWriteOnceIn, + ErrorCluster *error); + EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, + const void *lvStartDataPtrIn, + const void *lvEndDataPtrIn, + const void *lvTimeDataPtrIn, + ErrorCluster *error); -/********** TREENODEARRAY **********/ -EXPORT void mdsplus_treenodearray_destructor(void **lvTreeNodeArrayPtr); + /********** TREENODEARRAY **********/ + EXPORT void mdsplus_treenodearray_destructor(void **lvTreeNodeArrayPtr); -/********** TREEPATH **********/ -EXPORT void mdsplus_treepath_destructor(void **lvTreePathPtr); + /********** TREEPATH **********/ + EXPORT void mdsplus_treepath_destructor(void **lvTreePathPtr); -/********** UINT16 **********/ -EXPORT void mdsplus_uint16_constructor(void **lvUint16PtrOut, - unsigned short valIn, - ErrorCluster *error); -EXPORT void mdsplus_uint16_destructor(void **lvUint16Ptr); -EXPORT void mdsplus_uint16_getByte(const void *lvUint16Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_uint16_getDouble(const void *lvUint16Ptr, double *doubleOut, + /********** UINT16 **********/ + EXPORT void mdsplus_uint16_constructor(void **lvUint16PtrOut, + unsigned short valIn, + ErrorCluster *error); + EXPORT void mdsplus_uint16_destructor(void **lvUint16Ptr); + EXPORT void mdsplus_uint16_getByte(const void *lvUint16Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_uint16_getFloat(const void *lvUint16Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_uint16_getInt(const void *lvUint16Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_uint16_getLong(const void *lvUint16Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_uint16_getShort(const void *lvUint16Ptr, short *shortOut, + EXPORT void mdsplus_uint16_getDouble(const void *lvUint16Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_uint16_getFloat(const void *lvUint16Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_uint16_getInt(const void *lvUint16Ptr, int *intOut, ErrorCluster *error); + EXPORT void mdsplus_uint16_getLong(const void *lvUint16Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_uint16_getShort(const void *lvUint16Ptr, short *shortOut, + ErrorCluster *error); -/********** UINT16ARRAY **********/ -EXPORT void mdsplus_uint16array_constructor(void **lvUint16ArrayPtrOut, - const LUShtArrHdl lvUShtArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_uint16array_constructor_dims( - void **lvUint16ArrayPtrOut, const LUShtArrHdl lvUShtArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_uint16array_destructor(void **lvUint16ArrayPtr); + /********** UINT16ARRAY **********/ + EXPORT void mdsplus_uint16array_constructor(void **lvUint16ArrayPtrOut, + const LUShtArrHdl lvUShtArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_uint16array_constructor_dims( + void **lvUint16ArrayPtrOut, const LUShtArrHdl lvUShtArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_uint16array_destructor(void **lvUint16ArrayPtr); -/********** UINT32 **********/ -EXPORT void mdsplus_uint32_constructor(void **lvUint32PtrOut, - unsigned int valIn, ErrorCluster *error); -EXPORT void mdsplus_uint32_destructor(void **lvUint32Ptr); -EXPORT void mdsplus_uint32_getByte(const void *lvUint32Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_uint32_getDouble(const void *lvUint32Ptr, double *doubleOut, + /********** UINT32 **********/ + EXPORT void mdsplus_uint32_constructor(void **lvUint32PtrOut, + unsigned int valIn, ErrorCluster *error); + EXPORT void mdsplus_uint32_destructor(void **lvUint32Ptr); + EXPORT void mdsplus_uint32_getByte(const void *lvUint32Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_uint32_getFloat(const void *lvUint32Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_uint32_getInt(const void *lvUint32Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_uint32_getLong(const void *lvUint32Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_uint32_getShort(const void *lvUint32Ptr, short *shortOut, + EXPORT void mdsplus_uint32_getDouble(const void *lvUint32Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_uint32_getFloat(const void *lvUint32Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_uint32_getInt(const void *lvUint32Ptr, int *intOut, ErrorCluster *error); + EXPORT void mdsplus_uint32_getLong(const void *lvUint32Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_uint32_getShort(const void *lvUint32Ptr, short *shortOut, + ErrorCluster *error); -/********** UINT32ARRAY **********/ -EXPORT void mdsplus_uint32array_constructor(void **lvUint32ArrayPtrOut, - const LUIntArrHdl lvUIntArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_uint32array_constructor_dims( - void **lvUint32ArrayPtrOut, const LUIntArrHdl lvUIntArrHdlIn, - const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error); -EXPORT void mdsplus_uint32array_destructor(void **lvUint32ArrayPtr); - -/********** UINT64 **********/ -EXPORT void mdsplus_uint64_constructor(void **lvUint64PtrOut, uint64_t valIn, - ErrorCluster *error); -EXPORT void mdsplus_uint64_destructor(void **lvUint64Ptr); -EXPORT void mdsplus_uint64_getByte(const void *lvUint64Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_uint64_getDate(const void *lvUint64Ptr, - LStrHandle lvStrHdlOut, ErrorCluster *error); + /********** UINT32ARRAY **********/ + EXPORT void mdsplus_uint32array_constructor(void **lvUint32ArrayPtrOut, + const LUIntArrHdl lvUIntArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_uint32array_constructor_dims( + void **lvUint32ArrayPtrOut, const LUIntArrHdl lvUIntArrHdlIn, + const LIntArrHdl lvIntArrHdlDimIn, ErrorCluster *error); + EXPORT void mdsplus_uint32array_destructor(void **lvUint32ArrayPtr); -EXPORT void mdsplus_uint64_getDouble(const void *lvUint64Ptr, double *doubleOut, + /********** UINT64 **********/ + EXPORT void mdsplus_uint64_constructor(void **lvUint64PtrOut, uint64_t valIn, + ErrorCluster *error); + EXPORT void mdsplus_uint64_destructor(void **lvUint64Ptr); + EXPORT void mdsplus_uint64_getByte(const void *lvUint64Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_uint64_getFloat(const void *lvUint64Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_uint64_getInt(const void *lvUint64Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_uint64_getLong(const void *lvUint64Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_uint64_getShort(const void *lvUint64Ptr, short *shortOut, + EXPORT void mdsplus_uint64_getDate(const void *lvUint64Ptr, + LStrHandle lvStrHdlOut, ErrorCluster *error); + + EXPORT void mdsplus_uint64_getDouble(const void *lvUint64Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_uint64_getFloat(const void *lvUint64Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_uint64_getInt(const void *lvUint64Ptr, int *intOut, ErrorCluster *error); + EXPORT void mdsplus_uint64_getLong(const void *lvUint64Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_uint64_getShort(const void *lvUint64Ptr, short *shortOut, + ErrorCluster *error); -/********** UINT64ARRAY **********/ -EXPORT void mdsplus_uint64array_constructor(void **lvUint64ArrayPtrOut, - const LULngArrHdl lvULngArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_uint64array_constructor_dims( - void **lvUint64ArrayPtrOut, const LULngArrHdl lvULngArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_uint64array_destructor(void **lvUint64ArrayPtr); + /********** UINT64ARRAY **********/ + EXPORT void mdsplus_uint64array_constructor(void **lvUint64ArrayPtrOut, + const LULngArrHdl lvULngArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_uint64array_constructor_dims( + void **lvUint64ArrayPtrOut, const LULngArrHdl lvULngArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_uint64array_destructor(void **lvUint64ArrayPtr); -/********** UINT8 **********/ -EXPORT void mdsplus_uint8_constructor(void **lvUint8PtrOut, unsigned char valIn, - ErrorCluster *error); -EXPORT void mdsplus_uint8_destructor(void **lvUint8Ptr); -EXPORT void mdsplus_uint8_getByte(const void *lvUint8Ptr, char *byteOut, - ErrorCluster *error); -EXPORT void mdsplus_uint8_getDouble(const void *lvUint8Ptr, double *doubleOut, + /********** UINT8 **********/ + EXPORT void mdsplus_uint8_constructor(void **lvUint8PtrOut, unsigned char valIn, + ErrorCluster *error); + EXPORT void mdsplus_uint8_destructor(void **lvUint8Ptr); + EXPORT void mdsplus_uint8_getByte(const void *lvUint8Ptr, char *byteOut, ErrorCluster *error); -EXPORT void mdsplus_uint8_getFloat(const void *lvUint8Ptr, float *floatOut, - ErrorCluster *error); -EXPORT void mdsplus_uint8_getInt(const void *lvUint8Ptr, int *intOut, - ErrorCluster *error); -EXPORT void mdsplus_uint8_getLong(const void *lvUint8Ptr, int64_t *longOut, - ErrorCluster *error); -EXPORT void mdsplus_uint8_getShort(const void *lvUint8Ptr, short *shortOut, + EXPORT void mdsplus_uint8_getDouble(const void *lvUint8Ptr, double *doubleOut, + ErrorCluster *error); + EXPORT void mdsplus_uint8_getFloat(const void *lvUint8Ptr, float *floatOut, + ErrorCluster *error); + EXPORT void mdsplus_uint8_getInt(const void *lvUint8Ptr, int *intOut, ErrorCluster *error); + EXPORT void mdsplus_uint8_getLong(const void *lvUint8Ptr, int64_t *longOut, + ErrorCluster *error); + EXPORT void mdsplus_uint8_getShort(const void *lvUint8Ptr, short *shortOut, + ErrorCluster *error); -/********** UINT8ARRAY **********/ -EXPORT void mdsplus_uint8array_constructor(void **lvUint8ArrayPtrOut, - const LUByteArrHdl lvUByteArrHdlIn, - ErrorCluster *error); -EXPORT void mdsplus_uint8array_constructor_dims( - void **lvUint8ArrayPtrOut, const LUByteArrHdl lvUByteArrHdlIn, - const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); -EXPORT void mdsplus_uint8array_deserialize(const void *lvUint8ArrayPtr, - void **lvDataPtrOut, - ErrorCluster *error); -EXPORT void mdsplus_uint8array_destructor(void **lvUint8ArrayPtr); + /********** UINT8ARRAY **********/ + EXPORT void mdsplus_uint8array_constructor(void **lvUint8ArrayPtrOut, + const LUByteArrHdl lvUByteArrHdlIn, + ErrorCluster *error); + EXPORT void mdsplus_uint8array_constructor_dims( + void **lvUint8ArrayPtrOut, const LUByteArrHdl lvUByteArrHdlIn, + const LIntArrHdl lvIntArrHdlIn, ErrorCluster *error); + EXPORT void mdsplus_uint8array_deserialize(const void *lvUint8ArrayPtr, + void **lvDataPtrOut, + ErrorCluster *error); + EXPORT void mdsplus_uint8array_destructor(void **lvUint8ArrayPtr); -/******** CONNECTION ***********/ -EXPORT void mdsplus_connection_constructor(void **lvConnectionPtrOut, - const char *ipPortIn, - ErrorCluster *error); -EXPORT void mdsplus_connection_destructor(void **lvConnectionPtr); -EXPORT void mdsplus_connection_getData(const void *lvConnectionPtr, - void **lvDataPtrOut, - const char *expressionIn, - ErrorCluster *error); -EXPORT void mdsplus_connection_putData(const void *lvConnectionPtr, - const void *lvDataPtrIn, - const char *pathIn, ErrorCluster *error); -EXPORT void mdsplus_connection_openTree(const void *lvConnectionPtr, - const char *tree, int shot, - ErrorCluster *error); -EXPORT void mdsplus_connection_closeTree(const void *lvConnectionPtr, + /******** CONNECTION ***********/ + EXPORT void mdsplus_connection_constructor(void **lvConnectionPtrOut, + const char *ipPortIn, + ErrorCluster *error); + EXPORT void mdsplus_connection_destructor(void **lvConnectionPtr); + EXPORT void mdsplus_connection_getData(const void *lvConnectionPtr, + void **lvDataPtrOut, + const char *expressionIn, ErrorCluster *error); -EXPORT void mdsplus_connection_getNode(const void *lvConnectionPtr, - void **lvTreeNodePtrOut, - const char *pathIn, ErrorCluster *error); + EXPORT void mdsplus_connection_putData(const void *lvConnectionPtr, + const void *lvDataPtrIn, + const char *pathIn, ErrorCluster *error); + EXPORT void mdsplus_connection_openTree(const void *lvConnectionPtr, + const char *tree, int shot, + ErrorCluster *error); + EXPORT void mdsplus_connection_closeTree(const void *lvConnectionPtr, + ErrorCluster *error); + EXPORT void mdsplus_connection_getNode(const void *lvConnectionPtr, + void **lvTreeNodePtrOut, + const char *pathIn, ErrorCluster *error); #ifdef __cplusplus } diff --git a/mdsobjects/labview/mdstreeobjectswrp.cpp b/mdsobjects/labview/mdstreeobjectswrp.cpp index 280b394000..9955eb169c 100644 --- a/mdsobjects/labview/mdstreeobjectswrp.cpp +++ b/mdsobjects/labview/mdstreeobjectswrp.cpp @@ -34,18 +34,22 @@ using namespace std; EXPORT void mdsplus_tree_addDevice(const void *lvTreePtr, void **lvTreeNodePtrOut, const char *nameIn, - const char *typeIn, ErrorCluster *error) { + const char *typeIn, ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodePtrOut = treePtr->addDevice(const_cast(nameIn), const_cast(typeIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -56,18 +60,22 @@ EXPORT void mdsplus_tree_addDevice(const void *lvTreePtr, EXPORT void mdsplus_tree_addNode(const void *lvTreePtr, void **lvTreeNodePtrOut, const char *nameIn, const char *usageIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodePtrOut = treePtr->addNode(const_cast(nameIn), const_cast(usageIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -77,15 +85,19 @@ EXPORT void mdsplus_tree_addNode(const void *lvTreePtr, void **lvTreeNodePtrOut, } EXPORT void mdsplus_tree_constructor(void **lvTreePtrOut, const char *nameIn, - int shotIn, ErrorCluster *error) { + int shotIn, ErrorCluster *error) +{ Tree *treePtrOut = NULL; MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { treePtrOut = new Tree(const_cast(nameIn), shotIn); *lvTreePtrOut = reinterpret_cast(treePtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -98,16 +110,20 @@ EXPORT void mdsplus_tree_constructor(void **lvTreePtrOut, const char *nameIn, EXPORT void mdsplus_tree_constructor_mode(void **lvTreePtrOut, const char *nameIn, int shotIn, const char *modeIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtrOut = NULL; MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { treePtrOut = new Tree(const_cast(nameIn), shotIn, const_cast(modeIn)); *lvTreePtrOut = reinterpret_cast(treePtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -118,17 +134,21 @@ EXPORT void mdsplus_tree_constructor_mode(void **lvTreePtrOut, } EXPORT void mdsplus_tree_createPulse(const void *lvTreePtr, int shotIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->createPulse(shotIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -138,16 +158,20 @@ EXPORT void mdsplus_tree_createPulse(const void *lvTreePtr, int shotIn, } EXPORT void mdsplus_tree_deletePulse(const void *lvTreePtr, int shotIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->deletePulse(shotIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -156,22 +180,27 @@ EXPORT void mdsplus_tree_deletePulse(const void *lvTreePtr, int shotIn, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_tree_destructor(void **lvTreePtr) { +EXPORT void mdsplus_tree_destructor(void **lvTreePtr) +{ Tree *treePtr = reinterpret_cast(*lvTreePtr); delete treePtr; *lvTreePtr = NULL; } -EXPORT void mdsplus_tree_edit(const void *lvTreePtr, ErrorCluster *error) { +EXPORT void mdsplus_tree_edit(const void *lvTreePtr, ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->edit(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -182,17 +211,21 @@ EXPORT void mdsplus_tree_edit(const void *lvTreePtr, ErrorCluster *error) { EXPORT void mdsplus_tree_findTags(const void *lvTreePtr, void **lvStringArrayPtrOut, - const char *wildIn, ErrorCluster *error) { + const char *wildIn, ErrorCluster *error) +{ Tree *treePtr = NULL; StringArray *stringArrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); stringArrayPtrOut = treePtr->findTags(const_cast(wildIn)); *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = const_cast(e.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -202,15 +235,19 @@ EXPORT void mdsplus_tree_findTags(const void *lvTreePtr, } EXPORT void mdsplus_tree_getActiveTree(void **lvTreePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtrOut = getActiveTree(); *lvTreePtrOut = reinterpret_cast(treePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { delete treePtrOut; errorCode = bogusError; errorMessage = const_cast(mdsE.what()); @@ -221,13 +258,17 @@ EXPORT void mdsplus_tree_getActiveTree(void **lvTreePtrOut, } EXPORT void mdsplus_tree_getCurrent(int *currentOut, const char *treeNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { *currentOut = Tree::getCurrent(const_cast(treeNameIn)); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = const_cast(e.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -238,15 +279,19 @@ EXPORT void mdsplus_tree_getCurrent(int *currentOut, const char *treeNameIn, EXPORT void mdsplus_tree_getDatafileSize(const void *lvTreePtr, int64_t *sizeOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); *sizeOut = treePtr->getDatafileSize(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -257,17 +302,21 @@ EXPORT void mdsplus_tree_getDatafileSize(const void *lvTreePtr, EXPORT void mdsplus_tree_getDefault(const void *lvTreePtr, void **lvTreeNodePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodePtrOut = treePtr->getDefault(); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -277,18 +326,22 @@ EXPORT void mdsplus_tree_getDefault(const void *lvTreePtr, } EXPORT void mdsplus_tree_getNode(const void *lvTreePtr, void **lvTreeNodePtrOut, - const char *pathIn, ErrorCluster *error) { + const char *pathIn, ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodePtrOut = treePtr->getNode(const_cast(pathIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); fillErrorCluster(errorCode, errorSource, errorMessage, error); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; *lvTreeNodePtrOut = 0; fillErrorCluster(errorCode, errorSource, const_cast(mdsE.what()), @@ -297,18 +350,21 @@ EXPORT void mdsplus_tree_getNode(const void *lvTreePtr, void **lvTreeNodePtrOut, } EXPORT void mdsplus_tree_hasNode(const void *lvTreePtr, LVBoolean *lvhasNodeOut, - const char *pathIn, ErrorCluster *error) { + const char *pathIn, ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = (char *)""; *lvhasNodeOut = LVBooleanTrue; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); TreeNode *node = treePtr->getNode(const_cast(pathIn)); delete node; - - } catch (...) { + } + catch (...) + { *lvhasNodeOut = LVBooleanFalse; } fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -317,19 +373,23 @@ EXPORT void mdsplus_tree_hasNode(const void *lvTreePtr, LVBoolean *lvhasNodeOut, EXPORT void mdsplus_tree_getNode_string(const void *lvTreePtr, void **lvTreeNodePtrOut, const void *lvStringPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); String *stringPtrIn = reinterpret_cast(const_cast(lvStringPtrIn)); treeNodePtrOut = treePtr->getNode(stringPtrIn); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -341,19 +401,23 @@ EXPORT void mdsplus_tree_getNode_string(const void *lvTreePtr, EXPORT void mdsplus_tree_getNode_treepath(const void *lvTreePtr, void **lvTreeNodePtrOut, const void *lvTreePathPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); TreePath *treePathPtrIn = reinterpret_cast(const_cast(lvTreePathPtrIn)); treeNodePtrOut = treePtr->getNode(treePathPtrIn); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -364,17 +428,21 @@ EXPORT void mdsplus_tree_getNode_treepath(const void *lvTreePtr, EXPORT void mdsplus_tree_getNodeWild(const void *lvTreePtr, void **lvTreeNodeArrayPtrOut, - const char *pathIn, ErrorCluster *error) { + const char *pathIn, ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNodeArray *treeNodeArrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodeArrayPtrOut = treePtr->getNodeWild(const_cast(pathIn)); *lvTreeNodeArrayPtrOut = reinterpret_cast(treeNodeArrayPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -387,18 +455,22 @@ EXPORT void mdsplus_tree_getNodeWild_usageMask(const void *lvTreePtr, void **lvTreeNodeArrayPtrOut, const char *pathIn, int usageMaskIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNodeArray *treeNodeArrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodeArrayPtrOut = treePtr->getNodeWild(const_cast(pathIn), usageMaskIn); *lvTreeNodeArrayPtrOut = reinterpret_cast(treeNodeArrayPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -409,16 +481,20 @@ EXPORT void mdsplus_tree_getNodeWild_usageMask(const void *lvTreePtr, EXPORT void mdsplus_tree_isModified(const void *lvTreePtr, LVBoolean *lvIsModifiedOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); *lvIsModifiedOut = (treePtr->isModified() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -429,16 +505,20 @@ EXPORT void mdsplus_tree_isModified(const void *lvTreePtr, EXPORT void mdsplus_tree_isOpenForEdit(const void *lvTreePtr, LVBoolean *lvIsOpenForEditOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); *lvIsOpenForEditOut = (treePtr->isOpenForEdit() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -449,16 +529,20 @@ EXPORT void mdsplus_tree_isOpenForEdit(const void *lvTreePtr, EXPORT void mdsplus_tree_isReadOnly(const void *lvTreePtr, LVBoolean *lvIsReadOnlyOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); *lvIsReadOnlyOut = (treePtr->isReadOnly() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -467,15 +551,19 @@ EXPORT void mdsplus_tree_isReadOnly(const void *lvTreePtr, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_tree_quit(const void *lvTreePtr, ErrorCluster *error) { +EXPORT void mdsplus_tree_quit(const void *lvTreePtr, ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->quit(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -485,15 +573,19 @@ EXPORT void mdsplus_tree_quit(const void *lvTreePtr, ErrorCluster *error) { } EXPORT void mdsplus_tree_remove(const void *lvTreePtr, const char *nameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->remove(const_cast(nameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -503,15 +595,19 @@ EXPORT void mdsplus_tree_remove(const void *lvTreePtr, const char *nameIn, } EXPORT void mdsplus_tree_removeTag(const void *lvTreePtr, const char *tagNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->removeTag(const_cast(tagNameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -521,15 +617,19 @@ EXPORT void mdsplus_tree_removeTag(const void *lvTreePtr, const char *tagNameIn, } EXPORT void mdsplus_tree_setActiveTree(const void *lvTreePtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); setActiveTree(treePtrIn); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = const_cast(e.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -539,13 +639,17 @@ EXPORT void mdsplus_tree_setActiveTree(const void *lvTreePtrIn, } EXPORT void mdsplus_tree_setCurrent(const char *treeNameIn, int shotIn, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { Tree::setCurrent(const_cast(treeNameIn), shotIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -556,18 +660,22 @@ EXPORT void mdsplus_tree_setCurrent(const char *treeNameIn, int shotIn, EXPORT void mdsplus_tree_setDefault(const void *lvTreePtr, const void *lvTreeNodePtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; TreeNode *treeNodePtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treeNodePtrIn = reinterpret_cast(const_cast(lvTreeNodePtrIn)); treePtr->setDefault(treeNodePtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -580,7 +688,8 @@ EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, const void *lvStartDataPtrIn, const void *lvEndDataPtrIn, const void *lvDeltaDataPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; Data *startDataPtrIn = NULL; Data *endDataPtrIn = NULL; @@ -588,7 +697,8 @@ EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); startDataPtrIn = reinterpret_cast(const_cast(lvStartDataPtrIn)); @@ -596,7 +706,9 @@ EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, deltaDataPtrIn = reinterpret_cast(const_cast(lvDeltaDataPtrIn)); treePtr->setTimeContext(startDataPtrIn, endDataPtrIn, deltaDataPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -608,17 +720,21 @@ EXPORT void mdsplus_tree_setTimeContext(const void *lvTreePtr, EXPORT void mdsplus_tree_setVersionsInModel(const void *lvTreePtr, LVBoolean *lvVerEnabledIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; bool verEnabledIn; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); verEnabledIn = (*lvVerEnabledIn == LVBooleanTrue) ? true : false; treePtr->setVersionsInModel(verEnabledIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -629,17 +745,21 @@ EXPORT void mdsplus_tree_setVersionsInModel(const void *lvTreePtr, EXPORT void mdsplus_tree_setVersionsInPulse(const void *lvTreePtr, LVBoolean *lvVerEnabledIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; bool verEnabledIn; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); verEnabledIn = (*lvVerEnabledIn == LVBooleanTrue) ? true : false; treePtr->setVersionsInPulse(verEnabledIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -649,15 +769,19 @@ EXPORT void mdsplus_tree_setVersionsInPulse(const void *lvTreePtr, } EXPORT void mdsplus_tree_setViewDate(const void *lvTreePtr, const char *dateIn, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->setViewDate(const_cast(dateIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -668,17 +792,21 @@ EXPORT void mdsplus_tree_setViewDate(const void *lvTreePtr, const char *dateIn, EXPORT void mdsplus_tree_versionsInModelEnabled(const void *lvTreePtr, LVBoolean *lvVerEnabledOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; bool verEnabledOut; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); verEnabledOut = treePtr->versionsInModelEnabled(); *lvVerEnabledOut = (verEnabledOut == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -689,17 +817,21 @@ EXPORT void mdsplus_tree_versionsInModelEnabled(const void *lvTreePtr, EXPORT void mdsplus_tree_versionsInPulseEnabled(const void *lvTreePtr, LVBoolean *lvVerEnabledOut, - ErrorCluster *error) { + ErrorCluster *error) +{ Tree *treePtr = NULL; bool verEnabledOut; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); verEnabledOut = treePtr->versionsInPulseEnabled(); *lvVerEnabledOut = (verEnabledOut == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -708,15 +840,19 @@ EXPORT void mdsplus_tree_versionsInPulseEnabled(const void *lvTreePtr, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_tree_write(const void *lvTreePtr, ErrorCluster *error) { +EXPORT void mdsplus_tree_write(const void *lvTreePtr, ErrorCluster *error) +{ Tree *treePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treePtr = reinterpret_cast(const_cast(lvTreePtr)); treePtr->write(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -732,19 +868,23 @@ EXPORT void mdsplus_tree_write(const void *lvTreePtr, ErrorCluster *error) { EXPORT void mdsplus_treenode_addDevice(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, const char *nameIn, const char *typeIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->addDevice(const_cast(nameIn), const_cast(typeIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -756,19 +896,23 @@ EXPORT void mdsplus_treenode_addDevice(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_addNode(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, const char *nameIn, const char *usageIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->addNode(const_cast(nameIn), const_cast(usageIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -779,16 +923,20 @@ EXPORT void mdsplus_treenode_addNode(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_addTag(const void *lvTreeNodePtr, const char *tagNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->addTag(const_cast(tagNameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -802,7 +950,8 @@ EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, const void *lvEndDataPtrIn, const void *lvTimeDataPtrIn, const void *lvArrayPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *startDataPtrIn = NULL; Data *endDataPtrIn = NULL; @@ -811,7 +960,8 @@ EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); startDataPtrIn = @@ -823,7 +973,9 @@ EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, reinterpret_cast(const_cast(lvArrayPtrIn)); treeNodePtr->beginSegment(startDataPtrIn, endDataPtrIn, timeDataPtrIn, initialDataArrayPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -834,19 +986,23 @@ EXPORT void mdsplus_treenode_beginSegment(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_beginTimestampedSegment(const void *lvTreeNodePtr, const void *lvArrayPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Array *initDataArrayPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); initDataArrayPtrIn = reinterpret_cast(const_cast(lvArrayPtrIn)); treeNodePtr->beginTimestampedSegment(initDataArrayPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -857,18 +1013,22 @@ EXPORT void mdsplus_treenode_beginTimestampedSegment(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_containsVersions(const void *lvTreeNodePtr, LVBoolean *lvContainsVersionsOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvContainsVersionsOut = (treeNodePtr->containsVersions() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -878,16 +1038,20 @@ EXPORT void mdsplus_treenode_containsVersions(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_deleteData(const void *lvTreeNodePtr, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->deleteData(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -898,16 +1062,20 @@ EXPORT void mdsplus_treenode_deleteData(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_doMethod(const void *lvTreeNodePtr, const char *methodIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->doMethod(const_cast(methodIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -916,7 +1084,8 @@ EXPORT void mdsplus_treenode_doMethod(const void *lvTreeNodePtr, fillErrorCluster(errorCode, errorSource, errorMessage, error); } -EXPORT void mdsplus_treenode_destructor(void **lvTreeNodePtr) { +EXPORT void mdsplus_treenode_destructor(void **lvTreeNodePtr) +{ TreeNode *treeNodePtr = reinterpret_cast(*lvTreeNodePtr); delete treeNodePtr; *lvTreeNodePtr = NULL; @@ -924,18 +1093,22 @@ EXPORT void mdsplus_treenode_destructor(void **lvTreeNodePtr) { EXPORT void mdsplus_treenode_findTags(const void *lvTreeNodePtr, void **lvStringArrayPtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; StringArray *stringArrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); stringArrayPtrOut = treeNodePtr->findTags(); *lvStringArrayPtrOut = reinterpret_cast(stringArrayPtrOut); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { delete stringArrayPtrOut; errorCode = bogusError; errorMessage = const_cast(e.what()); @@ -947,18 +1120,22 @@ EXPORT void mdsplus_treenode_findTags(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getBrother(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->getBrother(); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -969,18 +1146,22 @@ EXPORT void mdsplus_treenode_getBrother(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getChild(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->getChild(); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -991,14 +1172,16 @@ EXPORT void mdsplus_treenode_getChild(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getChildren(const void *lvTreeNodePtr, LPtrArrHdl lvPtrArrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode **childrenArrOut; int childrenArrLen = 0; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); childrenArrOut = treeNodePtr->getChildren(&childrenArrLen); @@ -1009,14 +1192,18 @@ EXPORT void mdsplus_treenode_getChildren(const void *lvTreeNodePtr, errorCode = NumericArrayResize(typeCode, 1, reinterpret_cast(&lvPtrArrHdlOut), static_cast(childrenArrLen)); - if (!errorCode) { + if (!errorCode) + { for (int i = 0; i < childrenArrLen; i++) (*lvPtrArrHdlOut)->elt[i] = static_cast(childrenArrOut[i]); (*lvPtrArrHdlOut)->dimSize = static_cast(childrenArrLen); - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(reinterpret_cast(childrenArrOut)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1027,13 +1214,15 @@ EXPORT void mdsplus_treenode_getChildren(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getClass(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = const_cast(treeNodePtr->getClass()); @@ -1041,14 +1230,18 @@ EXPORT void mdsplus_treenode_getClass(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; // deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1059,16 +1252,20 @@ EXPORT void mdsplus_treenode_getClass(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getCompressedLength(const void *lvTreeNodePtr, int *compressedLengthOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *compressedLengthOut = treeNodePtr->getCompressedLength(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1079,16 +1276,20 @@ EXPORT void mdsplus_treenode_getCompressedLength(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getConglomerateElt(const void *lvTreeNodePtr, int *conglomerateEltOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *conglomerateEltOut = treeNodePtr->getConglomerateElt(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1099,18 +1300,22 @@ EXPORT void mdsplus_treenode_getConglomerateElt(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getConglomerateNodes(const void *lvTreeNodePtr, void **lvTreeNodeArrayPtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNodeArray *treeNodeArrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodeArrayPtrOut = treeNodePtr->getConglomerateNodes(); *lvTreeNodeArrayPtrOut = reinterpret_cast(treeNodeArrayPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1120,16 +1325,20 @@ EXPORT void mdsplus_treenode_getConglomerateNodes(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getDepth(const void *lvTreeNodePtr, int *depthOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *depthOut = treeNodePtr->getDepth(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1139,18 +1348,22 @@ EXPORT void mdsplus_treenode_getDepth(const void *lvTreeNodePtr, int *depthOut, } EXPORT void mdsplus_treenode_getData(const void *lvTreeNodePtr, - void **lvDataPtrOut, ErrorCluster *error) { + void **lvDataPtrOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *dataPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); dataPtrOut = treeNodePtr->getData(); *lvDataPtrOut = reinterpret_cast(dataPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1161,14 +1374,16 @@ EXPORT void mdsplus_treenode_getData(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getDescendants(const void *lvTreeNodePtr, LPtrArrHdl lvPtrArrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode **descendantsArrOut; int descendantsArrLen = 0; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); descendantsArrOut = treeNodePtr->getDescendants(&descendantsArrLen); @@ -1179,14 +1394,18 @@ EXPORT void mdsplus_treenode_getDescendants(const void *lvTreeNodePtr, errorCode = NumericArrayResize(typeCode, 1, reinterpret_cast(&lvPtrArrHdlOut), static_cast(descendantsArrLen)); - if (!errorCode) { + if (!errorCode) + { for (int i = 0; i < descendantsArrLen; i++) (*lvPtrArrHdlOut)->elt[i] = static_cast(descendantsArrOut[i]); (*lvPtrArrHdlOut)->dimSize = static_cast(descendantsArrLen); - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(reinterpret_cast(descendantsArrOut)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1197,13 +1416,15 @@ EXPORT void mdsplus_treenode_getDescendants(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getDType(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = const_cast(treeNodePtr->getDType()); @@ -1213,14 +1434,18 @@ EXPORT void mdsplus_treenode_getDType(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; // deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1231,13 +1456,15 @@ EXPORT void mdsplus_treenode_getDType(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getFullPath(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = treeNodePtr->getFullPath(); @@ -1247,14 +1474,18 @@ EXPORT void mdsplus_treenode_getFullPath(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1264,16 +1495,20 @@ EXPORT void mdsplus_treenode_getFullPath(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getLength(const void *lvTreeNodePtr, - int *lengthOut, ErrorCluster *error) { + int *lengthOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lengthOut = treeNodePtr->getLength(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1284,18 +1519,22 @@ EXPORT void mdsplus_treenode_getLength(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getMember(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->getMember(); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1306,14 +1545,16 @@ EXPORT void mdsplus_treenode_getMember(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getMembers(const void *lvTreeNodePtr, LPtrArrHdl lvPtrArrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode **membersArrOut; int membersArrLen = 0; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); membersArrOut = treeNodePtr->getMembers(&membersArrLen); @@ -1324,14 +1565,18 @@ EXPORT void mdsplus_treenode_getMembers(const void *lvTreeNodePtr, errorCode = NumericArrayResize(typeCode, 1, reinterpret_cast(&lvPtrArrHdlOut), static_cast(membersArrLen)); - if (!errorCode) { + if (!errorCode) + { for (int i = 0; i < membersArrLen; i++) (*lvPtrArrHdlOut)->elt[i] = static_cast(membersArrOut[i]); (*lvPtrArrHdlOut)->dimSize = static_cast(membersArrLen); - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(reinterpret_cast(membersArrOut)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1342,13 +1587,15 @@ EXPORT void mdsplus_treenode_getMembers(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getMinPath(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = treeNodePtr->getMinPath(); @@ -1358,14 +1605,18 @@ EXPORT void mdsplus_treenode_getMinPath(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1375,16 +1626,20 @@ EXPORT void mdsplus_treenode_getMinPath(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getNid(const void *lvTreeNodePtr, int *nidOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *nidOut = treeNodePtr->getNid(); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = const_cast(e.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1396,18 +1651,22 @@ EXPORT void mdsplus_treenode_getNid(const void *lvTreeNodePtr, int *nidOut, EXPORT void mdsplus_treenode_getNode(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, const char *relPathIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->getNode(const_cast(relPathIn)); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1419,20 +1678,24 @@ EXPORT void mdsplus_treenode_getNode(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNode_string(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, const void *lvStringPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; String *stringPtrIn = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); stringPtrIn = reinterpret_cast(const_cast(lvStringPtrIn)); treeNodePtrOut = treeNodePtr->getNode(stringPtrIn); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1443,13 +1706,15 @@ EXPORT void mdsplus_treenode_getNode_string(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNodeName(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = treeNodePtr->getNodeName(); @@ -1459,14 +1724,18 @@ EXPORT void mdsplus_treenode_getNodeName(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1477,16 +1746,20 @@ EXPORT void mdsplus_treenode_getNodeName(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNumChildren(const void *lvTreeNodePtr, int *numChildrenOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *numChildrenOut = treeNodePtr->getNumChildren(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1497,16 +1770,20 @@ EXPORT void mdsplus_treenode_getNumChildren(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNumDescendants(const void *lvTreeNodePtr, int *numDescendantsOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *numDescendantsOut = treeNodePtr->getNumDescendants(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1516,16 +1793,20 @@ EXPORT void mdsplus_treenode_getNumDescendants(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getNumElts(const void *lvTreeNodePtr, - int *numEltsOut, ErrorCluster *error) { + int *numEltsOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *numEltsOut = treeNodePtr->getNumElts(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1536,16 +1817,20 @@ EXPORT void mdsplus_treenode_getNumElts(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNumMembers(const void *lvTreeNodePtr, int *numMembersOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *numMembersOut = treeNodePtr->getNumMembers(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1556,16 +1841,20 @@ EXPORT void mdsplus_treenode_getNumMembers(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getNumSegments(const void *lvTreeNodePtr, int *numSegmentsOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *numSegmentsOut = treeNodePtr->getNumSegments(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1577,13 +1866,15 @@ EXPORT void mdsplus_treenode_getNumSegments(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getOriginalPartName(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = treeNodePtr->getOriginalPartName(); @@ -1593,14 +1884,18 @@ EXPORT void mdsplus_treenode_getOriginalPartName(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1610,16 +1905,20 @@ EXPORT void mdsplus_treenode_getOriginalPartName(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getOwnerId(const void *lvTreeNodePtr, - int *ownerIdOut, ErrorCluster *error) { + int *ownerIdOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *ownerIdOut = treeNodePtr->getOwnerId(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1630,18 +1929,22 @@ EXPORT void mdsplus_treenode_getOwnerId(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getParent(const void *lvTreeNodePtr, void **lvTreeNodePtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtrOut = treeNodePtr->getParent(); *lvTreeNodePtrOut = reinterpret_cast(treeNodePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1652,13 +1955,15 @@ EXPORT void mdsplus_treenode_getParent(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getPath(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; char *strOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); strOut = treeNodePtr->getPath(); @@ -1666,14 +1971,18 @@ EXPORT void mdsplus_treenode_getPath(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(reinterpret_cast(strOut), LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; deleteNativeArray(strOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1683,18 +1992,22 @@ EXPORT void mdsplus_treenode_getPath(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getSegment(const void *lvTreeNodePtr, void **lvArrayPtrOut, int segIdxIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Array *arrayPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); arrayPtrOut = treeNodePtr->getSegment(segIdxIn); *lvArrayPtrOut = reinterpret_cast(arrayPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1707,21 +2020,25 @@ EXPORT void mdsplus_treenode_getSegmentLimits(const void *lvTreeNodePtr, int segmentIdxIn, void **lvStartDataPtrOut, void **lvEndDataPtrOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *startDataPtrOut = NULL; Data *endDataPtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->getSegmentLimits(segmentIdxIn, &startDataPtrOut, &endDataPtrOut); *lvStartDataPtrOut = reinterpret_cast(startDataPtrOut); *lvEndDataPtrOut = reinterpret_cast(endDataPtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1731,16 +2048,20 @@ EXPORT void mdsplus_treenode_getSegmentLimits(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getStatus(const void *lvTreeNodePtr, - int *statusOut, ErrorCluster *error) { + int *statusOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *statusOut = treeNodePtr->getStatus(); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1752,12 +2073,14 @@ EXPORT void mdsplus_treenode_getStatus(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, int64_t *timeInsertedOut, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *timeInsertedOut = treeNodePtr->getTimeInserted(); @@ -1768,7 +2091,8 @@ EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, // GAB Oct 2014 if (NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), - sizeof(int32) + retLen) == noErr) { + sizeof(int32) + retLen) == noErr) + { MoveBlock(reinterpret_cast(retStr), LStrBuf(*lvStrHdlOut), retLen); (*lvStrHdlOut)->cnt = retLen; @@ -1776,7 +2100,9 @@ EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, deleteNativeArray(retStr); deleteData(retTimeStr); deleteData(timeInsertedData); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1786,18 +2112,22 @@ EXPORT void mdsplus_treenode_getTimeInserted(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_getTree(const void *lvTreeNodePtr, - void **lvTreePtrOut, ErrorCluster *error) { + void **lvTreePtrOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Tree *treePtrOut = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treePtrOut = treeNodePtr->getTree(); *lvTreePtrOut = reinterpret_cast(treePtrOut); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1808,11 +2138,13 @@ EXPORT void mdsplus_treenode_getTree(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_getUsage(const void *lvTreeNodePtr, LStrHandle lvStrHdlOut, - ErrorCluster *error) { + ErrorCluster *error) +{ MgErr errorCode = noErr; char const *errorSource = __func__; char const *errorMessage = (char *)""; - try { + try + { TreeNode *treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); char const *strOut = treeNodePtr->getUsage(); @@ -1822,12 +2154,16 @@ EXPORT void mdsplus_treenode_getUsage(const void *lvTreeNodePtr, errorCode = NumericArrayResize(uB, 1, reinterpret_cast(&lvStrHdlOut), strOutLen + sizeof(int32)); - if (!errorCode) { + if (!errorCode) + { MoveBlock(strOut, LStrBuf(*lvStrHdlOut), strOutLen); (*lvStrHdlOut)->cnt = strOutLen; - } else + } + else errorMessage = (char *)"NumericArrayResize error"; - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = e.what(); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1838,17 +2174,21 @@ EXPORT void mdsplus_treenode_getUsage(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isChild(const void *lvTreeNodePtr, LVBoolean *lvIsChildOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsChildOut = (treeNodePtr->isChild() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1859,18 +2199,22 @@ EXPORT void mdsplus_treenode_isChild(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isCompressOnPut(const void *lvTreeNodePtr, LVBoolean *lvIsCompressOnPutOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsCompressOnPutOut = (treeNodePtr->isCompressOnPut() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1881,17 +2225,21 @@ EXPORT void mdsplus_treenode_isCompressOnPut(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isEssential(const void *lvTreeNodePtr, LVBoolean *lvIsEssentialOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsEssentialOut = (treeNodePtr->isEssential() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1903,25 +2251,30 @@ EXPORT void mdsplus_treenode_isEssential(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isIncludedInPulse(const void *lvTreeNodePtr, LVBoolean *lvisIncludeInPulseOut, - ErrorCluster *error) { + ErrorCluster *error) +{ mdsplus_treenode_isIncludeInPulse(lvTreeNodePtr, lvisIncludeInPulseOut, error); } EXPORT void mdsplus_treenode_isIncludeInPulse(const void *lvTreeNodePtr, LVBoolean *lvisIncludeInPulseOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvisIncludeInPulseOut = (treeNodePtr->isIncludeInPulse() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1932,17 +2285,21 @@ EXPORT void mdsplus_treenode_isIncludeInPulse(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isMember(const void *lvTreeNodePtr, LVBoolean *lvIsMemberOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsMemberOut = (treeNodePtr->isMember() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1953,18 +2310,22 @@ EXPORT void mdsplus_treenode_isMember(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isNoWriteModel(const void *lvTreeNodePtr, LVBoolean *lvIsNoWriteModelOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsNoWriteModelOut = (treeNodePtr->isNoWriteModel() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1975,17 +2336,21 @@ EXPORT void mdsplus_treenode_isNoWriteModel(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isNoWriteShot(const void *lvTreeNodePtr, LVBoolean *lvIsNoWriteShotOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsNoWriteShotOut = (treeNodePtr->isNoWriteShot() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -1995,16 +2360,20 @@ EXPORT void mdsplus_treenode_isNoWriteShot(const void *lvTreeNodePtr, } EXPORT void mdsplus_treenode_isOn(const void *lvTreeNodePtr, - LVBoolean *lvIsOnOut, ErrorCluster *error) { + LVBoolean *lvIsOnOut, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsOnOut = (treeNodePtr->isOn() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2015,17 +2384,21 @@ EXPORT void mdsplus_treenode_isOn(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isSetup(const void *lvTreeNodePtr, LVBoolean *lvIsSetupOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsSetupOut = (treeNodePtr->isSetup() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2036,17 +2409,21 @@ EXPORT void mdsplus_treenode_isSetup(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_isWriteOnce(const void *lvTreeNodePtr, LVBoolean *lvIsWriteOnceOut, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); *lvIsWriteOnceOut = (treeNodePtr->isWriteOnce() == true) ? LVBooleanTrue : LVBooleanFalse; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2060,7 +2437,8 @@ EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, const void *lvEndDataPtrIn, const void *lvTimeDataPtrIn, const void *lvArrayPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *startDataPtrIn = NULL; Data *endDataPtrIn = NULL; @@ -2069,7 +2447,8 @@ EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); startDataPtrIn = @@ -2091,7 +2470,9 @@ EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, throw MdsException("initialDataArrayPtrIn NULL"); treeNodePtr->makeSegment(startDataPtrIn, endDataPtrIn, timeDataPtrIn, initialDataArrayPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2102,14 +2483,16 @@ EXPORT void mdsplus_treenode_makeSegment(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_makeTimestampedSegment( const void *lvTreeNodePtr, const void *lvArrayPtrIn, - const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error) { + const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Array *arrayPtrIn = NULL; int64_t *timesArrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); arrayPtrIn = reinterpret_cast(const_cast(lvArrayPtrIn)); @@ -2119,7 +2502,9 @@ EXPORT void mdsplus_treenode_makeTimestampedSegment( timesArrIn[i] = static_cast((*lvLngArrHdlIn)->elt[i]); treeNodePtr->makeTimestampedSegment(arrayPtrIn, timesArrIn); delete[] timesArrIn; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2130,19 +2515,23 @@ EXPORT void mdsplus_treenode_makeTimestampedSegment( EXPORT void mdsplus_treenode_move(const void *lvTreeNodePtr, const void *lvTreeNodePtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodeParentPtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodeParentPtr = reinterpret_cast(const_cast(lvTreeNodePtrIn)); treeNodePtr->move(treeNodeParentPtr); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2154,19 +2543,23 @@ EXPORT void mdsplus_treenode_move(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_move_newName(const void *lvTreeNodePtr, const void *lvTreeNodePtrIn, const char *newNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; TreeNode *treeNodeParentPtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodeParentPtr = reinterpret_cast(const_cast(lvTreeNodePtrIn)); treeNodePtr->move(treeNodeParentPtr, const_cast(newNameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2177,18 +2570,22 @@ EXPORT void mdsplus_treenode_move_newName(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_putData(const void *lvTreeNodePtr, const void *lvDataPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *dataPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); treeNodePtr->putData(dataPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2199,18 +2596,22 @@ EXPORT void mdsplus_treenode_putData(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_putRow(const void *lvTreeNodePtr, const void *lvDataPtrIn, int64_t *timeIn, - int sizeIn, ErrorCluster *error) { + int sizeIn, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *dataPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); dataPtrIn = reinterpret_cast(const_cast(lvDataPtrIn)); treeNodePtr->putRow(dataPtrIn, timeIn, sizeIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2221,18 +2622,22 @@ EXPORT void mdsplus_treenode_putRow(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_putSegment(const void *lvTreeNodePtr, const void *lvArrayPtrIn, int ofsIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Array *arrayPtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); arrayPtrIn = reinterpret_cast(const_cast(lvArrayPtrIn)); treeNodePtr->putSegment(arrayPtrIn, ofsIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2243,14 +2648,16 @@ EXPORT void mdsplus_treenode_putSegment(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_putTimestampedSegment( const void *lvTreeNodePtr, const void *lvArrayPtrIn, - const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error) { + const LLngArrHdl lvLngArrHdlIn, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Array *arrayPtrIn = NULL; int64_t *timesArrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); arrayPtrIn = reinterpret_cast(const_cast(lvArrayPtrIn)); @@ -2260,7 +2667,9 @@ EXPORT void mdsplus_treenode_putTimestampedSegment( timesArrIn[i] = static_cast((*lvLngArrHdlIn)->elt[i]); treeNodePtr->putTimestampedSegment(arrayPtrIn, timesArrIn); delete[] timesArrIn; - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2270,16 +2679,20 @@ EXPORT void mdsplus_treenode_putTimestampedSegment( } EXPORT void mdsplus_treenode_remove(const void *lvTreeNodePtr, - const char *nameIn, ErrorCluster *error) { + const char *nameIn, ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->remove(const_cast(nameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2290,16 +2703,20 @@ EXPORT void mdsplus_treenode_remove(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_removeTag(const void *lvTreeNodePtr, const char *tagNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->removeTag(const_cast(tagNameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2310,16 +2727,20 @@ EXPORT void mdsplus_treenode_removeTag(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_rename(const void *lvTreeNodePtr, const char *newNameIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treeNodePtr->rename(const_cast(newNameIn)); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2330,19 +2751,23 @@ EXPORT void mdsplus_treenode_rename(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setCompressOnPut(const void *lvTreeNodePtr, LVBoolean *lvCompressOnPutIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvCompressOnPutIn == LVBooleanTrue) treeNodePtr->setCompressOnPut(true); else treeNodePtr->setCompressOnPut(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2353,19 +2778,23 @@ EXPORT void mdsplus_treenode_setCompressOnPut(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setEssential(const void *lvTreeNodePtr, LVBoolean *lvEssentialIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvEssentialIn == LVBooleanTrue) treeNodePtr->setEssential(true); else treeNodePtr->setEssential(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2376,25 +2805,30 @@ EXPORT void mdsplus_treenode_setEssential(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setIncludedInPulse(const void *lvTreeNodePtr, LVBoolean *lvIncludeInPulseIn, - ErrorCluster *error) { + ErrorCluster *error) +{ mdsplus_treenode_setIncludeInPulse(lvTreeNodePtr, lvIncludeInPulseIn, error); } EXPORT void mdsplus_treenode_setIncludeInPulse(const void *lvTreeNodePtr, LVBoolean *lvIncludeInPulseIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvIncludeInPulseIn == LVBooleanTrue) treeNodePtr->setIncludeInPulse(true); else treeNodePtr->setIncludeInPulse(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2405,19 +2839,23 @@ EXPORT void mdsplus_treenode_setIncludeInPulse(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setNoWriteModel(const void *lvTreeNodePtr, LVBoolean *lvSetNoWriteModelIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvSetNoWriteModelIn == LVBooleanTrue) treeNodePtr->setNoWriteModel(true); else treeNodePtr->setNoWriteModel(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2428,19 +2866,23 @@ EXPORT void mdsplus_treenode_setNoWriteModel(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setNoWriteShot(const void *lvTreeNodePtr, LVBoolean *lvNoWriteShotIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvNoWriteShotIn == LVBooleanTrue) treeNodePtr->setNoWriteShot(true); else treeNodePtr->setNoWriteShot(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2450,19 +2892,23 @@ EXPORT void mdsplus_treenode_setNoWriteShot(const void *lvTreeNodePtr, } EXPORT void mdsplus_teenode_setOn(const void *lvTreeNodePtr, LVBoolean *lvOnIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvOnIn == LVBooleanTrue) treeNodePtr->setOn(true); else treeNodePtr->setOn(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2473,19 +2919,23 @@ EXPORT void mdsplus_teenode_setOn(const void *lvTreeNodePtr, LVBoolean *lvOnIn, EXPORT void mdsplus_treenode_setSubTree(const void *lvTreeNodePtr, LVBoolean *lvSubTreeIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvSubTreeIn == LVBooleanTrue) treeNodePtr->setSubtree(true); else treeNodePtr->setSubtree(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2496,18 +2946,22 @@ EXPORT void mdsplus_treenode_setSubTree(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setTree(const void *lvTreeNodePtr, const void *lvTreePtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Tree *treePtrIn = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); treePtrIn = reinterpret_cast(const_cast(lvTreePtrIn)); treeNodePtr->setTree(treePtrIn); - } catch (const MdsException &e) { + } + catch (const MdsException &e) + { errorCode = bogusError; errorMessage = const_cast(e.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2518,19 +2972,23 @@ EXPORT void mdsplus_treenode_setTree(const void *lvTreeNodePtr, EXPORT void mdsplus_treenode_setWriteOnce(const void *lvTreeNodePtr, LVBoolean *lvWriteOnceIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); if (*lvWriteOnceIn == LVBooleanTrue) treeNodePtr->setWriteOnce(true); else treeNodePtr->setWriteOnce(false); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2543,7 +3001,8 @@ EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, const void *lvStartDataPtrIn, const void *lvEndDataPtrIn, const void *lvTimeDataPtrIn, - ErrorCluster *error) { + ErrorCluster *error) +{ TreeNode *treeNodePtr = NULL; Data *startDataPtrIn = NULL; Data *endDataPtrIn = NULL; @@ -2551,7 +3010,8 @@ EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, MgErr errorCode = noErr; const char *errorSource = __FUNCTION__; char const *errorMessage = ""; - try { + try + { treeNodePtr = reinterpret_cast(const_cast(lvTreeNodePtr)); startDataPtrIn = @@ -2560,7 +3020,9 @@ EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, timeDataPtrIn = reinterpret_cast(const_cast(lvTimeDataPtrIn)); treeNodePtr->updateSegment(startDataPtrIn, endDataPtrIn, timeDataPtrIn); - } catch (const MdsException &mdsE) { + } + catch (const MdsException &mdsE) + { errorCode = bogusError; errorMessage = const_cast(mdsE.what()); fillErrorCluster(errorCode, errorSource, errorMessage, error); @@ -2573,7 +3035,8 @@ EXPORT void mdsplus_treenode_updateSegment(const void *lvTreeNodePtr, TREENODEARRAY ********************************************************************************************************/ -EXPORT void mdsplus_treenodearray_destructor(void **lvTreeNodeArrayPtr) { +EXPORT void mdsplus_treenodearray_destructor(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); delete treeNodeArrayPtr; @@ -2581,79 +3044,92 @@ EXPORT void mdsplus_treenodearray_destructor(void **lvTreeNodeArrayPtr) { } EXPORT TreeNode *mdsplus_treenodearray_getItem(void **lvTreeNodeArrayPtr, - int n) { + int n) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return (*treeNodeArrayPtr)[n]; } EXPORT Int32Array * -mdsplus_treenodearray_getCompressedLength(void **lvTreeNodeArrayPtr) { +mdsplus_treenodearray_getCompressedLength(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getCompressedLength(); } EXPORT StringArray * -mdsplus_treenodearray_getFullPath(void **lvTreeNodeArrayPtr) { +mdsplus_treenodearray_getFullPath(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getFullPath(); } -EXPORT Int32Array *mdsplus_treenodearray_getLength(void **lvTreeNodeArrayPtr) { +EXPORT Int32Array *mdsplus_treenodearray_getLength(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getLength(); } -EXPORT Int32Array *mdsplus_treenodearray_getNid(void **lvTreeNodeArrayPtr) { +EXPORT Int32Array *mdsplus_treenodearray_getNid(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getNid(); } -EXPORT StringArray *mdsplus_treenodearray_getPath(void **lvTreeNodeArrayPtr) { +EXPORT StringArray *mdsplus_treenodearray_getPath(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getPath(); } -EXPORT StringArray *mdsplus_treenodearray_getUsage(void **lvTreeNodeArrayPtr) { +EXPORT StringArray *mdsplus_treenodearray_getUsage(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->getUsage(); } EXPORT Int8Array * -mdsplus_treenodearray_isCompressOnPut(void **lvTreeNodeArrayPtr) { +mdsplus_treenodearray_isCompressOnPut(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isCompressOnPut(); } EXPORT Int8Array * -mdsplus_treenodearray_isNoWriteModel(void **lvTreeNodeArrayPtr) { +mdsplus_treenodearray_isNoWriteModel(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isNoWriteModel(); } EXPORT Int8Array * -mdsplus_treenodearray_isNoWriteShot(void **lvTreeNodeArrayPtr) { +mdsplus_treenodearray_isNoWriteShot(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isNoWriteShot(); } -EXPORT Int8Array *mdsplus_treenodearray_isOn(void **lvTreeNodeArrayPtr) { +EXPORT Int8Array *mdsplus_treenodearray_isOn(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isOn(); } -EXPORT Int8Array *mdsplus_treenodearray_isSetup(void **lvTreeNodeArrayPtr) { +EXPORT Int8Array *mdsplus_treenodearray_isSetup(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isSetup(); } -EXPORT Int8Array *mdsplus_treenodearray_isWriteOnce(void **lvTreeNodeArrayPtr) { +EXPORT Int8Array *mdsplus_treenodearray_isWriteOnce(void **lvTreeNodeArrayPtr) +{ TreeNodeArray *treeNodeArrayPtr = reinterpret_cast(*lvTreeNodeArrayPtr); return treeNodeArrayPtr->isWriteOnce(); @@ -2663,7 +3139,8 @@ EXPORT Int8Array *mdsplus_treenodearray_isWriteOnce(void **lvTreeNodeArrayPtr) { TREEPATH ********************************************************************************************************/ -EXPORT void mdsplus_treepath_destructor(void **lvTreePathPtr) { +EXPORT void mdsplus_treepath_destructor(void **lvTreePathPtr) +{ TreePath *treePathPtr = reinterpret_cast(*lvTreePathPtr); deleteData(treePathPtr); *lvTreePathPtr = NULL; diff --git a/mdsshr/MDSprintf.c b/mdsshr/MDSprintf.c index 29a63dc2dc..597eb3a9ef 100644 --- a/mdsshr/MDSprintf.c +++ b/mdsshr/MDSprintf.c @@ -80,7 +80,8 @@ STATIC_THREADSAFE int (*MDSvfprintf)() = /****************************************************************** * MDSprintf: ******************************************************************/ -EXPORT int MDSprintf(const char *const fmt, ...) { +EXPORT int MDSprintf(const char *const fmt, ...) +{ va_list ap; if (!MDSvprintf) @@ -92,7 +93,8 @@ EXPORT int MDSprintf(const char *const fmt, ...) { /****************************************************************** * MDSfprintf: ******************************************************************/ -int MDSfprintf(FILE *const fp, const char *const fmt, ...) { +int MDSfprintf(FILE *const fp, const char *const fmt, ...) +{ va_list ap; va_start(ap, fmt); /* initialize "ap" */ @@ -109,7 +111,8 @@ int MDSfprintf(FILE *const fp, const char *const fmt, ...) { ***************************************************************/ void MdsSetOutputFunctions(int (*const NEWvprintf)(const char *, void *), int (*const NEWvfprintf)(FILE *, const char *, - void *)) { + void *)) +{ MDSvprintf = ((void *)NEWvprintf == (void *)-1) ? (int (*)())vprintf : (int (*)())NEWvprintf; MDSvfprintf = ((void *)NEWvfprintf == (void *)-1) ? (int (*)())vfprintf @@ -117,7 +120,8 @@ void MdsSetOutputFunctions(int (*const NEWvprintf)(const char *, void *), return; } -void MdsGetOutputFunctions(void **const CURvprintf, void **const CURvfprintf) { +void MdsGetOutputFunctions(void **const CURvprintf, void **const CURvfprintf) +{ if (CURvprintf) *CURvprintf = (void *)MDSvprintf; if (CURvfprintf) @@ -130,21 +134,24 @@ void MdsGetOutputFunctions(void **const CURvprintf, void **const CURvfprintf) { * main: ****************************************************************/ -STATIC_ROUTINE int woof(const char *const fmt, va_list ap) { +STATIC_ROUTINE int woof(const char *const fmt, va_list ap) +{ char xxfmt[80]; sprintf(xxfmt, "\nWOOF: %s", fmt); return (vprintf(xxfmt, ap)); } -STATIC_ROUTINE int tweet(FILE *fp, const char *const fmt, va_list ap) { +STATIC_ROUTINE int tweet(FILE *fp, const char *const fmt, va_list ap) +{ char xxfmt[80]; sprintf(xxfmt, "\nTWEET: %s\n", fmt); return (vfprintf(fp, xxfmt, ap)); } -int main(int argc, void *argv[]) { +int main(int argc, void *argv[]) +{ void *save_vprintf; void *save_vfprintf; MDSprintf("woof %d %d %d\n", 1, 2, 3); diff --git a/mdsshr/MdsCmprs.c b/mdsshr/MdsCmprs.c index c3ef7d6366..3580ca8d58 100644 --- a/mdsshr/MdsCmprs.c +++ b/mdsshr/MdsCmprs.c @@ -107,16 +107,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define X_AND_Y(x, y) (int)(XFIELD(x) | YFIELD(y)) #define X_OF_INT(val) (int)(((unsigned int)(val) >> BITSY) & MASK(BITSX)) #define Y_OF_INT(val) (int)((unsigned int)(val)&MASK(BITSY)) -#define SWAP_SHORTS(in, out) \ +#define SWAP_SHORTS(in, out) \ ((short *)out)[0] = ((short *)in)[1], ((short *)out)[1] = ((short *)in)[0] -#define DEFINED_OVERFLOW(a, op, b) \ - (signed)(((unsigned)(a))op( \ +#define DEFINED_OVERFLOW(a, op, b) \ + (signed)(((unsigned)(a))op( \ (unsigned)(b))) // use defined + and - operations on unsigned -typedef struct { +typedef struct +{ int l; } * PF; -struct HEADER { +struct HEADER +{ int n; int e; }; @@ -125,7 +127,8 @@ STATIC_CONSTANT signed char FIELDSY = BITSY + BITSX; STATIC_CONSTANT int FIELDSX = 2; int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, - mdsdsc_a_t *const pack_dsc_ptr, int *const bit_ptr) { + mdsdsc_a_t *const pack_dsc_ptr, int *const bit_ptr) +{ int nitems = *nitems_ptr; int step = items_dsc_ptr->length; int dtype = items_dsc_ptr->dtype; @@ -170,7 +173,8 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, /*************** Do this in runs. ***************/ - while (nitems > 0) { + while (nitems > 0) + { memset((void *)tally, 0, sizeof(tally)); xn = j = MIN(nitems, MAXX); nitems -= j; @@ -181,7 +185,8 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, Temporary is exce. Repoint for ints. *********************/ - switch (dtype) { + switch (dtype) + { default: if (step == sizeof(int)) goto case_LU; @@ -239,7 +244,8 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, for the range -7 to +7. ******************************/ old = 0; - for (pn = diff, j = xn; --j >= 0; old = *p32++) { + for (pn = diff, j = xn; --j >= 0; old = *p32++) + { unsigned int delta; /**** Check for integer overflow, * previously was: @@ -251,25 +257,34 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, ***********/ int32_t ans = DEFINED_OVERFLOW(*p32, -, old); if ((((uint32_t)ans) == 0x80000000) || - (old < 0 ? ans < *p32 : ans > *p32)) { + (old < 0 ? ans < *p32 : ans > *p32)) + { *pn++ = ans; yy = 32; - } else { + } + else + { i = *pn++ = ans; delta = (uint32_t)((i < 0) ? -i : i); - if (delta <= 64) { + if (delta <= 64) + { yy = signif[delta]; - } else { + } + else + { yy = 0; - if (delta > 0x1000000) { + if (delta > 0x1000000) + { delta = delta >> 24; yy += 24; } - if (delta > 0x1000) { + if (delta > 0x1000) + { delta = delta >> 12; yy += 12; } - if (delta > 0x40) { + if (delta > 0x40) + { delta = delta >> 6; yy += 6; } @@ -281,11 +296,14 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, /*************************** Special case for all zeroes. ***************************/ - if (tally[0] == xn) { + if (tally[0] == xn) + { yn = 0; xe = 0; ye = 0; - } else { + } + else + { /************************************************** Determine exception width and do xn-sum(1:y). tally[0] is y=1 count, i.e., the number of zeros. @@ -304,8 +322,10 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, For y=ye there are no exceptions. *******************************************/ best = xn * yy; - while (--yy > 0) { - if ((test = xn * yy + *--ptally * ye) < best) { + while (--yy > 0) + { + if ((test = xn * yy + *--ptally * ye) < best) + { best = test; yn = yy; } @@ -318,7 +338,8 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, *********************/ int mark = (int)(0xFFFFFFFF << (yn - 1)); int maxim = ~mark; - for (pn = diff, pe = exce, j = xe; --j >= 0;) { + for (pn = diff, pe = exce, j = xe; --j >= 0;) + { while (*pn <= maxim && *pn > mark) ++pn; *pe++ = *pn; @@ -347,7 +368,8 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, Expand compressed data. */ EXPORT int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, - mdsdsc_a_t *const items_dsc_ptr, int *const bit_ptr) { + mdsdsc_a_t *const items_dsc_ptr, int *const bit_ptr) +{ int nitems = *nitems_ptr; char *ppack = memcpy(malloc(pack_dsc_ptr->arsize + 4), pack_dsc_ptr->pointer, pack_dsc_ptr->arsize); @@ -375,7 +397,8 @@ EXPORT int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, Note the sign-extended unpacking. ********************************/ memset(ppack + pack_dsc_ptr->arsize, -1, 4); - while (nitems > 0) { + while (nitems > 0) + { signed char nbits = FIELDSY; if ((*bit_ptr + 2 * (BITSY + BITSX)) > limit) break; @@ -393,13 +416,16 @@ EXPORT int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, nitems -= j; nbits = (char)yn; MdsUnpk(&nbits, &xn, (int *)ppack, diff, (int *)bit_ptr); - if (xe) { + if (xe) + { *bit_ptr -= yn * (xhead - j); pe = exce; nbits = (char)ye; MdsUnpk(&nbits, &xe, (int *)ppack, pe, (int *)bit_ptr); mark = (int)(0xFFFFFFFF << (-yn - 1)); - } else { + } + else + { pe = diff; mark = 0; } @@ -411,7 +437,8 @@ EXPORT int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, ***********************************/ pn = diff; old = 0; - switch (dtype) { + switch (dtype) + { default: if (step == sizeof(int)) goto case_LU; @@ -421,14 +448,15 @@ EXPORT int MdsXpand(int *const nitems_ptr, const mdsdsc_a_t *const pack_dsc_ptr, case DTYPE_T: case DTYPE_B: case DTYPE_BU: -#define load(type) \ - { \ - type *newone; \ - for (newone = (type *)px; --j >= 0; pn++, newone++) { \ - old = DEFINED_OVERFLOW(old, +, (xe && (*pn == mark)) ? *pe++ : *pn); \ - *newone = (type)old; \ - } \ - px = (PF)newone; \ +#define load(type) \ + { \ + type *newone; \ + for (newone = (type *)px; --j >= 0; pn++, newone++) \ + { \ + old = DEFINED_OVERFLOW(old, +, (xe && (*pn == mark)) ? *pe++ : *pn); \ + *newone = (type)old; \ + } \ + px = (PF)newone; \ } case_BU: load(char); diff --git a/mdsshr/MdsCompareXd.c b/mdsshr/MdsCompareXd.c index b2941db68d..dc28fd0c44 100644 --- a/mdsshr/MdsCompareXd.c +++ b/mdsshr/MdsCompareXd.c @@ -56,7 +56,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, - const mdsdsc_t *const dsc2_ptr) { + const mdsdsc_t *const dsc2_ptr) +{ const mdsdsc_t *d1 = dsc1_ptr; const mdsdsc_t *d2 = dsc2_ptr; int isequal = 0; @@ -69,9 +70,12 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, d1 = (const mdsdsc_t *)d1->pointer; while (d2 && d2->dtype == DTYPE_DSC) d2 = (const mdsdsc_t *)d2->pointer; - if (d1 && d2) { - if (d1->dtype == d2->dtype) { - switch (d1->class) { + if (d1 && d2) + { + if (d1->dtype == d2->dtype) + { + switch (d1->class) + { default: return 0; // TODO: handle missing classes case CLASS_S: @@ -83,7 +87,8 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, case CLASS_XD: case CLASS_XS: - if ((d2->class == CLASS_XS) || (d2->class == CLASS_XD)) { + if ((d2->class == CLASS_XS) || (d2->class == CLASS_XD)) + { mdsdsc_xd_t *xd1 = (mdsdsc_xd_t *)d1; mdsdsc_xd_t *xd2 = (mdsdsc_xd_t *)d2; if (xd1->l_length == xd2->l_length) @@ -92,17 +97,22 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, break; case CLASS_R: - if (d2->class == CLASS_R) { + if (d2->class == CLASS_R) + { mdsdsc_r_t *r1 = (mdsdsc_r_t *)d1; mdsdsc_r_t *r2 = (mdsdsc_r_t *)d2; int i; isequal = (r1->length == r2->length) && (r1->ndesc == r2->ndesc); - if (isequal) { - if (r1->length) { + if (isequal) + { + if (r1->length) + { isequal = memcmp(r1->pointer, r2->pointer, r1->length) == 0; } - if (isequal) { - for (i = 0; isequal && (i < r1->ndesc); i++) { + if (isequal) + { + for (i = 0; isequal && (i < r1->ndesc); i++) + { isequal = MdsCompareXd(r1->dscptrs[i], r2->dscptrs[i]) & 1; } } @@ -113,7 +123,8 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, case CLASS_A: case CLASS_CA: case CLASS_APD: - if (d2->class == d1->class) { + if (d2->class == d1->class) + { array_bounds *a1 = (array_bounds *)d1; array_bounds *a2 = (array_bounds *)d2; isequal = (a1->length == a2->length) && (a1->arsize == a2->arsize) && @@ -124,8 +135,10 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, (a1->aflags.column == a2->aflags.column) && (a1->aflags.coeff == a2->aflags.coeff) && (a1->aflags.bounds == a2->aflags.bounds); - if (isequal) { - if (a1->aflags.coeff) { + if (isequal) + { + if (a1->aflags.coeff) + { isequal = (a1->pointer - a1->a0 == a2->pointer - a2->a0); isequal &= (memcmp(a1->m, a2->m, sizeof(a1->m[0]) * a1->dimct) == 0); @@ -133,17 +146,20 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, isequal = memcmp(a1->m + a1->dimct, a2->m + a2->dimct, sizeof(bound_t) * a1->dimct) == 0; } - if (isequal) { + if (isequal) + { if (d1->class == CLASS_A) isequal = memcmp(a1->pointer, a2->pointer, a1->arsize) == 0; else if (d1->class == CLASS_CA) isequal = MdsCompareXd((mdsdsc_t *)a1->pointer, (mdsdsc_t *)a2->pointer); - else { // d1->class == CLASS_APD + else + { // d1->class == CLASS_APD l_length_t i, nelts = a1->arsize / a1->length; mdsdsc_t *ptr1 = (mdsdsc_t *)a1->pointer; mdsdsc_t *ptr2 = (mdsdsc_t *)a2->pointer; - for (i = 0; isequal && (i < nelts);) { + for (i = 0; isequal && (i < nelts);) + { isequal = MdsCompareXd(ptr1, ptr2); ptr1++; ptr2++; @@ -155,7 +171,9 @@ EXPORT int MdsCompareXd(const mdsdsc_t *const dsc1_ptr, break; } } - } else { + } + else + { isequal = !(d1 || d2); } return isequal; diff --git a/mdsshr/MdsCompress.c b/mdsshr/MdsCompress.c index 8f2a31e200..82598c298f 100644 --- a/mdsshr/MdsCompress.c +++ b/mdsshr/MdsCompress.c @@ -103,7 +103,8 @@ STATIC_CONSTANT EMPTYXD(EMPTY_XD); */ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, const mdsdsc_t *const pcentry, const int64_t delta, - mdsdsc_t *const pwork) { + mdsdsc_t *const pwork) +{ int j, stat1, status = 1; unsigned int bit = 0; int nitems, (*symbol)(); @@ -115,7 +116,8 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, mdsdsc_t *pd0, *pd1, **ppd; size_t asize, align_size; if (pwork) - switch (pwork->class) { + switch (pwork->class) + { case CLASS_APD: // pd1 = (mdsdsc_t *) pwork->pointer; ppd = (mdsdsc_t **)pwork->pointer; @@ -189,7 +191,8 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, pdat->arsize = (unsigned int)(plim - pcmp); nitems = (int)porig->arsize / (int)porig->length; - if (pcentry) { + if (pcentry) + { dximage = EMPTY_D; dxentry = EMPTY_D; status = LibFindImageSymbol(pcimage, pcentry, &symbol); @@ -197,9 +200,11 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, status = (*symbol)(&nitems, pwork, pdat, &bit, &dximage, &dxentry); pdat->arsize = (bit + 7) / 8; pd0 = (mdsdsc_t *)(pdat->pointer + pdat->arsize); - if (dximage.pointer) { + if (dximage.pointer) + { pd1 = &pd0[1] + dximage.length; - if ((char *)pd1 < (char *)plim) { + if ((char *)pd1 < (char *)plim) + { prec->dscptrs[0] = pd0; *pd0 = *(mdsdsc_t *)&dximage; _MOVC3(dximage.length, dximage.pointer, @@ -208,9 +213,11 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, pd0 = pd1; StrFree1Dx(&dximage); } - if (dxentry.pointer) { + if (dxentry.pointer) + { pd1 = &pd0[1] + dxentry.length; - if ((char *)pd1 < (char *)plim) { + if ((char *)pd1 < (char *)plim) + { prec->dscptrs[1] = pd0; *pd0 = *(mdsdsc_t *)&dxentry; _MOVC3(dxentry.length, dxentry.pointer, @@ -268,13 +275,15 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, EXPORT int MdsCompress(const mdsdsc_t *const cimage_ptr, const mdsdsc_t *const centry_ptr, const mdsdsc_t *const in_ptr, - mdsdsc_xd_t *const out_ptr) { + mdsdsc_xd_t *const out_ptr) +{ int status = 1; mdsdsc_xd_t work; STATIC_CONSTANT dtype_t dsc_dtype = DTYPE_DSC; if (in_ptr == 0) return MdsFree1Dx(out_ptr, NULL); - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_XD: work = *(mdsdsc_xd_t *)in_ptr; *(mdsdsc_xd_t *)in_ptr = EMPTY_XD; @@ -307,7 +316,8 @@ Compact/copy from work. #endif { status = MdsGet1Dx(&work.l_length, &dsc_dtype, out_ptr, NULL); - if (status & 1) { + if (status & 1) + { #ifdef _RECURSIVE_COMPRESS int orig_len = work.l_length; #endif @@ -319,11 +329,13 @@ Compact/copy from work. status = MdsCopyDxXd(work.pointer, out_ptr); MdsFree1Dx(&work, NULL); #ifdef _RECURSIVE_COMPRESS - if ((status == MdsCOMPRESSIBLE) && (orig_len / 2 > out_ptr->l_length)) { + if ((status == MdsCOMPRESSIBLE) && (orig_len / 2 > out_ptr->l_length)) + { work = *out_ptr; out_ptr->pointer = 0; out_ptr->l_length = 0; - } else + } + else status = 1; #endif } @@ -337,10 +349,12 @@ Compact/copy from work. status = MdsDecompress(%ref(class_ca or r_function), %ref(output_xd)) */ -EXPORT int MdsDecompress(const mdsdsc_r_t *rec_ptr, mdsdsc_xd_t *out_ptr) { +EXPORT int MdsDecompress(const mdsdsc_r_t *rec_ptr, mdsdsc_xd_t *out_ptr) +{ const mdsdsc_r_t *prec = rec_ptr; int status, (*symbol)(); - if (prec == 0) { + if (prec == 0) + { MdsFree1Dx(out_ptr, NULL); return 1; } @@ -351,28 +365,35 @@ EXPORT int MdsDecompress(const mdsdsc_r_t *rec_ptr, mdsdsc_xd_t *out_ptr) { if (prec->class != CLASS_R || prec->dtype != DTYPE_FUNCTION || prec->pointer == 0 || *(unsigned short *)prec->pointer != OpcDECOMPRESS) status = MdsCopyDxXd((mdsdsc_t *)prec, out_ptr); - else { + else + { mdsdsc_a_t *pa = (mdsdsc_a_t *)prec->dscptrs[2]; int nitems = (int)pa->arsize / (int)pa->length; int bit = 0; - if (prec->dscptrs[1]) { + if (prec->dscptrs[1]) + { status = LibFindImageSymbol(prec->dscptrs[0], prec->dscptrs[1], &symbol); if (!(status & 1)) return status; - } else { + } + else + { symbol = MdsXpand; status = 1; } if (status & 1) status = MdsGet1DxA(pa, &pa->length, &pa->dtype, out_ptr); - if (status & 1) { - if (prec->dscptrs[3]->class == CLASS_CA) { + if (status & 1) + { + if (prec->dscptrs[3]->class == CLASS_CA) + { EMPTYXD(tmp_xd); status = MdsDecompress((mdsdsc_r_t *)prec->dscptrs[3], &tmp_xd); if (status & 1) status = (*symbol)(&nitems, tmp_xd.pointer, out_ptr->pointer, &bit); MdsFree1Dx(&tmp_xd, 0); - } else + } + else status = (*symbol)(&nitems, prec->dscptrs[3], out_ptr->pointer, &bit); } } diff --git a/mdsshr/MdsEvents.c b/mdsshr/MdsEvents.c index bf56bbd145..5d49be5e51 100644 --- a/mdsshr/MdsEvents.c +++ b/mdsshr/MdsEvents.c @@ -45,7 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define _GNU_SOURCE /* glibc2 needs this */ #include #include -#define MAX_ACTIVE_EVENTS \ +#define MAX_ACTIVE_EVENTS \ 2000 /* Maximum number events concurrently dealt with by processes */ #ifndef EVENT_THREAD_STACK_SIZE_MIN @@ -59,7 +59,7 @@ static int send_sockets[256]; /* Socket to send external events */ static char *receive_servers[256]; /* Receive server names */ static char *send_servers[256]; /* Send server names */ static int external_shutdown = - 0; /* flag to request remote events thread termination */ + 0; /* flag to request remote events thread termination */ static int external_count = 0; /* remote event pendings count */ static int num_receive_servers = 0; /* numer of external event sources */ static int num_send_servers = 0; /* numer of external event destination */ @@ -72,109 +72,135 @@ static int eventAstRemote(char const *eventnam, void (*astadr)(), void *astprm, int *eventid); static void initializeRemote(int receive_events); -static int ConnectToMds_(const char *const host) { +static int ConnectToMds_(const char *const host) +{ static int (*rtn)(const char *const host) = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "ConnectToMds", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(host); } + if (STATUS_OK) + { + return rtn(host); + } return -1; } -static int DisconnectFromMds_(const int id) { +static int DisconnectFromMds_(const int id) +{ static int (*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "DisconnectFromMds", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(id); } + if (STATUS_OK) + { + return rtn(id); + } return -1; } static void *GetConnectionInfo_(const int id, char **const name, - int *const readfd, size_t *const len) { + int *const readfd, size_t *const len) +{ static void *(*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "GetConnectionInfo", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(id, name, readfd, len); } + if (STATUS_OK) + { + return rtn(id, name, readfd, len); + } return 0; } static int MdsEventAst_(const int conid, char const *const eventnam, void (*const astadr)(), void *const astprm, - int *const eventid) { + int *const eventid) +{ static int (*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "MdsEventAst", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(conid, eventnam, astadr, astprm, eventid); } + if (STATUS_OK) + { + return rtn(conid, eventnam, astadr, astprm, eventid); + } return 0; } -static Message *GetMdsMsg_(const int id, const int *const stat) { +static Message *GetMdsMsg_(const int id, const int *const stat) +{ static Message *(*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "GetMdsMsg", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(id, stat); } + if (STATUS_OK) + { + return rtn(id, stat); + } return 0; } -static int MdsEventCan_(const int id, const int eid) { +static int MdsEventCan_(const int id, const int eid) +{ static int (*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "MdsEventCan", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(id, eid); } + if (STATUS_OK) + { + return rtn(id, eid); + } return 0; } static int MdsValue_(const int id, const char *const exp, struct descrip *const d1, struct descrip *const d2, - struct descrip *const d3) { + struct descrip *const d3) +{ static int (*rtn)() = 0; int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "MdsValue", (void **)&rtn) : 1; - if - STATUS_OK { return rtn(id, exp, d1, d2, d3); } + if (STATUS_OK) + { + return rtn(id, exp, d1, d2, d3); + } return 0; } #ifdef GLOBUS -static int RegisterRead_(const int conid) { +static int RegisterRead_(const int conid) +{ int status = 1; static int (*rtn)(int) = 0; if (rtn == 0) status = LibFindImageSymbol_C("MdsIpShr", "RegisterRead", (void **)&rtn); - if - STATUS_NOT_OK { - printf("%s\n", MdsGetMsg(status)); - return status; - } + if (STATUS_NOT_OK) + { + printf("%s\n", MdsGetMsg(status)); + return status; + } return rtn(conid); } #endif -static char *eventName(const char *const eventnam_in) { +static char *eventName(const char *const eventnam_in) +{ size_t i, j; char *eventnam = 0; - if (eventnam_in) { + if (eventnam_in) + { eventnam = strdup(eventnam_in); - for (i = 0, j = 0; i < strlen(eventnam); i++) { + for (i = 0, j = 0; i < strlen(eventnam); i++) + { if (eventnam[i] != 32) eventnam[j++] = (char)toupper(eventnam[i]); } eventnam[j] = 0; - if (strlen(eventnam) == 0) { + if (strlen(eventnam) == 0) + { free(eventnam); eventnam = 0; } @@ -204,17 +230,21 @@ static char *eventName(const char *const eventnam_in) { /* MDsEvent: UNIX and Win32 implementation of MDS Events */ static pthread_t external_thread; /* Thread for remote event handling */ -static void ReconnectToServer(int idx, int recv) { +static void ReconnectToServer(int idx, int recv) +{ char **servers; int *sockets; int *ids; int num_servers; - if (recv) { + if (recv) + { servers = receive_servers; sockets = receive_sockets; ids = receive_ids; num_servers = num_receive_servers; - } else { + } + else + { servers = send_servers; sockets = send_sockets; ids = send_ids; @@ -224,17 +254,20 @@ static void ReconnectToServer(int idx, int recv) { return; DisconnectFromMds_(ids[idx]); ids[idx] = ConnectToMds_(servers[idx]); - if (ids[idx] <= 0) { + if (ids[idx] <= 0) + { printf("\nError connecting to %s", servers[idx]); perror("ConnectToMds_"); sockets[idx] = 0; - } else + } + else GetConnectionInfo_(ids[idx], 0, &sockets[idx], 0); } /************* OS dependent part ******************/ -static char *getEnvironmentVar(char const *name) { +static char *getEnvironmentVar(char const *name) +{ char *trans = getenv(name); if (!trans || !*trans) return NULL; @@ -243,32 +276,39 @@ static char *getEnvironmentVar(char const *name) { static void *handleRemoteAst(void *); -static int createThread(pthread_t *thread, void *(*rtn)(void *), void *par) { +static int createThread(pthread_t *thread, void *(*rtn)(void *), void *par) +{ int s, status = 1; size_t ssize; pthread_attr_t attr; s = pthread_attr_init(&attr); - if (s != 0) { + if (s != 0) + { perror("pthread_attr_init"); return 0; } pthread_attr_getstacksize(&attr, &ssize); - if (ssize < EVENT_THREAD_STACK_SIZE_MIN) { + if (ssize < EVENT_THREAD_STACK_SIZE_MIN) + { s = pthread_attr_setstacksize(&attr, EVENT_THREAD_STACK_SIZE_MIN); - if (s != 0) { + if (s != 0) + { perror("pthread_attr_setstacksize"); return 0; } } - if (pthread_create(thread, &attr, (void *(*)(void *))rtn, par) != 0) { + if (pthread_create(thread, &attr, (void *(*)(void *))rtn, par) != 0) + { status = 0; perror("createThread:pthread_create"); } return status; } -static void startRemoteAstHandler() { - if (pipe(fds) != 0) { +static void startRemoteAstHandler() +{ + if (pipe(fds) != 0) + { fprintf(stderr, "Error creating pipes for AstHandler\n"); return; } @@ -280,13 +320,15 @@ static void startRemoteAstHandler() { static pthread_mutex_t event_info_lock = PTHREAD_MUTEX_INITIALIZER; #define EVENT_INFO_LOCK pthread_mutex_lock(&event_info_lock) #define EVENT_INFO_UNLOCK pthread_mutex_unlock(&event_info_lock) -static struct { +static struct +{ int used; int local_id; int *external_ids; } event_info[MAX_ACTIVE_EVENTS]; -static void newRemoteId(int *id) { +static void newRemoteId(int *id) +{ int i; EVENT_INFO_LOCK; for (i = 0; i < MAX_ACTIVE_EVENTS - 1 && event_info[i].used; i++) @@ -297,13 +339,15 @@ static void newRemoteId(int *id) { EVENT_INFO_UNLOCK; } -static void setRemoteId(int id, int ofs, int evid) { +static void setRemoteId(int id, int ofs, int evid) +{ EVENT_INFO_LOCK; event_info[id].external_ids[ofs] = evid; EVENT_INFO_UNLOCK; } -static int getRemoteId(int id, int ofs) { +static int getRemoteId(int id, int ofs) +{ int retId; EVENT_INFO_LOCK; retId = event_info[id].external_ids[ofs]; @@ -312,17 +356,20 @@ static int getRemoteId(int id, int ofs) { } static void getServerDefinition(char const *env_var, char **servers, - int *num_servers) { + int *num_servers) +{ unsigned int i, j; char *envname = getEnvironmentVar(env_var); char curr_name[256]; - if (!envname || !*envname) { + if (!envname || !*envname) + { *num_servers = 0; return; } i = 0; *num_servers = 0; - while (i < strlen(envname)) { + while (i < strlen(envname)) + { for (j = 0; i < strlen(envname) && envname[i] != ';'; i++, j++) curr_name[j] = envname[i]; curr_name[j] = 0; @@ -338,17 +385,20 @@ static void handleRemoteEvent(int conid); static void KillHandler() {} -static void *handleRemoteAst(void *arg __attribute__((unused))) { +static void *handleRemoteAst(void *arg __attribute__((unused))) +{ Poll(handleRemoteEvent); return NULL; } -static void handleRemoteEvent(int conid) { +static void handleRemoteEvent(int conid) +{ char buf[16]; static struct descriptor int status = 1, i; Message *m; m = GetMdsMsg_(sock, &status); - if (status == 1 && m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) { + if (status == 1 && m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) + { MdsEventInfo *event = (MdsEventInfo *)m->bytes; ((void (*)())(*event->astadr))(event->astprm, 12, event->data); } @@ -359,7 +409,8 @@ static void handleRemoteEvent(int conid) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-result" -static void KillHandler() { +static void KillHandler() +{ void *dummy; external_shutdown = 1; write(fds[1], "x", 1); @@ -370,39 +421,47 @@ static void KillHandler() { external_thread_created = 0; } -static void *handleRemoteAst(void *arg __attribute__((unused))) { +static void *handleRemoteAst(void *arg __attribute__((unused))) +{ INIT_STATUS; char buf[16]; int i; Message *m; int selectstat; fd_set readfds; - while (1) { + while (1) + { FD_ZERO(&readfds); for (i = 0; i < num_receive_servers; i++) if (receive_sockets[i]) FD_SET(receive_sockets[i], &readfds); FD_SET(fds[0], &readfds); selectstat = select(FD_SETSIZE, &readfds, 0, 0, 0); - if (selectstat == -1) { + if (selectstat == -1) + { perror("select error"); return NULL; } - if (external_shutdown) { + if (external_shutdown) + { read(fds[0], buf, 1); pthread_exit(0); } - for (i = 0; i < num_receive_servers; i++) { - if (receive_ids[i] > 0 && FD_ISSET(receive_sockets[i], &readfds)) { + for (i = 0; i < num_receive_servers; i++) + { + if (receive_ids[i] > 0 && FD_ISSET(receive_sockets[i], &readfds)) + { m = GetMdsMsg_(receive_ids[i], &status); if (STATUS_OK && - m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) { + m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) + { MdsEventInfo *event = (MdsEventInfo *)m->bytes; ((void (*)())(*event->astadr))(event->astprm, 12, event->data); } if (m) free(m); - else { + else + { fprintf(stderr, "Error reading from event server, events may be disabled\n"); receive_sockets[i] = 0; @@ -425,11 +484,13 @@ static int searchOpenServer(char *server __attribute__((unused))) } static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; -static void initializeRemote(int receive_events) { +static void initializeRemote(int receive_events) +{ static int receive_initialized; static int send_initialized; pthread_mutex_lock(&init_lock); - if (receive_events ? receive_initialized : send_initialized) { + if (receive_events ? receive_initialized : send_initialized) + { pthread_mutex_unlock(&init_lock); return; } @@ -439,52 +500,66 @@ static void initializeRemote(int receive_events) { int num_servers; int status = 1, i; - if (receive_events) { + if (receive_events) + { receive_initialized = 1; getServerDefinition("mds_event_server", servers, &num_servers); num_receive_servers = num_servers; - } else { + } + else + { send_initialized = 1; getServerDefinition("mds_event_target", servers, &num_servers); num_send_servers = num_servers; } - if (num_servers > 0) { - if - STATUS_OK { - if (external_thread_created) - KillHandler(); - for (i = 0; i < num_servers; i++) { - if (receive_events) { - receive_ids[i] = searchOpenServer(servers[i]); - if (receive_ids[i] <= 0) - receive_ids[i] = ConnectToMds_(servers[i]); - if (receive_ids[i] <= 0) { - printf("\nError connecting to %s", servers[i]); - perror("ConnectToMds_"); - receive_ids[i] = 0; - } else { + if (num_servers > 0) + { + if (STATUS_OK) + { + if (external_thread_created) + KillHandler(); + for (i = 0; i < num_servers; i++) + { + if (receive_events) + { + receive_ids[i] = searchOpenServer(servers[i]); + if (receive_ids[i] <= 0) + receive_ids[i] = ConnectToMds_(servers[i]); + if (receive_ids[i] <= 0) + { + printf("\nError connecting to %s", servers[i]); + perror("ConnectToMds_"); + receive_ids[i] = 0; + } + else + { #ifdef GLOBUS - RegisterRead_(send_sockets[i]); + RegisterRead_(send_sockets[i]); #endif - GetConnectionInfo_(receive_ids[i], 0, &receive_sockets[i], 0); - receive_servers[i] = servers[i]; - } - } else { - send_ids[i] = searchOpenServer(servers[i]); - if (send_ids[i] <= 0) - send_ids[i] = ConnectToMds_(servers[i]); - if (send_ids[i] <= 0) { - printf("\nError connecting to %s", servers[i]); - perror("ConnectToMds_"); - send_ids[i] = 0; - } else { - send_servers[i] = servers[i]; - GetConnectionInfo_(send_ids[i], 0, &send_sockets[i], 0); - } + GetConnectionInfo_(receive_ids[i], 0, &receive_sockets[i], 0); + receive_servers[i] = servers[i]; + } + } + else + { + send_ids[i] = searchOpenServer(servers[i]); + if (send_ids[i] <= 0) + send_ids[i] = ConnectToMds_(servers[i]); + if (send_ids[i] <= 0) + { + printf("\nError connecting to %s", servers[i]); + perror("ConnectToMds_"); + send_ids[i] = 0; + } + else + { + send_servers[i] = servers[i]; + GetConnectionInfo_(send_ids[i], 0, &send_sockets[i], 0); } } - startRemoteAstHandler(); } + startRemoteAstHandler(); + } else printf("%s\n", MdsGetMsg(status)); } @@ -492,44 +567,46 @@ static void initializeRemote(int receive_events) { } static int eventAstRemote(char const *eventnam, void (*astadr)(), void *astprm, - int *eventid) { + int *eventid) +{ int status = 1, i; int curr_eventid; - if - STATUS_OK { - /* if external_thread running, it must be killed before sending messages + if (STATUS_OK) + { + /* if external_thread running, it must be killed before sending messages * over socket */ - if (external_thread_created) - KillHandler(); - newRemoteId(eventid); - for (i = 0; i < num_receive_servers; i++) { - if (receive_ids[i] <= 0) - ReconnectToServer(i, 1); - if (receive_ids[i] > 0) { - status = MdsEventAst_(receive_ids[i], eventnam, astadr, astprm, - &curr_eventid); + if (external_thread_created) + KillHandler(); + newRemoteId(eventid); + for (i = 0; i < num_receive_servers; i++) + { + if (receive_ids[i] <= 0) + ReconnectToServer(i, 1); + if (receive_ids[i] > 0) + { + status = MdsEventAst_(receive_ids[i], eventnam, astadr, astprm, + &curr_eventid); #ifdef GLOBUS - if - STATUS_OK + if (STATUS_OK) RegisterRead_(receive_ids[i]); #endif - setRemoteId(*eventid, i, curr_eventid); - } + setRemoteId(*eventid, i, curr_eventid); } - /* now external thread must be created in any case */ - if - STATUS_OK { - startRemoteAstHandler(); - external_count++; - } } - if - STATUS_NOT_OK - printf("%s\n", MdsGetMsg(status)); + /* now external thread must be created in any case */ + if (STATUS_OK) + { + startRemoteAstHandler(); + external_count++; + } + } + if (STATUS_NOT_OK) + printf("%s\n", MdsGetMsg(status)); return status; } -struct wfevent_thread_cond { +struct wfevent_thread_cond +{ int active; pthread_mutex_t mutex; pthread_cond_t cond; @@ -538,10 +615,12 @@ struct wfevent_thread_cond { int *datlen; }; -static void EventHappened(void *astprm, int len, char *data) { +static void EventHappened(void *astprm, int len, char *data) +{ struct wfevent_thread_cond *t = (struct wfevent_thread_cond *)astprm; pthread_mutex_lock(&t->mutex); - if (t->active) { + if (t->active) + { if (t->buflen && t->data) memcpy(t->data, data, (size_t)((t->buflen > len) ? len : t->buflen)); if (t->datlen) @@ -553,7 +632,8 @@ static void EventHappened(void *astprm, int len, char *data) { static int TIMEOUT = 0; -EXPORT int MDSSetEventTimeout(const int seconds) { +EXPORT int MDSSetEventTimeout(const int seconds) +{ int old_timeout; pthread_mutex_lock(&init_lock); old_timeout = TIMEOUT; @@ -562,7 +642,8 @@ EXPORT int MDSSetEventTimeout(const int seconds) { return old_timeout; } -EXPORT int MDSWfevent(char const *evname, int buflen, char *data, int *datlen) { +EXPORT int MDSWfevent(char const *evname, int buflen, char *data, int *datlen) +{ int timeout; pthread_mutex_lock(&init_lock); timeout = TIMEOUT; @@ -571,7 +652,8 @@ EXPORT int MDSWfevent(char const *evname, int buflen, char *data, int *datlen) { } EXPORT int MDSWfeventTimed(char const *evname, int buflen, char *data, - int *datlen, int timeout) { + int *datlen, int timeout) +{ int eventid = -1; int status; struct wfevent_thread_cond t = {0}; @@ -583,7 +665,8 @@ EXPORT int MDSWfeventTimed(char const *evname, int buflen, char *data, t.datlen = datlen; MDSEventAst(evname, EventHappened, &t, &eventid); pthread_mutex_lock(&t.mutex); - if (timeout > 0) { + if (timeout > 0) + { static struct timespec abstime; #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_REALTIME, &abstime); @@ -593,7 +676,9 @@ EXPORT int MDSWfeventTimed(char const *evname, int buflen, char *data, #endif abstime.tv_sec += timeout; status = pthread_cond_timedwait(&t.cond, &t.mutex, &abstime); - } else { + } + else + { status = pthread_cond_wait(&t.cond, &t.mutex); } pthread_mutex_unlock(&t.mutex); @@ -607,16 +692,18 @@ EXPORT int MDSWfeventTimed(char const *evname, int buflen, char *data, } static pthread_mutex_t event_queue_lock = PTHREAD_MUTEX_INITIALIZER; -#define EVENT_QUEUE_LOCK \ - pthread_mutex_lock(&event_queue_lock); \ +#define EVENT_QUEUE_LOCK \ + pthread_mutex_lock(&event_queue_lock); \ pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&event_queue_lock) #define EVENT_QUEUE_UNLOCK pthread_cleanup_pop(1) -struct eventQueue { +struct eventQueue +{ int data_len; char *data; struct eventQueue *next; }; -struct eventQueueHeader { +struct eventQueueHeader +{ int eventid; pthread_mutex_t mutex; pthread_cond_t cond; @@ -624,23 +711,30 @@ struct eventQueueHeader { struct eventQueueHeader *next; } *QueuedEvents = 0; -static void CancelEventQueue(int eventid) { +static void CancelEventQueue(int eventid) +{ struct eventQueueHeader *qh, *qh_p; struct eventQueue *q; EVENT_QUEUE_LOCK; for (qh = QueuedEvents, qh_p = 0; qh && qh->eventid != eventid; qh_p = qh, qh = qh->next) ; - if (qh) { - if (qh_p) { + if (qh) + { + if (qh_p) + { qh_p->next = qh->next; - } else { + } + else + { QueuedEvents = qh->next; } - for (q = qh->event; q;) { + for (q = qh->event; q;) + { struct eventQueue *this = q; q = q->next; - if (this->data_len > 0 && this->data) { + if (this->data_len > 0 && this->data) + { free(this->data); } free(this); @@ -656,7 +750,8 @@ static void CancelEventQueue(int eventid) { } static void MDSEventQueue_ast(void *const qh_in, const int data_len, - char *const data) { + char *const data) +{ EVENT_QUEUE_LOCK; struct eventQueueHeader *qh = (struct eventQueueHeader *)qh_in; struct eventQueue *q; @@ -678,28 +773,33 @@ static void MDSEventQueue_ast(void *const qh_in, const int data_len, EVENT_QUEUE_UNLOCK; } -EXPORT int MDSQueueEvent(const char *const evname, int *const eventid) { +EXPORT int MDSQueueEvent(const char *const evname, int *const eventid) +{ int status; EVENT_QUEUE_LOCK; struct eventQueueHeader *thisEventH = malloc(sizeof(struct eventQueueHeader)); status = MDSEventAst(evname, MDSEventQueue_ast, (void *)thisEventH, eventid); - if - STATUS_OK { - struct eventQueueHeader *qh; - thisEventH->eventid = *eventid; - thisEventH->event = 0; - thisEventH->next = 0; - pthread_mutex_init(&thisEventH->mutex, NULL); - pthread_cond_init(&thisEventH->cond, NULL); - for (qh = QueuedEvents; qh && qh->next; qh = qh->next) - ; - if (qh) { - qh->next = thisEventH; - } else { - QueuedEvents = thisEventH; - } + if (STATUS_OK) + { + struct eventQueueHeader *qh; + thisEventH->eventid = *eventid; + thisEventH->event = 0; + thisEventH->next = 0; + pthread_mutex_init(&thisEventH->mutex, NULL); + pthread_cond_init(&thisEventH->cond, NULL); + for (qh = QueuedEvents; qh && qh->next; qh = qh->next) + ; + if (qh) + { + qh->next = thisEventH; } - else { + else + { + QueuedEvents = thisEventH; + } + } + else + { free(thisEventH); } EVENT_QUEUE_UNLOCK; @@ -707,7 +807,8 @@ EXPORT int MDSQueueEvent(const char *const evname, int *const eventid) { } EXPORT int MDSGetEventQueue(const int eventid, const int timeout, - int *const data_len, char **const data) { + int *const data_len, char **const data) +{ int state, unlock; pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&event_queue_lock); unlock = FALSE; @@ -719,19 +820,25 @@ EXPORT int MDSGetEventQueue(const int eventid, const int timeout, unlock = TRUE; for (qh = QueuedEvents; qh && qh->eventid != eventid; qh = qh->next) ; - if (qh) { - if (qh->event) { + if (qh) + { + if (qh->event) + { struct eventQueue *this = qh->event; *data = this->data; *data_len = this->data_len; qh->event = this->next; free(this); - } else { - if (!waited && timeout >= 0) { + } + else + { + if (!waited && timeout >= 0) + { pthread_mutex_lock(&qh->mutex); pthread_mutex_unlock(&event_queue_lock); unlock = FALSE; - if (timeout > 0) { + if (timeout > 0) + { static struct timespec abstime; #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_REALTIME, &abstime); @@ -741,35 +848,45 @@ EXPORT int MDSGetEventQueue(const int eventid, const int timeout, #endif abstime.tv_sec += timeout; state = pthread_cond_timedwait(&qh->cond, &qh->mutex, &abstime) == 0; - } else { + } + else + { state = pthread_cond_wait(&qh->cond, &qh->mutex) == 0; } pthread_mutex_unlock(&qh->mutex); - if (state) { + if (state) + { waited = TRUE; goto retry; - } else { + } + else + { *data_len = 0; *data = NULL; } - } else { + } + else + { *data_len = 0; *data = NULL; state = 0; } } - } else + } + else state = 2; pthread_cleanup_pop(unlock); return state; } int RemoteMDSEventAst(const char *const eventnam_in, void (*const astadr)(), - void *const astprm, int *const eventid) { + void *const astprm, int *const eventid) +{ int status = 0; char *eventnam = eventName(eventnam_in); *eventid = -1; - if (eventnam) { + if (eventnam) + { initializeRemote(1); status = eventAstRemote(eventnam, astadr, astprm, eventid); free(eventnam); @@ -777,22 +894,25 @@ int RemoteMDSEventAst(const char *const eventnam_in, void (*const astadr)(), return status; } -static int canEventRemote(const int eventid) { +static int canEventRemote(const int eventid) +{ int status = 1, i; /* kill external thread before sending messages over the socket */ - if - STATUS_OK { - KillHandler(); - for (i = 0; i < num_receive_servers; i++) { - if (receive_ids[i] > 0) - status = MdsEventCan_(receive_ids[i], getRemoteId(eventid, i)); - } - startRemoteAstHandler(); + if (STATUS_OK) + { + KillHandler(); + for (i = 0; i < num_receive_servers; i++) + { + if (receive_ids[i] > 0) + status = MdsEventCan_(receive_ids[i], getRemoteId(eventid, i)); } + startRemoteAstHandler(); + } return status; } -int RemoteMDSEventCan(const int eventid) { +int RemoteMDSEventCan(const int eventid) +{ if (eventid < 0) return 0; @@ -801,7 +921,8 @@ int RemoteMDSEventCan(const int eventid) { } static int sendRemoteEvent(const char *const evname, const int data_len, - char *const data) { + char *const data) +{ int status = 1, i, tmp_status; char expression[256]; struct descrip ansarg; @@ -821,44 +942,50 @@ static int sendRemoteEvent(const char *const evname, const int data_len, desc.dims[0] = data_len; ansarg.ptr = 0; sprintf(expression, "setevent(\"%s\"%s)", evname, data_len > 0 ? ",$" : ""); - if - STATUS_OK { - int reconnects = 0; - tmp_status = 0; - for (i = 0; i < num_send_servers; i++) { - if (send_ids[i] > 0) { - if (data_len > 0) - tmp_status = - MdsValue_(send_ids[i], expression, &desc, &ansarg, NULL); - else - tmp_status = - MdsValue_(send_ids[i], expression, &ansarg, NULL, NULL); - } - if (tmp_status & 1) - tmp_status = (ansarg.ptr != NULL) ? *(int *)ansarg.ptr : 0; - if (!(tmp_status & 1)) { - status = tmp_status; - if (reconnects < 3) { - ReconnectToServer(i, 0); - reconnects++; - i--; - } + if (STATUS_OK) + { + int reconnects = 0; + tmp_status = 0; + for (i = 0; i < num_send_servers; i++) + { + if (send_ids[i] > 0) + { + if (data_len > 0) + tmp_status = + MdsValue_(send_ids[i], expression, &desc, &ansarg, NULL); + else + tmp_status = + MdsValue_(send_ids[i], expression, &ansarg, NULL, NULL); + } + if (tmp_status & 1) + tmp_status = (ansarg.ptr != NULL) ? *(int *)ansarg.ptr : 0; + if (!(tmp_status & 1)) + { + status = tmp_status; + if (reconnects < 3) + { + ReconnectToServer(i, 0); + reconnects++; + i--; } - free(ansarg.ptr); } + free(ansarg.ptr); } + } return status; } int RemoteMDSEvent(const char *const evname_in, const int data_len, - char *const data) { + char *const data) +{ int j; unsigned int u; char *evname; int status = 1; initializeRemote(0); evname = strdup(evname_in); - for (u = 0, j = 0; u < strlen(evname); u++) { + for (u = 0, j = 0; u < strlen(evname); u++) + { if (evname[u] != 32) evname[j++] = (char)toupper(evname[u]); } @@ -872,11 +999,13 @@ int RemoteMDSEvent(const char *const evname_in, const int data_len, EXPORT int MDSEventAst(const char *const eventNameIn, void (*const astadr)(void *, int, char *), - void *const astprm, int *const eventid) { + void *const astprm, int *const eventid) +{ char *eventName = malloc(strlen(eventNameIn) + 1); unsigned int i, j; int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) { + for (i = 0, j = 0; i < strlen(eventNameIn); i++) + { if (eventNameIn[i] != 32) eventName[j++] = (char)toupper(eventNameIn[i]); } @@ -889,14 +1018,15 @@ EXPORT int MDSEventAst(const char *const eventNameIn, return status; } - EXPORT int MDSEventAstMask(const char *const eventNameIn, - void (*const astadr)(void *, int, char *), - void *const astprm, int *const eventid, unsigned int cpuMask) { + void (*const astadr)(void *, int, char *), + void *const astprm, int *const eventid, unsigned int cpuMask) +{ char *eventName = malloc(strlen(eventNameIn) + 1); unsigned int i, j; int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) { + for (i = 0, j = 0; i < strlen(eventNameIn); i++) + { if (eventNameIn[i] != 32) eventName[j++] = (char)toupper(eventNameIn[i]); } @@ -910,11 +1040,13 @@ EXPORT int MDSEventAstMask(const char *const eventNameIn, } EXPORT int MDSEvent(const char *const eventNameIn, const int bufLen, - char *const buf) { + char *const buf) +{ char *eventName = alloca(strlen(eventNameIn) + 1); unsigned int i, j; int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) { + for (i = 0, j = 0; i < strlen(eventNameIn); i++) + { if (eventNameIn[i] != 32) eventName[j++] = (char)toupper(eventNameIn[i]); } @@ -926,7 +1058,8 @@ EXPORT int MDSEvent(const char *const eventNameIn, const int bufLen, return status; } -EXPORT int MDSEventCan(const int id) { +EXPORT int MDSEventCan(const int id) +{ int status; if (getenv("mds_event_server")) status = RemoteMDSEventCan(id); diff --git a/mdsshr/MdsGet1DxA.c b/mdsshr/MdsGet1DxA.c index 2179ac532e..407ce78071 100644 --- a/mdsshr/MdsGet1DxA.c +++ b/mdsshr/MdsGet1DxA.c @@ -74,7 +74,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -static inline l_length_t align(l_length_t bytes, l_length_t size) { +static inline l_length_t align(l_length_t bytes, l_length_t size) +{ if (size == 0) return bytes; return ((bytes + size - 1) / size) * size; @@ -83,7 +84,8 @@ static inline l_length_t align(l_length_t bytes, l_length_t size) { EXPORT int MdsGet1DxA(const mdsdsc_a_t *const in_ptr, const length_t *const length_ptr, const dtype_t *const dtype_ptr, - mdsdsc_xd_t *const out_xd) { + mdsdsc_xd_t *const out_xd) +{ array_coeff *in_dsc = (array_coeff *)in_ptr; l_length_t new_arsize; l_length_t dsc_size; @@ -107,45 +109,51 @@ EXPORT int MdsGet1DxA(const mdsdsc_a_t *const in_ptr, dsc_size = align(dsc_size, align_size); new_size = dsc_size + new_arsize; status = MdsGet1Dx(&new_size, &dsc_dtype, out_xd, NULL); - if - STATUS_OK { - out_dsc = (array_coeff *)out_xd->pointer; - *(mdsdsc_a_t *)out_dsc = *(mdsdsc_a_t *)in_dsc; - out_dsc->length = *length_ptr; - out_dsc->dtype = *dtype_ptr; - out_dsc->pointer = (char *)out_dsc + align(dsc_size, align_size); - out_dsc->arsize = new_arsize; - if (out_dsc->aflags.coeff || (new_arsize == 0 && in_dsc->pointer)) { - if (!in_dsc->aflags.coeff) { // new_arsize==0; in_dsc->a0 invalid - out_dsc->aflags.coeff = 1; - out_dsc->a0 = out_dsc->pointer; - out_dsc->dimct = 0; - } else { - int64_t offset; - if (out_dsc->class == CLASS_CA) - offset = ((int64_t)out_dsc->length) * - ((int64_t)(intptr_t)in_dsc->a0 / - ((int64_t)(in_dsc->length > 0 ? in_dsc->length : 1))); - else - offset = ((int64_t)out_dsc->length) * - ((in_dsc->a0 - in_dsc->pointer) / - ((int64_t)(in_dsc->length > 0 ? in_dsc->length : 1))); - out_dsc->a0 = out_dsc->pointer + offset; - } + if (STATUS_OK) + { + out_dsc = (array_coeff *)out_xd->pointer; + *(mdsdsc_a_t *)out_dsc = *(mdsdsc_a_t *)in_dsc; + out_dsc->length = *length_ptr; + out_dsc->dtype = *dtype_ptr; + out_dsc->pointer = (char *)out_dsc + align(dsc_size, align_size); + out_dsc->arsize = new_arsize; + if (out_dsc->aflags.coeff || (new_arsize == 0 && in_dsc->pointer)) + { + if (!in_dsc->aflags.coeff) + { // new_arsize==0; in_dsc->a0 invalid + out_dsc->aflags.coeff = 1; + out_dsc->a0 = out_dsc->pointer; + out_dsc->dimct = 0; + } + else + { + int64_t offset; + if (out_dsc->class == CLASS_CA) + offset = ((int64_t)out_dsc->length) * + ((int64_t)(intptr_t)in_dsc->a0 / + ((int64_t)(in_dsc->length > 0 ? in_dsc->length : 1))); + else + offset = ((int64_t)out_dsc->length) * + ((in_dsc->a0 - in_dsc->pointer) / + ((int64_t)(in_dsc->length > 0 ? in_dsc->length : 1))); + out_dsc->a0 = out_dsc->pointer + offset; + } + for (i = 0; i < out_dsc->dimct; i++) + out_dsc->m[i] = in_dsc->m[i]; + if (new_arsize == 0 && out_dsc->dimct == 0) + { + out_dsc->dimct = 1; + out_dsc->m[0] = in_dsc->arsize; + } + if (in_dsc->aflags.bounds) + { + bound_t *new_bound_ptr = (bound_t *)&out_dsc->m[out_dsc->dimct]; + bound_t *a_bound_ptr = (bound_t *)&in_dsc->m[in_dsc->dimct]; for (i = 0; i < out_dsc->dimct; i++) - out_dsc->m[i] = in_dsc->m[i]; - if (new_arsize == 0 && out_dsc->dimct == 0) { - out_dsc->dimct = 1; - out_dsc->m[0] = in_dsc->arsize; - } - if (in_dsc->aflags.bounds) { - bound_t *new_bound_ptr = (bound_t *)&out_dsc->m[out_dsc->dimct]; - bound_t *a_bound_ptr = (bound_t *)&in_dsc->m[in_dsc->dimct]; - for (i = 0; i < out_dsc->dimct; i++) - new_bound_ptr[i] = a_bound_ptr[i]; - } + new_bound_ptr[i] = a_bound_ptr[i]; } - out_dsc->class = CLASS_A; } + out_dsc->class = CLASS_A; + } return status; } diff --git a/mdsshr/MdsGet1DxS.c b/mdsshr/MdsGet1DxS.c index 72f766cc0e..dde94ee8d8 100644 --- a/mdsshr/MdsGet1DxS.c +++ b/mdsshr/MdsGet1DxS.c @@ -73,7 +73,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EXPORT int MdsGet1DxS(const length_t *const length_ptr, const dtype_t *const dtype_ptr, - mdsdsc_xd_t *const out_dsc_ptr) { + mdsdsc_xd_t *const out_dsc_ptr) +{ int status; uint32_t dsc_size = (uint32_t)sizeof(mdsdsc_t); uint32_t align_size = (*dtype_ptr == DTYPE_T) ? 1 : *length_ptr; @@ -82,12 +83,12 @@ EXPORT int MdsGet1DxS(const length_t *const length_ptr, dsc_size = align(dsc_size, align_size); length = dsc_size + *length_ptr; status = MdsGet1Dx(&length, &dsc_dtype, out_dsc_ptr, NULL); - if - STATUS_OK { - out_dsc_ptr->pointer->length = *length_ptr; - out_dsc_ptr->pointer->dtype = *dtype_ptr; - out_dsc_ptr->pointer->class = CLASS_S; - out_dsc_ptr->pointer->pointer = (char *)out_dsc_ptr->pointer + dsc_size; - } + if (STATUS_OK) + { + out_dsc_ptr->pointer->length = *length_ptr; + out_dsc_ptr->pointer->dtype = *dtype_ptr; + out_dsc_ptr->pointer->class = CLASS_S; + out_dsc_ptr->pointer->pointer = (char *)out_dsc_ptr->pointer + dsc_size; + } return status; } diff --git a/mdsshr/MdsGetSetShotId.c b/mdsshr/MdsGetSetShotId.c index f42cb6ebe7..5386c08fd8 100644 --- a/mdsshr/MdsGetSetShotId.c +++ b/mdsshr/MdsGetSetShotId.c @@ -50,13 +50,15 @@ int MdsGetCurrentShotId(experiment,shot) #include #include -int MdsGetCurrentShotId() { +int MdsGetCurrentShotId() +{ printf( "MdsGetCurrentShotId is obsolete, use TreeGetCurrentShotId in TreeShr\n"); return 0; } -int MdsSetCurrentShotId() { +int MdsSetCurrentShotId() +{ printf( "MdsSetCurrentShotId is obsolete, use TreeSetCurrentShotId in TreeShr\n"); return 0; diff --git a/mdsshr/MdsPk.c b/mdsshr/MdsPk.c index 67f15ae9c1..6853e7c2c6 100644 --- a/mdsshr/MdsPk.c +++ b/mdsshr/MdsPk.c @@ -56,18 +56,46 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include STATIC_CONSTANT unsigned int masks[33] = { - 0, 0x1, 0x3, 0x7, 0xf, 0x1f, - 0x3f, 0x7f, 0xff, 0x1ff, 0x3ff, 0x7ff, - 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff, - 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, - 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff, - 0x3fffffff, 0x7fffffff, 0xffffffff, + 0, + 0x1, + 0x3, + 0x7, + 0xf, + 0x1f, + 0x3f, + 0x7f, + 0xff, + 0x1ff, + 0x3ff, + 0x7ff, + 0xfff, + 0x1fff, + 0x3fff, + 0x7fff, + 0xffff, + 0x1ffff, + 0x3ffff, + 0x7ffff, + 0xfffff, + 0x1fffff, + 0x3fffff, + 0x7fffff, + 0xffffff, + 0x1ffffff, + 0x3ffffff, + 0x7ffffff, + 0xfffffff, + 0x1fffffff, + 0x3fffffff, + 0x7fffffff, + 0xffffffff, }; #include #include -STATIC_ROUTINE int SwapBytes(char *in_c) { +STATIC_ROUTINE int SwapBytes(char *in_c) +{ int out; char *out_c = (char *)&out; int i; @@ -84,7 +112,8 @@ STATIC_ROUTINE int SwapBytes(char *in_c) { #define getppack SwapBytes((char *)ppack) void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], - int *bit_ptr) { + int *bit_ptr) +{ int nbits = *nbits_ptr; int nitems = *nitems_ptr; int *ppack = &pack[*bit_ptr >> 5]; @@ -98,7 +127,8 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], signed char *pin; signed char *pout; unsigned int hold = 0; - if (off) { + if (off) + { for (i = 0; i < 4; i++) ((char *)&hold)[i] = ((char *)ppack)[3 - i]; hold = hold & masks[off]; @@ -109,8 +139,10 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], if (size == 0 || nitems <= 0) return; *bit_ptr += size * nitems; - if (size == 32) { - if ((off & 7) == 0) { + if (size == 32) + { + if ((off & 7) == 0) + { #ifdef WORDS_BIGENDIAN for (i = 0, pout = ((signed char *)ppack) + (off >> 3), pin = (signed char *)pitems; @@ -122,8 +154,10 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], sizeof(int) * (size_t)nitems); #endif return; - } else - for (; --nitems >= 0;) { + } + else + for (; --nitems >= 0;) + { hold |= *(unsigned int *)pitems << off; #ifdef __APPLE__ *ppack++ = SwapBytes((char *)&hold); @@ -138,12 +172,16 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], #endif hold = *(unsigned int *)pitems++ >> (32 - off); } - } else { + } + else + { mask = masks[size]; test = 32 - size; - for (; --nitems >= 0; ++pitems) { + for (; --nitems >= 0; ++pitems) + { hold |= (mask & *(unsigned int *)pitems) << off; - if (off >= test) { + if (off >= test) + { #ifdef __APPLE__ *ppack++ = SwapBytes((char *)&hold); #else @@ -157,7 +195,8 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], #endif hold = (mask & *(unsigned int *)pitems) >> (32 - off); off -= test; - } else + } + else off += size; } } @@ -173,7 +212,8 @@ void MdsPk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], /*-------------------------------------------------------------*/ void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], - int *bit_ptr) { + int *bit_ptr) +{ int nbits = *nbits_ptr; int nitems = *nitems_ptr; int *ppack = &pack[*bit_ptr >> 5]; @@ -185,14 +225,18 @@ void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], *bit_ptr += size * nitems; /*32-bit data*/ - if (test == 0) { - if ((off & 7) == 0) { + if (test == 0) + { + if ((off & 7) == 0) + { int i; ppack = (int *)(((char *)ppack) + (off >> 3)); for (i = 0; i < nitems; i++, ppack++) pitems[i] = getppack; - } else - for (; --nitems >= 0;) { + } + else + for (; --nitems >= 0;) + { hold = ((unsigned int)getppack) >> off; ppack++; hold |= ((unsigned int)getppack) << (32 - off); @@ -200,11 +244,14 @@ void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], } } /*sign extended*/ - else if (nbits < 0) { + else if (nbits < 0) + { full = mask + 1; max = mask >> 1; - for (; --nitems >= 0;) { - if (off >= test) { + for (; --nitems >= 0;) + { + if (off >= test) + { hold = ((unsigned int)getppack) >> off; ppack++; hold |= (((unsigned int)getppack) << (32 - off)) & mask; @@ -213,7 +260,9 @@ void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], else *pitems++ = (int)hold; off -= test; - } else { + } + else + { hold = (((unsigned int)getppack) >> off) & mask; if (hold > max) *pitems++ = (int)(hold - full); @@ -225,14 +274,18 @@ void MdsUnpk(signed char *nbits_ptr, int *nitems_ptr, int pack[], int items[], } /*zero extended*/ else if (nbits > 0) - for (; --nitems >= 0;) { - if (off >= test) { + for (; --nitems >= 0;) + { + if (off >= test) + { hold = ((unsigned int)getppack) >> off; ppack++; hold |= (((unsigned int)getppack) << (32 - off)) & mask; *pitems++ = (int)hold; off -= test; - } else { + } + else + { hold = (((unsigned int)getppack) >> off) & mask; *pitems++ = (int)hold; off += size; diff --git a/mdsshr/MdsSandbox.c b/mdsshr/MdsSandbox.c index 735e73fae0..5f0821d795 100644 --- a/mdsshr/MdsSandbox.c +++ b/mdsshr/MdsSandbox.c @@ -1,6 +1,7 @@ #include static int sandbox = 0; -EXPORT void MdsEnableSandbox() { +EXPORT void MdsEnableSandbox() +{ /*** enable sandbox flag to disable potentially harmful functions such as spawn and py() which could be executed by tdi expressions providing shell access to remote users. ***/ diff --git a/mdsshr/MdsSerialize.c b/mdsshr/MdsSerialize.c index c39bd88eeb..c986a10450 100644 --- a/mdsshr/MdsSerialize.c +++ b/mdsshr/MdsSerialize.c @@ -50,51 +50,51 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define set_a0(ans) swap(int, &in_ptr[16], ans) #define m() (&in_ptr[20]) #define LoadChar(in, outp) (outp)[0] = ((char *)&in)[0] -#define FixLength(a) \ - if (a.length == 0) \ +#define FixLength(a) \ + if (a.length == 0) \ MdsFixDscLength((mdsdsc_t *)&a) void MdsFixDscLength(mdsdsc_t *in); #ifdef WORDS_BIGENDIAN -#define LoadShort(in, outp) \ - (outp)[0] = ((char *)&in)[1]; \ +#define LoadShort(in, outp) \ + (outp)[0] = ((char *)&in)[1]; \ (outp)[1] = ((char *)&in)[0] -#define LoadInt(in, outp) \ - (outp)[0] = ((char *)&in)[3]; \ - (outp)[1] = ((char *)&in)[2]; \ - (outp)[2] = ((char *)&in)[1]; \ +#define LoadInt(in, outp) \ + (outp)[0] = ((char *)&in)[3]; \ + (outp)[1] = ((char *)&in)[2]; \ + (outp)[2] = ((char *)&in)[1]; \ (outp)[3] = ((char *)&in)[0] -#define LoadQuad(in, outp) \ - (outp)[0] = ((char *)&in)[7]; \ - (outp)[1] = ((char *)&in)[6]; \ - (outp)[2] = ((char *)&in)[5]; \ - (outp)[3] = ((char *)&in)[4]; \ - (outp)[4] = ((char *)&in)[3]; \ - (outp)[5] = ((char *)&in)[2]; \ - (outp)[6] = ((char *)&in)[1]; \ +#define LoadQuad(in, outp) \ + (outp)[0] = ((char *)&in)[7]; \ + (outp)[1] = ((char *)&in)[6]; \ + (outp)[2] = ((char *)&in)[5]; \ + (outp)[3] = ((char *)&in)[4]; \ + (outp)[4] = ((char *)&in)[3]; \ + (outp)[5] = ((char *)&in)[2]; \ + (outp)[6] = ((char *)&in)[1]; \ (outp)[7] = ((char *)&in)[0] #else -#define LoadShort(in, outp) \ - (outp)[0] = ((char *)&in)[0]; \ +#define LoadShort(in, outp) \ + (outp)[0] = ((char *)&in)[0]; \ (outp)[1] = ((char *)&in)[1] -#define LoadInt(in, outp) \ - (outp)[0] = ((char *)&in)[0]; \ - (outp)[1] = ((char *)&in)[1]; \ - (outp)[2] = ((char *)&in)[2]; \ +#define LoadInt(in, outp) \ + (outp)[0] = ((char *)&in)[0]; \ + (outp)[1] = ((char *)&in)[1]; \ + (outp)[2] = ((char *)&in)[2]; \ (outp)[3] = ((char *)&in)[3] -#define LoadQuad(in, outp) \ - (outp)[0] = ((char *)&in)[0]; \ - (outp)[1] = ((char *)&in)[1]; \ - (outp)[2] = ((char *)&in)[2]; \ - (outp)[3] = ((char *)&in)[3]; \ - (outp)[4] = ((char *)&in)[4]; \ - (outp)[5] = ((char *)&in)[5]; \ - (outp)[6] = ((char *)&in)[6]; \ +#define LoadQuad(in, outp) \ + (outp)[0] = ((char *)&in)[0]; \ + (outp)[1] = ((char *)&in)[1]; \ + (outp)[2] = ((char *)&in)[2]; \ + (outp)[3] = ((char *)&in)[3]; \ + (outp)[4] = ((char *)&in)[4]; \ + (outp)[5] = ((char *)&in)[5]; \ + (outp)[6] = ((char *)&in)[6]; \ (outp)[7] = ((char *)&in)[7] #endif -#define set_aflags(ptr, in) \ - ptr[10] = (char)((inp->aflags.binscale << 3) | (inp->aflags.redim << 4) | \ - (inp->aflags.column << 5) | (inp->aflags.coeff << 6) | \ +#define set_aflags(ptr, in) \ + ptr[10] = (char)((inp->aflags.binscale << 3) | (inp->aflags.redim << 4) | \ + (inp->aflags.column << 5) | (inp->aflags.coeff << 6) | \ (inp->aflags.bounds << 7)) #define offset(ptr) *(uint32_t *)&ptr @@ -107,52 +107,59 @@ union __bswap { #if defined(WORDS_BIGENDIAN) -#define swap(dtype, ptr, ans) \ - { \ - char const *p = ptr; \ - union __bswap bswap; \ - uint32_t __i; \ - for (__i = 0; __i < sizeof(dtype); __i++) \ - bswap.b[sizeof(dtype) - __i - 1] = p[__i]; \ - ans = bswap.dtype##_; \ +#define swap(dtype, ptr, ans) \ + { \ + char const *p = ptr; \ + union __bswap bswap; \ + uint32_t __i; \ + for (__i = 0; __i < sizeof(dtype); __i++) \ + bswap.b[sizeof(dtype) - __i - 1] = p[__i]; \ + ans = bswap.dtype##_; \ } #else -#define swap(dtype, ptr, ans) \ - { \ - char const *p = ptr; \ - union __bswap bswap; \ - uint32_t __i; \ - for (__i = 0; __i < sizeof(dtype); __i++) \ - bswap.b[__i] = p[__i]; \ - ans = bswap.dtype##_; \ +#define swap(dtype, ptr, ans) \ + { \ + char const *p = ptr; \ + union __bswap bswap; \ + uint32_t __i; \ + for (__i = 0; __i < sizeof(dtype); __i++) \ + bswap.b[__i] = p[__i]; \ + ans = bswap.dtype##_; \ } #endif STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, - l_length_t *b_out, l_length_t *b_in) { + l_length_t *b_out, l_length_t *b_in) +{ int status = 1; uint32_t bytes_out = 0, bytes_in = 0, i, j, size_out, size_in; - if (in_ptr && (in_ptr[0] || in_ptr[1] || in_ptr[2] || in_ptr[3])) { - switch (class()) { + if (in_ptr && (in_ptr[0] || in_ptr[1] || in_ptr[2] || in_ptr[3])) + { + switch (class()) + { case CLASS_S: - case CLASS_D: { + case CLASS_D: + { mdsdsc_t in = {0}; mdsdsc_t *po = (mdsdsc_t *)out_dsc_ptr; set_length(in.length); in.dtype = dtype(); FixLength(in); in.class = CLASS_S; - if (po) { + if (po) + { *po = in; po->pointer = (void *)(po + 1); memcpy(po->pointer, in_ptr + 8, in.length); #if defined(WORDS_BIGENDIAN) if (po->length > 1 && po->dtype != DTYPE_T && - po->dtype != DTYPE_IDENT && po->dtype != DTYPE_PATH) { - switch (po->length) { + po->dtype != DTYPE_IDENT && po->dtype != DTYPE_PATH) + { + switch (po->length) + { case 2: swap(int16_t, po->pointer, *(int16_t *)po->pointer); break; @@ -168,17 +175,20 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, } bytes_out = (uint32_t)align(sizeof(mdsdsc_t) + in.length, sizeof(void *)); bytes_in = 8u + in.length; - } break; + } + break; case CLASS_XS: - case CLASS_XD: { + case CLASS_XD: + { mdsdsc_xs_t in = {0}; mdsdsc_xs_t *po = (mdsdsc_xs_t *)out_dsc_ptr; in.length = 0; in.dtype = dtype(); in.class = CLASS_XS; set_l_length(in.l_length); - if (po) { + if (po) + { *po = in; po->pointer = (mdsdsc_t *)(po + 1); memcpy(po->pointer, in_ptr + 12, in.l_length); @@ -186,9 +196,11 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, bytes_out = (uint32_t)align(sizeof(mdsdsc_xs_t) + in.l_length, sizeof(void *)); bytes_in = 12u + in.l_length; - } break; + } + break; - case CLASS_R: { + case CLASS_R: + { mdsdsc_r_t pi_tmp = {0}; mdsdsc_r_t *pi = &pi_tmp; mdsdsc_r_t *po = (mdsdsc_r_t *)out_dsc_ptr; @@ -201,15 +213,18 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, bytes_out = (uint32_t)sizeof(mdsdsc_r_t) + (pi->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *); bytes_in = 12u + pi->ndesc * 4u; - if (po) { + if (po) + { memset(po, 0, bytes_out); *po = *pi; - if (pi->length > 0) { + if (pi->length > 0) + { po->pointer = (unsigned char *)po + bytes_out; memcpy(po->pointer, &in_ptr[12 + pi->ndesc * 4], pi->length); #if defined(WORDS_BIGENDIAN) - if (po->dtype == DTYPE_FUNCTION && po->length == 2) { + if (po->dtype == DTYPE_FUNCTION && po->length == 2) + { swap(short, (char *)po->pointer, *(short *)po->pointer); } #endif @@ -221,10 +236,12 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, /****************************** Each descriptor must be copied. ******************************/ - for (j = 0; j < pi->ndesc && STATUS_OK; ++j) { + for (j = 0; j < pi->ndesc && STATUS_OK; ++j) + { uint32_t offset; set_dscptrs(offset, j); - if (offset) { + if (offset) + { status = copy_rec_dx(in_ptr + bytes_in, po ? (mdsdsc_xd_t *)((char *)po + bytes_out) : 0, &size_out, &size_in); @@ -235,8 +252,10 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, bytes_in += size_in; } } - } break; - case CLASS_A: { + } + break; + case CLASS_A: + { uint32_t dsc_size, align_size; array_coeff a_tmp = {0}; array_coeff *pi = &a_tmp; @@ -268,12 +287,16 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); align_size = (pi->dtype == DTYPE_T) ? 1 : pi->length; bytes_out = dsc_size + pi->arsize + align_size; - if (po) { + if (po) + { memcpy(po, pi, sizeof(mdsdsc_a_t)); - for (i = 0; i < pi->dimct; i++) { - if (pi->aflags.coeff) { + for (i = 0; i < pi->dimct; i++) + { + if (pi->aflags.coeff) + { swap(int, m() + sizeof(int) * i, po->m[i]); - if (pi->aflags.bounds) { + if (pi->aflags.bounds) + { swap(int, m() + (pi->dimct + 2 * i) * sizeof(int), po->m[pi->dimct + 2 * i]); swap(int, m() + (pi->dimct + 2 * i + 1) * sizeof(int), @@ -283,7 +306,8 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, } po->pointer = (void *)align((intptr_t)po + dsc_size, align_size); memcpy(po->pointer, &in_ptr[bytes_in], pi->arsize); - if (pi->aflags.coeff) { + if (pi->aflags.coeff) + { uint32_t offset, a0; set_offset(offset); set_a0(a0); @@ -291,39 +315,49 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, } #if defined(WORDS_BIGENDIAN) if (po->dtype != DTYPE_T && po->dtype != DTYPE_IDENT && - po->dtype != DTYPE_PATH) { + po->dtype != DTYPE_PATH) + { int i; - switch (po->length) { - case 2: { + switch (po->length) + { + case 2: + { short *ptr; for (i = 0, ptr = (short *)po->pointer; i < (int)po->arsize; i += sizeof(*ptr), ptr++) swap(short, (char *)ptr, *ptr); - } break; - case 4: { + } + break; + case 4: + { int *ptr; for (i = 0, ptr = (int *)po->pointer; i < (int)po->arsize; i += sizeof(*ptr), ptr++) swap(int, (char *)ptr, *ptr); - } break; - case 8: { + } + break; + case 8: + { int64_t *ptr; for (i = 0, ptr = (int64_t *)po->pointer; i < (int)po->arsize; i += sizeof(*ptr), ptr++) swap(int64_t, (char *)ptr, *ptr); - } break; + } + break; } } #endif } bytes_out += pi->arsize; bytes_in += pi->arsize; - } break; + } + break; /************************************** For CA and APD, a0 is the offset. **************************************/ - case CLASS_APD: { + case CLASS_APD: + { array_coeff a_tmp = {0}; array_coeff *pi = &a_tmp; array_coeff *po = (array_coeff *)out_dsc_ptr; @@ -343,7 +377,8 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, a_tmp.aflags.bounds = bounds(); a_tmp.dimct = dimct(); set_arsize(a_tmp.arsize); - if (a_tmp.length != sizeof(void *)) { + if (a_tmp.length != sizeof(void *)) + { a_tmp.arsize = a_tmp.arsize / a_tmp.length * (uint32_t)sizeof(void *); a_tmp.length = sizeof(void *); } @@ -360,12 +395,16 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, : 0u) + (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); num_dsc = pi->arsize / pi->length; - if (po) { + if (po) + { memcpy(po, pi, sizeof(mdsdsc_a_t)); - for (i = 0; i < pi->dimct; i++) { - if (pi->aflags.coeff) { + for (i = 0; i < pi->dimct; i++) + { + if (pi->aflags.coeff) + { swap(int, m() + i * sizeof(int), po->m[i]); - if (pi->aflags.bounds) { + if (pi->aflags.bounds) + { swap(int, m() + (pi->dimct + 2 * i) * sizeof(int), po->m[pi->dimct + 2 * i]); swap(int, m() + (pi->dimct + 2 * i + 1) * sizeof(int), @@ -374,7 +413,8 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, } } po->pointer = (char *)po + bytes_out; - if (pi->aflags.coeff) { + if (pi->aflags.coeff) + { uint32_t offset; uint32_t a0; set_offset(offset); @@ -390,7 +430,8 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, /****************************** Each descriptor must be copied. ******************************/ - for (j = 0; j < num_dsc && STATUS_OK; ++j) { + for (j = 0; j < num_dsc && STATUS_OK; ++j) + { status = copy_rec_dx(in_ptr + bytes_in, po ? (mdsdsc_xd_t *)((char *)po + bytes_out) : 0, &size_out, &size_in); @@ -399,9 +440,11 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, bytes_out += size_out; bytes_in += size_in; } - } break; + } + break; - case CLASS_CA: { + case CLASS_CA: + { array_coeff a_tmp = {0}; array_coeff *pi = &a_tmp; array_coeff *po = (array_coeff *)out_dsc_ptr; @@ -435,17 +478,22 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u), (uint32_t)sizeof(void *)); set_offset(offset); - if (po) { + if (po) + { memcpy(po, pi, sizeof(mdsdsc_a_t)); - if (pi->aflags.coeff) { + if (pi->aflags.coeff) + { uint32_t a0; set_a0(a0); po->a0 = (char *)(intptr_t)a0; } - for (i = 0; i < pi->dimct; i++) { - if (pi->aflags.coeff) { + for (i = 0; i < pi->dimct; i++) + { + if (pi->aflags.coeff) + { swap(int, m() + i * sizeof(int), po->m[i]); - if (pi->aflags.bounds) { + if (pi->aflags.bounds) + { swap(int, m() + (pi->dimct + 2 * i) * sizeof(int), po->m[pi->dimct + 2 * i]); swap(int, m() + (pi->dimct + 2 * i + 1) * sizeof(int), @@ -456,7 +504,8 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, // do not use align!! po->pointer = offset ? ((char *)po + bytes_out) : 0; - if (po->pointer && pi->aflags.bounds) { + if (po->pointer && pi->aflags.bounds) + { po->a0 = (char *)(intptr_t) - (po->m[po->dimct] * po->length); } } @@ -464,23 +513,28 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, /*************************** Null pointer for shape only. ***************************/ - if (offset) { + if (offset) + { status = copy_rec_dx(in_ptr + bytes_in, po ? (mdsdsc_xd_t *)((char *)po + bytes_out) : 0, &size_out, &size_in); bytes_out += size_out; bytes_in += size_in; } - } break; + } + break; default: status = LibINVSTRDES; break; } - } else { + } + else + { mdsdsc_t *po = (mdsdsc_t *)out_dsc_ptr; static mdsdsc_t empty = {0, DTYPE_DSC, CLASS_S, 0}; - if (po) { + if (po) + { memcpy(po, &empty, sizeof(empty)); } bytes_out = align(sizeof(empty), sizeof(void *)); @@ -491,29 +545,35 @@ STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, return status; } -EXPORT int MdsSerializeDscIn(char const *in, mdsdsc_xd_t *out) { +EXPORT int MdsSerializeDscIn(char const *in, mdsdsc_xd_t *out) +{ l_length_t size_out, size_in; static const dtype_t dsc_dtype = DTYPE_DSC; int status = copy_rec_dx(in, 0, &size_out, &size_in); - if (STATUS_OK && size_out) { + if (STATUS_OK && size_out) + { status = MdsGet1Dx(&size_out, &dsc_dtype, out, 0); - if - STATUS_OK - status = copy_rec_dx(in, (mdsdsc_xd_t *)out->pointer, &size_out, &size_in); - } else + if (STATUS_OK) + status = copy_rec_dx(in, (mdsdsc_xd_t *)out->pointer, &size_out, &size_in); + } + else MdsFree1Dx(out, 0); return status; } STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, - l_length_t *b_out, l_length_t *b_in) { + l_length_t *b_out, l_length_t *b_in) +{ int status = MDSplusSUCCESS; unsigned bytes_out = 0, bytes_in = 0, j, size_out, size_in, num_dsc; if (in_ptr) - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_S: - case CLASS_D: { - if (out_ptr) { + case CLASS_D: + { + if (out_ptr) + { char *inp = ((char *)in_ptr) + offset(in_ptr->pointer); int dscsize = 8; LoadShort(in_ptr->length, out_ptr); @@ -523,8 +583,10 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, out_ptr += 8; #ifdef WORDS_BIGENDIAN if (in_ptr->dtype != DTYPE_T && in_ptr->dtype != DTYPE_IDENT && - in_ptr->dtype != DTYPE_PATH) { - switch (in_ptr->length) { + in_ptr->dtype != DTYPE_PATH) + { + switch (in_ptr->length) + { case 2: LoadShort(inp[0], out_ptr); break; @@ -538,19 +600,23 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, memcpy(out_ptr, inp, in_ptr->length); break; } - } else + } + else #endif memcpy(out_ptr, inp, in_ptr->length); out_ptr += in_ptr->length; } bytes_out = 8u + in_ptr->length; bytes_in = (uint32_t)sizeof(mdsdsc_t) + in_ptr->length; - } break; + } + break; case CLASS_XS: - case CLASS_XD: { + case CLASS_XD: + { mdsdsc_xs_t *inp = (mdsdsc_xs_t *)in_ptr; - if (out_ptr) { + if (out_ptr) + { int dscsize = 12; LoadShort(in_ptr->length, out_ptr); LoadChar(in_ptr->dtype, out_ptr + 2); @@ -564,13 +630,16 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, } bytes_in = (uint32_t)sizeof(mdsdsc_xs_t) + inp->l_length; bytes_out = 12u + inp->l_length; - } break; + } + break; - case CLASS_R: { + case CLASS_R: + { mdsdsc_r_t *inp = (mdsdsc_r_t *)in_ptr; char *begin = out_ptr; char *dscptrs = NULL; - if (out_ptr) { + if (out_ptr) + { int dscsize = inp->length ? 12 + inp->ndesc * 4 : 0; LoadShort(inp->length, out_ptr); LoadChar(inp->dtype, out_ptr + 2); @@ -580,10 +649,12 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, dscptrs = out_ptr + 12; memset(dscptrs, 0, inp->ndesc * 4u); out_ptr += 12u + inp->ndesc * 4u; - if (inp->length) { + if (inp->length) + { memcpy(out_ptr, ((char *)inp) + offset(inp->pointer), inp->length); #if defined(WORDS_BIGENDIAN) - if (inp->dtype == DTYPE_FUNCTION && inp->length == 2) { + if (inp->dtype == DTYPE_FUNCTION && inp->length == 2) + { short value; swap(short, (char *)out_ptr, value); memcpy(out_ptr, &value, 2); @@ -595,12 +666,15 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, bytes_out = 12u + inp->ndesc * 4u + inp->length; bytes_in = (uint32_t)sizeof(mdsdsc_r_t) + (inp->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *) + inp->length; - for (j = 0; j < inp->ndesc; j++) { - if (inp->dscptrs[j]) { + for (j = 0; j < inp->ndesc; j++) + { + if (inp->dscptrs[j]) + { status = copy_dx_rec((mdsdsc_t *)(((char *)inp) + offset(inp->dscptrs[j])), out_ptr, &size_out, &size_in); - if (out_ptr) { + if (out_ptr) + { uint32_t poffset = (uint32_t)(out_ptr - begin); LoadInt(poffset, dscptrs + (j * 4)); out_ptr += size_out; @@ -609,11 +683,14 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, bytes_in += size_in; } } - } break; + } + break; - case CLASS_A: { + case CLASS_A: + { array_coeff *inp = (array_coeff *)in_ptr; - if (out_ptr) { + if (out_ptr) + { char *inp2 = ((char *)inp) + offset(inp->pointer); uint32_t dscsize = 16u + @@ -632,16 +709,20 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, LoadChar(inp->dimct, out_ptr + 11); LoadInt(inp->arsize, out_ptr + 12); out_ptr += 16; - if (inp->aflags.coeff) { + if (inp->aflags.coeff) + { uint32_t a0 = dscsize + (offset(inp->a0) - offset(inp->pointer)); LoadInt(a0, out_ptr); out_ptr += 4; - for (j = 0; j < inp->dimct; j++) { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[j], out_ptr); out_ptr += 4; } - if (inp->aflags.bounds) { - for (j = 0; j < inp->dimct; j++) { + if (inp->aflags.bounds) + { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[inp->dimct + 2 * j], out_ptr); out_ptr += 4; LoadInt(inp->m[inp->dimct + 2 * j + 1], out_ptr); @@ -651,28 +732,34 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, } #ifdef WORDS_BIGENDIAN if (in_ptr->dtype != DTYPE_T && in_ptr->dtype != DTYPE_IDENT && - in_ptr->dtype != DTYPE_PATH) { + in_ptr->dtype != DTYPE_PATH) + { uint32_t i; - switch (in_ptr->length) { + switch (in_ptr->length) + { case 2: - for (i = 0; i < inp->arsize; i += sizeof(short)) { + for (i = 0; i < inp->arsize; i += sizeof(short)) + { LoadShort(inp2[i], out_ptr + i); } break; case 4: - for (i = 0; i < inp->arsize; i += sizeof(int)) { + for (i = 0; i < inp->arsize; i += sizeof(int)) + { LoadInt(inp2[i], out_ptr + i); } break; case 8: - for (i = 0; i < inp->arsize; i += in_ptr->length) { + for (i = 0; i < inp->arsize; i += in_ptr->length) + { LoadQuad(inp2[i], out_ptr + i); } break; default: memcpy(out_ptr, inp2, inp->arsize); } - } else + } + else #endif memcpy(out_ptr, inp2, inp->arsize); out_ptr += inp->arsize; @@ -691,18 +778,21 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, : 0u) + (inp->aflags.bounds ? (uint32_t)sizeof(int) * inp->dimct * 2u : 0u) + inp->arsize; - } break; + } + break; /************************************** For CA and APD, a0 is the offset. **************************************/ - case CLASS_APD: { + case CLASS_APD: + { array_coeff *inp = (array_coeff *)in_ptr; mdsdsc_t **dsc = (mdsdsc_t **)(((char *)in_ptr) + offset(inp->pointer)); char *begin = out_ptr; char *dscptr = NULL; num_dsc = inp->arsize / inp->length; - if (out_ptr) { + if (out_ptr) + { uint32_t dscsize = 16u + (inp->aflags.coeff @@ -721,16 +811,20 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, LoadChar(inp->dimct, out_ptr + 11); LoadInt(arsize, out_ptr + 12); out_ptr += 16; - if (inp->aflags.coeff) { + if (inp->aflags.coeff) + { uint32_t a0 = dscsize + (offset(inp->a0) - offset(inp->pointer)); LoadInt(a0, out_ptr); out_ptr += 4; - for (j = 0; j < inp->dimct; j++) { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[j], out_ptr); out_ptr += 4; } - if (inp->aflags.bounds) { - for (j = 0; j < inp->dimct; j++) { + if (inp->aflags.bounds) + { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[inp->dimct + 2 * j], out_ptr); out_ptr += 4; LoadInt(inp->m[inp->dimct + 2 * j + 1], out_ptr); @@ -758,19 +852,25 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, /****************************** Each descriptor must be copied. ******************************/ - for (j = 0; j < num_dsc; j++, bytes_in += 4) { - if (offset(dsc[j])) { + for (j = 0; j < num_dsc; j++, bytes_in += 4) + { + if (offset(dsc[j])) + { status = copy_dx_rec((mdsdsc_t *)(((char *)in_ptr) + offset(dsc[j])), out_ptr, &size_out, &size_in); - if (out_ptr) { + if (out_ptr) + { uint32_t poffset = (uint32_t)(out_ptr - begin); LoadInt(poffset, dscptr + (j * 4)); out_ptr += size_out; } bytes_out += size_out; bytes_in += size_in; - } else { - if (out_ptr) { + } + else + { + if (out_ptr) + { uint32_t poffset = 0; LoadInt(poffset, dscptr + (j * 4)); out_ptr += (uint32_t)sizeof(int); @@ -779,11 +879,14 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, bytes_in += (uint32_t)sizeof(void *); } } - } break; + } + break; - case CLASS_CA: { + case CLASS_CA: + { array_coeff *inp = (array_coeff *)in_ptr; - if (out_ptr) { + if (out_ptr) + { uint32_t dscsize = inp->pointer ? 16u + (inp->aflags.coeff @@ -804,16 +907,20 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, LoadChar(inp->dimct, out_ptr + 11); LoadInt(inp->arsize, out_ptr + 12); out_ptr += 16; - if (inp->aflags.coeff) { + if (inp->aflags.coeff) + { uint32_t a0 = (uint32_t)(uintptr_t)inp->a0; LoadInt(a0, out_ptr); out_ptr += 4; - for (j = 0; j < inp->dimct; j++) { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[j], out_ptr); out_ptr += 4; } - if (inp->aflags.bounds) { - for (j = 0; j < inp->dimct; j++) { + if (inp->aflags.bounds) + { + for (j = 0; j < inp->dimct; j++) + { LoadInt(inp->m[inp->dimct + 2 * j], out_ptr); out_ptr += 4; LoadInt(inp->m[inp->dimct + 2 * j + 1], out_ptr); @@ -837,14 +944,16 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, /*************************** Null pointer for shape only. ***************************/ - if (inp->pointer) { + if (inp->pointer) + { status = copy_dx_rec((mdsdsc_t *)(((char *)in_ptr) + offset(inp->pointer)), out_ptr, &size_out, &size_in); bytes_out += size_out; bytes_in += size_in; } - } break; + } + break; default: status = LibINVSTRDES; @@ -856,128 +965,147 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, } STATIC_ROUTINE int Dsc2Rec(const mdsdsc_t *inp, mdsdsc_xd_t *out_ptr, - arsize_t *reclen) { + arsize_t *reclen) +{ arsize_t size_out, size_in; static const dtype_t b_dtype = DTYPE_B; int status = copy_dx_rec(inp, 0, &size_out, &size_in); - if (STATUS_OK && size_out) { + if (STATUS_OK && size_out) + { length_t nlen = 1; array out_template = {1, DTYPE_B, CLASS_A, 0, 0, 0, {0, 1, 1, 0, 0}, 1, 0}; out_template.arsize = *reclen = size_out; status = MdsGet1DxA((mdsdsc_a_t *)&out_template, &nlen, &b_dtype, out_ptr); - if - STATUS_OK { - memset(out_ptr->pointer->pointer, 0, size_out); - status = copy_dx_rec((mdsdsc_t *)inp, out_ptr->pointer->pointer, - &size_out, &size_in); - } - } else + if (STATUS_OK) + { + memset(out_ptr->pointer->pointer, 0, size_out); + status = copy_dx_rec((mdsdsc_t *)inp, out_ptr->pointer->pointer, + &size_out, &size_in); + } + } + else MdsFree1Dx(out_ptr, NULL); return status; } -STATIC_CONSTANT int PointerToOffset(mdsdsc_t *dsc_ptr, l_length_t *length) { +STATIC_CONSTANT int PointerToOffset(mdsdsc_t *dsc_ptr, l_length_t *length) +{ int status = 1; if ((dsc_ptr->dtype == DTYPE_DSC) && (dsc_ptr->class != CLASS_A) && (dsc_ptr->class != CLASS_APD)) status = PointerToOffset((mdsdsc_t *)dsc_ptr->pointer, length); - if - STATUS_OK { - switch (dsc_ptr->class) { - case CLASS_S: - case CLASS_D: - *length += (uint32_t)sizeof(mdsdsc_t) + dsc_ptr->length; - dsc_ptr->pointer = dsc_ptr->pointer - (uintptr_t)dsc_ptr; - break; - case CLASS_XD: - case CLASS_XS: - *length += - (uint32_t)sizeof(mdsdsc_xd_t) + ((mdsdsc_xd_t *)dsc_ptr)->l_length; - dsc_ptr->pointer = - (void *)((intptr_t)dsc_ptr->pointer - (intptr_t)dsc_ptr); - break; - case CLASS_R: { - mdsdsc_r_t *r_ptr = (mdsdsc_r_t *)dsc_ptr; - int i; - *length += (uint32_t)sizeof(*r_ptr) + - (r_ptr->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *) + - r_ptr->length; - if (r_ptr->length != 0) - r_ptr->pointer = (void *)((intptr_t)r_ptr->pointer - (intptr_t)r_ptr); - for (i = 0; STATUS_OK && (i < r_ptr->ndesc); i++) - if (r_ptr->dscptrs[i] != 0) { - status = PointerToOffset(r_ptr->dscptrs[i], length); - r_ptr->dscptrs[i] = - (mdsdsc_t *)((intptr_t)r_ptr->dscptrs[i] - (intptr_t)r_ptr); - } - } break; - case CLASS_A: { - mdsdsc_a_t *a_ptr = (mdsdsc_a_t *)dsc_ptr; - *length += - (uint32_t)sizeof(mdsdsc_a_t) + - (a_ptr->aflags.coeff ? (uint32_t)sizeof(int) * (a_ptr->dimct + 1u) - : 0u) + - (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * a_ptr->dimct * 2u - : 0u) + - a_ptr->arsize; - a_ptr->pointer = (void *)((intptr_t)a_ptr->pointer - (intptr_t)a_ptr); - if (a_ptr->aflags.coeff) { + if (STATUS_OK) + { + switch (dsc_ptr->class) + { + case CLASS_S: + case CLASS_D: + *length += (uint32_t)sizeof(mdsdsc_t) + dsc_ptr->length; + dsc_ptr->pointer = dsc_ptr->pointer - (uintptr_t)dsc_ptr; + break; + case CLASS_XD: + case CLASS_XS: + *length += + (uint32_t)sizeof(mdsdsc_xd_t) + ((mdsdsc_xd_t *)dsc_ptr)->l_length; + dsc_ptr->pointer = + (void *)((intptr_t)dsc_ptr->pointer - (intptr_t)dsc_ptr); + break; + case CLASS_R: + { + mdsdsc_r_t *r_ptr = (mdsdsc_r_t *)dsc_ptr; + int i; + *length += (uint32_t)sizeof(*r_ptr) + + (r_ptr->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *) + + r_ptr->length; + if (r_ptr->length != 0) + r_ptr->pointer = (void *)((intptr_t)r_ptr->pointer - (intptr_t)r_ptr); + for (i = 0; STATUS_OK && (i < r_ptr->ndesc); i++) + if (r_ptr->dscptrs[i] != 0) + { + status = PointerToOffset(r_ptr->dscptrs[i], length); + r_ptr->dscptrs[i] = + (mdsdsc_t *)((intptr_t)r_ptr->dscptrs[i] - (intptr_t)r_ptr); + } + } + break; + case CLASS_A: + { + mdsdsc_a_t *a_ptr = (mdsdsc_a_t *)dsc_ptr; + *length += + (uint32_t)sizeof(mdsdsc_a_t) + + (a_ptr->aflags.coeff ? (uint32_t)sizeof(int) * (a_ptr->dimct + 1u) + : 0u) + + (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * a_ptr->dimct * 2u + : 0u) + + a_ptr->arsize; + a_ptr->pointer = (void *)((intptr_t)a_ptr->pointer - (intptr_t)a_ptr); + if (a_ptr->aflags.coeff) + { + uint32_t *a0_ptr = + (uint32_t *)((uintptr_t)a_ptr + sizeof(mdsdsc_a_t)); + *a0_ptr = *a0_ptr - (uint32_t)(uintptr_t)a_ptr; + } + } + break; + case CLASS_APD: + { + mdsdsc_a_t *a_ptr = (mdsdsc_a_t *)dsc_ptr; + uint32_t i, elts = a_ptr->arsize / a_ptr->length; + *length += + (uint32_t)sizeof(mdsdsc_a_t) + + (a_ptr->aflags.coeff ? (uint32_t)sizeof(int) * (a_ptr->dimct + 1u) + : 0u) + + (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * (a_ptr->dimct * 2u) + : 0u) + + a_ptr->arsize; + for (i = 0; (i < elts) && STATUS_OK; i++) + { + mdsdsc_t **dsc_ptr = (mdsdsc_t **)a_ptr->pointer + i; + if (dsc_ptr && *dsc_ptr) + { + status = PointerToOffset(*dsc_ptr, length); + *dsc_ptr = (mdsdsc_t *)((uintptr_t)*dsc_ptr - (uintptr_t)a_ptr); + } + else + { + status = 1; + *dsc_ptr = 0; + } + } + if (STATUS_OK) + { + a_ptr->pointer = + (void *)((uintptr_t)a_ptr->pointer - (uintptr_t)a_ptr); + if (a_ptr->aflags.coeff) + { uint32_t *a0_ptr = (uint32_t *)((uintptr_t)a_ptr + sizeof(mdsdsc_a_t)); *a0_ptr = *a0_ptr - (uint32_t)(uintptr_t)a_ptr; } - } break; - case CLASS_APD: { + } + } + break; + case CLASS_CA: + if (dsc_ptr->pointer) + { + uint32_t dummy_length; mdsdsc_a_t *a_ptr = (mdsdsc_a_t *)dsc_ptr; - uint32_t i, elts = a_ptr->arsize / a_ptr->length; *length += (uint32_t)sizeof(mdsdsc_a_t) + (a_ptr->aflags.coeff ? (uint32_t)sizeof(int) * (a_ptr->dimct + 1u) : 0u) + - (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * (a_ptr->dimct * 2u) + (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * a_ptr->dimct * 2u : 0u) + a_ptr->arsize; - for (i = 0; (i < elts) && STATUS_OK; i++) { - mdsdsc_t **dsc_ptr = (mdsdsc_t **)a_ptr->pointer + i; - if (dsc_ptr && *dsc_ptr) { - status = PointerToOffset(*dsc_ptr, length); - *dsc_ptr = (mdsdsc_t *)((uintptr_t)*dsc_ptr - (uintptr_t)a_ptr); - } else { - status = 1; - *dsc_ptr = 0; - } - } - if - STATUS_OK { - a_ptr->pointer = - (void *)((uintptr_t)a_ptr->pointer - (uintptr_t)a_ptr); - if (a_ptr->aflags.coeff) { - uint32_t *a0_ptr = - (uint32_t *)((uintptr_t)a_ptr + sizeof(mdsdsc_a_t)); - *a0_ptr = *a0_ptr - (uint32_t)(uintptr_t)a_ptr; - } - } - } break; - case CLASS_CA: - if (dsc_ptr->pointer) { - uint32_t dummy_length; - mdsdsc_a_t *a_ptr = (mdsdsc_a_t *)dsc_ptr; - *length += - (uint32_t)sizeof(mdsdsc_a_t) + - (a_ptr->aflags.coeff ? (uint32_t)sizeof(int) * (a_ptr->dimct + 1u) - : 0u) + - (a_ptr->aflags.bounds ? (uint32_t)sizeof(int) * a_ptr->dimct * 2u - : 0u) + - a_ptr->arsize; - status = PointerToOffset((mdsdsc_t *)dsc_ptr->pointer, &dummy_length); - a_ptr->pointer = (void *)((intptr_t)a_ptr->pointer - (intptr_t)a_ptr); - } - break; - default: - status = LibINVSTRDES; - break; + status = PointerToOffset((mdsdsc_t *)dsc_ptr->pointer, &dummy_length); + a_ptr->pointer = (void *)((intptr_t)a_ptr->pointer - (intptr_t)a_ptr); } + break; + default: + status = LibINVSTRDES; + break; } + } return status; } @@ -985,7 +1113,8 @@ EXPORT int MdsSerializeDscOutZ( mdsdsc_t const *in, mdsdsc_xd_t *out, int (*fixupNid)(), void *fixupNidArg, int (*fixupPath)(), void *fixupPathArg, int compress, int *compressible_out, l_length_t *length_out, l_length_t *reclen_out, dtype_t *dtype_out, - class_t *class_out, int altbuflen, void *altbuf, int *data_in_altbuf_out) { + class_t *class_out, int altbuflen, void *altbuf, int *data_in_altbuf_out) +{ int status; mdsdsc_t *out_ptr; mdsdsc_xd_t tempxd; @@ -997,70 +1126,83 @@ EXPORT int MdsSerializeDscOutZ( int data_in_altbuf = 0; status = MdsCopyDxXdZ(in, out, 0, fixupNid, fixupNidArg, fixupPath, fixupPathArg); - if (status == MdsCOMPRESSIBLE) { - if (compress) { + if (status == MdsCOMPRESSIBLE) + { + if (compress) + { tempxd = *out; out->l_length = 0; out->pointer = 0; status = MdsCompress(0, 0, tempxd.pointer, out); MdsFree1Dx(&tempxd, NULL); compressible = 0; - } else + } + else compressible = 1; - } else + } + else compressible = 0; - if - STATUS_OK { - if (out->pointer && out->dtype == DTYPE_DSC) { - out_ptr = out->pointer; - dtype = (dtype_t)out_ptr->dtype; - if ((out_ptr->class == CLASS_S || out_ptr->class == CLASS_D) && - out_ptr->length < altbuflen) { - data_in_altbuf = 1; - class = CLASS_S; - length = out_ptr->length + 8u; + if (STATUS_OK) + { + if (out->pointer && out->dtype == DTYPE_DSC) + { + out_ptr = out->pointer; + dtype = (dtype_t)out_ptr->dtype; + if ((out_ptr->class == CLASS_S || out_ptr->class == CLASS_D) && + out_ptr->length < altbuflen) + { + data_in_altbuf = 1; + class = CLASS_S; + length = out_ptr->length + 8u; #ifdef WORDS_BIGENDIAN - if (dtype != DTYPE_T && dtype != DTYPE_IDENT && dtype != DTYPE_PATH) { - char *outp = (char *)altbuf; - char *inp = out_ptr->pointer; - switch (out_ptr->length) { - case 2: - LoadShort(inp[0], outp); - break; - case 4: - LoadInt(inp[0], outp); - break; - case 8: - LoadQuad(inp[0], outp); - break; - default: - memcpy(outp, inp, out_ptr->length); - } - } else -#endif - memcpy(altbuf, out_ptr->pointer, out_ptr->length); - } else { - data_in_altbuf = 0; - class = (out_ptr->class == CLASS_XD) ? CLASS_XS : out_ptr->class; - length = 0; - status = PointerToOffset(out->pointer, &length); - if - STATUS_OK { - tempxd = *out; - out->l_length = 0; - out->pointer = 0; - Dsc2Rec(tempxd.pointer, out, &reclen); - MdsFree1Dx(&tempxd, NULL); - } + if (dtype != DTYPE_T && dtype != DTYPE_IDENT && dtype != DTYPE_PATH) + { + char *outp = (char *)altbuf; + char *inp = out_ptr->pointer; + switch (out_ptr->length) + { + case 2: + LoadShort(inp[0], outp); + break; + case 4: + LoadInt(inp[0], outp); + break; + case 8: + LoadQuad(inp[0], outp); + break; + default: + memcpy(outp, inp, out_ptr->length); + } } - } else { + else +#endif + memcpy(altbuf, out_ptr->pointer, out_ptr->length); + } + else + { + data_in_altbuf = 0; + class = (out_ptr->class == CLASS_XD) ? CLASS_XS : out_ptr->class; length = 0; - dtype = 0; - class = 0; - reclen = 0; - data_in_altbuf = 1; + status = PointerToOffset(out->pointer, &length); + if (STATUS_OK) + { + tempxd = *out; + out->l_length = 0; + out->pointer = 0; + Dsc2Rec(tempxd.pointer, out, &reclen); + MdsFree1Dx(&tempxd, NULL); + } } } + else + { + length = 0; + dtype = 0; + class = 0; + reclen = 0; + data_in_altbuf = 1; + } + } if (compressible_out) *compressible_out = compressible; if (length_out) @@ -1076,6 +1218,7 @@ EXPORT int MdsSerializeDscOutZ( return status; } -EXPORT int MdsSerializeDscOut(mdsdsc_t const *in, mdsdsc_xd_t *out) { +EXPORT int MdsSerializeDscOut(mdsdsc_t const *in, mdsdsc_xd_t *out) +{ return MdsSerializeDscOutZ(in, out, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } diff --git a/mdsshr/MdsThreadStatic.c b/mdsshr/MdsThreadStatic.c index 27b61b2978..9f65c857a0 100644 --- a/mdsshr/MdsThreadStatic.c +++ b/mdsshr/MdsThreadStatic.c @@ -35,14 +35,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Key for the thread-specific buffer */ static pthread_key_t mts_key; /* Free the thread-specific buffer */ -static inline void free_buffer(buffer_t *buf) { +static inline void free_buffer(buffer_t *buf) +{ if (!buf) return; buf->free(buf->buffer); free(buf); } -static void free_mts(MDSplusThreadStatic_t *mts) { - if (mts->is_owned) { +static void free_mts(MDSplusThreadStatic_t *mts) +{ + if (mts->is_owned) + { buffer_t **buf, **end = mts->buffers + THREADSTATIC_SIZE; for (buf = mts->buffers; buf < end; buf++) free_buffer(*buf); @@ -51,14 +54,16 @@ static void free_mts(MDSplusThreadStatic_t *mts) { free(mts); } static void init_mts_key() { pthread_key_create(&mts_key, (void *)free_mts); } -EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) { +EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) +{ // mts = MDSplusThreadStatic(NULL) : get current thread's mts // MDSplusThreadStatic(parent_mts) : setup parent mts in thread ; should be // first command of thread RUN_FUNCTION_ONCE(init_mts_key); MDSplusThreadStatic_t *mts = (MDSplusThreadStatic_t *)pthread_getspecific(mts_key); - if (in) { + if (in) + { // duplicate in and replace MDSplusThreadStatic_t *old_mts = mts; mts = (MDSplusThreadStatic_t *)malloc(sizeof(MDSplusThreadStatic_t)); @@ -67,9 +72,12 @@ EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) { pthread_setspecific(mts_key, (void *)mts); if (old_mts) free_mts(old_mts); - } else { + } + else + { // create if NULL - if (!mts) { + if (!mts) + { mts = (MDSplusThreadStatic_t *)malloc(sizeof(MDSplusThreadStatic_t)); mts->is_owned = TRUE; mts->buffers = calloc(THREADSTATIC_SIZE, sizeof(buffer_t *)); @@ -79,7 +87,8 @@ EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) { return mts; } -static inline MDSTHREADSTATIC_TYPE *buffer_alloc() { +static inline MDSTHREADSTATIC_TYPE *buffer_alloc() +{ MDSTHREADSTATIC_ARG = (MDSTHREADSTATIC_TYPE *)calloc(1, sizeof(MDSTHREADSTATIC_TYPE)); MDS_MDSGETMSG_DESC.dtype = DTYPE_T; @@ -91,10 +100,12 @@ static inline MDSTHREADSTATIC_TYPE *buffer_alloc() { IMPLEMENT_GETTHREADSTATIC(MDSTHREADSTATIC_TYPE, MdsGetThreadStatic, THREADSTATIC_MDSSHR, buffer_alloc, free) -EXPORT void LockMdsShrMutex(pthread_mutex_t *mutex, int *initialized) { +EXPORT void LockMdsShrMutex(pthread_mutex_t *mutex, int *initialized) +{ static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&initMutex); - if (!*initialized) { + if (!*initialized) + { pthread_mutexattr_t m_attr; pthread_mutexattr_init(&m_attr); pthread_mutexattr_settype(&m_attr, PTHREAD_MUTEX_RECURSIVE); @@ -105,7 +116,8 @@ EXPORT void LockMdsShrMutex(pthread_mutex_t *mutex, int *initialized) { pthread_mutex_lock(mutex); } -EXPORT void UnlockMdsShrMutex(pthread_mutex_t *mutex) { +EXPORT void UnlockMdsShrMutex(pthread_mutex_t *mutex) +{ pthread_mutex_unlock(mutex); } diff --git a/mdsshr/MdsXdRoutines.c b/mdsshr/MdsXdRoutines.c index 805cd645b0..08b4b3f872 100644 --- a/mdsshr/MdsXdRoutines.c +++ b/mdsshr/MdsXdRoutines.c @@ -54,13 +54,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define compression_threshold 128 #define _MOVC3(a, b, c) memcpy(c, b, (size_t)(a)) -inline static size_t _sizeAligned(const size_t bytes) { +inline static size_t _sizeAligned(const size_t bytes) +{ size_t b_mod = bytes % sizeof(void *); return (b_mod == 0) ? bytes : (bytes + sizeof(void *) - b_mod); } inline static char *_align(char *const ptr, const size_t offset, - const size_t size) { + const size_t size) +{ uintptr_t p_mod = (uintptr_t)(ptr + offset) % size; return (p_mod == 0) ? ptr + offset : (ptr + offset + size - p_mod); } @@ -69,45 +71,52 @@ inline static char *_align(char *const ptr, const size_t offset, EXPORT int MdsGet1Dx(const l_length_t *const length_ptr, const dtype_t *const dtype_ptr, mdsdsc_xd_t *const dsc_ptr, - void **const zone) { + void **const zone) +{ int status; - if (dsc_ptr->class == CLASS_XD) { - if (*length_ptr != dsc_ptr->l_length) { + if (dsc_ptr->class == CLASS_XD) + { + if (*length_ptr != dsc_ptr->l_length) + { if (dsc_ptr->l_length) status = LibFreeVm(&dsc_ptr->l_length, (void *)&dsc_ptr->pointer, zone); else status = 1; - if - STATUS_OK - status = - LibGetVm((uint32_t *)length_ptr, (void *)&dsc_ptr->pointer, zone); - } else + if (STATUS_OK) + status = + LibGetVm((uint32_t *)length_ptr, (void *)&dsc_ptr->pointer, zone); + } + else status = 1; - if - STATUS_OK { - dsc_ptr->length = 0; - dsc_ptr->l_length = *length_ptr; - dsc_ptr->class = CLASS_XD; - dsc_ptr->dtype = *dtype_ptr; - } - } else + if (STATUS_OK) + { + dsc_ptr->length = 0; + dsc_ptr->l_length = *length_ptr; + dsc_ptr->class = CLASS_XD; + dsc_ptr->dtype = *dtype_ptr; + } + } + else status = LibINVSTRDES; return status; } -EXPORT int MdsFree1Dx(mdsdsc_xd_t *const dsc_ptr, void **const zone) { +EXPORT int MdsFree1Dx(mdsdsc_xd_t *const dsc_ptr, void **const zone) +{ int status; - if (dsc_ptr->class == CLASS_XD) { + if (dsc_ptr->class == CLASS_XD) + { if (dsc_ptr->pointer) status = LibFreeVm(&dsc_ptr->l_length, (void *)&dsc_ptr->pointer, zone); else status = 1; - if - STATUS_OK { - dsc_ptr->pointer = 0; - dsc_ptr->l_length = 0; - } - } else if (dsc_ptr->class == CLASS_D) + if (STATUS_OK) + { + dsc_ptr->pointer = 0; + dsc_ptr->l_length = 0; + } + } + else if (dsc_ptr->class == CLASS_D) status = StrFree1Dx((mdsdsc_d_t *)dsc_ptr); else status = LibINVSTRDES; @@ -126,7 +135,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, mdsdsc_xd_t *const out_dsc_ptr, uint32_t *const bytes_used_ptr, int (*const fixup_nid)(), void *const fixup_nid_arg, int (*const fixup_path)(), - void *const fixup_path_arg, int *const compressible) { + void *const fixup_path_arg, int *const compressible) +{ int status = 1; uint32_t bytes = 0, j, size; mdsdsc_t *in_ptr = (mdsdsc_t *)in_dsc_ptr; @@ -134,21 +144,26 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, while (in_ptr && in_ptr->dtype == DTYPE_DSC && in_ptr->class != CLASS_APD) in_ptr = (mdsdsc_t *)in_ptr->pointer; if (in_ptr) - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_S: - case CLASS_D: { + case CLASS_D: + { mdsdsc_t in; mdsdsc_t *po = (mdsdsc_t *)out_dsc_ptr; mdsdsc_d_t path = {0, DTYPE_T, CLASS_D, 0}; in = *(mdsdsc_t *)in_ptr; in.class = CLASS_S; if (in.dtype == DTYPE_NID && fixup_nid && - (*fixup_nid)(in.pointer, fixup_nid_arg, &path)) { + (*fixup_nid)(in.pointer, fixup_nid_arg, &path)) + { in.length = path.length; in.dtype = DTYPE_PATH; in.pointer = path.pointer; - } else if (in.dtype == DTYPE_PATH && fixup_path && - (*fixup_path)(&in, fixup_path_arg, &path)) { + } + else if (in.dtype == DTYPE_PATH && fixup_path && + (*fixup_path)(&in, fixup_path_arg, &path)) + { in.length = path.length; in.pointer = path.pointer; } @@ -156,37 +171,46 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, ((in.dtype == DTYPE_T || in.dtype == DTYPE_PATH) && in.length) ? 1 : in.length; - if (po) { + if (po) + { *po = in; po->class = CLASS_S; - if (in.length) { + if (in.length) + { po->pointer = _align((char *)po, sizeof(mdsdsc_t), align_size); memcpy(po->pointer, in.pointer, in.length); - } else + } + else po->pointer = NULL; } if (path.pointer) StrFree1Dx(&path); bytes = (uint32_t)sizeof(mdsdsc_s_t) + in.length + align_size; - } break; + } + break; case CLASS_XS: - case CLASS_XD: { + case CLASS_XD: + { mdsdsc_xs_t in; mdsdsc_xs_t *po = (mdsdsc_xs_t *)out_dsc_ptr; mdsdsc_d_t path = {0, DTYPE_T, CLASS_D, 0}; in = *(mdsdsc_xs_t *)in_ptr; if (in.dtype == DTYPE_NID && fixup_nid && - (*fixup_nid)(in.pointer, fixup_nid_arg, &path)) { + (*fixup_nid)(in.pointer, fixup_nid_arg, &path)) + { in.l_length = path.length; in.dtype = DTYPE_PATH; in.pointer = (mdsdsc_t *)path.pointer; - } else if (in.dtype == DTYPE_PATH && fixup_path && - (*fixup_path)(&in, fixup_path_arg, &path)) { + } + else if (in.dtype == DTYPE_PATH && fixup_path && + (*fixup_path)(&in, fixup_path_arg, &path)) + { in.l_length = path.length; in.pointer = (mdsdsc_t *)path.pointer; } - if (po) { + if (po) + { *po = in; po->class = CLASS_XS; po->pointer = (mdsdsc_t *)po + sizeof(in); @@ -195,16 +219,20 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, if (path.pointer) StrFree1Dx(&path); bytes = (uint32_t)_sizeAligned(sizeof(mdsdsc_xs_t) + in.l_length); - } break; + } + break; - case CLASS_R: { + case CLASS_R: + { mdsdsc_r_t *pi = (mdsdsc_r_t *)in_ptr; mdsdsc_r_t *po = (mdsdsc_r_t *)out_dsc_ptr; bytes = (uint32_t)sizeof(mdsdsc_r_t) + (pi->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *); - if (po) { + if (po) + { _MOVC3(bytes, (char *)pi, (char *)po); - if (pi->length > 0) { + if (pi->length > 0) + { po->pointer = (unsigned char *)po + bytes; _MOVC3(pi->length, (char *)pi->pointer, (char *)po->pointer); } @@ -214,7 +242,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, Each descriptor must be copied. ******************************/ for (j = 0; j < pi->ndesc && STATUS_OK; ++j) - if (pi->dscptrs[j]) { + if (pi->dscptrs[j]) + { status = copy_dx((mdsdsc_xd_t *)pi->dscptrs[j], po ? (mdsdsc_xd_t *)((char *)po + bytes) : 0, &size, fixup_nid, fixup_nid_arg, fixup_path, fixup_path_arg, @@ -223,16 +252,19 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, po->dscptrs[j] = size ? (mdsdsc_t *)((char *)po + bytes) : 0; bytes = (uint32_t)_sizeAligned(bytes + size); } - } break; + } + break; - case CLASS_NCA: { + case CLASS_NCA: + { array_coeff *pi = (array_coeff *)FixedArray(in_ptr); array_coeff *po = (array_coeff *)out_dsc_ptr; bytes = (uint32_t)sizeof(mdsdsc_a_t) + (pi->aflags.coeff ? (uint32_t)sizeof(int) * (pi->dimct + 1u) : 0u) + (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); - if (po) { + if (po) + { _MOVC3(bytes, (char *)pi, (char *)po); po->pointer = (char *)po + bytes; _MOVC3(pi->arsize, pi->pointer, po->pointer); @@ -243,9 +275,11 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, if (pi->arsize > compression_threshold) *compressible = 1; free(pi); - } break; + } + break; - case CLASS_A: { + case CLASS_A: + { uint32_t dscsize, align_size; array_coeff *pi = (array_coeff *)in_ptr; array_coeff *po = (array_coeff *)out_dsc_ptr; @@ -259,7 +293,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, MdsFixDscLength((mdsdsc_t *)pi); align_size = (pi->dtype == DTYPE_T || pi->length == 0) ? 1 : pi->length; bytes = dscsize + pi->arsize + align_size; - if (po) { + if (po) + { _MOVC3(dscsize, (char *)pi, (char *)po); po->pointer = _align((char *)po, dscsize, align_size); if (pi->arsize > 0 && pi->pointer != NULL) @@ -269,12 +304,14 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, } if (pi->arsize > compression_threshold) *compressible = 1; - } break; + } + break; /************************************** For CA and APD, a0 is the offset. **************************************/ - case CLASS_APD: { + case CLASS_APD: + { mdsdsc_a_t *pi = (mdsdsc_a_t *)in_ptr; mdsdsc_a_t *po = (mdsdsc_a_t *)out_dsc_ptr; mdsdsc_t **pdi = (mdsdsc_t **)pi->pointer; @@ -285,7 +322,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, (uint32_t)sizeof(int) * pi->dimct : 0u) + (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); - if (po) { + if (po) + { _MOVC3(bytes, (char *)pi, (char *)po); pdo = (mdsdsc_t **)(po->pointer = (char *)po + bytes); } @@ -294,7 +332,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, /****************************** Each descriptor must be copied. ******************************/ - for (j = 0; j < num_dsc && STATUS_OK; ++j) { + for (j = 0; j < num_dsc && STATUS_OK; ++j) + { status = copy_dx((mdsdsc_xd_t *)*pdi++, po ? (mdsdsc_xd_t *)((char *)po + bytes) : 0, &size, fixup_nid, fixup_nid_arg, fixup_path, fixup_path_arg, @@ -303,9 +342,11 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, *pdo++ = size ? (mdsdsc_t *)((char *)po + bytes) : 0; bytes = (uint32_t)_sizeAligned(bytes + size); } - } break; + } + break; - case CLASS_CA: { + case CLASS_CA: + { mdsdsc_a_t *pi = (mdsdsc_a_t *)in_ptr; mdsdsc_a_t *po = (mdsdsc_a_t *)out_dsc_ptr; bytes = (uint32_t)_sizeAligned( @@ -314,7 +355,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, ? (uint32_t)sizeof(char *) + (uint32_t)sizeof(int) * pi->dimct : 0u) + (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u)); - if (po) { + if (po) + { _MOVC3(bytes, (char *)pi, (char *)po); if (pi->pointer) po->pointer = _align((char *)po, bytes, sizeof(void *)); @@ -325,14 +367,16 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, /*************************** Null pointer for shape only. ***************************/ - if (pi->pointer) { + if (pi->pointer) + { status = copy_dx((mdsdsc_xd_t *)pi->pointer, po ? (mdsdsc_xd_t *)(po->pointer) : 0, &size, fixup_nid, fixup_nid_arg, fixup_path, fixup_path_arg, compressible); bytes = (uint32_t)_sizeAligned(bytes + size); } - } break; + } + break; default: status = LibINVSTRDES; @@ -353,7 +397,8 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, EXPORT int MdsCopyDxXdZ(const mdsdsc_t *const in_dsc_ptr, mdsdsc_xd_t *const out_dsc_ptr, void **const zone, int (*const fixup_nid)(), void *const fixup_nid_arg, - int (*const fixup_path)(), void *const fixup_path_arg) { + int (*const fixup_path)(), void *const fixup_path_arg) +{ uint32_t size; static dtype_t dsc_dtype = DTYPE_DSC; /************************************************ @@ -365,21 +410,23 @@ EXPORT int MdsCopyDxXdZ(const mdsdsc_t *const in_dsc_ptr, int status = copy_dx((mdsdsc_xd_t *)in_dsc_ptr, 0, &size, fixup_nid, fixup_nid_arg, fixup_path, fixup_path_arg, &compressible); - if (STATUS_OK && size) { + if (STATUS_OK && size) + { status = MdsGet1Dx(&size, &dsc_dtype, out_dsc_ptr, zone); - if - STATUS_OK - status = copy_dx((mdsdsc_xd_t *)in_dsc_ptr, - (mdsdsc_xd_t *)out_dsc_ptr->pointer, &size, fixup_nid, - fixup_nid_arg, fixup_path, fixup_path_arg, &compressible); + if (STATUS_OK) + status = copy_dx((mdsdsc_xd_t *)in_dsc_ptr, + (mdsdsc_xd_t *)out_dsc_ptr->pointer, &size, fixup_nid, + fixup_nid_arg, fixup_path, fixup_path_arg, &compressible); if (STATUS_OK && compressible) status = MdsCOMPRESSIBLE; - } else + } + else MdsFree1Dx(out_dsc_ptr, zone); return status; } -static mdsdsc_t *FixedArray(const mdsdsc_t *const in) { +static mdsdsc_t *FixedArray(const mdsdsc_t *const in) +{ array_coeff *a = (array_coeff *)in; uint32_t dsize = (uint32_t)sizeof(mdsdsc_a_t) + 4u + 12u * a->dimct; @@ -396,12 +443,15 @@ static mdsdsc_t *FixedArray(const mdsdsc_t *const in) { return (mdsdsc_t *)answer; } -EXPORT int MdsCopyDxXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out) { +EXPORT int MdsCopyDxXd(const mdsdsc_t *const in, mdsdsc_xd_t *const out) +{ return MdsCopyDxXdZ(in, out, NULL, NULL, NULL, NULL, NULL); } -void MdsFixDscLength(mdsdsc_t *const in) { - switch (in->dtype) { +void MdsFixDscLength(mdsdsc_t *const in) +{ + switch (in->dtype) + { default: break; case DTYPE_B: diff --git a/mdsshr/UdpEventSettings.c b/mdsshr/UdpEventSettings.c index 77c98045bf..3923cc90be 100644 --- a/mdsshr/UdpEventSettings.c +++ b/mdsshr/UdpEventSettings.c @@ -36,7 +36,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //#define DEBUG -typedef enum { LOOP, TTL, MULTICAST_IF, PORT, ADDRESS } setting_types; +typedef enum +{ + LOOP, + TTL, + MULTICAST_IF, + PORT, + ADDRESS +} setting_types; #define NUM_SETTINGS 5 static const char *settings[NUM_SETTINGS] = {0, 0, 0, 0, 0}; static const char *environ_var[NUM_SETTINGS] = { @@ -50,23 +57,30 @@ static const char *fname = "eventsConfig.xml"; EXPORT void InitializeEventSettings(); pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; -static void initialize() { +static void initialize() +{ static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, InitializeEventSettings); } -EXPORT int UdpEventGetLoop(unsigned char *loop) { +EXPORT int UdpEventGetLoop(unsigned char *loop) +{ int status = 0; initialize(); pthread_mutex_lock(&init_lock); - if (settings[LOOP]) { - if (strcmp("0", settings[LOOP]) == 0) { + if (settings[LOOP]) + { + if (strcmp("0", settings[LOOP]) == 0) + { *loop = 0; status = 1; - } else if (strcmp("1", settings[LOOP]) == 0) { + } + else if (strcmp("1", settings[LOOP]) == 0) + { *loop = 1; status = 1; - } else + } + else fprintf( stderr, "Invalid udp_multicast_loop value specified. Value must be 0 or 1.\n" @@ -76,17 +90,21 @@ EXPORT int UdpEventGetLoop(unsigned char *loop) { return status; } -EXPORT int UdpEventGetTtl(unsigned char *ttl) { +EXPORT int UdpEventGetTtl(unsigned char *ttl) +{ int status = 0; initialize(); pthread_mutex_lock(&init_lock); - if (settings[TTL]) { + if (settings[TTL]) + { char *endptr; long int lttl = strtol(settings[TTL], &endptr, 0); - if (*endptr == '\0' && lttl >= 0) { + if (*endptr == '\0' && lttl >= 0) + { *ttl = (unsigned char)lttl; status = 1; - } else + } + else fprintf(stderr, "Invalid udp_multicast_ttl value specified. Value must " "be an integer >= 0.\n"); } @@ -94,28 +112,37 @@ EXPORT int UdpEventGetTtl(unsigned char *ttl) { return status; } -EXPORT int UdpEventGetPort(unsigned short *port) { +EXPORT int UdpEventGetPort(unsigned short *port) +{ int status = 0; initialize(); pthread_mutex_lock(&init_lock); - if (settings[PORT]) { + if (settings[PORT]) + { struct servent *srv = getservbyname(settings[PORT], "UDP"); - if (srv) { + if (srv) + { *port = (unsigned short)srv->s_port; status = 1; - } else { + } + else + { char *endptr; long int lport = strtol(settings[PORT], &endptr, 0); - if (*endptr == '\0' && lport > 0) { + if (*endptr == '\0' && lport > 0) + { *port = (unsigned short)lport; status = 1; - } else { + } + else + { fprintf(stderr, "Invalid port specified. Specify known port name or " "integer > 0.\n"); } } } - if (status == 0) { + if (status == 0) + { struct servent *srv = getservbyname("mdsevent_port", "udp"); *port = srv ? (unsigned short)srv->s_port : 4000u; status = 1; @@ -124,7 +151,8 @@ EXPORT int UdpEventGetPort(unsigned short *port) { return status; } #ifdef DEBUG -inline static void print_addr(FILE *file, struct sockaddr_in *addr) { +inline static void print_addr(FILE *file, struct sockaddr_in *addr) +{ size_t i; uint8_t *c = (uint8_t *)&addr->sin_addr; fprintf(stderr, "%d", c[0]); @@ -132,23 +160,25 @@ inline static void print_addr(FILE *file, struct sockaddr_in *addr) { fprintf(file, ".%u", c[i]); } #endif -EXPORT int UdpEventGetInterface(struct in_addr **interface_addr) { +EXPORT int UdpEventGetInterface(struct in_addr **interface_addr) +{ /******************************************* struct in_addr is ipv4 so dont look for ipv6 ********************************************/ int status = 0; initialize(); pthread_mutex_lock(&init_lock); - if (settings[MULTICAST_IF]) { + if (settings[MULTICAST_IF]) + { int err; #ifdef _WIN32 #include -#define GAA_FLAGS \ +#define GAA_FLAGS \ GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER #define HAS_NO_ADDRESS(ifa) (ifa->FirstUnicastAddress == NULL) #define CHECK_NAME(ifa) (wcsicmp(ifa->FriendlyName, lookup_name) == 0) -#define freeifaddrs(ifaddr) \ - free(ifaddr); \ +#define freeifaddrs(ifaddr) \ + free(ifaddr); \ free(lookup_name) #define ifa_name FriendlyName #define ifa_addr FirstUnicastAddress->Address.lpSockaddr @@ -162,7 +192,8 @@ EXPORT int UdpEventGetInterface(struct in_addr **interface_addr) { ULONG memlen = sizeof(IP_ADAPTER_ADDRESSES); IP_ADAPTER_ADDRESSES *ifa, *ifaddr = malloc(memlen); while ((err = GetAdaptersAddresses(AF_INET, GAA_FLAGS, NULL, ifaddr, - &memlen)) == ERROR_BUFFER_OVERFLOW) { + &memlen)) == ERROR_BUFFER_OVERFLOW) + { memlen *= 2; ifaddr = realloc(ifaddr, memlen); } @@ -172,13 +203,16 @@ EXPORT int UdpEventGetInterface(struct in_addr **interface_addr) { struct ifaddrs *ifaddr = 0, *ifa; err = getifaddrs(&ifaddr); #endif - if (!err) { - for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { + if (!err) + { + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { if HAS_NO_ADDRESS(ifa) continue; struct sockaddr_in *addr = (struct sockaddr_in *)ifa->ifa_addr; - if (CHECK_NAME(ifa) && (addr->sin_family == AF_INET)) { + if (CHECK_NAME(ifa) && (addr->sin_family == AF_INET)) + { *interface_addr = memcpy(malloc(sizeof(addr->sin_addr)), &addr->sin_addr, sizeof(addr->sin_addr)); #ifdef DEBUG @@ -197,7 +231,8 @@ EXPORT int UdpEventGetInterface(struct in_addr **interface_addr) { return status; } -EXPORT int UdpEventGetAddress(char **address, unsigned char *arange) { +EXPORT int UdpEventGetAddress(char **address, unsigned char *arange) +{ int num; unsigned int p1 = 224, p2 = 0, p3 = 0, p4 = 175, p5 = 255; *address = (char *)malloc(50); @@ -205,26 +240,34 @@ EXPORT int UdpEventGetAddress(char **address, unsigned char *arange) { arange[1] = 255; initialize(); pthread_mutex_lock(&init_lock); - if (settings[ADDRESS]) { - if (strcasecmp(settings[ADDRESS], "compat") == 0) { + if (settings[ADDRESS]) + { + if (strcasecmp(settings[ADDRESS], "compat") == 0) + { strcpy(*address, "225.0.0.%d"); arange[0] = 0; arange[1] = 255; - } else if (((num = sscanf(settings[ADDRESS], "%d.%d.%d.%d-%d", &p1, &p2, - &p3, &p4, &p5)) > 3) && - (p1 < 256) && (p2 < 256) && (p3 < 256) && (p4 < 256) && - (p5 >= p4) && (p5 < 256)) { + } + else if (((num = sscanf(settings[ADDRESS], "%d.%d.%d.%d-%d", &p1, &p2, + &p3, &p4, &p5)) > 3) && + (p1 < 256) && (p2 < 256) && (p3 < 256) && (p4 < 256) && + (p5 >= p4) && (p5 < 256)) + { sprintf(*address, "%d.%d.%d.%%d", p1, p2, p3); arange[0] = (unsigned char)p4; arange[1] = (unsigned char)(num < 5 ? p4 : p5); - } else { + } + else + { fprintf(stderr, "Invalid address format specified. Specify either n.n.n.n or " "n.n.n.n-n format.\nDefaulting to 224.0.0.175"); strcpy(*address, "224.0.0.%d"); arange[0] = arange[1] = 175; } - } else { + } + else + { strcpy(*address, "224.0.0.%d"); arange[0] = arange[1] = 175; } @@ -233,15 +276,20 @@ EXPORT int UdpEventGetAddress(char **address, unsigned char *arange) { } static const char *getProperty(xmlDocPtr doc, const char *settings, - const char *setting) { + const char *setting) +{ const char *ans = NULL; - if (doc != NULL) { + if (doc != NULL) + { xmlNodePtr node; - for (node = doc->children; node && (ans == NULL); node = node->next) { - if (strcasecmp(settings, (const char *)node->name) == 0) { + for (node = doc->children; node && (ans == NULL); node = node->next) + { + if (strcasecmp(settings, (const char *)node->name) == 0) + { xmlAttrPtr pnode; for (pnode = node->properties; pnode && (ans == NULL); - pnode = pnode->next) { + pnode = pnode->next) + { if (pnode->children && pnode->children->content && strcasecmp(setting, (const char *)pnode->name) == 0) ans = strdup((const char *)pnode->children->content); @@ -252,18 +300,21 @@ static const char *getProperty(xmlDocPtr doc, const char *settings, return ans; } -inline static void xmlInitParser_supp() { +inline static void xmlInitParser_supp() +{ // so it can targeted for valgrind suppression xmlInitParser(); } DEFINE_INITIALIZESOCKETS; -EXPORT void InitializeEventSettings() { +EXPORT void InitializeEventSettings() +{ INITIALIZESOCKETS; pthread_mutex_lock(&init_lock); pthread_cleanup_push((void *)pthread_mutex_unlock, &init_lock); int i, missing = 0; xmlInitParser_supp(); - for (i = 0; i < NUM_SETTINGS; i++) { + for (i = 0; i < NUM_SETTINGS; i++) + { settings[i] = getenv(environ_var[i]); if (settings[i] == NULL) missing = 1; @@ -275,7 +326,8 @@ EXPORT void InitializeEventSettings() { fprintf(stderr, " %s=\"%s\"", environ_var[i], settings[i]); fprintf(stderr, "\n"); #endif - if (missing) { + if (missing) + { #ifdef DEBUG fprintf(stderr, "user xml: "); #endif @@ -289,20 +341,25 @@ EXPORT void InitializeEventSettings() { #else home_dir = getenv("HOME"); #endif - if (home_dir) { + if (home_dir) + { xmlDocPtr doc = NULL; static const char *home_xml_dir = "/.mdsplus.conf/"; char *xmlfname = malloc(strlen(home_dir) + strlen(home_xml_dir) + strlen(fname) + 1); - if (xmlfname) { + if (xmlfname) + { sprintf(xmlfname, "%s%s%s", home_dir, home_xml_dir, fname); if (access(xmlfname, R_OK) == 0) doc = xmlParseFile(xmlfname); free(xmlfname); - if (doc) { + if (doc) + { missing = 0; - for (i = 0; i < NUM_SETTINGS; i++) { - if (settings[i] == NULL) { + for (i = 0; i < NUM_SETTINGS; i++) + { + if (settings[i] == NULL) + { settings[i] = getProperty(doc, "UdpEvents", xml_setting[i]); if (settings[i] == NULL) missing = 1; @@ -320,23 +377,28 @@ EXPORT void InitializeEventSettings() { fprintf(stderr, "\n"); #endif } - if (missing) { + if (missing) + { #ifdef DEBUG fprintf(stderr, "local xml: "); #endif xmlDocPtr doc = NULL; char *mdsplus_dir = getenv("MDSPLUS_DIR"); static const char *local_xml_dir = "/local/"; - if (mdsplus_dir) { + if (mdsplus_dir) + { char *xmlfname = malloc(strlen(mdsplus_dir) + strlen(local_xml_dir) + strlen(fname) + 1); - if (xmlfname) { + if (xmlfname) + { sprintf(xmlfname, "%s%s%s", mdsplus_dir, local_xml_dir, fname); if (access(xmlfname, R_OK) == 0) doc = xmlParseFile(xmlfname); free(xmlfname); - if (doc) { - for (i = 0; i < NUM_SETTINGS; i++) { + if (doc) + { + for (i = 0; i < NUM_SETTINGS; i++) + { if (settings[i] == NULL) settings[i] = getProperty(doc, "UdpEvents", xml_setting[i]); #ifdef DEBUG diff --git a/mdsshr/UdpEvents.c b/mdsshr/UdpEvents.c index c7dcf1f22f..c39dfe78f5 100644 --- a/mdsshr/UdpEvents.c +++ b/mdsshr/UdpEvents.c @@ -39,7 +39,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include - extern int UdpEventGetPort(unsigned short *port); extern int UdpEventGetAddress(char **addr_format, unsigned char *arange); extern int UdpEventGetTtl(char *ttl); @@ -47,7 +46,7 @@ extern int UdpEventGetLoop(char *loop); extern int UdpEventGetInterface(struct in_addr **interface_addr); #define MAX_MSG_LEN 4096 -#define MAX_EVENTS \ +#define MAX_EVENTS \ 1000000 /*Maximum number of events handled by a single process */ #ifndef EVENT_THREAD_STACK_SIZE_MIN @@ -56,9 +55,11 @@ extern int UdpEventGetInterface(struct in_addr **interface_addr); #ifdef _WIN32 #define socklen_t int -static void print_error_code(char *message, int error) { +static void print_error_code(char *message, int error) +{ char *errorstr; - switch (error) { + switch (error) + { case WSANOTINITIALISED: errorstr = "WSANOTINITIALISED"; break; @@ -103,21 +104,24 @@ static void print_error_code(char *message, int error) { else fprintf(stderr, "%s - error code %d\n", message, error); } -inline static void print_error(char *message) { +inline static void print_error(char *message) +{ print_error_code(message, WSAGetLastError()); } #else #define print_error(message) fprintf(stderr, "%s\n", message) #endif -typedef struct _EventList { +typedef struct _EventList +{ int eventid; pthread_t thread; SOCKET socket; struct _EventList *next; } EventList; -struct EventInfo { +struct EventInfo +{ SOCKET socket; char *eventName; void *arg; @@ -139,7 +143,8 @@ static pthread_mutex_t sendEventMutex = PTHREAD_MUTEX_INITIALIZER; ***********************/ -static void *handleMessage(void *info_in) { +static void *handleMessage(void *info_in) +{ struct EventInfo *info = (struct EventInfo *)info_in; pthread_mutex_lock(&eventIdMutex); SOCKET socket = info->socket; @@ -157,10 +162,12 @@ static void *handleMessage(void *info_in) { free(info->eventName); free(info); pthread_mutex_unlock(&eventIdMutex); - for (;;) { + for (;;) + { recBytes = recvfrom(socket, (char *)recBuf, MAX_MSG_LEN, 0, (struct sockaddr *)&clientAddr, &addrSize); - if (recBytes <= 0) { + if (recBytes <= 0) + { #ifdef _WIN32 int error = WSAGetLastError(); if (!(recBytes == 0 || error == WSAEBADF || error == WSAESHUTDOWN || @@ -194,7 +201,8 @@ static void *handleMessage(void *info_in) { return 0; } -static int pushEvent(pthread_t thread, SOCKET socket) { +static int pushEvent(pthread_t thread, SOCKET socket) +{ pthread_mutex_lock(&eventIdMutex); EventList *ev = malloc(sizeof(EventList)); ev->eventid = ++EVENTID; @@ -206,13 +214,15 @@ static int pushEvent(pthread_t thread, SOCKET socket) { return ev->eventid; } -static EventList *popEvent(int eventid) { +static EventList *popEvent(int eventid) +{ pthread_mutex_lock(&eventIdMutex); EventList *ev, *ev_prev; for (ev = EVENTLIST, ev_prev = 0; ev && ev->eventid != eventid; ev_prev = ev, ev = ev->next) ; - if (ev) { + if (ev) + { if (ev_prev) ev_prev->next = ev->next; else @@ -222,7 +232,8 @@ static EventList *popEvent(int eventid) { return ev; } -static void getMulticastAddr(char const *eventName, char *retIp) { +static void getMulticastAddr(char const *eventName, char *retIp) +{ char *addr_format; size_t i, len = strlen(eventName); unsigned char arange[2]; @@ -238,7 +249,8 @@ static void getMulticastAddr(char const *eventName, char *retIp) { } int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char *), - void *astprm, int *eventid, __attribute__((unused)) unsigned int cpuMask) { + void *astprm, int *eventid, __attribute__((unused)) unsigned int cpuMask) +{ int check_bind_in_directive; struct sockaddr_in serverAddr; @@ -256,7 +268,8 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * pthread_t thread; memset(&ipMreq, 0, sizeof(ipMreq)); UdpEventGetPort(&port); - if ((udpSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { + if ((udpSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1) + { print_error("Error creating socket"); return 0; } @@ -267,13 +280,15 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * // Allow multiple connections if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == - SOCKET_ERROR) { + SOCKET_ERROR) + { print_error("Cannot set REUSEADDR option"); return 0; } #ifdef SO_REUSEPORT if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) == - SOCKET_ERROR) { + SOCKET_ERROR) + { print_error("Cannot set REUSEPORT option"); } #endif @@ -284,7 +299,8 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * check_bind_in_directive = (bind(udpSocket, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr_in)) != 0); #endif - if (check_bind_in_directive) { + if (check_bind_in_directive) + { perror("Cannot bind socket\n"); return 0; } @@ -293,7 +309,8 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * ipMreq.imr_multiaddr.s_addr = inet_addr(ipAddress); ipMreq.imr_interface.s_addr = INADDR_ANY; if (setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ipMreq, - sizeof(ipMreq)) < 0) { + sizeof(ipMreq)) < 0) + { print_error( "Error setting socket options IP_ADD_MEMBERSHIP in udpStartReceiver"); return 0; @@ -309,37 +326,41 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * size_t ssize; pthread_attr_t attr; s = pthread_attr_init(&attr); - if (s != 0) { + if (s != 0) + { perror("pthread_attr_init"); return 0; } pthread_attr_getstacksize(&attr, &ssize); - if (ssize < EVENT_THREAD_STACK_SIZE_MIN) { + if (ssize < EVENT_THREAD_STACK_SIZE_MIN) + { s = pthread_attr_setstacksize(&attr, EVENT_THREAD_STACK_SIZE_MIN); - if (s != 0) { + if (s != 0) + { perror("pthread_attr_setstacksize"); return 0; } } s = pthread_create(&thread, &attr, handleMessage, (void *)currInfo); - if (s != 0) { + if (s != 0) + { perror("pthread_create"); return 0; } #ifdef CPU_SET - if(cpuMask != 0) + if (cpuMask != 0) { - cpu_set_t processorCpuSet; - unsigned int j; - CPU_ZERO(&processorCpuSet); - for (j = 0u; (j < (sizeof(cpuMask) * 8u)) && (j < CPU_SETSIZE); j++) - { - if (((cpuMask >> j) & 0x1u) == 0x1u) - { - CPU_SET(j, &processorCpuSet); - } + cpu_set_t processorCpuSet; + unsigned int j; + CPU_ZERO(&processorCpuSet); + for (j = 0u; (j < (sizeof(cpuMask) * 8u)) && (j < CPU_SETSIZE); j++) + { + if (((cpuMask >> j) & 0x1u) == 0x1u) + { + CPU_SET(j, &processorCpuSet); } - pthread_setaffinity_np(thread, sizeof(processorCpuSet), &processorCpuSet); + } + pthread_setaffinity_np(thread, sizeof(processorCpuSet), &processorCpuSet); } #endif } @@ -348,17 +369,17 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * return 1; } - int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), void *astprm, int *eventid) { - return MDSUdpEventAstMask(eventName, astadr, astprm, eventid, 0); + return MDSUdpEventAstMask(eventName, astadr, astprm, eventid, 0); } - -int MDSUdpEventCan(int eventid) { +int MDSUdpEventCan(int eventid) +{ EventList *ev = popEvent(eventid); - if (!ev) { + if (!ev) + { printf("invalid eventid %d\n", eventid); return 0; } @@ -386,13 +407,15 @@ int MDSUdpEventCan(int eventid) { static SOCKET send_socket = INVALID_SOCKET; static unsigned short sendPort = 0; static pthread_once_t send_socket_once = PTHREAD_ONCE_INIT; -static void send_socket_get() { +static void send_socket_get() +{ if ((send_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) print_error("Error creating socket"); UdpEventGetPort(&sendPort); } -int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) { +int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) +{ char multiIp[64]; uint32_t buflen_net_order = (uint32_t)htonl(bufLen); SOCKET udpSocket; @@ -438,17 +461,20 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) { setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); if (UdpEventGetLoop(&loop)) setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); - if (UdpEventGetInterface(&interface_addr)) { + if (UdpEventGetInterface(&interface_addr)) + { status = setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_IF, (char *)interface_addr, sizeof(*interface_addr)); free(interface_addr); } if (sendto(udpSocket, msg, msgLen, 0, (struct sockaddr *)&sin, sizeof(sin)) == - -1) { + -1) + { print_error("Error sending UDP message"); status = 0; - } else + } + else status = 1; free(msg); pthread_mutex_unlock(&sendEventMutex); diff --git a/mdsshr/librtl.c b/mdsshr/librtl.c index fb62f03d8d..23569a9556 100644 --- a/mdsshr/librtl.c +++ b/mdsshr/librtl.c @@ -43,8 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #endif @@ -68,7 +68,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define LIBRTL_SRC -typedef struct { +typedef struct +{ char *env; char *file; mdsdsc_t wild_descr; @@ -80,18 +81,21 @@ typedef struct { DIR *dir_ptr; } FindFileCtx; -typedef struct _VmList { +typedef struct _VmList +{ void *ptr; struct _VmList *next; } VmList; -typedef struct _ZoneList { +typedef struct _ZoneList +{ VmList *vm; struct _ZoneList *next; pthread_mutex_t lock; } ZoneList; -typedef struct node { +typedef struct node +{ void *left; void *right; short bal; @@ -108,14 +112,16 @@ typedef struct node { */ time_t ntimezone_; int daylight_; -inline static void tzset_() { +inline static void tzset_() +{ tzset(); ntimezone_ = -timezone; daylight_ = daylight; } #endif -static inline time_t get_tz_offset(time_t *const time) { +static inline time_t get_tz_offset(time_t *const time) +{ struct tm tmval; localtime_r(time, &tmval); #ifdef USE_TM_GMTOFF @@ -134,14 +140,16 @@ STATIC_CONSTANT int64_t VMS_TIME_OFFSET = LONG_LONG_CONSTANT(0x7c95674beb4000); /// \param secs the address of a constant floating point number representing the /// time to wait \return 1 if successful, 0 if failed or interrupted. /// -EXPORT int LibWait(const float *const secs) { +EXPORT int LibWait(const float *const secs) +{ struct timespec ts; ts.tv_sec = (unsigned int)*secs; ts.tv_nsec = (unsigned int)((*secs - (float)ts.tv_sec) * 1E9); return nanosleep(&ts, 0) == 0; } -EXPORT char *Now32(char *const buf) { +EXPORT char *Now32(char *const buf) +{ const time_t tim = time(0); ctime_r(&tim, buf); buf[strlen(buf) - 1] = '\0'; @@ -155,10 +163,12 @@ EXPORT char *Now32(char *const buf) { /// routine are supported. \param routine address of the routine to call \return /// the value returned by the routine as a void * /// -EXPORT void *LibCallg(void **const a, void *(*const routine)()) { +EXPORT void *LibCallg(void **const a, void *(*const routine)()) +{ if (!routine) abort(); // intercept definite stack corruption - switch (*(int *)a & 0xff) { + switch (*(int *)a & 0xff) + { case 0: return routine(); case 1: @@ -275,16 +285,19 @@ EXPORT void *LibCallg(void **const a, void *(*const routine)()) { } DEFINE_INITIALIZESOCKETS; -EXPORT uint32_t LibGetHostAddr(const char *const name) { +EXPORT uint32_t LibGetHostAddr(const char *const name) +{ INITIALIZESOCKETS; uint32_t addr = 0; struct addrinfo *entry, *info = NULL; const struct addrinfo hints = {0, AF_INET, SOCK_STREAM, 0, - 0, NULL, NULL, NULL}; - if (!getaddrinfo(name, NULL, &hints, &info)) { + 0, NULL, NULL, NULL}; + if (!getaddrinfo(name, NULL, &hints, &info)) + { for (entry = info; entry && !entry->ai_addr; entry = entry->ai_next) ; - if (entry) { + if (entry) + { const struct sockaddr_in *addrin = (struct sockaddr_in *)entry->ai_addr; addr = *(uint32_t *)&addrin->sin_addr; } @@ -296,15 +309,18 @@ EXPORT uint32_t LibGetHostAddr(const char *const name) { #ifdef _WIN32 -static char *GetRegistry(const HKEY where, const char *const pathname) { +static char *GetRegistry(const HKEY where, const char *const pathname) +{ HKEY regkey; unsigned char *path = NULL; if (RegOpenKeyEx(where, "SOFTWARE\\MIT\\MDSplus", 0, KEY_READ, ®key) == - ERROR_SUCCESS) { + ERROR_SUCCESS) + { unsigned long valtype; unsigned long valsize; if (RegQueryValueEx(regkey, pathname, 0, &valtype, NULL, &valsize) == - ERROR_SUCCESS) { + ERROR_SUCCESS) + { valsize += 2; path = malloc(valsize + 1); RegQueryValueEx(regkey, pathname, 0, &valtype, path, &valsize); @@ -315,7 +331,8 @@ static char *GetRegistry(const HKEY where, const char *const pathname) { } EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, - const int notifyFlag __attribute__((unused))) { + const int notifyFlag __attribute__((unused))) +{ if (MdsSandboxEnabled()) return MDSplusSANDBOX; char *cmd_c = MdsDescrToCstring(cmd); @@ -330,8 +347,10 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, arglist[3] = arglist[2]; arglist[4] = (void *)"/C"; arglist[5] = (void *)tok; - while ((tok = strtok(0, " ")) != 0) { - if (strlen(tok) > 0) { + while ((tok = strtok(0, " ")) != 0) + { + if (strlen(tok) > 0) + { arglist[numargs++] = (void *)tok; arglist[0] = numargs + NULL; } @@ -344,7 +363,8 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, #else /* _WIN32 */ -static char const *nonblank(const char *p) { +static char const *nonblank(const char *p) +{ if (!p) return (0); for (; *p && isspace(*p); p++) @@ -352,7 +372,8 @@ static char const *nonblank(const char *p) { return (*p ? p : 0); } -static void child_done(int sig) { +static void child_done(int sig) +{ if (sig == SIGCHLD) fprintf(stdout, "--> Process completed\n"); else @@ -362,7 +383,8 @@ static void child_done(int sig) { } EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, - const int notifyFlag) { + const int notifyFlag) +{ if (MdsSandboxEnabled()) return MDSplusSANDBOX; char *sh = "/bin/sh"; @@ -370,7 +392,8 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, char *cmdstring = MdsDescrToCstring(cmd); char *spawn_wrapper = TranslateLogical("MDSPLUS_SPAWN_WRAPPER"); int sts = 0; - if (spawn_wrapper) { + if (spawn_wrapper) + { char *oldcmdstring = cmdstring; cmdstring = strcpy(malloc(strlen(spawn_wrapper) + strlen(oldcmdstring) + 5), spawn_wrapper); @@ -381,11 +404,13 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, } signal(SIGCHLD, notifyFlag ? child_done : (waitFlag ? SIG_DFL : SIG_IGN)); pid = fork(); - if (!pid) { + if (!pid) + { /*-------------> child process: execute cmd */ char const *arglist[4]; int i = 0; - if (!waitFlag) { + if (!waitFlag) + { pid = fork(); if (pid != -1 && pid != 0) _exit(0); @@ -395,7 +420,8 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, if (arglist[0] == 0) arglist[0] = sh; i++; - if (cmd->length != 0) { + if (cmd->length != 0) + { arglist[i++] = "-c"; arglist[i++] = nonblank(cmdstring); } @@ -403,18 +429,21 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, sts = execvp(arglist[0], (char *const *)arglist); } /*-------------> parent process ... */ - if (pid == -1) { + if (pid == -1) + { fprintf(stderr, "Error %d from fork()\n", errno); return (0); } /* if (waitflag || cmd->length == 0) { */ - for (;;) { + for (;;) + { xpid = waitpid(pid, &sts, 0); if (xpid == pid) break; - else if (xpid == -1) { + else if (xpid == -1) + { if (errno != ECHILD) perror("Error during wait call"); break; @@ -430,7 +459,8 @@ EXPORT int LibSpawn(const mdsdsc_t *const cmd, const int waitFlag, #endif -EXPORT char *TranslateLogical(const char *const pathname) { +EXPORT char *TranslateLogical(const char *const pathname) +{ char *tpath = getenv(pathname); if (tpath) return strdup(tpath); @@ -446,12 +476,14 @@ EXPORT char *TranslateLogical(const char *const pathname) { } EXPORT int TranslateLogicalXd(const mdsdsc_t *const in, - mdsdsc_xd_t *const out) { + mdsdsc_xd_t *const out) +{ mdsdsc_t out_dsc = {0, DTYPE_T, CLASS_S, 0}; int status = 0; char *in_c = MdsDescrToCstring(in); char *out_c = TranslateLogical(in_c); - if (out_c) { + if (out_c) + { out_dsc.length = (uint16_t)strlen(out_c); out_dsc.pointer = out_c; status = 1; @@ -465,7 +497,8 @@ EXPORT int TranslateLogicalXd(const mdsdsc_t *const in, EXPORT void MdsFree(void *const ptr) { free(ptr); } -EXPORT char *MdsDescrToCstring(const mdsdsc_t *const in) { +EXPORT char *MdsDescrToCstring(const mdsdsc_t *const in) +{ char *out = malloc((size_t)in->length + 1); if (in->length > 0) memcpy(out, in->pointer, in->length); @@ -483,16 +516,23 @@ STATIC_THREADSAFE char *FIS_Error = ""; EXPORT char *LibFindImageSymbolErrString() { return FIS_Error; } static void *loadLib(const char *const dirspec, const char *const filename, - char *errorstr) { + char *errorstr) +{ void *handle = NULL; char *full_filename = alloca(strlen(dirspec) + strlen(filename) + 10); - if (strlen(dirspec) > 0) { - if (strchr(dirspec, '\\')) { + if (strlen(dirspec) > 0) + { + if (strchr(dirspec, '\\')) + { sprintf(full_filename, "%s\\%s", dirspec, filename); - } else { + } + else + { sprintf(full_filename, "%s/%s", dirspec, filename); } - } else { + } + else + { strcpy(full_filename, filename); } #ifndef _WIN32 @@ -500,7 +540,8 @@ static void *loadLib(const char *const dirspec, const char *const filename, if (!handle) #endif handle = dlopen(full_filename, RTLD_LAZY); - if (!handle) { + if (!handle) + { snprintf(errorstr + strlen(errorstr), 4096 - strlen(errorstr), "Error loading %s: %s\n", full_filename, dlerror()); } @@ -508,14 +549,16 @@ static void *loadLib(const char *const dirspec, const char *const filename, } EXPORT int LibFindImageSymbol_C(const char *const filename_in, - const char *const symbol, void **symbol_value) { + const char *const symbol, void **symbol_value) +{ int status; static pthread_mutex_t dlopen_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&dlopen_mutex); pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&dlopen_mutex); if (*symbol_value) // already loaded status = 1; - else { + else + { #ifdef _WIN32 const char *prefix = ""; const char delim = ';'; @@ -530,21 +573,26 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, errorstr[0] = '\0'; strcpy(filename, filename_in); if ((!(strchr(filename, '/') || strchr(filename, '\\'))) && - (strlen(prefix) > 0) && strncmp(filename_in, prefix, strlen(prefix))) { + (strlen(prefix) > 0) && strncmp(filename_in, prefix, strlen(prefix))) + { sprintf(filename, "%s%s", prefix, filename_in); } if (strcmp(filename + strlen(filename) - strlen(SHARELIB_TYPE), - SHARELIB_TYPE)) { + SHARELIB_TYPE)) + { strcat(filename, SHARELIB_TYPE); } handle = loadLib("", filename, errorstr); if (handle == NULL && (strchr(filename, '/') == 0) && - (strchr(filename, '\\') == 0)) { + (strchr(filename, '\\') == 0)) + { char *library_path = getenv("MDSPLUS_LIBRARY_PATH"); - if (library_path) { + if (library_path) + { size_t offset = 0; char *libpath = strdup(library_path); - while (offset < strlen(library_path)) { + while (offset < strlen(library_path)) + { char *dptr = strchr(libpath + offset, delim); if (dptr) *dptr = '\0'; @@ -555,30 +603,37 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, } free(libpath); } - if ((handle == NULL) && (delim == ':')) { + if ((handle == NULL) && (delim == ':')) + { char *mdir = getenv("MDSPLUS_DIR"); - if (mdir) { + if (mdir) + { char *libdir = alloca(strlen(mdir) + 10); sprintf(libdir, "%s/%s", mdir, "lib"); handle = loadLib(libdir, filename, errorstr); } } } - if (handle != NULL) { + if (handle != NULL) + { *symbol_value = dlsym(handle, symbol); - if (*symbol_value == NULL) { + if (*symbol_value == NULL) + { snprintf(errorstr + strlen(errorstr), 4096 - strlen(errorstr), "Error: %s\n", dlerror()); } } - if (strlen(FIS_Error) > 0) { + if (strlen(FIS_Error) > 0) + { free(FIS_Error); FIS_Error = ""; } - if (*symbol_value == NULL) { + if (*symbol_value == NULL) + { FIS_Error = strdup(errorstr); status = LibKEYNOTFOU; - } else + } + else status = 1; } pthread_cleanup_pop(1); @@ -587,7 +642,8 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, EXPORT int LibFindImageSymbol(const mdsdsc_t *const filename, const mdsdsc_t *const symbol, - void **const symbol_value) { + void **const symbol_value) +{ char *c_filename = MdsDescrToCstring(filename); char *c_symbol = MdsDescrToCstring(symbol); *symbol_value = NULL; // maintain previous behaviour @@ -597,35 +653,42 @@ EXPORT int LibFindImageSymbol(const mdsdsc_t *const filename, return status; } -EXPORT int StrConcat(mdsdsc_t *const out, ...) { +EXPORT int StrConcat(mdsdsc_t *const out, ...) +{ int i, nargs, len; mdsdsc_t *arglist[256]; VA_LIST_MDS_END_ARG(arglist, nargs, 0, 0, out); char *new; - if (out->class == CLASS_D) { + if (out->class == CLASS_D) + { len = 0; for (i = 0; i < nargs && arglist[i] && len < 0xFFFF; i++) len += (int)arglist[i]->length; if (len > 0xFFFF) return StrSTRTOOLON; new = malloc(len); - } else if (out->class == CLASS_S) + } + else if (out->class == CLASS_S) new = malloc(len = (int)out->length); else return LibINVSTRDES; // concat the strings char *p = new, *e = new + len, *p2, *e2; - for (i = 0; i < nargs && arglist[i] && p < e; i++) { + for (i = 0; i < nargs && arglist[i] && p < e; i++) + { p2 = arglist[i]->pointer; e2 = arglist[i]->pointer + (int)arglist[i]->length; while (p < e && p2 < e2) *p++ = *p2++; } - if (out->class == CLASS_S) { + if (out->class == CLASS_S) + { memcpy(out->pointer, new, p - new); memset(p, ' ', e - p); free(new); - } else { + } + else + { free(out->pointer); out->pointer = new; out->length = len; @@ -635,7 +698,8 @@ EXPORT int StrConcat(mdsdsc_t *const out, ...) { EXPORT int StrPosition(const mdsdsc_t *const source, const mdsdsc_t *const substring, - const int *const start) { + const int *const start) +{ char *source_c = MdsDescrToCstring(source); char *substring_c = MdsDescrToCstring(substring); char *search = source_c + ((start && *start > 0) ? (*start - 1) : 0); @@ -647,13 +711,15 @@ EXPORT int StrPosition(const mdsdsc_t *const source, } EXPORT int StrCopyR(mdsdsc_t *const out, const length_t *const len, - char *const in) { + char *const in) +{ const mdsdsc_t in_d = {*len, DTYPE_T, CLASS_S, in}; return StrCopyDx(out, &in_d); } EXPORT int StrLenExtr(mdsdsc_t *const out, const mdsdsc_t *const in, - const int *const start_in, const int *const len_in) { + const int *const start_in, const int *const len_in) +{ const length_t len = (length_t)((*len_in < 0) ? 0 : *len_in & 0xffff); const length_t start = (length_t)((*start_in > 1) ? (*start_in & 0xffff) - 1 : 0); @@ -670,7 +736,8 @@ EXPORT int StrLenExtr(mdsdsc_t *const out, const mdsdsc_t *const in, return status; } -EXPORT int StrGet1Dx(const length_t *const len, mdsdsc_d_t *const out) { +EXPORT int StrGet1Dx(const length_t *const len, mdsdsc_d_t *const out) +{ if (out->class != CLASS_D) return LibINVSTRDES; if (out->length == *len) @@ -685,7 +752,8 @@ EXPORT int StrGet1Dx(const length_t *const len, mdsdsc_d_t *const out) { int LibSFree1Dd(mdsdsc_d_t *const out) { return StrFree1Dx(out); } EXPORT int StrTrim(mdsdsc_t *const out, const mdsdsc_t *const in, - length_t *const lenout) { + length_t *const lenout) +{ mdsdsc_d_t tmp = {0, DTYPE_T, CLASS_D, 0}; mdsdsc_t s = {0, DTYPE_T, CLASS_S, 0}; uint16_t i; @@ -701,10 +769,12 @@ EXPORT int StrTrim(mdsdsc_t *const out, const mdsdsc_t *const in, return StrFree1Dx(&tmp); } -EXPORT int StrCopyDx(mdsdsc_t *const out, const mdsdsc_t *const in) { +EXPORT int StrCopyDx(mdsdsc_t *const out, const mdsdsc_t *const in) +{ if (out->class == CLASS_D && (in->length != out->length)) StrGet1Dx(&in->length, (mdsdsc_d_t *)out); - if (out->length && out->pointer != NULL) { + if (out->length && out->pointer != NULL) + { const length_t outlength = (out->class == CLASS_A) ? ((mdsdsc_a_t *)out)->arsize : out->length; const length_t inlength = @@ -720,7 +790,8 @@ EXPORT int StrCopyDx(mdsdsc_t *const out, const mdsdsc_t *const in) { return MDSplusSUCCESS; } -EXPORT int StrCompare(const mdsdsc_t *const str1, const mdsdsc_t *const str2) { +EXPORT int StrCompare(const mdsdsc_t *const str1, const mdsdsc_t *const str2) +{ const int len = str1->length < str2->length ? str1->length : str2->length; const int ans = strncmp(str1->pointer, str2->pointer, len); if (ans) @@ -733,7 +804,8 @@ EXPORT int StrCompare(const mdsdsc_t *const str1, const mdsdsc_t *const str2) { } EXPORT int StrCaseBlindCompare(const mdsdsc_t *const str1, - const mdsdsc_t *const str2) { + const mdsdsc_t *const str2) +{ const int len = str1->length < str2->length ? str1->length : str2->length; const int ans = strncasecmp(str1->pointer, str2->pointer, len); if (ans) @@ -745,10 +817,11 @@ EXPORT int StrCaseBlindCompare(const mdsdsc_t *const str1, return 0; } -EXPORT int StrUpcase(mdsdsc_t *const out, const mdsdsc_t *const in) { +EXPORT int StrUpcase(mdsdsc_t *const out, const mdsdsc_t *const in) +{ int status = StrCopyDx(out, in); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; const int outlength = (out->class == CLASS_A) ? ((mdsdsc_a_t *)out)->arsize : out->length; int i; @@ -758,7 +831,8 @@ EXPORT int StrUpcase(mdsdsc_t *const out, const mdsdsc_t *const in) { } EXPORT int StrRight(mdsdsc_t *const out, const mdsdsc_t *const in, - const length_t *const start) { + const length_t *const start) +{ mdsdsc_d_t tmp = {0, DTYPE_T, CLASS_D, 0}; mdsdsc_t s = {0, DTYPE_T, CLASS_S, 0}; StrCopyDx((mdsdsc_t *)&tmp, in); @@ -769,17 +843,18 @@ EXPORT int StrRight(mdsdsc_t *const out, const mdsdsc_t *const in, } static pthread_mutex_t zones_lock = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_ZONES \ - pthread_mutex_lock(&zones_lock); \ +#define LOCK_ZONES \ + pthread_mutex_lock(&zones_lock); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &zones_lock) #define UNLOCK_ZONES pthread_cleanup_pop(1); ZoneList *MdsZones = NULL; -#define LOCK_ZONE(zone) \ - pthread_mutex_lock(&(zone)->lock); \ +#define LOCK_ZONE(zone) \ + pthread_mutex_lock(&(zone)->lock); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &(zone)->lock) #define UNLOCK_ZONE(zone) pthread_cleanup_pop(1); -EXPORT int LibCreateVmZone(ZoneList **const zone) { +EXPORT int LibCreateVmZone(ZoneList **const zone) +{ ZoneList *list; *zone = malloc(sizeof(ZoneList)); (*zone)->vm = NULL; @@ -788,7 +863,8 @@ EXPORT int LibCreateVmZone(ZoneList **const zone) { LOCK_ZONES; if (MdsZones == NULL) MdsZones = *zone; - else { + else + { for (list = MdsZones; list->next; list = list->next) ; list->next = *zone; @@ -797,25 +873,31 @@ EXPORT int LibCreateVmZone(ZoneList **const zone) { return (*zone != NULL); } -EXPORT int LibDeleteVmZone(ZoneList **const zone) { +EXPORT int LibDeleteVmZone(ZoneList **const zone) +{ int found; ZoneList *list, *prev; LibResetVmZone(zone); LOCK_ZONES; found = 0; - if (*zone == MdsZones) { + if (*zone == MdsZones) + { found = 1; MdsZones = (*zone)->next; - } else { + } + else + { for (prev = 0, list = MdsZones; list && list != *zone; prev = list, list = list->next) ; - if (list && prev) { + if (list && prev) + { prev->next = list->next; found = 1; } } - if (found) { + if (found) + { free(*zone); *zone = 0; } @@ -823,14 +905,17 @@ EXPORT int LibDeleteVmZone(ZoneList **const zone) { return found; } -EXPORT int LibResetVmZone(ZoneList **const zone) { - if (zone && *zone) { +EXPORT int LibResetVmZone(ZoneList **const zone) +{ + if (zone && *zone) + { VmList *vm, *_vm; LOCK_ZONE(*zone); vm = (*zone)->vm; (*zone)->vm = NULL; UNLOCK_ZONE(*zone); - while (vm) { + while (vm) + { free(vm->ptr); _vm = vm; vm = _vm->next; @@ -844,15 +929,18 @@ EXPORT int LibResetVmZone(ZoneList **const zone) { #pragma GCC diagnostic ignored "-Wclobbered" EXPORT int LibFreeVm(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ VmList *list = NULL; - if (zone) { + if (zone) + { LOCK_ZONE(*zone); VmList *prev; for (prev = NULL, list = (*zone)->vm; list && (list->ptr != *vm); prev = list, list = list->next) ; - if (list) { + if (list) + { if (prev) prev->next = list->next; else @@ -868,22 +956,27 @@ EXPORT int LibFreeVm(const uint32_t *const len, void **const vm, #pragma GCC diagnostic pop EXPORT int libfreevm_(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ return LibFreeVm(len, vm, zone); } EXPORT int libfreevm(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ return LibFreeVm(len, vm, zone); } EXPORT int LibGetVm(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ *vm = malloc(*len); - if (*vm == NULL) { + if (*vm == NULL) + { printf("Insufficient virtual memory\n"); return LibINSVIRMEM; } - if (zone) { + if (zone) + { VmList *list = malloc(sizeof(VmList)); list->ptr = *vm; LOCK_ZONE(*zone); @@ -894,11 +987,13 @@ EXPORT int LibGetVm(const uint32_t *const len, void **const vm, return MDSplusSUCCESS; } EXPORT int libgetvm_(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ return LibGetVm(len, vm, zone); } EXPORT int libgetvm(const uint32_t *const len, void **const vm, - ZoneList **const zone) { + ZoneList **const zone) +{ return LibGetVm(len, vm, zone); } @@ -909,28 +1004,38 @@ EXPORT int libgetvm(const uint32_t *const len, void **const vm, #define SEC_PER_DAY (60 * 60 * 24) -EXPORT int LibConvertDateString(const char *asc_time, int64_t *const qtime) { +EXPORT int LibConvertDateString(const char *asc_time, int64_t *const qtime) +{ time_t tim = 0; char time_out[24]; int parse_it = 1; int ctime_it = 0; /* VMS time = unixtime * 10,000,000 + 0x7c95674beb4000q */ - if (asc_time == 0 || strcasecmp(asc_time, "now") == 0) { + if (asc_time == 0 || strcasecmp(asc_time, "now") == 0) + { tim = time(NULL); parse_it = 0; - } else if (strcasecmp(asc_time, "today") == 0) { + } + else if (strcasecmp(asc_time, "today") == 0) + { tim = time(NULL); ctime_it = 1; - } else if (strcasecmp(asc_time, "tomorrow") == 0) { + } + else if (strcasecmp(asc_time, "tomorrow") == 0) + { tim = time(NULL) + SEC_PER_DAY; ctime_it = 1; - } else if (strcasecmp(asc_time, "yesterday") == 0) { + } + else if (strcasecmp(asc_time, "yesterday") == 0) + { tim = time(NULL) - SEC_PER_DAY; ctime_it = 1; } - if (parse_it) { - if (ctime_it) { + if (parse_it) + { + if (ctime_it) + { char time_str[32]; ctime_r(&tim, time_str); time_out[0] = time_str[8]; @@ -969,12 +1074,15 @@ EXPORT int LibConvertDateString(const char *asc_time, int64_t *const qtime) { char *months[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; if (sscanf(asc_time, "%u-%3s-%u %u:%u:%u", &day, month, &year, &hour, - &minute, &second) < 6) { + &minute, &second) < 6) + { return 0; } _strupr(month); - for (tm.tm_mon = 0; tm.tm_mon < 12; tm.tm_mon++) { - if (strcmp(month, months[tm.tm_mon]) == 0) { + for (tm.tm_mon = 0; tm.tm_mon < 12; tm.tm_mon++) + { + if (strcmp(month, months[tm.tm_mon]) == 0) + { break; } } @@ -1003,7 +1111,8 @@ EXPORT int LibConvertDateString(const char *asc_time, int64_t *const qtime) { } EXPORT int LibTimeToVMSTime(const time_t *const time_in, - int64_t *const time_out) { + int64_t *const time_out) +{ time_t time_to_use = time_in ? *time_in : time(NULL); struct timeval tv; if (time_in) @@ -1016,10 +1125,12 @@ EXPORT int LibTimeToVMSTime(const time_t *const time_in, return MDSplusSUCCESS; } -EXPORT time_t LibCvtTim(const int *const time_in, double *const t) { +EXPORT time_t LibCvtTim(const int *const time_in, double *const t) +{ double t_out; time_t bintim = time(&bintim); - if (time_in) { + if (time_in) + { int64_t time_local; double time_d; memcpy(&time_local, time_in, sizeof(time_local)); @@ -1032,7 +1143,8 @@ EXPORT time_t LibCvtTim(const int *const time_in, double *const t) { time_t tz_offset = get_tz_offset(&bintim); t_out = (time_d > 0 ? time_d : 0.0) - (double)tz_offset; bintim -= tz_offset; - } else + } + else bintim = (long)(t_out = (double)time(0)); if (t != 0) *t = t_out; @@ -1040,7 +1152,8 @@ EXPORT time_t LibCvtTim(const int *const time_in, double *const t) { } EXPORT int LibSysAscTim(length_t *const len, mdsdsc_t *const str, - const int *const time_in) { + const int *const time_in) +{ char time_out[24]; uint16_t slen = sizeof(time_out) - 1; time_t bintim = LibCvtTim(time_in, 0); @@ -1048,7 +1161,8 @@ EXPORT int LibSysAscTim(length_t *const len, mdsdsc_t *const str, char time_str[32]; time_str[0] = '\0'; ctime_r(&bintim, time_str); - if (strlen(time_str) > 18) { + if (strlen(time_str) > 18) + { time_out[0] = time_str[8]; time_out[1] = time_str[9]; time_out[2] = '-'; @@ -1073,7 +1187,8 @@ EXPORT int LibSysAscTim(length_t *const len, mdsdsc_t *const str, time_out[21] = (char)('0' + chunks / 1000000); time_out[22] = (char)('0' + (chunks % 1000000) / 100000); time_out[23] = 0; - } else + } + else strcpy(time_out, "\?\?-\?\?\?-\?\?\?\? \?\?:\?\?:\?\?.\?\?"); StrCopyR(str, &slen, time_out); if (len) @@ -1088,17 +1203,22 @@ EXPORT int LibSysAscTim(length_t *const len, mdsdsc_t *const str, // return 1; //} -EXPORT int StrAppend(mdsdsc_d_t *const out, const mdsdsc_t *const tail) { - if (tail->length > 0 && tail->pointer) { +EXPORT int StrAppend(mdsdsc_d_t *const out, const mdsdsc_t *const tail) +{ + if (tail->length > 0 && tail->pointer) + { int len = (int)out->length + (int)tail->length; if (len > 0xffff) return StrSTRTOOLON; char *old = out->pointer; out->pointer = realloc(out->pointer, len); - if (out->pointer) { + if (out->pointer) + { memcpy(out->pointer + out->length, tail->pointer, tail->length); out->length = len; - } else { + } + else + { out->pointer = old; return LibINSVIRMEM; } @@ -1106,8 +1226,10 @@ EXPORT int StrAppend(mdsdsc_d_t *const out, const mdsdsc_t *const tail) { return MDSplusSUCCESS; } -EXPORT int StrFree1Dx(mdsdsc_d_t *const out) { - if (out->class == CLASS_D) { +EXPORT int StrFree1Dx(mdsdsc_d_t *const out) +{ + if (out->class == CLASS_D) + { free(out->pointer); out->pointer = NULL; out->length = 0; @@ -1116,9 +1238,11 @@ EXPORT int StrFree1Dx(mdsdsc_d_t *const out) { } EXPORT int StrFindFirstNotInSet(const mdsdsc_t *const source, - const mdsdsc_t *const set) { + const mdsdsc_t *const set) +{ int ans = 0; - if (source->length > 0) { + if (source->length > 0) + { char *src = MdsDescrToCstring(source); char *s = MdsDescrToCstring(set); size_t tmp; @@ -1131,9 +1255,11 @@ EXPORT int StrFindFirstNotInSet(const mdsdsc_t *const source, } EXPORT int StrFindFirstInSet(const mdsdsc_t *const source, - const mdsdsc_t *const set) { + const mdsdsc_t *const set) +{ int ans = 0; - if (source->length > 0) { + if (source->length > 0) + { char *src = MdsDescrToCstring(source); char *s = MdsDescrToCstring(set); char *tmp; @@ -1145,7 +1271,8 @@ EXPORT int StrFindFirstInSet(const mdsdsc_t *const source, return ans; } -struct bbtree_info { +struct bbtree_info +{ struct node *currentnode; char *keyname; int (*compare_routine)(); @@ -1161,7 +1288,8 @@ static int MdsInsertTree(); EXPORT int LibInsertTree(LibTreeNode **const treehead, void *const symbol_ptr, int *const control_flags, int (*const compare_rtn)(), int (*const alloc_rtn)(), - LibTreeNode **const blockaddr, void *const user_data) { + LibTreeNode **const blockaddr, void *const user_data) +{ struct bbtree_info bbtree; bbtree.currentnode = *treehead; bbtree.keyname = symbol_ptr; @@ -1178,7 +1306,8 @@ EXPORT int LibInsertTree(LibTreeNode **const treehead, void *const symbol_ptr, return bbtree.foundintree; } -static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { +static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) +{ #define currentNode (bbtree_ptr->currentnode) #define ALLOCATE (*(bbtree_ptr->alloc_routine)) @@ -1191,7 +1320,8 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { struct node *down_left; struct node *down_right; - if (currentNode == 0) { + if (currentNode == 0) + { if (!(ALLOCATE(bbtree_ptr->keyname, &save_current, bbtree_ptr->user_context) & 1)) @@ -1206,8 +1336,10 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { } save_current = currentNode; if ((in_balance = (*(bbtree_ptr->compare_routine))( - bbtree_ptr->keyname, currentNode, bbtree_ptr->user_context)) <= 0) { - if ((in_balance == 0) && (!(bbtree_ptr->controlflags & 1))) { + bbtree_ptr->keyname, currentNode, bbtree_ptr->user_context)) <= 0) + { + if ((in_balance == 0) && (!(bbtree_ptr->controlflags & 1))) + { bbtree_ptr->new_node = save_current; bbtree_ptr->foundintree = 3; return MDSplusSUCCESS; @@ -1221,22 +1353,27 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { currentNode->left = offset_of(currentNode, down_left); if (in_balance) return MDSplusSUCCESS; - else { + else + { currentNode->bal--; if (currentNode->bal == 0) return MDSplusSUCCESS; - else { + else + { if (currentNode->bal & 1) return MDSplusERROR; down_left = left_of(currentNode); - if (down_left->bal < 0) { + if (down_left->bal < 0) + { currentNode->left = offset_of(currentNode, right_of(down_left)); down_left->right = offset_of(down_left, currentNode); currentNode->bal = 0; currentNode = down_left; currentNode->bal = 0; return MDSplusSUCCESS; - } else { + } + else + { down_right = right_of(down_left); down_left->right = offset_of(down_left, left_of(down_right)); down_right->left = offset_of(down_right, down_left); @@ -1254,7 +1391,9 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { } } } - } else { + } + else + { currentNode = right_of(currentNode); in_balance = MdsInsertTree(bbtree_ptr); if ((bbtree_ptr->foundintree == 3) || (bbtree_ptr->foundintree == 0)) @@ -1264,22 +1403,27 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { currentNode->right = offset_of(currentNode, down_right); if (in_balance) return MDSplusSUCCESS; - else { + else + { currentNode->bal++; if (currentNode->bal == 0) return MDSplusSUCCESS; - else { + else + { if (currentNode->bal & 1) return MDSplusERROR; down_right = right_of(currentNode); - if (down_right->bal > 0) { + if (down_right->bal > 0) + { currentNode->right = offset_of(currentNode, left_of(down_right)); down_right->left = offset_of(down_right, currentNode); currentNode->bal = 0; currentNode = down_right; currentNode->bal = 0; return MDSplusSUCCESS; - } else { + } + else + { down_left = left_of(down_right); down_right->left = offset_of(down_right, right_of(down_left)); down_left->right = offset_of(down_left, down_right); @@ -1304,14 +1448,18 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) { EXPORT int LibLookupTree(LibTreeNode **const treehead, void *const symbol_ptr, int (*const compare_rtn)(), - LibTreeNode **const blockaddr) { + LibTreeNode **const blockaddr) +{ int ch_result; struct node *currentnode = *treehead; - while (currentnode != 0) { - if ((ch_result = compare_rtn(symbol_ptr, currentnode)) == 0) { + while (currentnode != 0) + { + if ((ch_result = compare_rtn(symbol_ptr, currentnode)) == 0) + { *blockaddr = currentnode; return MDSplusSUCCESS; - } else if (ch_result < 0) + } + else if (ch_result < 0) currentnode = left_of(currentnode); else currentnode = right_of(currentnode); @@ -1321,35 +1469,41 @@ EXPORT int LibLookupTree(LibTreeNode **const treehead, void *const symbol_ptr, inline static int MdsTraverseTree(int (*const user_rtn)(), void *const user_data, - struct node *const currentnode) { + struct node *const currentnode) +{ struct node *right_subtree; int status; if (currentnode == 0) return MDSplusSUCCESS; - if (left_of(currentnode)) { + if (left_of(currentnode)) + { status = MdsTraverseTree(user_rtn, user_data, left_of(currentnode)); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } right_subtree = right_of(currentnode); status = user_rtn(currentnode, user_data); - if - STATUS_NOT_OK return status; - if (right_subtree) { + if (STATUS_NOT_OK) + return status; + if (right_subtree) + { status = MdsTraverseTree(user_rtn, user_data, right_subtree); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } return MDSplusSUCCESS; } EXPORT int LibTraverseTree(LibTreeNode **treehead, int (*user_rtn)(), - void *user_data) { + void *user_data) +{ return MdsTraverseTree(user_rtn, user_data, *treehead); } static int match_wild(const char *const cand_ptr, const int cand_len, - const char *const pat_ptr, const int pat_len) { - struct descr { + const char *const pat_ptr, const int pat_len) +{ + struct descr + { const char *ptr; int length; }; @@ -1358,33 +1512,45 @@ static int match_wild(const char *const cand_ptr, const int cand_len, struct descr pat = {pat_ptr, pat_len}; struct descr spat = pat; char pc; - for (;;) { - if (--pat.length < 0) { + for (;;) + { + if (--pat.length < 0) + { if (cand.length == 0) return TRUE; - else { + else + { if (--scand.length < 0) return FALSE; - else { + else + { scand.ptr++; cand = scand; pat = spat; } } - } else { - if ((pc = *pat.ptr++) == '*') { + } + else + { + if ((pc = *pat.ptr++) == '*') + { if (pat.length == 0) return TRUE; scand = cand; spat = pat; - } else { + } + else + { if (--cand.length < 0) return FALSE; - if (*cand.ptr++ != pc) { - if (pc != '%') { + if (*cand.ptr++ != pc) + { + if (pc != '%') + { if (--scand.length < 0) return FALSE; - else { + else + { scand.ptr++; cand = scand; pat = spat; @@ -1398,7 +1564,8 @@ static int match_wild(const char *const cand_ptr, const int cand_len, } EXPORT int StrMatchWild(const mdsdsc_t *const candidate, - const mdsdsc_t *const pattern) { + const mdsdsc_t *const pattern) +{ if (match_wild(candidate->pointer, candidate->length, pattern->pointer, pattern->length)) return StrMATCH; @@ -1406,7 +1573,8 @@ EXPORT int StrMatchWild(const mdsdsc_t *const candidate, } EXPORT int StrElement(mdsdsc_t *const out, const int *const num, - const mdsdsc_t *const delim, const mdsdsc_t *const in) { + const mdsdsc_t *const delim, const mdsdsc_t *const in) +{ char *in_ptr = in->pointer; char *se_ptr = in_ptr + in->length; char *e_ptr; @@ -1429,12 +1597,15 @@ EXPORT int StrElement(mdsdsc_t *const out, const int *const num, } EXPORT int StrTranslate(mdsdsc_t *const out, const mdsdsc_t *const in, - const mdsdsc_t *const tran, mdsdsc_t *const match) { + const mdsdsc_t *const tran, mdsdsc_t *const match) +{ int status = 0; - if (in->class == CLASS_S || in->class == CLASS_D) { + if (in->class == CLASS_S || in->class == CLASS_D) + { char *dst = (char *)malloc(in->length); int i; - for (i = 0; i < in->length; i++) { + for (i = 0; i < in->length; i++) + { int j; int next = 1; for (j = 0; next && j < match->length; j += next) @@ -1444,10 +1615,12 @@ EXPORT int StrTranslate(mdsdsc_t *const out, const mdsdsc_t *const in, } status = StrCopyR(out, &in->length, dst); free(dst); - } else if ((in->class == CLASS_A) && (out->class == CLASS_A) && - (in->length > 0) && (out->length > 0) && - (((mdsdsc_a_t *)in)->arsize / in->length == - ((mdsdsc_a_t *)out)->arsize / out->length)) { + } + else if ((in->class == CLASS_A) && (out->class == CLASS_A) && + (in->length > 0) && (out->length > 0) && + (((mdsdsc_a_t *)in)->arsize / in->length == + ((mdsdsc_a_t *)out)->arsize / out->length)) + { mdsdsc_t outdsc = {0, DTYPE_T, CLASS_S, 0}; mdsdsc_t indsc = {0, DTYPE_T, CLASS_S, 0}; uint32_t num = ((mdsdsc_a_t *)in)->arsize / in->length; @@ -1465,7 +1638,8 @@ EXPORT int StrTranslate(mdsdsc_t *const out, const mdsdsc_t *const in, EXPORT int StrReplace(mdsdsc_t *const out, const mdsdsc_t *const in, const int *const start_idx, const int *const end_idx, - const mdsdsc_t *const rep) { + const mdsdsc_t *const rep) +{ int status; int start; int end; @@ -1504,11 +1678,13 @@ EXPORT int StrReplace(mdsdsc_t *const out, const mdsdsc_t *const in, #define FILE_INFO struct dirent * #endif -typedef struct { +typedef struct +{ DIR_HND *h; size_t wlen; } findstack_t; -typedef struct { +typedef struct +{ findstack_t *stack; int cur_stack; int max_stack; @@ -1532,13 +1708,16 @@ typedef struct { #define FILENAME(ctx) ctx->fd.cFileName #define ISDIRECTORY(ctx) (ctx->fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) #define REALLOCBUF(ctx, extra) -static inline void FINDFILECLOSE_OS(const ctx_t *const ctx) { +static inline void FINDFILECLOSE_OS(const ctx_t *const ctx) +{ FindClose(ctx->stack[ctx->cur_stack].h); } -static inline int FINDFILENEXT_OS(ctx_t *const ctx) { +static inline int FINDFILENEXT_OS(ctx_t *const ctx) +{ return FindNextFile(ctx->stack[ctx->cur_stack].h, &ctx->fd); } -static inline int FINDFILEFIRST_OS(ctx_t *const ctx) { +static inline int FINDFILEFIRST_OS(ctx_t *const ctx) +{ ctx->stack[ctx->cur_stack].h = FindFirstFile(ctx->buffer, &ctx->fd); return ctx->stack[ctx->cur_stack].h != INVALID_HANDLE_VALUE; } @@ -1549,36 +1728,44 @@ static inline int FINDFILEFIRST_OS(ctx_t *const ctx) { #define INVALID_HANDLE_VALUE NULL #define MAX_PATH 1 // at least fit empty string #define FILENAME(ctx) ctx->fd->d_name -static inline void REALLOCBUF(ctx_t *const ctx, const size_t extra) { +static inline void REALLOCBUF(ctx_t *const ctx, const size_t extra) +{ const size_t required = ctx->stack[ctx->cur_stack].wlen + extra; if (ctx->buflen >= required) return; char *newbuf = realloc(ctx->buffer, required); - if (newbuf) { + if (newbuf) + { ctx->buffer = newbuf; ctx->buflen = required; } } #include -static inline int ISDIRECTORY(const ctx_t *const ctx) { +static inline int ISDIRECTORY(const ctx_t *const ctx) +{ struct stat statbuf; if (stat(ctx->buffer, &statbuf) != 0) return FALSE; return S_ISDIR(statbuf.st_mode); } -static inline void FINDFILECLOSE_OS(const ctx_t *const ctx) { +static inline void FINDFILECLOSE_OS(const ctx_t *const ctx) +{ closedir(ctx->stack[ctx->cur_stack].h); } -static inline int FINDFILENEXT_OS(ctx_t *const ctx) { +static inline int FINDFILENEXT_OS(ctx_t *const ctx) +{ return (ctx->fd = readdir(ctx->stack[ctx->cur_stack].h)) != NULL; } -static inline int FINDFILEFIRST_OS(ctx_t *const ctx) { +static inline int FINDFILEFIRST_OS(ctx_t *const ctx) +{ ctx->stack[ctx->cur_stack].h = opendir(ctx->buffer); - if (!ctx->stack[ctx->cur_stack].h) { + if (!ctx->stack[ctx->cur_stack].h) + { ctx->cur_stack--; return FALSE; } - if (!FINDFILENEXT_OS(ctx)) { + if (!FINDFILENEXT_OS(ctx)) + { FINDFILECLOSE_OS(ctx); ctx->cur_stack--; return FALSE; @@ -1588,14 +1775,18 @@ static inline int FINDFILEFIRST_OS(ctx_t *const ctx) { #endif -static int findfileloopstart(ctx_t *const ctx) { +static int findfileloopstart(ctx_t *const ctx) +{ ctx->buffer[ctx->stack[ctx->cur_stack].wlen++] = SEP; #ifdef _WIN32 // after this wlen will mark the last SEP so we can simply attach the filename - if (ctx->recursive) { // append "\\*\0" + if (ctx->recursive) + { // append "\\*\0" ctx->buffer[ctx->stack[ctx->cur_stack].wlen] = '*'; ctx->buffer[ctx->stack[ctx->cur_stack].wlen + 1] = '\0'; - } else { // append "/\0" + } + else + { // append "/\0" // Windows will find he file much faster char *p; memcpy(p = ctx->buffer + ctx->stack[ctx->cur_stack].wlen, ctx->filename, @@ -1611,13 +1802,17 @@ static int findfileloopstart(ctx_t *const ctx) { return FINDFILEFIRST_OS(ctx); } -static size_t findfileloop(ctx_t *const ctx) { - if (ctx->stack[ctx->cur_stack].h == INVALID_HANDLE_VALUE) { +static size_t findfileloop(ctx_t *const ctx) +{ + if (ctx->stack[ctx->cur_stack].h == INVALID_HANDLE_VALUE) + { if (!findfileloopstart(ctx)) return 0; - } else if (!FINDFILENEXT_OS(ctx)) + } + else if (!FINDFILENEXT_OS(ctx)) goto close; - do { + do + { if (strcmp(FILENAME(ctx), ".") == 0 || strcmp(FILENAME(ctx), "..") == 0) continue; size_t flen = strlen(FILENAME(ctx)); @@ -1625,16 +1820,19 @@ static size_t findfileloop(ctx_t *const ctx) { flen + 2); // +2 for "/\0" - would be +3 for win but MAX_PATH memcpy(ctx->buffer + ctx->stack[ctx->cur_stack].wlen, FILENAME(ctx), flen + 1); - if (ctx->case_blind) { + if (ctx->case_blind) + { char *p; for (p = FILENAME(ctx); *p; p++) *p = toupper(*p); } if (match_wild(FILENAME(ctx), flen, ctx->filename, ctx->flen)) return ctx->stack[ctx->cur_stack].wlen + flen; - if (ctx->recursive && ISDIRECTORY(ctx)) { + if (ctx->recursive && ISDIRECTORY(ctx)) + { // DBG("path = %s\n", ctx->buffer); - if (++ctx->cur_stack == ctx->max_stack) { + if (++ctx->cur_stack == ctx->max_stack) + { DBG("max_stack increased = %d\n", ctx->max_stack); findstack_t *old = ctx->stack; ctx->max_stack *= 2; @@ -1658,18 +1856,22 @@ static size_t findfileloop(ctx_t *const ctx) { static inline void *_findfilestart(const char *const envname, const char *const filename, - const int recursive, const int case_blind) { + const int recursive, const int case_blind) +{ DBG("looking for '%s' in '%s'\n", filename, envname); ctx_t *ctx = (ctx_t *)malloc(sizeof(ctx_t)); ctx->max_stack = recursive ? 8 : 1; ctx->stack = malloc(ctx->max_stack * sizeof(findstack_t)); ctx->cur_stack = -1; char *folders; - if (envname && (folders = getenv(envname))) { + if (envname && (folders = getenv(envname))) + { ctx->folders = strdup(folders); *(size_t *)&ctx->flen = strlen(filename); ctx->filename = memcpy(malloc(ctx->flen + 1), filename, ctx->flen + 1); - } else { + } + else + { const size_t tlen = strlen(filename); char *tmp = memcpy(malloc(tlen + 1), filename, tlen + 1); #ifdef _WIN32 @@ -1681,13 +1883,16 @@ static inline void *_findfilestart(const char *const envname, char *p, *c; for (c = tmp, p = NULL; (c = strchr(c, SEP)); p = c, c = p + 1) ; - if (p) { // look in specified path + if (p) + { // look in specified path *(char *)p = '\0'; const size_t flen = p - tmp + 1; *(size_t *)&ctx->flen = tlen - flen; ctx->filename = strdup(p + 1); ctx->folders = realloc(tmp, flen); - } else { // look in current folder only + } + else + { // look in current folder only *(size_t *)&ctx->flen = tlen; ctx->filename = tmp; ctx->folders = calloc(1, 1); @@ -1700,7 +1905,8 @@ static inline void *_findfilestart(const char *const envname, ctx->recursive = recursive; ctx->case_blind = case_blind; ctx->cptr = ctx->ptr = ctx->folders; - if (ctx->case_blind) { + if (ctx->case_blind) + { char *p; for (p = (char *)ctx->filename; *p; p++) *p = toupper(*p); @@ -1709,14 +1915,18 @@ static inline void *_findfilestart(const char *const envname, } static inline void *findfilestart(const char *const filename, - const int recursive, const int case_blind) { + const int recursive, const int case_blind) +{ char *env; const char *colon = strchr(filename, ':'); - if (colon) { + if (colon) + { size_t envlen = (colon++ - filename); env = memcpy(malloc(envlen + 1), filename, envlen); env[envlen] = '\0'; - } else { + } + else + { env = NULL; colon = filename; } @@ -1729,19 +1939,23 @@ static inline void *findfilestart(const char *const filename, return ctx; } -static inline char *findfilenext(ctx_t *const ctx) { +static inline char *findfilenext(ctx_t *const ctx) +{ if (ctx->cur_stack >= 0) - do { + do + { if (findfileloop(ctx) > 0) return ctx->buffer; } while (ctx->cur_stack >= 0); if (ctx->cur_stack != -1) fprintf(stderr, "ctx_stack = %d != -1\n", ctx->cur_stack); - while (ctx->cptr) { + while (ctx->cptr) + { const size_t wlen = ((ctx->cptr = strchr(ctx->ptr, ';')) == NULL) ? (int)strlen(ctx->ptr) : (int)(ctx->cptr - ctx->ptr); - if (wlen == 0) { + if (wlen == 0) + { ctx->ptr = ctx->cptr + 1; // set ptr to start of next path continue; // if path empty, skip } @@ -1760,7 +1974,8 @@ static inline char *findfilenext(ctx_t *const ctx) { // allow current path , i.e. wlen = 0 if (ctx->stack[ctx->cur_stack].wlen == 0) ctx->buffer[ctx->stack[ctx->cur_stack].wlen++] = '.'; - else { + else + { // ensure buffer is not terminated by SEP while (ctx->stack[ctx->cur_stack].wlen > 0 && ctx->buffer[ctx->stack[ctx->cur_stack].wlen - 1] == SEP) @@ -1774,11 +1989,13 @@ static inline char *findfilenext(ctx_t *const ctx) { return NULL; } -static inline void findfileend(void *const ctx_i) { +static inline void findfileend(void *const ctx_i) +{ if (!ctx_i) return; ctx_t *ctx = (ctx_t *)ctx_i; - while (ctx->cur_stack >= 0) { + while (ctx->cur_stack >= 0) + { FINDFILECLOSE_OS(ctx); ctx->cur_stack--; } @@ -1789,7 +2006,8 @@ static inline void findfileend(void *const ctx_i) { free(ctx); } -EXPORT extern int LibFindFileEnd(void **const ctx) { +EXPORT extern int LibFindFileEnd(void **const ctx) +{ findfileend(*ctx); *ctx = NULL; return MDSplusSUCCESS; @@ -1797,12 +2015,14 @@ EXPORT extern int LibFindFileEnd(void **const ctx) { static int find_file(const mdsdsc_t *const filespec, mdsdsc_t *const result, void **const ctx, const int recursively, - int const case_blind) { + int const case_blind) +{ #ifdef DEBUG clock_t start = clock(); #endif int status; - if (*ctx == 0) { + if (*ctx == 0) + { char *fspec = malloc(filespec->length + 1); memcpy(fspec, filespec->pointer, filespec->length); fspec[filespec->length] = '\0'; @@ -1815,11 +2035,14 @@ static int find_file(const mdsdsc_t *const filespec, mdsdsc_t *const result, return MDSplusERROR; } char *ans = findfilenext(*(ctx_t **)ctx); - if (ans) { + if (ans) + { mdsdsc_t ansd = {strlen(ans), DTYPE_T, CLASS_S, ans}; StrCopyDx(result, &ansd); status = MDSplusSUCCESS; - } else { + } + else + { status = MDSplusERROR; LibFindFileEnd(ctx); } @@ -1831,18 +2054,21 @@ static int find_file(const mdsdsc_t *const filespec, mdsdsc_t *const result, } EXPORT int LibFindFile(const mdsdsc_t *const filespec, mdsdsc_t *const result, - void **const ctx) { + void **const ctx) +{ return find_file(filespec, result, ctx, 0, 0); } EXPORT int LibFindFileRecurseCaseBlind(const mdsdsc_t *const filespec, mdsdsc_t *const result, - void **const ctx) { + void **const ctx) +{ return find_file(filespec, result, ctx, 1, 1); } EXPORT int LibFindFileCaseBlind(const mdsdsc_t *const filespec, - mdsdsc_t *const result, void **const ctx) { + mdsdsc_t *const result, void **const ctx) +{ return find_file(filespec, result, ctx, 0, 1); } @@ -1893,24 +2119,30 @@ uint16_t Crc(const uint32_t len, uint8_t *const bufptr) } */ -EXPORT int MdsPutEnv(const char *const cmd) { +EXPORT int MdsPutEnv(const char *const cmd) +{ /* cmd action * name unset name * name= set name to "" * name=value set name to value */ INIT_STATUS_ERROR; - if (cmd != NULL) { + if (cmd != NULL) + { if (!strstr(cmd, "MDSPLUS_SPAWN_WRAPPER") && - !strstr(cmd, "MDSPLUS_LIBCALL_WRAPPER")) { + !strstr(cmd, "MDSPLUS_LIBCALL_WRAPPER")) + { char *value, *name = strdup(cmd); for (value = name; *value && *value != '='; value++) ; // find = - if (*value) { + if (*value) + { *(value++) = '\0'; DBG("setenv %s=%s\n", name, value); status = setenv(name, value, 1); - } else { + } + else + { DBG("unsetenv %s\n", name); status = unsetenv(name); } @@ -1922,13 +2154,16 @@ EXPORT int MdsPutEnv(const char *const cmd) { } EXPORT int libffs(const int *const position, const int *const size, - const char *const base, int *const find_position) { + const char *const base, int *const find_position) +{ INIT_STATUS_ERROR; int i; int *bits = (int *)(base + (*position) / 8); int top_bit_to_check = ((*size) + *position) - ((*position) / 8) * 8; - for (i = (*position) % 8; i < top_bit_to_check; i++) { - if (*bits & (1 << i)) { + for (i = (*position) % 8; i < top_bit_to_check; i++) + { + if (*bits & (1 << i)) + { *find_position = ((*position) / 8) * 8 + i; status = MDSplusSUCCESS; break; diff --git a/mdsshr/mds_dsc_string.c b/mdsshr/mds_dsc_string.c index 078551df8e..04500b70fa 100644 --- a/mdsshr/mds_dsc_string.c +++ b/mdsshr/mds_dsc_string.c @@ -28,16 +28,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define checkString(S) \ - case (S): \ +#define checkString(S) \ + case (S): \ return #S; -#define checkAltStr(A, S) \ - case (A): \ +#define checkAltStr(A, S) \ + case (A): \ return #S; -EXPORT char *MdsDtypeString(const dtype_t id) { +EXPORT char *MdsDtypeString(const dtype_t id) +{ static char dtypeString[24]; /* not really threadsafe but should be ok */ - switch (id) { + switch (id) + { #define DEFINE(name, ...) checkString(DTYPE_##name) #include #undef DEFINE @@ -47,9 +49,11 @@ EXPORT char *MdsDtypeString(const dtype_t id) { } } -EXPORT char *MdsClassString(const class_t id) { +EXPORT char *MdsClassString(const class_t id) +{ static char classString[24]; /* not really threadsafe but ok */ - switch (id) { + switch (id) + { #define DEFINE(name, ...) checkString(CLASS_##name) #include #undef DEFINE @@ -59,9 +63,11 @@ EXPORT char *MdsClassString(const class_t id) { } } -EXPORT char *MdsUsageString(const usage_t id) { +EXPORT char *MdsUsageString(const usage_t id) +{ static char usageString[24]; /* not really threadsafe but should be ok */ - switch (id) { + switch (id) + { checkString(TreeUSAGE_ANY) checkString(TreeUSAGE_STRUCTURE) checkString(TreeUSAGE_ACTION) checkString(TreeUSAGE_DEVICE) checkString( TreeUSAGE_DISPATCH) checkString(TreeUSAGE_NUMERIC) diff --git a/mdsshr/mdsmsg.c b/mdsshr/mdsmsg.c index c4ec15a156..ad1eb155fb 100644 --- a/mdsshr/mdsmsg.c +++ b/mdsshr/mdsmsg.c @@ -57,7 +57,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /***************************************************************** * MdsGetMsg: *****************************************************************/ -static void get_msg(int sts, MDSTHREADSTATIC_ARG) { +static void get_msg(int sts, MDSTHREADSTATIC_ARG) +{ static DESCRIPTOR(msg_files, "MDSMSG_PATH:*Msg.*"); static DESCRIPTOR(getmsg_nam, "getmsg"); struct descriptor_d filnam = {0, DTYPE_T, CLASS_D, 0}; @@ -67,41 +68,42 @@ static void get_msg(int sts, MDSTHREADSTATIC_ARG) { static const char *severity[] = {"W", "S", "E", "I", "F", "?", "?", "?"}; int (*getmsg)(int, const char **, const char **, const char **); status = MdsGetStdMsg(sts, &facnam, &msgnam, &msgtext); - if - STATUS_OK { - sprintf(MDS_MDSGETMSG_CSTR, "%%%s-%s-%s, %s", facnam, severity[sts & 0x7], - msgnam, msgtext); - return; - } + if (STATUS_OK) + { + sprintf(MDS_MDSGETMSG_CSTR, "%%%s-%s-%s, %s", facnam, severity[sts & 0x7], + msgnam, msgtext); + return; + } while (STATUS_NOT_OK && (LibFindFile((struct descriptor *)&msg_files, (struct descriptor *)&filnam, &ctx) & - 1)) { + 1)) + { status = LibFindImageSymbol(&filnam, &getmsg_nam, &getmsg); - if - STATUS_OK { - status = (*getmsg)(sts, &facnam, &msgnam, &msgtext); - if - STATUS_OK + if (STATUS_OK) + { + status = (*getmsg)(sts, &facnam, &msgnam, &msgtext); + if (STATUS_OK) sprintf(MDS_MDSGETMSG_CSTR, "%%%s-%s-%s, %s", facnam, severity[sts & 0x7], msgnam, msgtext); - } + } } LibFindFileEnd(&ctx); - if - STATUS_NOT_OK - sprintf(MDS_MDSGETMSG_CSTR, "%%NONAME-%s-NOMSG, Message number 0x%08X", - severity[sts & 0x7], sts); + if (STATUS_NOT_OK) + sprintf(MDS_MDSGETMSG_CSTR, "%%NONAME-%s-NOMSG, Message number 0x%08X", + severity[sts & 0x7], sts); } EXPORT char *MdsGetMsg( /* Return: addr of "status" string */ int status /* status value */ -) { +) +{ MDSTHREADSTATIC_INIT; get_msg(status, MDSTHREADSTATIC_VAR); return MDS_MDSGETMSG_CSTR; } -EXPORT void MdsGetMsgDsc(int status, struct descriptor *out) { +EXPORT void MdsGetMsgDsc(int status, struct descriptor *out) +{ MDSTHREADSTATIC_INIT; get_msg(status, MDSTHREADSTATIC_VAR); MDS_MDSGETMSG_DESC.length = (length_t)strlen(MDS_MDSGETMSG_CSTR); @@ -117,7 +119,8 @@ EXPORT int MdsMsg( /* Return: sts provided by user */ char const fmt[] /* format statement */ , ... /* arguments to fmt[] */ -) { +) +{ int write2stdout; va_list ap; /* arg ptr */ @@ -125,21 +128,27 @@ EXPORT int MdsMsg( /* Return: sts provided by user */ if ((sts & ALREADY_DISPLAYED) && (sts != -1)) return (sts); MDSTHREADSTATIC_INIT; - if (fmt) { + if (fmt) + { va_start(ap, fmt); /* initialize "ap" */ vsprintf(MDS_MDSMSG_CSTR, fmt, ap); - if (sts) { + if (sts) + { MDSfprintf(stderr, "%s\n\r sts=%s\n\n\r", MDS_MDSMSG_CSTR, MdsGetMsg(sts)); if (write2stdout) MDSfprintf(stdout, "%s\n\r sts=%s\n\n\r", MDS_MDSMSG_CSTR, MdsGetMsg(sts)); - } else { + } + else + { MDSfprintf(stderr, "%s\n\r", MDS_MDSMSG_CSTR); if (write2stdout) MDSfprintf(stdout, "%s\n\r", MDS_MDSMSG_CSTR); } - } else { + } + else + { MDSfprintf(stderr, "%s: sts=%s\n\r", MDS_MDSMSG_CSTR, MdsGetMsg(sts)); if (write2stdout) MDSfprintf(stdout, "%s: sts=%s\n\r", MDS_MDSMSG_CSTR, MdsGetMsg(sts)); @@ -149,7 +158,8 @@ EXPORT int MdsMsg( /* Return: sts provided by user */ } #ifdef MAIN -void main() { +void main() +{ MdsMsg(MDSDCL_STS_SUCCESS, 0); MDSprintf("\n"); MdsMsg(CLI_STS_PRESENT, 0); diff --git a/mdsshr/mdsshrp.h b/mdsshr/mdsshrp.h index dc134bc71b..804df40f72 100644 --- a/mdsshr/mdsshrp.h +++ b/mdsshr/mdsshrp.h @@ -17,8 +17,8 @@ extern int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), void *astprm, int *eventid); extern int MDSUdpEventAstMask(char const *eventName, - void (*astadr)(void *, int, char *), void *astprm, - int *eventid, unsigned int cpuMask); + void (*astadr)(void *, int, char *), void *astprm, + int *eventid, unsigned int cpuMask); extern int MDSUdpEventCan(int eventid); extern int MDSUdpEvent(char const *eventName, int bufLen, char const *buf); extern int LibSFree1Dd(struct descriptor *out); diff --git a/mdsshr/mdsthreadstatic.h b/mdsshr/mdsthreadstatic.h index c5415baa7e..7906dc5e80 100644 --- a/mdsshr/mdsthreadstatic.h +++ b/mdsshr/mdsthreadstatic.h @@ -9,29 +9,33 @@ #define THREADSTATIC_DCLSHR 3 #define THREADSTATIC_SIZE 4 -typedef struct { +typedef struct +{ void *buffer; void (*free)(); } buffer_t; -typedef struct { +typedef struct +{ buffer_t **buffers; int is_owned; } MDSplusThreadStatic_t; -#define DEFINE_GETTHREADSTATIC(type, name) \ +#define DEFINE_GETTHREADSTATIC(type, name) \ type *name(MDSplusThreadStatic_t *mts) -#define IMPLEMENT_GETTHREADSTATIC(type, name, bufidx, buffer_allow, \ - buffer_free) \ - DEFINE_GETTHREADSTATIC(type, name) { \ - if (!mts) \ - mts = MDSplusThreadStatic(NULL); \ - if (!mts->buffers[bufidx]) { \ - mts->buffers[bufidx] = (buffer_t *)malloc(sizeof(buffer_t)); \ - mts->buffers[bufidx]->buffer = (void *)buffer_alloc(); \ - mts->buffers[bufidx]->free = (void *)buffer_free; \ - } \ - return (type *)mts->buffers[bufidx]->buffer; \ +#define IMPLEMENT_GETTHREADSTATIC(type, name, bufidx, buffer_allow, \ + buffer_free) \ + DEFINE_GETTHREADSTATIC(type, name) \ + { \ + if (!mts) \ + mts = MDSplusThreadStatic(NULL); \ + if (!mts->buffers[bufidx]) \ + { \ + mts->buffers[bufidx] = (buffer_t *)malloc(sizeof(buffer_t)); \ + mts->buffers[bufidx]->buffer = (void *)buffer_alloc(); \ + mts->buffers[bufidx]->free = (void *)buffer_free; \ + } \ + return (type *)mts->buffers[bufidx]->buffer; \ } extern DEFINE_GETTHREADSTATIC(MDSplusThreadStatic_t, MDSplusThreadStatic); @@ -41,7 +45,8 @@ extern DEFINE_GETTHREADSTATIC(MDSplusThreadStatic_t, MDSplusThreadStatic); #define MDSTHREADSTATIC_ARG MDSTHREADSTATIC_TYPE *const MDSTHREADSTATIC_VAR #define MDSTHREADSTATIC(MTS) MDSTHREADSTATIC_ARG = MdsGetThreadStatic(MTS) #define MDSTHREADSTATIC_INIT MDSTHREADSTATIC(NULL) -typedef struct { +typedef struct +{ char MdsMsg_cstr[1024]; char MdsGetMsg_cstr[1024]; mdsdsc_t MdsGetMsg_desc; diff --git a/mdsshr/testing/UdpEventsTest.c b/mdsshr/testing/UdpEventsTest.c index 96f296f96b..9268ddd287 100644 --- a/mdsshr/testing/UdpEventsTest.c +++ b/mdsshr/testing/UdpEventsTest.c @@ -47,7 +47,8 @@ static pthread_mutex_t second_lock; static int astCount = 0; void eventAst(void *arg, int len __attribute__((unused)), - char *buf __attribute__((unused))) { + char *buf __attribute__((unused))) +{ printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), (char *)arg); pthread_mutex_lock(&astCount_lock); @@ -58,7 +59,8 @@ void eventAst(void *arg, int len __attribute__((unused)), static int first = 0, second = 0; void eventAstFirst(void *arg, int len __attribute__((unused)), - char *buf __attribute__((unused))) { + char *buf __attribute__((unused))) +{ printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), (char *)arg); pthread_mutex_lock(&first_lock); @@ -67,7 +69,8 @@ void eventAstFirst(void *arg, int len __attribute__((unused)), } void eventAstSecond(void *arg, int len __attribute__((unused)), - char *buf __attribute__((unused))) { + char *buf __attribute__((unused))) +{ printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), (char *)arg); pthread_mutex_lock(&second_lock); @@ -75,12 +78,14 @@ void eventAstSecond(void *arg, int len __attribute__((unused)), pthread_mutex_unlock(&second_lock); } -static void wait() { +static void wait() +{ static const struct timespec tspec = {0, 100000000}; nanosleep(&tspec, 0); } -int main(int argc, char **args) { +int main(int argc, char **args) +{ int status = 0; int i, iterations, ev_id; char *eventname = alloca(100); @@ -88,14 +93,18 @@ int main(int argc, char **args) { pthread_mutex_init(&first_lock, NULL); pthread_mutex_init(&second_lock, NULL); BEGIN_TESTING(UdpEvents); - if (argc < 2) { + if (argc < 2) + { iterations = 3; - } else { + } + else + { iterations = strtol(args[1], NULL, 0); printf("Doing %d iterations\n", iterations); } - for (i = 0; i < iterations; i++) { + for (i = 0; i < iterations; i++) + { sprintf(eventname, "ev_test_%d_%d", i, getpid()); status = MDSEventAst(eventname, eventAst, eventname, &ev_id); diff --git a/mdsshr/testing/UdpEventsTestStatics.c b/mdsshr/testing/UdpEventsTestStatics.c index dc4d341162..50214ed68d 100644 --- a/mdsshr/testing/UdpEventsTestStatics.c +++ b/mdsshr/testing/UdpEventsTestStatics.c @@ -43,9 +43,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // utils //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#define new_unique_event_name(str) \ +#define new_unique_event_name(str) \ _new_unique_event_name("%s_%d_%d", str, __LINE__, getpid()) -static char *_new_unique_event_name(const char *prefix, ...) { +static char *_new_unique_event_name(const char *prefix, ...) +{ char buffer[300]; va_list args; va_start(args, prefix); @@ -56,7 +57,8 @@ static char *_new_unique_event_name(const char *prefix, ...) { static int astCount = 0; void eventAst(void *arg, int len __attribute__((unused)), - char *buf __attribute__((unused))) { + char *buf __attribute__((unused))) +{ printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), (char *)arg); astCount++; @@ -84,7 +86,8 @@ static void getMulticastAddr(char const *eventName, char *retIp); /// fucntion but it doesn't detach the waiting thread, this seems to prevent /// memory allocation errors in valgrind. /// -void test_handleMessage() { +void test_handleMessage() +{ BEGIN_TESTING(UdpEvents handleMessage); char *eventName = new_unique_event_name("test_event"); @@ -155,18 +158,21 @@ void test_handleMessage() { // PUSH AND POP ////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static struct _list_el { +static struct _list_el +{ pthread_t thread; int id; } list[10]; -static void *_push_handler(void *arg) { +static void *_push_handler(void *arg) +{ struct _list_el *li = (struct _list_el *)arg; li->id = pushEvent(li->thread, 0); return NULL; } -void test_pushEvent() { +void test_pushEvent() +{ BEGIN_TESTING(UpdEvents pushEvent); printf("pushEvent test\n"); int i; @@ -177,14 +183,16 @@ void test_pushEvent() { END_TESTING } -static void *_pop_handler(void *arg) { +static void *_pop_handler(void *arg) +{ struct _list_el *li = (struct _list_el *)arg; EventList *ev = popEvent(li->id); free(ev); return NULL; } -void test_popEvent() { +void test_popEvent() +{ BEGIN_TESTING(UpdEvents popEvent); printf("popEvent test\n"); int i; @@ -199,26 +207,31 @@ void test_popEvent() { // Suppression /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static void *_thread_action(void *arg) { +static void *_thread_action(void *arg) +{ (void)arg; int status __attribute__((unused)); status = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); status = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); - while (1) { + while (1) + { // do nothing .. // } return NULL; } -void test_pthread_cancel_Suppresstion() { +void test_pthread_cancel_Suppresstion() +{ pthread_t thread[10]; int i; - for (i = 0; i < 10; ++i) { + for (i = 0; i < 10; ++i) + { pthread_create(&thread[i], NULL, _thread_action, NULL); pthread_detach(thread[i]); } usleep(10000); - for (i = 0; i < 10; ++i) { + for (i = 0; i < 10; ++i) + { while (pthread_cancel(thread[i]) != 0) ; } @@ -229,7 +242,8 @@ void test_pthread_cancel_Suppresstion() { //////////////////////////////////////////////////////////////////////////////// int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ test_handleMessage(); test_pushEvent(); test_popEvent(); diff --git a/mdssql/dynamic_syb.c b/mdssql/dynamic_syb.c index 295b4a8cea..c893985c39 100644 --- a/mdssql/dynamic_syb.c +++ b/mdssql/dynamic_syb.c @@ -55,8 +55,7 @@ static LOGINREC *loginrec = 0; static DBPROCESS *dbproc = 0; /*------------------------------FATAL ERROR----------------------------------*/ -static void Fatal(msg, arg) -char *msg; +static void Fatal(msg, arg) char *msg; char *arg; { fprintf(stderr, msg, arg); @@ -66,11 +65,11 @@ char *arg; #define MAXMSG 1024 static int DBSTATUS; static char DBMSGTEXT[MAXMSG]; -static struct descriptor DBMSGTEXT_DSC = {0,DTYPE_T,CLASS_S,DBMSGTEXT}; +static struct descriptor DBMSGTEXT_DSC = {0, DTYPE_T, CLASS_S, DBMSGTEXT}; static void strcatn(char *dst, const char *src, int max) { - strncat(dst,src,max-strlen(dst)); + strncat(dst, src, max - strlen(dst)); } /* @@ -88,21 +87,25 @@ static void strcatn(char *dst, const char *src, int max) /*------------------------------ERROR HANDLER--------------------------------*/ -static void SetMsgLen() { - DBMSGTEXT_DSC.length=strlen(DBMSGTEXT); +static void SetMsgLen() +{ + DBMSGTEXT_DSC.length = strlen(DBMSGTEXT); } -static int Err_Handler(DBPROCESS * dbproc, int severity __attribute__ ((unused)), int dberr, int oserr, - cnst char *dberrstr, cnst char *oserrstr) +static int Err_Handler(DBPROCESS *dbproc, int severity __attribute__((unused)), int dberr, int oserr, + cnst char *dberrstr, cnst char *oserrstr) { #ifdef WIN32 - if (dberr != SQLEPWD) { + if (dberr != SQLEPWD) + { #else - if (dberr != SYBERDNR) { + if (dberr != SYBERDNR) + { #endif strcatn(DBMSGTEXT, dberrstr, MAXMSG); strcatn(DBMSGTEXT, "\n", MAXMSG); - if (oserr != DBNOERR && oserrstr) { + if (oserr != DBNOERR && oserrstr) + { strcatn(DBMSGTEXT, oserrstr, MAXMSG); strcatn(DBMSGTEXT, "\n", MAXMSG); } @@ -110,7 +113,8 @@ static int Err_Handler(DBPROCESS * dbproc, int severity __attribute__ ((unused)) } /* if we have run out of licences then return cancel so we can wait and try again */ - if (DBSTATUS == 18460) { + if (DBSTATUS == 18460) + { return INT_CANCEL; } if (!dbproc) @@ -121,31 +125,35 @@ static int Err_Handler(DBPROCESS * dbproc, int severity __attribute__ ((unused)) } /*------------------------------MESSAGE HANDLER------------------------------*/ - static int Msg_Handler(DBPROCESS * dbproc __attribute__ ((unused)), DBINT msgno, int msgstate, int severity, - cnst char *msgtext, cnst char *servername, cnst char *procname, - DBUSMALLINT line) +static int Msg_Handler(DBPROCESS *dbproc __attribute__((unused)), DBINT msgno, int msgstate, int severity, + cnst char *msgtext, cnst char *servername, cnst char *procname, + DBUSMALLINT line) { char msg[512]; DBSTATUS = 1; if (msgno == 5701) - return 0; /*just a USE DATABASE notice */ - if (severity) { + return 0; /*just a USE DATABASE notice */ + if (severity) + { if (sizeof(msgno) == 8) - sprintf(msg,"\nMsg %ld, Level %d, State %d\n", (long)msgno, severity, msgstate); + sprintf(msg, "\nMsg %ld, Level %d, State %d\n", (long)msgno, severity, msgstate); else - sprintf(msg,"\nMsg %d, Level %d, State %d\n", (int)msgno, severity, msgstate); + sprintf(msg, "\nMsg %d, Level %d, State %d\n", (int)msgno, severity, msgstate); strcatn(DBMSGTEXT, msg, MAXMSG); if (servername) - if (strlen(servername)) { - sprintf(msg, "Server '%s', ", servername); - strcatn(DBMSGTEXT, msg, MAXMSG); + if (strlen(servername)) + { + sprintf(msg, "Server '%s', ", servername); + strcatn(DBMSGTEXT, msg, MAXMSG); } if (procname) - if (strlen(procname)) { - sprintf(msg, "Procedure '%s', ", procname); - strcatn(DBMSGTEXT, msg, MAXMSG); + if (strlen(procname)) + { + sprintf(msg, "Procedure '%s', ", procname); + strcatn(DBMSGTEXT, msg, MAXMSG); } - if (line) { + if (line) + { sprintf(msg, "Line %d", line); strcatn(DBMSGTEXT, msg, MAXMSG); } @@ -153,7 +161,7 @@ static int Err_Handler(DBPROCESS * dbproc, int severity __attribute__ ((unused)) strcatn(DBMSGTEXT, msgtext, MAXMSG); SetMsgLen(); DBSTATUS = msgno; - return 0; /* try to continue */ + return 0; /* try to continue */ } EXPORT int GetDBStatus() @@ -161,7 +169,8 @@ EXPORT int GetDBStatus() return DBSTATUS; } -EXPORT struct descriptor *GetDBMsgText_dsc() { +EXPORT struct descriptor *GetDBMsgText_dsc() +{ return &DBMSGTEXT_DSC; } @@ -184,25 +193,30 @@ EXPORT int Login_Sybase(char *host, char *user, char *pass) { #ifdef RETRY_CONNECTS - int try; + int try + ; #endif if (dbproc) Logout_Sybase(); - if (loginrec) { + if (loginrec) + { dbloginfree(loginrec); loginrec = 0; } if (dbinit() == FAIL) - Fatal("%s","Login_Sybase: Can't init DB-library\n"); + Fatal("%s", "Login_Sybase: Can't init DB-library\n"); dbmsghandle(Msg_Handler); dberrhandle(Err_Handler); loginrec = dblogin(); #ifdef Win32 - if (user == 0) { + if (user == 0) + { DBSETLSECURE(loginrec); - } else { + } + else + { #endif DBSETLUSER(loginrec, user); DBSETLPWD(loginrec, pass); @@ -215,11 +229,13 @@ EXPORT int Login_Sybase(char *host, char *user, char *pass) */ #ifdef RETRY_CONNECTS - for (try = 0; ((dbproc == 0) && (try < 10)); try++) { + for (try = 0; ((dbproc == 0) && (try < 10)); try ++) + { DBMSGTEXT[0] = 0; SetMsgLen(); dbproc = dbopen(loginrec, host); - if (!dbproc) { + if (!dbproc) + { Sleep(100); } } @@ -237,18 +253,18 @@ EXPORT int Login_Sybase(char *host, char *user, char *pass) } /*------------------------------DYNAMIC--------------------------------------*/ -EXPORT int SQL_DYNAMIC(USER_GETS, USER_PUTS, ptext, user_args, prows) -int (*USER_GETS) (); /*routine to fill markers */ -int (*USER_PUTS) (); /*routine to store selctions */ -char *ptext; /*text string address */ -int *user_args; /*value passed to GETS and PUTS */ +EXPORT int SQL_DYNAMIC(USER_GETS, USER_PUTS, ptext, user_args, prows) int (*USER_GETS)(); /*routine to fill markers */ +int (*USER_PUTS)(); /*routine to store selctions */ +char *ptext; /*text string address */ +int *user_args; /*value passed to GETS and PUTS */ int *prows; -{ /*output, number of rows */ +{ /*output, number of rows */ int status = 1, nmarks = 0; char parsed[MAXPARSE]; - if (dbproc == 0) { + if (dbproc == 0) + { DBSTATUS = 0; strcpy(DBMSGTEXT, "SET_DATABASE must preceed any DSQL calls"); SetMsgLen(); @@ -259,7 +275,8 @@ int *prows; DBMSGTEXT[0] = 0; SetMsgLen(); *prows = -1; - if (strchr(ptext, '?')) { + if (strchr(ptext, '?')) + { parsed[0] = '\0'; status = USER_GETS(ptext, parsed, &nmarks, user_args); } @@ -269,26 +286,30 @@ int *prows; if (status != SUCCEED) goto close; status = dbsqlexec(dbproc); - if (status == SUCCEED) { + if (status == SUCCEED) + { int rowcount = 0, rblob = strncmp("sElEcT", nmarks ? parsed : ptext, 6); - while ((status = dbresults(dbproc)) == SUCCEED) { + while ((status = dbresults(dbproc)) == SUCCEED) + { status = USER_PUTS(dbproc, &rowcount, user_args, rblob); if (STATUS_OK) - while ((status = dbnextrow(dbproc)) != NO_MORE_ROWS) { - ++rowcount; - status = USER_PUTS(dbproc, &rowcount, user_args, rblob); - if (STATUS_NOT_OK) - goto close; - } + while ((status = dbnextrow(dbproc)) != NO_MORE_ROWS) + { + ++rowcount; + status = USER_PUTS(dbproc, &rowcount, user_args, rblob); + if (STATUS_NOT_OK) + goto close; + } } - if (status == NO_MORE_ROWS || status == NO_MORE_RESULTS) { + if (status == NO_MORE_ROWS || status == NO_MORE_RESULTS) + { *prows = rowcount; rowcount = -(rowcount + 1); status = USER_PUTS(dbproc, &rowcount, user_args, rblob); } dbcancel(dbproc); } - close: +close: DBSTATUS = status; return status; } diff --git a/mdstcpip/ArgLen.c b/mdstcpip/ArgLen.c index c3e3584496..a8baf8cf1a 100644 --- a/mdstcpip/ArgLen.c +++ b/mdstcpip/ArgLen.c @@ -26,9 +26,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" -short ArgLen(struct descrip *d) { +short ArgLen(struct descrip *d) +{ short len = 0; - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_CSTRING: len = d->length ? d->length : (short)(d->ptr ? strlen(d->ptr) : 0); break; diff --git a/mdstcpip/CheckClient.c b/mdstcpip/CheckClient.c index 6df6989556..fbefb82570 100644 --- a/mdstcpip/CheckClient.c +++ b/mdstcpip/CheckClient.c @@ -48,7 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int TdiExecute(); -static inline int filter_string(char **const str_ptr, const int upcase) { +static inline int filter_string(char **const str_ptr, const int upcase) +{ #define str (*str_ptr) while (*str && isspace(*str)) str++; @@ -56,7 +57,8 @@ static inline int filter_string(char **const str_ptr, const int upcase) { while (isspace(*c)) c--; *++c = '\0'; // terminate - if (upcase) { + if (upcase) + { for (c = str; *c; c++) *c = toupper(*c); } @@ -70,7 +72,8 @@ static inline int filter_string(char **const str_ptr, const int upcase) { #define become_user(remote_user, local_user) 1 #else static int become_user(const char *remote_user, - const char *local_user) { // both args may be NULL + const char *local_user) +{ // both args may be NULL if (!local_user || !*local_user) return ACCESS_NOMATCH; // NULL or empty if (strcmp(local_user, "SELF") == 0) @@ -82,15 +85,20 @@ static int become_user(const char *remote_user, remote_user && strcmp(remote_user, "root") == 0; // if map_to_local map root to nobody const char *user; - if (map_to_local) { + if (map_to_local) + { user = is_root ? "nobody" : remote_user; - } else if (strcmp(local_user, "SANDBOX") == 0) { + } + else if (strcmp(local_user, "SANDBOX") == 0) + { MdsEnableSandbox(); user = "nobody"; - } else + } + else user = local_user; struct passwd *pwd = user ? getpwnam(user) : 0; - if (!pwd && user == remote_user) { + if (!pwd && user == remote_user) + { int i; char *lowuser = malloc(i = strlen(remote_user) + 1); while (i-- > 0) @@ -99,53 +107,71 @@ static int become_user(const char *remote_user, free(lowuser); } int access; - if (pwd) { + if (pwd) + { initgroups(pwd->pw_name, pwd->pw_gid); - if (setgid(pwd->pw_gid) || setuid(pwd->pw_uid)) { + if (setgid(pwd->pw_gid) || setuid(pwd->pw_uid)) + { fprintf(stderr, "Cannot set gid/uid - run server as root!\n"); access = ACCESS_DENIED; - } else { - if (setenv("HOME", pwd->pw_dir, TRUE)) { + } + else + { + if (setenv("HOME", pwd->pw_dir, TRUE)) + { fprintf(stderr, "Failed to set HOME for user \"%s\"\n", user); access = ACCESS_DENIED; - } else + } + else access = ACCESS_GRANTED; } - } else + } + else access = ACCESS_NOMATCH; return access; } #endif -static inline size_t bytes_added(ssize_t result_of_sprintf) { +static inline size_t bytes_added(ssize_t result_of_sprintf) +{ return (result_of_sprintf > 0) ? (size_t)result_of_sprintf : 0; } int CheckClient(const char *const username, int num, - char *const *const matchString) { + char *const *const matchString) +{ int access = ACCESS_NOMATCH; char *hostfile = GetHostfile(); - if (strncmp(hostfile, "TDI", 3)) { + if (strncmp(hostfile, "TDI", 3)) + { FILE *f = fopen(hostfile, "r"); - if (f) { - struct match { + if (f) + { + struct match + { char *c; mdsdsc_t d; } *matchS = calloc(num, sizeof(struct match)); char line_c[1024], *access_id, *local_user; int i, deny; - while (access == ACCESS_NOMATCH && fgets(line_c, 1023, f)) { - if (line_c[0] != '#') { + while (access == ACCESS_NOMATCH && fgets(line_c, 1023, f)) + { + if (line_c[0] != '#') + { access_id = line_c; local_user = strchr(line_c, '|'); - if (local_user) { + if (local_user) + { *local_user++ = '\0'; filter_string(&local_user, FALSE); } - if (filter_string(&access_id, TRUE)) { // not empty - if ((deny = access_id[0] == '!')) { + if (filter_string(&access_id, TRUE)) + { // not empty + if ((deny = access_id[0] == '!')) + { access_id++; // drop '!' - if (!filter_string(&access_id, FALSE)) { + if (!filter_string(&access_id, FALSE)) + { if (username) access = ACCESS_DENIED; // deny else @@ -153,9 +179,11 @@ int CheckClient(const char *const username, int num, } } DESCRIPTOR_FROM_CSTRING(access_d, access_id); - for (i = 0; i < num && access == ACCESS_NOMATCH; i++) { + for (i = 0; i < num && access == ACCESS_NOMATCH; i++) + { struct match *const match = &matchS[i]; - if (!match->c) { + if (!match->c) + { match->c = strdup(matchString[i]); match->d.dtype = DTYPE_T; match->d.class = CLASS_S; @@ -163,18 +191,19 @@ int CheckClient(const char *const username, int num, match->d.length = (length_t)filter_string(&match->d.pointer, TRUE); } - if (deny) { - if - IS_OK(StrMatchWild(&match->d, &access_d)) - access = ACCESS_DENIED; - } else { + if (deny) + { + if (IS_OK(StrMatchWild(&match->d, &access_d))) + access = ACCESS_DENIED; + } + else + { if (strcmp(match->d.pointer, "MULTI") == 0 && strcmp(access_id, "MULTI") == 0) access = become_user(NULL, local_user); - else if - IS_OK(StrMatchWild(&match->d, &access_d)) - access = GetMulti() ? ACCESS_GRANTED - : become_user(username, local_user); + else if (IS_OK(StrMatchWild(&match->d, &access_d))) + access = GetMulti() ? ACCESS_GRANTED + : become_user(username, local_user); } } } @@ -184,16 +213,22 @@ int CheckClient(const char *const username, int num, free(matchS[i].c); free(matchS); fclose(f); - } else { + } + else + { perror("CheckClient"); fprintf(stderr, "Unable to open hostfile: %s\n", GetHostfile()); access = ACCESS_DENIED; } - } else { + } + else + { // hostfile starts with TDI size_t cmdlen = strlen(hostfile) + 5; - if (username) { - if (strchr(username, '"')) { + if (username) + { + if (strchr(username, '"')) + { /* " in username would cause a syntax error * or could lead to unsafe code execution */ @@ -220,23 +255,27 @@ int CheckClient(const char *const username, int num, mdsdsc_t ans_d = {0, DTYPE_T, CLASS_D, 0}; int status = TdiExecute(&cmd_d, &ans_d MDS_END_ARG); free(cmd); - if - STATUS_OK { - access = ACCESS_GRANTED; - if (ans_d.pointer && ans_d.length > 0) { - if (!GetMulti()) { - ans_d.pointer = realloc(ans_d.pointer, ans_d.length + 1); - ans_d.pointer[ans_d.length] = '\0'; - access = become_user(username, ans_d.pointer); - } - StrFree1Dx((mdsdsc_d_t *)&ans_d); + if (STATUS_OK) + { + access = ACCESS_GRANTED; + if (ans_d.pointer && ans_d.length > 0) + { + if (!GetMulti()) + { + ans_d.pointer = realloc(ans_d.pointer, ans_d.length + 1); + ans_d.pointer[ans_d.length] = '\0'; + access = become_user(username, ans_d.pointer); } + StrFree1Dx((mdsdsc_d_t *)&ans_d); } - else if (status == TdiUNKNOWN_VAR) { + } + else if (status == TdiUNKNOWN_VAR) + { fprintf(stderr, "CheckClient: Failed to load tdi function \"%s\"\n", hostfile + 3); access = ACCESS_DENIED; - } else + } + else access = ACCESS_DENIED; } return access; diff --git a/mdstcpip/ClientType.c b/mdstcpip/ClientType.c index d35e02d091..5b324e1327 100644 --- a/mdstcpip/ClientType.c +++ b/mdstcpip/ClientType.c @@ -38,7 +38,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// | CRAY_CLIENT | 8 | - not supported anymore /// -char ClientType(void) { +char ClientType(void) +{ static const char ctype = #ifdef _WORDS_BIGENDIAN BigEndian | diff --git a/mdstcpip/CloseConnection.c b/mdstcpip/CloseConnection.c index abe09ed8c1..f3391722cd 100644 --- a/mdstcpip/CloseConnection.c +++ b/mdstcpip/CloseConnection.c @@ -27,16 +27,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" -int CloseConnection(int id) { +int CloseConnection(int id) +{ INIT_STATUS_AS MDSplusERROR; static int (*removeConnection)(int) = NULL; Connection *c = FindConnection(id, 0); - if (c) { + if (c) + { status = LibFindImageSymbol_C("MdsIpSrvShr", "RemoveConnection", &removeConnection); - if - STATUS_OK - status = (*removeConnection)(id); + if (STATUS_OK) + status = (*removeConnection)(id); } return status; } diff --git a/mdstcpip/ConnectToMds.c b/mdstcpip/ConnectToMds.c index b781116604..6ba082ec86 100644 --- a/mdstcpip/ConnectToMds.c +++ b/mdstcpip/ConnectToMds.c @@ -43,16 +43,21 @@ static void parseHost(char *hostin, char **protocol, char **host) *protocol = strcpy((char *)malloc(strlen(hostin) + 10), ""); *host = strcpy((char *)malloc(strlen(hostin) + 10), ""); sscanf(hostin, "%[^:]://%s", *protocol, *host); - if (strlen(*host) == 0) { - if (hostin[0] == '_') { + if (strlen(*host) == 0) + { + if (hostin[0] == '_') + { strcpy(*protocol, "gsi"); strcpy(*host, &hostin[1]); - } else { + } + else + { strcpy(*protocol, "tcp"); strcpy(*host, hostin); } } - for (i = strlen(*host) - 1; (*host)[i] == 32; i--) { + for (i = strlen(*host) - 1; (*host)[i] == 32; i--) + { (*host)[i] = 0; if (i == 0) break; @@ -70,7 +75,7 @@ static void parseHost(char *hostin, char **protocol, char **host) /// \return status o login into server 1 if success, MDSplusERROR if not authorized or error /// occurred /// -static int doLogin(Connection* c) +static int doLogin(Connection *c) { INIT_STATUS; Message *m; @@ -88,33 +93,39 @@ static int doLogin(Connection* c) memcpy(m->bytes, user_p, length); status = SendMdsMsgC(c, m, 0); free(m); - if STATUS_OK { + if (STATUS_OK) + { m = GetMdsMsgTOC(c, &status, 10000); - if (!m || STATUS_NOT_OK) { + if (!m || STATUS_NOT_OK) + { printf("Error in connect\n"); return MDSplusERROR; - } else { - if IS_NOT_OK(m->h.status) { - printf("Error in connect: Access denied\n"); - free(m); - return MDSplusERROR; + } + else + { + if (IS_NOT_OK(m->h.status)) + { + printf("Error in connect: Access denied\n"); + free(m); + return MDSplusERROR; } // SET CLIENT COMPRESSION FROM SERVER // - c->compression_level= (m->h.status & 0x1e) >> 1; + c->compression_level = (m->h.status & 0x1e) >> 1; c->client_type = m->h.client_type; - if (m->h.ndims>0) c->version = m->h.dims[0]; + if (m->h.ndims > 0) + c->version = m->h.dims[0]; } free(m); - } else { - fprintf(stderr,"Error connecting to server (DoLogin)\n"); + } + else + { + fprintf(stderr, "Error connecting to server (DoLogin)\n"); fflush(stderr); return MDSplusERROR; } return status; } - - //////////////////////////////////////////////////////////////////////////////// // Reuse Check /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -128,27 +139,28 @@ int ReuseCheck(char *hostin, char *unique, size_t buflen) char *host = 0; char *protocol = 0; parseHost(hostin, &protocol, &host); - IoRoutines* io = LoadIo(protocol); - if (io) { + IoRoutines *io = LoadIo(protocol); + if (io) + { if (io->reuseCheck) ok = io->reuseCheck(host, unique, buflen); - else { + else + { strncpy(unique, hostin, buflen); ok = 0; } - } else + } + else memset(unique, 0, buflen); free(protocol); free(host); return ok; } - //////////////////////////////////////////////////////////////////////////////// // ConnectToMds ////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - int ConnectToMds(char *hostin) { int id = -1; @@ -157,14 +169,19 @@ int ConnectToMds(char *hostin) if (hostin == 0) return id; parseHost(hostin, &protocol, &host); - Connection* c = NewConnectionC(protocol); - if (c) { - if (c->io && c->io->connect) { + Connection *c = NewConnectionC(protocol); + if (c) + { + if (c->io && c->io->connect) + { c->compression_level = GetCompressionLevel(); - if (c->io->connect(c, protocol, host)<0 || IS_NOT_OK(doLogin(c))) { - DisconnectConnectionC(c); - } else { - id = AddConnection(c); + if (c->io->connect(c, protocol, host) < 0 || IS_NOT_OK(doLogin(c))) + { + DisconnectConnectionC(c); + } + else + { + id = AddConnection(c); } } } diff --git a/mdstcpip/Connections.c b/mdstcpip/Connections.c index 80d9c6c8d2..d883eab3e4 100644 --- a/mdstcpip/Connections.c +++ b/mdstcpip/Connections.c @@ -36,20 +36,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #endif static Connection *ConnectionList = NULL; static pthread_mutex_t connection_mutex = PTHREAD_MUTEX_INITIALIZER; -#define CONNECTIONLIST_LOCK \ - pthread_mutex_lock(&connection_mutex); \ +#define CONNECTIONLIST_LOCK \ + pthread_mutex_lock(&connection_mutex); \ pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&connection_mutex); #define CONNECTIONLIST_UNLOCK pthread_cleanup_pop(1); -Connection *_FindConnection(int id, Connection **prev) { +Connection *_FindConnection(int id, Connection **prev) +{ Connection *c, *p; for (p = 0, c = ConnectionList; c && c->id != id; p = c, c = c->next) ; @@ -58,7 +59,8 @@ Connection *_FindConnection(int id, Connection **prev) { return c; } -Connection *FindConnection(int id, Connection **prev) { +Connection *FindConnection(int id, Connection **prev) +{ Connection *c; CONNECTIONLIST_LOCK; c = _FindConnection(id, prev); @@ -68,12 +70,15 @@ Connection *FindConnection(int id, Connection **prev) { return c; } -Connection *FindConnectionSending(int id) { +Connection *FindConnectionSending(int id) +{ Connection *c; CONNECTIONLIST_LOCK; c = _FindConnection(id, NULL); - if (c && c->state != CON_SENDARG) { - if (c->state & CON_SENDARG) { + if (c && c->state != CON_SENDARG) + { + if (c->state & CON_SENDARG) + { c->state &= CON_DISCONNECT; // preserve CON_DISCONNECT DBG("Connection %02d -> %02x unlocked\n", c->id, c->state); pthread_cond_signal(&c->cond); @@ -84,7 +89,8 @@ Connection *FindConnectionSending(int id) { return c; } -EXPORT int GetConnectionVersion(int id) { +EXPORT int GetConnectionVersion(int id) +{ int version; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(id, NULL); @@ -93,19 +99,25 @@ EXPORT int GetConnectionVersion(int id) { return version; } -Connection *FindConnectionWithLock(int id, con_t state) { +Connection *FindConnectionWithLock(int id, con_t state) +{ Connection *c; CONNECTIONLIST_LOCK; c = _FindConnection(id, NULL); - if (c) { - while (c->state & ~CON_DISCONNECT) { + if (c) + { + while (c->state & ~CON_DISCONNECT) + { DBG("Connection %02d -- %02x waiting\n", c->id, state); pthread_cond_wait(&c->cond, &connection_mutex); } - if (c->state & CON_DISCONNECT) { + if (c->state & CON_DISCONNECT) + { pthread_cond_signal(&c->cond); // pass on signal c = NULL; - } else { + } + else + { DBG("Connection %02d -> %02x locked\n", c->id, state); c->state = state; } @@ -114,12 +126,14 @@ Connection *FindConnectionWithLock(int id, con_t state) { return c; } -void UnlockConnection(Connection *c_in) { +void UnlockConnection(Connection *c_in) +{ CONNECTIONLIST_LOCK; Connection *c; // check if not yet freed for (c = ConnectionList; c && c != c_in; c = c->next) ; - if (c) { + if (c) + { c->state &= CON_DISCONNECT; // preserve CON_DISCONNECT DBG("Connection %02d -> %02x unlocked\n", c->id, c->state); pthread_cond_signal(&c->cond); @@ -127,19 +141,21 @@ void UnlockConnection(Connection *c_in) { CONNECTIONLIST_UNLOCK; } -#define CONNECTION_UNLOCK_PUSH(c) \ +#define CONNECTION_UNLOCK_PUSH(c) \ pthread_cleanup_push((void *)UnlockConnection, (void *)c) #define CONNECTION_UNLOCK(c) pthread_cleanup_pop(1) int NextConnection(void **ctx, char **info_name, void **info, - size_t *info_len) { // check + size_t *info_len) +{ // check int ans; CONNECTIONLIST_LOCK; Connection *c, *next; next = (*ctx != (void *)-1) ? (Connection *)*ctx : ConnectionList; for (c = ConnectionList; c && c != next; c = c->next) ; - if (c) { + if (c) + { *ctx = c->next; if (info_name) *info_name = c->info_name; @@ -148,7 +164,9 @@ int NextConnection(void **ctx, char **info_name, void **info, if (info_len) *info_len = c->info_len; ans = c->id; - } else { + } + else + { *ctx = 0; ans = INVALID_CONNECTION_ID; } @@ -156,7 +174,8 @@ int NextConnection(void **ctx, char **info_name, void **info, return ans; } -int SendToConnection(int id, const void *buffer, size_t buflen, int nowait) { +int SendToConnection(int id, const void *buffer, size_t buflen, int nowait) +{ int res; Connection *c = FindConnectionWithLock(id, CON_SEND); CONNECTION_UNLOCK_PUSH(c); @@ -168,7 +187,8 @@ int SendToConnection(int id, const void *buffer, size_t buflen, int nowait) { return res; } -int FlushConnection(int id) { +int FlushConnection(int id) +{ int res; Connection *c = FindConnectionWithLock(id, CON_FLUSH); CONNECTION_UNLOCK_PUSH(c); @@ -180,7 +200,8 @@ int FlushConnection(int id) { return res; } -int ReceiveFromConnection(int id, void *buffer, size_t buflen) { +int ReceiveFromConnection(int id, void *buffer, size_t buflen) +{ int res; Connection *c = FindConnectionWithLock(id, CON_RECV); CONNECTION_UNLOCK_PUSH(c); @@ -192,10 +213,12 @@ int ReceiveFromConnection(int id, void *buffer, size_t buflen) { return res; } -static void exitHandler(void) { +static void exitHandler(void) +{ int id; void *ctx = (void *)-1; - while ((id = NextConnection(&ctx, 0, 0, 0)) != INVALID_CONNECTION_ID) { + while ((id = NextConnection(&ctx, 0, 0, 0)) != INVALID_CONNECTION_ID) + { DisconnectConnection(id); ctx = 0; } @@ -206,7 +229,8 @@ static void registerHandler() { atexit(exitHandler); } // DisconnectConnection ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void DisconnectConnectionC(Connection *c) { +void DisconnectConnectionC(Connection *c) +{ // connection should not be in list at this point c->io->disconnect(c); free(c->info); @@ -219,16 +243,19 @@ void DisconnectConnectionC(Connection *c) { free(c); } -int DisconnectConnection(int conid) { +int DisconnectConnection(int conid) +{ Connection *p, *c; CONNECTIONLIST_LOCK; c = _FindConnection(conid, &p); if (c && c->state & CON_DISCONNECT) c = NULL; - else if (c) { + else if (c) + { c->state |= CON_DISCONNECT; // sets disconnect pthread_cond_broadcast(&c->cond); - if (c->state & ~CON_DISCONNECT) { // if any task but disconnect + if (c->state & ~CON_DISCONNECT) + { // if any task but disconnect struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); tp.tv_sec += 10; @@ -251,7 +278,8 @@ int DisconnectConnection(int conid) { ConnectionList = c->next; } CONNECTIONLIST_UNLOCK; - if (c) { + if (c) + { DisconnectConnectionC(c); return MDSplusSUCCESS; } @@ -262,10 +290,12 @@ int DisconnectConnection(int conid) { // NewConnection ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -Connection *NewConnectionC(char *protocol) { +Connection *NewConnectionC(char *protocol) +{ Connection *connection; IoRoutines *io = LoadIo(protocol); - if (io) { + if (io) + { RUN_FUNCTION_ONCE(registerHandler); connection = calloc(1, sizeof(Connection)); connection->io = io; @@ -277,7 +307,8 @@ Connection *NewConnectionC(char *protocol) { _TreeNewDbid(&connection->DBID); pthread_cond_init(&connection->cond, NULL); return connection; - } else + } + else return NULL; } @@ -285,12 +316,17 @@ Connection *NewConnectionC(char *protocol) { // FreeDescriptors /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void FreeDescriptors(Connection *c) { +void FreeDescriptors(Connection *c) +{ int i; - if (c) { - for (i = 0; i < MDSIP_MAX_ARGS; i++) { - if (c->descrip[i]) { - if (c->descrip[i] != MdsEND_ARG) { + if (c) + { + for (i = 0; i < MDSIP_MAX_ARGS; i++) + { + if (c->descrip[i]) + { + if (c->descrip[i] != MdsEND_ARG) + { free(c->descrip[i]->pointer); free(c->descrip[i]); } @@ -304,7 +340,8 @@ void FreeDescriptors(Connection *c) { // GetConnectionIo /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -IoRoutines *GetConnectionIo(int conid) { +IoRoutines *GetConnectionIo(int conid) +{ IoRoutines *io; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); @@ -318,8 +355,10 @@ IoRoutines *GetConnectionIo(int conid) { //////////////////////////////////////////////////////////////////////////////// void *GetConnectionInfoC(Connection *c, char **info_name, SOCKET *readfd, - size_t *len) { - if (c) { + size_t *len) +{ + if (c) + { if (len) *len = c->info_len; if (info_name) @@ -332,7 +371,8 @@ void *GetConnectionInfoC(Connection *c, char **info_name, SOCKET *readfd, } void *GetConnectionInfo(int conid, char **info_name, SOCKET *readfd, - size_t *len) { + size_t *len) +{ void *ans; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); @@ -346,13 +386,18 @@ void *GetConnectionInfo(int conid, char **info_name, SOCKET *readfd, //////////////////////////////////////////////////////////////////////////////// void SetConnectionInfoC(Connection *c, char *info_name, SOCKET readfd, - void *info, size_t len) { - if (c) { + void *info, size_t len) +{ + if (c) + { c->info_name = strcpy(malloc(strlen(info_name) + 1), info_name); - if (info) { + if (info) + { c->info = memcpy(malloc(len), info, len); c->info_len = len; - } else { + } + else + { c->info = 0; c->info_len = 0; } @@ -361,7 +406,8 @@ void SetConnectionInfoC(Connection *c, char *info_name, SOCKET readfd, } void SetConnectionInfo(int conid, char *info_name, SOCKET readfd, void *info, - size_t len) { + size_t len) +{ CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); if (c) @@ -373,7 +419,8 @@ void SetConnectionInfo(int conid, char *info_name, SOCKET readfd, void *info, // ConnectionCompression ///////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void SetConnectionCompression(int conid, int compression) { +void SetConnectionCompression(int conid, int compression) +{ CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, NULL); if (c) @@ -381,10 +428,12 @@ void SetConnectionCompression(int conid, int compression) { CONNECTIONLIST_UNLOCK; } -static inline int GetConnectionCompressionC(Connection *c) { +static inline int GetConnectionCompressionC(Connection *c) +{ return c ? c->compression_level : 0; } -int GetConnectionCompression(int conid) { +int GetConnectionCompression(int conid) +{ int complv; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, NULL); @@ -397,8 +446,10 @@ int GetConnectionCompression(int conid) { // IncrementConnectionMessageId ////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -unsigned char IncrementConnectionMessageIdC(Connection *c) { - if (c) { +unsigned char IncrementConnectionMessageIdC(Connection *c) +{ + if (c) + { c->message_id++; if (c->message_id == 0) c->message_id = 1; @@ -407,7 +458,8 @@ unsigned char IncrementConnectionMessageIdC(Connection *c) { return 0; } -unsigned char IncrementConnectionMessageId(int conid) { +unsigned char IncrementConnectionMessageId(int conid) +{ unsigned char id; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, NULL); @@ -420,11 +472,13 @@ unsigned char IncrementConnectionMessageId(int conid) { // GetConnectionMessageId //////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -inline static unsigned char GetConnectionMessageIdC(Connection *c) { +inline static unsigned char GetConnectionMessageIdC(Connection *c) +{ return c ? c->message_id : 0; } -unsigned char GetConnectionMessageId(int conid) { +unsigned char GetConnectionMessageId(int conid) +{ unsigned char id; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); @@ -440,7 +494,8 @@ unsigned char GetConnectionMessageId(int conid) { /// \param conid the connection id /// \param client_type the type of connection to be set /// -void SetConnectionClientType(int conid, int client_type) { +void SetConnectionClientType(int conid, int client_type) +{ CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); if (c) @@ -455,7 +510,8 @@ void SetConnectionClientType(int conid, int client_type) { /// \param conid the connection id /// \return client_type value stored in connection structure /// -int GetConnectionClientType(int conid) { +int GetConnectionClientType(int conid) +{ int type; CONNECTIONLIST_LOCK; Connection *c = _FindConnection(conid, 0); @@ -473,7 +529,8 @@ int GetConnectionClientType(int conid) { /// \param username of the user to be authorized for access /// \return true if authorized user found, false otherwise -static inline int authorizeClient(Connection *c, char *username) { +static inline int authorizeClient(Connection *c, char *username) +{ if (c && c->io) return c->io->authorize ? c->io->authorize(c, username) : MDSplusSUCCESS; return MDSplusERROR; @@ -482,7 +539,8 @@ static inline int authorizeClient(Connection *c, char *username) { //////////////////////////////////////////////////////////////////////////////// // AcceptConnection ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int AddConnection(Connection *c) { +int AddConnection(Connection *c) +{ static int id = 1; CONNECTIONLIST_LOCK; if (id == INVALID_CONNECTION_ID) @@ -496,17 +554,20 @@ int AddConnection(Connection *c) { } int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, - size_t info_len, int *id, char **usr) { + size_t info_len, int *id, char **usr) +{ Connection *c = NewConnectionC(protocol); INIT_STATUS_ERROR; - if (c) { + if (c) + { static Message m; Message *m_user; char *user = NULL, *user_p = NULL; // SET INFO // SetConnectionInfoC(c, info_name, readfd, info, info_len); m_user = GetMdsMsgTOC(c, &status, 10000); - if (!m_user || STATUS_NOT_OK) { + if (!m_user || STATUS_NOT_OK) + { free(m_user); *usr = NULL; DisconnectConnectionC(c); @@ -514,7 +575,8 @@ int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, } m.h.msglen = sizeof(MsgHdr); // AUTHORIZE // - if (STATUS_OK && (m_user) && (m_user->h.dtype == DTYPE_CSTRING)) { + if (STATUS_OK && (m_user) && (m_user->h.dtype == DTYPE_CSTRING)) + { user = malloc(m_user->h.length + 1); memcpy(user, m_user->bytes, m_user->h.length); user[m_user->h.length] = 0; @@ -523,20 +585,20 @@ int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, user_p = user ? user : "?"; status = authorizeClient(c, user_p); // SET COMPRESSION // - if - STATUS_OK { - c->compression_level = m_user->h.status & 0xf; - c->client_type = m_user->h.client_type; - *usr = strdup(user_p); - if (m_user->h.ndims > 0) - c->version = m_user->h.dims[0]; - } + if (STATUS_OK) + { + c->compression_level = m_user->h.status & 0xf; + c->client_type = m_user->h.client_type; + *usr = strdup(user_p); + if (m_user->h.ndims > 0) + c->version = m_user->h.dims[0]; + } else *usr = NULL; - if - STATUS_NOT_OK - fprintf(stderr, "Access denied: %s\n", user_p); - else fprintf(stderr, "Connected: %s\n", user_p); + if (STATUS_NOT_OK) + fprintf(stderr, "Access denied: %s\n", user_p); + else + fprintf(stderr, "Connected: %s\n", user_p); m.h.status = STATUS_OK ? (1 | (c->compression_level << 1)) : 0; m.h.client_type = m_user ? m_user->h.client_type : 0; m.h.ndims = 1; @@ -544,11 +606,11 @@ int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, MdsIpFree(m_user); // reply to client // SendMdsMsgC(c, &m, 0); - if - STATUS_OK { - // all good add connection - *id = AddConnection(c); - } + if (STATUS_OK) + { + // all good add connection + *id = AddConnection(c); + } else DisconnectConnectionC(c); // fflush(stderr); stderr needs no flush diff --git a/mdstcpip/DoMessage.c b/mdstcpip/DoMessage.c index c457889094..8178d46a56 100644 --- a/mdstcpip/DoMessage.c +++ b/mdstcpip/DoMessage.c @@ -32,7 +32,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // DoMessage ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int DoMessage(int id) { +int DoMessage(int id) +{ Connection *c = FindConnection(id, 0); static Message *(*processMessage)(Connection *, Message *) = NULL; int status = @@ -41,15 +42,17 @@ int DoMessage(int id) { return 0; // will cause tunnel to terminate Message *msgptr = GetMdsMsg(id, &status); Message *ans = 0; - if - STATUS_OK { - ans = processMessage(c, msgptr); - if (ans) { - status = SendMdsMsg(id, ans, 0); - free(ans); - } + if (STATUS_OK) + { + ans = processMessage(c, msgptr); + if (ans) + { + status = SendMdsMsg(id, ans, 0); + free(ans); } - else { + } + else + { CloseConnection(id); status = 0; // will cause tunnel to terminate } diff --git a/mdstcpip/FlipData.c b/mdstcpip/FlipData.c index 881500dc1d..4415bf158e 100644 --- a/mdstcpip/FlipData.c +++ b/mdstcpip/FlipData.c @@ -28,12 +28,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #include "mdsip_connections.h" -void FlipData(Message *m) { +void FlipData(Message *m) +{ int num = 1; int i; char *ptr; int dims[MAX_DIMS]; - for (i = 0; i < MAX_DIMS; i++) { + for (i = 0; i < MAX_DIMS; i++) + { #ifdef __CRAY dims[i] = i % 2 ? m->h.dims[i / 2] & 0xffffffff : m->h.dims[i / 2] >> 32; #else @@ -46,7 +48,8 @@ void FlipData(Message *m) { #ifdef DEBUG printf("num to flip = %d\n", num); #endif - switch (m->h.dtype) { + switch (m->h.dtype) + { #ifndef __CRAY case DTYPE_COMPLEX: case DTYPE_COMPLEX_DOUBLE: diff --git a/mdstcpip/FlipHeader.c b/mdstcpip/FlipHeader.c index 22bc140ff9..73f9c6a852 100644 --- a/mdstcpip/FlipHeader.c +++ b/mdstcpip/FlipHeader.c @@ -25,11 +25,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" -void FlipHeader(MsgHdr *header) { +void FlipHeader(MsgHdr *header) +{ int i; #ifdef __CRAY -#define Flip32(n) \ - n = ((n >> 24) & 0xff) | ((n >> 8) & 0xff00) | ((n << 8) & 0xff0000) | \ +#define Flip32(n) \ + n = ((n >> 24) & 0xff) | ((n >> 8) & 0xff00) | ((n << 8) & 0xff0000) | \ ((n << 24) & 0xff000000) #define Flip16(n) n = ((n >> 8) & 0xff) | ((n << 8) & 0xff00) Flip32(header->msglen); diff --git a/mdstcpip/GetAnswerInfo.c b/mdstcpip/GetAnswerInfo.c index 0d8930402f..223ca551d3 100644 --- a/mdstcpip/GetAnswerInfo.c +++ b/mdstcpip/GetAnswerInfo.c @@ -36,9 +36,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __attribute__((deprecated)) int GetAnswerInfo(int id, char *dtype, short *length, char *ndims, int *dims, int *numbytes, - void **dptr) { + void **dptr) +{ static void *m = 0; - if (m) { + if (m) + { free(m); m = NULL; } @@ -50,13 +52,15 @@ __attribute__((deprecated)) int GetAnswerInfo(int id, char *dtype, //////////////////////////////////////////////////////////////////////////////// inline int GetAnswerInfoTS(int id, char *dtype, short *length, char *ndims, - int *dims, int *numbytes, void **dptr, void **mout) { + int *dims, int *numbytes, void **dptr, void **mout) +{ return GetAnswerInfoTO(id, dtype, length, ndims, dims, numbytes, dptr, mout, -1); } int GetAnswerInfoTO(int id, char *dtype, short *length, char *ndims, int *dims, - int *numbytes, void **dptr, void **mout, int timeout_msec) { + int *numbytes, void **dptr, void **mout, int timeout_msec) +{ Connection *c = FindConnectionSending(id); if (!c) return MDSplusERROR; @@ -65,38 +69,47 @@ int GetAnswerInfoTO(int id, char *dtype, short *length, char *ndims, int *dims, Message *m; m = GetMdsMsgTOC(c, &status, timeout_msec); UnlockConnection(c); - if (!m && status == SsINTERNAL) { + if (!m && status == SsINTERNAL) + { DisconnectConnection(id); status = MDSplusERROR; } - if - STATUS_NOT_OK { - free(m); - *mout = NULL; - *dtype = 0; - *length = 0; - *ndims = 0; - *numbytes = 0; - *dptr = 0; - return status; - } + if (STATUS_NOT_OK) + { + free(m); + *mout = NULL; + *dtype = 0; + *length = 0; + *ndims = 0; + *numbytes = 0; + *dptr = 0; + return status; + } int datalen = (int)(m->h.msglen - sizeof(MsgHdr)); *numbytes = m->h.length; - if (m->h.ndims) { - for (i = 0; i < m->h.ndims; i++) { + if (m->h.ndims) + { + for (i = 0; i < m->h.ndims; i++) + { #ifdef __CRAY dims[i] = i % 2 ? m->h.dims[i / 2] & 0xffffffff : (*m)->h.dims[i / 2] >> 32; #else if (m->h.dims[i]) dims[i] = m->h.dims[i]; - else { - if (datalen > *numbytes && datalen % *numbytes) { + else + { + if (datalen > *numbytes && datalen % *numbytes) + { dims[i] = datalen / *numbytes; m->h.ndims = i + 1; - } else if (datalen == *numbytes && m->h.ndims == i + 1) { + } + else if (datalen == *numbytes && m->h.ndims == i + 1) + { dims[i] = 1; - } else { + } + else + { m->h.ndims = i; break; // dont mult numbytes } @@ -109,13 +122,17 @@ int GetAnswerInfoTO(int id, char *dtype, short *length, char *ndims, int *dims, } for (i = m->h.ndims; i < MAX_DIMS; i++) dims[i] = 0; - } else { + } + else + { for (i = 0; i < MAX_DIMS; i++) dims[i] = 0; } - if (*numbytes != datalen) { + if (*numbytes != datalen) + { *numbytes = 0; - if (m) { + if (m) + { free(m); *mout = 0; } diff --git a/mdstcpip/GetMdsMsg.c b/mdstcpip/GetMdsMsg.c index 0abe547bc3..3438892891 100644 --- a/mdstcpip/GetMdsMsg.c +++ b/mdstcpip/GetMdsMsg.c @@ -33,18 +33,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include static int GetBytesTO(Connection *c, void *buffer, size_t bytes_to_recv, - int to_msec) { + int to_msec) +{ char *bptr = (char *)buffer; - if (c && c->io) { + if (c && c->io) + { int id = c->id; - while (bytes_to_recv > 0) { + while (bytes_to_recv > 0) + { ssize_t bytes_recv; if (c->io->recv_to && to_msec >= 0) // don't use timeout if not available or requested bytes_recv = c->io->recv_to(c, bptr, bytes_to_recv, to_msec); else bytes_recv = c->io->recv(c, bptr, bytes_to_recv); - if (bytes_recv > 0) { + if (bytes_recv > 0) + { bytes_to_recv -= bytes_recv; bptr += bytes_recv; continue; @@ -57,7 +61,8 @@ static int GetBytesTO(Connection *c, void *buffer, size_t bytes_to_recv, return MDSplusERROR; if (errno == EINVAL) return SsINTERNAL; - if (errno) { + if (errno) + { fprintf(stderr, "Connection %d ", id); perror("possibly lost"); } @@ -72,69 +77,74 @@ static int GetBytesTO(Connection *c, void *buffer, size_t bytes_to_recv, // GetMdsMsg ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) { +Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) +{ MsgHdr header; Message *msg = NULL; // MdsSetClientAddr(0); *status = GetBytesTO(c, (void *)&header, sizeof(MsgHdr), to_msec); if (*status == SsINTERNAL) return NULL; - if - IS_OK(*status) { - if (Endian(header.client_type) != Endian(ClientType())) - FlipHeader(&header); + if (IS_OK(*status)) + { + if (Endian(header.client_type) != Endian(ClientType())) + FlipHeader(&header); #ifdef DEBUG - printf("msglen = %d\nstatus = %d\nlength = %d\nnargs = " - "%d\ndescriptor_idx = %d\nmessage_id = %d\ndtype = %d\n", - header.msglen, header.status, header.length, header.nargs, - header.descriptor_idx, header.message_id, header.dtype); - printf("client_type = %d\nndims = %d\n", header.client_type, - header.ndims); + printf("msglen = %d\nstatus = %d\nlength = %d\nnargs = " + "%d\ndescriptor_idx = %d\nmessage_id = %d\ndtype = %d\n", + header.msglen, header.status, header.length, header.nargs, + header.descriptor_idx, header.message_id, header.dtype); + printf("client_type = %d\nndims = %d\n", header.client_type, + header.ndims); #endif - uint32_t msglen = (uint32_t)header.msglen; - if (msglen < sizeof(MsgHdr) || CType(header.client_type) > CRAY_CLIENT || - header.ndims > MAX_DIMS) { - fprintf(stderr, - "\rGetMdsMsg shutdown connection %d: bad msg header, " - "header.ndims=%d, client_type=%d\n", - c->id, header.ndims, CType(header.client_type)); - *status = SsINTERNAL; - return NULL; - } - unsigned long dlen; - msg = malloc(msglen); - msg->h = header; - *status = GetBytesTO(c, msg->bytes, msglen - sizeof(MsgHdr), 1000); - if (IS_OK(*status) && IsCompressed(header.client_type)) { - Message *m; - memcpy(&msglen, msg->bytes, 4); - dlen = msglen - sizeof(MsgHdr); - if (Endian(header.client_type) != Endian(ClientType())) - FlipBytes(4, (char *)&msglen); - m = malloc(msglen); - m->h = header; - *status = uncompress((unsigned char *)m->bytes, &dlen, - (unsigned char *)msg->bytes + 4, dlen - 4) == 0; - if - IS_OK(*status) { - m->h.msglen = msglen; - free(msg); - msg = m; - } - else - free(m); + uint32_t msglen = (uint32_t)header.msglen; + if (msglen < sizeof(MsgHdr) || CType(header.client_type) > CRAY_CLIENT || + header.ndims > MAX_DIMS) + { + fprintf(stderr, + "\rGetMdsMsg shutdown connection %d: bad msg header, " + "header.ndims=%d, client_type=%d\n", + c->id, header.ndims, CType(header.client_type)); + *status = SsINTERNAL; + return NULL; + } + unsigned long dlen; + msg = malloc(msglen); + msg->h = header; + *status = GetBytesTO(c, msg->bytes, msglen - sizeof(MsgHdr), 1000); + if (IS_OK(*status) && IsCompressed(header.client_type)) + { + Message *m; + memcpy(&msglen, msg->bytes, 4); + dlen = msglen - sizeof(MsgHdr); + if (Endian(header.client_type) != Endian(ClientType())) + FlipBytes(4, (char *)&msglen); + m = malloc(msglen); + m->h = header; + *status = uncompress((unsigned char *)m->bytes, &dlen, + (unsigned char *)msg->bytes + 4, dlen - 4) == 0; + if (IS_OK(*status)) + { + m->h.msglen = msglen; + free(msg); + msg = m; } - if (IS_OK(*status) && - (Endian(header.client_type) != Endian(ClientType()))) - FlipData(msg); + else + free(m); } + if (IS_OK(*status) && + (Endian(header.client_type) != Endian(ClientType()))) + FlipData(msg); + } return msg; } -Message *GetMdsMsgTO(int id, int *status, int to_msec) { +Message *GetMdsMsgTO(int id, int *status, int to_msec) +{ Connection *c = FindConnection(id, NULL); Message *msg = GetMdsMsgTOC(c, status, to_msec); - if (!msg && *status == SsINTERNAL) { + if (!msg && *status == SsINTERNAL) + { // not for ETIMEDOUT or EINTR like exceptions DisconnectConnection(id); *status = MDSplusERROR; diff --git a/mdstcpip/GetSetSettings.c b/mdstcpip/GetSetSettings.c index 17e20fcd2f..6b3f3fae36 100644 --- a/mdstcpip/GetSetSettings.c +++ b/mdstcpip/GetSetSettings.c @@ -44,7 +44,8 @@ static SOCKET socketHandle = 0; SOCKET GetSocketHandle() { return socketHandle; } -SOCKET SetSocketHandle(SOCKET handle) { +SOCKET SetSocketHandle(SOCKET handle) +{ SOCKET old = socketHandle; socketHandle = handle; return old; @@ -52,7 +53,8 @@ SOCKET SetSocketHandle(SOCKET handle) { int GetFlags() { return flags; } -int SetFlags(int f) { +int SetFlags(int f) +{ int old = flags; flags = f; return old; @@ -60,7 +62,8 @@ int SetFlags(int f) { char *GetProtocol() { return protocol; } -char *SetProtocol(char *p) { +char *SetProtocol(char *p) +{ char *old = protocol; protocol = p; return old; @@ -70,7 +73,8 @@ char *GetPortname() { return Portname; } char *MdsGetServerPortname() { return Portname; } -char *SetPortname(char *p) { +char *SetPortname(char *p) +{ char *old = Portname; Portname = p; return old; @@ -78,7 +82,8 @@ char *SetPortname(char *p) { char *GetHostfile() { return hostfile ? hostfile : DEFAULT_HOSTFILE; } -char *SetHostfile(char *newhostfile) { +char *SetHostfile(char *newhostfile) +{ char *old = hostfile; hostfile = newhostfile; return old; @@ -88,15 +93,20 @@ char *SetHostfile(char *newhostfile) { // CONTEXT /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -char *GetLogDir() { +char *GetLogDir() +{ char *logdir = getenv("MDSIP_SERVICE_LOGDIR"); - if (logdir && (strlen(logdir) > 0)) { + if (logdir && (strlen(logdir) > 0)) + { logdir = strdup(logdir); size_t len = strlen(logdir); - if ((logdir[len - 1] == '\\') || (logdir[len - 1] == '/')) { + if ((logdir[len - 1] == '\\') || (logdir[len - 1] == '/')) + { logdir[len - 1] = '\000'; } - } else { + } + else + { logdir = strdup("C:\\"); } return logdir; @@ -108,7 +118,8 @@ unsigned char GetMulti() { return multi; } /// Set multi mode active in this scope. /// Mutiple connection mode (accepts multiple connections each with own context) /// -unsigned char SetMulti(unsigned char s) { +unsigned char SetMulti(unsigned char s) +{ unsigned char old_multi = multi; multi = s; return old_multi; @@ -116,7 +127,8 @@ unsigned char SetMulti(unsigned char s) { int GetContextSwitching() { return ContextSwitching; } -int SetContextSwitching(int s) { +int SetContextSwitching(int s) +{ int old_ctx_switching = ContextSwitching; ContextSwitching = s; return old_ctx_switching; @@ -128,13 +140,15 @@ int SetContextSwitching(int s) { int GetMaxCompressionLevel() { return MaxCompressionLevel; } -int SetMaxCompressionLevel(int s) { +int SetMaxCompressionLevel(int s) +{ int old_max_compression = MaxCompressionLevel; MaxCompressionLevel = s; return old_max_compression; } -int SetCompressionLevel(int level) { +int SetCompressionLevel(int level) +{ int old_level = CompressionLevel; CompressionLevel = level; return old_level; @@ -148,7 +162,8 @@ int GetCompressionLevel() { return CompressionLevel; } static int timeout_value = 0; static pthread_once_t timeout_once = PTHREAD_ONCE_INIT; static pthread_mutex_t timeout_mutex = PTHREAD_MUTEX_INITIALIZER; -static void timeout_init() { +static void timeout_init() +{ char *timeout = getenv("MDSIP_CONNECT_TIMEOUT"); if (timeout) timeout_value = strtol(timeout, NULL, 0); @@ -158,7 +173,8 @@ static void timeout_init() { // GetMdsConnectTimeout ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int GetMdsConnectTimeout() { +int GetMdsConnectTimeout() +{ int connect_timeout; pthread_mutex_lock(&timeout_mutex); pthread_cleanup_push((void *)pthread_mutex_unlock, &timeout_mutex); @@ -168,7 +184,8 @@ int GetMdsConnectTimeout() { return connect_timeout; } -int SetMdsConnectTimeout(int sec) { +int SetMdsConnectTimeout(int sec) +{ int old; pthread_mutex_lock(&timeout_mutex); pthread_cleanup_push((void *)pthread_mutex_unlock, &timeout_mutex); diff --git a/mdstcpip/IdlApi.c b/mdstcpip/IdlApi.c index b8353f8888..ad8c5ad8df 100644 --- a/mdstcpip/IdlApi.c +++ b/mdstcpip/IdlApi.c @@ -34,13 +34,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef NULL #define NULL (void *)0 #endif -STATIC_ROUTINE int BlockSig(int sig_number) { +STATIC_ROUTINE int BlockSig(int sig_number) +{ sigset_t newsigset; #if defined(sun) - if (sig_number == SIGALRM) { /* Solaris: simple block doesn't work? */ + if (sig_number == SIGALRM) + { /* Solaris: simple block doesn't work? */ struct sigaction act; sigaction(sig_number, NULL, &act); /* get current state ... */ - if (~act.sa_flags & SA_RESTART) { /*...set SA_RESTART bit */ + if (~act.sa_flags & SA_RESTART) + { /*...set SA_RESTART bit */ act.sa_flags |= SA_RESTART; if (sigaction(sig_number, &act, NULL)) perror("BlockSig *err* sigaction"); @@ -52,7 +55,8 @@ STATIC_ROUTINE int BlockSig(int sig_number) { return sigprocmask(SIG_BLOCK, &newsigset, NULL); } -STATIC_ROUTINE int UnBlockSig(int sig_number) { +STATIC_ROUTINE int UnBlockSig(int sig_number) +{ sigset_t newsigset; sigemptyset(&newsigset); sigaddset(&newsigset, sig_number); @@ -64,8 +68,10 @@ STATIC_ROUTINE int UnBlockSig(int sig_number) { // Start of Mac Changes static short bGUSIInit = 0; -STATIC_ROUTINE void BlockSig(int) { - if (!bGUSIInit) { +STATIC_ROUTINE void BlockSig(int) +{ + if (!bGUSIInit) + { // GUSISetup ( GUSIwithInternetSockets ); GUSISetupConfig(); bGUSIInit = 1; @@ -79,49 +85,57 @@ void main() {} // End of Mac Changes #endif -EXPORT int IdlMdsClose(int lArgc, void **lpvArgv) { +EXPORT int IdlMdsClose(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlMdsClose', connection, value=[1b]) */ int status = 0; BlockSig(SIGALRM); - if (lArgc == 1) { + if (lArgc == 1) + { status = MdsClose((int)((char *)lpvArgv[0] - (char *)0)); } UnBlockSig(SIGALRM); return status; } -EXPORT int IdlConnectToMds(int lArgc, void **lpvArgv) { +EXPORT int IdlConnectToMds(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlConnectToMds', 'host-name') */ int status = 0; BlockSig(SIGALRM); - if (lArgc == 1) { + if (lArgc == 1) + { status = ConnectToMds((char *)lpvArgv[0]); } UnBlockSig(SIGALRM); return status; } -EXPORT int IdlDisconnectFromMds(int lArgc, void **lpvArgv) { +EXPORT int IdlDisconnectFromMds(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlDisconnectFromMds', connection, * value=[1b]) */ int status = 0; BlockSig(SIGALRM); - if (lArgc == 1) { + if (lArgc == 1) + { status = DisconnectFromMds((int)((char *)lpvArgv[0] - (char *)0)); } UnBlockSig(SIGALRM); return status; } -EXPORT int IdlMdsOpen(int lArgc, void **lpvArgv) { +EXPORT int IdlMdsOpen(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlMdsOpen', connection, 'tree-name', * shot, value = [1b,0b,1b]) */ int status = 0; - if (lArgc == 3) { + if (lArgc == 3) + { BlockSig(SIGALRM); status = MdsOpen((int)((char *)lpvArgv[0] - (char *)0), (char *)lpvArgv[1], (int)((char *)lpvArgv[2] - (char *)0)); @@ -130,12 +144,14 @@ EXPORT int IdlMdsOpen(int lArgc, void **lpvArgv) { return status; } -EXPORT int IdlMdsSetDefault(int lArgc, void **lpvArgv) { +EXPORT int IdlMdsSetDefault(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlMdsSetDefault', connection, 'node', * value = [1b,0b]) */ int status = 0; - if (lArgc == 2) { + if (lArgc == 2) + { BlockSig(SIGALRM); status = MdsSetDefault((int)((char *)lpvArgv[0] - (char *)0), (char *)lpvArgv[1]); @@ -144,13 +160,15 @@ EXPORT int IdlMdsSetDefault(int lArgc, void **lpvArgv) { return status; } -EXPORT int IdlGetAnsInfo(int lArgc, void **lpvArgv) { +EXPORT int IdlGetAnsInfo(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlGetAnsInfo', connection_l, dtype_b, length_w, ndims_b, dims_l[7], numbytes_l, ans, value=[1b,0b,0b,0b,0b,0b,0b]) */ int status = 0; - if (lArgc == 7) { + if (lArgc == 7) + { BlockSig(SIGALRM); status = GetAnswerInfo((int)((char *)lpvArgv[0] - (char *)0), (char *)lpvArgv[1], (short *)lpvArgv[2], @@ -161,12 +179,14 @@ EXPORT int IdlGetAnsInfo(int lArgc, void **lpvArgv) { return status; } -EXPORT int Idlmemcpy(int lArgc, void **lpvArgv) { +EXPORT int Idlmemcpy(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','Idlmemcpy', answer, answer_ptr, nbytes, * value=[0b,1b,1b]) */ int status = 0; - if (lArgc == 3) { + if (lArgc == 3) + { #ifdef __alpha memcpy((void *)lpvArgv[0], *(void **)lpvArgv[1], (int)((char *)lpvArgv[2] - (char *)0)); @@ -179,13 +199,15 @@ EXPORT int Idlmemcpy(int lArgc, void **lpvArgv) { return status; } -EXPORT int IdlSendArg(int lArgc, void **lpvArgv) { +EXPORT int IdlSendArg(int lArgc, void **lpvArgv) +{ /* status = call_external('mdsipshr','IdlSendArg', connection_l, idx_l, dtype_b, nargs_w, length_w, ndims_b, dims_l[7], bytes, value=[1b,1b,1b,1b,1b,1b,1b,0b,0b]) */ int status = 0; - if (lArgc == 8) { + if (lArgc == 8) + { unsigned char idx = (unsigned char)((char *)lpvArgv[1] - (char *)0); unsigned char dtype = (unsigned char)((char *)lpvArgv[2] - (char *)0); unsigned char nargs = (unsigned char)((char *)lpvArgv[3] - (char *)0); @@ -199,13 +221,15 @@ EXPORT int IdlSendArg(int lArgc, void **lpvArgv) { return status; } -EXPORT int IdlSetCompressionLevel(int lArgc, void **lpvArgv) { +EXPORT int IdlSetCompressionLevel(int lArgc, void **lpvArgv) +{ extern int MdsSetCompression(int conid, int level); /* status = call_external('mdsipshr','IdlSetCompressionLevel', connection_l, * level_l, value=[1b,1b]) */ int status = 0; - if (lArgc == 2) { + if (lArgc == 2) + { status = MdsSetCompression((int)((char *)lpvArgv[0] - (char *)0), (int)((char *)lpvArgv[1] - (char *)0)); } diff --git a/mdstcpip/IoRoutinesGsi.c b/mdstcpip/IoRoutinesGsi.c index 60283067c7..0887e57548 100644 --- a/mdstcpip/IoRoutinesGsi.c +++ b/mdstcpip/IoRoutinesGsi.c @@ -68,7 +68,7 @@ static int gsi_authorize(Connection *c, char *username); static int gsi_connect(Connection *c, char *protocol, char *host); static int gsi_reuseCheck(char *host, char *unique, size_t buflen); static IoRoutines gsi_routines = { - gsi_connect, gsi_send, gsi_recv, NULL, gsi_listen, + gsi_connect, gsi_send, gsi_recv, NULL, gsi_listen, gsi_authorize, gsi_reuseCheck, gsi_disconnect, NULL, NULL}; static int MDSIP_SNDBUF = 32768; @@ -77,7 +77,8 @@ static int MDSIP_RCVBUF = 32768; static globus_mutex_t globus_l_mutex; static globus_cond_t globus_l_cond; -typedef struct _gsi_info { +typedef struct _gsi_info +{ globus_xio_handle_t xio_handle; globus_xio_driver_t gsi_driver; globus_xio_driver_t tcp_driver; @@ -86,16 +87,19 @@ typedef struct _gsi_info { EXPORT IoRoutines *Io() { return &gsi_routines; } -static short GetPort(char *pname) { +static short GetPort(char *pname) +{ short port; char *name = pname ? pname : GetPortname(); struct servent *sp; if (name == 0 || strcmp(name, "mdsip") == 0) name = "mdsips"; port = htons((short)strtol(name, NULL, 0)); - if (port == 0) { + if (port == 0) + { sp = getservbyname(name, "tcp"); - if (sp == NULL) { + if (sp == NULL) + { fprintf(stderr, "unknown service: %s/tcp\n\n", name); exit(0); } @@ -104,14 +108,17 @@ static short GetPort(char *pname) { return ntohs(port); } -static void testStatus(globus_result_t res, char *msg) { - if (res != GLOBUS_SUCCESS) { +static void testStatus(globus_result_t res, char *msg) +{ + if (res != GLOBUS_SUCCESS) + { fprintf(stderr, "ERROR:%s ---\n %s\n", msg, globus_object_printable_to_string(globus_error_get(res))); } } -static GSI_INFO *getGsiInfoC(Connection *c) { +static GSI_INFO *getGsiInfoC(Connection *c) +{ size_t len; char *info_name; int readfd; @@ -120,7 +127,8 @@ static GSI_INFO *getGsiInfoC(Connection *c) { ? info : 0; } -static GSI_INFO *getGsiInfo(int conid) { +static GSI_INFO *getGsiInfo(int conid) +{ size_t len; char *info_name; int readfd; @@ -131,16 +139,18 @@ static GSI_INFO *getGsiInfo(int conid) { : 0; } -#define doit(statvar, gfuncall, msg, fail_action) \ - statvar = gfuncall; \ - testStatus(statvar, msg); \ - if (statvar != GLOBUS_SUCCESS) \ +#define doit(statvar, gfuncall, msg, fail_action) \ + statvar = gfuncall; \ + testStatus(statvar, msg); \ + if (statvar != GLOBUS_SUCCESS) \ fail_action -static int gsi_authorize(Connection *c, char *username) { +static int gsi_authorize(Connection *c, char *username) +{ GSI_INFO *info = getGsiInfoC(c); int ans = 0; - if (info) { + if (info) + { char *hostname; char *hostip; globus_result_t res; @@ -165,7 +175,8 @@ static int gsi_authorize(Connection *c, char *username) { "Get Peer Name", return 0); status = gss_display_name(&mstatus, peer, &peer_name_buffer, GLOBUS_NULL); // gss_release_name(&mstatus,&peer); - if (status != GSS_S_COMPLETE) { + if (status != GSS_S_COMPLETE) + { fprintf(stderr, "Error getting display name\n"); return C_ERROR; } @@ -193,7 +204,8 @@ static int gsi_authorize(Connection *c, char *username) { info->connection_name); // gss_release_buffer(&status,&peer_name_buffer); ans = CheckClient(username, 2, match_string); - if (ans && GetMulti() == 0) { + if (ans && GetMulti() == 0) + { gss_cred_id_t credential; OM_uint32 major_status, minor_status; gss_buffer_desc buffer_desc = GSS_C_EMPTY_BUFFER; @@ -203,22 +215,28 @@ static int gsi_authorize(Connection *c, char *username) { testStatus(res, "openCallback,GET_DELEGATED_CRED"); major_status = gss_export_cred(&minor_status, credential, GSS_C_NO_OID, 0, &buffer_desc); - if (major_status != GSS_S_COMPLETE) { + if (major_status != GSS_S_COMPLETE) + { char *error_str; globus_gss_assist_display_status_str(&error_str, NULL, major_status, minor_status, 0); fprintf(stderr, "\nLINE %d ERROR: %s\n\n", __LINE__, error_str); - } else { + } + else + { char cred_file_name[] = "/tmp/x509pp_pXXXXXX"; int fd = mkstemp(cred_file_name); - if (fd != -1) { + if (fd != -1) + { fchmod(fd, 00600); if (write(fd, buffer_desc.value, buffer_desc.length) == -1) perror("Error in gsi_authorize writing to temporary file\n"); fchmod(fd, 00400); close(fd); setenv("X509_USER_PROXY", cred_file_name, 1); - } else { + } + else + { perror("Error creating proxy credential file"); } // major_status = gss_release_buffer(&minor_status,&buffer_desc); @@ -229,12 +247,14 @@ static int gsi_authorize(Connection *c, char *username) { } static ssize_t gsi_send(Connection *c, const void *bptr, size_t num, - int options __attribute__((unused))) { + int options __attribute__((unused))) +{ globus_size_t nbytes; globus_result_t result; GSI_INFO *info = getGsiInfoC(c); ssize_t sent = -1; - if (info != 0) { + if (info != 0) + { doit(result, globus_xio_write(info->xio_handle, (globus_byte_t *)bptr, num, num, &nbytes, NULL), @@ -244,12 +264,14 @@ static ssize_t gsi_send(Connection *c, const void *bptr, size_t num, return sent; } -static ssize_t gsi_recv(Connection *c, void *bptr, size_t num) { +static ssize_t gsi_recv(Connection *c, void *bptr, size_t num) +{ GSI_INFO *info = getGsiInfoC(c); globus_size_t numreceived; globus_result_t result; ssize_t recved = -1; - if (info != 0) { + if (info != 0) + { doit(result, globus_xio_read(info->xio_handle, (globus_byte_t *)bptr, num, num, &numreceived, NULL), @@ -259,10 +281,13 @@ static ssize_t gsi_recv(Connection *c, void *bptr, size_t num) { return recved; } -static int gsi_disconnect(Connection *c) { +static int gsi_disconnect(Connection *c) +{ GSI_INFO *info = getGsiInfoC(c); - if (info) { - if (info->connection_name) { + if (info) + { + if (info->connection_name) + { char now[32]; Now32(now); printf("%s (pid %d) Connection disconnected from %s\r\n", now, getpid(), @@ -275,16 +300,19 @@ static int gsi_disconnect(Connection *c) { return C_ERROR; } -static int gsi_reuseCheck(char *host, char *unique, size_t buflen) { +static int gsi_reuseCheck(char *host, char *unique, size_t buflen) +{ int ans; IoRoutines *io = LoadIo("tcp"); char *hoststr = strcpy((char *)malloc(strlen(host) + 10), host); - if ((strchr(host, ':')) == 0) { + if ((strchr(host, ':')) == 0) + { strcat(hoststr, ":"); strcat(hoststr, "mdsips"); } ans = (io && io->reuseCheck) ? io->reuseCheck(hoststr, unique, buflen) : -1; - if (strlen(unique) > 4 && strncmp("tcp:", unique, 4) == 0) { + if (strlen(unique) > 4 && strncmp("tcp:", unique, 4) == 0) + { unique[0] = 'g'; unique[1] = 's'; unique[2] = 'i'; @@ -294,7 +322,8 @@ static int gsi_reuseCheck(char *host, char *unique, size_t buflen) { } static int gsi_connect(Connection *c, char *protocol __attribute__((unused)), - char *host_in) { + char *host_in) +{ static int activated = 0; static globus_xio_stack_t stack_gsi; globus_result_t result; @@ -308,17 +337,21 @@ static int gsi_connect(Connection *c, char *protocol __attribute__((unused)), if (!host) return C_ERROR; info.connection_name = 0; - if ((colon = strchr(host, ':')) != 0) { + if ((colon = strchr(host, ':')) != 0) + { *colon = 0; portname = colon + 1; - } else { + } + else + { portname = "mdsips"; } contact_string = (char *)malloc(strlen(host) + 50); sprintf(contact_string, "%s:%d", host, GetPort(portname)); free(host); - if (activated == 0) { + if (activated == 0) + { doit(result, globus_module_activate(GLOBUS_XIO_MODULE), "GSI XIO Activate", return C_ERROR); activated = 1; @@ -375,18 +408,20 @@ static void readCallback(globus_xio_handle_t xio_handle __attribute__((unused)), globus_size_t nbytes __attribute__((unused)), globus_xio_data_descriptor_t data_desc __attribute__((unused)), - void *userarg) { + void *userarg) +{ int id = userarg ? *(int *)userarg : -1; - if (id > 0) { + if (id > 0) + { GSI_INFO *info = getGsiInfo(id); - if (info) { + if (info) + { globus_result_t res __attribute__((unused)); globus_byte_t buff[1]; int status = DoMessage(id); - if - STATUS_OK - res = globus_xio_register_read(info->xio_handle, buff, 0, 0, 0, - readCallback, userarg); + if (STATUS_OK) + res = globus_xio_register_read(info->xio_handle, buff, 0, 0, 0, + readCallback, userarg); } } } @@ -394,13 +429,15 @@ static void readCallback(globus_xio_handle_t xio_handle __attribute__((unused)), static void acceptCallback(globus_xio_server_t server, globus_xio_handle_t xio_handle, globus_result_t result __attribute__((unused)), - void *userarg) { + void *userarg) +{ globus_result_t res; char *username; int status; int id; GSI_INFO *info_s = (GSI_INFO *)userarg; - if (info_s != 0) { + if (info_s != 0) + { GSI_INFO info; info.tcp_driver = info_s->tcp_driver; info.gsi_driver = info_s->gsi_driver; @@ -408,18 +445,19 @@ static void acceptCallback(globus_xio_server_t server, info.connection_name = 0; res = globus_xio_open(xio_handle, NULL, NULL); testStatus(res, "mdsip_accept_cp, open"); - if (res == GLOBUS_SUCCESS) { + if (res == GLOBUS_SUCCESS) + { status = AcceptConnection("gsi", "gsi", 0, &info, sizeof(info), &id, &username); - if - STATUS_OK { - globus_byte_t buff[1]; - doit(res, - globus_xio_register_read( - xio_handle, buff, 0, 0, 0, readCallback, - memcpy(malloc(sizeof(id)), &id, sizeof(id))), - "GSI Register Read", DisconnectFromMds(id)); - } + if (STATUS_OK) + { + globus_byte_t buff[1]; + doit(res, + globus_xio_register_read( + xio_handle, buff, 0, 0, 0, readCallback, + memcpy(malloc(sizeof(id)), &id, sizeof(id))), + "GSI Register Read", DisconnectFromMds(id)); + } } res = globus_xio_server_register_accept(server, acceptCallback, userarg); testStatus(res, @@ -429,7 +467,8 @@ static void acceptCallback(globus_xio_server_t server, } } -static int gsi_listen(int argc, char **argv) { +static int gsi_listen(int argc, char **argv) +{ Options options[] = { {"p", "port", 1, 0, 0}, {"S", "security", 1, 0, 0}, {0, 0, 0, 0, 0}}; globus_xio_stack_t stack; @@ -451,7 +490,8 @@ static int gsi_listen(int argc, char **argv) { sl = GLOBUS_XIO_GSI_PROTECTION_LEVEL_INTEGRITY; else if (strcmp(security_level, "privacy") == 0) sl = GLOBUS_XIO_GSI_PROTECTION_LEVEL_PRIVACY; - else { + else + { fprintf(stderr, "Invalid security level specified, must be one of " "none,integrity or private\n"); exit(C_ERROR); @@ -466,7 +506,8 @@ static int gsi_listen(int argc, char **argv) { globus_xio_driver_load("gsi", &info.gsi_driver); globus_xio_stack_push_driver(stack, info.gsi_driver); globus_xio_attr_init(&server_attr); - if (GetMulti()) { + if (GetMulti()) + { res = globus_xio_attr_cntl(server_attr, info.tcp_driver, GLOBUS_XIO_TCP_SET_PORT, GetPort(0)); res = globus_xio_attr_cntl(server_attr, info.tcp_driver, @@ -477,7 +518,9 @@ static int gsi_listen(int argc, char **argv) { GLOBUS_XIO_TCP_SET_NODELAY, GLOBUS_TRUE); res = globus_xio_attr_cntl(server_attr, info.tcp_driver, GLOBUS_XIO_TCP_SET_KEEPALIVE, GLOBUS_TRUE); - } else { + } + else + { globus_xio_attr_cntl(server_attr, info.tcp_driver, GLOBUS_XIO_TCP_SET_HANDLE, STDIN_FILENO); } @@ -490,24 +533,30 @@ static int gsi_listen(int argc, char **argv) { globus_xio_attr_cntl(server_attr, info.gsi_driver, GLOBUS_XIO_GSI_SET_DELEGATION_MODE, GLOBUS_XIO_GSI_DELEGATION_MODE_FULL); - if (GetMulti()) { + if (GetMulti()) + { res = globus_xio_server_create((globus_xio_server_t *)&info.xio_handle, server_attr, stack); testStatus(res, "gsi_listen,server_create"); - if (res == GLOBUS_SUCCESS) { + if (res == GLOBUS_SUCCESS) + { res = globus_xio_server_register_accept( (globus_xio_server_t)info.xio_handle, acceptCallback, &info); if (res != GLOBUS_SUCCESS) exit(C_ERROR); - else { - while (1) { + else + { + while (1) + { res = globus_mutex_lock(&globus_l_mutex); res = globus_cond_wait(&globus_l_cond, &globus_l_mutex); res = globus_mutex_unlock(&globus_l_mutex); } } } - } else { + } + else + { char *username; int status; int id; @@ -518,8 +567,9 @@ static int gsi_listen(int argc, char **argv) { testStatus(res, "get handle to connection"); status = AcceptConnection("gsi", "gsi", 0, &info, sizeof(info), &id, &username); - if - STATUS_OK while (DoMessage(id)); + if (STATUS_OK) + while (DoMessage(id)) + ; } return C_OK; } diff --git a/mdstcpip/IoRoutinesThread.c b/mdstcpip/IoRoutinesThread.c index 80326f0ede..0a2b9a5720 100644 --- a/mdstcpip/IoRoutinesThread.c +++ b/mdstcpip/IoRoutinesThread.c @@ -31,9 +31,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #define PARENT_THREAD ((pthread_t)-1) -static int io_disconnect(Connection *c) { +static int io_disconnect(Connection *c) +{ io_pipes_t *p = get_pipes(c); - if (p && p->pth != PARENT_THREAD) { + if (p && p->pth != PARENT_THREAD) + { #ifdef _WIN32 if (WaitForSingleObject(p->pid, 0) == WAIT_TIMEOUT) TerminateThread(p->pid, 0); @@ -48,7 +50,8 @@ static int io_disconnect(Connection *c) { return C_OK; } -static void io_cleanup(void *pp) { +static void io_cleanup(void *pp) +{ void *ctx = (void *)-1; int id; char *info_name; @@ -56,9 +59,11 @@ static void io_cleanup(void *pp) { size_t info_len = 0; pthread_t me = pthread_self(); while ((id = NextConnection(&ctx, &info_name, (void *)&info, &info_len)) != - INVALID_CONNECTION_ID) { + INVALID_CONNECTION_ID) + { if (info_name && strcmp(info_name, PROTOCOL) == 0 && - pthread_equal(info->pth, me)) { + pthread_equal(info->pth, me)) + { DisconnectConnection(id); break; } @@ -66,15 +71,16 @@ static void io_cleanup(void *pp) { free(pp); } -static void io_listen(void *pp) { +static void io_listen(void *pp) +{ int id, status; pthread_cleanup_push(io_cleanup, pp); INIT_AND_FREE_ON_EXIT(char *, username); status = AcceptConnection("thread", "thread", 0, pp, sizeof(io_pipes_t), &id, &username); FREE_NOW(username); - if - STATUS_OK while (DoMessage(id)); + while (STATUS_OK) + status = DoMessage(id); close_pipe(((io_pipes_t *)pp)->in); close_pipe(((io_pipes_t *)pp)->out); pthread_cleanup_pop(1); @@ -82,7 +88,8 @@ static void io_listen(void *pp) { inline static int io_connect(Connection *c, char *protocol __attribute__((unused)), - char *host __attribute__((unused))) { + char *host __attribute__((unused))) +{ #ifdef _WIN32 io_pipes_t p = {NULL, NULL, NULL, 0}, *pp = calloc(sizeof(p), 1); pp->pth = PARENT_THREAD; @@ -95,19 +102,23 @@ inline static int io_connect(Connection *c, if (!CreatePipe(&pp->in, &p.out, &saAttr, 0)) fprintf(stderr, "Stdin CreatePipe"); if (!(p.pid = CreateThread(NULL, DEFAULT_STACKSIZE, (void *)io_listen, pp, 0, - NULL))) { + NULL))) + { #else io_pipes_t p, *pp = malloc(sizeof(p)); int pipe_up[2], pipe_dn[2], ok_up, ok_dn; ok_up = pipe(pipe_up); ok_dn = pipe(pipe_dn); - if (ok_up || ok_dn) { + if (ok_up || ok_dn) + { perror("Error in mdsip io_connect creating pipes\n"); - if (!ok_up) { + if (!ok_up) + { close(pipe_up[0]); close(pipe_up[1]); } - if (!ok_dn) { + if (!ok_dn) + { close(pipe_dn[0]); close(pipe_dn[1]); } @@ -118,7 +129,8 @@ inline static int io_connect(Connection *c, pp->in = pipe_up[0]; pp->out = pipe_dn[1]; pp->pth = PARENT_THREAD; - if (pthread_create(&p.pth, NULL, (void *)io_listen, pp)) { + if (pthread_create(&p.pth, NULL, (void *)io_listen, pp)) + { #endif close_pipe(p.in); close_pipe(p.out); @@ -131,5 +143,5 @@ inline static int io_connect(Connection *c, } const IoRoutines thread_routines = {io_connect, io_send, io_recv, NULL, - NULL, NULL, NULL, io_disconnect, + NULL, NULL, NULL, io_disconnect, io_recv_to, NULL}; diff --git a/mdstcpip/IoRoutinesTunnel.c b/mdstcpip/IoRoutinesTunnel.c index 79791b6fe4..c7e0a7e2b4 100644 --- a/mdstcpip/IoRoutinesTunnel.c +++ b/mdstcpip/IoRoutinesTunnel.c @@ -26,11 +26,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define PROT_TUNNEL #include "ioroutines_pipes.h" -static int io_disconnect(Connection *c) { +static int io_disconnect(Connection *c) +{ io_pipes_t *p = get_pipes(c); - if (p) { + if (p) + { #ifdef _WIN32 - if (p->pid) { + if (p->pid) + { DWORD exitcode; if (GetExitCodeProcess(p->pid, &exitcode) && exitcode == 9009) fprintf(stderr, "Protocol is not supported.\n"); @@ -45,7 +48,8 @@ static int io_disconnect(Connection *c) { close(p->out); int p_pid = p->pid; int pid = fork(); - if (pid == 0) { + if (pid == 0) + { int i; for (i = 30; !waitpid(p_pid, NULL, WNOHANG) && i-- > 0;) usleep(100000); @@ -61,12 +65,14 @@ static int io_disconnect(Connection *c) { } #ifndef _WIN32 -static void ChildSignalHandler(int num __attribute__((unused))) { +static void ChildSignalHandler(int num __attribute__((unused))) +{ // Ensure that the handler does not spoil errno. int saved_errno = errno; pid_t pid; int status; - while ((pid = waitpid((pid_t)-1, &status, WNOHANG)) > 0) { + while ((pid = waitpid((pid_t)-1, &status, WNOHANG)) > 0) + { #ifdef DEBUG printf("pid: %d, exited: %d, stop signal: %d, term signal: %d, exit " "status: %d\n", @@ -79,9 +85,11 @@ static void ChildSignalHandler(int num __attribute__((unused))) { void *info; size_t info_len = 0; while ((id = NextConnection(&ctx, &info_name, &info, &info_len)) != - INVALID_CONNECTION_ID) { + INVALID_CONNECTION_ID) + { if (info_name && strcmp(info_name, PROTOCOL) == 0 && - ((io_pipes_t *)info)->pid == pid) { + ((io_pipes_t *)info)->pid == pid) + { DisconnectConnection(id); break; } @@ -91,7 +99,8 @@ static void ChildSignalHandler(int num __attribute__((unused))) { } #endif -static int io_connect(Connection *c, char *protocol, char *host) { +static int io_connect(Connection *c, char *protocol, char *host) +{ #ifdef _WIN32 size_t len = strlen(protocol) * 2 + strlen(host) + 512; char *cmd = (char *)malloc(len); @@ -102,16 +111,19 @@ static int io_connect(Connection *c, char *protocol, char *host) { saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; - struct { + struct + { HANDLE rd; HANDLE wr; } pipe_p2c = {NULL, NULL}, pipe_c2p = {NULL, NULL}; HANDLE tmp; - if (!CreatePipe(&pipe_c2p.rd, &pipe_c2p.wr, &saAttr, 0)) { + if (!CreatePipe(&pipe_c2p.rd, &pipe_c2p.wr, &saAttr, 0)) + { fprintf(stderr, "pipe_c2p CreatePipe"); goto err; } - if (!CreatePipe(&pipe_p2c.rd, &pipe_p2c.wr, &saAttr, 0)) { + if (!CreatePipe(&pipe_p2c.rd, &pipe_p2c.wr, &saAttr, 0)) + { fprintf(stderr, "pipe_p2c CreatePipe"); goto err; } @@ -119,7 +131,8 @@ static int io_connect(Connection *c, char *protocol, char *host) { GetCurrentProcess(), &pipe_p2c.wr, 0, FALSE, DUPLICATE_SAME_ACCESS)) CloseHandle(tmp); - if (!SetHandleInformation(pipe_p2c.wr, HANDLE_FLAG_INHERIT, 0)) { + if (!SetHandleInformation(pipe_p2c.wr, HANDLE_FLAG_INHERIT, 0)) + { fprintf(stderr, "pipe_p2c SetHandleInformation"); goto err; }; @@ -138,7 +151,8 @@ static int io_connect(Connection *c, char *protocol, char *host) { BOOL bSuccess = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &siStartInfo, &piProcInfo); free(cmd); - if (bSuccess) { // parent + if (bSuccess) + { // parent io_pipes_t p; p.in = pipe_c2p.rd; p.out = pipe_p2c.wr; @@ -163,26 +177,31 @@ err:; CloseHandle(pipe_c2p.wr); return C_ERROR; #else - struct { + struct + { int rd; int wr; } pipe_p2c, pipe_c2p; int err_p2c = pipe((int *)&pipe_p2c); int err_c2p = pipe((int *)&pipe_c2p); - if (err_p2c || err_c2p) { + if (err_p2c || err_c2p) + { perror("Error in mdsip io_connect creating pipes\n"); - if (!err_p2c) { + if (!err_p2c) + { close(pipe_p2c.rd); close(pipe_p2c.wr); } - if (!err_c2p) { + if (!err_c2p) + { close(pipe_c2p.rd); close(pipe_c2p.wr); } return C_ERROR; } pid_t pid = fork(); - if (pid < 0) { // error + if (pid < 0) + { // error fprintf(stderr, "Error %d from fork()\n", errno); close(pipe_c2p.rd); close(pipe_c2p.wr); @@ -190,7 +209,8 @@ err:; close(pipe_p2c.wr); return C_ERROR; } - if (pid > 0) { // parent + if (pid > 0) + { // parent io_pipes_t p; p.in = pipe_c2p.rd; p.out = pipe_p2c.wr; @@ -228,12 +248,14 @@ err:; close(pipe_c2p.rd); fcntl(pipe_c2p.wr, F_SETFD, FD_CLOEXEC); int err = execvp(localcmd, arglist) ? errno : 0; - if (err == 2) { + if (err == 2) + { char *c = protocol; for (; *c; c++) *c = toupper(*c); fprintf(stderr, "Protocol %s is not supported.\n", protocol); - } else if ((errno = err)) + } + else if ((errno = err)) perror("Client process terminated"); exit(err); } @@ -241,7 +263,8 @@ err:; } static int io_listen(int argc __attribute__((unused)), - char **argv __attribute__((unused))) { + char **argv __attribute__((unused))) +{ int id, status; INIT_AND_FREE_ON_EXIT(char *, username); #ifdef _WIN32 @@ -262,11 +285,11 @@ static int io_listen(int argc __attribute__((unused)), status = AcceptConnection(GetProtocol(), PROTOCOL, 0, &p, sizeof(p), &id, &username); FREE_NOW(username); - if - STATUS_OK while (DoMessage(id)); + while (STATUS_OK) + status = DoMessage(id); return C_OK; } const IoRoutines tunnel_routines = {io_connect, io_send, io_recv, NULL, - io_listen, NULL, NULL, io_disconnect, + io_listen, NULL, NULL, io_disconnect, io_recv_to, NULL}; diff --git a/mdstcpip/LoadIo.c b/mdstcpip/LoadIo.c index af85d26190..10353c6e8a 100644 --- a/mdstcpip/LoadIo.c +++ b/mdstcpip/LoadIo.c @@ -39,14 +39,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern IoRoutines tunnel_routines; extern IoRoutines thread_routines; -IoRoutines *LoadIo(char *protocol_in) { +IoRoutines *LoadIo(char *protocol_in) +{ if (protocol_in == 0) protocol_in = "TCP"; char *protocol = strcpy((char *)malloc(strlen(protocol_in) + 1), protocol_in); size_t i; for (i = 0; i < strlen(protocol); i++) protocol[i] = toupper(protocol[i]); - if (strcmp(protocol, "THREAD") == 0) { + if (strcmp(protocol, "THREAD") == 0) + { free(protocol); return &thread_routines; } diff --git a/mdstcpip/MakeDescrip.c b/mdstcpip/MakeDescrip.c index 1fedd59828..b87bf64e12 100644 --- a/mdstcpip/MakeDescrip.c +++ b/mdstcpip/MakeDescrip.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. struct descrip *MakeDescripWithLength(struct descrip *in_descrip, char dtype, int length, char ndims, int *dims, - void *ptr) { + void *ptr) +{ int i; in_descrip->dtype = dtype; in_descrip->ndims = ndims; @@ -49,7 +50,8 @@ struct descrip *MakeDescripWithLength(struct descrip *in_descrip, char dtype, //////////////////////////////////////////////////////////////////////////////// struct descrip *MakeDescrip(struct descrip *in_descrip, char dtype, char ndims, - int *dims, void *ptr) { + int *dims, void *ptr) +{ int i; in_descrip->dtype = dtype; in_descrip->ndims = ndims; diff --git a/mdstcpip/MdsClose.c b/mdstcpip/MdsClose.c index 467c4136af..1027c6757b 100644 --- a/mdstcpip/MdsClose.c +++ b/mdstcpip/MdsClose.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsClose ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsClose(int id) { +int MdsClose(int id) +{ struct descrip ansarg; STATIC_CONSTANT char *expression = "TreeClose()"; int status = MdsValue(id, expression, &ansarg, NULL); diff --git a/mdstcpip/MdsDispatchEvent.c b/mdstcpip/MdsDispatchEvent.c index 63b76331b6..66e7833469 100644 --- a/mdstcpip/MdsDispatchEvent.c +++ b/mdstcpip/MdsDispatchEvent.c @@ -31,11 +31,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsDispachEvent /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void MdsDispatchEvent(int id) { +void MdsDispatchEvent(int id) +{ INIT_STATUS; Message *m; - if ((m = GetMdsMsg(id, &status)) != 0) { - if (STATUS_OK && m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) { + if ((m = GetMdsMsg(id, &status)) != 0) + { + if (STATUS_OK && m->h.msglen == (sizeof(MsgHdr) + sizeof(MdsEventInfo))) + { MdsEventInfo *event = (MdsEventInfo *)m->bytes; (*event->astadr)(event->astprm, 12, event->data); } diff --git a/mdstcpip/MdsEventAst.c b/mdstcpip/MdsEventAst.c index 987918c3ca..234dfa346f 100644 --- a/mdstcpip/MdsEventAst.c +++ b/mdstcpip/MdsEventAst.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// int MdsEventAst(int id, char *eventnam, void (*astadr)(), void *astprm, - int *eventid) { + int *eventid) +{ struct descrip eventnamarg; struct descrip infoarg; @@ -48,7 +49,8 @@ int MdsEventAst(int id, char *eventnam, void (*astadr)(), void *astprm, eventnam), MakeDescrip((struct descrip *)&infoarg, DTYPE_UCHAR, 1, &size, &info), (struct descrip *)&ansarg, (struct descrip *)NULL); - if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) { + if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) + { *eventid = *(int *)ansarg.ptr; } free(ansarg.ptr); diff --git a/mdstcpip/MdsEventCan.c b/mdstcpip/MdsEventCan.c index a0e1aabb7f..774342f948 100644 --- a/mdstcpip/MdsEventCan.c +++ b/mdstcpip/MdsEventCan.c @@ -30,7 +30,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsEventCan /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsEventCan(int id, int eventid) { +int MdsEventCan(int id, int eventid) +{ struct descrip eventarg; struct descrip ansarg = {0}; int status = MdsValue( diff --git a/mdstcpip/MdsOpen.c b/mdstcpip/MdsOpen.c index e1f9a79658..8744d90977 100644 --- a/mdstcpip/MdsOpen.c +++ b/mdstcpip/MdsOpen.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsOpen /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsOpen(int id, char *tree, int shot) { +int MdsOpen(int id, char *tree, int shot) +{ struct descrip treearg; struct descrip shotarg; struct descrip ansarg; diff --git a/mdstcpip/MdsPut.c b/mdstcpip/MdsPut.c index b31399460b..ee5bd6962a 100644 --- a/mdstcpip/MdsPut.c +++ b/mdstcpip/MdsPut.c @@ -32,7 +32,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsPut //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsPut(int id, char *node, char *expression, ...) { +int MdsPut(int id, char *node, char *expression, ...) +{ /**** NOTE: NULL terminated argument list expected ****/ int i; int status = 1; @@ -52,21 +53,21 @@ int MdsPut(int id, char *node, char *expression, ...) { status = SendArg(id, i, arglist[i]->dtype, nargs, ArgLen(arglist[i]), arglist[i]->ndims, arglist[i]->dims, arglist[i]->ptr); free(putexpr); - if - STATUS_OK { - char dtype; - int dims[MAX_DIMS]; - char ndims; - short len; - int numbytes; - void *dptr; - void *mem = 0; - status = GetAnswerInfoTS(id, &dtype, &len, &ndims, dims, &numbytes, &dptr, - &mem); - if (STATUS_OK && dtype == DTYPE_LONG && ndims == 0 && - numbytes == sizeof(int)) - memcpy(&status, dptr, numbytes); - free(mem); - } + if (STATUS_OK) + { + char dtype; + int dims[MAX_DIMS]; + char ndims; + short len; + int numbytes; + void *dptr; + void *mem = 0; + status = GetAnswerInfoTS(id, &dtype, &len, &ndims, dims, &numbytes, &dptr, + &mem); + if (STATUS_OK && dtype == DTYPE_LONG && ndims == 0 && + numbytes == sizeof(int)) + memcpy(&status, dptr, numbytes); + free(mem); + } return status; } diff --git a/mdstcpip/MdsSetCompression.c b/mdstcpip/MdsSetCompression.c index 12e4a3d46d..e5155369fa 100644 --- a/mdstcpip/MdsSetCompression.c +++ b/mdstcpip/MdsSetCompression.c @@ -31,14 +31,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsSetCompression ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsSetCompression(int id, int level) { +int MdsSetCompression(int id, int level) +{ int old_level; if (level < 0) level = 0; else if (level > 9) level = 9; old_level = SetCompressionLevel(level); - if (id != -1) { + if (id != -1) + { char expression[128]; struct descrip ans = {0}; sprintf(expression, "MdsSetCompression(%d)", level); diff --git a/mdstcpip/MdsSetDefault.c b/mdstcpip/MdsSetDefault.c index ce150f2fef..8d91f71c2f 100644 --- a/mdstcpip/MdsSetDefault.c +++ b/mdstcpip/MdsSetDefault.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsSetDefault ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int MdsSetDefault(int id, char *node) { +int MdsSetDefault(int id, char *node) +{ struct descrip nodearg; struct descrip ansarg; STATIC_CONSTANT char *expression = "TreeSetDefault($)"; diff --git a/mdstcpip/MdsValue.c b/mdstcpip/MdsValue.c index 80e5c52150..07ff5a4953 100644 --- a/mdstcpip/MdsValue.c +++ b/mdstcpip/MdsValue.c @@ -38,22 +38,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - {} +#define DBG(...) \ + { \ + } #endif EXPORT int MdsIpGetDescriptor(int id, const char *expression, int nargs, struct descriptor **arglist_in, - struct descriptor_xd *ans_ptr) { + struct descriptor_xd *ans_ptr) +{ int dim = 0; int i, status; Connection *c = FindConnection(id, NULL); - if (c->version >= MDSIP_VERSION_DSC_ARGS) { + if (c->version >= MDSIP_VERSION_DSC_ARGS) + { status = SendArg(id, 0, DTYPE_CSTRING, ++nargs, 0, 0, &dim, (char *)expression); for (i = 1; i < nargs && STATUS_OK; i++) status = SendDsc(id, i, nargs, arglist_in[i - 1]); - } else { + } + else + { EMPTYXD(xd); char *newexp = malloc(strlen(expression) + 256 + nargs * 8); strcpy(newexp, "public fun __si(in " @@ -73,69 +78,75 @@ EXPORT int MdsIpGetDescriptor(int id, const char *expression, int nargs, struct descriptor_a *arr; status = SendArg(id, 1, DTYPE_CSTRING, nargs, strlen(expression), 0, &dim, (char *)expression); - for (i = 2; i < nargs && STATUS_OK; i++) { + for (i = 2; i < nargs && STATUS_OK; i++) + { status = MdsSerializeDscOut(arglist_in[i - 2], &xd); arr = (struct descriptor_a *)xd.pointer; - if - STATUS_OK - status = SendArg(id, i, arr->dtype, nargs, arr->length, 1, - (int *)&arr->arsize, arr->pointer); + if (STATUS_OK) + status = SendArg(id, i, arr->dtype, nargs, arr->length, 1, + (int *)&arr->arsize, arr->pointer); } MdsFree1Dx(&xd, NULL); } - if - STATUS_OK { - char ndims; - void *mem = 0; - int dims[MAX_DIMS] = {0}; - struct descriptor_a ser = {0}; - status = GetAnswerInfoTS(id, (char *)&ser.dtype, (short int *)&ser.length, - &ndims, dims, (int *)&ser.arsize, - (void **)&ser.pointer, &mem); - ser.class = CLASS_A; - if (ser.dtype == DTYPE_SERIAL || ser.dtype == DTYPE_B) - status = MdsSerializeDscIn(ser.pointer, ans_ptr); - else - status = MDSplusERROR; - free(mem); - } + if (STATUS_OK) + { + char ndims; + void *mem = 0; + int dims[MAX_DIMS] = {0}; + struct descriptor_a ser = {0}; + status = GetAnswerInfoTS(id, (char *)&ser.dtype, (short int *)&ser.length, + &ndims, dims, (int *)&ser.arsize, + (void **)&ser.pointer, &mem); + ser.class = CLASS_A; + if (ser.dtype == DTYPE_SERIAL || ser.dtype == DTYPE_B) + status = MdsSerializeDscIn(ser.pointer, ans_ptr); + else + status = MDSplusERROR; + free(mem); + } return status; } EXPORT int _MdsValue(int id, int nargs, struct descrip **arglist, - struct descrip *ans_arg) { + struct descrip *ans_arg) +{ DBG("mdstcpip.MdsValue> '%s'\n", (char *)(**arglist).ptr); int i, status = 1; for (i = 0; i < nargs && STATUS_OK; i++) status = SendArg(id, i, arglist[i]->dtype, nargs, ArgLen(arglist[i]), arglist[i]->ndims, arglist[i]->dims, arglist[i]->ptr); - if - STATUS_OK { - short len; - int numbytes; - void *dptr; - void *mem = 0; - status = GetAnswerInfoTS(id, &ans_arg->dtype, &len, &ans_arg->ndims, - ans_arg->dims, &numbytes, &dptr, &mem); - ans_arg->length = len; - if (numbytes) { - if (ans_arg->dtype == DTYPE_CSTRING) { - ans_arg->ptr = malloc(numbytes + 1); - ((char *)ans_arg->ptr)[numbytes] = 0; - } else if (numbytes > 0) - ans_arg->ptr = malloc(numbytes); - if (numbytes > 0) - memcpy(ans_arg->ptr, dptr, numbytes); - } else - ans_arg->ptr = NULL; - free(mem); + if (STATUS_OK) + { + short len; + int numbytes; + void *dptr; + void *mem = 0; + status = GetAnswerInfoTS(id, &ans_arg->dtype, &len, &ans_arg->ndims, + ans_arg->dims, &numbytes, &dptr, &mem); + ans_arg->length = len; + if (numbytes) + { + if (ans_arg->dtype == DTYPE_CSTRING) + { + ans_arg->ptr = malloc(numbytes + 1); + ((char *)ans_arg->ptr)[numbytes] = 0; + } + else if (numbytes > 0) + ans_arg->ptr = malloc(numbytes); + if (numbytes > 0) + memcpy(ans_arg->ptr, dptr, numbytes); } + else + ans_arg->ptr = NULL; + free(mem); + } else ans_arg->ptr = NULL; return status; } -EXPORT int MdsValue(int id, char *expression, ...) { +EXPORT int MdsValue(int id, char *expression, ...) +{ /**** NOTE: NULL terminated argument list expected ****/ int nargs; struct descrip *arglist[265]; @@ -145,7 +156,8 @@ EXPORT int MdsValue(int id, char *expression, ...) { return _MdsValue(id, nargs, arglist, arglist[nargs]); } -EXPORT int MdsValueDsc(int id, const char *expression, ...) { +EXPORT int MdsValueDsc(int id, const char *expression, ...) +{ /**** NOTE: MDS_END_ARG terminated argument list expected ****/ int nargs; struct descriptor *arglist[265]; @@ -154,14 +166,16 @@ EXPORT int MdsValueDsc(int id, const char *expression, ...) { return MdsIpGetDescriptor(id, expression, nargs, arglist, ans_ptr); } -EXPORT void MdsIpFree(void *ptr) { +EXPORT void MdsIpFree(void *ptr) +{ /* for compatibility malloc memory should be freed by same module/lib * use MdsIpFree to free ans.ptr returned by MdsValue */ free(ptr); } -EXPORT void MdsIpFreeDsc(struct descriptor_xd *xd) { +EXPORT void MdsIpFreeDsc(struct descriptor_xd *xd) +{ /* for compatibility malloc memory should be freed by same module/lib * use MdsIpFreeDsc to free xd returned by MdsValueDsc */ diff --git a/mdstcpip/ParseCommand.c b/mdstcpip/ParseCommand.c index 43ea442425..c169438825 100644 --- a/mdstcpip/ParseCommand.c +++ b/mdstcpip/ParseCommand.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" -void PrintHelp(char *option) { +void PrintHelp(char *option) +{ if (option) printf("Invalid options specified: %s\n\n", option); printf( @@ -80,89 +81,116 @@ void PrintHelp(char *option) { /// Parse standard input command options. /// void ParseCommand(int argc, char **argv, Options options[], int more, - int *rem_argc, char ***rem_argv) { + int *rem_argc, char ***rem_argv) +{ INIT_AS_AND_FREE_ON_EXIT(char **, extra_argv, malloc(argc * sizeof(char *))); int i; int extra_argc = 1; extra_argv[0] = argv[0]; - for (i = 1; i < argc; i++) { + for (i = 1; i < argc; i++) + { char *arg = argv[i]; size_t arglen = strlen(arg); - if (arg[0] == '-') { + if (arg[0] == '-') + { int option_found = FALSE; int opt, islong; arg++; arglen--; - if ((islong = *arg == '-')) { + if ((islong = *arg == '-')) + { arg++; arglen--; } if (strcmp("help", arg) == 0) PrintHelp(0); - for (opt = 0; options[opt].short_name || options[opt].long_name; opt++) { - if (islong) { + for (opt = 0; options[opt].short_name || options[opt].long_name; opt++) + { + if (islong) + { if (!options[opt].long_name) continue; char *long_name = options[opt].long_name; size_t optlen = strlen(long_name); if ((arglen == optlen || (arglen > optlen && arg[optlen] == '=')) && - strncmp(arg, long_name, optlen) == 0) { + strncmp(arg, long_name, optlen) == 0) + { option_found = options[opt].present = TRUE; if (arglen > optlen) options[opt].value = &arg[optlen + 1]; - else if (options[opt].expects_value == 1) { - if (++i < argc) { + else if (options[opt].expects_value == 1) + { + if (++i < argc) + { options[opt].value = argv[i]; - } else { + } + else + { fprintf(stderr, "Invalid option: --%s expects value but non given.\n", options[opt].long_name); exit(1); // ERROR_INVALID_PARAMETER } - } else if (options[opt].expects_value == 2) { + } + else if (options[opt].expects_value == 2) + { if (i + 1 < argc && argv[i + 1][0] != '-') options[opt].value = argv[++i]; } break; } - } else if (options[opt].short_name && - arg[0] == options[opt].short_name[0]) { + } + else if (options[opt].short_name && + arg[0] == options[opt].short_name[0]) + { option_found = options[opt].present = TRUE; - if (arglen > 1) { + if (arglen > 1) + { options[opt].value = &arg[arg[1] == '=' ? 2 : 1]; - } else if (options[opt].expects_value == 1) { + } + else if (options[opt].expects_value == 1) + { if (++i < argc) options[opt].value = argv[i]; - else { + else + { fprintf(stderr, "Invalid option: -%s expects value but non given.\n", options[opt].short_name); exit(1); // ERROR_INVALID_PARAMETER } - } else if (options[opt].expects_value == 2) { + } + else if (options[opt].expects_value == 2) + { if (i + 1 < argc && argv[i + 1][0] != '-') options[opt].value = argv[++i]; } break; } } - if (!option_found) { + if (!option_found) + { if (!more) PrintHelp(argv[i]); - else { + else + { extra_argv[extra_argc] = argv[i]; extra_argc++; } } - } else { + } + else + { extra_argv[extra_argc] = argv[i]; extra_argc++; } } - if (rem_argc) { + if (rem_argc) + { *rem_argc = extra_argc; *rem_argv = extra_argv; - } else + } + else free(extra_argv); FREE_CANCEL(); } @@ -170,7 +198,8 @@ void ParseCommand(int argc, char **argv, Options options[], int more, /// /// Parse standard input command options. /// -void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv) { +void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv) +{ Options options[] = {{"P", "protocol", 1, 0, 0}, {"h", "hostfile", 1, 0, 0}, {"s", "server", 0, 0, 0}, @@ -183,27 +212,35 @@ void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv) { SetProtocol(options[0].value); if (options[1].present && options[1].value) SetHostfile(options[1].value); - if (options[2].present) { - if (options[3].present) { + if (options[2].present) + { + if (options[3].present) + { fprintf( stderr, "Invalid option: Cannot select both server mode and multi mode\n\n"); PrintHelp(0); - } else { + } + else + { SetMulti(1); SetContextSwitching(0); } } - if (options[3].present) { + if (options[3].present) + { SetMulti(1); SetContextSwitching(1); } - if (options[4].present) { + if (options[4].present) + { int cmpr = 9; - if (options[4].value) { + if (options[4].value) + { char *invalid; cmpr = strtol(options[4].value, &invalid, 0); - if (cmpr == 0 && (errno == EINVAL || options[4].value == invalid)) { + if (cmpr == 0 && (errno == EINVAL || options[4].value == invalid)) + { fprintf(stderr, "Invalid compression value: %s\n", options[4].value); exit(1); } diff --git a/mdstcpip/ProcessMessage.c b/mdstcpip/ProcessMessage.c index 6fded2b0b9..282e15ebbf 100644 --- a/mdstcpip/ProcessMessage.c +++ b/mdstcpip/ProcessMessage.c @@ -73,13 +73,15 @@ extern int TdiSaveContext(); #define max(a, b) (((a) > (b)) ? (a) : (b)) static void ConvertBinary(int num, int sign_extend, short in_length, - char *in_ptr, short out_length, char *out_ptr) { + char *in_ptr, short out_length, char *out_ptr) +{ int i; int j; signed char *in_p = (signed char *)in_ptr; signed char *out_p = (signed char *)out_ptr; short min_len = min(out_length, in_length); - for (i = 0; i < num; i++, in_p += in_length, out_p += out_length) { + for (i = 0; i < num; i++, in_p += in_length, out_p += out_length) + { for (j = 0; j < min_len; j++) out_p[j] = in_p[j]; for (; j < out_length; j++) @@ -88,15 +90,18 @@ static void ConvertBinary(int num, int sign_extend, short in_length, } static void ConvertFloat(int num, int in_type, char in_length, char *in_ptr, - int out_type, char out_length, char *out_ptr) { + int out_type, char out_length, char *out_ptr) +{ int i; char *in_p; char *out_p; for (i = 0, in_p = in_ptr, out_p = out_ptr; i < num; - i++, in_p += in_length, out_p += out_length) { + i++, in_p += in_length, out_p += out_length) + { char *ptr = in_p; char cray_f[8]; - if (in_type == CvtCRAY) { + if (in_type == CvtCRAY) + { int j, k; for (j = 0; j < 2; j++) for (k = 0; k < 4; k++) @@ -109,7 +114,8 @@ static void ConvertFloat(int num, int in_type, char in_length, char *in_ptr, } CvtConvertFloat(ptr, in_type, out_p, out_type, 0); #ifdef WORDS_BIGENDIAN - if (out_type == CvtCRAY) { + if (out_type == CvtCRAY) + { int j, k; ptr = out_p; for (j = 0; j < 2; j++) @@ -132,12 +138,13 @@ static void ConvertFloat(int num, int in_type, char in_length, char *in_ptr, /// static Message *BuildResponse(int client_type, unsigned char message_id, - int status, struct descriptor *d) { + int status, struct descriptor *d) +{ Message *m = NULL; /* if (SupportsCompression(client_type)) { INIT_AND_FREEXD_ON_EXIT(out); - if IS_OK(MdsSerializeDscOut(d, &out)) { + if (IS_OK(MdsSerializeDscOut(d, &out))) { struct descriptor_a* array = (struct descriptor_a*)out.pointer; m = malloc(sizeof(MsgHdr) + array->arsize); memset(&m->h,0,sizeof(MsgHdr)); @@ -156,8 +163,10 @@ static Message *BuildResponse(int client_type, unsigned char message_id, int nbytes = (d->class == CLASS_S) ? d->length : ((array_coeff *)d)->arsize; int num = nbytes / ((d->length < 1) ? 1 : d->length); short length = d->length; - if (CType(client_type) == CRAY_CLIENT) { - switch (d->dtype) { + if (CType(client_type) == CRAY_CLIENT) + { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_ULONG: case DTYPE_SHORT: @@ -178,8 +187,11 @@ static Message *BuildResponse(int client_type, unsigned char message_id, break; } nbytes = num * length; - } else if (CType(client_type) == CRAY_IEEE_CLIENT) { - switch (d->dtype) { + } + else if (CType(client_type) == CRAY_IEEE_CLIENT) + { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_SHORT: length = 4; @@ -204,7 +216,8 @@ static Message *BuildResponse(int client_type, unsigned char message_id, m->h.length = length; if (d->class == CLASS_S) m->h.ndims = 0; - else { + else + { int i; array_coeff *a = (array_coeff *)d; m->h.ndims = a->dimct; @@ -216,10 +229,12 @@ static Message *BuildResponse(int client_type, unsigned char message_id, for (i = m->h.ndims; i < MAX_DIMS; i++) m->h.dims[i] = 0; } - switch (CType(client_type)) { + switch (CType(client_type)) + { case IEEE_CLIENT: case JAVA_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_F: ConvertFloat(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, (char)m->h.length, m->bytes); @@ -272,7 +287,8 @@ static Message *BuildResponse(int client_type, unsigned char message_id, } break; case CRAY_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_ULONG: ConvertBinary(num, 0, d->length, d->pointer, m->h.length, m->bytes); @@ -316,7 +332,8 @@ static Message *BuildResponse(int client_type, unsigned char message_id, } break; case CRAY_IEEE_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_ULONG: ConvertBinary(num, 0, d->length, d->pointer, m->h.length, m->bytes); @@ -378,7 +395,8 @@ static Message *BuildResponse(int client_type, unsigned char message_id, } break; case VMSG_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_F: memcpy(m->bytes, d->pointer, nbytes); m->h.dtype = DTYPE_FLOAT; @@ -431,7 +449,8 @@ static Message *BuildResponse(int client_type, unsigned char message_id, } break; default: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_F: memcpy(m->bytes, d->pointer, nbytes); m->h.dtype = DTYPE_FLOAT; @@ -487,17 +506,21 @@ static Message *BuildResponse(int client_type, unsigned char message_id, return m; } -static void GetErrorText(int status, mdsdsc_xd_t *xd) { +static void GetErrorText(int status, mdsdsc_xd_t *xd) +{ static DESCRIPTOR(unknown, "unknown error occured"); struct descriptor message = {0, DTYPE_T, CLASS_S, 0}; - if ((message.pointer = MdsGetMsg(status)) != NULL) { + if ((message.pointer = MdsGetMsg(status)) != NULL) + { message.length = strlen(message.pointer); MdsCopyDxXd(&message, xd); - } else + } + else MdsCopyDxXd((struct descriptor *)&unknown, xd); } -static void ClientEventAst(MdsEventList *e, int data_len, char *data) { +static void ClientEventAst(MdsEventList *e, int data_len, char *data) +{ int conid = e->conid; Connection *c = FindConnection(e->conid, 0); int i; @@ -506,13 +529,15 @@ static void ClientEventAst(MdsEventList *e, int data_len, char *data) { JMdsEventInfo *info; int len; // Check Connection: if down, cancel the event and return - if (!c) { + if (!c) + { MDSEventCan(e->eventid); return; } client_type = c->client_type; LockAsts(); - if (CType(client_type) == JAVA_CLIENT) { + if (CType(client_type) == JAVA_CLIENT) + { len = sizeof(MsgHdr) + sizeof(JMdsEventInfo); m = memset(malloc(len), 0, len); m->h.ndims = 0; @@ -525,7 +550,9 @@ static void ClientEventAst(MdsEventList *e, int data_len, char *data) { for (i = data_len; i < 12; i++) info->data[i] = 0; info->eventid = e->jeventid; - } else { + } + else + { m = memset(malloc(sizeof(MsgHdr) + e->info_len), 0, sizeof(MsgHdr) + e->info_len); m->h.ndims = 0; @@ -548,7 +575,8 @@ static void ClientEventAst(MdsEventList *e, int data_len, char *data) { * mdstcpip/ProcessMessage.c * Problems with the implementation are likely to be fixed in all locations. */ -typedef struct { +typedef struct +{ void **ctx; int status; #ifndef _WIN32 @@ -559,19 +587,22 @@ typedef struct { mdsdsc_xd_t *const xd_out; } worker_args_t; -typedef struct { +typedef struct +{ worker_args_t *const wa; mdsdsc_xd_t *const xdp; } worker_cleanup_t; -static void WorkerCleanup(worker_cleanup_t *const wc) { +static void WorkerCleanup(worker_cleanup_t *const wc) +{ #ifndef _WIN32 CONDITION_SET(wc->wa->condition); #endif free_xd(wc->xdp); } -static int WorkerThread(void *args) { +static int WorkerThread(void *args) +{ EMPTYXD(xd); worker_cleanup_t wc = {(worker_args_t *)args, &xd}; pthread_cleanup_push((void *)WorkerCleanup, (void *)&wc); @@ -580,14 +611,14 @@ static int WorkerThread(void *args) { wc.wa->status = TdiIntrinsic(OPC_EXECUTE, wc.wa->connection->nargs, wc.wa->connection->descrip, &xd); ++TDI_INTRINSIC_REC; - if - IS_OK(wc.wa->status) - wc.wa->status = TdiData(xd.pointer, wc.wa->xd_out MDS_END_ARG); + if (IS_OK(wc.wa->status)) + wc.wa->status = TdiData(xd.pointer, wc.wa->xd_out MDS_END_ARG); pthread_cleanup_pop(1); return wc.wa->status; } -static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { +static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) +{ // fprintf(stderr,"starting task for connection %d\n",connection->id); void *tdicontext[6], *pc = NULL; MDSplusThreadStatic_t *mts = MDSplusThreadStatic(NULL); @@ -602,7 +633,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { .connection = connection, .xd_out = ans_xd }; - if (GetContextSwitching()) { + if (GetContextSwitching()) + { pc = TreeCtxPush(&connection->DBID); TdiSaveContext(tdicontext); TdiRestoreContext(connection->tdicontext); @@ -610,7 +642,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { #ifdef _WIN32 HANDLE hWorker = CreateThread(NULL, DEFAULT_STACKSIZE * 16, (void *)WorkerThread, &wa, 0, NULL); - if (!hWorker) { + if (!hWorker) + { errno = GetLastError(); perror("ERROR CreateThread"); wa.status = MDSplusFATAL; @@ -618,7 +651,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { } int canceled = B_FALSE; if (connection->io->check) - while (WaitForSingleObject(hWorker, 100) == WAIT_TIMEOUT) { + while (WaitForSingleObject(hWorker, 100) == WAIT_TIMEOUT) + { if (!connection->io->check(connection)) continue; fflush(stdout); @@ -634,7 +668,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { pthread_t Worker; _CONDITION_LOCK(wa.condition); CREATE_THREAD(Worker, *16, WorkerThread, &wa); - if (c_status) { + if (c_status) + { perror("ERROR pthread_create"); _CONDITION_UNLOCK(wa.condition); pthread_cond_destroy(&WorkerRunning.cond); @@ -643,7 +678,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { goto end; } int canceled = B_FALSE; - for (;;) { + for (;;) + { _CONDITION_WAIT_1SEC(wa.condition, ); if (WorkerRunning.value) break; @@ -661,7 +697,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { fflush(stdout); if (WorkerRunning.value) fprintf(stderr, " ok\n"); - else { + else + { fprintf(stderr, " failed - sending SIGCHLD\n"); pthread_kill(Worker, SIGCHLD); } @@ -676,7 +713,8 @@ static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) { wa.status = TdiABORT; #endif end:; - if (pc) { + if (pc) + { TdiSaveContext(connection->tdicontext); TdiRestoreContext(tdicontext); TreeCtxPop(pc); @@ -700,7 +738,8 @@ end:; /// \param connection the Connection instance filled with proper descriptor /// arguments \return the execute message answer built using BuildAnswer() /// -static Message *ExecuteMessage(Connection *connection) { +static Message *ExecuteMessage(Connection *connection) +{ Message *ans = 0; // return message instance // int status = 1; // return status // @@ -714,7 +753,8 @@ static Message *ExecuteMessage(Connection *connection) { // AST REQUEST // if (StrCompare(connection->descrip[0], (struct descriptor *)&eventastreq) == - 0) { + 0) + { static int eventid = -1; static DESCRIPTOR_LONG(eventiddsc, &eventid); MdsEventList *newe = (MdsEventList *)malloc(sizeof(MdsEventList)); @@ -731,29 +771,37 @@ static Message *ExecuteMessage(Connection *connection) { newe, &newe->eventid); free(evname); - if (java) { + if (java) + { newe->info = 0; newe->info_len = 0; newe->jeventid = *connection->descrip[2]->pointer; - } else { + } + else + { newe->info = (MdsEventInfo *)memcpy(malloc(info->arsize), info->pointer, info->arsize); newe->info_len = info->arsize; newe->info->eventid = newe->eventid; } newe->next = 0; - if (!(status & 1)) { + if (!(status & 1)) + { eventiddsc.pointer = (void *)&eventid; free(newe->info); free(newe); - } else { + } + else + { MdsEventList *e; eventiddsc.pointer = (void *)&newe->eventid; - if (connection->event) { + if (connection->event) + { for (e = connection->event; e->next; e = e->next) ; e->next = newe; - } else + } + else connection->event = newe; } if (!java) @@ -761,7 +809,8 @@ static Message *ExecuteMessage(Connection *connection) { } // CAN REQUEST // else if (StrCompare(connection->descrip[0], - (struct descriptor *)&eventcanreq) == 0) { + (struct descriptor *)&eventcanreq) == 0) + { static int eventid; static DESCRIPTOR_LONG(eventiddsc, &eventid); MdsEventList *e; @@ -770,11 +819,13 @@ static Message *ExecuteMessage(Connection *connection) { eventid = *(int *)connection->descrip[1]->pointer; else eventid = (int)*connection->descrip[1]->pointer; - if (connection->event) { + if (connection->event) + { for (p = &connection->event, e = connection->event; e && (e->eventid != eventid); p = &e->next, e = e->next) ; - if (e) { + if (e) + { /**/ MDSEventCan(e->eventid); /**/ *p = e->next; free(e); @@ -784,13 +835,14 @@ static Message *ExecuteMessage(Connection *connection) { ans = BuildResponse(client_type, message_id, status, &eventiddsc); } // NORMAL TDI COMMAND // - else { + else + { INIT_AND_FREEXD_ON_EXIT(ans_xd); status = executeCommand(connection, &ans_xd); - if - STATUS_NOT_OK - GetErrorText(status, &ans_xd); - if (GetCompressionLevel() != connection->compression_level) { + if (STATUS_NOT_OK) + GetErrorText(status, &ans_xd); + if (GetCompressionLevel() != connection->compression_level) + { connection->compression_level = GetCompressionLevel(); if (connection->compression_level > GetMaxCompressionLevel()) connection->compression_level = GetMaxCompressionLevel(); @@ -804,7 +856,8 @@ static Message *ExecuteMessage(Connection *connection) { return ans; } -static inline char *replaceBackslashes(char *filename) { +static inline char *replaceBackslashes(char *filename) +{ char *ptr; while ((ptr = strchr(filename, '\\')) != NULL) *ptr = '/'; @@ -821,18 +874,23 @@ static inline char *replaceBackslashes(char *filename) { /// \param message the message to process /// \return message answer /// -Message *ProcessMessage(Connection *connection, Message *message) { +Message *ProcessMessage(Connection *connection, Message *message) +{ Message *ans = 0; // COMING NEW MESSAGE // // reset connection id // - if (connection->message_id != message->h.message_id) { + if (connection->message_id != message->h.message_id) + { FreeDescriptors(connection); - if (message->h.nargs < MDSIP_MAX_ARGS - 1) { + if (message->h.nargs < MDSIP_MAX_ARGS - 1) + { connection->message_id = message->h.message_id; connection->nargs = message->h.nargs; - } else { + } + else + { DESCRIPTOR_LONG(status_d, 0); int status = 0; status_d.pointer = (char *)&status; @@ -844,21 +902,25 @@ Message *ProcessMessage(Connection *connection, Message *message) { // STANADARD COMMANDS //////////////////////////////////////////////////////// // idx < nargs //////////////////////////////////////////////////////// - if (message->h.descriptor_idx < connection->nargs) { + if (message->h.descriptor_idx < connection->nargs) + { // set connection to the message client_type // connection->client_type = message->h.client_type; -#define COPY_DESC(name, GENERATOR, ...) \ - do { \ - const GENERATOR(__VA_ARGS__); \ - *(void **)&d = memcpy(malloc(sizeof(tmp)), &tmp, sizeof(tmp)); \ +#define COPY_DESC(name, GENERATOR, ...) \ + do \ + { \ + const GENERATOR(__VA_ARGS__); \ + *(void **)&d = memcpy(malloc(sizeof(tmp)), &tmp, sizeof(tmp)); \ } while (0) // d -> reference to curent idx argument desctriptor // struct descriptor *d = connection->descrip[message->h.descriptor_idx]; - if (message->h.dtype == DTYPE_SERIAL) { - if (d && d->class != CLASS_XD) { + if (message->h.dtype == DTYPE_SERIAL) + { + if (d && d->class != CLASS_XD) + { if (d->class == CLASS_D && d->pointer) free(d->pointer); free(d); @@ -867,34 +929,41 @@ Message *ProcessMessage(Connection *connection, Message *message) { connection->descrip[message->h.descriptor_idx] = d; return ans; } - if (!d) { + if (!d) + { // instance the connection descriptor field // const short lengths[] = {0, 0, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 8, 16, 0}; - if (message->h.ndims == 0) { + if (message->h.ndims == 0) + { d = calloc(1, sizeof(struct descriptor_s)); d->class = CLASS_S; - } else + } + else COPY_DESC(d, DESCRIPTOR_A_COEFF, tmp, 0, 0, 0, MAX_DIMS, 0); d->length = message->h.dtype < DTYPE_CSTRING ? lengths[message->h.dtype] : message->h.length; d->dtype = message->h.dtype; - if (d->class == CLASS_A) { + if (d->class == CLASS_A) + { array_coeff *a = (array_coeff *)d; int num = 1; int i; a->dimct = message->h.ndims; - for (i = 0; i < a->dimct; i++) { + for (i = 0; i < a->dimct; i++) + { a->m[i] = message->h.dims[i]; num *= a->m[i]; } a->arsize = a->length * num; a->pointer = a->a0 = malloc(a->arsize); - } else + } + else d->pointer = d->length ? malloc(d->length) : 0; // set new instance // connection->descrip[message->h.descriptor_idx] = d; } - if (d) { + if (d) + { // have valid connection descriptor instance // // copy the message buffer into the descriptor // @@ -902,13 +971,15 @@ Message *ProcessMessage(Connection *connection, Message *message) { : (int)((array_coeff *)d)->arsize; int num = dbytes / max(1, d->length); - switch (CType(connection->client_type)) { + switch (CType(connection->client_type)) + { case IEEE_CLIENT: case JAVA_CLIENT: memcpy(d->pointer, message->bytes, dbytes); break; case CRAY_IEEE_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_ULONG: ConvertBinary(num, 0, message->h.length, message->bytes, d->length, @@ -925,7 +996,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { } break; case CRAY_CLIENT: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_USHORT: case DTYPE_ULONG: ConvertBinary(num, 0, message->h.length, message->bytes, d->length, @@ -955,7 +1027,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { } break; default: - switch (d->dtype) { + switch (d->dtype) + { case DTYPE_FLOAT: ConvertFloat(num, CvtVAX_F, (char)message->h.length, message->bytes, CvtIEEE_S, sizeof(float), d->pointer); @@ -986,7 +1059,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { break; } } - switch (d->dtype) { + switch (d->dtype) + { default: break; case DTYPE_FLOAT: @@ -1004,7 +1078,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { } // CALL EXECUTE MESSAGE // - if (message->h.descriptor_idx == (message->h.nargs - 1)) { + if (message->h.descriptor_idx == (message->h.nargs - 1)) + { ans = ExecuteMessage(connection); } } @@ -1012,12 +1087,15 @@ Message *ProcessMessage(Connection *connection, Message *message) { // SPECIAL I/O MESSAGES ////////////////////////////////////////////////////// // idx >= nargs ////////////////////////////////////////////////////// - else { + else + { connection->client_type = message->h.client_type; const mdsio_t *mdsio = (mdsio_t *)message->h.dims; - switch (message->h.descriptor_idx) { - case MDS_IO_OPEN_K: { + switch (message->h.descriptor_idx) + { + case MDS_IO_OPEN_K: + { char *filename = (char *)message->bytes; int options = mdsio->open.options; mode_t mode = mdsio->open.mode; @@ -1040,7 +1118,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_CLOSE_K: { + case MDS_IO_CLOSE_K: + { int fd = mdsio->close.fd; int ans_o = MDS_IO_CLOSE(fd); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; @@ -1048,7 +1127,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_LSEEK_K: { + case MDS_IO_LSEEK_K: + { int fd = mdsio->lseek.fd; int64_t offset = mdsio->lseek.offset; SWAP_INT_IF_BIGENDIAN(&offset); @@ -1061,7 +1141,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { SWAP_INT_IF_BIGENDIAN(ans_d.pointer); break; } - case MDS_IO_READ_K: { + case MDS_IO_READ_K: + { int fd = mdsio->read.fd; size_t count = mdsio->read.count; void *buf = malloc(count); @@ -1069,13 +1150,16 @@ Message *ProcessMessage(Connection *connection, Message *message) { #ifdef USE_PERF TreePerfRead(nbytes); #endif - if (nbytes > 0) { + if (nbytes > 0) + { DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); if ((size_t)nbytes != count) perror("READ_K wrong byte count"); ans = BuildResponse(connection->client_type, connection->message_id, 1, (struct descriptor *)&ans_d); - } else { + } + else + { DESCRIPTOR(ans_d, ""); ans = BuildResponse(connection->client_type, connection->message_id, 1, (struct descriptor *)&ans_d); @@ -1083,7 +1167,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { free(buf); break; } - case MDS_IO_WRITE_K: { + case MDS_IO_WRITE_K: + { /* from http://man7.org/linux/man-pages/man2/write.2.html * On Linux, write() (and similar system calls) will transfer at most * 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes @@ -1103,7 +1188,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_LOCK_K: { + case MDS_IO_LOCK_K: + { int fd = mdsio->lock.fd; off_t offset = mdsio->lock.offset; SWAP_INT_IF_BIGENDIAN(&offset); @@ -1118,7 +1204,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { deleted ? 3 : 1, &ans_d); break; } - case MDS_IO_EXISTS_K: { + case MDS_IO_EXISTS_K: + { char *filename = message->bytes; int ans_o = MDS_IO_EXISTS(filename); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; @@ -1126,7 +1213,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_REMOVE_K: { + case MDS_IO_REMOVE_K: + { char *filename = message->bytes; int ans_o = MDS_IO_REMOVE(filename); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; @@ -1134,7 +1222,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_RENAME_K: { + case MDS_IO_RENAME_K: + { char *old = message->bytes; char *new = message->bytes + strlen(old) + 1; int ans_o = MDS_IO_RENAME(old, new); @@ -1143,7 +1232,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { &ans_d); break; } - case MDS_IO_READ_X_K: { + case MDS_IO_READ_X_K: + { int fd = mdsio->read_x.fd; off_t offset = mdsio->read_x.offset; SWAP_INT_IF_BIGENDIAN(&offset); @@ -1151,13 +1241,16 @@ Message *ProcessMessage(Connection *connection, Message *message) { void *buf = malloc(count); int deleted; size_t nbytes = MDS_IO_READ_X(fd, offset, buf, count, &deleted); - if (nbytes > 0) { + if (nbytes > 0) + { DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); if ((size_t)nbytes != count) perror("READ_X_K wrong byte count"); ans = BuildResponse(connection->client_type, connection->message_id, deleted ? 3 : 1, (struct descriptor *)&ans_d); - } else { + } + else + { DESCRIPTOR(ans_d, ""); ans = BuildResponse(connection->client_type, connection->message_id, deleted ? 3 : 1, (struct descriptor *)&ans_d); @@ -1165,7 +1258,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { free(buf); break; } - case MDS_IO_OPEN_ONE_K: { + case MDS_IO_OPEN_ONE_K: + { char *treename = message->bytes; char *filepath = message->bytes + strlen(treename) + 1; int shot = mdsio->open_one.shot; @@ -1181,7 +1275,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { DESCRIPTOR_A(ans_d, sizeof(char), DTYPE_B, msg, msglen); memcpy(msg, &status, 4); memcpy(msg + 4, &fd, 4); - if (fullpath) { + if (fullpath) + { memcpy(msg + 8, fullpath, msglen - 8); free(fullpath); } @@ -1190,7 +1285,8 @@ Message *ProcessMessage(Connection *connection, Message *message) { free(msg); break; } - default: { + default: + { int ans_o = 0; struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; ans = BuildResponse(connection->client_type, connection->message_id, 1, diff --git a/mdstcpip/RemoveConnection.c b/mdstcpip/RemoveConnection.c index db6dadb94f..787ac9597e 100644 --- a/mdstcpip/RemoveConnection.c +++ b/mdstcpip/RemoveConnection.c @@ -37,22 +37,27 @@ extern int MDSEventCan(); /// \param conid /// \return /// -int RemoveConnection(int conid) { +int RemoveConnection(int conid) +{ int status = 0; Connection *c = FindConnection(conid, 0); - if (c) { + if (c) + { void *tdi_context[6]; MdsEventList *e, *nexte; FreeDescriptors(c); - for (e = c->event; e; e = nexte) { + for (e = c->event; e; e = nexte) + { nexte = e->next; /**/ MDSEventCan(e->eventid); /**/ if (e->info_len > 0) free(e->info); free(e); } - while - IS_OK(_TreeClose(&c->DBID, 0, 0)); + do + { + status = _TreeClose(&c->DBID, 0, 0); + } while (STATUS_OK); TdiSaveContext(tdi_context); TdiDeleteContext(c->tdicontext); TdiRestoreContext(tdi_context); diff --git a/mdstcpip/SendArg.c b/mdstcpip/SendArg.c index 37ffbba868..63becd3b31 100644 --- a/mdstcpip/SendArg.c +++ b/mdstcpip/SendArg.c @@ -30,24 +30,26 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int SendDsc(int id, unsigned char idx, unsigned char nargs, - struct descriptor *dsc) { + struct descriptor *dsc) +{ int status; INIT_AND_FREEXD_ON_EXIT(out); status = MdsSerializeDscOut(dsc, &out); - if - STATUS_OK { - struct descriptor_a *array = (struct descriptor_a *)out.pointer; - int dims[MAX_DIMS] = {0}; - dims[0] = array->arsize; - status = SendArg(id, idx, DTYPE_SERIAL, nargs, 1, 1, dims, - (char *)array->pointer); - } + if (STATUS_OK) + { + struct descriptor_a *array = (struct descriptor_a *)out.pointer; + int dims[MAX_DIMS] = {0}; + dims[0] = array->arsize; + status = SendArg(id, idx, DTYPE_SERIAL, nargs, 1, 1, dims, + (char *)array->pointer); + } FREEXD_NOW(out); return status; } int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, - unsigned short length, char ndims, int *dims, char *bytes) { + unsigned short length, char ndims, int *dims, char *bytes) +{ Connection *c = (idx == 0 || idx > nargs) ? FindConnectionWithLock(id, CON_SENDARG) : FindConnectionSending(id); @@ -62,14 +64,18 @@ int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, // MESSAGE ID // // * if this is the first argument sent, increments connection message id // // * get the connection message_id and store it inside message // - if (idx > nargs) { + if (idx > nargs) + { /**** Special I/O message ****/ - if (idx == MDS_IO_OPEN_ONE_K && c->version < MDSIP_VERSION_OPEN_ONE) { + if (idx == MDS_IO_OPEN_ONE_K && c->version < MDSIP_VERSION_OPEN_ONE) + { UnlockConnection(c); return MDSplusFATAL; } nbytes = dims[0]; - } else { + } + else + { for (i = 0; i < ndims; i++) nbytes *= dims[i]; } @@ -99,7 +105,7 @@ int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, : c->message_id; int status = m->h.message_id ? SendMdsMsgC(c, m, 0) : MDSplusERROR; free(m); - if - STATUS_NOT_OK UnlockConnection(c); + if (STATUS_NOT_OK) + UnlockConnection(c); return status; } diff --git a/mdstcpip/SendMdsMsg.c b/mdstcpip/SendMdsMsg.c index fbc1168deb..c6aa762c12 100644 --- a/mdstcpip/SendMdsMsg.c +++ b/mdstcpip/SendMdsMsg.c @@ -33,20 +33,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" static int SendBytes(Connection *c, void *buffer, size_t bytes_to_send, - int options) { + int options) +{ char *bptr = (char *)buffer; - if (c && c->io) { + if (c && c->io) + { int tries = 0; - while ((bytes_to_send > 0) && (tries < 10)) { + while ((bytes_to_send > 0) && (tries < 10)) + { ssize_t bytes_sent; bytes_sent = c->io->send(c, bptr, bytes_to_send, options); - if (bytes_sent < 0) { - if (errno != EINTR) { + if (bytes_sent < 0) + { + if (errno != EINTR) + { perror("Error sending data to remote server"); return MDSplusERROR; } tries++; - } else { + } + else + { bytes_to_send -= bytes_sent; bptr += bytes_sent; if (bytes_sent) @@ -55,7 +62,8 @@ static int SendBytes(Connection *c, void *buffer, size_t bytes_to_send, tries++; } } - if (tries >= 10) { + if (tries >= 10) + { char msg[256]; sprintf(msg, "\rsend failed, shutting down connection %d", c->id); perror(msg); @@ -67,14 +75,16 @@ static int SendBytes(Connection *c, void *buffer, size_t bytes_to_send, return MDSplusERROR; } -int SendMdsMsgC(Connection *c, Message *m, int msg_options) { +int SendMdsMsgC(Connection *c, Message *m, int msg_options) +{ unsigned long len = m->h.msglen - sizeof(m->h); unsigned long clength = 0; Message *cm = 0; int status; int do_swap = 0; /*Added to handle byte swapping with compression */ if (len > 0 && GetCompressionLevel() > 0 && - m->h.client_type != SENDCAPABILITIES) { + m->h.client_type != SENDCAPABILITIES) + { clength = len; cm = (Message *)malloc(m->h.msglen + 4); } @@ -82,18 +92,22 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) { c->io->flush(c); if (m->h.client_type == SENDCAPABILITIES) m->h.status = GetCompressionLevel(); - if ((m->h.client_type & SwapEndianOnServer) != 0) { - if (Endian(m->h.client_type) != Endian(ClientType())) { + if ((m->h.client_type & SwapEndianOnServer) != 0) + { + if (Endian(m->h.client_type) != Endian(ClientType())) + { FlipData(m); FlipHeader(&m->h); do_swap = 1; /* Recall that the header field msglen needs to be swapped */ } - } else + } + else m->h.client_type = ClientType(); if (clength && compress2((unsigned char *)cm->bytes + 4, &clength, (unsigned char *)m->bytes, len, GetCompressionLevel()) == 0 && - clength < len) { + clength < len) + { cm->h = m->h; cm->h.client_type |= COMPRESSED; memcpy(cm->bytes, &cm->h.msglen, 4); @@ -101,16 +115,19 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) { if (do_swap) FlipBytes(4, (char *)&cm->h.msglen); status = SendBytes(c, (char *)cm, msglen, msg_options); - } else + } + else status = SendBytes(c, (char *)m, len + sizeof(MsgHdr), msg_options); if (clength) free(cm); return status; } -int SendMdsMsg(int id, Message *m, int msg_options) { +int SendMdsMsg(int id, Message *m, int msg_options) +{ Connection *c = FindConnection(id, NULL); - if (SendMdsMsgC(c, m, msg_options) == SsINTERNAL) { + if (SendMdsMsgC(c, m, msg_options) == SsINTERNAL) + { DisconnectConnection(id); return MDSplusFATAL; } diff --git a/mdstcpip/cvtdef.h b/mdstcpip/cvtdef.h index bf85321c12..2bcb01852c 100644 --- a/mdstcpip/cvtdef.h +++ b/mdstcpip/cvtdef.h @@ -11,7 +11,8 @@ //#endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #define __unknown_params ... #else #define __unknown_params @@ -36,8 +37,8 @@ extern "C" { #define CvtCRAY 8 /* Cray Floating point data */ #define CvtIEEE_X 9 /* IEEE X Floating point data */ -extern int CvtConvertFloat(void *invalue, uint32_t indtype, void *outvalue, - uint32_t outdtype, uint32_t options); + extern int CvtConvertFloat(void *invalue, uint32_t indtype, void *outvalue, + uint32_t outdtype, uint32_t options); #ifdef __cplusplus } diff --git a/mdstcpip/ioroutines.h b/mdstcpip/ioroutines.h index cb90c74cab..5535470a09 100644 --- a/mdstcpip/ioroutines.h +++ b/mdstcpip/ioroutines.h @@ -30,15 +30,16 @@ static int GetHostAndPort(char *hostin, struct sockaddr_in *sin); -static int io_reuseCheck(char *host, char *unique, size_t buflen) { +static int io_reuseCheck(char *host, char *unique, size_t buflen) +{ struct sockaddr_in sin; - if - IS_OK(GetHostAndPort(host, &sin)) { - uint8_t *addr = (uint8_t *)&sin.sin_addr; - snprintf(unique, buflen, "%s://%u.%u.%u.%u:%u", PROT, addr[0], addr[1], - addr[2], addr[3], (unsigned)ntohs(sin.sin_port)); - return C_OK; - } + if (IS_OK(GetHostAndPort(host, &sin))) + { + uint8_t *addr = (uint8_t *)&sin.sin_addr; + snprintf(unique, buflen, "%s://%u.%u.%u.%u:%u", PROT, addr[0], addr[1], + addr[2], addr[3], (unsigned)ntohs(sin.sin_port)); + return C_OK; + } *unique = 0; return C_ERROR; } diff --git a/mdstcpip/ioroutinesV6.h b/mdstcpip/ioroutinesV6.h index b1501f6afb..81cd829b31 100644 --- a/mdstcpip/ioroutinesV6.h +++ b/mdstcpip/ioroutinesV6.h @@ -6,8 +6,8 @@ #define SIN_ADDR sin6_addr #define SIN_PORT sin6_port #define _INADDR_ANY in6addr_any -#define GET_IPHOST(sin) \ - char iphost[INET6_ADDRSTRLEN]; \ +#define GET_IPHOST(sin) \ + char iphost[INET6_ADDRSTRLEN]; \ inet_ntop(AF_INET6, &sin.sin6_addr, iphost, INET6_ADDRSTRLEN) #include @@ -30,18 +30,20 @@ static int GetHostAndPort(char *hostin, struct sockaddr_in6 *sin); -static int io_reuseCheck(char *host, char *unique, size_t buflen) { +static int io_reuseCheck(char *host, char *unique, size_t buflen) +{ struct sockaddr_in6 sin; - if - IS_OK(GetHostAndPort(host, &sin)) { - uint16_t *addr = (uint16_t *)&sin.sin6_addr; - snprintf(unique, buflen, - "%s://%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x#%u", PROT, addr[0], - addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], - (unsigned)ntohs(sin.sin6_port)); - return C_OK; - } - else { + if (IS_OK(GetHostAndPort(host, &sin))) + { + uint16_t *addr = (uint16_t *)&sin.sin6_addr; + snprintf(unique, buflen, + "%s://%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x#%u", PROT, addr[0], + addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7], + (unsigned)ntohs(sin.sin6_port)); + return C_OK; + } + else + { *unique = 0; return C_ERROR; } diff --git a/mdstcpip/ioroutines_pipes.h b/mdstcpip/ioroutines_pipes.h index 4456cfd960..b0ae55a6f7 100644 --- a/mdstcpip/ioroutines_pipes.h +++ b/mdstcpip/ioroutines_pipes.h @@ -44,7 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define close_pipe(p) close(p) #endif -typedef struct { +typedef struct +{ #ifdef _WIN32 HANDLE out; HANDLE in; @@ -61,7 +62,8 @@ typedef struct { #endif } io_pipes_t; -static io_pipes_t *get_pipes(Connection *c) { +static io_pipes_t *get_pipes(Connection *c) +{ size_t len; char *info_name; io_pipes_t *p = (io_pipes_t *)GetConnectionInfoC(c, &info_name, 0, &len); @@ -72,7 +74,8 @@ static io_pipes_t *get_pipes(Connection *c) { } static ssize_t io_send(Connection *c, const void *buffer, size_t buflen, - int nowait __attribute__((unused))) { + int nowait __attribute__((unused))) +{ io_pipes_t *p = get_pipes(c); if (!p) return -1; @@ -85,7 +88,8 @@ static ssize_t io_send(Connection *c, const void *buffer, size_t buflen, } static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, - int to_msec) { + int to_msec) +{ io_pipes_t *p = get_pipes(c); if (!p) return -1; @@ -103,10 +107,13 @@ static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, return ReadFile(p->in, buffer, buflen, (DWORD *)&num, NULL) ? num : -1; #else struct timeval to, timeout; - if (to_msec < 0) { + if (to_msec < 0) + { timeout.tv_sec = 1; timeout.tv_usec = 0; - } else { + } + else + { timeout.tv_sec = to_msec / 1000; timeout.tv_usec = (to_msec % 1000) * 1000; } @@ -114,7 +121,8 @@ static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, fd_set rf, readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); - do { // loop even for nowait for responsiveness + do + { // loop even for nowait for responsiveness to = timeout; rf = readfds; sel = select(fd + 1, &rf, NULL, NULL, &to); @@ -129,6 +137,7 @@ static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, #endif } -static ssize_t io_recv(Connection *c, void *buffer, size_t buflen) { +static ssize_t io_recv(Connection *c, void *buffer, size_t buflen) +{ return io_recv_to(c, buffer, buflen, -1); } diff --git a/mdstcpip/ioroutinestcp.h b/mdstcpip/ioroutinestcp.h index 7bfa1a3d21..d1a233661c 100644 --- a/mdstcpip/ioroutinestcp.h +++ b/mdstcpip/ioroutinestcp.h @@ -1,9 +1,11 @@ #define _TCP DEFINE_INITIALIZESOCKETS; #ifdef _WIN32 -static void socketerror() { +static void socketerror() +{ int err; - switch (err = WSAGetLastError()) { + switch (err = WSAGetLastError()) + { case 0: perror(""); break; @@ -59,18 +61,20 @@ static void socketerror() { fprintf(stderr, "WSA %d\n", err); } } -#define PERROR(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - socketerror(); \ +#define PERROR(...) \ + do \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, ": "); \ + socketerror(); \ } while (0) #else -#define PERROR(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - perror(""); \ +#define PERROR(...) \ + do \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, ": "); \ + perror(""); \ } while (0) #include #endif @@ -93,14 +97,16 @@ static int io_flush(Connection *c); /// \param s socket to set options to /// \param reuse set SO_REUSEADDR to be able to reuse the same address. /// -static void SetSocketOptions(SOCKET s, int reuse) { +static void SetSocketOptions(SOCKET s, int reuse) +{ int sendbuf = SEND_BUF_SIZE, recvbuf = RECV_BUF_SIZE; int one = 1; #ifndef _WIN32 fcntl(s, F_SETFD, FD_CLOEXEC); #endif const char *tcp_window_size = getenv("TCP_WINDOW_SIZE"); - if (tcp_window_size && strlen(tcp_window_size)) { + if (tcp_window_size && strlen(tcp_window_size)) + { recvbuf = sendbuf = strtol(tcp_window_size, NULL, 0); setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&recvbuf, sizeof(int)); setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&sendbuf, sizeof(int)); @@ -120,7 +126,8 @@ static void SetSocketOptions(SOCKET s, int reuse) { #ifdef _WIN32 static SOCKET int_sock = INVALID_SOCKET; static void *old_handler; -static void int_select(int signo) { +static void int_select(int signo) +{ signal(signo, old_handler); raise(signo); if (int_sock != INVALID_SOCKET) @@ -128,17 +135,19 @@ static void int_select(int signo) { } #endif static int io_connect(Connection *c, char *protocol __attribute__((unused)), - char *host) { + char *host) +{ struct SOCKADDR_IN sin; SOCKET sock; - if - IS_NOT_OK(GetHostAndPort(host, &sin)) { - fprintf(stderr, "Connect failed to host: %s\n", host); - return C_ERROR; - } + if (IS_NOT_OK(GetHostAndPort(host, &sin))) + { + fprintf(stderr, "Connect failed to host: %s\n", host); + return C_ERROR; + } INITIALIZESOCKETS; sock = socket(AF_T, SOCK_STREAM, 0); - if (sock == INVALID_SOCKET) { + if (sock == INVALID_SOCKET) + { PERROR("Error creating socket"); return C_ERROR; } @@ -161,7 +170,8 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), err = ioctlsocket(sock, FIONBIO, &ul); if (err == 0) err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); - if ((err == -1) && (WSAGetLastError() == WSAEWOULDBLOCK)) { + if ((err == -1) && (WSAGetLastError() == WSAEWOULDBLOCK)) + { fd_set rdfds, wrfds; FD_ZERO(&wrfds); FD_ZERO(&rdfds); @@ -170,7 +180,8 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), old_handler = signal(SIGINT, int_select); err = select(maxsock, &rdfds, &wrfds, NULL, timeout); signal(SIGINT, old_handler); - if (err < 1) { + if (err < 1) + { if (err < 0) PERROR("Error in connect"); else @@ -178,7 +189,8 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), close(int_sock); goto error; } - if (FD_ISSET(int_sock, &rdfds)) { + if (FD_ISSET(int_sock, &rdfds)) + { errno = EINTR; perror("Error in connect"); goto error; @@ -190,11 +202,13 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), ul = FALSE; ioctlsocket(sock, FIONBIO, &ul); #else // _WIN32 - if (connectTimer.tv_sec) { + if (connectTimer.tv_sec) + { err = fcntl(sock, F_SETFL, O_NONBLOCK); if (err == 0) err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); - if ((err == -1) && (errno == EINPROGRESS)) { + if ((err == -1) && (errno == EINPROGRESS)) + { fd_set writefds; FD_ZERO(&writefds); FD_SET(sock, &writefds); @@ -203,7 +217,8 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), pthread_sigmask(SIG_SETMASK, &sigmask, &origmask); err = select(sock + 1, NULL, &writefds, NULL, &connectTimer); pthread_sigmask(SIG_SETMASK, &origmask, NULL); - if (err < 1) { + if (err < 1) + { if (err == 0) fprintf(stderr, "Error in connect: timeout\n"); else @@ -215,10 +230,12 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), } if (err != -1) fcntl(sock, F_SETFL, 0); - } else + } + else err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); #endif // !_WIN32 - if (err == -1) { + if (err == -1) + { PERROR("Error in connect to service"); error:; shutdown(sock, SHUT_RDWR); @@ -234,10 +251,12 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), // FLUSH ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static int io_flush(Connection *c) { +static int io_flush(Connection *c) +{ #if !defined(__sparc__) SOCKET sock = getSocket(c); - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { struct timeval timout = {0, 1}; int err; FIONREAD_TYPE nbytes; @@ -251,11 +270,14 @@ static int io_flush(Connection *c) { while (((((err = select(sock + 1, &readfds, &writefds, 0, &timout)) > 0) && FD_ISSET(sock, &readfds)) || (err == -1 && errno == EINTR)) && - tries < 10) { + tries < 10) + { tries++; - if (FD_ISSET(sock, &readfds)) { + if (FD_ISSET(sock, &readfds)) + { err = ioctl(sock, FIONREAD, &nbytes); - if (nbytes > 0 && err != -1) { + if (nbytes > 0 && err != -1) + { nbytes = recv(sock, buffer, sizeof(buffer) > (size_t)nbytes ? nbytes @@ -264,7 +286,8 @@ static int io_flush(Connection *c) { if (nbytes > 0) tries = 0; } - } else + } + else FD_SET(sock, &readfds); timout.tv_usec = 100000; FD_CLR(sock, &writefds); @@ -278,14 +301,18 @@ static int io_flush(Connection *c) { // LISTEN //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static short getPort(char *name) { +static short getPort(char *name) +{ short port; struct servent *sp; port = htons((short)strtol(name, NULL, 0)); - if (port == 0) { + if (port == 0) + { sp = getservbyname(name, "tcp"); - if (!sp) { - if (errno) { + if (!sp) + { + if (errno) + { fprintf(stderr, "Error: unknown service port %s/%s; %s\n", name, PROT, strerror(errno)); exit(0); @@ -299,7 +326,8 @@ static short getPort(char *name) { return port; } -static int io_listen(int argc, char **argv) { +static int io_listen(int argc, char **argv) +{ Options options[] = {{"p", "port", 1, 0, 0}, #ifdef _WIN32 {"S", "sockethandle", 1, 0, 0}, @@ -339,7 +367,8 @@ static int io_listen(int argc, char **argv) { // SOCKET // /* Create the socket and set it up to accept connections. */ SOCKET ssock = socket(AF_T, SOCK_STREAM, 0); - if (ssock == INVALID_SOCKET) { + if (ssock == INVALID_SOCKET) + { PERROR("Error getting Connection Socket"); exit(EXIT_FAILURE); } @@ -354,12 +383,14 @@ static int io_listen(int argc, char **argv) { sin.SIN_PORT = port; sin.SIN_FAMILY = AF_T; sin.SIN_ADDR = _INADDR_ANY; - if (bind(ssock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { + if (bind(ssock, (struct sockaddr *)&sin, sizeof(sin)) < 0) + { PERROR("Error binding to service (tcp_listen)"); exit(EXIT_FAILURE); } // LISTEN // - if (listen(ssock, 128) < 0) { + if (listen(ssock, 128) < 0) + { PERROR("Error from listen"); exit(EXIT_FAILURE); } @@ -367,16 +398,19 @@ static int io_listen(int argc, char **argv) { struct timeval readto, timeout = {1, 0}; int error_count = 0; fd_set readfds; - for (;;) { + for (;;) + { readfds = fdactive; readto = timeout; int num = select(FD_SETSIZE, &readfds, NULL, NULL, &readto); if (num == 0) continue; // timeout - if (num > 0) { + if (num > 0) + { // read ready from socket list // error_count = 0; - if (FD_ISSET(ssock, &readfds)) { + if (FD_ISSET(ssock, &readfds)) + { socklen_t len = sizeof(sin); int id = -1; char *username; @@ -386,25 +420,29 @@ static int io_listen(int argc, char **argv) { PERROR("Error accepting socket"); else SetSocketOptions(sock, 0); - if - IS_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username)) { - // add client to client list // - Client *client = memset(malloc(sizeof(Client)), 0, sizeof(Client)); - client->id = id; - client->sock = sock; - client->next = ClientList; - client->username = username; - client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; - client->iphost = getHostInfo(sock, &client->host); - ClientList = client; - // add socket to active sockets // - FD_SET(sock, &fdactive); - } - } else { + if (IS_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username))) + { + // add client to client list // + Client *client = memset(malloc(sizeof(Client)), 0, sizeof(Client)); + client->id = id; + client->sock = sock; + client->next = ClientList; + client->username = username; + client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; + client->iphost = getHostInfo(sock, &client->host); + ClientList = client; + // add socket to active sockets // + FD_SET(sock, &fdactive); + } + } + else + { // Process Clients in list searching for active sockets // Client *c = ClientList; - while (c) { - if (FD_ISSET(c->sock, &readfds)) { + while (c) + { + if (FD_ISSET(c->sock, &readfds)) + { // process active socket client // MdsSetClientAddr(c->addr); // DO MESSAGE ---> ProcessMessage() on client c // @@ -415,35 +453,46 @@ static int io_listen(int argc, char **argv) { if (c_chk) FD_CLR(c->sock, &readfds); c = ClientList; - } else + } + else c = c->next; } } - } else if (errno == EINTR) { + } + else if (errno == EINTR) + { continue; // exit(EINTR);// signal interrupt; can be triggered by python // os.system() - } else { // Select returned -1 error code + } + else + { // Select returned -1 error code error_count++; PERROR("error in main select"); fprintf(stderr, "Error count=%d\n", error_count); fflush(stderr); - if (error_count > 100) { + if (error_count > 100) + { fprintf(stderr, "Error count exceeded, shutting down\n"); exit(EXIT_FAILURE); - } else { + } + else + { Client *c; FD_ZERO(&fdactive); if (ssock != INVALID_SOCKET) FD_SET(ssock, &fdactive); - for (c = ClientList; c; c = c->next) { + for (c = ClientList; c; c = c->next) + { struct SOCKADDR_IN sin; socklen_t n = sizeof(sin); LockAsts(); - if (getpeername(c->sock, (struct sockaddr *)&sin, &n)) { + if (getpeername(c->sock, (struct sockaddr *)&sin, &n)) + { fprintf(stderr, "Removed disconnected client\n"); fflush(stderr); CloseConnection(c->id); - } else + } + else FD_SET(c->sock, &fdactive); UnlockAsts(); } diff --git a/mdstcpip/ioroutinesudt.h b/mdstcpip/ioroutinesudt.h index ae870c7a09..1b85ed30c6 100644 --- a/mdstcpip/ioroutinesudt.h +++ b/mdstcpip/ioroutinesudt.h @@ -1,18 +1,20 @@ #ifdef _WIN32 #define close closesocket -#define PERROR(...) \ - do { \ - errno = WSAGetLastError(); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - perror(""); \ +#define PERROR(...) \ + do \ + { \ + errno = WSAGetLastError(); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, ": "); \ + perror(""); \ } while (0) #undef INVALID_SOCKET #else -#define PERROR(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": %s\n", udt_getlasterror_desc()); \ +#define PERROR(...) \ + do \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, ": %s\n", udt_getlasterror_desc()); \ } while (0) #endif #undef SOCKET @@ -31,24 +33,28 @@ int server_epoll = -1; //////////////////////////////////////////////////////////////////////////////// static int io_connect(Connection *c, char *protocol __attribute__((unused)), - char *host) { + char *host) +{ struct SOCKADDR_IN sin; UDTSOCKET sock; - if - IS_OK(GetHostAndPort(host, &sin)) { - sock = udt_socket(PF_T, SOCK_STREAM, 0); - if (!sock) { - perror("Error in (udt) connect"); - return C_ERROR; - } - if (udt_connect(sock, (struct sockaddr *)&sin, sizeof(sin))) { - PERROR("Error in connect to service"); - return C_ERROR; - } - SetConnectionInfoC(c, PROT, sock, NULL, 0); - return C_OK; + if (IS_OK(GetHostAndPort(host, &sin))) + { + sock = udt_socket(PF_T, SOCK_STREAM, 0); + if (!sock) + { + perror("Error in (udt) connect"); + return C_ERROR; + } + if (udt_connect(sock, (struct sockaddr *)&sin, sizeof(sin))) + { + PERROR("Error in connect to service"); + return C_ERROR; } - else { + SetConnectionInfoC(c, PROT, sock, NULL, 0); + return C_OK; + } + else + { fprintf(stderr, "Connect failed to host: %s\n", host); fflush(stderr); return C_ERROR; @@ -59,7 +65,8 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), // LISTEN //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static int io_listen(int argc, char **argv) { +static int io_listen(int argc, char **argv) +{ Options options[] = {{"p", "port", 1, 0, 0}, #ifdef _WIN32 {"S", "sockethandle", 1, 0, 0}, @@ -75,7 +82,8 @@ static int io_listen(int argc, char **argv) { SetPortname("mdsip"); INITIALIZESOCKETS; server_epoll = udt_epoll_create(); - if (GetMulti()) { + if (GetMulti()) + { ////////////////////////////////////////////////////////////////////////// // MULTIPLE CONNECTION MODE ///////////////////////////////// // multiple connections with own context ///////////////////////////////// @@ -86,9 +94,10 @@ static int io_listen(int argc, char **argv) { int events = UDT_UDT_EPOLL_IN | UDT_UDT_EPOLL_ERR; int gai_stat; static const struct addrinfo hints = {AI_PASSIVE, AF_T, SOCK_STREAM, 0, - 0, 0, 0, 0}; + 0, 0, 0, 0}; gai_stat = getaddrinfo(NULL, GetPortname(), &hints, &result); - if (gai_stat) { + if (gai_stat) + { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_stat)); exit(EXIT_FAILURE); } @@ -101,7 +110,8 @@ static int io_listen(int argc, char **argv) { #else exit(EX_NOPERM); #endif - for (rp = result; rp != NULL; rp = rp->ai_next) { + for (rp = result; rp != NULL; rp = rp->ai_next) + { ssock = udt_socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (ssock == INVALID_SOCKET) continue; @@ -111,19 +121,24 @@ static int io_listen(int argc, char **argv) { } udt_epoll_add_usock(server_epoll, ssock, &events); memset(&sin, 0, sizeof(sin)); - if (udt_listen(ssock, 128) < 0) { + if (udt_listen(ssock, 128) < 0) + { fprintf(stderr, "Error from udt_listen: %s\n", udt_getlasterror_desc()); exit(EXIT_FAILURE); } - for (;;) { + for (;;) + { int i; int readfds_num = 1024; if (udt_epoll_wait2(server_epoll, readfds, &readfds_num, NULL, NULL, 5000, - NULL, NULL, NULL, NULL)) { + NULL, NULL, NULL, NULL)) + { Client *c; LockAsts(); - for (;;) { - for (c = ClientList; c; c = c->next) { + for (;;) + { + for (c = ClientList; c; c = c->next) + { int c_epoll = udt_epoll_create(); UDTSOCKET readfds[1]; UDTSOCKET writefds[1]; @@ -133,7 +148,8 @@ static int io_listen(int argc, char **argv) { int err = udt_epoll_wait2(c_epoll, readfds, &readnum, writefds, &writenum, 0, NULL, NULL, NULL, NULL); udt_epoll_release(c_epoll); - if (err) { + if (err) + { CloseConnection(c->id); goto next; break; @@ -144,9 +160,13 @@ static int io_listen(int argc, char **argv) { continue; } UnlockAsts(); - } else { - for (i = 0; readfds_num != 1024 && i < readfds_num; i++) { - if (readfds[i] == ssock) { + } + else + { + for (i = 0; readfds_num != 1024 && i < readfds_num; i++) + { + if (readfds[i] == ssock) + { // int events = UDT_UDT_EPOLL_IN | UDT_UDT_EPOLL_ERR; int len = sizeof(sin); int id = -1; @@ -155,23 +175,27 @@ static int io_listen(int argc, char **argv) { UDTSOCKET sock = udt_accept(ssock, (struct sockaddr *)&sin, &len); status = AcceptConnection(PROT, PROT, sock, NULL, 0, &id, &username); - if - STATUS_OK { - Client *client = - memset(malloc(sizeof(Client)), 0, sizeof(Client)); - client->id = id; - client->sock = sock; - client->next = ClientList; - client->username = username; - client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; - client->iphost = getHostInfo(sock, &client->host); - ClientList = client; - udt_epoll_add_usock(server_epoll, sock, &events); - } - } else { + if (STATUS_OK) + { + Client *client = + memset(malloc(sizeof(Client)), 0, sizeof(Client)); + client->id = id; + client->sock = sock; + client->next = ClientList; + client->username = username; + client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; + client->iphost = getHostInfo(sock, &client->host); + ClientList = client; + udt_epoll_add_usock(server_epoll, sock, &events); + } + } + else + { Client *c; - for (c = ClientList; c;) { - if (c->sock == readfds[i]) { + for (c = ClientList; c;) + { + if (c->sock == readfds[i]) + { Client *c_chk; int c_epoll = udt_epoll_create(); UDTSOCKET readfds[1]; @@ -182,7 +206,8 @@ static int io_listen(int argc, char **argv) { int err = udt_epoll_wait2(c_epoll, readfds, &readnum, writefds, &writenum, 0, NULL, NULL, NULL, NULL); udt_epoll_release(c_epoll); - if (err) { + if (err) + { CloseConnection(c->id); break; } @@ -192,14 +217,16 @@ static int io_listen(int argc, char **argv) { c_chk = c_chk->next) ; c = c_chk ? c->next : ClientList; - } else + } + else c = c->next; } } } } } - } else + } + else runServerMode(&options[1]); return C_ERROR; } diff --git a/mdstcpip/ioroutinesx.h b/mdstcpip/ioroutinesx.h index 8aec01f03e..6ecc69fefa 100644 --- a/mdstcpip/ioroutinesx.h +++ b/mdstcpip/ioroutinesx.h @@ -13,21 +13,24 @@ static int io_check(Connection *c); #else #define io_check NULL #endif -static ssize_t io_recv(Connection *c, void *buffer, size_t len) { +static ssize_t io_recv(Connection *c, void *buffer, size_t len) +{ return io_recv_to(c, buffer, len, -1); } static IoRoutines io_routines = { - io_connect, io_send, io_recv, io_flush, io_listen, + io_connect, io_send, io_recv, io_flush, io_listen, io_authorize, io_reuseCheck, io_disconnect, io_recv_to, io_check}; #include #include #include #define IP(addr) ((uint8_t *)&addr) -#define ADDR2IP(a) IP(a)[0], IP(a)[1], IP(a)[2], IP(a)[3] +#define ADDR2IP(a) IP(a) \ + [0], IP(a)[1], IP(a)[2], IP(a)[3] // Connected client definition for client list -typedef struct _client { +typedef struct _client +{ SOCKET sock; int id; char *username; @@ -45,7 +48,8 @@ static Client *ClientList = NULL; //////////////////////////////////////////////////////////////////////////////// // List of active sockets -typedef struct _socket { +typedef struct _socket +{ SOCKET socket; struct _socket *next; } Socket; @@ -55,7 +59,8 @@ static Socket *SocketList = NULL; EXPORT IoRoutines *Io() { return &io_routines; } -static SOCKET getSocket(Connection *c) { +static SOCKET getSocket(Connection *c) +{ size_t len; char *info_name; SOCKET readfd; @@ -65,13 +70,14 @@ static SOCKET getSocket(Connection *c) { static pthread_mutex_t socket_list_mutex = PTHREAD_MUTEX_INITIALIZER; static void unlock_socket_list() { pthread_mutex_unlock(&socket_list_mutex); } -#define LOCK_SOCKET_LIST \ - pthread_mutex_lock(&socket_list_mutex); \ +#define LOCK_SOCKET_LIST \ + pthread_mutex_lock(&socket_list_mutex); \ pthread_cleanup_push(unlock_socket_list, NULL); #define UNLOCK_SOCKET_LIST pthread_cleanup_pop(1); #ifdef _TCP -static void socket_list_cleanup() { +static void socket_list_cleanup() +{ LOCK_SOCKET_LIST; Socket *s; for (s = SocketList; s; s = s->next) @@ -84,15 +90,18 @@ static volatile sig_atomic_t fatal_error_in_progress = 0; #ifndef _WIN32 static struct sigaction act; #endif -static void signal_handler(int sig) { - if (!fatal_error_in_progress) { +static void signal_handler(int sig) +{ + if (!fatal_error_in_progress) + { fatal_error_in_progress = 1; socket_list_cleanup(); } signal(sig, SIG_DFL); raise(sig); } -static void set_signal_handler(int sig) { +static void set_signal_handler(int sig) +{ #ifdef _WIN32 void *old = signal(sig, signal_handler); if (old != SIG_DFL) @@ -105,11 +114,13 @@ static void set_signal_handler(int sig) { } #endif -static void PushSocket(SOCKET socket) { +static void PushSocket(SOCKET socket) +{ LOCK_SOCKET_LIST; #ifdef _TCP static int initialized = FALSE; - if (!initialized) { + if (!initialized) + { #ifndef _WIN32 sigemptyset(&act.sa_mask); act.sa_flags = 0; @@ -129,12 +140,14 @@ static void PushSocket(SOCKET socket) { UNLOCK_SOCKET_LIST; } -static void PopSocket(SOCKET socket) { +static void PopSocket(SOCKET socket) +{ LOCK_SOCKET_LIST; Socket *p, *s; for (s = SocketList, p = 0; s && s->socket != socket; p = s, s = s->next) ; - if (s) { + if (s) + { if (p) p->next = s->next; else @@ -144,7 +157,8 @@ static void PopSocket(SOCKET socket) { UNLOCK_SOCKET_LIST; } -static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) { +static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) +{ int status; INITIALIZESOCKETS; char *host = strdup(hostin); @@ -153,20 +167,29 @@ static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) { size_t i; for (i = 0; i < strlen(host) && host[i] != PORTDELIM; i++) ; - if (i < strlen(host)) { + if (i < strlen(host)) + { host[i] = '\0'; service = &host[i + 1]; - } else { + } + else + { service = "mdsip"; } - if (strtol(service, NULL, 0) == 0) { - if (!getservbyname(service, "tcp")) { + if (strtol(service, NULL, 0) == 0) + { + if (!getservbyname(service, "tcp")) + { char *env_service = getenv(service); - if ((env_service == NULL)) { - if (strcmp(service, "mdsip") == 0) { + if ((env_service == NULL)) + { + if (strcmp(service, "mdsip") == 0) + { service = "8000"; } - } else { + } + else + { service = env_service; } } @@ -174,11 +197,14 @@ static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) { struct addrinfo *info = NULL; static const struct addrinfo hints = {0, AF_T, SOCK_STREAM, 0, 0, 0, 0, 0}; int err = getaddrinfo(host, service, &hints, &info); - if (err) { + if (err) + { status = MDSplusERROR; fprintf(stderr, "Error connecting to host: %s, port %s error=%s\n", host, service, gai_strerror(err)); - } else { + } + else + { memcpy(sin, info->ai_addr, sizeof(*sin) < info->ai_addrlen ? sizeof(*sin) : info->ai_addrlen); status = MDSplusSUCCESS; @@ -189,22 +215,29 @@ static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) { return status; } -static char *getHostInfo(SOCKET sock, char **hostnameptr) { +static char *getHostInfo(SOCKET sock, char **hostnameptr) +{ struct SOCKADDR_IN sin; int err = 0; SOCKLEN_T len = sizeof(sin); - if (!GETPEERNAME(sock, (struct sockaddr *)&sin, &len)) { + if (!GETPEERNAME(sock, (struct sockaddr *)&sin, &len)) + { GET_IPHOST(sin); - if (hostnameptr) { + if (hostnameptr) + { char hbuf[NI_MAXHOST]; if (getnameinfo((struct sockaddr *)&sin, len, hbuf, sizeof(hbuf), NULL, 0, - NI_NAMEREQD) == 0) { + NI_NAMEREQD) == 0) + { *hostnameptr = strdup(hbuf); - } else { + } + else + { struct addrinfo *entry, *info = NULL; struct addrinfo hints = {AI_CANONNAME, AF_T, SOCK_STREAM, 0, 0, - NULL, NULL, NULL}; - if (!(err = getaddrinfo(iphost, NULL, &hints, &info))) { + NULL, NULL, NULL}; + if (!(err = getaddrinfo(iphost, NULL, &hints, &info))) + { for (entry = info; entry && !entry->ai_canonname; entry = entry->ai_next) ; @@ -215,13 +248,16 @@ static char *getHostInfo(SOCKET sock, char **hostnameptr) { } } } - if (err) { + if (err) + { fprintf(stderr, "Error resolving ip '%s': error=%s\n", iphost, gai_strerror(err)); return NULL; } return strdup(iphost); - } else { + } + else + { fprintf(stderr, "Error resolving ip of socket %d, ", (int)sock); perror("error"); } @@ -230,12 +266,14 @@ static char *getHostInfo(SOCKET sock, char **hostnameptr) { #ifdef _WIN32 VOID CALLBACK ShutdownEvent(PVOID arg __attribute__((unused)), - BOOLEAN fired __attribute__((unused))) { + BOOLEAN fired __attribute__((unused))) +{ fprintf(stderr, "Service shut down\n"); exit(0); } -static int getSocketHandle(char *name) { +static int getSocketHandle(char *name) +{ HANDLE shutdownEvent, waitHandle; HANDLE h; int ppid; @@ -246,7 +284,8 @@ static int getSocketHandle(char *name) { char *portnam = GetPortname(); char *logfile = malloc(strlen(logdir) + strlen(portnam) + 50); FREE_ON_EXIT(logfile); - if (name == 0 || sscanf(name, "%d:%d", &ppid, (int *)&psock) != 2) { + if (name == 0 || sscanf(name, "%d:%d", &ppid, (int *)&psock) != 2) + { fprintf(stderr, "Mdsip single connection server can only be started from " "windows service\n"); free(logfile); @@ -261,7 +300,8 @@ static int getSocketHandle(char *name) { if (!DuplicateHandle(OpenProcess(PROCESS_ALL_ACCESS, TRUE, ppid), (HANDLE)psock, GetCurrentProcess(), (HANDLE *)&h, PROCESS_ALL_ACCESS, TRUE, - DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { + DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) + { fprintf(stderr, "Attempting to duplicate socket from pid %d socket %d\n", ppid, (int)psock); perror("Error duplicating socket from parent"); @@ -275,7 +315,8 @@ static int getSocketHandle(char *name) { return *(int *)&h; } #else -static void ChildSignalHandler(int num __attribute__((unused))) { +static void ChildSignalHandler(int num __attribute__((unused))) +{ sigset_t set, oldset; pid_t pid; int err; @@ -284,7 +325,8 @@ static void ChildSignalHandler(int num __attribute__((unused))) { sigaddset(&set, SIGCHLD); sigprocmask(SIG_BLOCK, &set, &oldset); /* wait for child */ - while ((pid = waitpid((pid_t)-1, &err, WNOHANG)) > 0) { + while ((pid = waitpid((pid_t)-1, &err, WNOHANG)) > 0) + { /* re-install the signal handler (some systems need this) */ signal(SIGCHLD, ChildSignalHandler); /* and unblock it */ @@ -299,7 +341,8 @@ static void ChildSignalHandler(int num __attribute__((unused))) { // AUTHORIZE ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static int io_authorize(Connection *c, char *username) { +static int io_authorize(Connection *c, char *username) +{ int ans; char *iphost = NULL, *hoststr = NULL; FREE_ON_EXIT(iphost); @@ -308,7 +351,8 @@ static int io_authorize(Connection *c, char *username) { SOCKET sock = getSocket(c); char now[32]; Now32(now); - if ((iphost = getHostInfo(sock, &hoststr))) { + if ((iphost = getHostInfo(sock, &hoststr))) + { printf("%s (%d) (pid %d) Connection received from %s@%s [%s]\r\n", now, (int)sock, getpid(), username, hoststr, iphost); char *matchString[2] = {NULL, NULL}; @@ -319,7 +363,8 @@ static int io_authorize(Connection *c, char *username) { strcpy(malloc(strlen(username) + strlen(iphost) + 3), username); strcat(matchString[0], "@"); strcat(matchString[0], iphost); - if (hoststr) { + if (hoststr) + { matchString[1] = strcpy(malloc(strlen(username) + strlen(hoststr) + 3), username); strcat(matchString[1], "@"); @@ -329,7 +374,8 @@ static int io_authorize(Connection *c, char *username) { ans = CheckClient(username, num, matchString); FREE_NOW(matchString[1]); FREE_NOW(matchString[0]); - } else + } + else PERROR("error getting hostinfo"); FREE_NOW(iphost); FREE_NOW(hoststr); @@ -343,7 +389,8 @@ static int io_authorize(Connection *c, char *username) { //////////////////////////////////////////////////////////////////////////////// static ssize_t io_send(Connection *c, const void *bptr, size_t num, - int nowait) { + int nowait) +{ SOCKET sock = getSocket(c); int options = nowait ? MSG_DONTWAIT : 0; if (sock != INVALID_SOCKET) @@ -355,24 +402,30 @@ static ssize_t io_send(Connection *c, const void *bptr, size_t num, // RECEIVE /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) { +static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) +{ SOCKET sock = getSocket(c); ssize_t recved = -1; - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { PushSocket(sock); #ifdef _TCP struct timeval to, timeout; - if (to_msec < 0) { + if (to_msec < 0) + { timeout.tv_sec = 10; timeout.tv_usec = 0; - } else { + } + else + { timeout.tv_sec = to_msec / 1000; timeout.tv_usec = (to_msec % 1000) * 1000; } fd_set rf, readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); - do { + do + { to = timeout; rf = readfds; recved = select(sock + 1, &rf, NULL, NULL, &to); @@ -381,14 +434,17 @@ static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) { fd.fd = sock; fd.events = POLLIN; int to_val = to_msec < 0 ? 10 : to_msec; - do { + do + { recved = poll(&fd, 1, to_val); #endif - if (recved > 0) { // for select this will be 1 + if (recved > 0) + { // for select this will be 1 recved = RECV(sock, bptr, num, MSG_NOSIGNAL); break; } - if (recved < 0) { + if (recved < 0) + { if (errno == EAGAIN) continue; break; // Error @@ -400,22 +456,26 @@ static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) { } #ifdef _TCP -static int io_check(Connection *c) { +static int io_check(Connection *c) +{ SOCKET sock = getSocket(c); ssize_t err = -1; - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { PushSocket(sock); struct timeval timeout = {0, 0}; fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); err = select(sock + 1, &readfds, NULL, NULL, &timeout); - switch (err) { + switch (err) + { case -1: break; // Error case 0: - break; // Timeout - default: { // for select this will be 1 + break; // Timeout + default: + { // for select this will be 1 char bptr[1]; err = RECV(sock, bptr, 1, MSG_NOSIGNAL || MSG_PEEK); err = (err == 1) ? 0 : -1; @@ -432,23 +492,28 @@ static int io_check(Connection *c) { // DISCONNECT //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static int io_disconnect(Connection *con) { +static int io_disconnect(Connection *con) +{ SOCKET sock = getSocket(con); int err = C_OK; char now[32]; Now32(now); - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { Client *c, **p; for (p = &ClientList, c = ClientList; c && c->id != con->id; p = &c->next, c = c->next) ; - if (c) { + if (c) + { *p = c->next; #ifdef _TCP - if (FD_ISSET(sock, &fdactive)) { + if (FD_ISSET(sock, &fdactive)) + { FD_CLR(sock, &fdactive); #else - if (server_epoll != -1) { + if (server_epoll != -1) + { udt_epoll_remove_usock(server_epoll, sock); #endif printf("%s (%d) (pid %d) Connection disconnected from %s@%s [%s]\r\n", @@ -470,9 +535,11 @@ static int io_disconnect(Connection *con) { } #ifdef _WIN32 -int runServerMode(Options *options) { +int runServerMode(Options *options) +{ #else -int runServerMode(Options *options __attribute__((unused))) { +int runServerMode(Options *options __attribute__((unused))) +{ #endif ////////////////////////////////////////////////////////////////////////// // SERVER MODE //////////////////////////// @@ -484,9 +551,8 @@ int runServerMode(Options *options __attribute__((unused))) { #endif int id; char *username; - if - IS_NOT_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username)) - return C_ERROR; + if (IS_NOT_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username))) + return C_ERROR; struct SOCKADDR_IN sin; SOCKLEN_T len = sizeof(sin); if (GETPEERNAME(sock, (struct sockaddr *)&sin, &len) == 0) diff --git a/mdstcpip/mdsIo.h b/mdstcpip/mdsIo.h index aa03b30a12..1763f1c2b9 100644 --- a/mdstcpip/mdsIo.h +++ b/mdstcpip/mdsIo.h @@ -2,7 +2,8 @@ #pragma once #ifndef DOXYGEN // hide this part from documentation -typedef enum { +typedef enum +{ MDS_IO_OPEN_K = 1, MDS_IO_CLOSE_K, MDS_IO_LSEEK_K, @@ -51,53 +52,64 @@ typedef enum { typedef union { int dims[MAX_DIMS]; uint32_t length; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int options; int mode; } open; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int fd; } close; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int fd; int64_t offset; int whence; } lseek; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int fd; uint32_t count; } read; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t count; int fd; } write; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int fd; int64_t offset; uint32_t size; int mode; } lock; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; } exists; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; } remove; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; } rename; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int fd; int64_t offset; uint32_t count; } read_x; - struct __attribute__((__packed__)) { + struct __attribute__((__packed__)) + { uint32_t length; int shot; int type; @@ -107,15 +119,15 @@ typedef union { } mdsio_t; #ifdef WORDS_BIGENDIAN -#define SWAP_INT_IF_BIGENDIAN(pointer) \ - { \ - int *ptr = (int *)(pointer), tmp = ptr[0]; \ - ptr[0] = ptr[1]; \ - ptr[0] = tmp; \ +#define SWAP_INT_IF_BIGENDIAN(pointer) \ + { \ + int *ptr = (int *)(pointer), tmp = ptr[0]; \ + ptr[0] = ptr[1]; \ + ptr[0] = tmp; \ } #else -#define SWAP_INT_IF_BIGENDIAN(...) \ - { /**/ \ +#define SWAP_INT_IF_BIGENDIAN(...) \ + { /**/ \ } #endif #endif // DOXYGEN end of hidden code diff --git a/mdstcpip/mdsip.c b/mdstcpip/mdsip.c index b513484224..2e32c8ca61 100644 --- a/mdstcpip/mdsip.c +++ b/mdstcpip/mdsip.c @@ -28,7 +28,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" #include -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int errout; INIT_AND_FREE_ON_EXIT(char **, extra_argv); IoRoutines *io; @@ -37,7 +38,8 @@ int main(int argc, char **argv) { io = LoadIo(GetProtocol()); if (io && io->listen) errout = io->listen(extra_argc, extra_argv); - else { + else + { fprintf(stderr, "Protocol %s does not support servers\n", GetProtocol()); errout = 1; } diff --git a/mdstcpip/mdsip.h b/mdstcpip/mdsip.h index 8717cfd901..acebb6feed 100644 --- a/mdstcpip/mdsip.h +++ b/mdstcpip/mdsip.h @@ -134,19 +134,22 @@ int errno = 0; #define bits16 #endif -typedef struct _eventinfo { +typedef struct _eventinfo +{ char data[12]; int eventid; void (*astadr)(void *, int, char *); void *astprm; } MdsEventInfo; -typedef struct _jeventinfo { +typedef struct _jeventinfo +{ char data[12]; char eventid; } JMdsEventInfo; -typedef struct _eventlist { +typedef struct _eventlist +{ SOCKET sock; int eventid; char jeventid; @@ -155,7 +158,8 @@ typedef struct _eventlist { struct _eventlist *next; } MdsEventList; -typedef struct _msghdr { +typedef struct _msghdr +{ int msglen bits32; int status bits32; short length bits16; @@ -172,7 +176,8 @@ typedef struct _msghdr { #endif } MsgHdr; -typedef struct _mds_message { +typedef struct _mds_message +{ MsgHdr h; char bytes[1]; } Message, *MsgPtr; diff --git a/mdstcpip/mdsip_connections.h b/mdstcpip/mdsip_connections.h index b960947a65..d75844c1ec 100644 --- a/mdstcpip/mdsip_connections.h +++ b/mdstcpip/mdsip_connections.h @@ -18,7 +18,8 @@ #define NULL (void *)0 #endif -enum _mdsip_client_types { +enum _mdsip_client_types +{ VMS_CLIENT = 1, IEEE_CLIENT = 2, JAVA_CLIENT = 3, @@ -27,19 +28,22 @@ enum _mdsip_client_types { CRAY_CLIENT = 8 }; -typedef struct { +typedef struct +{ char data[12]; int eventid; void (*astadr)(void *, int, char *); void *astprm; } MdsEventInfo; -typedef struct { +typedef struct +{ char data[12]; char eventid; } JMdsEventInfo; -typedef struct _eventlist { +typedef struct _eventlist +{ int conid; int eventid; char jeventid; @@ -48,7 +52,8 @@ typedef struct _eventlist { struct _eventlist *next; } MdsEventList; -typedef struct { +typedef struct +{ char *short_name; char *long_name; int expects_value; @@ -58,7 +63,8 @@ typedef struct { typedef uint8_t con_t; -typedef struct _connection { +typedef struct _connection +{ int id; // unique connection id struct _connection *next; pthread_cond_t cond; @@ -107,7 +113,8 @@ int errno = 0; /// /// \brief Header of Message structure. /// -typedef struct { +typedef struct +{ int msglen bits32; int status bits32; short length bits16; @@ -127,7 +134,8 @@ typedef struct { /// /// \brief Message structure for passing data through connections /// -typedef struct { +typedef struct +{ MsgHdr h; char bytes[1]; } Message, *MsgPtr; @@ -147,7 +155,8 @@ typedef struct { /// | disconnect | clear connection instance | /// | recv_to | receive buffer from cocnection with time out | /// -typedef struct _io_routines { +typedef struct _io_routines +{ int (*connect)(Connection *c, char *protocol, char *connectString); ssize_t (*send)(Connection *c, const void *buffer, size_t buflen, int nowait); ssize_t (*recv)(Connection *c, void *buffer, size_t buflen); @@ -183,16 +192,17 @@ typedef struct _io_routines { #endif #define SupportsCompression(c) (c & SUPPORTS_COMPRESSION) -#define FlipBytes(num, ptr) \ - { \ - int __i; \ - int __n = num; \ - char *__p = ptr; \ - for (__i = 0; __i < __n / 2; __i++) { \ - char __tmp = __p[__i]; \ - __p[__i] = __p[__n - __i - 1]; \ - __p[__n - __i - 1] = __tmp; \ - } \ +#define FlipBytes(num, ptr) \ + { \ + int __i; \ + int __n = num; \ + char *__p = ptr; \ + for (__i = 0; __i < __n / 2; __i++) \ + { \ + char __tmp = __p[__i]; \ + __p[__i] = __p[__n - __i - 1]; \ + __p[__n - __i - 1] = __tmp; \ + } \ } #if HAVE_PTHREAD_H #include diff --git a/mdstcpip/mdsip_service.c b/mdstcpip/mdsip_service.c index ece8da55c9..5d792f93d4 100644 --- a/mdstcpip/mdsip_service.c +++ b/mdstcpip/mdsip_service.c @@ -42,7 +42,8 @@ static char **extra_argv; // static char *dirname = "bin_x86"; // #endif -static char *ServiceName(int generic) { +static char *ServiceName(int generic) +{ char *name = strcpy((char *)malloc(512), "MDSplus "); if (!generic) strcat(name, GetMulti() ? "Action Server - Port " : "Data Server - Port "); @@ -50,7 +51,8 @@ static char *ServiceName(int generic) { return name; } -static int SpawnWorker(SOCKET sock) { +static int SpawnWorker(SOCKET sock) +{ int status; STARTUPINFO startupinfo; PROCESS_INFORMATION pinfo; @@ -83,7 +85,8 @@ static SERVICE_STATUS_HANDLE hService; static void ServiceMain(DWORD, CHAR **); static SERVICE_STATUS serviceStatus; -static void SetThisServiceStatus(int state, int hint) { +static void SetThisServiceStatus(int state, int hint) +{ serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwCurrentState = state; serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; @@ -94,9 +97,12 @@ static void SetThisServiceStatus(int state, int hint) { SetServiceStatus(hService, &serviceStatus); } -VOID WINAPI serviceHandler(DWORD fdwControl) { - switch (fdwControl) { - case SERVICE_CONTROL_STOP: { +VOID WINAPI serviceHandler(DWORD fdwControl) +{ + switch (fdwControl) + { + case SERVICE_CONTROL_STOP: + { SetThisServiceStatus(SERVICE_STOP_PENDING, 1000); SetThisServiceStatus(SERVICE_STOPPED, 0); shut = 1; @@ -106,7 +112,8 @@ VOID WINAPI serviceHandler(DWORD fdwControl) { } } -static void InitializeService() { +static void InitializeService() +{ char name[120]; hService = RegisterServiceCtrlHandler(TEXT(ServiceName(1)), (LPHANDLER_FUNCTION)serviceHandler); @@ -115,12 +122,15 @@ static void InitializeService() { SetThisServiceStatus(SERVICE_START_PENDING, 1000); } -static BOOL RemoveService() { +static BOOL RemoveService() +{ BOOL status = 1; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); - if (hSCManager) { + if (hSCManager) + { SC_HANDLE hService = OpenService(hSCManager, TEXT(ServiceName(1)), DELETE); - if (hService) { + if (hService) + { status = DeleteService(hService); status = CloseServiceHandle(hService); } @@ -129,12 +139,14 @@ static BOOL RemoveService() { return status; } -static int InstallService() { +static int InstallService() +{ int status = 1; SC_HANDLE hSCManager; RemoveService(); hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); - if (hSCManager) { + if (hSCManager) + { SC_HANDLE hService; char *cmd; static const char *multi_opt = "--multi"; @@ -144,15 +156,19 @@ static int InstallService() { GetMulti() ? (GetContextSwitching() ? "--multi" : "--server") : ""; SERVICE_DESCRIPTION sd; LPTSTR description = (LPTSTR)malloc(4096); - if (GetMulti()) { - if (GetContextSwitching()) { + if (GetMulti()) + { + if (GetContextSwitching()) + { opts = multi_opt; wsprintf( description, TEXT("MDSplus data service listening on port %s.\nPermits multiple " "connections each with own tdi and tree context\n"), GetPortname()); - } else { + } + else + { opts = server_opt; wsprintf( description, @@ -160,7 +176,9 @@ static int InstallService() { "connections with shared tdi and tree context\n"), GetPortname()); } - } else { + } + else + { opts = data_opt; wsprintf(description, TEXT("MDSplus data service listening on port %s.\nEach " @@ -180,9 +198,11 @@ static int InstallService() { NULL, NULL, NULL, NULL, NULL); if (hService == NULL) status = GetLastError(); - else { + else + { ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sd); - if (GetMulti()) { + if (GetMulti()) + { SERVICE_FAILURE_ACTIONS sfa; SC_ACTION actions[] = {{SC_ACTION_RESTART, 5000}}; sfa.dwResetPeriod = INFINITE; @@ -204,14 +224,17 @@ static int InstallService() { return status; } -static short GetPort() { +static short GetPort() +{ short port; char *name = GetPortname(); struct servent *sp; port = htons((short)strtol(name, NULL, 0)); - if (port == 0) { + if (port == 0) + { sp = getservbyname(name, "tcp"); - if (sp == NULL) { + if (sp == NULL) + { fprintf(stderr, "unknown service: %s/tcp\n\n", name); exit(0); } @@ -220,7 +243,8 @@ static short GetPort() { return port; } -static void RedirectOutput() { +static void RedirectOutput() +{ char *logdir = GetLogDir(); char *portname = GetPortname(); char *file = malloc(strlen(logdir) + strlen(portname) + 20); @@ -231,7 +255,8 @@ static void RedirectOutput() { free(file); } -static void ServiceMain(DWORD argc, CHAR **argv) { +static void ServiceMain(DWORD argc, CHAR **argv) +{ SOCKET s; int status; static struct sockaddr_in sin; @@ -243,19 +268,24 @@ static void ServiceMain(DWORD argc, CHAR **argv) { RedirectOutput(); InitializeService(); SetThisServiceStatus(SERVICE_RUNNING, 0); - if (GetMulti()) { + if (GetMulti()) + { IoRoutines *io; io = LoadIo(GetProtocol()); if (io && io->listen) io->listen(argc, argv); - else { + else + { fprintf(stderr, "Protocol %s does not support servers\n", GetProtocol()); exit(1); } exit(0); - } else { + } + else + { s = socket(AF_INET, SOCK_STREAM, 0); - if (s == INVALID_SOCKET) { + if (s == INVALID_SOCKET) + { printf("Error getting Connection Socket\n"); exit(1); } @@ -264,31 +294,39 @@ static void ServiceMain(DWORD argc, CHAR **argv) { sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; status = bind(s, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)); - if (status < 0) { + if (status < 0) + { perror("Error binding to service\n"); exit(1); } status = listen(s, 128); - if (status < 0) { + if (status < 0) + { perror("Error listen on port\n"); exit(1); } FD_ZERO(&fdactive); FD_SET(s, &fdactive); - for (readfds = fdactive; !shut; readfds = fdactive) { - if (select(s + 1, &readfds, 0, 0, &timeout) != SOCKET_ERROR) { + for (readfds = fdactive; !shut; readfds = fdactive) + { + if (select(s + 1, &readfds, 0, 0, &timeout) != SOCKET_ERROR) + { error_count = 0; - if (FD_ISSET(s, &readfds)) { + if (FD_ISSET(s, &readfds)) + { int len = sizeof(struct sockaddr_in); SOCKET sock = accept(s, (struct sockaddr *)&sin, &len); SpawnWorker(sock); } - } else { + } + else + { error_count++; perror("error in main select"); fprintf(stderr, "Error count=%d\n", error_count); fflush(stderr); - if (error_count > 100) { + if (error_count > 100) + { fprintf(stderr, "Error count exceeded, shutting down\n"); shut = 1; } @@ -300,7 +338,8 @@ static void ServiceMain(DWORD argc, CHAR **argv) { } DEFINE_INITIALIZESOCKETS; -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int x_argc; char **x_argv; Options options[] = {{"i", "install", 0, 0, 0}, @@ -313,13 +352,18 @@ int main(int argc, char **argv) { SetPortname(options[2].value); else if (GetPortname() == 0) SetPortname("mdsip"); - if (options[0].present) { + if (options[0].present) + { InstallService(); exit(0); - } else if (options[1].present) { + } + else if (options[1].present) + { RemoveService(); exit(0); - } else { + } + else + { SERVICE_TABLE_ENTRY srvcTable[] = { {ServiceName(1), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {NULL, NULL}}; INITIALIZESOCKETS; diff --git a/mdstcpip/testing/mdscp.c b/mdstcpip/testing/mdscp.c index 6f3b54d2c3..a4f2a2233b 100644 --- a/mdstcpip/testing/mdscp.c +++ b/mdstcpip/testing/mdscp.c @@ -55,12 +55,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "mdsip_connections.h" -struct mdsfile { +struct mdsfile +{ SOCKET socket; int fd; }; -static float getSeconds(struct timeval *time) { +static float getSeconds(struct timeval *time) +{ struct timeval now; float ans; gettimeofday(&now, 0); @@ -70,7 +72,8 @@ static float getSeconds(struct timeval *time) { return ans; } -static void printHelp() { +static void printHelp() +{ printf("Usage: mdscp [--help] [-?] [--streams=n] [--statistics] srcfile " "dstfile\n\n" " --streams=n can be used to specify the number of parallel " @@ -83,23 +86,27 @@ static void printHelp() { } static int doOpen(int streams, char *name, int options, int mode, - struct mdsfile *mfile) { + struct mdsfile *mfile) +{ char *tmp = strcpy((char *)malloc(strlen(name) + 1), name); char *hostpart = tmp; char *filepart = strstr(tmp, "::"); int status; - if (filepart) { + if (filepart) + { int info[3]; hostpart = tmp; filepart[0] = '\0'; filepart += 2; mfile->socket = ConnectToMds(hostpart); - if (mfile->socket == -1) { + if (mfile->socket == -1) + { fprintf(stderr, "Error connecting to host: %s\n", hostpart); return -1; } info[0] = strlen(filepart) + 1; - if (O_CREAT == 0x0200) { /* BSD */ + if (O_CREAT == 0x0200) + { /* BSD */ if (options & O_CREAT) options = (options & ~O_CREAT) | 0100; if (options & O_TRUNC) @@ -116,7 +123,8 @@ static int doOpen(int streams, char *name, int options, int mode, info[2] = (int)mode; status = SendArg(mfile->socket, MDS_IO_OPEN_K, 0, 0, 0, sizeof(info) / sizeof(int), info, filepart); - if (status & 1) { + if (status & 1) + { char dtype; short length; char ndims; @@ -128,43 +136,56 @@ static int doOpen(int streams, char *name, int options, int mode, if (((sts = GetAnswerInfoTS(mfile->socket, &dtype, &length, &ndims, dims, &numbytes, &dptr, &msg)) & 1) && - (length == sizeof(mfile->fd))) { + (length == sizeof(mfile->fd))) + { memcpy(&mfile->fd, dptr, sizeof(mfile->fd)); status = 0; - } else { + } + else + { printf("Err in GetAnswerInfoTS in io_open_remote: status = %d, length " "= %d\n", sts, length); status = -1; } free(msg); - } else { + } + else + { fprintf(stderr, "Error opening file: %s\n", name); status = -1; } - } else { + } + else + { mfile->socket = -1; mfile->fd = open(name, options, mode); - if (mfile->fd == -1) { + if (mfile->fd == -1) + { char *fmt = "Error opening file: %s"; char *msg = (char *)malloc(strlen(name) + strlen(fmt) + 10); sprintf(msg, fmt, name); perror(msg); free(msg); status = -1; - } else + } + else status = 0; } free(tmp); return status; } -off_t getSize(struct mdsfile *file) { - if (file->socket == -1) { +off_t getSize(struct mdsfile *file) +{ + if (file->socket == -1) + { off_t ans = lseek(file->fd, 0, SEEK_END); lseek(file->fd, 0, SEEK_SET); return ans; - } else { + } + else + { off_t ret = -1; int info[] = {0, 0, 0, 0, 0}; SOCKET sock = file->socket; @@ -174,7 +195,8 @@ off_t getSize(struct mdsfile *file) { *(off_t *)(&info[2]) = 0; status = SendArg(sock, MDS_IO_LSEEK_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) { + if (status & 1) + { char dtype; unsigned short length; char ndims; @@ -185,7 +207,8 @@ off_t getSize(struct mdsfile *file) { if ((GetAnswerInfoTS(sock, &dtype, &length, &ndims, dims, &numbytes, &dptr, &msg) & 1) && - (length >= sizeof(int))) { + (length >= sizeof(int))) + { ret = 0; memcpy(&ret, dptr, (length > sizeof(ret)) ? sizeof(ret) : length); } @@ -194,7 +217,8 @@ off_t getSize(struct mdsfile *file) { } status = SendArg(sock, MDS_IO_LSEEK_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) { + if (status & 1) + { char dtype; unsigned short length; char ndims; @@ -206,7 +230,8 @@ off_t getSize(struct mdsfile *file) { if ((GetAnswerInfoTS(sock, &dtype, &length, &ndims, dims, &numbytes, &dptr, &msg) & 1) && - (length >= sizeof(int))) { + (length >= sizeof(int))) + { dumret = 0; memcpy(&dumret, dptr, (length > sizeof(dumret)) ? sizeof(dumret) : length); @@ -217,10 +242,14 @@ off_t getSize(struct mdsfile *file) { } } -off_t doRead(struct mdsfile *file, off_t count, void *buff) { - if (file->socket == -1) { +off_t doRead(struct mdsfile *file, off_t count, void *buff) +{ + if (file->socket == -1) + { return read(file->fd, buff, count); - } else { + } + else + { off_t ret = -1; int info[] = {0, 0, 0}; SOCKET sock = file->socket; @@ -229,7 +258,8 @@ off_t doRead(struct mdsfile *file, off_t count, void *buff) { info[2] = count; status = SendArg(sock, MDS_IO_READ_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) { + if (status & 1) + { char dtype; unsigned short length; char ndims; @@ -239,7 +269,8 @@ off_t doRead(struct mdsfile *file, off_t count, void *buff) { void *msg = 0; if ((GetAnswerInfoTS(sock, &dtype, &length, &ndims, dims, &numbytes, &dptr, &msg) & - 1)) { + 1)) + { ret = numbytes; if (ret) memcpy(buff, dptr, ret); @@ -250,10 +281,14 @@ off_t doRead(struct mdsfile *file, off_t count, void *buff) { } } -static off_t doWrite(struct mdsfile *file, off_t count, void *buff) { - if (file->socket == -1) { +static off_t doWrite(struct mdsfile *file, off_t count, void *buff) +{ + if (file->socket == -1) + { return write(file->fd, buff, count); - } else { + } + else + { off_t ret = -1; int info[] = {0, 0}; SOCKET sock = file->socket; @@ -262,7 +297,8 @@ static off_t doWrite(struct mdsfile *file, off_t count, void *buff) { info[0] = count; status = SendArg(sock, MDS_IO_WRITE_K, 0, 0, 0, sizeof(info) / sizeof(int), info, buff); - if (status & 1) { + if (status & 1) + { char dtype; unsigned short length; char ndims; @@ -272,7 +308,8 @@ static off_t doWrite(struct mdsfile *file, off_t count, void *buff) { void *msg = 0; if ((GetAnswerInfoTS(sock, &dtype, &length, &ndims, dims, &numbytes, &dptr, &msg) & - 1)) { + 1)) + { ret = (off_t) * (int *)dptr; } free(msg); @@ -281,10 +318,14 @@ static off_t doWrite(struct mdsfile *file, off_t count, void *buff) { } } -static int doClose(struct mdsfile *file) { - if (file->socket == -1) { +static int doClose(struct mdsfile *file) +{ + if (file->socket == -1) + { return close(file->fd); - } else { + } + else + { int ret = -1; int info[] = {0, 0}; SOCKET sock = file->socket; @@ -292,7 +333,8 @@ static int doClose(struct mdsfile *file) { info[1] = file->fd; status = SendArg(sock, MDS_IO_CLOSE_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) { + if (status & 1) + { char dtype; short length; char ndims; @@ -311,14 +353,16 @@ static int doClose(struct mdsfile *file) { } } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int c; int streams = 1; int stats = 0; int error = 0; int help = 0; struct timeval time, timeStart; - while (1) { + while (1) + { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = {{"streams", 1, 0, 0}, @@ -328,12 +372,15 @@ int main(int argc, char **argv) { c = getopt_long(argc, argv, "", long_options, &option_index); if (c == -1) break; - switch (c) { + switch (c) + { case 0: - switch (option_index) { + switch (option_index) + { case 0: streams = strtol(optarg, NULL, 0); - if (streams < 1 || streams > 32) { + if (streams < 1 || streams > 32) + { printf("Invalid number of streams specified."); error = 1; } @@ -350,11 +397,15 @@ int main(int argc, char **argv) { error = 1; } } - if (error == 0) { - if (argc - optind != 2) { + if (error == 0) + { + if (argc - optind != 2) + { printf("Invalid number of arguments provided."); error = 1; - } else { + } + else + { char *srcfile = argv[optind]; char *destfile = argv[optind + 1]; off_t inSize; @@ -362,27 +413,32 @@ int main(int argc, char **argv) { off_t offset = 0; struct mdsfile inFile, outFile; int status; - if (stats) { + if (stats) + { gettimeofday(&time, 0); timeStart = time; } status = doOpen(streams, srcfile, O_RDONLY, 0, &inFile); - if (status == -1) { + if (status == -1) + { printf("Error opening source file: %s\n", srcfile); return 1; } if (stats) printf("Time to open source file: %g\n", getSeconds(&time)); status = doOpen(streams, destfile, O_WRONLY | O_CREAT, 0777, &outFile); - if (status == -1) { + if (status == -1) + { printf("Error opening destination file: %s\n", destfile); return 1; } if (stats) printf("Time to open destination file: %g\n", getSeconds(&time)); inSize = getSize(&inFile); - if (inSize > 2000) { - if (streams > 1) { + if (inSize > 2000) + { + if (streams > 1) + { if (inFile.socket != -1) MdsSetStreams(inFile.socket, streams); if (outFile.socket != -1) @@ -393,18 +449,21 @@ int main(int argc, char **argv) { } } buff = malloc(inSize > MAX_IO_SIZE ? MAX_IO_SIZE : inSize); - while (offset < inSize) { + while (offset < inSize) + { off_t bytes_this_time = inSize - offset; off_t bytes; if (bytes_this_time > MAX_IO_SIZE) bytes_this_time = MAX_IO_SIZE; bytes = doRead(&inFile, bytes_this_time, buff); - if (bytes != bytes_this_time) { + if (bytes != bytes_this_time) + { fprintf(stderr, "Error reading from source file"); return 1; } bytes = doWrite(&outFile, bytes_this_time, buff); - if (bytes != bytes_this_time) { + if (bytes != bytes_this_time) + { fprintf(stderr, "Error writing to destination file"); return 1; } @@ -412,7 +471,8 @@ int main(int argc, char **argv) { } doClose(&inFile); doClose(&outFile); - if (stats) { + if (stats) + { float secs; printf("Time to copy files: %g\n", secs = getSeconds(&time)); printf("Total time to copy files: %g\n", getSeconds(&timeStart)); @@ -420,11 +480,14 @@ int main(int argc, char **argv) { } } } - if (error) { + if (error) + { printf("\n\n"); printHelp(); return 1; - } else if (help) { + } + else if (help) + { printHelp(); } return 0; diff --git a/mdstcpip/testing/mdsiptest.c b/mdstcpip/testing/mdsiptest.c index d4b031eba3..5d92fdc218 100644 --- a/mdstcpip/testing/mdsiptest.c +++ b/mdstcpip/testing/mdsiptest.c @@ -30,22 +30,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int status; struct descrip ans; float val = 9876; struct descrip vald = {DTYPE_FLOAT, 0, {0}, 0, 0}; long sock = ConnectToMds((argc > 1) ? argv[1] : "lost.pfc.mit.edu:9000"); - if (sock != -1) { + if (sock != -1) + { printf("status from MdsOpen = %d\n", MdsOpen(sock, "main", -1)); ans.ptr = 0; - if (MdsValue(sock, "f_float(member)", &ans, NULL) & 1) { + if (MdsValue(sock, "f_float(member)", &ans, NULL) & 1) + { printf("%g\n", *(float *)ans.ptr); val = *(float *)ans.ptr; val = val + (float)1.; - } else + } + else printf("%s\n", (char *)ans.ptr); - if (ans.ptr) { + if (ans.ptr) + { free(ans.ptr); ans.ptr = 0; } diff --git a/mdsvme/dmaexreg.h b/mdsvme/dmaexreg.h index 646b69dfd0..1b7ffee098 100644 --- a/mdsvme/dmaexreg.h +++ b/mdsvme/dmaexreg.h @@ -70,7 +70,8 @@ * user code and by the driver itself. * ***************************************************/ -struct dmaex_ioctl_data { +struct dmaex_ioctl_data +{ unsigned long data[6]; }; @@ -115,7 +116,8 @@ struct dmaex_ioctl_data { #define MMAP_K_TO_U_MEM_WRT 1 #define MMAP_K_TO_U_MEM_RD 2 -enum dmaex_commands { +enum dmaex_commands +{ C1, C2, C3, diff --git a/mdsvme/mdsvme.c b/mdsvme/mdsvme.c index 2610f0dd44..d95c16f270 100644 --- a/mdsvme/mdsvme.c +++ b/mdsvme/mdsvme.c @@ -54,11 +54,13 @@ static void SigCatcher(int signo) {} static int fd1 = 0, fd2 = 0; -int VmeWaitForInterrupt(char *device, int irq, int vector) { +int VmeWaitForInterrupt(char *device, int irq, int vector) +{ struct dmaex_ioctl_data data; int fd = open("/dev/dmaex0", O_RDWR); int status = 0; - if (fd != -1) { + if (fd != -1) + { struct sigaction newsigaction, oldsigaction; sigset_t empty_set, new_set; newsigaction.sa_handler = SigCatcher; @@ -74,7 +76,8 @@ int VmeWaitForInterrupt(char *device, int irq, int vector) { data.data[1] = vector; if (ioctl(fd, SET_INT_HANDLER, data.data) != 0) perror("error in ioctl SET_INT_HANDLER"); - else { + else + { sigsuspend(&empty_set); if (ioctl(fd, CLR_INT_HANDLER, data.data) != 0) perror("error in ioctl CLR_INT_HANDLER"); @@ -82,96 +85,117 @@ int VmeWaitForInterrupt(char *device, int irq, int vector) { status = 0; } close(fd); - } else + } + else perror("Error opening VME device"); return status; } int VmePioRead(char *device, unsigned long addr, unsigned long mode, - int bufsize, void *buffer, int *bytes_read) { + int bufsize, void *buffer, int *bytes_read) +{ struct dmaex_ioctl_data data; int fd = open(device, O_RDWR); int status = 0; *bytes_read = 0; - if (fd != -1) { + if (fd != -1) + { data.data[0] = bufsize; data.data[1] = addr; data.data[2] = mode; if (ioctl(fd, SETUP_VME_FOR_STRATEGY_PIO, data.data) != 0) perror("error in ioctl SETUP_VME_FOR_STRATEGY_PIO"); - else { + else + { data.data[0] = PIO_XFER_MODE; if (ioctl(fd, SET_STRATEGY_XFER_MODE, data.data) != 0) perror("error in ioctl SET_STRATEGY_XFER_MODE"); - else { + else + { memset(buffer, 0, bufsize); *bytes_read = read(fd, buffer, bufsize); - if (*bytes_read < 0) { + if (*bytes_read < 0) + { perror("PIO_XFER_MODE read error"); status = 0; - } else + } + else status = 1; ioctl(fd, UNMAP_VME_FOR_STRATEGY_PIO, data.data); } } close(fd); - } else + } + else perror("Error opening VME device"); return status; } int VmePioWrite(char *device, unsigned long addr, unsigned long mode, - int bufsize, void *buffer, int *bytes_written) { + int bufsize, void *buffer, int *bytes_written) +{ struct dmaex_ioctl_data data; int fd = open(device, O_RDWR); int status = 0; *bytes_written = 0; - if (fd != -1) { + if (fd != -1) + { data.data[0] = bufsize; data.data[1] = addr; data.data[2] = mode; if (ioctl(fd, SETUP_VME_FOR_STRATEGY_PIO, data.data) != 0) perror("error in ioctl SETUP_VME_FOR_STRATEGY_PIO"); - else { + else + { data.data[0] = PIO_XFER_MODE; if (ioctl(fd, SET_STRATEGY_XFER_MODE, data.data) != 0) perror("error in ioctl SET_STRATEGY_XFER_MODE"); - else { + else + { *bytes_written = write(fd, buffer, bufsize); - if (*bytes_written < 0) { + if (*bytes_written < 0) + { perror("PIO_XFER_MODE write error"); status = 0; - } else + } + else status = 1; ioctl(fd, UNMAP_VME_FOR_STRATEGY_PIO, data.data); } } close(fd); - } else + } + else perror("Error opening VME device"); return status; } int PioRead(char *device, unsigned int addr, unsigned int mode, int bufsize, - void *buffer) { + void *buffer) +{ struct pio_info setVme, getVme; int fd = open(device, O_RDWR); int status = 0; void *pMapAdr; - if (fd != -1) { + if (fd != -1) + { setVme.pio_addr = addr; setVme.pio_size = bufsize; setVme.pio_am = mode; setVme.pio_access = HANDLE_LONGWORD; if (ioctl(fd, VMP_MAP_PIO_ADDR, &setVme) < 0) perror("error in ioctl VMP_MAP_PIO_ADDR"); - else { + else + { memset(buffer, 0, bufsize); pMapAdr = (int *)mmap((caddr_t)0, setVme.pio_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (pMapAdr == (int *)-1) { + if (pMapAdr == (int *)-1) + { printf("### error in mmap\n"); - } else { + } + else + { memcpy(buffer, pMapAdr, bufsize); if (ioctl(fd, VMP_UNMAP_PIO_ADDR, &setVme) < 0) printf("### error in ioctl-UNMAP\n"); @@ -181,30 +205,37 @@ int PioRead(char *device, unsigned int addr, unsigned int mode, int bufsize, } } close(fd); - } else + } + else perror("Error opening VME device"); return status; } int PioWrite(char *device, unsigned int addr, unsigned int mode, int bufsize, - void *buffer) { + void *buffer) +{ struct pio_info setVme, getVme; int fd = open(device, O_RDWR); int status = 0; void *pMapAdr; - if (fd != -1) { + if (fd != -1) + { setVme.pio_addr = addr; setVme.pio_size = bufsize; setVme.pio_am = mode; setVme.pio_access = HANDLE_LONGWORD; if (ioctl(fd, VMP_MAP_PIO_ADDR, &setVme) < 0) perror("error in ioctl VMP_MAP_PIO_ADDR"); - else { + else + { pMapAdr = (int *)mmap((caddr_t)0, setVme.pio_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (pMapAdr == (int *)-1) { + if (pMapAdr == (int *)-1) + { printf("### error in mmap\n"); - } else { + } + else + { memcpy(pMapAdr, buffer, bufsize); if (ioctl(fd, VMP_UNMAP_PIO_ADDR, &setVme) < 0) printf("### error in ioctl-UNMAP\n"); @@ -214,17 +245,21 @@ int PioWrite(char *device, unsigned int addr, unsigned int mode, int bufsize, } } close(fd); - } else + } + else perror("Error opening VME device"); return status; } -void termfunc(int dummy) { - if (fd1 != 0) { +void termfunc(int dummy) +{ + if (fd1 != 0) + { ioctl(fd1, VMP_DEL_INTR); close(fd1); } - if (fd2 != 0) { + if (fd2 != 0) + { ioctl(fd2, VMP_DEL_INTR); close(fd2); } @@ -232,12 +267,14 @@ void termfunc(int dummy) { } int WaitForInterrupt(char *device1, int priority1, int vector1, char *device2, - int priority2, int vector2) { + int priority2, int vector2) +{ struct vmpintr_info setIntr; fd_set mask; int status = 0; fd1 = open(device1, O_RDWR); - if (fd1 != -1) { + if (fd1 != -1) + { signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); signal(SIGHUP, SIG_IGN); @@ -253,7 +290,8 @@ int WaitForInterrupt(char *device1, int priority1, int vector1, char *device2, ioctl(fd1, VMP_ADD_INTR, &setIntr); FD_ZERO(&mask); FD_SET(fd1, &mask); - if (strlen(device2) > 0) { + if (strlen(device2) > 0) + { fd2 = open(device2, O_RDWR); setIntr.priority = priority2; setIntr.vector = vector2; @@ -268,12 +306,14 @@ int WaitForInterrupt(char *device1, int priority1, int vector1, char *device2, ioctl(fd1, VMP_DEL_INTR); close(fd1); fd1 = 0; - if (fd2 != 0) { + if (fd2 != 0) + { ioctl(fd2, VMP_DEL_INTR); close(fd2); fd2 = 0; } - } else + } + else perror("Error opening VME device"); return status; } diff --git a/mdsvme/vmp_reg.h b/mdsvme/vmp_reg.h index 34c2c4c1e8..b2719c864e 100644 --- a/mdsvme/vmp_reg.h +++ b/mdsvme/vmp_reg.h @@ -6,7 +6,8 @@ * VMP_MAP_PIO_ADDR and VMP_GET_PIO_INFO. */ -struct pio_info { +struct pio_info +{ unsigned int pio_addr; /* VME address to map outbound to */ unsigned int pio_size; /* Size to map outbound to */ unsigned int pio_am; /* Address modifier for pio_addr */ @@ -14,7 +15,8 @@ struct pio_info { unsigned int intcount; }; -struct vmpioctl { +struct vmpioctl +{ unsigned int vmp_addr; /* VMEbus address */ unsigned int vmp_size; /* Size VMEbus Window */ unsigned int vmp_am; /* Address modifier */ @@ -23,7 +25,8 @@ struct vmpioctl { unsigned int vmp_return; /* Return value */ }; -struct vmpintr_info { +struct vmpintr_info +{ int priority; /* Interrupt priority */ int vector; /* Interrupt vector */ }; diff --git a/mitdevices/a12_gen.c b/mitdevices/a12_gen.c index 1067e390e2..009c306272 100644 --- a/mitdevices/a12_gen.c +++ b/mitdevices/a12_gen.c @@ -38,17 +38,17 @@ EXPORT int a12__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(A12_K_CONG_NODES); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); status = TreeAddNode(name_ptr, &head_nid, usage); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); status = TreeGetDefaultNid(&old_nid); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); status = TreeSetDefaultNid(head_nid); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:EXT_CLOCK_IN, TreeUSAGE_AXIS) @@ -128,7 +128,7 @@ EXPORT int a12__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if STATUS_NOT_OK goto end; + GOTO_IF_STATUS_NOT_OK(end); status = TreeSetDefaultNid(old_nid); end: free(name_ptr); diff --git a/php/mdsplus.c b/php/mdsplus.c index 9d5b67ef92..c4ff1c92c5 100644 --- a/php/mdsplus.c +++ b/php/mdsplus.c @@ -86,7 +86,7 @@ zend_module_entry mdsplus_module_entry = { mdsplus_functions, PHP_MINIT(mdsplus), PHP_MSHUTDOWN(mdsplus), - PHP_RINIT(mdsplus), /* Replace with NULL if there's nothing to do at request + PHP_RINIT(mdsplus), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(mdsplus), /* Replace with NULL if there's nothing to do at request end */ @@ -122,7 +122,8 @@ static void php_mdsplus_init_globals(zend_mdsplus_globals *mdsplus_globals) } */ /* }}} */ -static void mdsplus_replace_error(char *msg, int do_not_copy) { +static void mdsplus_replace_error(char *msg, int do_not_copy) +{ free(mdsplus_error_msg); if (do_not_copy) mdsplus_error_msg = msg; @@ -130,7 +131,8 @@ static void mdsplus_replace_error(char *msg, int do_not_copy) { mdsplus_error_msg = strcpy(malloc(strlen(msg) + 1), msg); } -static char *mdsplus_translate_status(int socket, int status) { +static char *mdsplus_translate_status(int socket, int status) +{ char expression[100]; struct descrip ans; int tmpstat; @@ -138,7 +140,8 @@ static char *mdsplus_translate_status(int socket, int status) { tmpstat = MdsValue(socket, expression, &ans, NULL); if (tmpstat & 1 && ans.ptr) return (char *)ans.ptr; - else { + else + { char *msg = malloc(100); sprintf(msg, "Unable to determine error string, error status=%d", status); return msg; @@ -147,7 +150,8 @@ static char *mdsplus_translate_status(int socket, int status) { /* {{{ PHP_MINIT_FUNCTION */ -PHP_MINIT_FUNCTION(mdsplus) { +PHP_MINIT_FUNCTION(mdsplus) +{ /* If you have INI entries, uncomment these lines ZEND_INIT_MODULE_GLOBALS(mdsplus, php_mdsplus_init_globals, NULL); REGISTER_INI_ENTRIES(); @@ -159,7 +163,8 @@ PHP_MINIT_FUNCTION(mdsplus) { /* {{{ PHP_MSHUTDOWN_FUNCTION */ -PHP_MSHUTDOWN_FUNCTION(mdsplus) { +PHP_MSHUTDOWN_FUNCTION(mdsplus) +{ /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ @@ -184,7 +189,8 @@ PHP_RSHUTDOWN_FUNCTION(mdsplus) { return SUCCESS; } /* {{{ PHP_MINFO_FUNCTION */ -PHP_MINFO_FUNCTION(mdsplus) { +PHP_MINFO_FUNCTION(mdsplus) +{ php_info_print_table_start(); php_info_print_table_header(2, "mdsplus support", "enabled"); php_info_print_table_end(); @@ -208,7 +214,8 @@ static int persistent = 0; static char *lastHost = 0; static int persistentConnection = -1; -PHP_FUNCTION(mdsplus_connect) { +PHP_FUNCTION(mdsplus_connect) +{ char *arg = NULL; int arg_len, len; int handle; @@ -219,7 +226,8 @@ PHP_FUNCTION(mdsplus_connect) { mdsplus_replace_error(0, 1); persistent = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &arg, &zarg_len, - &zpersistent) == FAILURE) { + &zpersistent) == FAILURE) + { RETURN_FALSE; } arg_len = (int)zarg_len; @@ -228,9 +236,12 @@ PHP_FUNCTION(mdsplus_connect) { strcmp(arg, lastHost) != 0) ? ConnectToMds(arg) : persistentConnection; - if (handle != -1) { - if (persistent) { - if (lastHost != 0) { + if (handle != -1) + { + if (persistent) + { + if (lastHost != 0) + { free(lastHost); lastHost = 0; } @@ -238,7 +249,9 @@ PHP_FUNCTION(mdsplus_connect) { persistentConnection = handle; } RETURN_LONG(handle); - } else { + } + else + { char *error = strcpy(malloc(arg_len + strlen("Error connecting to host: ") + 1), "Error connecting to host: "); @@ -257,11 +270,13 @@ PHP_FUNCTION(mdsplus_connect) { /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -PHP_FUNCTION(mdsplus_disconnect) { +PHP_FUNCTION(mdsplus_disconnect) +{ int socket; long int zsocket; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &zsocket) == - FAILURE) { + FAILURE) + { return; } socket = (int)zsocket; @@ -281,7 +296,8 @@ PHP_FUNCTION(mdsplus_disconnect) { /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -PHP_FUNCTION(mdsplus_open) { +PHP_FUNCTION(mdsplus_open) +{ char *tree = NULL; int arg_len, len; long zarg_len; @@ -292,7 +308,8 @@ PHP_FUNCTION(mdsplus_open) { int status; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lsl", &zsocket, &tree, - &zarg_len, &zshot) == FAILURE) { + &zarg_len, &zshot) == FAILURE) + { return; } socket = (int)zsocket; @@ -300,9 +317,12 @@ PHP_FUNCTION(mdsplus_open) { shot = (int)zshot; mdsplus_replace_error(0, 1); status = MdsOpen(socket, tree, shot); - if (status & 1) { + if (status & 1) + { RETURN_TRUE; - } else { + } + else + { mdsplus_replace_error(mdsplus_translate_status(socket, status), 1); RETURN_FALSE; } @@ -317,21 +337,26 @@ PHP_FUNCTION(mdsplus_open) { /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -PHP_FUNCTION(mdsplus_close) { +PHP_FUNCTION(mdsplus_close) +{ int socket; long zsocket; int status; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &zsocket) == - FAILURE) { + FAILURE) + { return; } socket = (int)zsocket; mdsplus_replace_error(0, 1); status = MdsClose(socket); - if (status & 1) { + if (status & 1) + { RETURN_TRUE; - } else { + } + else + { char *msg; mdsplus_replace_error(msg = mdsplus_translate_status(socket, status), 1); RETURN_FALSE; @@ -348,12 +373,16 @@ PHP_FUNCTION(mdsplus_close) { /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -static void MakeArray(zval *arr, struct descrip *ans, int dim, int *index) { +static void MakeArray(zval *arr, struct descrip *ans, int dim, int *index) +{ int i; array_init(arr); - if (dim == 0) { - for (i = 0; i < ans->dims[dim]; i++) { - switch (ans->dtype) { + if (dim == 0) + { + for (i = 0; i < ans->dims[dim]; i++) + { + switch (ans->dtype) + { case DTYPE_UCHAR: add_next_index_long(arr, (int)((unsigned char *)ans->ptr)[*index]); break; @@ -378,7 +407,8 @@ static void MakeArray(zval *arr, struct descrip *ans, int dim, int *index) { case DTYPE_DOUBLE: add_next_index_double(arr, ((double *)ans->ptr)[*index]); break; - case DTYPE_CSTRING: { + case DTYPE_CSTRING: + { char *string = strncpy(emalloc(ans->length + 1), ((char *)ans->ptr) + (*index * ans->length), ans->length); @@ -389,8 +419,11 @@ static void MakeArray(zval *arr, struct descrip *ans, int dim, int *index) { } *index = *index + 1; } - } else { - for (i = 0; i < ans->dims[dim]; i++) { + } + else + { + for (i = 0; i < ans->dims[dim]; i++) + { zval *arr2; MAKE_STD_ZVAL(arr2); MakeArray(arr2, ans, dim - 1, index); @@ -399,7 +432,8 @@ static void MakeArray(zval *arr, struct descrip *ans, int dim, int *index) { } } -PHP_FUNCTION(mdsplus_value) { +PHP_FUNCTION(mdsplus_value) +{ char *expression = NULL; int expression_len, len; int socket; @@ -423,14 +457,17 @@ PHP_FUNCTION(mdsplus_value) { mdsplus_replace_error(0, 1); if (num_args == 2) status = MdsValue(socket, expression, &ans, NULL); - else { + else + { int dims[7] = {0, 0, 0, 0, 0, 0, 0}; if (zend_get_parameters_array_ex(num_args, args) != SUCCESS) WRONG_PARAM_COUNT; status = SendArg(socket, 0, DTYPE_CSTRING, num_args - 1, strlen(expression), 0, dims, expression); - for (i = 2; (status & 1) && i < num_args; i++) { - switch (Z_TYPE_P(*args[i])) { + for (i = 2; (status & 1) && i < num_args; i++) + { + switch (Z_TYPE_P(*args[i])) + { case IS_LONG: status = SendArg(socket, i - 1, DTYPE_LONG, num_args - 1, sizeof(int), 0, dims, (void *)&Z_LVAL_P(*args[i])); @@ -448,16 +485,20 @@ PHP_FUNCTION(mdsplus_value) { "invalid argument type, must be long, double or string only", 0); RETURN_FALSE; } - if (!(status & 1)) { + if (!(status & 1)) + { mdsplus_replace_error("error sending argument to server", 0); RETURN_FALSE; break; } } - if (!(status & 1)) { + if (!(status & 1)) + { mdsplus_replace_error("error sending argument to server", 0); RETURN_FALSE; - } else { + } + else + { short len; int numbytes; void *dptr; @@ -465,22 +506,29 @@ PHP_FUNCTION(mdsplus_value) { status = GetAnswerInfoTS(socket, &ans.dtype, &len, &ans.ndims, &ans.dims, &numbytes, &dptr, &mem); ans.length = len; - if (numbytes) { - if (ans.dtype == DTYPE_CSTRING) { + if (numbytes) + { + if (ans.dtype == DTYPE_CSTRING) + { ans.ptr = malloc(numbytes + 1); ((char *)ans.ptr)[numbytes] = 0; - } else if (numbytes > 0) + } + else if (numbytes > 0) ans.ptr = malloc(numbytes); if (numbytes > 0) memcpy(ans.ptr, dptr, numbytes); - } else + } + else ans.ptr = NULL; free(mem); } } - if (status & 1) { - if (ans.ndims == 0) { - switch (ans.dtype) { + if (status & 1) + { + if (ans.ndims == 0) + { + switch (ans.dtype) + { case DTYPE_UCHAR: RETURN_LONG((int)*(unsigned char *)ans.ptr); break; @@ -508,7 +556,8 @@ PHP_FUNCTION(mdsplus_value) { case DTYPE_CSTRING: RETURN_STRING(ans.ptr ? ans.ptr : strcpy(malloc(1), ""), 1); break; - default: { + default: + { char error[128]; sprintf(error, "expression '%s' returned unsupported data type: %d", expression, ans.dtype); @@ -517,9 +566,12 @@ PHP_FUNCTION(mdsplus_value) { break; } } - } else { + } + else + { int index = 0; - switch (ans.dtype) { + switch (ans.dtype) + { case DTYPE_UCHAR: case DTYPE_USHORT: case DTYPE_ULONG: @@ -530,7 +582,8 @@ PHP_FUNCTION(mdsplus_value) { case DTYPE_DOUBLE: case DTYPE_CSTRING: break; - default: { + default: + { char error[128]; sprintf(error, "expression '%s' returned unsupported data type: %d", expression, ans.dtype); @@ -542,14 +595,19 @@ PHP_FUNCTION(mdsplus_value) { } MakeArray(return_value, &ans, ans.ndims - 1, &index); } - } else { + } + else + { char *error; - if (ans.ptr) { + if (ans.ptr) + { error = malloc(strlen(ans.ptr) + strlen(expression) + 128); sprintf(error, "expression '%s' evaluation failed with the following error: %s", expression, ans.ptr); - } else { + } + else + { error = malloc(strlen(expression) + 128); sprintf(error, "expression '%s' evaluation failed with status return %d", expression, status); @@ -569,7 +627,8 @@ PHP_FUNCTION(mdsplus_value) { /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -PHP_FUNCTION(mdsplus_put) { +PHP_FUNCTION(mdsplus_put) +{ char *node = NULL; int node_len; char *expression = NULL; @@ -596,7 +655,8 @@ PHP_FUNCTION(mdsplus_put) { mdsplus_replace_error(0, 1); if (num_args == 3) status = MdsPut(socket, node, expression, &ans, NULL); - else { + else + { int dims[7] = {0, 0, 0, 0, 0, 0, 0}; char putexp[512]; if (zend_get_parameters_array_ex(num_args, args) != SUCCESS) @@ -611,8 +671,10 @@ PHP_FUNCTION(mdsplus_put) { node); status = SendArg(socket, 2, DTYPE_CSTRING, num_args, strlen(expression), 0, dims, expression); - for (i = 3; (status & 1) && i < num_args; i++) { - switch (Z_TYPE_P(*args[i])) { + for (i = 3; (status & 1) && i < num_args; i++) + { + switch (Z_TYPE_P(*args[i])) + { case IS_LONG: status = SendArg(socket, i, DTYPE_LONG, num_args, sizeof(int), 0, dims, (void *)&Z_LVAL_P(*args[i])); @@ -632,15 +694,19 @@ PHP_FUNCTION(mdsplus_put) { goto done_mdsplus_put; break; } - if (!(status & 1)) { + if (!(status & 1)) + { mdsplus_replace_error("error sending argument to server", 0); goto done_mdsplus_put; } } - if (!(status & 1)) { + if (!(status & 1)) + { mdsplus_replace_error("error sending argument to server", 0); goto done_mdsplus_put; - } else { + } + else + { short len; int numbytes; void *dptr; @@ -648,36 +714,49 @@ PHP_FUNCTION(mdsplus_put) { status = GetAnswerInfoTS(socket, &ans.dtype, &len, &ans.ndims, &ans.dims, &numbytes, &dptr, &mem); ans.length = len; - if (numbytes) { - if (ans.dtype == DTYPE_CSTRING) { + if (numbytes) + { + if (ans.dtype == DTYPE_CSTRING) + { ans.ptr = malloc(numbytes + 1); ((char *)ans.ptr)[numbytes] = 0; - } else if (numbytes > 0) + } + else if (numbytes > 0) ans.ptr = malloc(numbytes); if (numbytes > 0) memcpy(ans.ptr, dptr, numbytes); - } else + } + else ans.ptr = NULL; free(mem); } } - if (status & 1) { - if (ans.ptr && (*(int *)ans.ptr & 1)) { + if (status & 1) + { + if (ans.ptr && (*(int *)ans.ptr & 1)) + { goto done_mdsplus_put; - } else { + } + else + { mdsplus_replace_error(mdsplus_translate_status(socket, *(int *)ans.ptr), 1); status = 0; goto done_mdsplus_put; } - } else { + } + else + { char *error; - if (ans.ptr) { + if (ans.ptr) + { error = malloc(strlen(ans.ptr) + strlen(expression) + 128); sprintf(error, "expression '%s' evaluation failed with the following error: %s", expression, ans.ptr); - } else { + } + else + { error = malloc(strlen(expression) + 128); sprintf(error, "expression '%s' evaluation failed with status return %d", expression, status); @@ -686,9 +765,12 @@ PHP_FUNCTION(mdsplus_put) { } done_mdsplus_put: free(ans.ptr); - if (status & 1) { + if (status & 1) + { RETURN_TRUE; - } else { + } + else + { RETURN_FALSE; } } @@ -702,10 +784,14 @@ PHP_FUNCTION(mdsplus_put) { /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_mdsplus_compiled(string arg) Return a string to confirm that the module is compiled in */ -PHP_FUNCTION(mdsplus_error) { - if (mdsplus_error_msg) { +PHP_FUNCTION(mdsplus_error) +{ + if (mdsplus_error_msg) + { RETVAL_STRING(mdsplus_error_msg, 1); - } else { + } + else + { RETURN_FALSE; } return; diff --git a/python/MDSplus/mdsdcl.py b/python/MDSplus/mdsdcl.py index b9e6b993bb..31ada5618d 100644 --- a/python/MDSplus/mdsdcl.py +++ b/python/MDSplus/mdsdcl.py @@ -76,8 +76,7 @@ def dcl(command, return_out=False, return_error=False, raise_exception=False, tr status = _mdsdcl.mdsdcl_do_command_dsc( _ver.tobytes(command), error_p, out_p) if (return_out or return_error) and raise_exception: - if raise_exception: - _exc.checkStatus(status, message=xd_error.value) + _exc.checkStatus(status, message=xd_error.value) if return_out and return_error: return (xd_output.value, xd_error.value) elif return_out: diff --git a/remcam/CamIosb.c b/remcam/CamIosb.c index 8e99931139..7c16166d56 100644 --- a/remcam/CamIosb.c +++ b/remcam/CamIosb.c @@ -30,32 +30,38 @@ extern unsigned short RemCamLastIosb[4]; EXPORT int CamVerbose(int flag __attribute__((unused))) { return 1; } -EXPORT int CamBytcnt(unsigned short *iosb) { +EXPORT int CamBytcnt(unsigned short *iosb) +{ return (int)(iosb ? iosb[1] : RemCamLastIosb[1]); } -EXPORT int CamError(int *xexp, int *qexp, unsigned short *iosb_in) { +EXPORT int CamError(int *xexp, int *qexp, unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((!(iosb[0] & 1)) || (xexp && ((*xexp & 1) != (iosb[2] & 1))) || (qexp && ((*qexp & 1) != ((iosb[2] >> 1) & 1)))); } -EXPORT int CamX(unsigned short *iosb_in) { +EXPORT int CamX(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && (iosb[2] & 1)); } -EXPORT int CamQ(unsigned short *iosb_in) { +EXPORT int CamQ(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && (iosb[2] & 2)); } -EXPORT int CamGetStat(unsigned short *iosb_in) { +EXPORT int CamGetStat(unsigned short *iosb_in) +{ memcpy(iosb_in, RemCamLastIosb, sizeof(RemCamLastIosb)); return 1; } -EXPORT int CamXandQ(unsigned short *iosb_in) { +EXPORT int CamXandQ(unsigned short *iosb_in) +{ unsigned short *iosb = iosb_in ? iosb_in : RemCamLastIosb; return ((iosb[0] & 1) && ((iosb[2] & 3) == 3)); } diff --git a/remcam/CamMulti.c b/remcam/CamMulti.c index dd864c118e..d3c15d06e6 100644 --- a/remcam/CamMulti.c +++ b/remcam/CamMulti.c @@ -39,10 +39,11 @@ extern int RemoteServerId(); static int CamMulti(char *routine, char *name, int a, int f, int count, void *data, int mem, unsigned short *iosb); -#define MakeMulti(locnam, remnam) \ - EXPORT int locnam(char *name, int a, int f, int count, void *data, int mem, \ - unsigned short *iosb) { \ - return CamMulti(#remnam, name, a, f, count, data, mem, iosb); \ +#define MakeMulti(locnam, remnam) \ + EXPORT int locnam(char *name, int a, int f, int count, void *data, int mem, \ + unsigned short *iosb) \ + { \ + return CamMulti(#remnam, name, a, f, count, data, mem, iosb); \ } MakeMulti(CamFQrepw, FQrepw) MakeMulti(CamFQstopw, FQstopw) @@ -54,7 +55,8 @@ MakeMulti(CamFQrepw, FQrepw) MakeMulti(CamFQstopw, FQstopw) int count, void *data, int mem, short *iosb); static int CamMulti(char *routine, char *name, int a, int f, int count, - void *data, int mem, unsigned short *iosb) { + void *data, int mem, unsigned short *iosb) +{ int status = 1; iosb = (iosb) ? iosb : (unsigned short *)&RemCamLastIosb; @@ -66,12 +68,14 @@ static int CamMulti(char *routine, char *name, int a, int f, int count, return status; } -static void getiosb(int serverid, short *iosb) { +static void getiosb(int serverid, short *iosb) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, 0); if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && - ans_d.dims[0] == 4) { + ans_d.dims[0] == 4) + { memcpy(RemCamLastIosb, ans_d.ptr, 8); if (iosb) memcpy(iosb, ans_d.ptr, 8); @@ -79,7 +83,8 @@ static void getiosb(int serverid, short *iosb) { free(ans_d.ptr); } -static void getdata(int serverid, void *data) { +static void getdata(int serverid, void *data) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, 0); @@ -91,26 +96,32 @@ static void getdata(int serverid, void *data) { } static int DoCamMulti(char *routine, char *name, int a, int f, int count, - void *data, int mem, short *iosb) { + void *data, int mem, short *iosb) +{ int serverid = RemoteServerId(); int status = 0; int writeData; - if (serverid) { + if (serverid) + { struct descrip data_d = {8, 1, {0}, 0, 0}; struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; writeData = (!(f & 0x08)) && (f > 8); sprintf(cmd, "CamMulti('%s','%s',%d,%d,%d,%s,%d,_iosb)", routine, name, a, f, count, writeData ? "_data=$" : "_data", mem); - if (writeData) { + if (writeData) + { data_d.dtype = mem < 24 ? DTYPE_SHORT : DTYPE_LONG; data_d.dims[0] = count; data_d.ptr = data; status = MdsValue(serverid, cmd, &data_d, &ans_d, 0); - } else { + } + else + { status = MdsValue(serverid, cmd, &ans_d, 0); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; @@ -122,37 +133,45 @@ static int DoCamMulti(char *routine, char *name, int a, int f, int count, return status; } -EXPORT int CamSetMAXBUF(char *name, int new) { +EXPORT int CamSetMAXBUF(char *name, int new) +{ int serverid = RemoteServerId(); int status = -1; - if (serverid) { + if (serverid) + { struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; sprintf(cmd, "CamSetMAXBUF('%s',%d)", name, new); status = MdsValue(serverid, cmd, &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; - } else + } + else status = -1; } return status; } -EXPORT int CamGetMAXBUF(char *name) { +EXPORT int CamGetMAXBUF(char *name) +{ int serverid = RemoteServerId(); int status = -1; - if (serverid) { + if (serverid) + { struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; sprintf(cmd, "CamGetMAXBUF('%s')", name); status = MdsValue(serverid, cmd, &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; - } else + } + else status = -1; } return status; diff --git a/remcam/CamSingle.c b/remcam/CamSingle.c index 4d4fedb193..ad1f42cc4c 100644 --- a/remcam/CamSingle.c +++ b/remcam/CamSingle.c @@ -31,14 +31,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. short RemCamLastIosb[4]; -int RemoteServerId() { +int RemoteServerId() +{ static int socket = 0; - if (socket == 0) { + if (socket == 0) + { char *server = getenv("camac_server"); - if (server == 0) { + if (server == 0) + { printf("Set the camac_server environment variable to your camac server " "address\n"); - } else { + } + else + { socket = ConnectToMds(server); if (socket < 0) socket = 0; @@ -50,20 +55,23 @@ int RemoteServerId() { static int CamSingle(char *routine, char *name, int a, int f, void *data, int mem, short *iosb); -#define MakeSingle(locnam, remnam) \ - EXPORT int locnam(char *name, int a, int f, void *data, int mem, \ - short *iosb) { \ - return CamSingle(#remnam, name, a, f, data, mem, iosb); \ +#define MakeSingle(locnam, remnam) \ + EXPORT int locnam(char *name, int a, int f, void *data, int mem, \ + short *iosb) \ + { \ + return CamSingle(#remnam, name, a, f, data, mem, iosb); \ } MakeSingle(CamPiow, Piow) MakeSingle(CamPioQrepw, PioQrepw) - static void getiosb(int serverid, short *iosb) { + static void getiosb(int serverid, short *iosb) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, 0); if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && - ans_d.dims[0] == 4) { + ans_d.dims[0] == 4) + { memcpy(RemCamLastIosb, ans_d.ptr, 8); if (iosb) memcpy(iosb, ans_d.ptr, 8); @@ -71,7 +79,8 @@ MakeSingle(CamPiow, Piow) MakeSingle(CamPioQrepw, PioQrepw) free(ans_d.ptr); } -static void getdata(int serverid, void *data) { +static void getdata(int serverid, void *data) +{ int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, 0); @@ -82,11 +91,13 @@ static void getdata(int serverid, void *data) { } static int CamSingle(char *routine, char *name, int a, int f, void *data, - int mem, short *iosb) { + int mem, short *iosb) +{ int serverid = RemoteServerId(); int status = 0; int writeData; - if (serverid) { + if (serverid) + { struct descrip data_d = {8, 0, {0}, 0, 0}; struct descrip ans_d = {0, 0, {0}, 0, 0}; char cmd[512]; @@ -94,14 +105,18 @@ static int CamSingle(char *routine, char *name, int a, int f, void *data, writeData = (!(f & 0x08)) && (f > 8); sprintf(cmd, "CamSingle('%s','%s',%d,%d,%s,%d,_iosb)", routine, name, a, f, (writeData) ? "_data=$" : "_data", mem); - if (writeData) { + if (writeData) + { data_d.dtype = mem < 24 ? DTYPE_SHORT : DTYPE_LONG; data_d.ptr = data; status = MdsValue(serverid, cmd, &data_d, &ans_d, 0); - } else { + } + else + { status = MdsValue(serverid, cmd, &ans_d, 0); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { + if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); ans_d.ptr = 0; diff --git a/roam/roam_check_access.c b/roam/roam_check_access.c index a4ca09708c..792bf43c3b 100644 --- a/roam/roam_check_access.c +++ b/roam/roam_check_access.c @@ -42,19 +42,26 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #endif -static char *urlencode(char *in) { +static char *urlencode(char *in) +{ char *ans = 0; int i; int j = 0; int inlen = strlen(in); ans = malloc(inlen * 3); - for (i = 0, j = 0; i < inlen; i++) { + for (i = 0, j = 0; i < inlen; i++) + { if ((in[i] >= '0' && in[i] <= '9') || (in[i] >= 'A' && in[i] <= 'Z') || - (in[i] >= 'a' && in[i] <= 'z')) { + (in[i] >= 'a' && in[i] <= 'z')) + { ans[j++] = in[i]; - } else if (in[i] == ' ') { + } + else if (in[i] == ' ') + { ans[j++] = '+'; - } else { + } + else + { ans[j++] = '%'; sprintf(&ans[j], "%2X", (unsigned int)in[i]); j += 2; @@ -67,7 +74,8 @@ static char *urlencode(char *in) { #ifdef XIO EXPORT int roam_check_access(char *host, int https, char *resource, char *permit, char *dn, - struct descriptor_xd *aux) { + struct descriptor_xd *aux) +{ globus_xio_driver_t tcp_driver; globus_xio_driver_t gsi_driver; globus_xio_driver_t http_driver; @@ -99,14 +107,16 @@ EXPORT int roam_check_access(char *host, int https, char *resource, globus_xio_stack_init(&stack, NULL); globus_xio_driver_load("tcp", &tcp_driver); globus_xio_stack_push_driver(stack, tcp_driver); - if (https) { + if (https) + { globus_xio_driver_load("gsi", &gsi_driver); globus_xio_stack_push_driver(stack, gsi_driver); } globus_xio_driver_load("http", &http_driver); globus_xio_stack_push_driver(stack, http_driver); globus_xio_attr_init(&attr); - if (https) { + if (https) + { globus_xio_attr_cntl(attr, gsi_driver, GLOBUS_XIO_GSI_SET_SSL_COMPATIBLE, GLOBUS_TRUE); } @@ -114,15 +124,20 @@ EXPORT int roam_check_access(char *host, int https, char *resource, // test_res(res); res = globus_xio_open(xio_handle, url, attr); // test_res(res); - while (res == GLOBUS_SUCCESS) { + while (res == GLOBUS_SUCCESS) + { nbytes = 0; res = globus_xio_read(xio_handle, line, LINE_LEN, 1, &nbytes, NULL); - if (nbytes > 0) { - if (ans) { + if (nbytes > 0) + { + if (ans) + { int newlen = strlen(ans) + nbytes; ans = strncat(realloc(ans, newlen + 1), line, nbytes); ans[newlen] = 0; - } else { + } + else + { ans = strncpy(malloc(nbytes + 1), line, nbytes); ans[nbytes] = 0; } @@ -130,8 +145,10 @@ EXPORT int roam_check_access(char *host, int https, char *resource, if (res) break; } - if (ans && strlen(ans) > 4) { - if (strncmp(ans, "yes", 3) == 0) { + if (ans && strlen(ans) > 4) + { + if (strncmp(ans, "yes", 3) == 0) + { struct descriptor accnt = {0, DTYPE_T, CLASS_S, 0}; status = GLOBUS_SUCCESS; accnt.pointer = malloc(strlen(ans) - 4); @@ -150,18 +167,23 @@ EXPORT int roam_check_access(char *host, int https, char *resource, } #else -struct _buf { +struct _buf +{ size_t size; char *ptr; }; -static size_t callback(void *contents, size_t size, size_t nmemb, void *userp) { +static size_t callback(void *contents, size_t size, size_t nmemb, void *userp) +{ char *ptr = (char *)contents; struct _buf *buf = (struct _buf *)userp; - if (buf->size == 0) { + if (buf->size == 0) + { buf->ptr = malloc(size * nmemb + 1); memcpy(buf->ptr, ptr, size * nmemb); - } else { + } + else + { buf->ptr = realloc(buf->ptr, buf->size + size * nmemb + 1); memcpy(buf->ptr + buf->size, ptr, size * nmemb); } @@ -172,7 +194,8 @@ static size_t callback(void *contents, size_t size, size_t nmemb, void *userp) { EXPORT int roam_check_access(char *host, int https, char *resource, char *permit, char *dn, - struct descriptor_xd *aux) { + struct descriptor_xd *aux) +{ CURL *ctx = curl_easy_init(); CURLcode status; struct _buf buf = {0, 0}; @@ -195,9 +218,12 @@ EXPORT int roam_check_access(char *host, int https, char *resource, curl_easy_setopt(ctx, CURLOPT_CAPATH, "/etc/grid-security/certificates"); status = curl_easy_perform(ctx); curl_easy_cleanup(ctx); - if (status == 0 && buf.size >= 4) { - if (strncmp(buf.ptr, "yes", 3) == 0) { - if (buf.size > 4) { + if (status == 0 && buf.size >= 4) + { + if (strncmp(buf.ptr, "yes", 3) == 0) + { + if (buf.size > 4) + { struct descriptor accnt = {0, DTYPE_T, CLASS_S, 0}; accnt.pointer = malloc(buf.size - 4); if (buf.size > 5) @@ -206,9 +232,12 @@ EXPORT int roam_check_access(char *host, int https, char *resource, accnt.length = strlen(accnt.pointer); MdsCopyDxXd(&accnt, aux); } - } else + } + else status = -2; - } else { + } + else + { status = -1; } free(buf.ptr); diff --git a/roam/roam_gridmap_callout.c b/roam/roam_gridmap_callout.c index 0e481a951c..74f89d2ee6 100644 --- a/roam/roam_gridmap_callout.c +++ b/roam/roam_gridmap_callout.c @@ -93,7 +93,8 @@ extern int MdsFree1Dx(); int roam_check_access(); -EXPORT globus_result_t roam_gridmap_callout(va_list ap) { +EXPORT globus_result_t roam_gridmap_callout(va_list ap) +{ gss_ctx_id_t context; char *service; char *desired_identity; @@ -130,7 +131,8 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL, &initiator, GLOBUS_NULL); - if (GSS_ERROR(major_status)) { + if (GSS_ERROR(major_status)) + { GLOBUS_GRIDMAP_CALLOUT_GSS_ERROR(result, major_status, minor_status); goto error; } @@ -140,7 +142,8 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { initiator ? &peer : GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL, GLOBUS_NULL); - if (GSS_ERROR(major_status)) { + if (GSS_ERROR(major_status)) + { GLOBUS_GRIDMAP_CALLOUT_GSS_ERROR(result, major_status, minor_status); goto error; } @@ -148,7 +151,8 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { major_status = gss_display_name(&minor_status, peer, &peer_name_buffer, GLOBUS_NULL); - if (GSS_ERROR(major_status)) { + if (GSS_ERROR(major_status)) + { GLOBUS_GRIDMAP_CALLOUT_GSS_ERROR(result, major_status, minor_status); gss_release_name(&minor_status, &peer); goto error; @@ -156,7 +160,8 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { gss_release_name(&minor_status, &peer); - if (desired_identity == NULL) { + if (desired_identity == NULL) + { struct descriptor expression_d = {0, DTYPE_T, CLASS_S, 0}; struct descriptor local_user_d = {0, DTYPE_T, CLASS_D, 0}; int status; @@ -168,16 +173,20 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { expression_d.length = strlen(expression); expression_d.pointer = expression; status = TdiExecute(&expression_d, &local_user_d MDS_END_ARG); - if (status & 1) { + if (status & 1) + { rc = GLOBUS_SUCCESS; local_identity = strncpy((char *)malloc(local_user_d.length + 1), local_user_d.pointer, local_user_d.length); local_identity[local_user_d.length] = 0; MdsFree1Dx(&local_user_d, 0); - } else { + } + else + { rc = globus_gss_assist_gridmap(peer_name_buffer.value, &local_identity); } - if (rc != 0) { + if (rc != 0) + { GLOBUS_GRIDMAP_CALLOUT_ERROR( result, GLOBUS_GRIDMAP_CALLOUT_LOOKUP_FAILED, ("Could not map %s\n", peer_name_buffer.value)); @@ -185,16 +194,21 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) { goto error; } - if (strlen(local_identity) + 1 > buffer_length) { + if (strlen(local_identity) + 1 > buffer_length) + { GLOBUS_GRIDMAP_CALLOUT_ERROR( result, GLOBUS_GRIDMAP_CALLOUT_BUFFER_TOO_SMALL, ("Local identity length: %d Buffer length: %d\n", strlen(local_identity), buffer_length)); - } else { + } + else + { strcpy(identity_buffer, local_identity); } free(local_identity); - } else { + } + else + { GLOBUS_GRIDMAP_CALLOUT_ERROR( result, GLOBUS_GRIDMAP_CALLOUT_LOOKUP_FAILED, ("Could not map %s to %s\n", peer_name_buffer.value, desired_identity)); diff --git a/servershr/ServerAbortServer.c b/servershr/ServerAbortServer.c index 4b77d9693c..166cf52415 100644 --- a/servershr/ServerAbortServer.c +++ b/servershr/ServerAbortServer.c @@ -56,7 +56,8 @@ int SERVER$ABORT_SERVER( struct dsc$descriptor *server ) #include #include "servershrp.h" -EXPORT int ServerAbortServer(char *server, int flush) { +EXPORT int ServerAbortServer(char *server, int flush) +{ struct descrip p1; return ServerSendMessage(0, server, SrvAbort, NULL, NULL, NULL, NULL, NULL, NULL, 1, MakeDescrip(&p1, DTYPE_LONG, 0, 0, &flush)); diff --git a/servershr/ServerBuildDispatchTable.c b/servershr/ServerBuildDispatchTable.c index dc467eee68..2665294b59 100644 --- a/servershr/ServerBuildDispatchTable.c +++ b/servershr/ServerBuildDispatchTable.c @@ -76,7 +76,8 @@ extern int TdiGetNci(); static int num_actions; static ActionInfo *actions; -static int CompareActions(ActionInfo *a, ActionInfo *b) { +static int CompareActions(ActionInfo *a, ActionInfo *b) +{ return a->on == b->on ? (a->phase == b->phase ? a->sequence - b->sequence : a->phase - b->phase) : b->on - a->on; @@ -84,13 +85,17 @@ static int CompareActions(ActionInfo *a, ActionInfo *b) { #define MAX_ACTIONS 10000 -static int ifAddReference(int idx, int *nid) { +static int ifAddReference(int idx, int *nid) +{ int i, j; - for (i = 0; i < num_actions; i++) { - if (actions[i].nid == *nid) { + for (i = 0; i < num_actions; i++) + { + if (actions[i].nid == *nid) + { if (actions[i].num_references == 0) actions[i].referenced_by = (int *)malloc(sizeof(int)); - else { + else + { for (j = 0; j < actions[i].num_references; j++) if (actions[i].referenced_by[j] == idx) return B_TRUE; @@ -106,7 +111,8 @@ static int ifAddReference(int idx, int *nid) { return B_FALSE; } -static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) { +static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) +{ INIT_STATUS; static DESCRIPTOR(dtype_str, "DTYPE"); static int dtype; @@ -114,7 +120,8 @@ static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) { DESCRIPTOR_NID(niddsc, 0); niddsc.pointer = (char *)nid; status = TdiGetNci(&niddsc, &dtype_str, &dtype_dsc MDS_END_ARG); - if (STATUS_OK && dtype == DTYPE_ACTION && ifAddReference(idx, nid)) { + if (STATUS_OK && dtype == DTYPE_ACTION && ifAddReference(idx, nid)) + { char ident[64]; char tmp[64]; struct descriptor ident_dsc = {0, DTYPE_T, CLASS_S, 0}; @@ -136,31 +143,35 @@ static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) { } static int fixup_path(struct descriptor *path_in, int idx, - struct descriptor_d *path_out) { + struct descriptor_d *path_out) +{ char *path = strncpy((char *)malloc(path_in->length + 1), path_in->pointer, path_in->length); int nid; int flag = B_FALSE; path[path_in->length] = 0; - if - IS_OK(TreeFindNode(path, &nid)) - flag = fixup_nid(&nid, idx, path_out); + if (IS_OK(TreeFindNode(path, &nid))) + flag = fixup_nid(&nid, idx, path_out); free(path); return flag; } static int make_idents(struct descriptor *path_in, int idx __attribute__((unused)), - struct descriptor *path_out __attribute__((unused))) { + struct descriptor *path_out __attribute__((unused))) +{ if (path_in && path_in->pointer && path_in->pointer[0] == '_') path_in->dtype = DTYPE_IDENT; return B_FALSE; } -static void LinkConditions() { +static void LinkConditions() +{ int i; - for (i = 0; i < num_actions; i++) { - if (actions[i].condition) { + for (i = 0; i < num_actions; i++) + { + if (actions[i].condition) + { EMPTYXD(xd); MdsCopyDxXdZ(actions[i].condition, &xd, 0, fixup_nid, i + (char *)0, fixup_path, i + (char *)0); @@ -173,7 +184,8 @@ static void LinkConditions() { } EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, - void **table) { + void **table) +{ if (*table) ServerFreeDispatchTable(*table); DispatchTable **table_ptr = (DispatchTable **)table; @@ -213,7 +225,8 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, (num_actions < MAX_ACTIONS)) num_actions++; TreeFindNodeEnd(&ctx); - if (num_actions) { + if (num_actions) + { static int zero = 0; int table_size = sizeof(DispatchTable) + (num_actions - 1) * sizeof(ActionInfo); @@ -221,7 +234,8 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, actions = (*table_ptr)->actions; (*table_ptr)->shot = shot; strcpy((*table_ptr)->tree, tree); - for (i = 0, nidptr = nids; i < num_actions; nidptr++, i++) { + for (i = 0, nidptr = nids; i < num_actions; nidptr++, i++) + { struct descriptor_d event_name = {0, DTYPE_T, CLASS_D, 0}; struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, 0}; static EMPTYXD(xd); @@ -234,11 +248,14 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, actions[i].dispatched = 0; actions[i].closed = 0; actions[i].condition = 0; - if (actions[i].on) { - if (TdiDispatchOf(&niddsc, &xd MDS_END_ARG) & 1) { + if (actions[i].on) + { + if (TdiDispatchOf(&niddsc, &xd MDS_END_ARG) & 1) + { struct descriptor_dispatch *dispatch = (struct descriptor_dispatch *)xd.pointer; - if (dispatch->pointer && (dispatch->pointer[0] == TreeSCHED_SEQ)) { + if (dispatch->pointer && (dispatch->pointer[0] == TreeSCHED_SEQ)) + { struct descriptor server = {sizeof(actions->server), DTYPE_T, CLASS_S, 0}; static DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); @@ -249,7 +266,8 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, &phase_d MDS_END_ARG) & 1)) actions[i].phase = 0x10000001; - if (!(TdiGetLong(dispatch->when, &actions[i].sequence) & 1)) { + if (!(TdiGetLong(dispatch->when, &actions[i].sequence) & 1)) + { static EMPTYXD(emptyxd); actions[i].sequence = 0; actions[i].condition = (struct descriptor *)memcpy( @@ -257,22 +275,26 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, MdsCopyDxXd((struct descriptor *)dispatch->when, (struct descriptor_xd *)actions[i].condition); actions[i].path = TreeGetMinimumPath(&zero, actions[i].nid); - } else if (actions[i].sequence <= 0) + } + else if (actions[i].sequence <= 0) actions[i].phase = 0x10000002; else actions[i].path = TreeGetMinimumPath(&zero, actions[i].nid); if (!(TdiData(dispatch->ident, &server MDS_END_ARG) & 1)) actions[i].phase = 0x10000003; - } else + } + else actions[i].phase = 0x10000004; if (TdiData(dispatch->completion, &event_name MDS_END_ARG) & 1 && - event_name.length) { + event_name.length) + { actions[i].event = strncpy((char *)malloc(event_name.length + 1), event_name.pointer, event_name.length); actions[i].event[event_name.length] = 0; StrFree1Dx(&event_name); } - } else + } + else actions[i].phase = 0x10000005; } } @@ -282,7 +304,8 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, ; (*table_ptr)->num = i; LinkConditions(); - if (monitor_name) { + if (monitor_name) + { char tree[13]; char *cptr; for (i = 0, cptr = (*table_ptr)->tree; i < 12; i++) @@ -293,23 +316,25 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, tree[i] = 0; char *server = ""; #define SKIP_OTHERS -#define SEND(i, mode) \ - ServerSendMonitor(monitor_name, tree, (*table_ptr)->shot, actions[i].phase, \ - actions[i].nid, actions[i].on, mode, server, \ +#define SEND(i, mode) \ + ServerSendMonitor(monitor_name, tree, (*table_ptr)->shot, actions[i].phase, \ + actions[i].nid, actions[i].on, mode, server, \ actions[i].status) - if - IS_OK(SEND(0, MonitorBuildBegin)) { // send begin + if (IS_OK(SEND(0, MonitorBuildBegin))) + { // send begin #ifdef SKIP_OTHERS - if (num_actions > 1) + if (num_actions > 1) #else - for (i = 1; i < num_actions - 1; i++) - IS_NOT_OK(SEND(i, MonitorBuild)) break; // send others - if (i == num_actions - 1) + for (i = 1; i < num_actions - 1; i++) + IS_NOT_OK(SEND(i, MonitorBuild)) + break; // send others + if (i == num_actions - 1) #endif - SEND(num_actions - 1, MonitorBuildEnd); // send last - } + SEND(num_actions - 1, MonitorBuildEnd); // send last + } } - } else + } + else status = TreeNNF; free(nids); return status; diff --git a/servershr/ServerCloseTrees.c b/servershr/ServerCloseTrees.c index 71a8c82769..e4d1c289c2 100644 --- a/servershr/ServerCloseTrees.c +++ b/servershr/ServerCloseTrees.c @@ -56,7 +56,8 @@ int SERVER$CLOSE_TREES( struct dsc$descriptor *server ) #include #include "servershrp.h" -EXPORT int ServerCloseTrees(char *server) { +EXPORT int ServerCloseTrees(char *server) +{ return ServerSendMessage(0, server, SrvClose, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL); } diff --git a/servershr/ServerCreatePulse.c b/servershr/ServerCreatePulse.c index e70e524fe2..3e9b8b53e6 100644 --- a/servershr/ServerCreatePulse.c +++ b/servershr/ServerCreatePulse.c @@ -60,7 +60,8 @@ dsc$descriptor *tree, int *shot, void (*ast)(), int astprm, int *netid, void EXPORT int ServerCreatePulse(int *id, char *server, char *tree, int shot, void (*ast)(), void *astprm, int *retstatus, - pthread_rwlock_t *lock, void (*before_ast)()) { + pthread_rwlock_t *lock, void (*before_ast)()) +{ struct descrip p1, p2; return ServerSendMessage(id, server, SrvAction, retstatus, lock, NULL, ast, astprm, before_ast, 2, diff --git a/servershr/ServerDispatchAction.c b/servershr/ServerDispatchAction.c index 4b3167fa2f..cdba034100 100644 --- a/servershr/ServerDispatchAction.c +++ b/servershr/ServerDispatchAction.c @@ -61,7 +61,8 @@ dsc$descriptor *tree, int *shot, int *nid, void (*ast)(), int astprm, int EXPORT int ServerDispatchAction(int *id, char *server, char *tree, int shot, int nid, void (*ast)(), void *astprm, int *retstatus, pthread_rwlock_t *lock, - int *socket, void (*before_ast)()) { + int *socket, void (*before_ast)()) +{ struct descrip p1, p2, p3; return ServerSendMessage(id, server, SrvAction, retstatus, lock, socket, ast, astprm, before_ast, 3, diff --git a/servershr/ServerDispatchClose.c b/servershr/ServerDispatchClose.c index 06ce35c6f3..b52570c966 100644 --- a/servershr/ServerDispatchClose.c +++ b/servershr/ServerDispatchClose.c @@ -55,7 +55,8 @@ int SERVER$DISPATCH_CLOSE(DispatchTable *table) #include #include "servershrp.h" -static char *Server(char *out, char *srv) { +static char *Server(char *out, char *srv) +{ int i; for (i = 0; i < 32; i++) out[i] = srv[i] == ' ' ? 0 : srv[i]; @@ -63,7 +64,8 @@ static char *Server(char *out, char *srv) { return out; } extern void serverDisarmDispatchTable(void *vtable); -EXPORT int ServerDispatchClose(void *vtable) { +EXPORT int ServerDispatchClose(void *vtable) +{ if (!vtable) return MDSplusSUCCESS; serverDisarmDispatchTable(vtable); @@ -72,10 +74,13 @@ EXPORT int ServerDispatchClose(void *vtable) { ActionInfo *action = table->actions; int num_actions = table->num; int i, j; - for (i = 0; i < num_actions; i++) { - if (action[i].dispatched && !action[i].closed) { + for (i = 0; i < num_actions; i++) + { + if (action[i].dispatched && !action[i].closed) + { ServerCloseTrees(Server(server, action[i].server)); - for (j = i + 1; j < num_actions; j++) { + for (j = i + 1; j < num_actions; j++) + { if (action[i].netid == action[j].netid) action[j].closed = 1; } diff --git a/servershr/ServerDispatchCommand.c b/servershr/ServerDispatchCommand.c index 953d3c7f86..7151ea0b3b 100644 --- a/servershr/ServerDispatchCommand.c +++ b/servershr/ServerDispatchCommand.c @@ -61,7 +61,8 @@ int *netid, void (*link_down)(), void (*before_ast)()) EXPORT int ServerDispatchCommand(int *id, char *server, char *cli, char *command, void (*ast)(), void *astprm, int *retstatus, pthread_rwlock_t *lock, - void (*before_ast)()) { + void (*before_ast)()) +{ struct descrip p1, p2; return ServerSendMessage(id, server, SrvCommand, retstatus, lock, NULL, ast, astprm, before_ast, 2, diff --git a/servershr/ServerDispatchPhase.c b/servershr/ServerDispatchPhase.c index 4dcf8ef94a..69ff1baebf 100644 --- a/servershr/ServerDispatchPhase.c +++ b/servershr/ServerDispatchPhase.c @@ -101,7 +101,8 @@ STATIC_ROUTINE void WaitForActions(int conditionals, int first_g, int last_g, // STATIC_CONSTANT const int zero = 0; -typedef struct _complete { +typedef struct _complete +{ struct _complete *next; int idx; } Complete; @@ -109,7 +110,8 @@ typedef struct _complete { STATIC_THREADSAFE Complete *CompletedQueueHead = NULL; STATIC_THREADSAFE Complete *CompletedQueueTail = NULL; -typedef struct _send_monitor { +typedef struct _send_monitor +{ struct _send_monitor *next; int idx; int mode; @@ -128,7 +130,8 @@ STATIC_THREADSAFE int last_s; static int AbortInProgress; static pthread_mutex_t abortinprogress_mutex = PTHREAD_MUTEX_INITIALIZER; -static inline int setAbortInProgress(int val_in) { +static inline int setAbortInProgress(int val_in) +{ int val_out; pthread_mutex_lock(&abortinprogress_mutex); val_out = AbortInProgress; @@ -136,7 +139,8 @@ static inline int setAbortInProgress(int val_in) { pthread_mutex_unlock(&abortinprogress_mutex); return val_out; } -static inline int isAbortInProgress() { +static inline int isAbortInProgress() +{ int val; pthread_mutex_lock(&abortinprogress_mutex); val = AbortInProgress; @@ -149,8 +153,8 @@ STATIC_THREADSAFE Condition SendMonitorC = CONDITION_INITIALIZER; STATIC_THREADSAFE Condition CompletedC = CONDITION_INITIALIZER; static pthread_mutex_t send_monitor_queue_mutex = PTHREAD_MUTEX_INITIALIZER; -#define MONITOR_QUEUE_LOCK \ - pthread_mutex_lock(&send_monitor_queue_mutex); \ +#define MONITOR_QUEUE_LOCK \ + pthread_mutex_lock(&send_monitor_queue_mutex); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &send_monitor_queue_mutex) #define MONITOR_QUEUE_UNLOCK pthread_cleanup_pop(1) @@ -163,35 +167,37 @@ STATIC_THREADSAFE pthread_rwlock_t table_lock = PTHREAD_RWLOCK_INITIALIZER; #define UNLOCK_TABLE pthread_rwlock_unlock(&table_lock) #define ACTION_LOCK(idx) table->actions[idx].lock -#define DEBUG_LOCK( \ - idx, info, typ, \ - b) // fprintf(stderr,"%d: %-10s - // %s[%d,%d]%c\n",idx,#info,#typ,ACTION_LOCK(idx).__data.__readers,ACTION_LOCK(idx).__data.__writers,b) -#define XLOCK_ACTION(idx, info, typ) \ - do { \ - DEBUG_LOCK(idx, info, typ, '?'); \ - pthread_rwlock_##typ##lock(&ACTION_LOCK(idx)); \ - DEBUG_LOCK(idx, info, typ, '!'); \ +#define DEBUG_LOCK( \ + idx, info, typ, \ + b) // fprintf(stderr,"%d: %-10s %s[%d,%d]%c\n",idx,#info,#typ,ACTION_LOCK(idx).__data.__readers,ACTION_LOCK(idx).__data.__writers,b) +#define XLOCK_ACTION(idx, info, typ) \ + do \ + { \ + DEBUG_LOCK(idx, info, typ, '?'); \ + pthread_rwlock_##typ##lock(&ACTION_LOCK(idx)); \ + DEBUG_LOCK(idx, info, typ, '!'); \ } while (0) #define WRLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, wr) #define RDLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, rd) #define UNLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, un) //#define DEBUG -#define PRINT_ACTIONS \ - { \ - int sti; \ - for (sti = 0; sti < table->num; sti++) { \ - RDLOCK_ACTION(sti, debug); \ - fprintf(stderr, "Action(%d): %s, p=%d(%d), %d, %d\n", sti, \ - table->actions[sti].path, table->actions[sti].phase, \ - table->actions[sti].condition != NULL, \ - table->actions[sti].dispatched, table->actions[sti].done); \ - UNLOCK_ACTION(sti, debug); \ - } \ +#define PRINT_ACTIONS \ + { \ + int sti; \ + for (sti = 0; sti < table->num; sti++) \ + { \ + RDLOCK_ACTION(sti, debug); \ + fprintf(stderr, "Action(%d): %s, p=%d(%d), %d, %d\n", sti, \ + table->actions[sti].path, table->actions[sti].phase, \ + table->actions[sti].condition != NULL, \ + table->actions[sti].dispatched, table->actions[sti].done); \ + UNLOCK_ACTION(sti, debug); \ + } \ } //" -STATIC_ROUTINE char *Server(char *out, char *srv) { +STATIC_ROUTINE char *Server(char *out, char *srv) +{ int i; for (i = 0; i < 32; i++) out[i] = srv[i] == ' ' ? 0 : srv[i]; @@ -199,13 +205,16 @@ STATIC_ROUTINE char *Server(char *out, char *srv) { return out; } -void SendMonitor(int mode, int idx) { - if (MonitorOn) { +void SendMonitor(int mode, int idx) +{ + if (MonitorOn) + { char tree[13]; char *cptr; int i; RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault for (i = 0, cptr = table->tree; i < 12; i++) if (cptr[i] == (char)32) break; @@ -228,31 +237,36 @@ void SendMonitor(int mode, int idx) { } } -STATIC_ROUTINE void ActionDone(int idx) { +STATIC_ROUTINE void ActionDone(int idx) +{ int i; char logmsg[1024]; - if (idx >= 0) { + if (idx >= 0) + { RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault RDLOCK_ACTION(idx, ad); ActionInfo *actions = table->actions; if (actions[idx].event) MDSEvent(actions[idx].event, sizeof(int), (char *)&table->shot); DoSendMonitor(MonitorDone, idx); - if (Output) { + if (Output) + { char now[32]; Now32(now); - if - IS_OK(actions[idx].status) - sprintf(logmsg, "%s, Action %s completed", now, actions[idx].path); - else { + if (IS_OK(actions[idx].status)) + sprintf(logmsg, "%s, Action %s completed", now, actions[idx].path); + else + { char *emsg = MdsGetMsg(actions[idx].status); sprintf(logmsg, "%s, Action %s failed, %s", now, actions[idx].path, emsg); } (*Output)(logmsg); } - if (!isAbortInProgress()) { + if (!isAbortInProgress()) + { EMPTYXD(xd); char expression[60]; struct descriptor expression_d = {0, DTYPE_T, CLASS_S, 0}; @@ -261,32 +275,37 @@ STATIC_ROUTINE void ActionDone(int idx) { actions[idx].nid, actions[idx].status); TdiExecute(&expression_d, &xd MDS_END_ARG); MdsFree1Dx(&xd, NULL); - for (i = 0; i < actions[idx].num_references; i++) { + for (i = 0; i < actions[idx].num_references; i++) + { int dstat; int doit; int cidx = actions[idx].referenced_by[i]; RDLOCK_ACTION(cidx, adl); - if (!actions[cidx].done) { - if - IS_OK(dstat = TdiGetLong(actions[cidx].condition, &doit)) { - UNLOCK_ACTION(cidx, ad_ftt); - if (doit) - Dispatch(cidx); - else { - WRLOCK_ACTION(cidx, ad_ftte); - actions[cidx].status = ServerNOT_DISPATCHED; - UNLOCK_ACTION(cidx, ad_ftte); - DoActionDone(cidx); - } + if (!actions[cidx].done) + { + if (IS_OK(dstat = TdiGetLong(actions[cidx].condition, &doit))) + { + UNLOCK_ACTION(cidx, ad_ftt); + if (doit) + Dispatch(cidx); + else + { + WRLOCK_ACTION(cidx, ad_ftte); + actions[cidx].status = ServerNOT_DISPATCHED; + UNLOCK_ACTION(cidx, ad_ftte); + DoActionDone(cidx); } - else if (dstat != TdiUNKNOWN_VAR) { + } + else if (dstat != TdiUNKNOWN_VAR) + { UNLOCK_ACTION(cidx, ad_fte); WRLOCK_ACTION(cidx, ad_fte); actions[cidx].status = ServerINVALID_DEPENDENCY; UNLOCK_ACTION(cidx, ad_fte); DoActionDone(cidx); } - } else + } + else UNLOCK_ACTION(cidx, ad_fe); } } @@ -303,16 +322,19 @@ STATIC_ROUTINE void ActionDone(int idx) { CONDITION_SET(&JobWaitC); } -STATIC_ROUTINE void Before(int idx) { +STATIC_ROUTINE void Before(int idx) +{ RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault WRLOCK_ACTION(idx, b); { ActionInfo *actions = table->actions; char logmsg[1024]; actions[idx].doing = 1; DoSendMonitor(MonitorDoing, idx); - if (Output) { + if (Output) + { char server[33]; char now[32]; Now32(now); @@ -333,51 +355,63 @@ STATIC_ROUTINE void Before(int idx) { * UNLOCKs action[i] if FIND_NEXT_ACTION left if locked, i.e. CONDITION was met, * inum -#define FIND_NEXT_ACTION_END(END, info) \ - if (i < END) \ +#define FIND_NEXT_ACTION_END(END, info) \ + if (i < END) \ UNLOCK_ACTION(i, fnae_##info); -STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c) { +STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c) +{ int i; RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault ActionInfo *actions = table->actions; #ifdef DEBUG PRINT_ACTIONS; #endif FIND_NEXT_ACTION(0, table->num, actions[i].phase == phase, sar) - if (i < table->num) { - if (actions[i].condition) { + if (i < table->num) + { + if (actions[i].condition) + { UNLOCK_ACTION(i, sar1); *first_c = i; FIND_NEXT_ACTION(*first_c + 1, table->num, (actions[i].phase != phase) || !actions[i].condition, sar1); *last_c = i; - } else + } + else *first_c = *last_c = table->num; - if (i < table->num && actions[i].phase == phase) { + if (i < table->num && actions[i].phase == phase) + { UNLOCK_ACTION(i, sar2); first_s = i; FIND_NEXT_ACTION(first_s + 1, table->num, actions[i].phase != phase, sar2); last_s = i; - } else + } + else first_s = last_s = table->num; FIND_NEXT_ACTION_END(table->num, sar); - } else { + } + else + { *first_c = first_s = table->num; *last_c = last_s = table->num; } - } else { + } + else + { *first_c = first_s = 0; *last_c = last_s = 0; } @@ -388,14 +422,17 @@ STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c) { #endif } -STATIC_ROUTINE void AbortRange(int s, int e) { +STATIC_ROUTINE void AbortRange(int s, int e) +{ int i; RDLOCK_TABLE; { ActionInfo *actions = table->actions; - for (i = s; i < e; i++) { + for (i = s; i < e; i++) + { RDLOCK_ACTION(i, ar); - if (actions[i].dispatched && !actions[i].done) { + if (actions[i].dispatched && !actions[i].done) + { char server[33]; int one = 1; ServerAbortServer(Server(server, actions[i].server), one); @@ -406,15 +443,18 @@ STATIC_ROUTINE void AbortRange(int s, int e) { UNLOCK_TABLE; } -STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) { - if (first_g == last_s) { +STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) +{ + if (first_g == last_s) + { *last_g = last_s; return; } int i; int group; RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault ActionInfo *actions = table->actions; sync = (sync < 1) ? 1 : sync; RDLOCK_ACTION(first_g, sg); @@ -423,14 +463,17 @@ STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) { FIND_NEXT_ACTION(first_g + 1, last_s, (actions[i].sequence / sync) != group, sg); FIND_NEXT_ACTION_END(last_s, sg); - } else { + } + else + { i = first_g - 1; } UNLOCK_TABLE; *last_g = i; } -STATIC_ROUTINE int NoOutstandingActions(const int s, const int e) { +STATIC_ROUTINE int NoOutstandingActions(const int s, const int e) +{ int i; ActionInfo *actions = table->actions; FIND_NEXT_ACTION(s, e, actions[i].dispatched && !actions[i].done, noa); @@ -441,20 +484,25 @@ STATIC_ROUTINE int NoOutstandingActions(const int s, const int e) { return i >= e; } -STATIC_ROUTINE void RecordStatus(int s, int e) { +STATIC_ROUTINE void RecordStatus(int s, int e) +{ int i; RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault ActionInfo *actions = table->actions; - for (i = s; i < e; i++) { + for (i = s; i < e; i++) + { WRLOCK_ACTION(i, rs); - if (actions[i].done && !actions[i].recorded) { + if (actions[i].done && !actions[i].recorded) + { NCI_ITM setnci[] = {{sizeof(actions[0].status), NciSTATUS, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; setnci[0].pointer = (unsigned char *)&actions[i].status; TreeSetNci(actions[i].nid, setnci); actions[i].recorded = 1; - if (IS_NOT_OK(actions[i].status) && !table->failed_essential) { + if (IS_NOT_OK(actions[i].status) && !table->failed_essential) + { int flags; NCI_ITM getnci[] = {{sizeof(flags), NciGET_FLAGS, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; @@ -470,7 +518,8 @@ STATIC_ROUTINE void RecordStatus(int s, int e) { } STATIC_ROUTINE void WaitForActions(int all, int first_g, int last_g, - int first_c, int last_c) { + int first_c, int last_c) +{ int c_status = C_OK; _CONDITION_LOCK(&JobWaitC); struct timespec tp; @@ -478,7 +527,8 @@ STATIC_ROUTINE void WaitForActions(int all, int first_g, int last_g, int g, c = 1; while ((c_status == ETIMEDOUT || c_status == C_OK) && !isAbortInProgress() && (g = !NoOutstandingActions(first_g, last_g) || - (all && (c = !NoOutstandingActions(first_c, last_c))))) { + (all && (c = !NoOutstandingActions(first_c, last_c))))) + { #ifdef DEBUG fprintf(stderr, "%lu: %d, %d\n", (long unsigned int)tp.tv_sec, g, c); PRINT_ACTIONS; @@ -493,21 +543,26 @@ STATIC_ROUTINE void WaitForActions(int all, int first_g, int last_g, _CONDITION_UNLOCK(&JobWaitC); } -STATIC_ROUTINE char *DetailProc(int full) { +STATIC_ROUTINE char *DetailProc(int full) +{ char *msg; RDLOCK_TABLE; - if (table) { // if no table prevent seg fault + if (table) + { // if no table prevent seg fault msg = NULL; int i; int doing; char msg1[1024]; unsigned int msglen = 4096; ActionInfo *actions = table->actions; - for (doing = 1; doing > (full ? -1 : 0); doing--) { - for (i = 0; i < table->num; i++) { + for (doing = 1; doing > (full ? -1 : 0); doing--) + { + for (i = 0; i < table->num; i++) + { RDLOCK_ACTION(i, dp); if (actions[i].dispatched && !actions[i].done && - ((int)actions[i].doing == doing)) { + ((int)actions[i].doing == doing)) + { char server[33]; sprintf(msg1, " %s %s %s for shot %d\n", actions[i].path, actions[i].doing ? "in progress on" : "dispatched to", @@ -515,31 +570,39 @@ STATIC_ROUTINE char *DetailProc(int full) { UNLOCK_ACTION(i, dp_t); if (!msg) msg = strcpy((char *)malloc(msglen), "\nWaiting on:\n"); - if (msglen < (strlen(msg) + strlen(msg1) + 1)) { + if (msglen < (strlen(msg) + strlen(msg1) + 1)) + { char *oldmsg = msg; msglen += 4096; msg = strcpy((char *)malloc(msglen), oldmsg); free(oldmsg); } strcat(msg, msg1); - } else + } + else UNLOCK_ACTION(i, dp_e); } } - } else { + } + else + { msg = NULL; } UNLOCK_TABLE; return msg; } -static inline void setMonitor(const char *monitor) { +static inline void setMonitor(const char *monitor) +{ MONITOR_QUEUE_LOCK; - if (monitor) { + if (monitor) + { MonitorOn = B_TRUE; free(Monitor); Monitor = strdup(monitor); - } else { + } + else + { free(Monitor); Monitor = NULL; MonitorOn = B_FALSE; @@ -549,7 +612,8 @@ static inline void setMonitor(const char *monitor) { EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, char *phasenam, char noact_in, int sync, - void (*output_rtn)(), const char *monitor) { + void (*output_rtn)(), const char *monitor) +{ WRLOCK_TABLE; { table = vtable; @@ -574,7 +638,8 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, ProgLoc = 6005; int status = TdiExecute(&phase_lookup, &phasenam_d, &phase_d MDS_END_ARG); ProgLoc = 6006; - if (STATUS_OK && (phase > 0)) { + if (STATUS_OK && (phase > 0)) + { setMonitor(monitor); ProgLoc = 6007; SetActionRanges(phase, &first_c, &last_c); @@ -582,7 +647,8 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, ServerSetDetailProc(DetailProc); ProgLoc = 6009; first_g = first_s; - while (!isAbortInProgress() && (first_g < last_s)) { + while (!isAbortInProgress() && (first_g < last_s)) + { ProgLoc = 6010; SetGroup(sync, first_g, &last_g); ProgLoc = 6011; @@ -593,7 +659,8 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, first_g = last_g; } ProgLoc = 6013; - if (setAbortInProgress(0)) { + if (setAbortInProgress(0)) + { AbortRange(first_c, last_c); AbortRange(first_s, last_s); status = ServerABORT; @@ -603,11 +670,14 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, ProgLoc = 6015; setAbortInProgress(1); RDLOCK_TABLE; - if (table) { + if (table) + { ActionInfo *actions = table->actions; - for (i = first_c; i < last_c; i++) { + for (i = first_c; i < last_c; i++) + { RDLOCK_ACTION(i, sdp); - if (!actions[i].done) { + if (!actions[i].done) + { UNLOCK_ACTION(i, sdpw); WRLOCK_ACTION(i, sdpw); actions[i].status = ServerCANT_HAPPEN; @@ -631,25 +701,31 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, return status; } -EXPORT int ServerFailedEssential(void *vtable, int reset) { +EXPORT int ServerFailedEssential(void *vtable, int reset) +{ // returns B_FALSE if no table int failed; WRLOCK_TABLE; - if (vtable) { + if (vtable) + { DispatchTable *table = (DispatchTable *)vtable; failed = table->failed_essential; if (reset) table->failed_essential = B_FALSE; - } else { + } + else + { failed = B_FALSE; } UNLOCK_TABLE; return failed; } -STATIC_ROUTINE void Dispatch(int i) { +STATIC_ROUTINE void Dispatch(int i) +{ RDLOCK_TABLE; - if (table) { + if (table) + { int status; char logmsg[1024]; char server[33]; @@ -659,7 +735,8 @@ STATIC_ROUTINE void Dispatch(int i) { actions[i].done = 0; actions[i].doing = 0; actions[i].dispatched = 0; - if (Output) { + if (Output) + { char now[32]; Now32(now); sprintf(logmsg, "%s, Dispatching node %s to %s", now, actions[i].path, @@ -669,11 +746,14 @@ STATIC_ROUTINE void Dispatch(int i) { // ProgLoc = 7001; DoSendMonitor(MonitorDispatched, i); // ProgLoc = 7002; - if (noact) { + if (noact) + { actions[i].dispatched = 1; actions[i].status = status = 1; DoActionDone(i); - } else { + } + else + { UNLOCK_ACTION(i, d_w); status = ServerDispatchAction( 0, Server(server, actions[i].server), table->tree, table->shot, @@ -681,16 +761,15 @@ STATIC_ROUTINE void Dispatch(int i) { &actions[i].lock, &actions[i].netid, Before); WRLOCK_ACTION(i, d_w); // ProgLoc = 7003; - if - STATUS_OK - actions[i].dispatched = 1; + if (STATUS_OK) + actions[i].dispatched = 1; } // ProgLoc = 7004; - if - STATUS_NOT_OK { - actions[i].status = status; - DoActionDone(i); - } + if (STATUS_NOT_OK) + { + actions[i].status = status; + DoActionDone(i); + } // ProgLoc = 7005; } UNLOCK_ACTION(i, d); @@ -700,11 +779,13 @@ STATIC_ROUTINE void Dispatch(int i) { STATIC_ROUTINE void WakeCompletedActionQueue() { CONDITION_SET(&CompletedC); } -STATIC_ROUTINE void WaitForActionDoneQueue() { +STATIC_ROUTINE void WaitForActionDoneQueue() +{ CONDITION_WAIT_1SEC(&CompletedC); } -STATIC_ROUTINE void QueueCompletedAction(int i) { +STATIC_ROUTINE void QueueCompletedAction(int i) +{ Complete *c = malloc(sizeof(Complete)); c->idx = i; c->next = 0; @@ -718,11 +799,14 @@ STATIC_ROUTINE void QueueCompletedAction(int i) { WakeCompletedActionQueue(); } -STATIC_ROUTINE int DequeueCompletedAction(int *i) { +STATIC_ROUTINE int DequeueCompletedAction(int *i) +{ int doneAction = -1; - while (doneAction == -1) { + while (doneAction == -1) + { pthread_mutex_lock(&completed_queue_mutex); - if (CompletedQueueHead) { + if (CompletedQueueHead) + { Complete *c = CompletedQueueHead; doneAction = CompletedQueueHead->idx; CompletedQueueHead = CompletedQueueHead->next; @@ -730,7 +814,9 @@ STATIC_ROUTINE int DequeueCompletedAction(int *i) { CompletedQueueTail = 0; free(c); pthread_mutex_unlock(&completed_queue_mutex); - } else { + } + else + { CONDITION_RESET(&CompletedC); // reset list state pthread_mutex_unlock(&completed_queue_mutex); WaitForActionDoneQueue(); @@ -744,7 +830,8 @@ STATIC_THREADSAFE Condition ActionDoneRunningC = CONDITION_INITIALIZER; STATIC_ROUTINE void ActionDoneExit() { CONDITION_RESET(&ActionDoneRunningC); } -STATIC_ROUTINE void ActionDoneThread() { +STATIC_ROUTINE void ActionDoneThread() +{ int i; pthread_cleanup_push(ActionDoneExit, 0); CONDITION_SET(&ActionDoneRunningC); @@ -754,24 +841,27 @@ STATIC_ROUTINE void ActionDoneThread() { pthread_exit(NULL); } -STATIC_ROUTINE void DoActionDone(int i) { +STATIC_ROUTINE void DoActionDone(int i) +{ INIT_STATUS; pthread_t thread; QueueCompletedAction(i); /***** must be done before starting thread ****/ CONDITION_START_THREAD(&ActionDoneRunningC, thread, , ActionDoneThread, NULL); - if - STATUS_NOT_OK perror("DoActionDone: pthread creation failed"); + if (STATUS_NOT_OK) + perror("DoActionDone: pthread creation failed"); } STATIC_THREADSAFE Condition SendMonitorRunningC = CONDITION_INITIALIZER; STATIC_ROUTINE void WakeSendMonitorQueue() { CONDITION_SET(&SendMonitorC); } -STATIC_ROUTINE void WaitForSendMonitorQueue() { +STATIC_ROUTINE void WaitForSendMonitorQueue() +{ CONDITION_WAIT_1SEC(&SendMonitorC); } -STATIC_ROUTINE void QueueSendMonitor(int mode, int i) { +STATIC_ROUTINE void QueueSendMonitor(int mode, int i) +{ SendMonitorInfo *c = malloc(sizeof(SendMonitorInfo)); c->idx = i; c->mode = mode; @@ -786,14 +876,17 @@ STATIC_ROUTINE void QueueSendMonitor(int mode, int i) { WakeSendMonitorQueue(); } -STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) { +STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) +{ int idx; int mode; - do { + do + { int release; MONITOR_QUEUE_LOCK; release = 1; - if (SendMonitorQueueHead) { + if (SendMonitorQueueHead) + { SendMonitorInfo *c = SendMonitorQueueHead; idx = SendMonitorQueueHead->idx; mode = SendMonitorQueueHead->mode; @@ -801,7 +894,9 @@ STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) { if (!SendMonitorQueueHead) SendMonitorQueueTail = NULL; free(c); - } else { + } + else + { pthread_mutex_unlock(&send_monitor_queue_mutex); release = 0; idx = -1; @@ -817,7 +912,8 @@ STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) { STATIC_ROUTINE void SendMonitorExit() { CONDITION_RESET(&SendMonitorRunningC); } -STATIC_ROUTINE void SendMonitorThread() { +STATIC_ROUTINE void SendMonitorThread() +{ int i; int mode; pthread_cleanup_push(SendMonitorExit, NULL); @@ -828,33 +924,38 @@ STATIC_ROUTINE void SendMonitorThread() { pthread_exit(NULL); } -STATIC_ROUTINE void DoSendMonitor(int mode, int idx) { +STATIC_ROUTINE void DoSendMonitor(int mode, int idx) +{ INIT_STATUS; pthread_t thread; QueueSendMonitor(mode, idx); /***** must be done before starting thread ****/ CONDITION_START_THREAD(&SendMonitorRunningC, thread, , SendMonitorThread, NULL); - if - STATUS_NOT_OK perror("DoSendMonitor: pthread creation failed"); + if (STATUS_NOT_OK) + perror("DoSendMonitor: pthread creation failed"); } -void serverDisarmDispatchTable(void *vtable) { +void serverDisarmDispatchTable(void *vtable) +{ WRLOCK_TABLE; if (table == vtable) table = NULL; // disarm table UNLOCK_TABLE; } -static inline void serverFreeDispatchTable(void *vtable) { +static inline void serverFreeDispatchTable(void *vtable) +{ ActionInfo *actions = ((DispatchTable *)vtable)->actions; int num_actions = ((DispatchTable *)vtable)->num; int i; - for (i = 0; i < num_actions; i++) { + for (i = 0; i < num_actions; i++) + { free(actions[i].referenced_by); if (actions[i].path) TreeFree(actions[i].path); free(actions[i].event); - if (actions[i].condition) { + if (actions[i].condition) + { MdsFree1Dx((struct descriptor_xd *)actions[i].condition, 0); free(actions[i].condition); } @@ -862,9 +963,11 @@ static inline void serverFreeDispatchTable(void *vtable) { free(vtable); } -EXPORT int ServerFreeDispatchTable(void *vtable) { +EXPORT int ServerFreeDispatchTable(void *vtable) +{ // should be called during CloseTopTree - if (vtable) { + if (vtable) + { serverDisarmDispatchTable(vtable); serverFreeDispatchTable(vtable); } diff --git a/servershr/ServerFindServers.c b/servershr/ServerFindServers.c index 81436f591d..af72e6598c 100644 --- a/servershr/ServerFindServers.c +++ b/servershr/ServerFindServers.c @@ -60,33 +60,41 @@ int SERVER$FIND_SERVERS(int *ctx, struct dsc$descriptor *server ) #include #include -EXPORT char *ServerFindServers(void **ctx, char *wild_match) { +EXPORT char *ServerFindServers(void **ctx, char *wild_match) +{ char *ans = NULL; DIR *dir = (DIR *)*ctx; - if (dir == 0) { + if (dir == 0) + { char *serverdir = getenv("MDSIP_SERVER_LOGDIR"); if (serverdir) *ctx = dir = opendir(serverdir); } - if (dir) { - for (;;) { + if (dir) + { + for (;;) + { struct dirent *entry = readdir(dir); - if (entry) { + if (entry) + { char *ans_c = strcpy(malloc(strlen(entry->d_name) + 1), entry->d_name); if ((strcmp(ans_c, ".") == 0) || (strcmp(ans_c, "..") == 0)) continue; - else { + else + { struct descriptor ans_d = {strlen(ans_c), DTYPE_T, CLASS_S, ans_c}; struct descriptor wild_d = {strlen(wild_match), DTYPE_T, CLASS_S, wild_match}; - if - IS_OK(StrMatchWild(&ans_d, &wild_d)) { - ans = ans_c; - break; - } + if (IS_OK(StrMatchWild(&ans_d, &wild_d))) + { + ans = ans_c; + break; + } } free(ans_c); - } else { + } + else + { closedir(dir); *ctx = 0; break; diff --git a/servershr/ServerGetInfo.c b/servershr/ServerGetInfo.c index 4ca61a606b..7648f881e6 100644 --- a/servershr/ServerGetInfo.c +++ b/servershr/ServerGetInfo.c @@ -65,37 +65,43 @@ doing. extern int ServerConnect(); extern int GetAnswerInfoTS(); -EXPORT char *ServerGetInfo(int full __attribute__((unused)), char *server) { +EXPORT char *ServerGetInfo(int full __attribute__((unused)), char *server) +{ char *cmd = "MdsServerShr->ServerInfo:dsc()"; char *ans; char *ansret; short len = 0; void *mem = 0; SOCKET sock = ServerConnect(server); - if (sock != INVALID_SOCKET) { + if (sock != INVALID_SOCKET) + { int status = SendArg(sock, (unsigned char)0, (char)DTYPE_CSTRING, (unsigned char)1, (short)strlen(cmd), 0, 0, cmd); - if - STATUS_OK { - char dtype; - char ndims; - int dims[8]; - int numbytes; - char *reply; - status = GetAnswerInfoTS(sock, &dtype, &len, &ndims, dims, &numbytes, - (void **)&reply, &mem, 10); - if (STATUS_OK && (dtype == DTYPE_CSTRING)) - ans = reply; - else { - ans = "Invalid response from server"; - len = strlen(ans); - } + if (STATUS_OK) + { + char dtype; + char ndims; + int dims[8]; + int numbytes; + char *reply; + status = GetAnswerInfoTS(sock, &dtype, &len, &ndims, dims, &numbytes, + (void **)&reply, &mem, 10); + if (STATUS_OK && (dtype == DTYPE_CSTRING)) + ans = reply; + else + { + ans = "Invalid response from server"; + len = strlen(ans); } - else { + } + else + { ans = "No response from server"; len = strlen(ans); } - } else { + } + else + { ans = "Error connecting to server"; len = strlen(ans); } diff --git a/servershr/ServerMonitorCheckin.c b/servershr/ServerMonitorCheckin.c index dd6b2a608c..e941714bf9 100644 --- a/servershr/ServerMonitorCheckin.c +++ b/servershr/ServerMonitorCheckin.c @@ -64,30 +64,36 @@ astparam, void (*link_down)()) static void (*appAst)() = 0; static void eventAst(void *astprm, int msglen __attribute__((unused)), - char *msg) { + char *msg) +{ (*appAst)(astprm, msg); } -EXPORT int ServerMonitorCheckin(char *server, void (*ast)(), void *astprm) { +EXPORT int ServerMonitorCheckin(char *server, void (*ast)(), void *astprm) +{ static int usingEvents = -1; const char *event_str = "event:"; const unsigned int event_len = strlen(event_str); - if (usingEvents == -1) { + if (usingEvents == -1) + { char *svr_env = getenv(server); if (!svr_env) svr_env = server; if ((strlen(svr_env) > event_len) && - (strncasecmp(svr_env, event_str, event_len) == 0)) { + (strncasecmp(svr_env, event_str, event_len) == 0)) + { int evid; appAst = ast; usingEvents = MDSEventAst(strdup(svr_env + event_len), eventAst, astprm, &evid) & 1; - } else + } + else usingEvents = B_FALSE; } if (usingEvents) return MDSplusSUCCESS; - else { + else + { struct descrip p1, p2, p3, p4, p5, p6, p7, p8; char *cstring = ""; int zero = 0; diff --git a/servershr/ServerQAction.c b/servershr/ServerQAction.c index 5c9fc1db11..4370095749 100644 --- a/servershr/ServerQAction.c +++ b/servershr/ServerQAction.c @@ -51,13 +51,15 @@ typedef int SOCKET; #endif #include -typedef struct _MonitorList { +typedef struct _MonitorList +{ uint32_t addr; uint16_t port; struct _MonitorList *next; } MonitorList; -typedef struct _ClientList { +typedef struct _ClientList +{ uint32_t addr; uint16_t port; SOCKET sock; @@ -103,8 +105,8 @@ static int RemoveLast(); static void LockQueue(); static void UnlockQueue(); -#define QUEUE_LOCK \ - LockQueue(); \ +#define QUEUE_LOCK \ + LockQueue(); \ pthread_cleanup_push(UnlockQueue, NULL); #define QUEUE_UNLOCK pthread_cleanup_pop(1); @@ -123,7 +125,8 @@ static int LeftWorkerLoop = 0; static int CondWStat = 0; int ProgLoc = 0; -EXPORT struct descriptor *ServerInfo() { +EXPORT struct descriptor *ServerInfo() +{ static DESCRIPTOR(nothing, ""); static EMPTYXD(xd); int status = ShowCurrentJob(&xd); @@ -133,7 +136,8 @@ EXPORT struct descriptor *ServerInfo() { return (struct descriptor *)¬hing; } -EXPORT int ServerDebug(int setting) { +EXPORT int ServerDebug(int setting) +{ int old = Debug; Debug = setting; return old; @@ -141,22 +145,28 @@ EXPORT int ServerDebug(int setting) { // main EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, int *jobid, void *p1, void *p2, void *p3, void *p4, - void *p5, void *p6, void *p7, void *p8) { + void *p5, void *p6, void *p7, void *p8) +{ int status = ServerINVALID_ACTION_OPERATION; - switch (*op) { - case SrvRemoveLast: { + switch (*op) + { + case SrvRemoveLast: + { status = RemoveLast(); break; } - case SrvAbort: { + case SrvAbort: + { KillWorker(); ServerSetDetailProc(0); QUEUE_LOCK; AbortJob(CurrentJob); CurrentJob = 0; - if (*(int *)p1) { + if (*(int *)p1) + { SrvJob *next, *job = JobQueue; - while (job) { + while (job) + { next = job->h.next; AbortJob(job); job = next; @@ -167,7 +177,8 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, QUEUE_UNLOCK; break; } - case SrvAction: { + case SrvAction: + { SrvActionJob job; job.h.addr = addr ? *addr : MdsGetClientAddr(); job.h.port = *port; @@ -184,7 +195,8 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, status = DoSrvAction((SrvJob *)&job); break; } - case SrvClose: { + case SrvClose: + { SrvCloseJob job; job.h.addr = MdsGetClientAddr(); job.h.port = *port; @@ -198,7 +210,8 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, status = DoSrvClose((SrvJob *)&job); break; } - case SrvCreatePulse: { + case SrvCreatePulse: + { SrvCreatePulseJob job; job.h.addr = MdsGetClientAddr(); job.h.port = *port; @@ -214,12 +227,14 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, status = DoSrvCreatePulse((SrvJob *)&job); break; } - case SrvSetLogging: { + case SrvSetLogging: + { Logging = *(int *)p1; status = MDSplusSUCCESS; break; } - case SrvCommand: { + case SrvCommand: + { SrvCommandJob job; job.h.addr = MdsGetClientAddr(); job.h.port = *port; @@ -235,7 +250,8 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, status = DoSrvCommand((SrvJob *)&job); break; } - case SrvMonitor: { + case SrvMonitor: + { SrvMonitorJob job; job.h.addr = MdsGetClientAddr(); job.h.port = *port; @@ -257,11 +273,13 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, status = MDSplusERROR; break; } - case SrvShow: { + case SrvShow: + { status = ShowCurrentJob((struct descriptor_xd *)p1); break; } - case SrvStop: { + case SrvStop: + { char now[32]; Now32(now); printf("%s, Server stop requested\n", now); @@ -272,14 +290,17 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, return status; } // main -static void AbortJob(SrvJob *job) { - if (job) { +static void AbortJob(SrvJob *job) +{ + if (job) + { SendReply(job, SrvJobFINISHED, ServerABORT, 0, 0); FreeJob(job); } } // main -static int QJob(SrvJob *job) { +static int QJob(SrvJob *job) +{ SrvJob *qjob = (SrvJob *)memcpy(malloc(job->h.length), job, job->h.length); QUEUE_LOCK; if (JobQueueNext) @@ -294,8 +315,10 @@ static int QJob(SrvJob *job) { return StartWorker(); } // main -static void LogPrefix(char *ans_c) { - if (ans_c) { +static void LogPrefix(char *ans_c) +{ + if (ans_c) + { char hname[512]; char *port = MdsGetServerPortname(); gethostname(hname, 512); @@ -303,7 +326,8 @@ static void LogPrefix(char *ans_c) { Now32(now); sprintf(ans_c, "%s, %s:%s, %s, ", now, hname, port ? port : "?", Logging == 0 ? "logging disabled" : "logging enabled"); - if (Debug) { + if (Debug) + { sprintf(ans_c + strlen(ans_c), "\nDebug info: QueueLocked = %d ProgLoc = %d WorkerDied = %d" "\n LeftWorkerLoop = %d CondWStat = %d\n", @@ -312,26 +336,33 @@ static void LogPrefix(char *ans_c) { } } // main -static int ShowCurrentJob(struct descriptor_xd *ans) { +static int ShowCurrentJob(struct descriptor_xd *ans) +{ char *ans_c; struct descriptor ans_d = {0, DTYPE_T, CLASS_S, 0}; QUEUE_LOCK; char *job_text = current_job_text; - if (job_text == 0) { + if (job_text == 0) + { ans_c = malloc(1024); LogPrefix(ans_c); strcat(ans_c, "Inactive"); - } else { + } + else + { char *(*detail_proc)(int); char *detail; if (((detail_proc = ServerGetDetailProc()) != 0) && - ((detail = (*detail_proc)(1)) != 0)) { + ((detail = (*detail_proc)(1)) != 0)) + { ans_c = malloc(1024 + strlen(job_text) + strlen(detail)); LogPrefix(ans_c); strcat(ans_c, job_text); strcat(ans_c, detail); free(detail); - } else { + } + else + { ans_c = malloc(1024 + strlen(job_text)); LogPrefix(ans_c); strcat(ans_c, job_text); @@ -345,12 +376,14 @@ static int ShowCurrentJob(struct descriptor_xd *ans) { return MDSplusSUCCESS; } // main -static int RemoveLast() { +static int RemoveLast() +{ int status; SrvJob *job; QUEUE_LOCK; job = JobQueueNext; - if (job) { + if (job) + { JobQueueNext = job->h.previous; if (JobQueueNext) JobQueueNext->h.next = 0; @@ -359,19 +392,23 @@ static int RemoveLast() { FreeJob(job); printf("Removed pending action"); status = MDSplusSUCCESS; - } else + } + else status = MDSplusERROR; QUEUE_UNLOCK; return status; } // thread -static SrvJob *NextJob(int wait) { +static SrvJob *NextJob(int wait) +{ SrvJob *job; // int done = 0; - while (1) { + while (1) + { QUEUE_LOCK; job = JobQueue; - if (job) { + if (job) + { JobQueue = job->h.next; if (JobQueue) ((SrvJob *)JobQueue)->h.previous = 0; @@ -387,8 +424,10 @@ static SrvJob *NextJob(int wait) { return job; } // both -static void FreeJob(SrvJob *job) { - switch (job->h.op) { +static void FreeJob(SrvJob *job) +{ + switch (job->h.op) + { case SrvAction: free(((SrvActionJob *)job)->tree); break; @@ -406,32 +445,37 @@ static void FreeJob(SrvJob *job) { free(job); } // thread -static void SetCurrentJob(SrvJob *job) { +static void SetCurrentJob(SrvJob *job) +{ QUEUE_LOCK; CurrentJob = job; QUEUE_UNLOCK; } // thread -static inline void LockQueue() { +static inline void LockQueue() +{ _CONDITION_LOCK(&JobQueueCond); QueueLocked = 1; } // thread -static inline void UnlockQueue() { +static inline void UnlockQueue() +{ QueueLocked = 0; _CONDITION_UNLOCK(&JobQueueCond); } // main static int doingNid; static pthread_rwlock_t doing_nid_rwlock = PTHREAD_RWLOCK_INITIALIZER; -EXPORT int GetDoingNid() { +EXPORT int GetDoingNid() +{ pthread_rwlock_rdlock(&doing_nid_rwlock); int nid = doingNid; pthread_rwlock_unlock(&doing_nid_rwlock); return nid; } // thread -static int DoSrvAction(SrvJob *job_in) { +static int DoSrvAction(SrvJob *job_in) +{ INIT_STATUS_ERROR; SrvActionJob *job = (SrvActionJob *)job_in; char *job_text, *old_job_text; @@ -440,53 +484,54 @@ static int DoSrvAction(SrvJob *job_in) { current_job_text = job_text; void *dbid = NULL; status = _TreeNewDbid(&dbid); - if - STATUS_NOT_OK goto end; + if (STATUS_NOT_OK) + goto end; void *pc = TreeCtxPush(&dbid); status = TreeOpen(job->tree, job->shot, 0); - if - STATUS_OK { - int retstatus; - DESCRIPTOR_NID(nid_dsc, 0); - DESCRIPTOR_LONG(ans_dsc, 0); - struct descriptor_d fullpath = {0, DTYPE_T, CLASS_D, 0}; - DESCRIPTOR(fullpath_d, "FULLPATH"); - DESCRIPTOR(nullstr, "\0"); - DESCRIPTOR_NID(niddsc, 0); - niddsc.pointer = (char *)&job->nid; - pthread_rwlock_wrlock(&doing_nid_rwlock); - doingNid = job->nid; - pthread_rwlock_unlock(&doing_nid_rwlock); - status = TdiGetNci(&niddsc, &fullpath_d, &fullpath MDS_END_ARG); - StrAppend(&fullpath, (struct descriptor *)&nullstr); - job_text = malloc(fullpath.length + 1024); - sprintf(job_text, "Doing %s in %s shot %d", fullpath.pointer, job->tree, - job->shot); - old_job_text = current_job_text; - current_job_text = job_text; - free(old_job_text); - StrFree1Dx(&fullpath); - nid_dsc.pointer = (char *)&job->nid; - ans_dsc.pointer = (char *)&retstatus; - TreeSetDefaultNid(0); - if (Logging) { - char now[32]; - Now32(now); - printf("%s, %s\n", now, current_job_text); - fflush(stdout); - } - status = TdiDoTask(&nid_dsc, &ans_dsc MDS_END_ARG); - if (Logging) { - char now[32]; - Now32(now); - memcpy(current_job_text, "Done ", 5); - printf("%s, %s\n", now, current_job_text); - fflush(stdout); - } - if - STATUS_OK - status = retstatus; + if (STATUS_OK) + { + int retstatus; + DESCRIPTOR_NID(nid_dsc, 0); + DESCRIPTOR_LONG(ans_dsc, 0); + struct descriptor_d fullpath = {0, DTYPE_T, CLASS_D, 0}; + DESCRIPTOR(fullpath_d, "FULLPATH"); + DESCRIPTOR(nullstr, "\0"); + DESCRIPTOR_NID(niddsc, 0); + niddsc.pointer = (char *)&job->nid; + pthread_rwlock_wrlock(&doing_nid_rwlock); + doingNid = job->nid; + pthread_rwlock_unlock(&doing_nid_rwlock); + status = TdiGetNci(&niddsc, &fullpath_d, &fullpath MDS_END_ARG); + StrAppend(&fullpath, (struct descriptor *)&nullstr); + job_text = malloc(fullpath.length + 1024); + sprintf(job_text, "Doing %s in %s shot %d", fullpath.pointer, job->tree, + job->shot); + old_job_text = current_job_text; + current_job_text = job_text; + free(old_job_text); + StrFree1Dx(&fullpath); + nid_dsc.pointer = (char *)&job->nid; + ans_dsc.pointer = (char *)&retstatus; + TreeSetDefaultNid(0); + if (Logging) + { + char now[32]; + Now32(now); + printf("%s, %s\n", now, current_job_text); + fflush(stdout); } + status = TdiDoTask(&nid_dsc, &ans_dsc MDS_END_ARG); + if (Logging) + { + char now[32]; + Now32(now); + memcpy(current_job_text, "Done ", 5); + printf("%s, %s\n", now, current_job_text); + fflush(stdout); + } + if (STATUS_OK) + status = retstatus; + } TreeCtxPop(pc); end:; TreeFreeDbid(dbid); @@ -495,19 +540,23 @@ end:; return status; } // thread -static int DoSrvClose(SrvJob *job_in) { +static int DoSrvClose(SrvJob *job_in) +{ INIT_STATUS_ERROR; char *job_text = strcpy((char *)malloc(32), "Closing trees"); current_job_text = job_text; - while - IS_OK(status = TreeClose(0, 0)); + do + { + status = TreeClose(0, 0); + } while (STATUS_OK); status = (status == TreeNOT_OPEN) ? TreeSUCCESS : status; if (job_in->h.addr) SendReply(job_in, SrvJobFINISHED, status, 0, 0); return status; } // thread -static int DoSrvCreatePulse(SrvJob *job_in) { +static int DoSrvCreatePulse(SrvJob *job_in) +{ INIT_STATUS_ERROR; SrvCreatePulseJob *job = (SrvCreatePulseJob *)job_in; char *job_text = malloc(100); @@ -520,7 +569,8 @@ static int DoSrvCreatePulse(SrvJob *job_in) { return status; } // thread -static int DoSrvCommand(SrvJob *job_in) { +static int DoSrvCommand(SrvJob *job_in) +{ INIT_STATUS_ERROR; SrvCommandJob *job = (SrvCommandJob *)job_in; char *set_table = strcpy(malloc(strlen(job->table) + 24), "set command "); @@ -538,12 +588,12 @@ static int DoSrvCommand(SrvJob *job_in) { ProgLoc = 65; free(set_table); ProgLoc = 66; - if - STATUS_OK { - ProgLoc = 67; - status = mdsdcl_do_command(job->command); - // ProgLoc = 68; - } + if (STATUS_OK) + { + ProgLoc = 67; + status = mdsdcl_do_command(job->command); + // ProgLoc = 68; + } ProgLoc = 69; if (job_in->h.addr) SendReply(job_in, SrvJobFINISHED, status, 0, 0); @@ -551,7 +601,8 @@ static int DoSrvCommand(SrvJob *job_in) { return status; } // thread -static int AddMonitorClient(SrvJob *job) { +static int AddMonitorClient(SrvJob *job) +{ MonitorList *mlist; for (mlist = Monitors; mlist; mlist = mlist->next) if (job->h.addr == mlist->addr && job->h.port == mlist->port) @@ -564,7 +615,8 @@ static int AddMonitorClient(SrvJob *job) { return MDSplusSUCCESS; } // thread -static void SendToMonitor(MonitorList *m, MonitorList *prev, SrvJob *job_in) { +static void SendToMonitor(MonitorList *m, MonitorList *prev, SrvJob *job_in) +{ INIT_STATUS_ERROR; SrvMonitorJob *job = (SrvMonitorJob *)job_in; char *msg = NULL; // char msg[1024]; @@ -576,28 +628,29 @@ static void SendToMonitor(MonitorList *m, MonitorList *prev, SrvJob *job_in) { DESCRIPTOR_NID(niddsc, 0); char *status_text = MdsGetMsg(job->status); status = TreeOpen(job->tree, job->shot, 0); - if - STATUS_NOT_OK // try to open model instead - status = TreeOpen(job->tree, -1, 0); + if (STATUS_NOT_OK) + // try to open model instead + status = TreeOpen(job->tree, -1, 0); char now[32]; Now32(now); - if - STATUS_OK { - niddsc.pointer = (char *)&job->nid; - status = TdiGetNci(&niddsc, &fullpath_d, &fullpath MDS_END_ARG); - StrAppend(&fullpath, (struct descriptor *)&nullstr); - msg = malloc(fullpath.length + 1024 + strlen(status_text)); - if (job->server && *job->server) - sprintf(msg, "%s %d %d %d %d %d %s %d %s %s; %s", job->tree, job->shot, - job->phase, job->nid, job->on, job->mode, job->server, - job->status, fullpath.pointer, now, status_text); - else - sprintf(msg, "%s %d %d %d %d %d unknown %d %s %s; %s", job->tree, - job->shot, job->phase, job->nid, job->on, job->mode, - job->status, fullpath.pointer, now, status_text); - StrFree1Dx(&fullpath); - } - else { + if (STATUS_OK) + { + niddsc.pointer = (char *)&job->nid; + status = TdiGetNci(&niddsc, &fullpath_d, &fullpath MDS_END_ARG); + StrAppend(&fullpath, (struct descriptor *)&nullstr); + msg = malloc(fullpath.length + 1024 + strlen(status_text)); + if (job->server && *job->server) + sprintf(msg, "%s %d %d %d %d %d %s %d %s %s; %s", job->tree, job->shot, + job->phase, job->nid, job->on, job->mode, job->server, + job->status, fullpath.pointer, now, status_text); + else + sprintf(msg, "%s %d %d %d %d %d unknown %d %s %s; %s", job->tree, + job->shot, job->phase, job->nid, job->on, job->mode, + job->status, fullpath.pointer, now, status_text); + StrFree1Dx(&fullpath); + } + else + { msg = malloc(1024 + strlen(status_text)); sprintf(msg, "%s %d %d %d %d %d %s %d unknown %s; %s", job->tree, job->shot, job->phase, job->nid, job->on, job->mode, job->server, job->status, @@ -605,21 +658,23 @@ static void SendToMonitor(MonitorList *m, MonitorList *prev, SrvJob *job_in) { } status = SendReply(job_in, SrvJobFINISHED, 1, strlen(msg), msg); free(msg); - if - STATUS_NOT_OK { - if (prev) - prev->next = m->next; - else - Monitors = m->next; - free(m); - } + if (STATUS_NOT_OK) + { + if (prev) + prev->next = m->next; + else + Monitors = m->next; + free(m); + } } // thread -static int SendToMonitors(SrvJob *job) { +static int SendToMonitors(SrvJob *job) +{ MonitorList *m, *prev, *next; uint32_t prev_addr = job->h.addr; uint16_t prev_port = job->h.port; - for (prev = NULL, m = Monitors; m; m = next) { + for (prev = NULL, m = Monitors; m; m = next) + { job->h.addr = m->addr; job->h.port = m->port; next = m->next; @@ -630,7 +685,8 @@ static int SendToMonitors(SrvJob *job) { return MDSplusSUCCESS; } // thread -static void DoSrvMonitor(SrvJob *job_in) { +static void DoSrvMonitor(SrvJob *job_in) +{ INIT_STATUS_ERROR; SrvMonitorJob *job = (SrvMonitorJob *)job_in; status = (job->mode == MonitorCheckin) ? AddMonitorClient(job_in) @@ -640,7 +696,8 @@ static void DoSrvMonitor(SrvJob *job_in) { status, 0, 0); } // thread -static void WorkerExit(void *arg __attribute__((unused))) { +static void WorkerExit(void *arg __attribute__((unused))) +{ if (QueueLocked) UnlockQueue(); CONDITION_RESET(&WorkerRunning); @@ -648,12 +705,14 @@ static void WorkerExit(void *arg __attribute__((unused))) { fprintf(stderr, "Worker thread exitted\n"); } // thread -static void WorkerThread(void *arg __attribute__((unused))) { +static void WorkerThread(void *arg __attribute__((unused))) +{ SrvJob *job; pthread_cleanup_push(WorkerExit, NULL); ProgLoc = 1; CONDITION_SET(&WorkerRunning); - while ((job = NextJob(1))) { + while ((job = NextJob(1))) + { if (Debug) fprintf(stderr, "job started.\n"); char *save_text; @@ -662,12 +721,14 @@ static void WorkerThread(void *arg __attribute__((unused))) { ProgLoc = 3; SetCurrentJob(job); ProgLoc = 4; - if ((job->h.flags & SrvJobBEFORE_NOTIFY) != 0) { + if ((job->h.flags & SrvJobBEFORE_NOTIFY) != 0) + { ProgLoc = 5; SendReply(job, SrvJobSTARTING, 1, 0, 0); } ProgLoc = 6; - switch (job->h.op) { + switch (job->h.op) + { case SrvAction: DoSrvAction(job); break; @@ -701,17 +762,20 @@ static void WorkerThread(void *arg __attribute__((unused))) { pthread_exit(NULL); } // main -static int StartWorker() { +static int StartWorker() +{ INIT_STATUS; CONDITION_START_THREAD(&WorkerRunning, Worker, / 4, WorkerThread, NULL); - if - STATUS_NOT_OK exit(-1); + if (STATUS_NOT_OK) + exit(-1); return status; } // main -static void KillWorker() { +static void KillWorker() +{ _CONDITION_LOCK(&WorkerRunning); - if (WorkerRunning.value) { + if (WorkerRunning.value) + { pthread_cancel(Worker); _CONDITION_WAIT_RESET(&WorkerRunning); } @@ -719,7 +783,8 @@ static void KillWorker() { } // both -static SOCKET AttachPort(uint32_t addr, uint16_t port) { +static SOCKET AttachPort(uint32_t addr, uint16_t port) +{ SOCKET sock; struct sockaddr_in sin; ClientList *l, *new; @@ -730,8 +795,10 @@ static SOCKET AttachPort(uint32_t addr, uint16_t port) { sin.sin_family = AF_INET; *(uint32_t *)(&sin.sin_addr) = addr; sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock != INVALID_SOCKET) { - if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) { + if (sock != INVALID_SOCKET) + { + if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) + { shutdown(sock, 2); close(sock); uint8_t *ip = (uint8_t *)&addr; @@ -753,10 +820,13 @@ static SOCKET AttachPort(uint32_t addr, uint16_t port) { return sock; } // both -static void RemoveClient(SrvJob *job) { +static void RemoveClient(SrvJob *job) +{ ClientList *l, *prev; - for (prev = 0, l = Clients; l;) { - if (job->h.addr == l->addr && job->h.port == l->port) { + for (prev = 0, l = Clients; l;) + { + if (job->h.addr == l->addr && job->h.port == l->port) + { shutdown(l->sock, 2); close(l->sock); if (prev) @@ -765,7 +835,9 @@ static void RemoveClient(SrvJob *job) { Clients = l->next; free(l); break; - } else { + } + else + { prev = l; l = l->next; } @@ -773,11 +845,15 @@ static void RemoveClient(SrvJob *job) { } #ifndef _WIN32 -static void reset_sigpipe_handler() { signal(SIGPIPE, SIG_DFL); } +static void reset_sigpipe_handler() +{ + signal(SIGPIPE, SIG_DFL); +} #endif // both static int SendReply(SrvJob *job, int replyType, int status_in, int length, - char *msg) { + char *msg) +{ int status; #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); @@ -787,7 +863,8 @@ static int SendReply(SrvJob *job, int replyType, int status_in, int length, SOCKET sock; long msg_len = msg ? (long)strlen(msg) : 0; int try_again = TRUE; - do { + do + { errno = 0; sock = AttachPort(job->h.addr, (uint16_t)job->h.port); if (sock == INVALID_SOCKET) @@ -797,26 +874,29 @@ static int SendReply(SrvJob *job, int replyType, int status_in, int length, memset(reply, 0, 60); sprintf(reply, "%d %d %d %ld", job->h.jobid, replyType, status_in, msg_len); bytes = send(sock, reply, 60, MSG_DONTWAIT); - if (bytes == 60) { + if (bytes == 60) + { bytes = send(sock, msg, length, MSG_DONTWAIT); - if (bytes == length) { + if (bytes == length) + { status = MDSplusSUCCESS; break; } } - if - STATUS_NOT_OK { - try_again = errno == EPIPE; - if (Debug) { - uint8_t *ip = (uint8_t *)&job->h.addr; - char now[32]; - Now32(now); - fprintf(stderr, "%s, Dropped connection to %u.%u.%u.%u:%u", now, - ip[0], ip[1], ip[2], ip[3], job->h.port); - perror(" "); - } - RemoveClient(job); + if (STATUS_NOT_OK) + { + try_again = errno == EPIPE; + if (Debug) + { + uint8_t *ip = (uint8_t *)&job->h.addr; + char now[32]; + Now32(now); + fprintf(stderr, "%s, Dropped connection to %u.%u.%u.%u:%u", now, + ip[0], ip[1], ip[2], ip[3], job->h.port); + perror(" "); } + RemoveClient(job); + } } while (try_again--); #ifndef _WIN32 pthread_cleanup_pop(1); diff --git a/servershr/ServerSendMessage.c b/servershr/ServerSendMessage.c index 1703a2bb92..b3ea5393a6 100644 --- a/servershr/ServerSendMessage.c +++ b/servershr/ServerSendMessage.c @@ -73,10 +73,11 @@ int ServerSendMessage(); #include "servershrp.h" #ifdef _WIN32 #define random rand -#define SOCKERROR(...) \ - do { \ - errno = WSAGetLastError(); \ - fprintf(stderr, __VA_ARGS__); \ +#define SOCKERROR(...) \ + do \ + { \ + errno = WSAGetLastError(); \ + fprintf(stderr, __VA_ARGS__); \ } while (0) #else #define SOCKERROR(...) fprintf(stderr, __VA_ARGS__) @@ -86,13 +87,14 @@ int ServerSendMessage(); #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #endif #define IP(addr) ((uint8_t *)&addr) -#define ADDR2IP(a) IP(a)[0], IP(a)[1], IP(a)[2], IP(a)[3] +#define ADDR2IP(a) IP(a) \ + [0], IP(a)[1], IP(a)[2], IP(a)[3] extern short ArgLen(); @@ -104,7 +106,8 @@ extern int GetAnswerInfoTS(); * int value; *} Condition; */ -typedef struct job { +typedef struct job +{ struct job *next; int jobid; int conid; @@ -116,17 +119,18 @@ typedef struct job { void (*before_ast)(); } Job; pthread_mutex_t jobs_mutex = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_JOBS \ - pthread_mutex_lock(&jobs_mutex); \ +#define LOCK_JOBS \ + pthread_mutex_lock(&jobs_mutex); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &jobs_mutex) #define UNLOCK_JOBS pthread_cleanup_pop(1) -#define UNLOCK_JOBS_REV \ - pthread_mutex_unlock(&jobs_mutex); \ +#define UNLOCK_JOBS_REV \ + pthread_mutex_unlock(&jobs_mutex); \ pthread_cleanup_push((void *)pthread_mutex_lock, &jobs_mutex) #define LOCK_JOBS_REV pthread_cleanup_pop(1) static Job *Jobs = NULL; -typedef struct _client { +typedef struct _client +{ SOCKET reply_sock; int conid; uint32_t addr; @@ -134,12 +138,12 @@ typedef struct _client { struct _client *next; } Client; static pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_CLIENTS \ - pthread_mutex_lock(&clients_mutex); \ +#define LOCK_CLIENTS \ + pthread_mutex_lock(&clients_mutex); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &clients_mutex) #define UNLOCK_CLIENTS pthread_cleanup_pop(1) -#define UNLOCK_CLIENTS_REV \ - pthread_mutex_unlock(&clients_mutex); \ +#define UNLOCK_CLIENTS_REV \ + pthread_mutex_unlock(&clients_mutex); \ pthread_cleanup_push((void *)pthread_mutex_lock, &clients_mutex) #define LOCK_CLIENTS_REV pthread_cleanup_pop(1) static Client *Clients = NULL; @@ -166,7 +170,8 @@ static void AcceptClient(SOCKET reply_sock, struct sockaddr_in *sin, fd_set *fdactive); extern void *GetConnectionInfo(); -static SOCKET getSocket(int conid) { +static SOCKET getSocket(int conid) +{ size_t len; char *info_name = NULL; SOCKET readfd = INVALID_SOCKET; @@ -179,10 +184,12 @@ static SOCKET getSocket(int conid) { int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, pthread_rwlock_t *lock, int *conid_out, void (*ast)(), void *astparam, void (*before_ast)(), int numargs_in, - ...) { + ...) +{ uint16_t port = 0; int conid; - if (start_receiver(&port) || ((conid = ServerConnect(server)) < 0)) { + if (start_receiver(&port) || ((conid = ServerConnect(server)) < 0)) + { if (ast && astparam) ast(astparam); return ServerPATH_DOWN; @@ -209,7 +216,8 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, socklen_t len = sizeof(addr_struct); if (getsockname(sock, (struct sockaddr *)&addr_struct, &len) == 0) addr = *(uint32_t *)&addr_struct.sin_addr; - if (!addr) { + if (!addr) + { perror("Error getting the address the socket is bound to.\n"); if (ast && astparam) ast(astparam); @@ -221,19 +229,23 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, sprintf(cmd, "MdsServerShr->ServerQAction(%ulu,%uwu,%d,%d,%d", addr, port, op, flags, jobid); va_start(vlist, numargs_in); - for (i = 0; i < numargs; i++) { + for (i = 0; i < numargs; i++) + { strcat(cmd, ","); arg = va_arg(vlist, struct descrip *); if (op == SrvMonitor && numargs == 8 && i == 5 && arg->dtype == DTYPE_LONG && *(int *)arg->ptr == MonitorCheckin) MonJob = jobid; - switch (arg->dtype) { - case DTYPE_CSTRING: { + switch (arg->dtype) + { + case DTYPE_CSTRING: + { int j, k; char *c = (char *)arg->ptr; int len = strlen(c); strcat(cmd, "\""); - for (j = 0, k = strlen(cmd); j < len; j++, k++) { + for (j = 0, k = strlen(cmd); j < len; j++, k++) + { if (c[j] == '"' || c[j] == '\\') cmd[k++] = '\\'; cmd[k] = c[j]; @@ -255,37 +267,42 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, } strcat(cmd, ")"); status = SendArg(conid, 0, DTYPE_CSTRING, 1, (short)strlen(cmd), 0, 0, cmd); - if - STATUS_NOT_OK { - perror("Error sending message to server"); - CleanupJob(status, jobid); - return status; - } + if (STATUS_NOT_OK) + { + perror("Error sending message to server"); + CleanupJob(status, jobid); + return status; + } status = GetAnswerInfoTS(conid, &dtype, &len, &ndims, dims, &numbytes, (void **)&dptr, &mem); - if (op == SrvStop) { - if - STATUS_NOT_OK { - status = MDSplusSUCCESS; - CleanupJob(status, jobid); - } - else { + if (op == SrvStop) + { + if (STATUS_NOT_OK) + { + status = MDSplusSUCCESS; + CleanupJob(status, jobid); + } + else + { status = MDSplusERROR; CleanupJob(status, jobid); } - } else { - if - STATUS_NOT_OK { - perror("Error: no response from server"); - CleanupJob(status, jobid); - return status; - } + } + else + { + if (STATUS_NOT_OK) + { + perror("Error: no response from server"); + CleanupJob(status, jobid); + return status; + } } free(mem); return status; } -static inline void remove_job(Job *j_i) { +static inline void remove_job(Job *j_i) +{ // only call this when cond is NULL LOCK_JOBS; Job *j, *p; @@ -303,7 +320,8 @@ static inline void remove_job(Job *j_i) { static pthread_mutex_t job_conds = PTHREAD_MUTEX_INITIALIZER; -static void doCompletionAst(Job *j, int status, char *msg, int removeJob) { +static void doCompletionAst(Job *j, int status, char *msg, int removeJob) +{ if (j->lock) pthread_rwlock_wrlock(j->lock); if (j->retstatus) @@ -315,15 +333,19 @@ static void doCompletionAst(Job *j, int status, char *msg, int removeJob) { /**** If job has a condition, RemoveJob will not remove it. ***/ pthread_mutex_lock(&job_conds); pthread_cleanup_push((void *)pthread_mutex_unlock, &job_conds); - if (j->cond) { + if (j->cond) + { CONDITION_SET(j->cond); - } else if (removeJob && j->jobid != MonJob) { + } + else if (removeJob && j->jobid != MonJob) + { remove_job(j); DBG("Job #%d async done.\n", j->jobid); } pthread_cleanup_pop(1); } -static inline Job *get_job_by_jobid(int jobid) { +static inline Job *get_job_by_jobid(int jobid) +{ Job *j; LOCK_JOBS; for (j = Jobs; j && j->jobid != jobid; j = j->next) @@ -331,12 +353,14 @@ static inline Job *get_job_by_jobid(int jobid) { UNLOCK_JOBS; return j; } -static Job *pop_job_by_jobid(int jobid) { +static Job *pop_job_by_jobid(int jobid) +{ Job *j, *p; LOCK_JOBS; for (j = Jobs, p = NULL; j && j->jobid != jobid; p = j, j = j->next) ; - if (j) { + if (j) + { if (p) p->next = j->next; else @@ -345,12 +369,14 @@ static Job *pop_job_by_jobid(int jobid) { UNLOCK_JOBS; return j; } -static Job *pop_job_by_conid(int conid) { +static Job *pop_job_by_conid(int conid) +{ Job *j, *p; LOCK_JOBS; for (j = Jobs, p = NULL; j && j->conid != conid; p = j, j = j->next) ; - if (j) { + if (j) + { if (p) p->next = j->next; else @@ -359,26 +385,33 @@ static Job *pop_job_by_conid(int conid) { UNLOCK_JOBS; return j; } -static inline int get_client_conid(Client *c, fd_set *fdactive) { +static inline int get_client_conid(Client *c, fd_set *fdactive) +{ int client_found; LOCK_CLIENTS; client_found = 0; - if (Clients == c) { + if (Clients == c) + { client_found = 1; Clients = c->next; - } else { + } + else + { Client *cp; for (cp = Clients; cp && cp->next != c; cp = cp->next) ; - if (cp && cp->next == c) { + if (cp && cp->next == c) + { client_found = 1; cp->next = c->next; } } UNLOCK_CLIENTS; - if (client_found) { + if (client_found) + { int conid = c->conid; - if (c->reply_sock != INVALID_SOCKET) { + if (c->reply_sock != INVALID_SOCKET) + { shutdown(c->reply_sock, 2); close(c->reply_sock); if (fdactive) @@ -391,62 +424,78 @@ static inline int get_client_conid(Client *c, fd_set *fdactive) { } return -1; } -static void RemoveClient(Client *c, fd_set *fdactive) { +static void RemoveClient(Client *c, fd_set *fdactive) +{ int conid = get_client_conid(c, fdactive); - for (;;) { + for (;;) + { Job *j = pop_job_by_conid(conid); - if (j) { + if (j) + { doCompletionAst(j, ServerPATH_DOWN, NULL, FALSE); free(j); - } else + } + else break; } } -static void CleanupJob(int status, int jobid) { +static void CleanupJob(int status, int jobid) +{ Job *j = pop_job_by_jobid(jobid); - if (j) { + if (j) + { const int conid = j->conid; DisconnectFromMds(conid); doCompletionAst(j, status, NULL, FALSE); free(j); - for (;;) { + for (;;) + { j = pop_job_by_conid(conid); - if (j) { + if (j) + { doCompletionAst(j, status, NULL, FALSE); free(j); - } else + } + else break; } } } -static void abandon(void *in) { +static void abandon(void *in) +{ Job *j = *(Job **)in; pthread_mutex_lock(&job_conds); pthread_cleanup_push((void *)pthread_mutex_unlock, &job_conds); - if (j && j->cond) { + if (j && j->cond) + { CONDITION_DESTROY_PTR(j->cond, &job_conds); DBG("Job #%d sync abandoned!\n", j->jobid); } pthread_cleanup_pop(1); } -static inline void wait_and_remove_job(Job *j) { +static inline void wait_and_remove_job(Job *j) +{ CONDITION_WAIT_SET(j->cond); CONDITION_DESTROY_PTR(j->cond, &job_conds); remove_job(j); } -void ServerWait(int jobid) { +void ServerWait(int jobid) +{ Job *j = get_job_by_jobid(jobid); - if (j && j->cond) { + if (j && j->cond) + { DBG("Job #%d sync pending.\n", jobid); pthread_cleanup_push(abandon, (void *)&j); wait_and_remove_job(j); pthread_cleanup_pop(0); DBG("Job #%d sync done.\n", jobid); - } else + } + else DBG("Job #%d sync lost!\n", jobid); } -static void DoBeforeAst(int jobid) { +static void DoBeforeAst(int jobid) +{ Job *j; void *astparam; void (*before_ast)(); @@ -455,7 +504,8 @@ static void DoBeforeAst(int jobid) { before_ast = NULL; for (j = Jobs; j && (j->jobid != jobid); j = j->next) ; - if (j) { + if (j) + { astparam = j->astparam; before_ast = j->before_ast; } @@ -466,7 +516,8 @@ static void DoBeforeAst(int jobid) { static int RegisterJob(int *msgid, int *retstatus, pthread_rwlock_t *lock, void (*ast)(), void *astparam, void (*before_ast)(), - int conid) { + int conid) +{ Job *j = (Job *)malloc(sizeof(Job)); j->retstatus = retstatus; j->lock = lock; @@ -476,12 +527,15 @@ static int RegisterJob(int *msgid, int *retstatus, pthread_rwlock_t *lock, j->conid = conid; LOCK_JOBS; j->jobid = ++JobId; - if (msgid) { + if (msgid) + { j->cond = malloc(sizeof(Condition)); CONDITION_INIT(j->cond); *msgid = j->jobid; DBG("Job #%d sync registered.\n", j->jobid); - } else { + } + else + { j->cond = NULL; DBG("Job #%d async registered.\n", j->jobid); } @@ -492,11 +546,14 @@ static int RegisterJob(int *msgid, int *retstatus, pthread_rwlock_t *lock, } DEFINE_INITIALIZESOCKETS; -static SOCKET CreatePort(uint16_t *port_out) { +static SOCKET CreatePort(uint16_t *port_out) +{ static uint16_t start_port = 0, range_port; - if (!start_port) { + if (!start_port) + { char *range = TranslateLogical("MDSIP_PORT_RANGE"); - if (range) { + if (range) + { char *dash; for (dash = range; *dash && *dash != '-'; dash++) ; @@ -510,7 +567,8 @@ static SOCKET CreatePort(uint16_t *port_out) { range_port = 100; } TranslateLogicalFree(range); - if (!start_port) { + if (!start_port) + { start_port = 8800; range_port = 256; } @@ -526,7 +584,8 @@ static SOCKET CreatePort(uint16_t *port_out) { int one = 1; INITIALIZESOCKETS; s = socket(AF_INET, SOCK_STREAM, 0); - if (s == INVALID_SOCKET) { + if (s == INVALID_SOCKET) + { perror("Error getting Connection Socket\n"); return s; } @@ -535,17 +594,20 @@ static SOCKET CreatePort(uint16_t *port_out) { setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(int)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; - for (tries = 0; (c_status < 0) && (tries < 500); tries++) { + for (tries = 0; (c_status < 0) && (tries < 500); tries++) + { port = start_port + (random() % range_port); sin.sin_port = htons(port); c_status = bind(s, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)); } - if (c_status < 0) { + if (c_status < 0) + { perror("Error binding to service\n"); return INVALID_SOCKET; } c_status = listen(s, 5); - if (c_status < 0) { + if (c_status < 0) + { perror("Error from listen\n"); return INVALID_SOCKET; } @@ -556,25 +618,32 @@ static SOCKET CreatePort(uint16_t *port_out) { static Condition ReceiverRunning = CONDITION_INITIALIZER; -static int start_receiver(uint16_t *port_out) { +static int start_receiver(uint16_t *port_out) +{ INIT_STATUS; static uint16_t port = 0; static SOCKET sock; static pthread_t thread; _CONDITION_LOCK(&ReceiverRunning); - if (port == 0) { + if (port == 0) + { sock = CreatePort(&port); - if (sock == INVALID_SOCKET) { + if (sock == INVALID_SOCKET) + { _CONDITION_UNLOCK(&ReceiverRunning); return C_ERROR; } } - if (!ReceiverRunning.value) { + if (!ReceiverRunning.value) + { CREATE_DETACHED_THREAD(thread, *16, ReceiverThread, &sock); - if (c_status) { + if (c_status) + { perror("Error creating pthread"); status = MDSplusERROR; - } else { + } + else + { _CONDITION_WAIT_SET(&ReceiverRunning); status = MDSplusSUCCESS; } @@ -584,32 +653,40 @@ static int start_receiver(uint16_t *port_out) { return STATUS_NOT_OK; } -static void ReceiverExit(void *arg __attribute__((unused))) { +static void ReceiverExit(void *arg __attribute__((unused))) +{ DBG("ServerSendMessage thread exitted\n"); CONDITION_RESET(&ReceiverRunning); } -static void _RemoveClient(Client *c) { +static void _RemoveClient(Client *c) +{ UNLOCK_CLIENTS_REV; RemoveClient(c, NULL); LOCK_CLIENTS_REV; } -static void ResetFdactive(int rep, SOCKET sock, fd_set *active) { +static void ResetFdactive(int rep, SOCKET sock, fd_set *active) +{ LOCK_CLIENTS; Client *c; - if (rep > 0) { - for (c = Clients; c;) { - if (is_broken_socket(c->reply_sock)) { + if (rep > 0) + { + for (c = Clients; c;) + { + if (is_broken_socket(c->reply_sock)) + { DBG("removed client in ResetFdactive\n"); _RemoveClient(c); c = Clients; - } else + } + else c = c->next; } } FD_ZERO(active); FD_SET(sock, active); - for (c = Clients; c; c = c->next) { + for (c = Clients; c; c = c->next) + { if (c->reply_sock != INVALID_SOCKET) FD_SET(c->reply_sock, active); } @@ -620,7 +697,8 @@ static void ResetFdactive(int rep, SOCKET sock, fd_set *active) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wclobbered" // fc21 claims 'last_client_port' is clobbered -static void ReceiverThread(void *sockptr) { +static void ReceiverThread(void *sockptr) +{ atexit((void *)ReceiverExit); CONDITION_SET(&ReceiverRunning); // CONDITION_SET(&ReceiverRunning); @@ -639,21 +717,27 @@ static void ReceiverThread(void *sockptr) { FD_SET(sock, &fdactive); int rep; struct timeval readto, timeout = {1, 0}; - for (rep = 0; rep < 10; rep++) { + for (rep = 0; rep < 10; rep++) + { for (readfds = fdactive, readto = timeout;; - readfds = fdactive, readto = timeout, rep = 0) { + readfds = fdactive, readto = timeout, rep = 0) + { int num = select(FD_SETSIZE, &readfds, NULL, NULL, &readto); if (num < 0) break; if (num == 0) continue; - if (FD_ISSET(sock, &readfds)) { + if (FD_ISSET(sock, &readfds)) + { socklen_t len = sizeof(struct sockaddr_in); AcceptClient(accept(sock, (struct sockaddr *)&sin, &len), &sin, &fdactive); - } else { + } + else + { Client *c, *next; - for (;;) { + for (;;) + { LOCK_CLIENTS; for (c = Clients, next = c ? c->next : 0; c && (c->reply_sock == INVALID_SOCKET || @@ -661,13 +745,15 @@ static void ReceiverThread(void *sockptr) { c = next, next = c ? c->next : 0) ; UNLOCK_CLIENTS; - if (c) { + if (c) + { SOCKET reply_sock = c->reply_sock; last_client_addr = c->addr; last_client_port = c->port; DoMessage(c, &fdactive); FD_CLR(reply_sock, &readfds); - } else + } + else break; } } @@ -682,8 +768,10 @@ static void ReceiverThread(void *sockptr) { } #pragma GCC diagnostic pop -int is_broken_socket(SOCKET socket) { - if (socket != INVALID_SOCKET) { +int is_broken_socket(SOCKET socket) +{ + if (socket != INVALID_SOCKET) + { fd_set fdactive; FD_ZERO(&fdactive); FD_SET(socket, &fdactive); @@ -693,7 +781,8 @@ int is_broken_socket(SOCKET socket) { return B_TRUE; } -static Client *get_client(uint32_t addr, uint16_t port) { +static Client *get_client(uint32_t addr, uint16_t port) +{ Client *c; LOCK_CLIENTS; for (c = Clients; c && (c->addr != addr || c->port != port); c = c->next) @@ -702,29 +791,34 @@ static Client *get_client(uint32_t addr, uint16_t port) { return c; } -static Client *get_addr_port(char *server, uint32_t *addrp, uint16_t *portp) { +static Client *get_addr_port(char *server, uint32_t *addrp, uint16_t *portp) +{ uint32_t addr; uint16_t port; char hostpart[256] = {0}; char portpart[256] = {0}; int num = sscanf(server, "%[^:]:%s", hostpart, portpart); - if (num != 2) { + if (num != 2) + { DBG("Server '%s' unknown\n", server); return NULL; } addr = LibGetHostAddr(hostpart); if (!addr) return NULL; - if (strtol(portpart, NULL, 0) == 0) { + if (strtol(portpart, NULL, 0) == 0) + { struct servent *sp = getservbyname(portpart, "tcp"); if (sp) port = sp->s_port; - else { + else + { char *portnam = getenv(portpart); portnam = (!portnam) ? ((hostpart[0] == '_') ? "8200" : "8000") : portnam; port = htons((uint16_t)strtol(portnam, NULL, 0)); } - } else + } + else port = htons((uint16_t)strtol(portpart, NULL, 0)); if (addrp) *addrp = addr; @@ -733,32 +827,37 @@ static Client *get_addr_port(char *server, uint32_t *addrp, uint16_t *portp) { return get_client(addr, port); } -EXPORT int ServerDisconnect(char *server_in) { +EXPORT int ServerDisconnect(char *server_in) +{ char *srv = TranslateLogical(server_in); char *server = srv ? srv : server_in; Client *c = get_addr_port(server, NULL, NULL); free(srv); - if (c) { + if (c) + { RemoveClient(c, NULL); return MDSplusSUCCESS; } return MDSplusERROR; } -EXPORT int ServerConnect(char *server_in) { +EXPORT int ServerConnect(char *server_in) +{ int conid = -1; char *srv = TranslateLogical(server_in); char *server = srv ? srv : server_in; uint32_t addr; uint16_t port = 0; Client *c = get_addr_port(server, &addr, &port); - if (c) { + if (c) + { if (is_broken_socket(getSocket(c->conid))) RemoveClient(c, NULL); else conid = c->conid; } - if (port && conid == -1) { + if (port && conid == -1) + { conid = ConnectToMds(server); if (conid >= 0) AddClient(addr, port, conid); @@ -767,7 +866,8 @@ EXPORT int ServerConnect(char *server_in) { return conid; } -static void DoMessage(Client *c, fd_set *fdactive) { +static void DoMessage(Client *c, fd_set *fdactive) +{ char reply[60]; char *msg = 0; int jobid; @@ -777,28 +877,34 @@ static void DoMessage(Client *c, fd_set *fdactive) { int num; int nbytes; nbytes = recv(c->reply_sock, reply, 60, MSG_WAITALL); - if (nbytes != 60) { + if (nbytes != 60) + { RemoveClient(c, fdactive); return; } num = sscanf(reply, "%d %d %d %d", &jobid, &replyType, &status, &msglen); - if (num != 4) { + if (num != 4) + { RemoveClient(c, fdactive); return; } FREE_ON_EXIT(msg); - if (msglen != 0) { + if (msglen != 0) + { msg = (char *)malloc(msglen + 1); msg[msglen] = 0; nbytes = recv(c->reply_sock, msg, msglen, MSG_WAITALL); - if (nbytes != msglen) { + if (nbytes != msglen) + { free(msg); RemoveClient(c, fdactive); return; } } - switch (replyType) { - case SrvJobFINISHED: { + switch (replyType) + { + case SrvJobFINISHED: + { Job *j = get_job_by_jobid(jobid); if (!j) j = get_job_by_jobid(MonJob); @@ -817,7 +923,8 @@ static void DoMessage(Client *c, fd_set *fdactive) { FREE_NOW(msg); } -static void AddClient(unsigned int addr, uint16_t port, int conid) { +static void AddClient(unsigned int addr, uint16_t port, int conid) +{ Client *c; Client *new = (Client *)malloc(sizeof(Client)); new->reply_sock = INVALID_SOCKET; @@ -837,7 +944,8 @@ static void AddClient(unsigned int addr, uint16_t port, int conid) { } static void AcceptClient(SOCKET reply_sock, struct sockaddr_in *sin, - fd_set *fdactive) { + fd_set *fdactive) +{ if (reply_sock == INVALID_SOCKET) return; uint32_t addr = *(uint32_t *)&sin->sin_addr; @@ -847,11 +955,14 @@ static void AcceptClient(SOCKET reply_sock, struct sockaddr_in *sin, c = c->next) ; UNLOCK_CLIENTS; - if (c) { + if (c) + { c->reply_sock = reply_sock; FD_SET(reply_sock, fdactive); DBG("accepted connection from %u.%u.%u.%u\n", ADDR2IP(addr)); - } else { + } + else + { shutdown(reply_sock, 2); close(reply_sock); DBG("dropped connection from %u.%u.%u.%u\n", ADDR2IP(addr)); diff --git a/servershr/ServerSendMonitor.c b/servershr/ServerSendMonitor.c index 9e36602d5e..bc6e45e9c9 100644 --- a/servershr/ServerSendMonitor.c +++ b/servershr/ServerSendMonitor.c @@ -31,14 +31,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int ServerSendMonitor(char *monitor, char *tree, int shot, int phase, int nid, - int on, int mode, char *server, int actstatus) { + int on, int mode, char *server, int actstatus) +{ static int initialized = B_FALSE; static char *event = NULL; char now[32]; Now32(now); const char *event_str = "event:"; const unsigned int event_len = strlen(event_str); - if (!initialized) { + if (!initialized) + { initialized = B_TRUE; char *mon_env = getenv(monitor); if (!mon_env) @@ -47,7 +49,8 @@ int ServerSendMonitor(char *monitor, char *tree, int shot, int phase, int nid, (strncasecmp(mon_env, event_str, event_len) == 0)) event = strdup(mon_env + event_len); } - if (event) { + if (event) + { char *path = TreeGetPath(nid); char *status_text = MdsGetMsg(actstatus); char *eventmsg = alloca(1024); diff --git a/servershr/ServerSetDetailProc.c b/servershr/ServerSetDetailProc.c index be7bbc264b..b04ec0ed10 100644 --- a/servershr/ServerSetDetailProc.c +++ b/servershr/ServerSetDetailProc.c @@ -56,7 +56,8 @@ void (*)(struct dsc$descriptor *)SERVER$GET_DETAIL_PROC() #include static char *(*DetailProc)() = 0; -EXPORT void ServerSetDetailProc(char *(*detail_proc)()) { +EXPORT void ServerSetDetailProc(char *(*detail_proc)()) +{ DetailProc = detail_proc; } diff --git a/servershr/ServerSetLogging.c b/servershr/ServerSetLogging.c index be769072de..46d98996dc 100644 --- a/servershr/ServerSetLogging.c +++ b/servershr/ServerSetLogging.c @@ -62,7 +62,8 @@ int SERVER$SET_LOGGING( struct dsc$descriptor *server, char *logging_mode) #include #include "servershrp.h" -EXPORT int ServerSetLogging(char *server, char logging_mode) { +EXPORT int ServerSetLogging(char *server, char logging_mode) +{ struct descrip p1; return ServerSendMessage(0, server, SrvSetLogging, NULL, NULL, NULL, NULL, NULL, NULL, 1, diff --git a/servershr/ServerStopServer.c b/servershr/ServerStopServer.c index f17c7c7f6f..06623ed822 100644 --- a/servershr/ServerStopServer.c +++ b/servershr/ServerStopServer.c @@ -56,7 +56,8 @@ int SERVER$STOP_SERVER( struct dsc$descriptor *server ) #include #include "servershrp.h" -EXPORT int ServerStopServer(char *server) { +EXPORT int ServerStopServer(char *server) +{ return ServerSendMessage(0, server, SrvStop, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL); } diff --git a/servershr/servershrp.h b/servershr/servershrp.h index 2a75480468..0db2a6a7e0 100644 --- a/servershr/servershrp.h +++ b/servershr/servershrp.h @@ -14,8 +14,8 @@ extern void pthread_unlock_global_np(); #ifdef MDSOBJECTSCPPSHRVS_EXPORTS // visual studio uses int types for typedef #define TYPEDEF(bytes) enum -#define ENDDEF(type, name) \ - ; \ +#define ENDDEF(type, name) \ + ; \ typedef type name #else #define TYPEDEF(bytes) typedef enum __attribute__((__packed__)) @@ -28,7 +28,7 @@ TYPEDEF(4){ SrvAction = 2, /**** Execute an action nid in a tree ***/ SrvClose = 3, /**** Close open trees ***/ SrvCreatePulse = - 4, /**** Create pulse files for single tree (no subtrees) ***/ + 4, /**** Create pulse files for single tree (no subtrees) ***/ SrvSetLogging = 5, /**** Turn logging on/off ***/ SrvCommand = 6, /**** Execute MDSDCL command ***/ SrvMonitor = 7, /**** Broadcast messages to action monitors ***/ @@ -39,8 +39,12 @@ TYPEDEF(4){ } ENDDEF(int, srv_t); TYPEDEF(4){ - MonitorBuildBegin = 1, MonitorBuild = 2, MonitorBuildEnd = 3, - MonitorCheckin = 4, MonitorDispatched = 5, MonitorDoing = 6, + MonitorBuildBegin = 1, + MonitorBuild = 2, + MonitorBuildEnd = 3, + MonitorCheckin = 4, + MonitorDispatched = 5, + MonitorDoing = 6, MonitorDone = 7, } ENDDEF(int, monitor_t); @@ -58,7 +62,8 @@ TYPEDEF(4){ #undef TYPEDEF #undef ENDDEF -typedef struct { +typedef struct +{ struct _SrvJob *next; struct _SrvJob *previous; unsigned int addr; @@ -70,34 +75,40 @@ typedef struct { int jobid; } JHeader; -typedef struct _SrvJob { +typedef struct _SrvJob +{ JHeader h; } SrvJob; -typedef struct { +typedef struct +{ JHeader h; char *tree; int shot; int nid; } SrvActionJob; -typedef struct { +typedef struct +{ JHeader h; } SrvCloseJob; -typedef struct { +typedef struct +{ JHeader h; char *tree; int shot; } SrvCreatePulseJob; -typedef struct { +typedef struct +{ JHeader h; char *table; char *command; } SrvCommandJob; -typedef struct { +typedef struct +{ JHeader h; char *tree; int shot; @@ -109,7 +120,8 @@ typedef struct { int status; } SrvMonitorJob; -typedef struct { +typedef struct +{ char server[32]; int nid; int phase; @@ -130,7 +142,8 @@ typedef struct { pthread_rwlock_t lock; } ActionInfo; -typedef struct { +typedef struct +{ int num; char tree[13]; int shot; @@ -138,7 +151,8 @@ typedef struct { ActionInfo actions[1]; } DispatchTable; -typedef struct { +typedef struct +{ int shot; union { int nid; diff --git a/setevent/setevent.c b/setevent/setevent.c index 4363dc341f..a3a82198f3 100644 --- a/setevent/setevent.c +++ b/setevent/setevent.c @@ -26,12 +26,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include extern int MDSEvent(char *eventname, int len, char *data); -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int status; - if (argc < 2) { + if (argc < 2) + { printf("Usage: %s [optional-data-string]\n", argv[0]); status = 0; - } else { + } + else + { int len = (int)((argc > 2) ? strlen(argv[2]) : 0); status = MDSEvent(argv[1], len, argv[2]); } diff --git a/tcl/tcl_add_node.c b/tcl/tcl_add_node.c index 68ad83825e..77dcdc850e 100644 --- a/tcl/tcl_add_node.c +++ b/tcl/tcl_add_node.c @@ -50,8 +50,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Add a node *****************************************************************/ -char tclUsageToNumber(const char *usage, char **error) { - struct usageMap { +char tclUsageToNumber(const char *usage, char **error) +{ + struct usageMap + { char *name; char value; } map[] = {{"ANY", TreeUSAGE_ANY}, @@ -83,7 +85,8 @@ char tclUsageToNumber(const char *usage, char **error) { EXPORT int TclAddNode(void *ctx, char **error, char **output - __attribute__((unused))) { /* Return: status */ + __attribute__((unused))) +{ /* Return: status */ int nid; int sts; char usage = 0; @@ -93,27 +96,34 @@ EXPORT int TclAddNode(void *ctx, char **error, char *usageStr = 0; sts = cli_get_value(ctx, "NODENAME", &nodnam); - if (cli_get_value(ctx, "MODEL", &modelType) & 1) { + if (cli_get_value(ctx, "MODEL", &modelType) & 1) + { if (cli_get_value(ctx, "QUALIFIERS", &qualifiers) & 1) *error = strdup("--> QUALIFIERS option is obsolete (ignored)\n"); sts = TreeAddConglom(nodnam, modelType, &nid); - } else { + } + else + { cli_get_value(ctx, "USAGE", &usageStr); - if (usageStr) { + if (usageStr) + { usage = tclUsageToNumber(usageStr, error); - if (usage == -1) { + if (usage == -1) + { sts = MdsdclIVVERB; goto done; } } sts = TreeAddNode(nodnam, &nid, usage); - if (sts && (usage == TreeUSAGE_SUBTREE)) { + if (sts && (usage == TreeUSAGE_SUBTREE)) + { sts = TreeSetSubtree(nid); } } if (sts & 1) TclNodeTouched(nid, new); - else { + else + { char *msg = MdsGetMsg(sts); free(*error); *error = malloc(strlen(nodnam) + strlen(msg) + 100); diff --git a/tcl/tcl_add_tag.c b/tcl/tcl_add_tag.c index 11abf0e0a4..8414443ddd 100644 --- a/tcl/tcl_add_tag.c +++ b/tcl/tcl_add_tag.c @@ -44,7 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************/ EXPORT int TclAddTag(void *ctx, char **error, char **output - __attribute__((unused))) { /* Return: status */ + __attribute__((unused))) +{ /* Return: status */ int nid; int sts; char *nodnam = 0; @@ -55,7 +56,8 @@ EXPORT int TclAddTag(void *ctx, char **error, sts = TreeFindNode(nodnam, &nid); if (sts & 1) sts = TreeAddTag(nid, tagnam); - if (!(sts & 1)) { + if (!(sts & 1)) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(tagnam) + strlen(msg) + 100); sprintf(*error, "Error adding tag %s\nError message was: %s\n", tagnam, diff --git a/tcl/tcl_clean_datafile.c b/tcl/tcl_clean_datafile.c index ac9736fe3f..0a3c0fc225 100644 --- a/tcl/tcl_clean_datafile.c +++ b/tcl/tcl_clean_datafile.c @@ -46,7 +46,8 @@ extern int TdiExecute(); * TclCleanDatafile: ****************************************************************/ EXPORT int TclCleanDatafile(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int sts; int shot; char *filnam = 0; @@ -54,9 +55,11 @@ EXPORT int TclCleanDatafile(void *ctx, char **error, cli_get_value(ctx, "FILE", &filnam); cli_get_value(ctx, "SHOTID", &asciiShot); sts = tclStringToShot(asciiShot, &shot, error); - if (sts & 1) { + if (sts & 1) + { sts = TreeCleanDatafile(filnam, shot); - if (!(sts & 1)) { + if (!(sts & 1)) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + strlen(filnam) + 100); sprintf(*error, diff --git a/tcl/tcl_close.c b/tcl/tcl_close.c index a8ab2ac66a..ac9a155c87 100644 --- a/tcl/tcl_close.c +++ b/tcl/tcl_close.c @@ -46,25 +46,30 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Close tree file(s). ***************************************************************/ EXPORT int TclClose(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int sts; char *exp = 0; char *shotidstr = 0; int shotid; - if (cli_get_value(ctx, "FILE", &exp) & 1) { + if (cli_get_value(ctx, "FILE", &exp) & 1) + { cli_get_value(ctx, "SHOTID", &shotidstr); sts = tclStringToShot(shotidstr, &shotid, error); if (sts & 1) sts = TreeClose(exp, shotid); - } else { + } + else + { int doall = cli_present(ctx, "ALL") & 1; while ((sts = TreeClose(0, 0)) & 1 && doall) ; if (doall && sts == TreeNOT_OPEN) sts = TreeSUCCESS; } - if (sts == TreeWRITEFIRST) { + if (sts == TreeWRITEFIRST) + { if (cli_present(ctx, "CONFIRM") & 1) sts = TreeQuitTree(0, 0); else diff --git a/tcl/tcl_compress_datafile.c b/tcl/tcl_compress_datafile.c index 5976818b8c..f4130e06e7 100644 --- a/tcl/tcl_compress_datafile.c +++ b/tcl/tcl_compress_datafile.c @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclCompressDatafile: ****************************************************************/ EXPORT int TclCompressDatafile(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int shot; int sts; char *filnam = 0; @@ -54,9 +55,11 @@ EXPORT int TclCompressDatafile(void *ctx, char **error, cli_get_value(ctx, "FILE", &filnam); cli_get_value(ctx, "SHOTID", &asciiShot); sts = tclStringToShot(asciiShot, &shot, error); - if (sts & 1) { + if (sts & 1) + { sts = TreeCompressDatafile(filnam, shot); - if (!(sts & 1)) { + if (!(sts & 1)) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + strlen(filnam) + 100); sprintf(*error, diff --git a/tcl/tcl_create_pulse.c b/tcl/tcl_create_pulse.c index 31769fd4f2..17b63cb78c 100644 --- a/tcl/tcl_create_pulse.c +++ b/tcl/tcl_create_pulse.c @@ -52,7 +52,8 @@ extern int ServerCreatePulse(int efn, char *server, char *treenam, int ishot, (*linkdown_handler) () , void (*before_ast) () ); */ -typedef struct _server { +typedef struct _server +{ char *server; int *nid; int current_nid; @@ -67,7 +68,8 @@ extern int TdiExecute(); /**************************************************************** * CheckCondtion: ****************************************************************/ -static int CheckCondition(int nid) { +static int CheckCondition(int nid) +{ int ans = 1; int thisNid; static int parent_nid; @@ -77,10 +79,13 @@ static int CheckCondition(int nid) { {4, NciPARENT_TREE, (unsigned char *)&parent_nid, &retlen}, {0, 0, 0, 0}}; static NCI_ITM flag_itm[] = { {4, NciGET_FLAGS, (unsigned char *)&nci_flags, &retlen}, {0, 0, 0, 0}}; - if (nid != 0) { - for (thisNid = nid; thisNid;) { + if (nid != 0) + { + for (thisNid = nid; thisNid;) + { TreeGetNci(thisNid, flag_itm); - if ((nci_flags & NciM_INCLUDE_IN_PULSE) == 0) { + if ((nci_flags & NciM_INCLUDE_IN_PULSE) == 0) + { ans = 0; break; } @@ -95,7 +100,8 @@ static int CheckCondition(int nid) { * TclCreatePulse: **************************************************************/ EXPORT int TclCreatePulse(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int shot; char *asciiShot = 0; int status = 1; @@ -110,42 +116,54 @@ EXPORT int TclCreatePulse(void *ctx, char **error, cli_get_value(ctx, "SHOT", &asciiShot); sts = tclStringToShot(asciiShot, &shot, error); free(asciiShot); - if (sts & 1) { - if (include | exclude | nomain | conditional | dispatch) { + if (sts & 1) + { + if (include | exclude | nomain | conditional | dispatch) + { int nids[256] = {0}; int nid; int num = 0; TreeGetDefaultNid(&old_default); TreeSetDefaultNid(0); - if (include) { + if (include) + { num = !nomain; char *nodename = 0; - while (cli_get_value(ctx, "INCLUDE", &nodename) & 1) { + while (cli_get_value(ctx, "INCLUDE", &nodename) & 1) + { void *fctx = 0; while (TreeFindNodeWild(nodename, &nid, &fctx, (1 << TreeUSAGE_SUBTREE)) & - 1) { + 1) + { if (!conditional || CheckCondition(nid)) nids[num++] = nid; } free(nodename); TreeFindNodeEnd(&fctx); } - } else { + } + else + { void *fctx = 0; while (num < 256 && TreeFindTagWild("TOP", &nid, &fctx)) if (nid ? (!conditional || CheckCondition(nid)) : !nomain) nids[num++] = nid; } - if (exclude) { + if (exclude) + { char *nodename = 0; - while (cli_get_value(ctx, "EXCLUDE", &nodename) & 1) { + while (cli_get_value(ctx, "EXCLUDE", &nodename) & 1) + { void *fctx = 0; while (TreeFindNodeWild(nodename, &nid, &fctx, (1 << TreeUSAGE_SUBTREE)) & - 1) { - for (i = 0; i < num; i++) { - if (nids[i] == nid) { + 1) + { + for (i = 0; i < num; i++) + { + if (nids[i] == nid) + { num--; for (; i < num; i++) nids[i] = nids[i + 1]; @@ -160,9 +178,11 @@ EXPORT int TclCreatePulse(void *ctx, char **error, TreeSetDefaultNid(old_default); if (num) status = TreeCreatePulseFile(shot, num, nids); - } else + } + else status = TreeCreatePulseFile(shot, 0, 0); - } else + } + else status = sts; return status; } diff --git a/tcl/tcl_decompile.c b/tcl/tcl_decompile.c index e4d690b3cf..951ee7b3eb 100644 --- a/tcl/tcl_decompile.c +++ b/tcl/tcl_decompile.c @@ -50,7 +50,8 @@ extern int StrFree1Dx(); /**************************************************************** * TclDecompile: ****************************************************************/ -EXPORT int TclDecompile(void *ctx, char **error, char **output) { +EXPORT int TclDecompile(void *ctx, char **error, char **output) +{ int nid; int sts = MdsdclIVVERB; char *path = 0; @@ -58,21 +59,26 @@ EXPORT int TclDecompile(void *ctx, char **error, char **output) { static struct descriptor_xd xd = {0, 0, CLASS_XD, 0, 0}; cli_get_value(ctx, "PATH", &path); - if (path != NULL) { + if (path != NULL) + { sts = TreeFindNode(path, &nid); free(path); - if (sts & 1) { + if (sts & 1) + { sts = TreeGetRecord(nid, &xd); - if (sts & 1) { + if (sts & 1) + { sts = TdiDecompile(&xd, &dsc_string MDS_END_ARG); - if (sts & 1) { + if (sts & 1) + { *output = malloc(dsc_string.length + 100); sprintf(*output, "%.*s\n", dsc_string.length, dsc_string.pointer); } StrFree1Dx(&dsc_string); } } - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_delete_node.c b/tcl/tcl_delete_node.c index f098ec1bec..fd07ae68b0 100644 --- a/tcl/tcl_delete_node.c +++ b/tcl/tcl_delete_node.c @@ -43,7 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ************************************************************************/ -typedef struct _nidlist { +typedef struct _nidlist +{ int nid; struct _nidlist *next; } NidList; @@ -53,9 +54,11 @@ static NidList *nid_list = 0; /*************************************************************** * InitTouchNodes: ***************************************************************/ -static void InitTouchNodes() { +static void InitTouchNodes() +{ int nid = 0; - while (TreeDeleteNodeGetNid(&nid) & 1) { + while (TreeDeleteNodeGetNid(&nid) & 1) + { NidList *new = malloc(sizeof(NidList)); new->nid = nid; new->next = nid_list; @@ -66,8 +69,10 @@ static void InitTouchNodes() { /*************************************************************** * TouchNodes: ***************************************************************/ -static void TouchNodes() { - while (nid_list) { +static void TouchNodes() +{ + while (nid_list) + { NidList *first = nid_list; TclNodeTouched(first->nid, delete); nid_list = first->next; @@ -79,7 +84,8 @@ static void TouchNodes() { * TclDeleteNode: * Delete a node ****************************************************************/ -EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { +EXPORT int TclDeleteNode(void *ctx, char **error, char **output) +{ int count = 0; int nids = 0; int reset = 1; @@ -92,10 +98,12 @@ EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { int log = cli_present(ctx, "LOG") & 1; int confirm = cli_present(ctx, "CONFIRM") & 1; int status = 1; - while (cli_get_value(ctx, "NODENAME", &nodename) & 1) { + while (cli_get_value(ctx, "NODENAME", &nodename) & 1) + { ctx_fn = 0; while (TreeFindNodeWild(nodename, &nid, &ctx_fn, usageMask) & 1 && - (status & 1)) { + (status & 1)) + { nids++; status = TreeDeleteNodeInitialize(nid, &count, reset); reset = 0; @@ -103,16 +111,19 @@ EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { TreeFindNodeEnd(&ctx_fn); free(nodename); } - if (status == TreeNOEDIT) { + if (status == TreeNOEDIT) + { *error = strdup("Error: The tree must be open for edit before you can " "deleted nodes.\n"); return 1; } - if (!count) { + if (!count) + { *error = strdup("Error: No nodes found.\n"); return 1; } - if ((nids != count) && !(dryrun || confirm)) { + if ((nids != count) && !(dryrun || confirm)) + { *error = strdup("Warning: This operation will result in deleting " "additional descendant\n" "nodes and/or nodes associcated with a " @@ -123,9 +134,11 @@ EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { return 1; } *output = strdup(""); - if (log || dryrun) { + if (log || dryrun) + { nid = 0; - while (TreeDeleteNodeGetNid(&nid) & 1) { + while (TreeDeleteNodeGetNid(&nid) & 1) + { char *msg; pathnam = TreeGetPath(nid); msg = malloc(strlen(pathnam) + 100); @@ -135,7 +148,8 @@ EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { TreeFree(pathnam); } } - if (~cli_present(ctx, "DRYRUN") & 1) { + if (~cli_present(ctx, "DRYRUN") & 1) + { InitTouchNodes(); TreeDeleteNodeExecute(); TouchNodes(); diff --git a/tcl/tcl_delete_pulse.c b/tcl/tcl_delete_pulse.c index 9fdac32116..bef1309fa2 100644 --- a/tcl/tcl_delete_pulse.c +++ b/tcl/tcl_delete_pulse.c @@ -40,7 +40,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ EXPORT int TclDeletePulse(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *asciiShot = 0; int shot; int sts; @@ -50,7 +51,8 @@ EXPORT int TclDeletePulse(void *ctx, char **error, sscanf(asciiShot, "%d", &shot); free(asciiShot); sts = TreeDeletePulseFile(shot, delete_all); - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_directory.c b/tcl/tcl_directory.c index 32e37f207b..b944d8b8af 100644 --- a/tcl/tcl_directory.c +++ b/tcl/tcl_directory.c @@ -62,9 +62,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ static int doFull(char **output, int nid, unsigned char nodeUsage, int version); -static char *mds_owner(/* Return: ptr to "user" string */ +static char *mds_owner( /* Return: ptr to "user" string */ unsigned int owner /* owner id */ -) { +) +{ static char ownerString[512]; int gid = owner >> 16; int uid = owner & 0xFFFF; @@ -72,14 +73,16 @@ static char *mds_owner(/* Return: ptr to "user" string */ char *username = 0; #ifdef HAVE_GETGRGID struct group *g = getgrgid(gid); - if (g) { + if (g) + { groupname = alloca(strlen(g->gr_name) + 3); sprintf(groupname, "(%s)", g->gr_name); } #endif #ifdef HAVE_GETPWUID struct passwd *p = getpwuid(uid); - if (p) { + if (p) + { username = alloca(strlen(p->pw_name) + 3); sprintf(username, "(%s)", p->pw_name); } @@ -94,7 +97,8 @@ static char *mds_owner(/* Return: ptr to "user" string */ static char *mds_datetime( /* Return: ptr to date+time string */ int time[] /* date/time to display: quadword */ -) { +) +{ unsigned short len; static char datime[24]; static DESCRIPTOR(dsc_datime, datime); @@ -107,7 +111,8 @@ static char *mds_datetime( /* Return: ptr to date+time string */ return (datime); } -void tclAppend(char **output, char *str) { +void tclAppend(char **output, char *str) +{ if (*output) *output = strcat(realloc(*output, strlen(*output) + strlen(str) + 1), str); else @@ -119,7 +124,8 @@ void tclAppend(char **output, char *str) { * Perform directory function ****************************************************************/ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ char *tagnam; char msg[128]; char *nodnam = 0; @@ -152,30 +158,40 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), if (*output == 0) *output = strdup(""); full = cli_present(ctx, "FULL") & 1; - if (cli_present(ctx, "USAGE") & 1) { + if (cli_present(ctx, "USAGE") & 1) + { char *usageStr = 0; usageMask = 0; - while (cli_get_value(ctx, "USAGE", &usageStr) & 1) { - if (usageStr) { + while (cli_get_value(ctx, "USAGE", &usageStr) & 1) + { + if (usageStr) + { char usage = tclUsageToNumber(usageStr, error); - if (usage == -1) { + if (usage == -1) + { free(usageStr); return 0; - } else { + } + else + { usageMask = usageMask | (1 << usage); free(usageStr); } } } } - while (cli_get_value(ctx, "NODE", &nodnam) & 1) { + while (cli_get_value(ctx, "NODE", &nodnam) & 1) + { int listlen = 0; - while ((status = TreeFindNodeWild(nodnam, &nid, &ctx1, usageMask)) & 1) { + while ((status = TreeFindNodeWild(nodnam, &nid, &ctx1, usageMask)) & 1) + { grand_found++; status = TreeGetNci(nid, general_info_list); nodnamC[nodnamLen] = '\0'; - if (parent_nid != last_parent_nid) { - if (found) { + if (parent_nid != last_parent_nid) + { + if (found) + { sprintf(msg, "\n\nTotal of %d node%s.\n", found, (found > 1) ? "s" : ""); listlen = 0; @@ -184,7 +200,8 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), found = 0; last_parent_nid = parent_nid; pathnam = TreeGetPath(parent_nid); - if (pathnam) { + if (pathnam) + { sprintf(msg, "\n%s\n\n", pathnam); free(pathnam); tclAppend(output, msg); @@ -192,8 +209,10 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), previous_relationship = relationship; } found++; - if (full) { - if (previous_relationship != relationship) { + if (full) + { + if (previous_relationship != relationship) + { tclAppend(output, "\n"); previous_relationship = relationship; } @@ -202,7 +221,8 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), tclAppend(output, msg); ctx2 = 0; first_tag = 1; - while ((tagnam = TreeFindNodeTags(nid, &ctx2))) { + while ((tagnam = TreeFindNodeTags(nid, &ctx2))) + { sprintf(msg, "%s\\%s", first_tag ? " tags: " : ",", tagnam); tclAppend(output, msg); free(tagnam); @@ -212,8 +232,11 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), version = 0; while (doFull(output, nid, nodeUsage, version++) & 1) ; - } else { - if (previous_relationship != relationship) { + } + else + { + if (previous_relationship != relationship) + { tclAppend(output, "\n\n"); listlen = 0; previous_relationship = relationship; @@ -222,7 +245,8 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), nodnamC); tclAppend(output, msg); listlen = listlen + strlen(msg); - if (listlen > 60) { + if (listlen > 60) + { tclAppend(output, "\n"); listlen = 0; } @@ -235,8 +259,10 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), sprintf(msg, "%s\nTotal of %d node%s.\n", full ? "" : "\n", found, ((found > 1) || (found == 0)) ? "s" : ""); tclAppend(output, msg); - if (grand_found) { - if (found != grand_found) { + if (grand_found) + { + if (found != grand_found) + { sprintf(msg, "\n\nGrand total of %d node%s.\n", grand_found, ((grand_found > 1) || (grand_found == 0)) ? "s" : ""); tclAppend(output, msg); @@ -246,7 +272,8 @@ EXPORT int TclDirectory(void *ctx, char **error __attribute__((unused)), } static int doFull(char **output, int nid, unsigned char nodeUsage, - int version) { + int version) +{ char *pathnam; int time[2]; char partC[64 + 1]; @@ -260,9 +287,9 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, int k; char *p; char msg[128]; - static char *usages[] = {"any", "structure", "action", "device", - "dispatch", "numeric", "signal", "task", - "text", "window", "axis", "subtree", + static char *usages[] = {"any", "structure", "action", "device", + "dispatch", "numeric", "signal", "task", + "text", "window", "axis", "subtree", "compound data", "unknown"}; #define MAX_USAGES (sizeof(usages) / sizeof(usages[0])) int nciFlags; @@ -284,8 +311,10 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, int status; vers = version; status = TreeGetNci(nid, full_list); - if (status & 1) { - if (version == 0) { + if (status & 1) + { + if (version == 0) + { k = (nodeUsage < MAX_USAGES) ? nodeUsage : (MAX_USAGES - 1); p = usages[k]; sprintf(msg, " Status: %s,parent is %s, usage %s%s%s%s\n", @@ -301,38 +330,44 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, tclAppend(output, " not writeable in model\n"); if (nciFlags & NciM_NO_WRITE_SHOT) tclAppend(output, " not writeable in pulse file\n"); - if (nodeUsage == TreeUSAGE_SUBTREE) { + if (nodeUsage == TreeUSAGE_SUBTREE) + { sprintf(msg, " subtree %sincluded in pulse file.\n", (nciFlags & NciM_INCLUDE_IN_PULSE) ? "" : "NOT "); tclAppend(output, msg); } msg[0] = 0; - if (nciFlags & NciM_COMPRESSIBLE) { + if (nciFlags & NciM_COMPRESSIBLE) + { strcat(msg, "compressible"); strcat(msg, (nciFlags & (NciM_COMPRESS_ON_PUT | NciM_DO_NOT_COMPRESS | NciM_COMPRESS_SEGMENTS)) ? "," : "\n"); } - if (nciFlags & NciM_COMPRESS_ON_PUT) { + if (nciFlags & NciM_COMPRESS_ON_PUT) + { strcat(msg, "compress on put"); strcat(msg, (nciFlags & (NciM_DO_NOT_COMPRESS | NciM_COMPRESS_SEGMENTS)) ? "," : "\n"); } - if (nciFlags & NciM_DO_NOT_COMPRESS) { + if (nciFlags & NciM_DO_NOT_COMPRESS) + { strcat(msg, "do not compress"); strcat(msg, (nciFlags & NciM_COMPRESS_SEGMENTS) ? "," : "\n"); } if (nciFlags & NciM_COMPRESS_SEGMENTS) strcat(msg, "compress segments\n"); - if (strlen(msg) > 0) { + if (strlen(msg) > 0) + { tclAppend(output, " "); tclAppend(output, msg); } - switch (nciFlags & (NciM_PATH_REFERENCE | NciM_NID_REFERENCE)) { + switch (nciFlags & (NciM_PATH_REFERENCE | NciM_NID_REFERENCE)) + { case NciM_PATH_REFERENCE: reference = " contains node references (paths only)\n"; break; @@ -346,7 +381,8 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, reference = 0; break; } - if (reference) { + if (reference) + { tclAppend(output, reference); } } @@ -355,18 +391,22 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, tclAppend(output, " Owner: "); tclAppend(output, mds_owner(owner)); tclAppend(output, "\n"); - if (dataLen) { + if (dataLen) + { sprintf(msg, " Dtype: %-20s Class: %-18s Length: %u bytes\n", MdsDtypeString((int)dtype), MdsClassString((int)class), dataLen); tclAppend(output, msg); - } else + } + else tclAppend(output, " There is no data stored for this node\n"); - if (conglomerate_elt != 0) { + if (conglomerate_elt != 0) + { sprintf(msg, " Model element: %d\n", conglomerate_elt); tclAppend(output, msg); partlen = 0; TreeGetNci(nid, cong_list); - if (partlen) { + if (partlen) + { pathnam = TreeGetPath(head_nid); partC[partlen] = 0; sprintf(msg, " Original element name: %s%s\n", pathnam, partC); @@ -378,9 +418,11 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, struct descriptor nid_d = {4, DTYPE_NID, CLASS_S, (char *)&nid}; int stat = TdiExecute((struct descriptor *)&expression, &nid_d, &help_d MDS_END_ARG); - if (stat & 1 && help_d.pointer != NULL) { + if (stat & 1 && help_d.pointer != NULL) + { char *help = MdsDescrToCstring(help_d.pointer); - if (strlen(help) > 0) { + if (strlen(help) > 0) + { tclAppend(output, " Device Help: "); tclAppend(output, help); tclAppend(output, "\n"); @@ -393,7 +435,8 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, return status; } -EXPORT int TclLs(void *ctx) { +EXPORT int TclLs(void *ctx) +{ char *cmd = 0; cli_get_value(ctx, "command_line", &cmd); printf("TclLs called with command line: '%s'\n", cmd); diff --git a/tcl/tcl_directory_tag.c b/tcl/tcl_directory_tag.c index 8683a5aea5..5556a21c34 100644 --- a/tcl/tcl_directory_tag.c +++ b/tcl/tcl_directory_tag.c @@ -48,7 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Perform directory of all of the tags ****************************************************************/ EXPORT int TclDirectoryTag(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ int sub_total; int grand_total; char *nodename; @@ -59,18 +60,22 @@ EXPORT int TclDirectoryTag(void *ctx, char **error __attribute__((unused)), *output = strdup(""); sub_total = grand_total = 0; - while (cli_get_value(ctx, "TAG", &tagnam) & 1 && (strlen(tagnam) < 24)) { + while (cli_get_value(ctx, "TAG", &tagnam) & 1 && (strlen(tagnam) < 24)) + { ctx1 = 0; sub_total = 0; sprintf(text, "\nTag listing for %s\n\n", tagnam); tclAppend(output, text); - while ((nodename = TreeFindTagWild(tagnam, 0, &ctx1))) { - if (path) { + while ((nodename = TreeFindTagWild(tagnam, 0, &ctx1))) + { + if (path) + { NCI_ITM itmlist[] = {{0, NciFULLPATH, 0, 0}, {0, 0, 0, 0}}; int nid; TreeFindNode(nodename, &nid); TreeGetNci(nid, itmlist); - if (itmlist[0].pointer) { + if (itmlist[0].pointer) + { char *info = malloc(strlen(nodename) + strlen(itmlist[0].pointer) + 100); sprintf(info, "%s%.*s = %s\n", nodename, (int)(40 - strlen(nodename)), @@ -80,7 +85,9 @@ EXPORT int TclDirectoryTag(void *ctx, char **error __attribute__((unused)), free(info); free(itmlist[0].pointer); } - } else { + } + else + { sprintf(text, "%s\n", nodename); tclAppend(output, text); } @@ -93,7 +100,8 @@ EXPORT int TclDirectoryTag(void *ctx, char **error __attribute__((unused)), tclAppend(output, text); free(tagnam); } - if (grand_total != sub_total) { + if (grand_total != sub_total) + { sprintf(text, "Grand Total of %d tags\n", sub_total); tclAppend(output, text); } diff --git a/tcl/tcl_dispatch.c b/tcl/tcl_dispatch.c index 0d442c6b77..439286a30f 100644 --- a/tcl/tcl_dispatch.c +++ b/tcl/tcl_dispatch.c @@ -70,17 +70,19 @@ extern int TdiIdentOf(); * TclDispatch_close: ****************************************************************/ EXPORT int TclDispatch_close(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *ident; if (IS_NOT_OK(cli_present(ctx, "SERVER"))) ServerDispatchClose(DBID_TABLE); - else { - while - IS_OK(cli_get_value(ctx, "SERVER", &ident)) { - FREE_ON_EXIT(ident); - ServerCloseTrees(ident); - FREE_NOW(ident); - } + else + { + while (IS_OK(cli_get_value(ctx, "SERVER", &ident))) + { + FREE_ON_EXIT(ident); + ServerCloseTrees(ident); + FREE_NOW(ident); + } } return TclNORMAL; } @@ -89,20 +91,21 @@ EXPORT int TclDispatch_close(void *ctx, char **error __attribute__((unused)), * TclDispatch_build: **************************************************************/ EXPORT int TclDispatch_build(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ INIT_TCLSTATUS; INIT_AND_FREE_ON_EXIT(char *, monitor); cli_get_value(ctx, "MONITOR", &monitor); status = ServerBuildDispatchTable(0, monitor, &DBID_TABLE); - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(strlen(msg) + 100); - sprintf(*error, - "Error: problem building dispatch table\n" - "Error message was: %s\n", - msg); - } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(strlen(msg) + 100); + sprintf(*error, + "Error: problem building dispatch table\n" + "Error message was: %s\n", + msg); + } FREE_NOW(monitor); return status; } @@ -115,81 +118,86 @@ static void syncwait(void *syncid_p) { ServerWait(*(int *)syncid_p); } /*************************************************************** * TclDispatch_command: ***************************************************************/ -typedef struct { +typedef struct +{ char *treenode; void *svr; void *xd; int *sid; } cln_act_t; -static void cln_act(void *cin) { +static void cln_act(void *cin) +{ cln_act_t *c = (cln_act_t *)cin; free(c->treenode); if (c->svr) free_d(c->svr); if (c->xd) free_xd(c->xd); - if (c->sid) { + if (c->sid) + { syncwait(c->sid); free(c->sid); } } EXPORT int TclDispatch(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status, sync, IOS; cln_act_t c = {0}; pthread_cleanup_push(cln_act, (void *)&c); status = TclNORMAL; sync = cli_present(ctx, "WAIT") != MdsdclNEGATED; IOS = SsINTERNAL; - if - IS_NOT_OK(cli_get_value(ctx, "NODE", &c.treenode)) { - status = MdsdclERROR; - *error = strdup("Error: Missing node path.\n"); - goto cleanup; - } + if (IS_NOT_OK(cli_get_value(ctx, "NODE", &c.treenode))) + { + status = MdsdclERROR; + *error = strdup("Error: Missing node path.\n"); + goto cleanup; + } EMPTYXD(xd); c.xd = &xd; struct descriptor_d svr = {0, DTYPE_T, CLASS_D, 0}; c.svr = &svr; int nid; status = TreeFindNode(c.treenode, &nid); - if - STATUS_OK { - struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, (char *)&nid}; - status = TdiIdentOf(&niddsc, &xd MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, (char *)&nid}; + status = TdiIdentOf(&niddsc, &xd MDS_END_ARG); + if (STATUS_OK) status = TdiData(&xd, &svr MDS_END_ARG); - if - STATUS_OK { - static char treename[13]; - static DESCRIPTOR(nullstr, "\0"); - static int shot; - static DBI_ITM itmlst[] = {{13, DbiNAME, treename, 0}, - {4, DbiSHOTID, &shot, 0}, - {0, 0, 0, 0}}; - TreeGetDbi(itmlst); - StrAppend(&svr, (struct descriptor *)&nullstr); - int *iostatusp; - if (sync) { - c.sid = calloc(1, sizeof(int)); - IOS = SsINTERNAL; - iostatusp = &IOS; - } else - iostatusp = NULL; - status = ServerDispatchAction(c.sid, svr.pointer, treename, shot, nid, - NULL, NULL, iostatusp, NULL, NULL, 0); - } - } - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(strlen(msg) + strlen(c.treenode) + 100); - sprintf(*error, - "Error dispatching node %s\n" - "Error message was: %s\n", - c.treenode, msg); + if (STATUS_OK) + { + static char treename[13]; + static DESCRIPTOR(nullstr, "\0"); + static int shot; + static DBI_ITM itmlst[] = {{13, DbiNAME, treename, 0}, + {4, DbiSHOTID, &shot, 0}, + {0, 0, 0, 0}}; + TreeGetDbi(itmlst); + StrAppend(&svr, (struct descriptor *)&nullstr); + int *iostatusp; + if (sync) + { + c.sid = calloc(1, sizeof(int)); + IOS = SsINTERNAL; + iostatusp = &IOS; + } + else + iostatusp = NULL; + status = ServerDispatchAction(c.sid, svr.pointer, treename, shot, nid, + NULL, NULL, iostatusp, NULL, NULL, 0); } + } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(strlen(msg) + strlen(c.treenode) + 100); + sprintf(*error, + "Error dispatching node %s\n" + "Error message was: %s\n", + c.treenode, msg); + } cleanup:; pthread_cleanup_pop(1); if (STATUS_OK && sync) @@ -203,13 +211,16 @@ cleanup:; * TclDispatch_start_server: **************************************************************/ EXPORT int TclDispatch_abort_server(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ INIT_TCLSTATUS; char *ident; - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) { + while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) + { FREE_ON_EXIT(ident); status = ServerAbortServer(ident, 0); - if (STATUS_NOT_OK && status) { + if (STATUS_NOT_OK && status) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + strlen(ident) + 1000); sprintf(*error, @@ -223,13 +234,16 @@ EXPORT int TclDispatch_abort_server(void *ctx, char **error, } EXPORT int TclDispatch_stop_server(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ INIT_TCLSTATUS; char *ident; - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVNAM", &ident))) { + while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVNAM", &ident))) + { FREE_ON_EXIT(ident); status = ServerStopServer(ident); - if (STATUS_NOT_OK && status) { + if (STATUS_NOT_OK && status) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + strlen(ident) + 100); sprintf(*error, @@ -243,13 +257,16 @@ EXPORT int TclDispatch_stop_server(void *ctx, char **error, } EXPORT int TclDispatch_start_server(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ INIT_TCLSTATUS; char *ident; - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER", &ident))) { + while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER", &ident))) + { FREE_ON_EXIT(ident); status = ServerStartServer(ident); - if (STATUS_NOT_OK && status) { + if (STATUS_NOT_OK && status) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + strlen(ident) + 100); sprintf(*error, @@ -266,35 +283,39 @@ EXPORT int TclDispatch_start_server(void *ctx, char **error, * TclDispatch_set_server: ***************************************************************/ -static inline int setLogging(void *ctx, int logging, char **error) { +static inline int setLogging(void *ctx, int logging, char **error) +{ char *ident; int status; status = TclNORMAL; - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER", &ident))) { + while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER", &ident))) + { FREE_ON_EXIT(ident); status = ServerSetLogging(ident, logging); - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - if (*error) - *error = realloc(*error, - strlen(*error) + strlen(msg) + strlen(ident) + 100); - else - *error = malloc(strlen(msg) + strlen(ident) + 100); - sprintf(*error, - "Error: Problem setting logging on serv %s\n" - "Error message was: %s\n", - ident, msg); - } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + if (*error) + *error = realloc(*error, + strlen(*error) + strlen(msg) + strlen(ident) + 100); + else + *error = malloc(strlen(msg) + strlen(ident) + 100); + sprintf(*error, + "Error: Problem setting logging on serv %s\n" + "Error message was: %s\n", + ident, msg); + } FREE_NOW(ident); } return status; } EXPORT int TclDispatch_set_server(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status; - if (cli_present(ctx, "LOG") == MdsdclPRESENT) { + if (cli_present(ctx, "LOG") == MdsdclPRESENT) + { INIT_AND_FREE_ON_EXIT(char *, log_type); int logging; cli_get_value(ctx, "LOG", &log_type); @@ -306,7 +327,8 @@ EXPORT int TclDispatch_set_server(void *ctx, char **error, logging = 0; status = setLogging(ctx, logging, error); FREE_NOW(log_type); - } else + } + else status = setLogging(ctx, 0, error); return status; } @@ -316,19 +338,23 @@ EXPORT int TclDispatch_set_server(void *ctx, char **error, **************************************************************/ EXPORT int TclDispatch_show_server(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ INIT_TCLSTATUS; char *ident; int dooutput = IS_OK(cli_present(ctx, "OUTPUT")); int full = IS_OK(cli_present(ctx, "FULL")); if (dooutput) *output = strdup(""); - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) { + while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) + { FREE_ON_EXIT(ident); - if (IS_WILD(ident)) { /* contains wildcard? */ + if (IS_WILD(ident)) + { /* contains wildcard? */ void *ctx1 = NULL; char *server = NULL; - while ((server = ServerFindServers(&ctx1, ident))) { + while ((server = ServerFindServers(&ctx1, ident))) + { FREE_ON_EXIT(server); tclAppend(output, "Checking server: "); tclAppend(output, server); @@ -336,15 +362,19 @@ EXPORT int TclDispatch_show_server(void *ctx, mdsdclFlushOutput(*output); char *info = NULL; FREE_ON_EXIT(info); - if (dooutput) { + if (dooutput) + { tclAppend(output, info = ServerGetInfo(full, server)); tclAppend(output, "\n"); - } else + } + else info = ServerGetInfo(full, server); FREE_NOW(info); FREE_NOW(server); } - } else { + } + else + { char *info = NULL; tclAppend(output, "Checking server: "); tclAppend(output, ident); @@ -352,7 +382,8 @@ EXPORT int TclDispatch_show_server(void *ctx, mdsdclFlushOutput(*output); FREE_ON_EXIT(info); info = ServerGetInfo(full, ident); - if (dooutput) { + if (dooutput) + { tclAppend(output, info); tclAppend(output, "\n"); } @@ -369,7 +400,8 @@ static inline void printIt(char *output) { fprintf(stdout, "%s\n", output); } * TclDispatch_phase: *****************************************************************/ EXPORT int TclDispatch_phase(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status; INIT_AND_FREE_ON_EXIT(char *, phase); INIT_AND_FREE_ON_EXIT(char *, synch_str); @@ -387,15 +419,15 @@ EXPORT int TclDispatch_phase(void *ctx, char **error, output_rtn, monitor); else status = TclNO_DISPATCH_TABLE; - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(strlen(msg) + 100); - sprintf(*error, - "Error: problem dispatching phase\n" - "Error message was: %s\n", - msg); - } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(strlen(msg) + 100); + sprintf(*error, + "Error: problem dispatching phase\n" + "Error message was: %s\n", + msg); + } FREE_NOW(monitor); FREE_NOW(synch_str); FREE_NOW(phase); @@ -405,20 +437,22 @@ EXPORT int TclDispatch_phase(void *ctx, char **error, /************************************************************** * TclDispatch_command: **************************************************************/ -typedef struct { +typedef struct +{ int status; char *command; } DispatchedCommand; -static void CommandDone(DispatchedCommand *command) { - if - IS_NOT_OK(command->status) { - char *msg = MdsGetMsg(command->status); - fprintf(stderr, - "Error: Command failed - '%s'\n" - "Error message was: %s\n", - command->command, msg); - } +static void CommandDone(DispatchedCommand *command) +{ + if (IS_NOT_OK(command->status)) + { + char *msg = MdsGetMsg(command->status); + fprintf(stderr, + "Error: Command failed - '%s'\n" + "Error message was: %s\n", + command->command, msg); + } free(command->command); free(command); } @@ -426,63 +460,73 @@ static void CommandDone(DispatchedCommand *command) { /*************************************************************** * TclDispatch_command: ***************************************************************/ -typedef struct { +typedef struct +{ char *svr; char *tab; DispatchedCommand *cmd; int *sid; } cln_cmd_t; -static void cln_cmd(void *cin) { +static void cln_cmd(void *cin) +{ cln_cmd_t *c = (cln_cmd_t *)cin; free(c->svr); free(c->tab); - if (c->sid) { + if (c->sid) + { syncwait(c->sid); free(c->sid); - } else + } + else free(c->cmd); } EXPORT int TclDispatch_command(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status, sync, IOS; cln_cmd_t c = {0}; pthread_cleanup_push(cln_cmd, (void *)&c); status = TclNORMAL; sync = 0; IOS = SsINTERNAL; - if - IS_NOT_OK(cli_get_value(ctx, "SERVER", &c.svr)) { - status = MdsdclERROR; - *error = strdup("Error: Missing server ident.\n"); - goto cleanup; - } + if (IS_NOT_OK(cli_get_value(ctx, "SERVER", &c.svr))) + { + status = MdsdclERROR; + *error = strdup("Error: Missing server ident.\n"); + goto cleanup; + } c.cmd = calloc(1, sizeof(DispatchedCommand)); cli_get_value(ctx, "TABLE", &c.tab); cli_get_value(ctx, "P1", &c.cmd->command); - if (c.cmd->command) { + if (c.cmd->command) + { sync = IS_OK(cli_present(ctx, "WAIT")); int *iostatusp; - if (sync) { + if (sync) + { c.sid = calloc(1, sizeof(int)); c.cmd->status = IOS; iostatusp = &IOS; - } else { + } + else + { c.cmd->status = ServerPATH_DOWN; iostatusp = &c.cmd->status; } status = ServerDispatchCommand(c.sid, c.svr, c.tab, c.cmd->command, CommandDone, c.cmd, iostatusp, NULL, 0); - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(100 + strlen(msg)); - sprintf(*error, - "Error: Problem dispatching async command.\n" - "Error message was: %s\n", - msg); - } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(100 + strlen(msg)); + sprintf(*error, + "Error: Problem dispatching async command.\n" + "Error message was: %s\n", + msg); + } c.cmd = NULL; - } else + } + else status = MdsdclMISSING_VALUE; cleanup:; pthread_cleanup_pop(1); @@ -495,10 +539,13 @@ cleanup:; * TclDispatch_check: ***************************************************************/ EXPORT int TclDispatch_check(void *ctx, char **error, - char **output __attribute__((unused))) { - if (ServerFailedEssential(DBID_TABLE, cli_present(ctx, "RESET"))) { + char **output __attribute__((unused))) +{ + if (ServerFailedEssential(DBID_TABLE, cli_present(ctx, "RESET"))) + { *error = strdup("Error: A essential action failed!\n"); return TclFAILED_ESSENTIAL; - } else + } + else return TclNORMAL; } diff --git a/tcl/tcl_do_method.c b/tcl/tcl_do_method.c index fdf9a5762f..bf51d65ce3 100644 --- a/tcl/tcl_do_method.c +++ b/tcl/tcl_do_method.c @@ -49,7 +49,8 @@ extern void TdiGetLong(); * TclDoMethod: ****************************************************************/ EXPORT int TclDoMethod(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int i; int argc; int status; @@ -67,72 +68,78 @@ EXPORT int TclDoMethod(void *ctx, char **error, cli_get_value(ctx, "OBJECT", &object); status = TreeFindNode(object, &nid); - if - STATUS_OK { - do_it = (TreeIsOn(nid) | cli_present(ctx, "OVERRIDE")) & 1; - if (IS_OK(cli_present(ctx, "IF"))) { - struct descriptor if_clause_dsc = {0, DTYPE_T, CLASS_S, 0}; - struct descriptor *args[] = {&if_clause_dsc}; - cli_get_value(ctx, "IF", &if_clause); - if_clause_dsc.length = strlen(if_clause); - if_clause_dsc.pointer = if_clause; - status = TdiIntrinsic(OPC_EXECUTE, 1, &args, &bool_dsc); - free(if_clause); - if - STATUS_OK + if (STATUS_OK) + { + do_it = (TreeIsOn(nid) | cli_present(ctx, "OVERRIDE")) & 1; + if (IS_OK(cli_present(ctx, "IF"))) + { + struct descriptor if_clause_dsc = {0, DTYPE_T, CLASS_S, 0}; + struct descriptor *args[] = {&if_clause_dsc}; + cli_get_value(ctx, "IF", &if_clause); + if_clause_dsc.length = strlen(if_clause); + if_clause_dsc.pointer = if_clause; + status = TdiIntrinsic(OPC_EXECUTE, 1, &args, &bool_dsc); + free(if_clause); + if (STATUS_OK) do_it = do_it && boolVal; - else do_it = 0; - } - if (do_it) { - cli_get_value(ctx, "METHOD", &method); - method_dsc.length = strlen(method); - method_dsc.pointer = method; - argc = 0; - mdsdsc_xd_t xdarg[255]; - mdsdsc_t *arglist[255]; - EMPTYXD(xd); - if (IS_OK(cli_present(ctx, "ARGUMENT"))) { - while (argc < 255 && IS_OK(cli_get_value(ctx, "ARGUMENT", &arg))) { - struct descriptor arg_dsc = {strlen(arg), DTYPE_T, CLASS_S, arg}; - struct descriptor *arg_dsc_ptr = &arg_dsc; - xdarg[argc] = xd; // empty_xd - status = TdiIntrinsic(OPC_COMPILE, 1, &arg_dsc_ptr, &xdarg[argc]); - free(arg); - if - STATUS_OK { - arglist[argc] = xdarg[argc].pointer; - argc++; - } - else - break; + else + do_it = 0; + } + if (do_it) + { + cli_get_value(ctx, "METHOD", &method); + method_dsc.length = strlen(method); + method_dsc.pointer = method; + argc = 0; + mdsdsc_xd_t xdarg[255]; + mdsdsc_t *arglist[255]; + EMPTYXD(xd); + if (IS_OK(cli_present(ctx, "ARGUMENT"))) + { + while (argc < 255 && IS_OK(cli_get_value(ctx, "ARGUMENT", &arg))) + { + struct descriptor arg_dsc = {strlen(arg), DTYPE_T, CLASS_S, arg}; + struct descriptor *arg_dsc_ptr = &arg_dsc; + xdarg[argc] = xd; // empty_xd + status = TdiIntrinsic(OPC_COMPILE, 1, &arg_dsc_ptr, &xdarg[argc]); + free(arg); + if (STATUS_OK) + { + arglist[argc] = xdarg[argc].pointer; + argc++; } + else + break; } - if - STATUS_OK { - status = TreeDoMethodA(&nid_dsc, &method_dsc, argc, arglist, &xd); - if - STATUS_OK { - if (xd.pointer) { - TdiGetLong(&xd, &status); - MdsFree1Dx(&xd, NULL); - } else - status = SsSUCCESS; - } + } + if (STATUS_OK) + { + status = TreeDoMethodA(&nid_dsc, &method_dsc, argc, arglist, &xd); + if (STATUS_OK) + { + if (xd.pointer) + { + TdiGetLong(&xd, &status); + MdsFree1Dx(&xd, NULL); } - free(method); - for (i = 0; i < argc; i++) - MdsFree1Dx(&xdarg[i], NULL); + else + status = SsSUCCESS; + } } + free(method); + for (i = 0; i < argc; i++) + MdsFree1Dx(&xdarg[i], NULL); } + } free(object); - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(strlen(msg) + 100); - sprintf(*error, - "Error executing device method\n" - "Error message was: %s\n", - msg); - } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(strlen(msg) + 100); + sprintf(*error, + "Error executing device method\n" + "Error message was: %s\n", + msg); + } return status; } diff --git a/tcl/tcl_do_node.c b/tcl/tcl_do_node.c index 9183f6915f..ab56cc6a6a 100644 --- a/tcl/tcl_do_node.c +++ b/tcl/tcl_do_node.c @@ -47,7 +47,8 @@ extern int TdiDoTask(); * TclDoNode: ***************************************************************/ EXPORT int TclDoNode(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ INIT_STATUS, retstatus; char *nodnam = NULL; int nid; @@ -55,22 +56,21 @@ EXPORT int TclDoNode(void *ctx, char **error, DESCRIPTOR_LONG(retstatus_d, &retstatus); cli_get_value(ctx, "NODE", &nodnam); status = TreeFindNode(nodnam, &nid); - if - STATUS_OK { - status = TdiDoTask(&niddsc, &retstatus_d MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + status = TdiDoTask(&niddsc, &retstatus_d MDS_END_ARG); + if (STATUS_OK) status = retstatus; - } - if - STATUS_NOT_OK { - char *msg = MdsGetMsg(status); - *error = malloc(strlen(msg) + strlen(nodnam) + 100); - sprintf(*error, - "Error: problem doing node %s\n" - "Error message was: %s\n", - nodnam, msg); - } + } + if (STATUS_NOT_OK) + { + char *msg = MdsGetMsg(status); + *error = malloc(strlen(msg) + strlen(nodnam) + 100); + sprintf(*error, + "Error: problem doing node %s\n" + "Error message was: %s\n", + nodnam, msg); + } free(nodnam); return status; } diff --git a/tcl/tcl_edit.c b/tcl/tcl_edit.c index c90aebb41f..04f42ec08b 100644 --- a/tcl/tcl_edit.c +++ b/tcl/tcl_edit.c @@ -46,7 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Open tree for edit ***************************************************************/ EXPORT int TclEdit(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int shot; int sts; char *filnam = 0; @@ -61,7 +62,8 @@ EXPORT int TclEdit(void *ctx, char **error, sts = TreeOpenEdit(filnam, shot); if (sts & 1) TclNodeTouched(0, tree); - else { + else + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_help_device.c b/tcl/tcl_help_device.c index 20ed25ae0c..32a17380f7 100644 --- a/tcl/tcl_help_device.c +++ b/tcl/tcl_help_device.c @@ -21,11 +21,13 @@ #include EXPORT int tcl_help_device(void *ctx, char **error __attribute__((unused)), - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *device = NULL; char *expr = NULL; cli_get_value(ctx, "devtype", &device); - if (device != NULL) { + if (device != NULL) + { int full = cli_present(ctx, "FULL") & 1; size_t len = strlen("DevHelp('','')") + strlen(device) + 20; expr = malloc(len); @@ -36,8 +38,10 @@ EXPORT int tcl_help_device(void *ctx, char **error __attribute__((unused)), char *ans; int status = TdiExecute(&expr_d, &ans_d MDS_END_ARG); free(expr); - if ((status & 1) && (ans_d.pointer != NULL)) { - if ((ans_d.pointer->dtype == DTYPE_T) && (ans_d.pointer->length > 0)) { + if ((status & 1) && (ans_d.pointer != NULL)) + { + if ((ans_d.pointer->dtype == DTYPE_T) && (ans_d.pointer->length > 0)) + { ans = MdsDescrToCstring(ans_d.pointer); if ((*output) == NULL) *output = strdup(""); @@ -46,8 +50,9 @@ EXPORT int tcl_help_device(void *ctx, char **error __attribute__((unused)), strcat(*output, "\n"); free(ans); return MdsdclSUCCESS; - - } else { + } + else + { char *errorstr = "Error obtaining information on that type of device\n"; if ((*error) == NULL) *error = strdup(""); diff --git a/tcl/tcl_p.h b/tcl/tcl_p.h index d183597f4f..3092bb6f6d 100644 --- a/tcl/tcl_p.h +++ b/tcl/tcl_p.h @@ -1,7 +1,15 @@ #ifndef TCL_P #define TCL_P -typedef enum { on_off, rename_node, delete, new, tree, set_def } NodeTouchType; +typedef enum +{ + on_off, + rename_node, + delete, + new, + tree, + set_def +} NodeTouchType; extern void TclSetCallbacks( /* Returns: void */ diff --git a/tcl/tcl_put_expression.c b/tcl/tcl_put_expression.c index 453d4f75dc..c73eb3e4b4 100644 --- a/tcl/tcl_put_expression.c +++ b/tcl/tcl_put_expression.c @@ -55,7 +55,8 @@ extern int TdiCompile(); ***************************************************************/ EXPORT int TclPutExpression(void *ctx, char **error, char **output __attribute__((unused)), - char *(*getline)(), void *getlineinfo) { + char *(*getline)(), void *getlineinfo) +{ char *nodnam = 0; char *ascValue = 0; struct descriptor dsc_ascValue = {0, DTYPE_T, CLASS_S, 0}; @@ -65,18 +66,22 @@ EXPORT int TclPutExpression(void *ctx, char **error, cli_get_value(ctx, "NODE", &nodnam); sts = TreeFindNode(nodnam, &nid); - if (sts & 1) { - if (cli_present(ctx, "EXTENDED") & 1) { + if (sts & 1) + { + if (cli_present(ctx, "EXTENDED") & 1) + { char *eof = 0; int use_lf = cli_present(ctx, "LF") & 1; char *line = 0; ascValue = strdup(""); cli_get_value(ctx, "EOF", &eof); while ((line = (getline ? getline(getlineinfo) : readline("PUT> "))) && - (strlen(line)) > 0) { + (strlen(line)) > 0) + { if (getline == NULL) add_history(line); - if ((eof && (strcasecmp(line, eof) == 0)) || (strlen(line) == 0)) { + if ((eof && (strcasecmp(line, eof) == 0)) || (strlen(line) == 0)) + { free(line); line = 0; break; @@ -88,12 +93,14 @@ EXPORT int TclPutExpression(void *ctx, char **error, tclAppend(&ascValue, "\n"); } free(line); - } else + } + else cli_get_value(ctx, "VALUE", &ascValue); dsc_ascValue.length = strlen(ascValue); dsc_ascValue.pointer = ascValue; sts = TdiCompile(&dsc_ascValue, &value_xd MDS_END_ARG); - if (sts & 1) { + if (sts & 1) + { if (!value_xd.l_length) value_xd.dtype = DTYPE_DSC; sts = TreePutRecord(nid, (struct descriptor *)&value_xd, 0); @@ -102,7 +109,8 @@ EXPORT int TclPutExpression(void *ctx, char **error, free(ascValue); free(nodnam); MdsFree1Dx(&value_xd, NULL); - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_remove_tag.c b/tcl/tcl_remove_tag.c index d57479fab9..f2fd1e7af3 100644 --- a/tcl/tcl_remove_tag.c +++ b/tcl/tcl_remove_tag.c @@ -44,13 +44,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Remove a tag name ***************************************************************/ EXPORT int TclRemoveTag(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int sts; char *tagnam = 0; cli_get_value(ctx, "TAGNAME", &tagnam); sts = TreeRemoveTag(tagnam); - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + strlen(tagnam) + 100); sprintf(*error, diff --git a/tcl/tcl_rename.c b/tcl/tcl_rename.c index 161ad8816f..ec8aea9e50 100644 --- a/tcl/tcl_rename.c +++ b/tcl/tcl_rename.c @@ -46,22 +46,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Rename a node or subtree. ***************************************************************/ EXPORT int TclRename(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int nid; int sts = MdsdclIVVERB; char *srcnam = 0; char *destnam = 0; cli_get_value(ctx, "SOURCE", &srcnam); - if (srcnam && (strlen(srcnam) > 0)) { + if (srcnam && (strlen(srcnam) > 0)) + { cli_get_value(ctx, "DEST", &destnam); - if (destnam && (strlen(destnam) > 0)) { + if (destnam && (strlen(destnam) > 0)) + { sts = TreeFindNode(srcnam, &nid); - if (sts & 1) { + if (sts & 1) + { sts = TreeRenameNode(nid, destnam); if (sts & 1) TclNodeTouched(nid, rename_node); - else { + else + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(srcnam) + strlen(destnam) + strlen(msg) + 100); sprintf(*error, @@ -69,14 +74,20 @@ EXPORT int TclRename(void *ctx, char **error, "Error message was: %s\n", srcnam, destnam, msg); } - } else { + } + else + { *error = malloc(strlen(srcnam) + 100); sprintf(*error, "Error: Cannot find node %s\n", srcnam); } - } else { + } + else + { *error = strdup("Error: destination node parameter missing\n"); } - } else { + } + else + { *error = strdup("Error: source node parameter missing\n"); } free(srcnam); diff --git a/tcl/tcl_set_callbacks.c b/tcl/tcl_set_callbacks.c index e07dcff38c..167a814c71 100644 --- a/tcl/tcl_set_callbacks.c +++ b/tcl/tcl_set_callbacks.c @@ -80,8 +80,10 @@ TclSetCallbacks( /* Returns: void */ , void ( *node_touched)() /* addro of "node touched" routine */ -) { - if (!initialized) { +) +{ + if (!initialized) + { pthread_mutex_init(&saved_output_mutex, 0); initialized = 1; } @@ -97,22 +99,27 @@ EXPORT void TclNodeTouched( /* Returns: void */ int nid /* node id */ , NodeTouchType type /* type of "touch" */ -) { +) +{ if (NodeTouched) (*NodeTouched)(nid, type); } -STATIC_ROUTINE void AppendOut(char *text) { +STATIC_ROUTINE void AppendOut(char *text) +{ char *msg = text ? text : ""; size_t len = strlen(msg); char *old_saved_output; pthread_mutex_lock(&saved_output_mutex); old_saved_output = saved_output; - if (saved_output) { + if (saved_output) + { saved_output = strcpy((char *)malloc(strlen(old_saved_output) + len + 2), old_saved_output); free(old_saved_output); - } else { + } + else + { saved_output = (char *)malloc(len + 2); saved_output[0] = '\0'; } @@ -123,13 +130,16 @@ STATIC_ROUTINE void AppendOut(char *text) { STATIC_ROUTINE void StatusOut(int status) { AppendOut(MdsGetMsg(status)); } -EXPORT void TclSaveOut() { - if (!initialized) { +EXPORT void TclSaveOut() +{ + if (!initialized) + { pthread_mutex_init(&saved_output_mutex, 0); initialized = 1; } pthread_mutex_lock(&saved_output_mutex); - if (saved_output) { + if (saved_output) + { free(saved_output); saved_output = 0; } @@ -137,7 +147,8 @@ EXPORT void TclSaveOut() { pthread_mutex_unlock(&saved_output_mutex); } -EXPORT int TclOutLen() { +EXPORT int TclOutLen() +{ int ans; pthread_mutex_lock(&saved_output_mutex); ans = saved_output ? strlen(saved_output) : 0; @@ -145,13 +156,16 @@ EXPORT int TclOutLen() { return ans; } -EXPORT int TclGetOut(int free_out, int len_out, char *out) { +EXPORT int TclGetOut(int free_out, int len_out, char *out) +{ int len = 0; pthread_mutex_lock(&saved_output_mutex); - if (saved_output) { + if (saved_output) + { len = strlen(saved_output); strncpy(out, saved_output, len_out); - if (free_out) { + if (free_out) + { free(saved_output); saved_output = 0; } diff --git a/tcl/tcl_set_current.c b/tcl/tcl_set_current.c index 6d522c9c14..b7bacde1d2 100644 --- a/tcl/tcl_set_current.c +++ b/tcl/tcl_set_current.c @@ -47,25 +47,30 @@ extern int TdiExecute(); * TclSetCurrent: *****************************************************************/ EXPORT int TclSetCurrent(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int sts; char *experiment = 0; char *shotasc = 0; int shot; cli_get_value(ctx, "EXPERIMENT", &experiment); - if (cli_present(ctx, "INCREMENT") & 1) { + if (cli_present(ctx, "INCREMENT") & 1) + { shot = TreeGetCurrentShotId(experiment); shot++; sts = TreeSetCurrentShotId(experiment, shot); - } else { + } + else + { cli_get_value(ctx, "SHOT", &shotasc); sts = tclStringToShot(shotasc, &shot, error); free(shotasc); sts = TreeSetCurrentShotId(experiment, shot); } - if (((sts & 1) != 1) && (*error == NULL)) { + if (((sts & 1) != 1) && (*error == NULL)) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_set_default.c b/tcl/tcl_set_default.c index 1b68badd49..d9b4db2f79 100644 --- a/tcl/tcl_set_default.c +++ b/tcl/tcl_set_default.c @@ -46,7 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclSetDefault: ****************************************************************/ EXPORT int TclSetDefault(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int nid; int sts; char *nodename; @@ -55,7 +56,8 @@ EXPORT int TclSetDefault(void *ctx, char **error, sts = TreeSetDefault(nodename, &nid); if (sts & 1) TclNodeTouched(nid, set_def); - else { + else + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + strlen(nodename) + 100); sprintf(*error, @@ -72,11 +74,13 @@ EXPORT int TclSetDefault(void *ctx, char **error, ***************************************************************/ EXPORT int TclShowDefault(void *ctx __attribute__((unused)), char **error __attribute__((unused)), - char **output) { /* Returns: status */ + char **output) +{ /* Returns: status */ char *p; int nid; TreeGetDefaultNid(&nid); - if ((p = TreeGetPath(nid))) { + if ((p = TreeGetPath(nid))) + { *output = malloc(strlen(p) + 10); sprintf(*output, "%s\n", p); TreeFree(p); diff --git a/tcl/tcl_set_node.c b/tcl/tcl_set_node.c index 7e029dc178..02f3fd00ef 100644 --- a/tcl/tcl_set_node.c +++ b/tcl/tcl_set_node.c @@ -54,7 +54,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /**************************************************************** * TclSetNode: ****************************************************************/ -EXPORT int TclSetNode(void *ctx, char **error, char **output) { +EXPORT int TclSetNode(void *ctx, char **error, char **output) +{ int nid; int status = 1; int log; @@ -67,18 +68,22 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { log = cli_present(ctx, "LOG") & 1; usageMask = -1; - while ((status = TreeFindNodeWild(nodename, &nid, &ctx1, usageMask)) & 1) { - if (statusStr) { + while ((status = TreeFindNodeWild(nodename, &nid, &ctx1, usageMask)) & 1) + { + if (statusStr) + { int statval = strtol(statusStr, NULL, 0); NCI_ITM setnci[] = {{sizeof(int), NciSTATUS, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; setnci[0].pointer = (unsigned char *)&statval; TreeSetNci(nid, setnci); } - switch (cli_present(ctx, "SUBTREE")) { + switch (cli_present(ctx, "SUBTREE")) + { case MdsdclPRESENT: status = TreeSetSubtree(nid); - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); sprintf(*error, @@ -90,7 +95,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { break; case MdsdclNEGATED: status = TreeSetNoSubtree(nid); - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); sprintf(*error, @@ -103,11 +109,13 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { } if (!(status & 1)) goto error; - if (cli_present(ctx, "ON") & 1) { + if (cli_present(ctx, "ON") & 1) + { status = TreeTurnOn(nid); if (status & 1) TclNodeTouched(nid, on_off); - else { + else + { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); sprintf(*error, @@ -116,11 +124,14 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { nodename, msg); goto error; } - } else if (cli_present(ctx, "OFF") & 1) { + } + else if (cli_present(ctx, "OFF") & 1) + { status = TreeTurnOff(nid); if (status & 1) TclNodeTouched(nid, on_off); - else { + else + { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); sprintf(*error, @@ -141,7 +152,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { {0, NciEND_OF_LIST, 0, 0}}; set_flags = 0; clear_flags = 0; - switch (cli_present(ctx, "WRITE_ONCE")) { + switch (cli_present(ctx, "WRITE_ONCE")) + { case MdsdclPRESENT: set_flags |= NciM_WRITE_ONCE; break; @@ -149,7 +161,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_WRITE_ONCE; break; } - switch (cli_present(ctx, "CACHED")) { + switch (cli_present(ctx, "CACHED")) + { case MdsdclPRESENT: set_flags |= NciM_CACHED; break; @@ -157,7 +170,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_CACHED; break; } - switch (cli_present(ctx, "COMPRESS_ON_PUT")) { + switch (cli_present(ctx, "COMPRESS_ON_PUT")) + { case MdsdclPRESENT: set_flags |= NciM_COMPRESS_ON_PUT; break; @@ -165,7 +179,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_COMPRESS_ON_PUT; break; } - switch (cli_present(ctx, "COMPRESS_SEGMENTS")) { + switch (cli_present(ctx, "COMPRESS_SEGMENTS")) + { case MdsdclPRESENT: set_flags |= NciM_COMPRESS_SEGMENTS; break; @@ -173,7 +188,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_COMPRESS_SEGMENTS; break; } - switch (cli_present(ctx, "DO_NOT_COMPRESS")) { + switch (cli_present(ctx, "DO_NOT_COMPRESS")) + { case MdsdclPRESENT: set_flags |= NciM_DO_NOT_COMPRESS; break; @@ -181,7 +197,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_DO_NOT_COMPRESS; break; } - switch (cli_present(ctx, "SHOT_WRITE")) { + switch (cli_present(ctx, "SHOT_WRITE")) + { case MdsdclPRESENT: clear_flags |= NciM_NO_WRITE_SHOT; break; @@ -189,7 +206,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { set_flags |= NciM_NO_WRITE_SHOT; break; } - switch (cli_present(ctx, "MODEL_WRITE")) { + switch (cli_present(ctx, "MODEL_WRITE")) + { case MdsdclPRESENT: clear_flags |= NciM_NO_WRITE_MODEL; break; @@ -197,7 +215,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { set_flags |= NciM_NO_WRITE_MODEL; break; } - switch (cli_present(ctx, "INCLUDED")) { + switch (cli_present(ctx, "INCLUDED")) + { case MdsdclPRESENT: set_flags |= NciM_INCLUDE_IN_PULSE; break; @@ -205,7 +224,8 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { clear_flags |= NciM_INCLUDE_IN_PULSE; break; } - switch (cli_present(ctx, "ESSENTIAL")) { + switch (cli_present(ctx, "ESSENTIAL")) + { case MdsdclPRESENT: set_flags |= NciM_ESSENTIAL; break; @@ -217,13 +237,18 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { status = TreeSetNci(nid, set_itmlst); if (clear_flags) status = TreeSetNci(nid, clear_itmlst); - if (status & 1) { - if (log) { + if (status & 1) + { + if (log) + { char *nout; - if (*output) { + if (*output) + { *output = realloc(*output, strlen(*output) + dsc_path.length + 100); nout = *output + strlen(*output); - } else { + } + else + { *output = malloc(dsc_path.length + 100); nout = *output; } @@ -231,7 +256,9 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { dsc_path.pointer); } StrFree1Dx(&dsc_path); - } else { + } + else + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + dsc_path.length + 100); sprintf(*error, diff --git a/tcl/tcl_set_readonly.c b/tcl/tcl_set_readonly.c index 8a6cf51ecc..1c39158205 100644 --- a/tcl/tcl_set_readonly.c +++ b/tcl/tcl_set_readonly.c @@ -37,14 +37,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************/ EXPORT int TclSetReadonly(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status = 1; /*-------------------------------------------------------- * Executable ... *-------------------------------------------------------*/ status = TreeSetDbiItm(DbiREADONLY, (cli_present(ctx, "OFF") & 1) == 0); - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_set_tree.c b/tcl/tcl_set_tree.c index 828f89960b..018c72e655 100644 --- a/tcl/tcl_set_tree.c +++ b/tcl/tcl_set_tree.c @@ -38,24 +38,29 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int TdiExecute(); -int tclStringToShot(char *str, int *shot_out, char **error) { +int tclStringToShot(char *str, int *shot_out, char **error) +{ int shot = -2; int status = TreeINVSHOT; char *endptr; - if (str && strlen(str) > 0) { + if (str && strlen(str) > 0) + { status = 1; /* First try just treating arg as an integer string */ shot = strtol(str, &endptr, 0); - if (*endptr != 0) { + if (*endptr != 0) + { /* Next see if the string "model" was used. */ if (strcasecmp(str, "model") == 0) shot = -1; - else { + else + { /* Next see if TDI can make sense of the string */ DESCRIPTOR_LONG(dsc_shot, &shot); struct descriptor str_d = {strlen(str), DTYPE_T, CLASS_S, str}; status = TdiExecute(&str_d, &dsc_shot MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { *error = malloc(strlen(str) + 100); sprintf(*error, "Error: Could not convert shot specified '%s' to a valid " @@ -64,12 +69,14 @@ int tclStringToShot(char *str, int *shot_out, char **error) { } } } - if ((status & 1) && (shot < -1)) { + if ((status & 1) && (shot < -1)) + { *error = malloc(100); sprintf(*error, "Error: Invalid shot number specified - %d\n", shot); status = TreeINVSHOT; } - } else + } + else *error = strdup("Error: Zero length shot string specified\n"); if (status & 1) *shot_out = shot; @@ -80,7 +87,8 @@ int tclStringToShot(char *str, int *shot_out, char **error) { * TclSetTree: **************************************************************/ EXPORT int TclSetTree(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int sts = MdsdclIVVERB; int shot; char *filnam = 0; @@ -92,14 +100,16 @@ EXPORT int TclSetTree(void *ctx, char **error, cli_get_value(ctx, "FILE", &filnam); cli_get_value(ctx, "SHOTID", &asciiShot); sts = tclStringToShot(asciiShot, &shot, error); - if (sts & 1) { + if (sts & 1) + { if (cli_present(ctx, "READONLY") & 1) sts = TreeOpen(filnam, shot, 1); else sts = TreeOpen(filnam, shot, 0); if (sts & 1) TclNodeTouched(0, tree); - else { + else + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(filnam) + strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_set_view.c b/tcl/tcl_set_view.c index 313e922625..6c3474a140 100644 --- a/tcl/tcl_set_view.c +++ b/tcl/tcl_set_view.c @@ -48,16 +48,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclSetView: ****************************************************************/ EXPORT int TclSetView(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status; int64_t viewDate = -1; char *viewDateStr = 0; cli_get_value(ctx, "DATE", &viewDateStr); if ((strcasecmp(viewDateStr, "NOW") == 0) || - ((status = LibConvertDateString(viewDateStr, &viewDate)) & 1)) { + ((status = LibConvertDateString(viewDateStr, &viewDate)) & 1)) + { status = TreeSetViewDate(&viewDate); } - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 200); sprintf(*error, diff --git a/tcl/tcl_setevent.c b/tcl/tcl_setevent.c index 1b9f235060..ce3cbf77c1 100644 --- a/tcl/tcl_setevent.c +++ b/tcl/tcl_setevent.c @@ -41,7 +41,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclSetevent: * Close tree file(s). ***************************************************************/ -EXPORT int TclSetEvent(void *ctx) { +EXPORT int TclSetEvent(void *ctx) +{ char *event = 0; int status; cli_get_value(ctx, "EVENT", &event); diff --git a/tcl/tcl_setshow_attribute.c b/tcl/tcl_setshow_attribute.c index 1387283b6f..0e2d3f96a7 100644 --- a/tcl/tcl_setshow_attribute.c +++ b/tcl/tcl_setshow_attribute.c @@ -54,7 +54,8 @@ extern int TdiSortVal(); /*************************************************************** * TclShowAttribute: ***************************************************************/ -EXPORT int TclShowAttribute(void *ctx, char **error, char **output) { +EXPORT int TclShowAttribute(void *ctx, char **error, char **output) +{ int status; int nid; EMPTYXD(xd); @@ -63,13 +64,17 @@ EXPORT int TclShowAttribute(void *ctx, char **error, char **output) { struct descriptor_d dsc_string = {0, DTYPE_T, CLASS_D, 0}; cli_get_value(ctx, "NODE", &node); status = TreeFindNode(node, &nid); - if (status & 1) { + if (status & 1) + { status = cli_get_value(ctx, "NAME", &attr); - if (status & 1) { + if (status & 1) + { status = TreeGetXNci(nid, attr, &xd); - if (status & 1) { + if (status & 1) + { status = TdiDecompile(&xd, &dsc_string MDS_END_ARG); - if (status & 1) { + if (status & 1) + { *output = strncpy(malloc(dsc_string.length + 100), dsc_string.pointer, dsc_string.length); (*output)[dsc_string.length] = '\n'; @@ -78,31 +83,41 @@ EXPORT int TclShowAttribute(void *ctx, char **error, char **output) { StrFree1Dx(&dsc_string); MdsFree1Dx(&xd, 0); } - } else { - if (TreeGetXNci(nid, "attributenames", &xd) & 1) { + } + else + { + if (TreeGetXNci(nid, "attributenames", &xd) & 1) + { TdiSortVal(&xd, &xd MDS_END_ARG); - if (xd.pointer && xd.pointer->class == CLASS_A) { + if (xd.pointer && xd.pointer->class == CLASS_A) + { typedef ARRAY(char) ARRAY_DSC; ARRAY_DSC *array = (ARRAY_DSC *)xd.pointer; char *name = array->pointer; *output = strdup("Defined attributes for this node:\n"); for (name = array->pointer; name < array->pointer + array->arsize; - name += array->length) { + name += array->length) + { char *out = alloca(array->length + 100); sprintf(out, " %.*s\n", array->length, name); tclAppend(output, out); } - } else { + } + else + { *output = strdup("No attributes defined for this node\n"); } MdsFree1Dx(&xd, 0); - } else { + } + else + { *output = strdup("No attributes defined for this node\n"); } status = 1; } } - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + strlen(node) + 100); sprintf(*error, @@ -119,7 +134,8 @@ extern int TdiCompile(); EXPORT int TclSetAttribute(void *ctx, char **error, char **output __attribute__((unused)), - char *(*getline)(), void *getlineinfo) { + char *(*getline)(), void *getlineinfo) +{ char *nodnam = 0; char *attname = 0; char *ascValue = 0; @@ -131,15 +147,19 @@ EXPORT int TclSetAttribute(void *ctx, char **error, cli_get_value(ctx, "NODE", &nodnam); cli_get_value(ctx, "NAME", &attname); sts = TreeFindNode(nodnam, &nid); - if (sts & 1) { - if (cli_present(ctx, "EXTENDED") & 1) { + if (sts & 1) + { + if (cli_present(ctx, "EXTENDED") & 1) + { int use_lf = cli_present(ctx, "LF") & 1; char *line = 0; while ((line = (getline ? getline(getlineinfo) : readline("ATT> "))) && - (strlen(line)) > 0) { + (strlen(line)) > 0) + { if (getline == NULL) add_history(line); - if (strlen(line) == 0) { + if (strlen(line) == 0) + { free(line); line = 0; break; @@ -151,19 +171,22 @@ EXPORT int TclSetAttribute(void *ctx, char **error, tclAppend(&ascValue, "\n"); } free(line); - } else + } + else cli_get_value(ctx, "VALUE", &ascValue); dsc_ascValue.length = strlen(ascValue); dsc_ascValue.pointer = ascValue; sts = TdiCompile(&dsc_ascValue, &value_xd MDS_END_ARG); - if (sts & 1) { + if (sts & 1) + { if (!value_xd.l_length) value_xd.dtype = DTYPE_DSC; sts = TreeSetXNci(nid, attname, (struct descriptor *)&value_xd); } } MdsFree1Dx(&value_xd, NULL); - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + strlen(nodnam) + 100); sprintf(*error, diff --git a/tcl/tcl_setshow_versions.c b/tcl/tcl_setshow_versions.c index 20ad10b168..d1aaceae38 100644 --- a/tcl/tcl_setshow_versions.c +++ b/tcl/tcl_setshow_versions.c @@ -37,13 +37,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************/ EXPORT int TclSetVersions(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ int status = 1; /*-------------------------------------------------------- * Executable ... *-------------------------------------------------------*/ - switch (cli_present(ctx, "MODEL")) { + switch (cli_present(ctx, "MODEL")) + { case MdsdclPRESENT: status = TreeSetDbiItm(DbiVERSIONS_IN_MODEL, 1); break; @@ -53,7 +55,8 @@ EXPORT int TclSetVersions(void *ctx, char **error, } if (!(status & 1)) goto error; - switch (cli_present(ctx, "SHOT")) { + switch (cli_present(ctx, "SHOT")) + { case MdsdclPRESENT: status = TreeSetDbiItm(DbiVERSIONS_IN_PULSE, 1); break; @@ -62,7 +65,8 @@ EXPORT int TclSetVersions(void *ctx, char **error, break; } error: - if (!(status & 1)) { + if (!(status & 1)) + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); sprintf(*error, @@ -75,19 +79,23 @@ EXPORT int TclSetVersions(void *ctx, char **error, EXPORT int TclShowVersions(void *ctx __attribute__((unused)), char **error __attribute__((unused)), - char **output) { + char **output) +{ int in_model, in_pulse, status; DBI_ITM itmlst[] = {{4, DbiVERSIONS_IN_MODEL, &in_model, 0}, {4, DbiVERSIONS_IN_PULSE, &in_pulse, 0}, {0, 0, 0, 0}}; status = TreeGetDbi(itmlst); - if (status & 1) { + if (status & 1) + { *output = malloc(500); sprintf(*output, " Versions are %s in the model file and %s in the shot file.\n", in_model ? "enabled" : "disabled", in_pulse ? "enabled" : "disabled"); - } else { + } + else + { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_show_current.c b/tcl/tcl_show_current.c index 01d9821536..c7d85c5ab4 100644 --- a/tcl/tcl_show_current.c +++ b/tcl/tcl_show_current.c @@ -42,16 +42,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /*************************************************************** * TclShowCurrent: ***************************************************************/ -EXPORT int TclShowCurrent(void *ctx, char **error, char **output) { +EXPORT int TclShowCurrent(void *ctx, char **error, char **output) +{ int shot; char *experiment = 0; cli_get_value(ctx, "EXPERIMENT", &experiment); shot = TreeGetCurrentShotId(experiment); - if (shot) { + if (shot) + { *output = malloc(100); sprintf(*output, "Current shot is %d\n", shot); - } else { + } + else + { *error = strdup("Failed to get shotid.\n"); } free(experiment); diff --git a/tcl/tcl_show_data.c b/tcl/tcl_show_data.c index 4ee3295ea9..ef9a6667fe 100644 --- a/tcl/tcl_show_data.c +++ b/tcl/tcl_show_data.c @@ -64,9 +64,10 @@ static int CvtDxT(struct descriptor *in_dsc_ptr, int depth, char **error, * TclDtypeString: * Simply a re-formatted version of MdsDtypeString ... ****************************************************************/ -static char *TclDtypeString(/* Returns: address of formatted string */ +static char *TclDtypeString( /* Returns: address of formatted string */ char dtype /* data type code */ -) { +) +{ char *string = malloc(100); if (string) sprintf(string, "%-30s: ", MdsDtypeString(dtype)); @@ -76,7 +77,8 @@ static char *TclDtypeString(/* Returns: address of formatted string */ /**************************************************************** * CvtIdentT: ****************************************************************/ -static int CvtIdentT(struct descriptor *in_dsc_ptr, int depth, char **output) { +static int CvtIdentT(struct descriptor *in_dsc_ptr, int depth, char **output) +{ char *ident = MdsDescrToCstring(in_dsc_ptr); char *dtype = TclDtypeString(in_dsc_ptr->dtype); char *out_str = alloca(strlen(ident) + strlen(dtype) + depth + 10); @@ -91,31 +93,40 @@ static int CvtIdentT(struct descriptor *in_dsc_ptr, int depth, char **output) { * CvtNidT: ****************************************************************/ static int CvtNidT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int nid = *(int *)in_dsc_ptr->pointer; int sts = 0; char *dstr = TclDtypeString(in_dsc_ptr->dtype); - if (nid == 0) { + if (nid == 0) + { char *out_str = alloca(strlen(dstr) + strlen("$VALUE") + depth + 10); sprintf(out_str, "%*s$VALUE\n", (int)(strlen(dstr) + depth), dstr); tclAppend(output, out_str); sts = 1; - } else { + } + else + { char *pathname = 0; - if ((pathname = TreeGetPath(nid))) { + if ((pathname = TreeGetPath(nid))) + { struct descriptor_xd lxd = {0, 0, CLASS_XD, 0, 0}; char *out_str = alloca(strlen(dstr) + strlen(pathname) + depth + 10); sprintf(out_str, "%*s%s\n", (int)(strlen(dstr) + depth), dstr, pathname); tclAppend(output, out_str); TreeFree(pathname); sts = TreeGetRecord(nid, &lxd); - if (sts & 1) { + if (sts & 1) + { sts = CvtDxT((struct descriptor *)(&lxd), depth + 4, error, output); MdsFree1Dx(&lxd, NULL); - } else + } + else sts = 1; - } else { + } + else + { char *out_str = alloca(strlen("***** Bad Nid Reference ********") + depth + strlen(dstr) + 10); sprintf(out_str, "%*s***** Bad Nid Reference ********\n", @@ -132,7 +143,8 @@ static int CvtNidT(struct descriptor *in_dsc_ptr, int depth, char **error, * CvtNumericT: **************************************************************/ static int CvtNumericT(struct descriptor *in_dsc_ptr, int depth, - char **output) { + char **output) +{ int sts; char *dstr = TclDtypeString(in_dsc_ptr->dtype); #define STATIC_STRING_LEN 132 @@ -140,10 +152,12 @@ static int CvtNumericT(struct descriptor *in_dsc_ptr, int depth, struct descriptor str = {STATIC_STRING_LEN, DTYPE_T, CLASS_S, str_chars}; str_chars[STATIC_STRING_LEN] = 0; sts = TdiDecompile(in_dsc_ptr, &str MDS_END_ARG); - if (sts & 1) { + if (sts & 1) + { char *out_str = alloca(strlen(dstr) + STATIC_STRING_LEN + depth + 10); int i; - for (i = STATIC_STRING_LEN; i; i--) { + for (i = STATIC_STRING_LEN; i; i--) + { if (str_chars[i - 1] == ' ') str_chars[i] = 0; else @@ -151,7 +165,9 @@ static int CvtNumericT(struct descriptor *in_dsc_ptr, int depth, } sprintf(out_str, "%*s%s\n", (int)(strlen(dstr) + depth), dstr, str_chars); tclAppend(output, out_str); - } else { + } + else + { char *out_str = alloca( strlen(dstr) + strlen("There is no primative display for this datatype") + depth + 10); @@ -167,7 +183,8 @@ static int CvtNumericT(struct descriptor *in_dsc_ptr, int depth, * CvtPathT: ***************************************************************/ static int CvtPathT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int sts; int nid; char *dstr = TclDtypeString(in_dsc_ptr->dtype); @@ -178,19 +195,25 @@ static int CvtPathT(struct descriptor *in_dsc_ptr, int depth, char **error, tclAppend(output, out_str); sts = TreeFindNode(ident, &nid); free(ident); - if (sts & 1) { + if (sts & 1) + { sts = TreeGetRecord(nid, &xd); - if (sts & 1) { + if (sts & 1) + { sts = CvtDxT((struct descriptor *)&xd, depth + 4, error, output); MdsFree1Dx(&xd, NULL); - } else { + } + else + { char *out_str = alloca(strlen("Error reading data record") + depth + 10); sprintf(out_str, "%*s\n", (int)(strlen("Error reading data record") + depth + 4), "Error reading data record"); tclAppend(output, out_str); } - } else { + } + else + { char *out_str = alloca(strlen("Record not found") + depth + 10); sprintf(out_str, "%*s\n", (int)(strlen("Record not found") + depth + 4), "Record not found"); @@ -204,11 +227,13 @@ static int CvtPathT(struct descriptor *in_dsc_ptr, int depth, char **error, * CvtDdscT: *************************************************************/ static int CvtDdscT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int sts; char *dstr = TclDtypeString(in_dsc_ptr->dtype); char *out_str; - switch (in_dsc_ptr->dtype) { + switch (in_dsc_ptr->dtype) + { case DTYPE_DSC: sts = @@ -247,15 +272,20 @@ static int CvtDdscT(struct descriptor *in_dsc_ptr, int depth, char **error, * CvtGenericRT: ***************************************************************/ static int CvtGenericRT(struct descriptor_r *in_dsc_ptr, int depth, - char **error, char **output) { + char **error, char **output) +{ int i; int sts = 1; - for (i = 0; sts && i < in_dsc_ptr->ndesc; i++) { - if (in_dsc_ptr->dscptrs[i]) { + for (i = 0; sts && i < in_dsc_ptr->ndesc; i++) + { + if (in_dsc_ptr->dscptrs[i]) + { sts = CvtDxT(in_dsc_ptr->dscptrs[i], depth + 4, error, output); - } else { + } + else + { char *out_str = alloca(strlen("*** EMPTY ****") + depth + 10); sprintf(out_str, "%*s\n", (int)(strlen("*** EMPTY ****") + depth + 4), "*** EMPTY ****"); @@ -270,7 +300,8 @@ static int CvtGenericRT(struct descriptor_r *in_dsc_ptr, int depth, * CvtFunctionT: ***************************************************************/ static int CvtFunctionT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int sts; char *dstr = TclDtypeString(in_dsc_ptr->dtype); static struct descriptor_xd ostr = {0, DTYPE_T, CLASS_XD, 0, 0}; @@ -278,7 +309,8 @@ static int CvtFunctionT(struct descriptor *in_dsc_ptr, int depth, char **error, opcode_dsc.pointer = (char *)in_dsc_ptr->pointer; sts = TdiOpcodeString(&opcode_dsc, &ostr MDS_END_ARG); - if (sts & 1) { + if (sts & 1) + { char *out_str = alloca(strlen(dstr) + depth + ostr.pointer->length + 10); sprintf(out_str, "%*s%.*s\n", (int)(strlen(dstr) + depth), dstr, ostr.pointer->length, ostr.pointer->pointer); @@ -294,12 +326,14 @@ static int CvtFunctionT(struct descriptor *in_dsc_ptr, int depth, char **error, * CvtRdscT: ***************************************************************/ static int CvtRdscT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int sts; char *dstr = TclDtypeString(in_dsc_ptr->dtype); if (in_dsc_ptr->dtype == DTYPE_FUNCTION) sts = CvtFunctionT(in_dsc_ptr, depth, error, output); - else { + else + { char *out_str = alloca(strlen(dstr) + depth + 10); sprintf(out_str, "%*s\n", (int)(strlen(dstr) + depth), dstr); tclAppend(output, out_str); @@ -312,7 +346,8 @@ static int CvtRdscT(struct descriptor *in_dsc_ptr, int depth, char **error, /**************************************************************** * CvtAdscT: ****************************************************************/ -static int CvtAdscT(struct descriptor_a *in_dsc_ptr, int depth, char **output) { +static int CvtAdscT(struct descriptor_a *in_dsc_ptr, int depth, char **output) +{ char *dstr = TclDtypeString(in_dsc_ptr->dtype); int *bptr; int *lbptr; @@ -322,10 +357,12 @@ static int CvtAdscT(struct descriptor_a *in_dsc_ptr, int depth, char **output) { char bchars[BOUNDS_LENGTH]; char *out_str = malloc(strlen(dstr) + depth + 20); sprintf(out_str, "%*s Array [ ", (int)(strlen(dstr) + depth), dstr); - if (in_dsc_ptr->aflags.bounds) { + if (in_dsc_ptr->aflags.bounds) + { bptr = (int *)((char *)in_dsc_ptr + sizeof(struct descriptor_a) + sizeof(void *) + (in_dsc_ptr->dimct) * sizeof(int)); - for (dim = 0; dim < in_dsc_ptr->dimct; dim++) { + for (dim = 0; dim < in_dsc_ptr->dimct; dim++) + { lbptr = bptr++; ubptr = bptr++; sprintf(bchars, "%d:%d%s", *lbptr, *ubptr, @@ -333,16 +370,21 @@ static int CvtAdscT(struct descriptor_a *in_dsc_ptr, int depth, char **output) { out_str = realloc(out_str, strlen(out_str) + strlen(bchars) + 10); strcat(out_str, bchars); } - } else if (in_dsc_ptr->aflags.coeff) { + } + else if (in_dsc_ptr->aflags.coeff) + { bptr = (int *)((char *)in_dsc_ptr + sizeof(struct descriptor_a) + sizeof(void *)); - for (dim = 0; dim < in_dsc_ptr->dimct; dim++) { + for (dim = 0; dim < in_dsc_ptr->dimct; dim++) + { sprintf(bchars, "%d%s", *bptr++, (dim < in_dsc_ptr->dimct - 1) ? "," : ""); out_str = realloc(out_str, strlen(out_str) + strlen(bchars) + 10); strcat(out_str, bchars); } - } else { + } + else + { sprintf(bchars, "%d", in_dsc_ptr->arsize / ((in_dsc_ptr->length) ? in_dsc_ptr->length : 1)); @@ -360,23 +402,28 @@ static int CvtAdscT(struct descriptor_a *in_dsc_ptr, int depth, char **output) { * CvtDxT: ****************************************************************/ static int CvtDxT(struct descriptor *in_dsc_ptr, int depth, char **error, - char **output) { + char **output) +{ int sts = 0; - switch (in_dsc_ptr->class) { + switch (in_dsc_ptr->class) + { default: break; case CLASS_XD: - case CLASS_XS: { + case CLASS_XS: + { if (in_dsc_ptr->dtype == DTYPE_DSC) sts = CvtDxT((struct descriptor *)in_dsc_ptr->pointer, depth, error, output); - else { + else + { const char *errormsg = "Invalid Dtype for XD or XS must be DSC\n"; char *out_str = alloca(strlen(errormsg) + depth + 10); sprintf(out_str, "%*s\n", (int)(strlen(errormsg) + depth), errormsg); tclAppend(output, out_str); } - } break; + } + break; case CLASS_D: case CLASS_S: @@ -399,7 +446,8 @@ static int CvtDxT(struct descriptor *in_dsc_ptr, int depth, char **error, /**************************************************************** * TclShowData: ****************************************************************/ -EXPORT int TclShowData(void *ctx, char **error, char **output) { +EXPORT int TclShowData(void *ctx, char **error, char **output) +{ int nid; int sts; int usageMask; @@ -409,8 +457,10 @@ EXPORT int TclShowData(void *ctx, char **error, char **output) { struct descriptor_xd data = {0, 0, CLASS_XD, 0, 0}; usageMask = -1; - while (cli_get_value(ctx, "NODE", &nodnam) & 1) { - while (TreeFindNodeWild(nodnam, &nid, &ctx1, usageMask) & 1) { + while (cli_get_value(ctx, "NODE", &nodnam) & 1) + { + while (TreeFindNodeWild(nodnam, &nid, &ctx1, usageMask) & 1) + { char *line; if (*output == NULL) *output = strdup(""); @@ -421,12 +471,14 @@ EXPORT int TclShowData(void *ctx, char **error, char **output) { free(line); TreeFree(pathnam); sts = TreeGetRecord(nid, &data); - if (sts & 1) { + if (sts & 1) + { sts = CvtDxT((struct descriptor *)(&data), 1, error, output); MdsFree1Dx(&data, 0); if ((sts & 1) == 0) tclAppend(output, " Error displaying data\n"); - } else + } + else tclAppend(output, " No data found\n"); } TreeFindNodeEnd(&ctx1); diff --git a/tcl/tcl_show_db.c b/tcl/tcl_show_db.c index 4a05a5f698..57c7adab19 100644 --- a/tcl/tcl_show_db.c +++ b/tcl/tcl_show_db.c @@ -46,15 +46,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclShowDb: ***************************************************************/ EXPORT int TclShowDB(void *ctx __attribute__((unused)), - char **error __attribute__((unused)), char **output) { + char **error __attribute__((unused)), char **output) +{ int sts; int open; DBI_ITM itm1[] = {{sizeof(open), DbiNUMBER_OPENED, &open, 0}, {0}}; sts = TreeGetDbi(itm1); - if (sts & 1) { + if (sts & 1) + { int idx; *output = strdup(""); - for (idx = 0; idx < open; idx++) { + for (idx = 0; idx < open; idx++) + { int shotid; char modified; char edit; diff --git a/tcl/tcl_verify_tree.c b/tcl/tcl_verify_tree.c index 29b4ce2cde..bf1b1c175a 100644 --- a/tcl/tcl_verify_tree.c +++ b/tcl/tcl_verify_tree.c @@ -43,11 +43,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************/ EXPORT int TclVerifyTree(void *ctx __attribute__((unused)), char **error, char **output - __attribute__((unused))) { /* Returns: status */ + __attribute__((unused))) +{ /* Returns: status */ int sts; sts = TreeVerify(); - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *error = malloc(strlen(msg) + 100); sprintf(*error, diff --git a/tcl/tcl_wfevent.c b/tcl/tcl_wfevent.c index d00b20e05f..0a1cc19c3a 100644 --- a/tcl/tcl_wfevent.c +++ b/tcl/tcl_wfevent.c @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************/ EXPORT int TclWfevent(void *ctx, char **error, - char **output __attribute__((unused))) { + char **output __attribute__((unused))) +{ char *event = 0; char *timeout = 0; int seconds = 0; @@ -54,12 +55,16 @@ EXPORT int TclWfevent(void *ctx, char **error, cli_get_value(ctx, "TIMEOUT", &timeout); seconds = strtol(timeout, NULL, 0); free(timeout); - if (event) { - if (seconds > 0) { + if (event) + { + if (seconds > 0) + { status = MDSWfeventTimed(event, 0, 0, 0, seconds); if (!(status & 1)) *error = strdup("Timeout\n"); - } else { + } + else + { status = MDSWfevent(event, 0, 0, 0); } free(event); diff --git a/tcl/tcl_write.c b/tcl/tcl_write.c index 3f8a4ff4e3..27579aee70 100644 --- a/tcl/tcl_write.c +++ b/tcl/tcl_write.c @@ -44,10 +44,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * TclWrite: ***************************************************************/ EXPORT int TclWrite(void *ctx, char **error __attribute__((unused)), - char **output) { + char **output) +{ int sts; char *exp = 0; - if (cli_get_value(ctx, "FILE", &exp) & 1) { + if (cli_get_value(ctx, "FILE", &exp) & 1) + { char *shotidStr = 0; int shotid; cli_get_value(ctx, "SHOTID", &shotidStr); @@ -55,11 +57,14 @@ EXPORT int TclWrite(void *ctx, char **error __attribute__((unused)), sts = TreeWriteTree(exp, shotid); free(exp); free(shotidStr); - } else { + } + else + { sts = TreeWriteTree(0, 0); } - if (~sts & 1) { + if (~sts & 1) + { char *msg = MdsGetMsg(sts); *output = malloc(strlen(msg) + 100); sprintf(*output, diff --git a/tdic/TdiShrExt.c b/tdic/TdiShrExt.c index 05895bbea0..0173509b3c 100644 --- a/tdic/TdiShrExt.c +++ b/tdic/TdiShrExt.c @@ -76,7 +76,8 @@ static char serv[STRLEN]; /* Current server */ static EMPTYXD(ans_xd); /* Connection record */ -typedef struct _connection { +typedef struct _connection +{ int id; /* Mark the conid as unopen */ char *unique; /* Unique connection name */ int port; @@ -106,7 +107,8 @@ struct descriptor_xd *bTest1(struct descriptor *in_bufD); #endif /* Return the name of the current connection */ -EXPORT struct descriptor_xd *rMdsCurrent() { +EXPORT struct descriptor_xd *rMdsCurrent() +{ /* Values for changing matrix dimensions */ struct descriptor_s ans_dsc = {0, 0, CLASS_S, 0}; @@ -119,20 +121,24 @@ EXPORT struct descriptor_xd *rMdsCurrent() { } /* List Current connections */ -EXPORT int rMdsList() { +EXPORT int rMdsList() +{ Connection *cptr; int i = 0; if (!strcmp(serv, LOCAL)) printf("Current connection is local\n"); - for (cptr = Connections; (cptr != NULL);) { + for (cptr = Connections; (cptr != NULL);) + { i++; - if (cptr->id != INVALID_ID) { + if (cptr->id != INVALID_ID) + { printf("Name[%20s] Id[%s] Connection[%3d]", cptr->serv, cptr->unique, (int)cptr->id); if (cptr->id == id) printf(" <-- active"); - } else + } + else printf("UnUsed slot"); printf("\n"); cptr = cptr->next; @@ -141,7 +147,8 @@ EXPORT int rMdsList() { } /* Return the version number to TDI */ -EXPORT struct descriptor_xd *rgetenv(char *expression) { +EXPORT struct descriptor_xd *rgetenv(char *expression) +{ char *sptr; struct descriptor_s ans_dsc = {0, 0, CLASS_S, 0}; @@ -155,7 +162,8 @@ EXPORT struct descriptor_xd *rgetenv(char *expression) { } /* Return the version number to TDI */ -EXPORT struct descriptor_xd *rMdsVersion() { +EXPORT struct descriptor_xd *rMdsVersion() +{ struct descriptor_s ans_dsc = {0, 0, CLASS_S, 0}; ans_dsc.pointer = VERSION; @@ -167,18 +175,22 @@ EXPORT struct descriptor_xd *rMdsVersion() { } /* Routine returns conid if valid */ -static int AddConnection(char *server) { +static int AddConnection(char *server) +{ Connection *cptr; int nid; char unique[128] = "\0"; /* Extract the ip and port numbers */ - if ((nid = ReuseCheck(server, unique, 128)) == INVALID_ID) { + if ((nid = ReuseCheck(server, unique, 128)) == INVALID_ID) + { printf("hostname [%s] invalid, No Connection\n", server); return INVALID_ID; } /* scan through current list looking for an ip/port pair */ - for (cptr = Connections; (cptr != NULL);) { - if ((cptr->id != INVALID_ID) && (strcmp(unique, cptr->unique) == 0)) { + for (cptr = Connections; (cptr != NULL);) + { + if ((cptr->id != INVALID_ID) && (strcmp(unique, cptr->unique) == 0)) + { #ifdef DEBUG printf("mdsopen: Keep conid! name changed from [%s] to [%s]\n", cptr->serv, server); @@ -190,13 +202,16 @@ static int AddConnection(char *server) { cptr = cptr->next; } /* See if the connection works */ - if ((nid = ConnectToMds(server)) == INVALID_ID) { + if ((nid = ConnectToMds(server)) == INVALID_ID) + { printf("mdsopen: Could not open connection to MDS server\n"); return (INVALID_ID); } /* Connection valid, find a slot in the stack */ - for (cptr = Connections; (cptr != NULL);) { - if (cptr->id == INVALID_ID) { /* found an empty slot */ + for (cptr = Connections; (cptr != NULL);) + { + if (cptr->id == INVALID_ID) + { /* found an empty slot */ #ifdef DEBUG printf("Found empty slot\n"); #endif @@ -205,7 +220,8 @@ static int AddConnection(char *server) { cptr = cptr->next; } /* If slot in stack empty, create a new one */ - if (cptr == NULL) { /* End of List */ + if (cptr == NULL) + { /* End of List */ #ifdef DEBUG printf("Making new Connection\n"); #endif @@ -221,7 +237,8 @@ static int AddConnection(char *server) { } /* mds server connect */ -EXPORT int rMdsConnect(char *hostin) { +EXPORT int rMdsConnect(char *hostin) +{ char host[STRLEN]; unsigned int i; if (hostin == NULL) @@ -230,17 +247,22 @@ EXPORT int rMdsConnect(char *hostin) { for (i = 0; i < (STRLEN - 1) && i < strlen(hostin); i++) host[i] = tolower(hostin[i]); host[i] = 0; - if (!strcmp(host, LOCAL)) { + if (!strcmp(host, LOCAL)) + { strcpy(serv, LOCAL); id = INVALID_ID; return (id); } /* If no conid, or server name has changed */ - if ((id == INVALID_ID) || strcmp(host, serv)) { - if ((id = AddConnection(hostin)) == INVALID_ID) { + if ((id == INVALID_ID) || strcmp(host, serv)) + { + if ((id = AddConnection(hostin)) == INVALID_ID) + { *serv = '\0'; return (0); /* no connection obtained */ - } else { + } + else + { strcpy(serv, host); /* copy new name to memory, keep conid open */ } } @@ -249,27 +271,37 @@ EXPORT int rMdsConnect(char *hostin) { /* mdsdisconnect * ==================================================================== */ -EXPORT int rMdsDisconnect(int all) { +EXPORT int rMdsDisconnect(int all) +{ int status = 1; Connection *cptr; - if (all) { - for (cptr = Connections; (cptr != NULL); cptr = cptr->next) { - if (cptr->id != INVALID_ID) { + if (all) + { + for (cptr = Connections; (cptr != NULL); cptr = cptr->next) + { + if (cptr->id != INVALID_ID) + { DisconnectFromMds(id); cptr->id = INVALID_ID; - if (cptr->unique) { + if (cptr->unique) + { free(cptr->unique); cptr->unique = 0; } } } - } else if (id != INVALID_ID) { + } + else if (id != INVALID_ID) + { status = DisconnectFromMds(id); - for (cptr = Connections; (cptr != NULL);) { - if (cptr->id == id) { + for (cptr = Connections; (cptr != NULL);) + { + if (cptr->id == id) + { cptr->id = INVALID_ID; - if (cptr->unique) { + if (cptr->unique) + { free(cptr->unique); cptr->unique = 0; } @@ -277,7 +309,9 @@ EXPORT int rMdsDisconnect(int all) { } cptr = cptr->next; } - } else if (strcmp(serv, "local")) { + } + else if (strcmp(serv, "local")) + { printf("mdsdisconnect: warning, communication conid aleady closed\n"); status = 0; } @@ -288,7 +322,8 @@ EXPORT int rMdsDisconnect(int all) { /* ================================================================================ */ -EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) { +EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) +{ /**** NOTE: NULL terminated argument list expected ****/ va_list incrmtr; int i, j; @@ -306,21 +341,24 @@ EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) { void *dptr; void *mem = 0; /* check there is a connection open */ - if (id == INVALID_ID) { + if (id == INVALID_ID) + { printf("MdsValue: No Socket open\n"); return (0); } /* Count the arguments which is needed by SendArg routine*/ va_start(incrmtr, expression); tdiarg = (struct descriptor *)expression; - for (nargs = 0; tdiarg != NULL; nargs++) { + for (nargs = 0; tdiarg != NULL; nargs++) + { tdiarg = va_arg(incrmtr, struct descriptor *); #ifdef DEBUG printf("Vararg [%d] for [0x%" PRIxPTR "]\n", nargs, (uintptr_t)tdiarg); #endif } /* note minimum 1 arg I/P and 1 arg O/P */ - if (expression == NULL || nargs < 1) { + if (expression == NULL || nargs < 1) + { printf("MdsValue: not enough arguments given [%d]\n", nargs); return (0); } @@ -331,13 +369,15 @@ EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) { #endif tdiarg = expression; /* first in list (corresponding to string) */ /* Cycle through the arguments */ - for (i = 0; (i < nargs) && (status & 1); i++) { + for (i = 0; (i < nargs) && (status & 1); i++) + { #ifdef DEBUG printf("idx[%d] dtype[%d] nargs[%d]\n", i, tdiarg->dtype, nargs); bTest(tdiarg); /* Display the descriptor */ #endif /* Make up the correct packet for SendArg */ - switch (tdiarg->class) { + switch (tdiarg->class) + { default: break; case CLASS_S: /* fixed-length descriptor */ @@ -348,12 +388,14 @@ EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) { desca = (struct descriptor_a *)tdiarg; num = desca->arsize / desca->length; ndims = desca->dimct; /* dimensions count */ - if (desca->aflags.coeff) { + if (desca->aflags.coeff) + { array_bounds *bptr = (array_bounds *)desca; /* access the array bounds of descriptor_a */ for (j = 0; j < desca->dimct; j++) dims[j] = bptr->m[j]; /* copy in the dimensions */ - } else + } + else dims[0] = num; /* simple vector assignment */ break; } @@ -372,55 +414,61 @@ EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) { } va_end(incrmtr); /* Get the reply ================================================== */ - if - STATUS_OK { - status = GetAnswerInfoTS(id, &dtype, &len, &ndims, dims, &numbytes, &dptr, - &mem); + if (STATUS_OK) + { + status = GetAnswerInfoTS(id, &dtype, &len, &ndims, dims, &numbytes, &dptr, + &mem); #ifdef DEBUG - printf( - "Reply status[%d],dtype[%d],len[%d],ndims[%d],numbytes[%d],ans[%d]\n", - status, dtype, len, ndims, numbytes, *(int *)dptr); + printf( + "Reply status[%d],dtype[%d],len[%d],ndims[%d],numbytes[%d],ans[%d]\n", + status, dtype, len, ndims, numbytes, *(int *)dptr); #endif - if - STATUS_OK { - /* Remap the descriptor types */ - dtype = IpToMds(dtype); - /* Copy the Josh way ( see his example in MdsRemote.c ) */ - if (ndims == 0) { - struct descriptor_s ans_dsc = { - 0, 0, CLASS_S, - 0}; /* Create scalar descriptor for arrived data */ - ans_dsc.pointer = dptr; - ans_dsc.dtype = dtype; - ans_dsc.length = len; - MdsCopyDxXd((struct descriptor *)&ans_dsc, - &ans_xd); /* Copy the arrival data to xd output */ - } else { - DESCRIPTOR_A_COEFF( - a_dsc, 0, 0, 0, MAX_DIMS, - 0); /* Create array descriptor for arrived data */ - int i; - a_dsc.pointer = dptr; - a_dsc.dimct = ndims; - a_dsc.dtype = dtype; - a_dsc.length = len; - a_dsc.a0 = dptr; - a_dsc.arsize = numbytes; /* Use byte count already available from + if (STATUS_OK) + { + /* Remap the descriptor types */ + dtype = IpToMds(dtype); + /* Copy the Josh way ( see his example in MdsRemote.c ) */ + if (ndims == 0) + { + struct descriptor_s ans_dsc = { + 0, 0, CLASS_S, + 0}; /* Create scalar descriptor for arrived data */ + ans_dsc.pointer = dptr; + ans_dsc.dtype = dtype; + ans_dsc.length = len; + MdsCopyDxXd((struct descriptor *)&ans_dsc, + &ans_xd); /* Copy the arrival data to xd output */ + } + else + { + DESCRIPTOR_A_COEFF( + a_dsc, 0, 0, 0, MAX_DIMS, + 0); /* Create array descriptor for arrived data */ + int i; + a_dsc.pointer = dptr; + a_dsc.dimct = ndims; + a_dsc.dtype = dtype; + a_dsc.length = len; + a_dsc.a0 = dptr; + a_dsc.arsize = numbytes; /* Use byte count already available from MdsIp reply */ - /* a_dsc.arsize= len;*/ - for (i = 0; i < ndims; i++) { - a_dsc.m[i] = dims[i]; - /* a_dsc.arsize *= dims[i];*/ - } - MdsCopyDxXd((struct descriptor *)&a_dsc, - &ans_xd); /* Copy the arrival data to xd output */ - } + /* a_dsc.arsize= len;*/ + for (i = 0; i < ndims; i++) + { + a_dsc.m[i] = dims[i]; + /* a_dsc.arsize *= dims[i];*/ } - else { - MdsFree1Dx(&ans_xd, 0); + MdsCopyDxXd((struct descriptor *)&a_dsc, + &ans_xd); /* Copy the arrival data to xd output */ } } - else { + else + { + MdsFree1Dx(&ans_xd, 0); + } + } + else + { MdsFree1Dx(&ans_xd, 0); rMdsDisconnect(id); } @@ -435,7 +483,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( #endif /* definitions from ipdesc.h for MdsIp descriptor */ static int - MdsToIp(struct descriptor * *tdiarg, short *len) { + MdsToIp(struct descriptor * *tdiarg, short *len) +{ int dtype; short llen; static EMPTYXD(xd); @@ -443,7 +492,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( if (len == NULL) len = &llen; /* ensure writing is not invalid */ - switch ((*tdiarg)->dtype) { + switch ((*tdiarg)->dtype) + { case DTYPE_BU: /* 2 byte (unsigned); 8-bit unsigned quantity */ dtype = DTYPE_UCHAR; @@ -493,7 +543,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( case DTYPE_F: /* 10 F_floating; 32-bit single-precision floating point */ case DTYPE_FS: /* 52 IEEE float basic single S */ - if ((*tdiarg)->dtype != DTYPE_NATIVE_FLOAT) { + if ((*tdiarg)->dtype != DTYPE_NATIVE_FLOAT) + { static char tmp[4]; static struct descriptor mold = {4, DTYPE_NATIVE_FLOAT, CLASS_S, tmp}; TdiCvt(*tdiarg, &mold, &xd MDS_END_ARG); @@ -505,7 +556,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( case DTYPE_D: case DTYPE_G: case DTYPE_FT: /* 53 IEEE float basic double T */ - if ((*tdiarg)->dtype != DTYPE_NATIVE_DOUBLE) { + if ((*tdiarg)->dtype != DTYPE_NATIVE_DOUBLE) + { static char tmp[8]; static struct descriptor mold = {8, DTYPE_NATIVE_DOUBLE, CLASS_S, tmp}; TdiCvt(*tdiarg, &mold, &xd MDS_END_ARG); @@ -516,7 +568,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( break; case DTYPE_FC: case DTYPE_FSC: /* 54 IEEE float basic single S complex */ - if ((*tdiarg)->dtype != DTYPE_FLOAT_COMPLEX) { + if ((*tdiarg)->dtype != DTYPE_FLOAT_COMPLEX) + { static char tmp[8]; static struct descriptor mold = {8, DTYPE_FLOAT_COMPLEX, CLASS_S, tmp}; TdiCvt(*tdiarg, &mold, &xd MDS_END_ARG); @@ -528,7 +581,8 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( case DTYPE_DC: case DTYPE_GC: case DTYPE_FTC: /* 54 IEEE float basic single S complex */ - if ((*tdiarg)->dtype != DTYPE_DOUBLE_COMPLEX) { + if ((*tdiarg)->dtype != DTYPE_DOUBLE_COMPLEX) + { static char tmp[16]; static struct descriptor mold = {16, DTYPE_DOUBLE_COMPLEX, CLASS_S, tmp}; TdiCvt(*tdiarg, &mold, &xd MDS_END_ARG); @@ -549,9 +603,11 @@ _ans = build_call(8, 'BpdMdsUnix', 'rMdsOpen', 'localhost::') _a = build_call( return (dtype); } -static int IpToMds(int dtypein) { +static int IpToMds(int dtypein) +{ int dtype = DTYPE_Z; - switch (dtypein) { + switch (dtypein) + { case DTYPE_UCHAR: dtype = DTYPE_BU; break; /* 2 byte (unsigned); 8-bit unsigned quantity */ @@ -604,7 +660,8 @@ static int IpToMds(int dtypein) { #ifdef DEBUG /* test routines for fun */ -static void bTest(struct descriptor *desc) { +static void bTest(struct descriptor *desc) +{ int i, num; int8_t *pntC; uint8_t *pntUC; @@ -619,7 +676,8 @@ static void bTest(struct descriptor *desc) { struct descriptor_a *desca; /* if an array, print out other info */ - switch (desc->class) { + switch (desc->class) + { case CLASS_S: /* fixed-length descriptor */ printf("got descriptor [%d],[%d],[%d],[%" PRIu64 "]\n", desc->length, desc->dtype, desc->class, (uintptr_t)desc->pointer); @@ -635,7 +693,8 @@ static void bTest(struct descriptor *desc) { desca->aflags.binscale, desca->aflags.redim, desca->aflags.column, desca->aflags.coeff, desca->aflags.bounds); num = desca->arsize / desca->length; - if (desca->aflags.coeff) { + if (desca->aflags.coeff) + { int j; array_bounds *bptr = (array_bounds *)desca; /* access the array bounds of descriptor_a */ @@ -658,7 +717,8 @@ static void bTest(struct descriptor *desc) { return; } if (num) - switch (desc->dtype) { + switch (desc->dtype) + { case DTYPE_Z: /* 0 unspecified */ printf("unspecified ($MISSING)"); break; @@ -790,7 +850,8 @@ static void bTest(struct descriptor *desc) { } /* simple example routine as to how to copy or make a xd return descriptor */ -struct descriptor_xd *bTest1(struct descriptor *in_bufD) { +struct descriptor_xd *bTest1(struct descriptor *in_bufD) +{ /* Values for changing matrix dimensions */ struct descriptor_s ans_dsc = {0, 0, CLASS_S, 0}; /* by casting to a descriptor with a_coeff, there is enough room to put in @@ -799,7 +860,8 @@ struct descriptor_xd *bTest1(struct descriptor *in_bufD) { struct descriptor_a *desca; /* Copy the incoming vector into the output */ - switch (in_bufD->class) { + switch (in_bufD->class) + { case CLASS_S: /* fixed-length descriptor */ ans_dsc.pointer = in_bufD->pointer; ans_dsc.dtype = in_bufD->dtype; @@ -815,12 +877,14 @@ struct descriptor_xd *bTest1(struct descriptor *in_bufD) { a_dsc.dimct = desca->dimct; /* number of dimensions used */ a_dsc.arsize = desca->arsize; /* total size in bytes */ a_dsc.aflags = desca->aflags; /* description flags of extended fields */ - if (desca->aflags.coeff) { + if (desca->aflags.coeff) + { int i; array_bounds *bptr = (array_bounds *)desca; /* access the array bounds of descriptor_a */ a_dsc.a0 = desca->pointer; /* pointer to first element of data */ - for (i = 0; i < desca->dimct; i++) { + for (i = 0; i < desca->dimct; i++) + { a_dsc.m[i] = bptr->m[i]; } } diff --git a/tdic/tdic.c b/tdic/tdic.c index 798ef60c05..98ea56f594 100644 --- a/tdic/tdic.c +++ b/tdic/tdic.c @@ -84,12 +84,14 @@ char *bfgets(char *s, int size, FILE *stream, static void tdiputs(char *line); */ /* Lookup up entry point in shareable */ -void *dlsymget(void *handle, char *sym) { +void *dlsymget(void *handle, char *sym) +{ char *error; void *ret = NULL; ret = dlsym(handle, sym); dlerror(); /* Clear any existing error */ - if ((error = dlerror()) != NULL) { + if ((error = dlerror()) != NULL) + { fprintf(stderr, "%s\n", error); exit(1); } @@ -98,7 +100,8 @@ void *dlsymget(void *handle, char *sym) { #pragma GCC diagnostic ignored "-Wunused-result" -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ FILE *in = stdin; int status; char temp[MAXEXPR]; /* temp strings for command */ @@ -124,9 +127,11 @@ int main(int argc, char **argv) { strcat(hfile, HFILE); #endif #ifdef DYNTdiShr - if (TDIhandle == NULL) { + if (TDIhandle == NULL) + { TDIhandle = dlopen(DYNTdiShr, RTLD_LAZY); - if (!TDIhandle) { + if (!TDIhandle) + { fprintf(stderr, "%s\n", dlerror()); exit(1); } @@ -135,12 +140,14 @@ int main(int argc, char **argv) { #endif #ifdef DYNreadline - if (READhandle == NULL) { + if (READhandle == NULL) + { CURSEShandle = dlopen(DYNcurses, RTLD_NOW | RTLD_GLOBAL); READhandle = dlopen(DYNreadline, RTLD_LAZY); // READhandle = dlopen(DYNreadline, RTLD_NOW); // READhandle = dlopen(DYNreadline, RTLD_NOW | RTLD_GLOBAL); - if (!READhandle) { + if (!READhandle) + { fprintf(stderr, "%s\n", dlerror()); exit(1); } @@ -156,70 +163,89 @@ int main(int argc, char **argv) { Busing_history(); *last_line = 0; /* get input from file */ - if (argc > 1) { + if (argc > 1) + { in = fopen(argv[1], "r"); - if (in == (FILE *)0) { + if (in == (FILE *)0) + { printf("Error opening input file /%s/\n", argv[1]); return (0); } } /* if specified, output to a file, defaults to stdout */ - if (argc > 2) { + if (argc > 2) + { struct descriptor out_d = {0, DTYPE_T, CLASS_S, 0}; out_d.length = (unsigned short)strlen(argv[2]); out_d.pointer = argv[2]; BTdiExecute(&out_unit_other, &out_d, &output_unit MDS_END_ARG); - } else { + } + else + { BTdiExecute(&out_unit_stdout, &output_unit MDS_END_ARG); } /* get history loaded */ Bread_history(hfile); /* main loop to get characters */ - while (bfgets(line_in, MAXEXPR, in, PROMPT) != NULL) { + while (bfgets(line_in, MAXEXPR, in, PROMPT) != NULL) + { int comment = line_in[0] == '%'; /* is a comment */ int len = strlen(line_in); /* get first line of command */ - if (!comment) { + if (!comment) + { BTdiExecute(&reset_output_unit, &output_unit, &ans MDS_END_ARG); /* tdiputs(line_in);*/ } /* if a continuation, keep getting the rest of the command */ - while (line_in[len - 1] == '\\') { + while (line_in[len - 1] == '\\') + { bfgets(&line_in[len - 1], MAXEXPR - len + 1, in, "> "); /* if (!comment) tdiputs(&line_in[len-1]);*/ len = strlen(line_in); } - if (!comment) { + if (!comment) + { static DESCRIPTOR(error_out, "_MSG=DEBUG(0),DEBUG(4),WRITE($,_MSG)"); static DESCRIPTOR(clear_errors, "WRITE($,DECOMPILE($)),DEBUG(4)"); #ifdef OLDHIST - if (!strcmp(line_in, last_line) || (*line_in == ' ')) { + if (!strcmp(line_in, last_line) || (*line_in == ' ')) + { /* printf("Removing [%d]\n",Bwhere_history());*/ HIST_ENTRY *entry = Bremove_history(Bwhere_history()); - if (entry) { + if (entry) + { free(entry->line); free(entry); } - } else + } + else strcpy(last_line, line_in); #else - if (*line_in && (*line_in != ' ') && strcmp(line_in, last_line)) { + if (*line_in && (*line_in != ' ') && strcmp(line_in, last_line)) + { Badd_history(line_in); strcpy(last_line, line_in); } #endif /* Check the special TDIC options */ - if (!strcmp(line_in, "exit") || !strcmp(line_in, "quit")) { + if (!strcmp(line_in, "exit") || !strcmp(line_in, "quit")) + { Bwrite_history(hfile); - if (getenv("HISTFILESIZE")) { + if (getenv("HISTFILESIZE")) + { int i; sscanf(getenv("HISTFILESIZE"), "%d", &i); Bhistory_truncate_file(hfile, i); } exit(1); - } else if (*line_in == '!') { + } + else if (*line_in == '!') + { *line_in = ' '; /* replace by a space */ system(line_in); - } else if (!strcmp(line_in, "help") || !strcmp(line_in, "man")) { + } + else if (!strcmp(line_in, "help") || !strcmp(line_in, "man")) + { printf("TDI(C) reference (October 1999)\n"); printf(" help func \n"); printf(" help func* \n"); @@ -229,13 +255,16 @@ int main(int argc, char **argv) { printf(" tcl \n open \n"); printf(" !\n man [TDI intrinsic]\n"); printf(" exit (guess)\n ; behaves as in MatLab\n"); - } else if (!strncmp(line_in, "type ", 5)) { + } + else if (!strncmp(line_in, "type ", 5)) + { char *nameStart, *nameEnd, *mdspath, *tpath; struct stat statf; strcpy(temp, line_in + 5); /* copy the target */ /* Check the path name for finding file */ mdspath = getenv(MDSPATH); /* get pointer */ - if (mdspath == NULL) { + if (mdspath == NULL) + { printf("Path [%s] not defined !\n", MDSPATH); return (0); } @@ -254,64 +283,82 @@ int main(int argc, char **argv) { *++nameEnd = '\0'; /* If there is anything left, scan the path */ if (strlen(nameStart)) - do { + do + { strcpy(line_in, "more "); - if ((tpath = strchr(mdspath, ';')) == NULL) { + if ((tpath = strchr(mdspath, ';')) == NULL) + { strcat(line_in, mdspath); - } else { + } + else + { strncat(line_in, mdspath, tpath - mdspath); mdspath = tpath + 1; /* put to next char */ } strcat(line_in, "/"); strcat(line_in, nameStart); /* put back the target */ strcat(line_in, ".fun"); - if (!stat(line_in + 5, &statf)) { + if (!stat(line_in + 5, &statf)) + { printf("Found <%s>\n", line_in + 5); system(line_in); tpath = NULL; } } while (tpath != NULL); - } else if (!strncmp(line_in, "man ", 4)) { + } + else if (!strncmp(line_in, "man ", 4)) + { strcpy(temp, line_in + 4); /* copy the target */ strcpy(line_in, "man "); strcat(line_in, temp); /* put back the target */ system(line_in); - } else if (!strncmp(line_in, "tcl", 3)) { + } + else if (!strncmp(line_in, "tcl", 3)) + { strcpy(line_in, "$MDSPLUS/bin/tcl"); /* move the text to the left */ system(line_in); } #ifdef NEVER - else if (!strncmp(line_in, "tcl", 3)) { + else if (!strncmp(line_in, "tcl", 3)) + { strcpy(line_in, line_in + 4); /* move the text to the left */ mdsdcl$do(&Dtcl, &Dcommand); - } else if (!strncmp(line_in, "open", 4)) { + } + else if (!strncmp(line_in, "open", 4)) + { strcpy(temp, line_in + 5); /* copy shot number into temp */ strcpy(line_in, "set tree tcv_shot/shot="); strcat(line_in, temp); /* concantenate the number */ mdsdcl$do(&Dtcl, &Dcommand); } #endif - else { + else + { #ifdef NEVER - else if (!strncmp(line_in, "use ", 4)) { + else if (!strncmp(line_in, "use ", 4)) + { strcpy(temp, line_in + 4); /* copy the target */ strcpy(line_in, "help('"); strcat(line_in, temp); strcat(line_in, "',,1)"); } - else if (line_in[length] != ';') { + else if (line_in[length] != ';') + { strcpy(temp, line_in); /* copy string */ strcpy(line_in, "write(*,"); strcat(line_in, temp); strcat(line_in, ")"); } #endif - if (!strncmp(line_in, "help ", 5)) { + if (!strncmp(line_in, "help ", 5)) + { strcpy(temp, line_in + 5); /* copy the target */ strcpy(line_in, "help('"); strcat(line_in, temp); strcat(line_in, "');"); - } else if (!strncmp(line_in, "open", 4)) { + } + else if (!strncmp(line_in, "open", 4)) + { strcpy(temp, line_in + 5); /* copy shot number into temp */ strcpy(line_in, "TreeOpen('tcv_shot',"); strcat(line_in, temp); /* concantenate the number */ @@ -332,10 +379,12 @@ int main(int argc, char **argv) { expr[expr_dsc.length++] = ')'; */ status = BTdiExecute(&expr_dsc, &ans MDS_END_ARG); - if (status & 1) { + if (status & 1) + { if (!comment) BTdiExecute(&clear_errors, &output_unit, &ans, &ans MDS_END_ARG); - } else + } + else BTdiExecute(&error_out, &output_unit, &ans MDS_END_ARG); } } @@ -357,7 +406,8 @@ static void tdiputs(char *line) */ #ifndef HAVE_READLINE_READLINE_H /* Routine to replace fgets using readline on stdin */ -static char *Breadline(char *prompt) { +static char *Breadline(char *prompt) +{ if (prompt) printf("%s ", prompt); return fgets(malloc(1024), 1023, stdin); @@ -365,10 +415,12 @@ static char *Breadline(char *prompt) { static void Badd_history(char *string) { return; } #endif -char *bfgets(char *s, int size, FILE *stream, char *prompt) { +char *bfgets(char *s, int size, FILE *stream, char *prompt) +{ char *rep; /* if not stdin, read from file */ - if (stream == stdin) { + if (stream == stdin) + { rep = Breadline(prompt); strncpy(s, rep ? rep : "", size - 1); /* Copy respecting the size limit */ #ifdef OLDHIST @@ -378,6 +430,7 @@ char *bfgets(char *s, int size, FILE *stream, char *prompt) { free(rep); s[size - 1] = '\0'; /* null terminate if necessary */ return (s); - } else + } + else return (fgets(s, size, stream)); } diff --git a/tdishr/CvtConvertFloat.c b/tdishr/CvtConvertFloat.c index 00d15d2011..df0e13ea4d 100644 --- a/tdishr/CvtConvertFloat.c +++ b/tdishr/CvtConvertFloat.c @@ -178,7 +178,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define CVT_M_BIG_ENDIAN 0x20 #define CVT_M_ERR_UNDERFLOW 0x40 #define CVT_M_SPARE2 0xFFFFFF80 -struct cvt_r_conversion_options { +struct cvt_r_conversion_options +{ unsigned cvt_v_round_to_nearest : 1; unsigned cvt_v_truncate : 1; unsigned cvt_v_round_to_pos : 1; @@ -417,36 +418,36 @@ static const uint32_t cray[] = { #define IEEE_S_NEG_ZERO ((options & CVT_M_BIG_ENDIAN) ? &ieee_s[5] : &ieee_s[4]) #define IEEE_S_POS_HUGE ((options & CVT_M_BIG_ENDIAN) ? &ieee_s[7] : &ieee_s[6]) #define IEEE_S_NEG_HUGE ((options & CVT_M_BIG_ENDIAN) ? &ieee_s[9] : &ieee_s[8]) -#define IEEE_S_POS_INFINITY \ +#define IEEE_S_POS_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_s[11] : &ieee_s[10]) -#define IEEE_S_NEG_INFINITY \ +#define IEEE_S_NEG_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_s[13] : &ieee_s[12]) #define IEEE_T_INVALID ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[2] : &ieee_t[0]) #define IEEE_T_POS_ZERO ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[6] : &ieee_t[4]) -#define IEEE_T_NEG_ZERO \ +#define IEEE_T_NEG_ZERO \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[10] : &ieee_t[8]) -#define IEEE_T_POS_HUGE \ +#define IEEE_T_POS_HUGE \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[14] : &ieee_t[12]) -#define IEEE_T_NEG_HUGE \ +#define IEEE_T_NEG_HUGE \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[18] : &ieee_t[16]) -#define IEEE_T_POS_INFINITY \ +#define IEEE_T_POS_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[22] : &ieee_t[20]) -#define IEEE_T_NEG_INFINITY \ +#define IEEE_T_NEG_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_t[26] : &ieee_t[24]) #define IEEE_X_INVALID ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[4] : &ieee_x[0]) -#define IEEE_X_POS_ZERO \ +#define IEEE_X_POS_ZERO \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[12] : &ieee_x[8]) -#define IEEE_X_NEG_ZERO \ +#define IEEE_X_NEG_ZERO \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[20] : &ieee_x[16]) -#define IEEE_X_POS_HUGE \ +#define IEEE_X_POS_HUGE \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[28] : &ieee_x[24]) -#define IEEE_X_NEG_HUGE \ +#define IEEE_X_NEG_HUGE \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[36] : &ieee_x[32]) -#define IEEE_X_POS_INFINITY \ +#define IEEE_X_POS_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[44] : &ieee_x[40]) -#define IEEE_X_NEG_INFINITY \ +#define IEEE_X_NEG_INFINITY \ ((options & CVT_M_BIG_ENDIAN) ? &ieee_x[52] : &ieee_x[48]) #define IBM_S_INVALID &ibm_s[0] @@ -652,8 +653,10 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, ** Validate the options parameter. ** ========================================================================== */ - if (input_type == output_type) { - switch (input_type) { + if (input_type == output_type) + { + switch (input_type) + { case VAX_F: *(float *)output_value = *(float *)input_value; return !IsRoprandF(input_value); @@ -675,9 +678,11 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, } } - switch (options & ~(CVT_M_BIG_ENDIAN | CVT_M_ERR_UNDERFLOW)) { + switch (options & ~(CVT_M_BIG_ENDIAN | CVT_M_ERR_UNDERFLOW)) + { case 0: - switch (output_type) { + switch (output_type) + { case VAX_F: case VAX_D: case VAX_G: @@ -730,7 +735,8 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, ** ** ========================================================================== */ - switch (input_type) { + switch (input_type) + { case VAX_F: unpack_vax_f(input_value, intermediate_value, options); break; @@ -781,7 +787,8 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, ** specified by the output_type parameter. ** ========================================================================== */ - switch (output_type) { + switch (output_type) + { case VAX_F: return_status = pack_vax_f(intermediate_value, output_value, options); break; @@ -834,7 +841,8 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, return return_status; } -static void FlipDouble(int *in) { +static void FlipDouble(int *in) +{ int tmp = in[0]; in[0] = in[1]; in[1] = tmp; @@ -908,16 +916,22 @@ static CVT_STATUS pack_vax_f(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { - if (intermediate_value[U_R_FLAGS] & U_R_ZERO) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { + if (intermediate_value[U_R_FLAGS] & U_R_ZERO) + { memcpy(output_value, VAX_F_ZERO, 4); - } else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { memcpy(output_value, VAX_F_INVALID, 4); if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) RAISE(cvt_s_neg_infinity); else RAISE(cvt_s_pos_infinity); - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, VAX_F_INVALID, 4); RAISE(cvt_s_invalid_value); } @@ -927,14 +941,16 @@ static CVT_STATUS pack_vax_f(UNPACKED_REAL intermediate_value, ** Round the intermediate value at bit position 24. ** ========================================================================== */ - else { + else + { _round(intermediate_value, 24, options); /* ** Check for underflow. ** ======================================================================= */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 127)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 127)) + { memcpy(output_value, VAX_F_ZERO, 4); if (options & CVT_M_ERR_UNDERFLOW) RAISE(cvt_s_underflow); @@ -944,26 +960,34 @@ static CVT_STATUS pack_vax_f(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================= */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 127)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 127)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, VAX_F_NEG_HUGE, 4); - } else { + } + else + { memcpy(output_value, VAX_F_POS_HUGE, 4); } } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_F_NEG_HUGE, 4); } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_F_POS_HUGE, 4); } - else { + else + { memcpy(output_value, VAX_F_INVALID, 4); } @@ -974,7 +998,8 @@ static CVT_STATUS pack_vax_f(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================= */ - else { + else + { /* ** Adjust bias of exponent. **----------------------------------------------------------------------- @@ -1088,10 +1113,14 @@ static CVT_STATUS pack_vax_d(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { - if (intermediate_value[U_R_FLAGS] & U_R_ZERO) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { + if (intermediate_value[U_R_FLAGS] & U_R_ZERO) + { memcpy(output_value, VAX_D_ZERO, 8); - } else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { memcpy(output_value, VAX_D_INVALID, 8); if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) RAISE(cvt_s_neg_infinity); @@ -1099,7 +1128,8 @@ static CVT_STATUS pack_vax_d(UNPACKED_REAL intermediate_value, RAISE(cvt_s_pos_infinity); } - else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, VAX_D_INVALID, 8); RAISE(cvt_s_invalid_value); } @@ -1109,14 +1139,16 @@ static CVT_STATUS pack_vax_d(UNPACKED_REAL intermediate_value, ** Round the intermediate value at bit position 56. ** ========================================================================== */ - else { + else + { _round(intermediate_value, 56, options); /* ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 127)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 127)) + { memcpy(output_value, VAX_D_ZERO, 8); if (options & CVT_M_ERR_UNDERFLOW) RAISE(cvt_s_underflow); @@ -1126,26 +1158,34 @@ static CVT_STATUS pack_vax_d(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 127)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 127)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, VAX_D_NEG_HUGE, 8); - } else { + } + else + { memcpy(output_value, VAX_D_POS_HUGE, 8); } } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_D_NEG_HUGE, 8); } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_D_POS_HUGE, 8); } - else { + else + { memcpy(output_value, VAX_D_INVALID, 8); } RAISE(cvt_s_overflow); @@ -1155,7 +1195,8 @@ static CVT_STATUS pack_vax_d(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -1280,16 +1321,22 @@ static CVT_STATUS pack_vax_g(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { - if (intermediate_value[U_R_FLAGS] & U_R_ZERO) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { + if (intermediate_value[U_R_FLAGS] & U_R_ZERO) + { memcpy(output_value, VAX_G_ZERO, 8); - } else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { memcpy(output_value, VAX_G_INVALID, 8); if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) RAISE(cvt_s_neg_infinity); else RAISE(cvt_s_pos_infinity); - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, VAX_G_INVALID, 8); RAISE(cvt_s_invalid_value); } @@ -1299,14 +1346,16 @@ static CVT_STATUS pack_vax_g(UNPACKED_REAL intermediate_value, ** Round the intermediate value at bit position 53. ** ========================================================================== */ - else { + else + { _round(intermediate_value, 53, options); /* ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 1023)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 1023)) + { memcpy(output_value, VAX_G_ZERO, 8); if (options & CVT_M_ERR_UNDERFLOW) RAISE(cvt_s_underflow); @@ -1316,20 +1365,31 @@ static CVT_STATUS pack_vax_g(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 1023)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 1023)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, VAX_G_NEG_HUGE, 8); - } else { + } + else + { memcpy(output_value, VAX_G_POS_HUGE, 8); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_G_NEG_HUGE, 8); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_G_POS_HUGE, 8); - } else { + } + else + { memcpy(output_value, VAX_G_INVALID, 8); } RAISE(cvt_s_overflow); @@ -1339,7 +1399,8 @@ static CVT_STATUS pack_vax_g(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -1469,16 +1530,22 @@ static CVT_STATUS pack_vax_h(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { - if (intermediate_value[U_R_FLAGS] & U_R_ZERO) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { + if (intermediate_value[U_R_FLAGS] & U_R_ZERO) + { memcpy(output_value, VAX_H_ZERO, 16); - } else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { memcpy(output_value, VAX_H_INVALID, 16); if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) RAISE(cvt_s_neg_infinity); else RAISE(cvt_s_pos_infinity); - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, VAX_H_INVALID, 16); RAISE(cvt_s_invalid_value); } @@ -1488,14 +1555,16 @@ static CVT_STATUS pack_vax_h(UNPACKED_REAL intermediate_value, ** Round the intermediate value at bit position 113. ** ========================================================================== */ - else { + else + { _round(intermediate_value, 113, options); /* ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 16383)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 16383)) + { memcpy(output_value, VAX_H_ZERO, 16); if (options & CVT_M_ERR_UNDERFLOW) RAISE(cvt_s_underflow); @@ -1505,20 +1574,31 @@ static CVT_STATUS pack_vax_h(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 16383)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 16383)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, VAX_H_NEG_HUGE, 16); - } else { + } + else + { memcpy(output_value, VAX_H_POS_HUGE, 16); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_H_NEG_HUGE, 16); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, VAX_H_POS_HUGE, 16); - } else { + } + else + { memcpy(output_value, VAX_H_INVALID, 16); } RAISE(cvt_s_overflow); @@ -1528,7 +1608,8 @@ static CVT_STATUS pack_vax_h(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -1655,23 +1736,32 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { if (intermediate_value[U_R_FLAGS] & U_R_ZERO) - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_S_NEG_ZERO, 4); - } else { + } + else + { memcpy(output_value, IEEE_S_POS_ZERO, 4); } - else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_S_NEG_INFINITY, 4); - } else { + } + else + { memcpy(output_value, IEEE_S_POS_INFINITY, 4); } } - else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, IEEE_S_INVALID, 4); RAISE(cvt_s_invalid_value); } @@ -1682,7 +1772,8 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** round (0 <= i <= 24). ** ========================================================================== */ - else { + else + { round_bit_position = intermediate_value[U_R_EXP] - ((U_R_BIAS - 126) - 23); if (round_bit_position < 0) round_bit_position = 0; @@ -1695,15 +1786,20 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** Check for Denorm or underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 125)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 125)) + { /* ** Value is too small for a denorm, so underflow. ** ---------------------------------------------------------------------- */ - if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 125) - 23)) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 125) - 23)) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_S_NEG_ZERO, 4); - } else { + } + else + { memcpy(output_value, IEEE_S_POS_ZERO, 4); } @@ -1715,7 +1811,8 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** Figure leading zeros for denorm and right-justify fraction ** ---------------------------------------------------------------------- */ - else { + else + { i = 32 - (intermediate_value[U_R_EXP] - ((U_R_BIAS - 126) - 23)); intermediate_value[1] >>= i; @@ -1725,13 +1822,16 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, */ intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); intermediate_value[0] |= ((intermediate_value[1] >> 8) & 0x0000FF00L); memcpy(output_value, intermediate_value, 4); - } else { + } + else + { memcpy(output_value, &intermediate_value[1], 4); } } @@ -1741,23 +1841,37 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 128)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 128)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_S_NEG_HUGE, 4); - } else { + } + else + { memcpy(output_value, IEEE_S_POS_HUGE, 4); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_S_NEG_HUGE, 4); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_S_POS_HUGE, 4); - } else { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + } + else + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_S_NEG_INFINITY, 4); - } else { + } + else + { memcpy(output_value, IEEE_S_POS_INFINITY, 4); } } @@ -1768,7 +1882,8 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -1794,13 +1909,16 @@ static CVT_STATUS pack_ieee_s(UNPACKED_REAL intermediate_value, intermediate_value[1] |= (intermediate_value[U_R_EXP] << 23); intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); intermediate_value[0] |= ((intermediate_value[1] >> 8) & 0x0000FF00L); memcpy(output_value, intermediate_value, 4); - } else { + } + else + { memcpy(output_value, &intermediate_value[1], 4); } } @@ -1886,31 +2004,40 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { if (intermediate_value[U_R_FLAGS] & U_R_ZERO) - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_T_NEG_ZERO, 8); if (flip) FlipDouble((int *)output_value); - } else { + } + else + { memcpy(output_value, IEEE_T_POS_ZERO, 8); if (flip) FlipDouble((int *)output_value); } - else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_T_NEG_INFINITY, 8); if (flip) FlipDouble((int *)output_value); - } else { + } + else + { memcpy(output_value, IEEE_T_POS_INFINITY, 8); if (flip) FlipDouble((int *)output_value); } } - else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, IEEE_T_INVALID, 8); if (flip) FlipDouble((int *)output_value); @@ -1923,7 +2050,8 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** round (0 <= i <= 53). ** ========================================================================== */ - else { + else + { round_bit_position = intermediate_value[U_R_EXP] - ((U_R_BIAS - 1022) - 52); if (round_bit_position < 0) round_bit_position = 0; @@ -1936,17 +2064,22 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** Check for Denorm or underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 1021)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 1021)) + { /* ** Value is too small for a denorm, so underflow. ** ---------------------------------------------------------------------- */ - if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 1021) - 52)) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 1021) - 52)) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_T_NEG_ZERO, 8); if (flip) FlipDouble((int *)output_value); - } else { + } + else + { memcpy(output_value, IEEE_T_POS_ZERO, 8); if (flip) FlipDouble((int *)output_value); @@ -1960,13 +2093,17 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** Figure leading zeros for denorm and right-justify fraction ** ---------------------------------------------------------------------- */ - else { + else + { i = 64 - (intermediate_value[U_R_EXP] - ((U_R_BIAS - 1022) - 52)); - if (i > 31) { + if (i > 31) + { i -= 32; intermediate_value[2] = (intermediate_value[1] >> i); intermediate_value[1] = 0; - } else { + } + else + { intermediate_value[2] >>= i; intermediate_value[2] |= (intermediate_value[1] << (32 - i)); intermediate_value[1] >>= i; @@ -1977,7 +2114,8 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** -------------------------------------------------------------------- */ intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); @@ -1986,7 +2124,9 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ((intermediate_value[2] << 24) | (intermediate_value[2] >> 24)); intermediate_value[1] |= ((intermediate_value[2] << 8) & 0x00FF0000L); intermediate_value[1] |= ((intermediate_value[2] >> 8) & 0x0000FF00L); - } else { + } + else + { intermediate_value[0] = intermediate_value[2]; } memcpy(output_value, intermediate_value, 8); @@ -1999,13 +2139,18 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 1024)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 1024)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_T_NEG_HUGE, 8); if (flip) FlipDouble((int *)output_value); - } else { + } + else + { memcpy(output_value, IEEE_T_POS_HUGE, 8); if (flip) FlipDouble((int *)output_value); @@ -2013,25 +2158,31 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_T_NEG_HUGE, 8); if (flip) FlipDouble((int *)output_value); } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_T_POS_HUGE, 8); if (flip) FlipDouble((int *)output_value); } - else { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_T_NEG_INFINITY, 8); if (flip) FlipDouble((int *)output_value); - } else { + } + else + { memcpy(output_value, IEEE_T_POS_INFINITY, 8); if (flip) FlipDouble((int *)output_value); @@ -2044,7 +2195,8 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -2072,7 +2224,8 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, intermediate_value[1] |= (intermediate_value[U_R_EXP] << 20); intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); @@ -2081,7 +2234,9 @@ static CVT_STATUS pack_ieee_t(UNPACKED_REAL intermediate_value, ((intermediate_value[2] << 24) | (intermediate_value[2] >> 24)); intermediate_value[1] |= ((intermediate_value[2] << 8) & 0x00FF0000L); intermediate_value[1] |= ((intermediate_value[2] >> 8) & 0x0000FF00L); - } else { + } + else + { intermediate_value[0] = intermediate_value[2]; } memcpy(output_value, &intermediate_value[0], 8); @@ -2170,23 +2325,32 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { if (intermediate_value[U_R_FLAGS] & U_R_ZERO) - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_X_NEG_ZERO, 16); - } else { + } + else + { memcpy(output_value, IEEE_X_POS_ZERO, 16); } - else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_X_NEG_INFINITY, 16); - } else { + } + else + { memcpy(output_value, IEEE_X_POS_INFINITY, 16); } } - else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, IEEE_X_INVALID, 16); RAISE(cvt_s_invalid_value); } @@ -2197,7 +2361,8 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** round (0 <= i <= 113). ** ========================================================================== */ - else { + else + { round_bit_position = intermediate_value[U_R_EXP] - ((U_R_BIAS - 16382) - 112); if (round_bit_position < 0) @@ -2211,15 +2376,20 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** Check for Denorm or underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 16381)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 16381)) + { /* ** Value is too small for a denorm, so underflow. ** ---------------------------------------------------------------------- */ - if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 16381) - 112)) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_EXP] < ((U_R_BIAS - 16381) - 112)) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_X_NEG_ZERO, 16); - } else { + } + else + { memcpy(output_value, IEEE_X_POS_ZERO, 16); } @@ -2231,22 +2401,28 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** Figure leading zeros for denorm and right-justify fraction ** ---------------------------------------------------------------------- */ - else { + else + { i = 128 - (intermediate_value[U_R_EXP] - ((U_R_BIAS - 16382) - 112)); - if (i > 95) { + if (i > 95) + { i -= 96; intermediate_value[4] = (intermediate_value[1] >> i); intermediate_value[3] = 0; intermediate_value[2] = 0; intermediate_value[1] = 0; - } else if (i > 63) { + } + else if (i > 63) + { i -= 64; intermediate_value[4] = (intermediate_value[2] >> i); intermediate_value[4] |= (intermediate_value[1] << (32 - i)); intermediate_value[3] = (intermediate_value[1] >> i); intermediate_value[2] = 0; intermediate_value[1] = 0; - } else if (i > 31) { + } + else if (i > 31) + { i -= 32; intermediate_value[4] = (intermediate_value[3] >> i); intermediate_value[4] |= (intermediate_value[2] << (32 - i)); @@ -2254,7 +2430,9 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, intermediate_value[3] |= (intermediate_value[1] << (32 - i)); intermediate_value[2] = (intermediate_value[1] >> i); intermediate_value[1] = 0; - } else { + } + else + { intermediate_value[4] >>= i; intermediate_value[4] |= (intermediate_value[3] << (32 - i)); intermediate_value[3] >>= i; @@ -2269,7 +2447,8 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** -------------------------------------------------------------------- */ intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); @@ -2289,7 +2468,9 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ((intermediate_value[4] << 24) | (intermediate_value[4] >> 24)); intermediate_value[3] |= ((intermediate_value[4] << 8) & 0x00FF0000L); intermediate_value[3] |= ((intermediate_value[4] >> 8) & 0x0000FF00L); - } else { + } + else + { intermediate_value[0] = intermediate_value[3]; intermediate_value[3] = intermediate_value[1]; intermediate_value[1] = intermediate_value[0]; @@ -2303,29 +2484,40 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 16384)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 16384)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_X_NEG_HUGE, 16); - } else { + } + else + { memcpy(output_value, IEEE_X_POS_HUGE, 16); } } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_X_NEG_HUGE, 16); } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IEEE_X_POS_HUGE, 16); } - else { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IEEE_X_NEG_INFINITY, 16); - } else { + } + else + { memcpy(output_value, IEEE_X_POS_INFINITY, 16); } } @@ -2336,7 +2528,8 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust the bias of the exponent. ** ---------------------------------------------------------------------- @@ -2368,7 +2561,8 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, intermediate_value[1] |= (intermediate_value[U_R_EXP] << 16); intermediate_value[1] |= (intermediate_value[U_R_FLAGS] << 31); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { intermediate_value[0] = ((intermediate_value[1] << 24) | (intermediate_value[1] >> 24)); intermediate_value[0] |= ((intermediate_value[1] << 8) & 0x00FF0000L); @@ -2388,7 +2582,9 @@ static CVT_STATUS pack_ieee_x(UNPACKED_REAL intermediate_value, ((intermediate_value[4] << 24) | (intermediate_value[4] >> 24)); intermediate_value[3] |= ((intermediate_value[4] << 8) & 0x00FF0000L); intermediate_value[3] |= ((intermediate_value[4] >> 8) & 0x0000FF00L); - } else { + } + else + { intermediate_value[0] = intermediate_value[3]; intermediate_value[3] = intermediate_value[1]; intermediate_value[1] = intermediate_value[0]; @@ -2476,21 +2672,31 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { if (intermediate_value[U_R_FLAGS] & U_R_ZERO) - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_L_NEG_ZERO, 8); - } else { + } + else + { memcpy(output_value, IBM_L_POS_ZERO, 8); } - else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_L_NEG_INFINITY, 8); - } else { + } + else + { memcpy(output_value, IBM_L_POS_INFINITY, 8); } - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, IBM_L_INVALID, 8); RAISE(cvt_s_invalid_value); } @@ -2502,7 +2708,8 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, ** (53 <= i <= 56). ** ========================================================================== */ - else { + else + { i = (intermediate_value[U_R_EXP] & 0x00000003L); if (i) round_bit_position = i + 52; @@ -2515,14 +2722,18 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 255)) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 255)) + { /* ** Value is too small, so underflow. ** ---------------------------------------------------------------------- */ - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_L_NEG_ZERO, 8); - } else { + } + else + { memcpy(output_value, IBM_L_POS_ZERO, 8); } @@ -2533,27 +2744,41 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 252)) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 252)) + { /* ** Value is too large, so overflow. ** ---------------------------------------------------------------------- */ - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_L_NEG_HUGE, 8); - } else { + } + else + { memcpy(output_value, IBM_L_POS_HUGE, 8); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IBM_L_NEG_HUGE, 8); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IBM_L_POS_HUGE, 8); - } else { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + } + else + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_L_NEG_INFINITY, 8); - } else { + } + else + { memcpy(output_value, IBM_L_POS_INFINITY, 8); } } @@ -2564,7 +2789,8 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Figure leading zeros (i) and biased exponent (j) ** ---------------------------------------------------------------------- @@ -2572,11 +2798,14 @@ static CVT_STATUS pack_ibm_l(UNPACKED_REAL intermediate_value, i = (intermediate_value[U_R_EXP] & 0x00000003L); j = ((int)(intermediate_value[U_R_EXP] - U_R_BIAS) / 4) + 64; - if (i) { + if (i) + { if (intermediate_value[U_R_EXP] > U_R_BIAS) j += 1; i = 12 - i; - } else { + } + else + { i = 8; } @@ -2689,21 +2918,30 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { if (intermediate_value[U_R_FLAGS] & U_R_ZERO) - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_S_NEG_ZERO, 4); - } else { + } + else + { memcpy(output_value, IBM_S_POS_ZERO, 4); } - else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_S_NEG_INFINITY, 4); - } else { + } + else + { memcpy(output_value, IBM_S_POS_INFINITY, 4); } - - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, IBM_S_INVALID, 4); RAISE(cvt_s_invalid_value); } @@ -2715,7 +2953,8 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, ** (21 <= i <=24). ** ========================================================================== */ - else { + else + { i = (intermediate_value[U_R_EXP] & 0x00000003L); if (i) round_bit_position = i + 20; @@ -2728,14 +2967,19 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 255)) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 255)) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_S_NEG_ZERO, 4); - } else { + } + else + { memcpy(output_value, IBM_S_POS_ZERO, 4); } - if (options & CVT_M_ERR_UNDERFLOW) { + if (options & CVT_M_ERR_UNDERFLOW) + { RAISE(cvt_s_underflow); } } @@ -2744,23 +2988,37 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 252)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 252)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_S_NEG_HUGE, 4); - } else { + } + else + { memcpy(output_value, IBM_S_POS_HUGE, 4); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IBM_S_NEG_HUGE, 4); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, IBM_S_POS_HUGE, 4); - } else { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + } + else + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, IBM_S_NEG_INFINITY, 4); - } else { + } + else + { memcpy(output_value, IBM_S_POS_INFINITY, 4); } } @@ -2771,7 +3029,8 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Figure leading zeros (i) and biased exponent (j) ** ---------------------------------------------------------------------- @@ -2779,11 +3038,14 @@ static CVT_STATUS pack_ibm_s(UNPACKED_REAL intermediate_value, i = (intermediate_value[U_R_EXP] & 0x00000003L); j = ((int)(intermediate_value[U_R_EXP] - U_R_BIAS) / 4) + 64; - if (i) { + if (i) + { if (intermediate_value[U_R_EXP] > U_R_BIAS) j += 1; i = 12 - i; - } else { + } + else + { i = 8; } @@ -2896,23 +3158,34 @@ static CVT_STATUS pack_cray(UNPACKED_REAL intermediate_value, ** ie. zero, infinity or invalid numbers. ** ========================================================================== */ - if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) { - if (intermediate_value[U_R_FLAGS] & U_R_ZERO) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_UNUSUAL) + { + if (intermediate_value[U_R_FLAGS] & U_R_ZERO) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, CRAY_NEG_ZERO, 8); - } else { + } + else + { memcpy(output_value, CRAY_POS_ZERO, 8); } } - if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_FLAGS] & U_R_INFINITY) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, CRAY_NEG_INFINITY, 8); RAISE(cvt_s_neg_infinity); - } else { + } + else + { memcpy(output_value, CRAY_POS_INFINITY, 8); RAISE(cvt_s_pos_infinity); } - } else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) { + } + else if (intermediate_value[U_R_FLAGS] & U_R_INVALID) + { memcpy(output_value, CRAY_INVALID, 8); RAISE(cvt_s_invalid_value); } @@ -2922,7 +3195,8 @@ static CVT_STATUS pack_cray(UNPACKED_REAL intermediate_value, ** Round at position 48. ** ========================================================================== */ - else { + else + { round_bit_position = 48; _round(intermediate_value, round_bit_position, options); @@ -2931,14 +3205,19 @@ static CVT_STATUS pack_cray(UNPACKED_REAL intermediate_value, ** Check for underflow. ** ======================================================================== */ - if (intermediate_value[U_R_EXP] < (U_R_BIAS - 8192)) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + if (intermediate_value[U_R_EXP] < (U_R_BIAS - 8192)) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, CRAY_NEG_ZERO, 8); - } else { + } + else + { memcpy(output_value, CRAY_POS_ZERO, 8); } - if (options & CVT_M_ERR_UNDERFLOW) { + if (options & CVT_M_ERR_UNDERFLOW) + { RAISE(cvt_s_underflow); } } @@ -2947,20 +3226,31 @@ static CVT_STATUS pack_cray(UNPACKED_REAL intermediate_value, ** Check for overflow. ** ======================================================================== */ - else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 8191)) { - if (options & CVT_M_TRUNCATE) { - if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) { + else if (intermediate_value[U_R_EXP] > (U_R_BIAS + 8191)) + { + if (options & CVT_M_TRUNCATE) + { + if (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE) + { memcpy(output_value, CRAY_NEG_HUGE, 8); - } else { + } + else + { memcpy(output_value, CRAY_POS_HUGE, 8); } - } else if ((options & CVT_M_ROUND_TO_POS) && - (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_POS) && + (intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, CRAY_NEG_HUGE, 8); - } else if ((options & CVT_M_ROUND_TO_NEG) && - !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) { + } + else if ((options & CVT_M_ROUND_TO_NEG) && + !(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) + { memcpy(output_value, CRAY_POS_HUGE, 8); - } else { + } + else + { memcpy(output_value, CRAY_INVALID, 8); } RAISE(cvt_s_overflow); @@ -2970,7 +3260,8 @@ static CVT_STATUS pack_cray(UNPACKED_REAL intermediate_value, ** Pack up the output value and return it. ** ======================================================================== */ - else { + else + { /* ** Adjust bias of exponent ** ---------------------------------------------------------------------- @@ -3131,7 +3422,8 @@ static void _round(UNPACKED_REAL intermediate_value, ** If we are not going to TRUNCATE the number. ** ========================================================================== */ - if (!(options & CVT_M_TRUNCATE)) { + if (!(options & CVT_M_TRUNCATE)) + { /* ** Determine which word the round bit resides in. @@ -3156,9 +3448,11 @@ static void _round(UNPACKED_REAL intermediate_value, ** Else handle the other rounding options. ** ======================================================================== */ - else { + else + { roundup = 0; - switch (intermediate_value[i] & bit_mask) { + switch (intermediate_value[i] & bit_mask) + { /* ** If round bit is clear, and ROUND TO NEAREST option is selected we @@ -3177,7 +3471,8 @@ static void _round(UNPACKED_REAL intermediate_value, */ default: if (!(more_bits = intermediate_value[i] & (bit_mask - 1))) - switch (i) { + switch (i) + { case 1: more_bits = intermediate_value[2]; MDS_ATTR_FALLTHROUGH @@ -3197,11 +3492,16 @@ static void _round(UNPACKED_REAL intermediate_value, ** round bit is set. ** ---------------------------------------------------------- */ - if (options & CVT_M_ROUND_TO_NEAREST) { - if (!(roundup = more_bits)) { - if (bit_mask << 1) { + if (options & CVT_M_ROUND_TO_NEAREST) + { + if (!(roundup = more_bits)) + { + if (bit_mask << 1) + { roundup = intermediate_value[i] & (bit_mask << 1); - } else { + } + else + { if (i != 1) roundup = intermediate_value[i - 1] & 1; } @@ -3212,7 +3512,8 @@ static void _round(UNPACKED_REAL intermediate_value, ** Check ROUND TO POSITIVE INFINITY option. ** ---------------------------------------------------------- */ - else if (options & CVT_M_ROUND_TO_POS) { + else if (options & CVT_M_ROUND_TO_POS) + { if (!(intermediate_value[U_R_FLAGS] & U_R_NEGATIVE)) roundup = (intermediate_value[i] & bit_mask) | more_bits; } @@ -3230,7 +3531,8 @@ static void _round(UNPACKED_REAL intermediate_value, ** Perform rounding if necessary. ** ======================================================================== */ - if (roundup) { + if (roundup) + { /* ** Add 1 at round position. @@ -3332,7 +3634,8 @@ static void unpack_vax_f(CVT_VAX_F input_value, UNPACKED_REAL output_value, ** a zero value. Set the flag bits accordingly. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { if (output_value[U_R_FLAGS]) output_value[U_R_FLAGS] |= U_R_INVALID; else @@ -3343,7 +3646,8 @@ static void unpack_vax_f(CVT_VAX_F input_value, UNPACKED_REAL output_value, ** Else the exponent is not zero and we will always have a valid number. ** ========================================================================== */ - else { + else + { output_value[1] = ((output_value[1] << 16) | (output_value[1] >> 16)); /* @@ -3455,7 +3759,8 @@ static void unpack_vax_d(CVT_VAX_D input_value, UNPACKED_REAL output_value, ** a zero value. Set the flag bits accordingly. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { if (output_value[U_R_FLAGS]) output_value[U_R_FLAGS] |= U_R_INVALID; else @@ -3466,7 +3771,8 @@ static void unpack_vax_d(CVT_VAX_D input_value, UNPACKED_REAL output_value, ** Else the exponent is not zero and we will always have a valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust for VAX 16 bit floating format. ** ------------------------------------------------------------------------ @@ -3585,7 +3891,8 @@ static void unpack_vax_g(CVT_VAX_G input_value, UNPACKED_REAL output_value, ** a zero value. Set the flag bits accordingly. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { if (output_value[U_R_FLAGS]) output_value[U_R_FLAGS] |= U_R_INVALID; else @@ -3596,7 +3903,8 @@ static void unpack_vax_g(CVT_VAX_G input_value, UNPACKED_REAL output_value, ** Else the exponent is not zero and we will always have a valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust for VAX 16 bit floating format. ** ------------------------------------------------------------------------ @@ -3714,7 +4022,8 @@ static void unpack_vax_h(CVT_VAX_H input_value, UNPACKED_REAL output_value, ** a zero value. Set the flag bits accordingly. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { if (output_value[U_R_FLAGS]) output_value[U_R_FLAGS] |= U_R_INVALID; else @@ -3725,7 +4034,8 @@ static void unpack_vax_h(CVT_VAX_H input_value, UNPACKED_REAL output_value, ** Else the exponent is not zero and we will always have a valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust for VAX 16 bit floating format. ** ------------------------------------------------------------------------ @@ -3826,7 +4136,8 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, ** Initialization. ** ========================================================================== */ - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { memcpy(output_value, input_value, 4); /* @@ -3836,7 +4147,9 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, output_value[1] = ((output_value[0] << 24) | (output_value[0] >> 24)); output_value[1] |= ((output_value[0] << 8) & 0x00FF0000L); output_value[1] |= ((output_value[0] >> 8) & 0x0000FF00L); - } else { + } + else + { memcpy(&output_value[1], input_value, 4); } @@ -3856,7 +4169,8 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, ** Check for denormalized values. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { /* ** Clear sign bit. ** ------------------------------------------------------------------------ @@ -3867,13 +4181,15 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, ** If fraction is non-zero then normalize it. ** ------------------------------------------------------------------------ */ - if (output_value[1] != 0) { + if (output_value[1] != 0) + { /* ** Count leading zeros. ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x00400000L)) { + while (!(output_value[1] & 0x00400000L)) + { output_value[1] <<= 1; i += 1; } @@ -3894,7 +4210,8 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, output_value[4] = 0; } - else { + else + { output_value[U_R_FLAGS] |= U_R_ZERO; } } @@ -3903,7 +4220,8 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, ** Check for NANs and INFINITIES. ** ========================================================================== */ - else if (output_value[U_R_EXP] == 255) { + else if (output_value[U_R_EXP] == 255) + { /* ** Clear sign bit and exponent. ** ------------------------------------------------------------------------ @@ -3919,7 +4237,8 @@ static void unpack_ieee_s(CVT_IEEE_S input_value, UNPACKED_REAL output_value, ** We have ourselves a genuine valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust exponent bias. ** ------------------------------------------------------------------------ @@ -4019,7 +4338,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, memcpy(output_value, input_value, 8); if (flip) FlipDouble((int *)output_value); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { /* ** Shuffle bytes to little endian format. ** ------------------------------------------------------------------------ @@ -4030,7 +4350,9 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, output_value[1] = ((output_value[0] << 24) | (output_value[0] >> 24)); output_value[1] |= ((output_value[0] << 8) & 0x00FF0000L); output_value[1] |= ((output_value[0] >> 8) & 0x0000FF00L); - } else { + } + else + { output_value[2] = output_value[0]; } @@ -4050,7 +4372,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, ** Check for denormalized values. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { /* ** Clear sign bit. ** ------------------------------------------------------------------------ @@ -4061,13 +4384,15 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, ** If fraction is non-zero then normalize it. ** ------------------------------------------------------------------------ */ - if (output_value[1] != 0) { + if (output_value[1] != 0) + { /* ** Count leading zeros in fraction. ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x00080000L)) { + while (!(output_value[1] & 0x00080000L)) + { output_value[1] <<= 1; i += 1; } @@ -4090,7 +4415,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, output_value[4] = 0; } - else if (output_value[2]) { + else if (output_value[2]) + { output_value[1] = output_value[2]; /* @@ -4098,7 +4424,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, ** ---------------------------------------------------------------------- */ i = 20; - while (!(output_value[1] & 0x80000000L)) { + while (!(output_value[1] & 0x80000000L)) + { output_value[1] <<= 1; i += 1; } @@ -4116,7 +4443,9 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, output_value[2] = 0; output_value[3] = 0; output_value[4] = 0; - } else { + } + else + { output_value[U_R_FLAGS] |= U_R_ZERO; } } @@ -4125,7 +4454,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, ** Check for NANs and INFINITIES. ** ========================================================================== */ - else if (output_value[U_R_EXP] == 2047) { + else if (output_value[U_R_EXP] == 2047) + { /* ** Clear sign bit and exponent. ** ------------------------------------------------------------------------ @@ -4142,7 +4472,8 @@ static void unpack_ieee_t(CVT_IEEE_T input_value, UNPACKED_REAL output_value, ** We have ourselves a genuine valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust exponent. ** ------------------------------------------------------------------------ @@ -4240,7 +4571,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, */ memcpy(output_value, input_value, 16); - if (options & CVT_M_BIG_ENDIAN) { + if (options & CVT_M_BIG_ENDIAN) + { /* ** Shuffle bytes to little endian format. ** ------------------------------------------------------------------------ @@ -4260,7 +4592,9 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, output_value[1] = ((output_value[0] << 24) | (output_value[0] >> 24)); output_value[1] |= ((output_value[0] << 8) & 0x00FF0000L); output_value[1] |= ((output_value[0] >> 8) & 0x0000FF00L); - } else { + } + else + { output_value[4] = output_value[0]; output_value[0] = output_value[3]; output_value[3] = output_value[1]; @@ -4283,7 +4617,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** Check for denormalized values. ** ========================================================================== */ - if (output_value[U_R_EXP] == 0) { + if (output_value[U_R_EXP] == 0) + { /* ** Clear sign bit. ** ------------------------------------------------------------------------ @@ -4294,13 +4629,15 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** If fraction is non-zero then normalize it. ** ------------------------------------------------------------------------ */ - if (output_value[1] != 0) { + if (output_value[1] != 0) + { /* ** Count leading zeros in fraction. ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x00008000L)) { + while (!(output_value[1] & 0x00008000L)) + { output_value[1] <<= 1; i += 1; } @@ -4325,7 +4662,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** longword and then normalize it. ** ------------------------------------------------------------------------ */ - else if (output_value[2]) { + else if (output_value[2]) + { output_value[1] = output_value[2]; output_value[2] = output_value[3]; output_value[3] = output_value[4]; @@ -4335,7 +4673,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x80000000L)) { + while (!(output_value[1] & 0x80000000L)) + { output_value[1] <<= 1; i += 1; } @@ -4362,7 +4701,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** longwords and then normalize it. ** ------------------------------------------------------------------------ */ - else if (output_value[3]) { + else if (output_value[3]) + { output_value[1] = output_value[3]; output_value[2] = output_value[4]; @@ -4371,7 +4711,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x80000000L)) { + while (!(output_value[1] & 0x80000000L)) + { output_value[1] <<= 1; i += 1; } @@ -4397,7 +4738,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** longwords and then normalize it. ** ------------------------------------------------------------------------ */ - else if (output_value[4]) { + else if (output_value[4]) + { output_value[1] = output_value[4]; /* @@ -4405,7 +4747,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** ---------------------------------------------------------------------- */ i = 0; - while (!(output_value[1] & 0x80000000L)) { + while (!(output_value[1] & 0x80000000L)) + { output_value[1] <<= 1; i += 1; } @@ -4429,7 +4772,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** Otherwise the fraction is completely zero, so set the zero flag. ** ------------------------------------------------------------------------ */ - else { + else + { output_value[U_R_FLAGS] |= U_R_ZERO; } } @@ -4438,7 +4782,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** Check for NANs and INFINITIES. ** ========================================================================== */ - else if (output_value[U_R_EXP] == 32767) { + else if (output_value[U_R_EXP] == 32767) + { /* ** Clear sign bit and exponent. ** ------------------------------------------------------------------------ @@ -4455,7 +4800,8 @@ static void unpack_ieee_x(CVT_IEEE_X input_value, UNPACKED_REAL output_value, ** We have ourselves a genuine valid number. ** ========================================================================== */ - else { + else + { /* ** Adjust exponent. ** ------------------------------------------------------------------------ @@ -4577,7 +4923,8 @@ static void unpack_ibm_l(CVT_IBM_LONG input_value, UNPACKED_REAL output_value, ** Check if 0. ** ========================================================================== */ - if ((output_value[1] == 0) && (output_value[2] == 0)) { + if ((output_value[1] == 0) && (output_value[2] == 0)) + { output_value[U_R_FLAGS] |= U_R_ZERO; } @@ -4585,7 +4932,8 @@ static void unpack_ibm_l(CVT_IBM_LONG input_value, UNPACKED_REAL output_value, ** Ok, we know that the number is not zero. ** ========================================================================== */ - else { + else + { /* ** Get unbiased hexadecimal exponent and convert it to binary. ** ------------------------------------------------------------------------ @@ -4597,7 +4945,8 @@ static void unpack_ibm_l(CVT_IBM_LONG input_value, UNPACKED_REAL output_value, ** ------------------------------------------------------------------------ */ i = 0; - while (!(output_value[1] & 0x00800000L)) { + while (!(output_value[1] & 0x00800000L)) + { i += 1; if (i > 3) break; @@ -4608,7 +4957,8 @@ static void unpack_ibm_l(CVT_IBM_LONG input_value, UNPACKED_REAL output_value, ** If we have more than three leading zero bits then number is invalid. ** ------------------------------------------------------------------------ */ - if (i > 3) { + if (i > 3) + { output_value[U_R_FLAGS] |= U_R_INVALID; } @@ -4616,7 +4966,8 @@ static void unpack_ibm_l(CVT_IBM_LONG input_value, UNPACKED_REAL output_value, ** Number is valid so far... ** ------------------------------------------------------------------------ */ - else { + else + { /* ** Adjust exponent to compensate for leading zeros. @@ -4734,7 +5085,8 @@ static void unpack_ibm_s(CVT_IBM_SHORT input_value, UNPACKED_REAL output_value, ** Check if 0. ** ========================================================================== */ - if (output_value[1] == 0) { + if (output_value[1] == 0) + { output_value[U_R_FLAGS] |= U_R_ZERO; } @@ -4742,7 +5094,8 @@ static void unpack_ibm_s(CVT_IBM_SHORT input_value, UNPACKED_REAL output_value, ** Ok, we know that the number is not zero. ** ========================================================================== */ - else { + else + { /* ** Get unbiased hexadecimal exponent and convert it to binary. ** ------------------------------------------------------------------------ @@ -4754,7 +5107,8 @@ static void unpack_ibm_s(CVT_IBM_SHORT input_value, UNPACKED_REAL output_value, ** ------------------------------------------------------------------------ */ i = 0; - while (!(output_value[1] & 0x00800000L)) { + while (!(output_value[1] & 0x00800000L)) + { i += 1; if (i > 3) break; @@ -4765,7 +5119,8 @@ static void unpack_ibm_s(CVT_IBM_SHORT input_value, UNPACKED_REAL output_value, ** If we have more than three leading zero bits then number is invalid. ** ------------------------------------------------------------------------ */ - if (i > 3) { + if (i > 3) + { output_value[U_R_FLAGS] |= U_R_INVALID; } @@ -4773,7 +5128,8 @@ static void unpack_ibm_s(CVT_IBM_SHORT input_value, UNPACKED_REAL output_value, ** Number is valid so far... ** ------------------------------------------------------------------------ */ - else { + else + { /* ** Adjust exponent to compensate for leading zeros. @@ -4899,11 +5255,14 @@ static void unpack_cray(CVT_CRAY input_value, UNPACKED_REAL output_value, ** Check if 0 or an invalid exponent. ** ========================================================================== */ - if ((output_value[1] == 0) && (output_value[2] == 0)) { + if ((output_value[1] == 0) && (output_value[2] == 0)) + { output_value[U_R_FLAGS] |= U_R_ZERO; - } else if ((output_value[U_R_EXP] < 0x2000) || - (output_value[U_R_EXP] >= 0x6000) || - (!(output_value[1] & 0x00008000L))) { + } + else if ((output_value[U_R_EXP] < 0x2000) || + (output_value[U_R_EXP] >= 0x6000) || + (!(output_value[1] & 0x00008000L))) + { output_value[U_R_FLAGS] |= U_R_INVALID; } @@ -4911,7 +5270,8 @@ static void unpack_cray(CVT_CRAY input_value, UNPACKED_REAL output_value, ** Ok, we know that the number is not zero. ** ========================================================================== */ - else { + else + { /* ** Adjust bias. ** ------------------------------------------------------------------------ diff --git a/tdishr/DummyRoutines.c b/tdishr/DummyRoutines.c index 842ff5d5d3..876432e6b2 100644 --- a/tdishr/DummyRoutines.c +++ b/tdishr/DummyRoutines.c @@ -23,10 +23,11 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#define dummy(a) \ - int a() { \ - printf("Routine %s not implemented yet\n", #a); \ - return 0; \ +#define dummy(a) \ + int a() \ + { \ + printf("Routine %s not implemented yet\n", #a); \ + return 0; \ } /* dummy(LibConvertDateString) */ dummy(LibFindVmZone) dummy(LibShowVmZone) diff --git a/tdishr/IsRoprand.c b/tdishr/IsRoprand.c index 335ae159b3..9dee81e352 100644 --- a/tdishr/IsRoprand.c +++ b/tdishr/IsRoprand.c @@ -41,9 +41,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define t_float_exp(val) (((*(int64_t *)val) >> 52) & 0x7ff) #define IsRoprandT(val) (t_float_exp(val) == 2047) -EXPORT int IsRoprand(int dtype, void *value) { +EXPORT int IsRoprand(int dtype, void *value) +{ int ans = 0; - switch (dtype) { + switch (dtype) + { case DTYPE_F: ans = IsRoprandF(value); break; diff --git a/tdishr/TdiAbs.c b/tdishr/TdiAbs.c index 17b553762e..c00d333a20 100644 --- a/tdishr/TdiAbs.c +++ b/tdishr/TdiAbs.c @@ -85,147 +85,171 @@ extern int CvtConvertFloat(); static const int roprand = 0x8000; -#define start_operate(type) \ - { \ - type *in = (type *)(in_ptr->pointer); \ - type *out = (type *)(out_ptr->pointer); \ - for (i = 0; i < out_count; i++) { - -#define start_operate1(itype, otype) \ - { \ - itype *in = (itype *)(in_ptr->pointer); \ - otype *out = (otype *)(out_ptr->pointer); \ - for (i = 0; i < out_count; i++) { - -#define start_operate2(type) \ - { \ - type *out = (type *)(out_ptr->pointer); \ - for (i = 0; i < out_count; i++) { - -#define end_operate \ - } \ - break; \ +#define start_operate(type) \ + { \ + type *in = (type *)(in_ptr->pointer); \ + type *out = (type *)(out_ptr->pointer); \ + for (i = 0; i < out_count; i++) \ + { + +#define start_operate1(itype, otype) \ + { \ + itype *in = (itype *)(in_ptr->pointer); \ + otype *out = (otype *)(out_ptr->pointer); \ + for (i = 0; i < out_count; i++) \ + { + +#define start_operate2(type) \ + { \ + type *out = (type *)(out_ptr->pointer); \ + for (i = 0; i < out_count; i++) \ + { + +#define end_operate \ + } \ + break; \ } -#define AbsFloat(dtype) \ - double tmp; \ - if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - tmp = tmp > 0 ? tmp : -tmp; \ - CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ - } else \ +#define AbsFloat(dtype) \ + double tmp; \ + if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + tmp = tmp > 0 ? tmp : -tmp; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); -#define UnaryMinusFloat(dtype) \ - double tmp; \ - if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - tmp = -tmp; \ - CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ - } else \ +#define UnaryMinusFloat(dtype) \ + double tmp; \ + if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + tmp = -tmp; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); -#define UnaryMinusComplex(dtype) \ - double tmp; \ - if (CvtConvertFloat(&in[i * 2], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - tmp = -tmp; \ - CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i * 2], dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, &out[i * 2], dtype, 0); \ - if (CvtConvertFloat(&in[i * 2 + 1], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - tmp = -tmp; \ - CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i * 2 + 1], dtype, 0); \ - } else \ +#define UnaryMinusComplex(dtype) \ + double tmp; \ + if (CvtConvertFloat(&in[i * 2], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + tmp = -tmp; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i * 2], dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, &out[i * 2], dtype, 0); \ + if (CvtConvertFloat(&in[i * 2 + 1], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + tmp = -tmp; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, &out[i * 2 + 1], dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, &out[i * 2 + 1], dtype, 0); -#define NintFloat(dtype) \ - double tmp; \ - if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - out[i] = (int)(tmp + (tmp > 0 ? .5 : -.5)); \ - } else \ +#define NintFloat(dtype) \ + double tmp; \ + if (CvtConvertFloat(&in[i], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + out[i] = (int)(tmp + (tmp > 0 ? .5 : -.5)); \ + } \ + else \ out[i] = 0; -#define NintComplex(dtype) \ - double tmp; \ - if (CvtConvertFloat(&in[i * 2], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) { \ - out[i] = (int)(tmp + (tmp > 0 ? .5 : -.5)); \ - } else \ +#define NintComplex(dtype) \ + double tmp; \ + if (CvtConvertFloat(&in[i * 2], dtype, &tmp, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + out[i] = (int)(tmp + (tmp > 0 ? .5 : -.5)); \ + } \ + else \ out[i] = 0; -#define AbssqComplex(dtype) \ - double r; \ - double imag; \ - double ans; \ - if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) { \ - ans = r * r + imag * imag; \ - CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ - } else \ +#define AbssqComplex(dtype) \ + double r; \ + double imag; \ + double ans; \ + if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + ans = r * r + imag * imag; \ + CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); -#define ConjgComplex(dtype) \ - double imag; \ - double ans; \ - memcpy(&out[i * 2], &in[i * 2], sizeof(in[i * 2])); \ - if (CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) { \ - ans = -imag; \ - CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i * 2 + 1], dtype, 0); \ - } else \ +#define ConjgComplex(dtype) \ + double imag; \ + double ans; \ + memcpy(&out[i * 2], &in[i * 2], sizeof(in[i * 2])); \ + if (CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + ans = -imag; \ + CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i * 2 + 1], dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, &out[i * 2 + 1], dtype, 0); -#define AbsComplex(dtype) \ - double r; \ - double imag; \ - double mx; \ - double mn; \ - double ans; \ - int bad = 0; \ - if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) { \ - r = r > 0 ? r : -r; \ - imag = imag > 0 ? imag : -imag; \ - mx = r > imag ? r : imag; \ - mn = r <= imag ? r : imag; \ - if (mx > 0) \ - ans = mx * sqrt((mn * mn) / (mx * mx) + 1.); \ - else \ - ans = 0.0; \ - } else \ - bad = 1; \ - if (bad) \ - CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); \ - else \ +#define AbsComplex(dtype) \ + double r; \ + double imag; \ + double mx; \ + double mn; \ + double ans; \ + int bad = 0; \ + if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + r = r > 0 ? r : -r; \ + imag = imag > 0 ? imag : -imag; \ + mx = r > imag ? r : imag; \ + mn = r <= imag ? r : imag; \ + if (mx > 0) \ + ans = mx * sqrt((mn * mn) / (mx * mx) + 1.); \ + else \ + ans = 0.0; \ + } \ + else \ + bad = 1; \ + if (bad) \ + CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); \ + else \ CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); -#define Abs1Complex(dtype) \ - double r; \ - double imag; \ - double ans; \ - int bad = 0; \ - if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) { \ - r = r > 0 ? r : -r; \ - imag = imag > 0 ? imag : -imag; \ - ans = r + imag; \ - } else \ - bad = 1; \ - if (bad) \ - CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); \ - else \ +#define Abs1Complex(dtype) \ + double r; \ + double imag; \ + double ans; \ + int bad = 0; \ + if (CvtConvertFloat(&in[i * 2], dtype, &r, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in[i * 2 + 1], dtype, &imag, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + r = r > 0 ? r : -r; \ + imag = imag > 0 ? imag : -imag; \ + ans = r + imag; \ + } \ + else \ + bad = 1; \ + if (bad) \ + CvtConvertFloat(&roprand, DTYPE_F, &out[i], dtype, 0); \ + else \ CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, &out[i], dtype, 0); int MthJNINT(); int MthJIGNNT(); -int Tdi3Abs(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Abs(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: start_operate(uint8_t) out[i] = in[i]; end_operate case DTYPE_WU : start_operate(uint16_t) out[i] = in[i]; @@ -259,17 +283,18 @@ int Tdi3Abs(struct descriptor *in_ptr, struct descriptor *out_ptr) { return status; } -int Tdi3Abs1(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Abs1(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: start_operate(uint8_t) out[i] = in[i]; end_operate case DTYPE_WU : start_operate(uint16_t) out[i] = in[i]; @@ -303,17 +328,18 @@ int Tdi3Abs1(struct descriptor *in_ptr, struct descriptor *out_ptr) { return status; } -int Tdi3AbsSq(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3AbsSq(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: case DTYPE_WU: case DTYPE_LU: @@ -343,17 +369,18 @@ int Tdi3AbsSq(struct descriptor *in_ptr, struct descriptor *out_ptr) { return status; } -int Tdi3Aimag(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Aimag(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_B: case DTYPE_BU: start_operate2(int8_t) out[i] = 0; @@ -386,15 +413,16 @@ int Tdi3Aimag(struct descriptor *in_ptr, struct descriptor *out_ptr) { return status; } -int Tdi3Conjg(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Conjg(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; - switch (in_ptr->dtype) { + if (STATUS_NOT_OK) + return status; + switch (in_ptr->dtype) + { case DTYPE_BU: case DTYPE_B: start_operate(uint8_t) out[i] = in[i]; @@ -421,15 +449,16 @@ int Tdi3Conjg(struct descriptor *in_ptr, struct descriptor *out_ptr) { return status; } -int Tdi3Inot(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Inot(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; - switch (in_ptr->dtype) { + if (STATUS_NOT_OK) + return status; + switch (in_ptr->dtype) + { case DTYPE_B: case DTYPE_BU: start_operate(uint8_t) out[i] = ~in[i]; @@ -449,15 +478,16 @@ int Tdi3Inot(struct descriptor *in_ptr, struct descriptor *out_ptr) { int Tdi3Logical(struct descriptor *in_ptr, struct descriptor *kind __attribute__((unused)), - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; - switch (in_ptr->dtype) { + if (STATUS_NOT_OK) + return status; + switch (in_ptr->dtype) + { case DTYPE_B: case DTYPE_BU: start_operate1(uint8_t, uint8_t) out[i] = (uint8_t)(1 & in[i]); @@ -474,15 +504,16 @@ int Tdi3Logical(struct descriptor *in_ptr, return status; } -int Tdi3Not(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Not(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; - switch (in_ptr->dtype) { + if (STATUS_NOT_OK) + return status; + switch (in_ptr->dtype) + { case DTYPE_B: case DTYPE_BU: start_operate1(uint8_t, uint8_t) out[i] = (uint8_t) !(in[i] & 1); @@ -503,17 +534,18 @@ int Tdi3Not(struct descriptor *in_ptr, struct descriptor *out_ptr) { int Tdi3Nint(struct descriptor *in_ptr, struct descriptor *kind __attribute__((unused)), - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: start_operate(uint8_t) out[i] = in[i]; end_operate case DTYPE_WU : start_operate(uint16_t) out[i] = in[i]; @@ -547,17 +579,18 @@ int Tdi3Nint(struct descriptor *in_ptr, return status; } -int Tdi3UnaryMinus(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3UnaryMinus(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int out_count = 1; register int i; status = TdiUnary(in_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: start_operate(int8_t) out[i] = -in[i]; end_operate case DTYPE_WU : start_operate(int16_t) out[i] = -in[i]; diff --git a/tdishr/TdiAdd.c b/tdishr/TdiAdd.c index 5201a4cd46..3dfaaf13f2 100644 --- a/tdishr/TdiAdd.c +++ b/tdishr/TdiAdd.c @@ -62,221 +62,248 @@ int Tdi3Add(struct descriptor *in1, struct descriptor *in2, struct descriptor extern int CvtConvertFloat(); -#define SetupArgs \ - struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ - struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - unsigned int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina1->arsize / ina1->length < nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in2->class) { \ - case CLASS_S: \ - case CLASS_D: \ - if (scalars && (nout > 1)) \ - return TdiINV_SIZE; \ - scalars |= 2; \ - break; \ - case CLASS_A: \ - if (ina2->arsize / ina2->length < nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ +#define SetupArgs \ + struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ + struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + unsigned int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina1->arsize / ina1->length < nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in2->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + if (scalars && (nout > 1)) \ + return TdiINV_SIZE; \ + scalars |= 2; \ + break; \ + case CLASS_A: \ + if (ina2->arsize / ina2->length < nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ } -#define Operate(type, operator) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) \ - *outp++ = (type)(*in1p++ operator*in2p++); \ - break; \ - case 1: { \ - type scalar = *in1p; \ - while (nout--) \ - *outp++ = (type)(scalar operator*in2p++); \ - } break; \ - case 2: { \ - type scalar = *in2p; \ - while (nout--) \ - *outp++ = (type)(*in1p++ operator scalar); \ - } break; \ - } \ - break; \ +#define Operate(type, operator) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + *outp++ = (type)(*in1p++ operator*in2p++); \ + break; \ + case 1: \ + { \ + type scalar = *in1p; \ + while (nout--) \ + *outp++ = (type)(scalar operator*in2p++); \ + } \ + break; \ + case 2: \ + { \ + type scalar = *in2p; \ + while (nout--) \ + *outp++ = (type)(*in1p++ operator scalar); \ + } \ + break; \ + } \ + break; \ } static const int roprand = 0x8000; -#define OperateFloatOne(type, dtype, native, operator, p1, p2) \ - { \ - type a, b, ans; \ - type p1v = *p1; \ - type p2v = *p2; \ - if (IsRoprand(dtype, &p1v) || IsRoprand(dtype, &p2v)) \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - else { \ - if (dtype == native) \ - *outp++ = p1v operator p2v; \ - else { \ - if (CvtConvertFloat(&p1v, dtype, &a, native, 0) && \ - CvtConvertFloat(&p2v, dtype, &b, native, 0)) { \ - ans = a operator b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - } \ - } \ +#define OperateFloatOne(type, dtype, native, operator, p1, p2) \ + { \ + type a, b, ans; \ + type p1v = *p1; \ + type p2v = *p2; \ + if (IsRoprand(dtype, &p1v) || IsRoprand(dtype, &p2v)) \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + else \ + { \ + if (dtype == native) \ + *outp++ = p1v operator p2v; \ + else \ + { \ + if (CvtConvertFloat(&p1v, dtype, &a, native, 0) && \ + CvtConvertFloat(&p2v, dtype, &b, native, 0)) \ + { \ + ans = a operator b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + } \ + } \ } -#define OperateFloat(type, dtype, native, operator) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) \ - OperateFloatOne(type, dtype, native, operator, in1p++, in2p++) break; \ - case 1: \ - while (nout--) \ - OperateFloatOne(type, dtype, native, operator, in1p, in2p++) break; \ - case 2: \ - while (nout--) \ - OperateFloatOne(type, dtype, native, operator, in1p++, in2p) break; \ - } \ - break; \ +#define OperateFloat(type, dtype, native, operator) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + OperateFloatOne(type, dtype, native, operator, in1p++, in2p++) break; \ + case 1: \ + while (nout--) \ + OperateFloatOne(type, dtype, native, operator, in1p, in2p++) break; \ + case 2: \ + while (nout--) \ + OperateFloatOne(type, dtype, native, operator, in1p++, in2p) break; \ + } \ + break; \ } -#define OperateComplexOne(type, dtype, native, operator) \ - OperateFloatOne(type, dtype, native, operator, &in1p[0], &in2p[0]) \ +#define OperateComplexOne(type, dtype, native, operator) \ + OperateFloatOne(type, dtype, native, operator, &in1p[0], &in2p[0]) \ OperateFloatOne(type, dtype, native, operator, &in1p[1], &in2p[1]) -#define OperateComplex(type, dtype, native, operator) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - OperateComplexOne(type, dtype, native, operator) in1p += 2; \ - in2p += 2; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - OperateComplexOne(type, dtype, native, operator) in2p += 2; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - OperateComplexOne(type, dtype, native, operator) in1p += 2; \ - } \ - break; \ - } \ - break; \ +#define OperateComplex(type, dtype, native, operator) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + OperateComplexOne(type, dtype, native, operator) in1p += 2; \ + in2p += 2; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + OperateComplexOne(type, dtype, native, operator) in2p += 2; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + OperateComplexOne(type, dtype, native, operator) in1p += 2; \ + } \ + break; \ + } \ + break; \ } -#define MultiplyComplexOne(type, dtype, native, operator) \ - { \ - type a, ai, b, bi, ans, ansi; \ - if (CvtConvertFloat(&in1p[0], dtype, &a, native, 0) && \ - CvtConvertFloat(&in1p[1], dtype, &ai, native, 0) && \ - CvtConvertFloat(&in2p[0], dtype, &b, native, 0) && \ - CvtConvertFloat(&in2p[1], dtype, &bi, native, 0)) { \ - ans = a * b - ai * bi; \ - ansi = a * bi + ai * b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - CvtConvertFloat(&ansi, native, outp++, dtype, 0); \ - } else { \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - } \ +#define MultiplyComplexOne(type, dtype, native, operator) \ + { \ + type a, ai, b, bi, ans, ansi; \ + if (CvtConvertFloat(&in1p[0], dtype, &a, native, 0) && \ + CvtConvertFloat(&in1p[1], dtype, &ai, native, 0) && \ + CvtConvertFloat(&in2p[0], dtype, &b, native, 0) && \ + CvtConvertFloat(&in2p[1], dtype, &bi, native, 0)) \ + { \ + ans = a * b - ai * bi; \ + ansi = a * bi + ai * b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + CvtConvertFloat(&ansi, native, outp++, dtype, 0); \ + } \ + else \ + { \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + } \ } -#define MultiplyComplex(type, dtype, native) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - MultiplyComplexOne(type, dtype, native, operator) in1p += 2; \ - in2p += 2; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - MultiplyComplexOne(type, dtype, native, operator) in2p += 2; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - MultiplyComplexOne(type, dtype, native, operator) in1p += 2; \ - } \ - break; \ - } \ - break; \ +#define MultiplyComplex(type, dtype, native) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + MultiplyComplexOne(type, dtype, native, operator) in1p += 2; \ + in2p += 2; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + MultiplyComplexOne(type, dtype, native, operator) in2p += 2; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + MultiplyComplexOne(type, dtype, native, operator) in1p += 2; \ + } \ + break; \ + } \ + break; \ } -#define Operate128(type, routine) \ - { \ - type##_t *in1p = (type##_t *)in1->pointer; \ - type##_t *in2p = (type##_t *)in2->pointer; \ - type##_t *outp = (type##_t *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) \ - type##_##routine(in1p++, in2p++, outp++); \ - break; \ - case 1: \ - while (nout--) \ - type##_##routine(in1p, in2p++, outp++); \ - break; \ - case 2: \ - while (nout--) \ - type##_##routine(in1p++, in2p, outp++); \ - break; \ - } \ - break; \ +#define Operate128(type, routine) \ + { \ + type##_t *in1p = (type##_t *)in1->pointer; \ + type##_t *in2p = (type##_t *)in2->pointer; \ + type##_t *outp = (type##_t *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + type##_##routine(in1p++, in2p++, outp++); \ + break; \ + case 1: \ + while (nout--) \ + type##_##routine(in1p, in2p++, outp++); \ + break; \ + case 2: \ + while (nout--) \ + type##_##routine(in1p++, in2p, outp++); \ + break; \ + } \ + break; \ } int Tdi3Add(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, +) case DTYPE_BU : Operate(uint8_t, +) case DTYPE_W : Operate(uint16_t, +) case DTYPE_WU : Operate(uint16_t, +) case DTYPE_L @@ -300,8 +327,10 @@ int Tdi3Add(struct descriptor *in1, struct descriptor *in2, } int Tdi3Subtract(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, -) case DTYPE_BU : Operate(uint8_t, -) case DTYPE_W : Operate(uint16_t, -) case DTYPE_WU : Operate(uint16_t, -) case DTYPE_L @@ -325,8 +354,10 @@ int Tdi3Subtract(struct descriptor *in1, struct descriptor *in2, } int Tdi3Multiply(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, *) case DTYPE_BU : Operate(uint8_t, *) case DTYPE_W : Operate(uint16_t, *) case DTYPE_WU : Operate(uint16_t, *) case DTYPE_L @@ -349,14 +380,17 @@ int Tdi3Multiply(struct descriptor *in1, struct descriptor *in2, return 1; } -int TdiMultiplyOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) { +int TdiMultiplyOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) +{ return int128_mul((int128_t *)a, (int128_t *)b, (int128_t *)ans); } -int TdiAddOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) { +int TdiAddOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) +{ return int128_add((int128_t *)a, (int128_t *)b, (int128_t *)ans); } -int TdiSubtractOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) { +int TdiSubtractOctaword(unsigned int *a, unsigned int *b, unsigned int *ans) +{ return int128_sub((int128_t *)a, (int128_t *)b, (int128_t *)ans); } diff --git a/tdishr/TdiAnd.c b/tdishr/TdiAnd.c index 11718e8437..6de2426063 100644 --- a/tdishr/TdiAnd.c +++ b/tdishr/TdiAnd.c @@ -79,8 +79,10 @@ int Tdi3And(struct descriptor *in1, struct descriptor *in2, struct descriptor static inline int Operate(struct descriptor *in1, struct descriptor *in2, struct descriptor *out, - char operator(const char, const char)) { - if (in1->dtype != 2) { + char operator(const char, const char)) +{ + if (in1->dtype != 2) + { fprintf( stderr, "FATAL: TdiAnd.c function called with other than DTYPE_BU (%d,%d)\n", @@ -92,7 +94,8 @@ static inline int Operate(struct descriptor *in1, struct descriptor *in2, struct descriptor_a *outa = (struct descriptor_a *)out; int scalars = 0; unsigned int nout; - switch (out->class) { + switch (out->class) + { case CLASS_S: case CLASS_D: nout = 1; @@ -105,7 +108,8 @@ static inline int Operate(struct descriptor *in1, struct descriptor *in2, default: return TdiINVCLADSC; } - switch (in1->class) { + switch (in1->class) + { case CLASS_S: case CLASS_D: scalars |= 1; @@ -117,7 +121,8 @@ static inline int Operate(struct descriptor *in1, struct descriptor *in2, default: return TdiINVCLADSC; } - switch (in2->class) { + switch (in2->class) + { case CLASS_S: case CLASS_D: if (scalars && (nout > 1)) @@ -134,7 +139,8 @@ static inline int Operate(struct descriptor *in1, struct descriptor *in2, char *in1p = (char *)in1->pointer; char *in2p = (char *)in2->pointer; char *outp = (char *)out->pointer; - switch (scalars) { + switch (scalars) + { case 0: while (nout--) *outp++ = operator(*in1p++, *in2p++); @@ -154,74 +160,94 @@ static inline int Operate(struct descriptor *in1, struct descriptor *in2, return MDSplusSUCCESS; } -static inline char and (const char a, const char b) { +static inline char and (const char a, const char b) +{ return (char)(1 & (a & b)); } -static inline char nand(const char a, const char b) { +static inline char nand(const char a, const char b) +{ return (char)(1 & ~(a & b)); } -static inline char and_not(const char a, const char b) { +static inline char and_not(const char a, const char b) +{ return (char)(1 & (a & ~b)); } -static inline char nand_not(const char a, const char b) { +static inline char nand_not(const char a, const char b) +{ return (char)(1 & ~(a & ~b)); } -static inline char or (const char a, const char b) { +static inline char or (const char a, const char b) +{ return (char)(1 & (a | b)); } -static inline char nor(const char a, const char b) { +static inline char nor(const char a, const char b) +{ return (char)(1 & ~(a | b)); } -static inline char or_not(const char a, const char b) { +static inline char or_not(const char a, const char b) +{ return (char)(1 & (a | ~b)); } -static inline char nor_not(const char a, const char b) { +static inline char nor_not(const char a, const char b) +{ return (char)(1 & ~(a | ~b)); } -static inline char eqv(const char a, const char b) { +static inline char eqv(const char a, const char b) +{ return (char)(1 & (a ^ ~b)); } -static inline char neqv(const char a, const char b) { +static inline char neqv(const char a, const char b) +{ return (char)(1 & (a ^ b)); } int Tdi3And(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, and); } int Tdi3Nand(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, nand); } int Tdi3AndNot(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, and_not); } int Tdi3NandNot(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, nand_not); } int Tdi3Or(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, or); } int Tdi3Nor(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, nor); } int Tdi3OrNot(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, or_not); } int Tdi3NorNot(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, nor_not); } int Tdi3Eqv(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, eqv); } int Tdi3Neqv(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ return Operate(in1, in2, out, neqv); } diff --git a/tdishr/TdiApd.c b/tdishr/TdiApd.c index 0ecb095d4c..86dbdadf2f 100644 --- a/tdishr/TdiApd.c +++ b/tdishr/TdiApd.c @@ -38,7 +38,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int TdiData(); extern int TdiEvaluate(); -int unwrapCommaCount(int ndesc, struct descriptor *list[]) { +int unwrapCommaCount(int ndesc, struct descriptor *list[]) +{ if (list[0] && list[0]->class == CLASS_R && list[0]->dtype == DTYPE_FUNCTION && list[0]->length == 2 && *(short *)list[0]->pointer == OPC_COMMA) @@ -49,7 +50,8 @@ int unwrapCommaCount(int ndesc, struct descriptor *list[]) { } int UnwrapCommaDesc(int ndesc, struct descriptor *list[], int *nout, - struct descriptor *list_out[]) { + struct descriptor *list_out[]) +{ INIT_STATUS; struct descriptor_xd xd = EMPTY_XD; if (list[0] && list[0]->class == CLASS_R && @@ -58,13 +60,15 @@ int UnwrapCommaDesc(int ndesc, struct descriptor *list[], int *nout, status = UnwrapCommaDesc(((struct descriptor_r *)list[0])->ndesc, ((struct descriptor_r *)list[0])->dscptrs, nout, list_out); - else { + else + { status = TdiData(list[0], &xd MDS_END_ARG); - if - STATUS_OK list_out[(*nout)++] = xd.pointer; + if (STATUS_OK) + list_out[(*nout)++] = xd.pointer; } int i; - for (i = 1; STATUS_OK && i < ndesc; i++) { + for (i = 1; STATUS_OK && i < ndesc; i++) + { xd.pointer = NULL; status = TdiEvaluate(list[i], &xd MDS_END_ARG); list_out[(*nout)++] = xd.pointer; @@ -73,23 +77,25 @@ int UnwrapCommaDesc(int ndesc, struct descriptor *list[], int *nout, } int UnwrapComma(int narg, struct descriptor *list[], int *nout_p, - struct descriptor **list_ptr[]) { + struct descriptor **list_ptr[]) +{ *nout_p = unwrapCommaCount(narg, list); int nout = 0; *list_ptr = malloc(*nout_p * sizeof(void *)); int status = UnwrapCommaDesc(narg, list, &nout, *list_ptr); - if - STATUS_NOT_OK { - int i; - for (i = 0; i < nout; i++) - free((*list_ptr)[i]); - free(*list_ptr); - } + if (STATUS_NOT_OK) + { + int i; + for (i = 0; i < nout; i++) + free((*list_ptr)[i]); + free(*list_ptr); + } return status; } int Tdi1Apd(int dtype, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ struct descriptor_a arr = {sizeof(void *), (unsigned char)(dtype & 0xff), CLASS_APD, @@ -104,29 +110,37 @@ int Tdi1Apd(int dtype, int narg, struct descriptor *list[], struct descriptor **alist, **olist; int osize, asize, alen; int status = UnwrapComma(narg, list, &alen, &alist); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; asize = (alen - 1) * sizeof(void *); struct descriptor_a *oarr = (struct descriptor_a *)alist[0]; - if (oarr && oarr->dtype) { - if (oarr->class != CLASS_APD || oarr->length != sizeof(void *)) { + if (oarr && oarr->dtype) + { + if (oarr->class != CLASS_APD || oarr->length != sizeof(void *)) + { status = ApdAPD_APPEND; goto free_alist; } osize = oarr->arsize; olist = (struct descriptor **)oarr->pointer; - } else { + } + else + { osize = 0; olist = NULL; } - if (arr.dtype == DTYPE_DICTIONARY) { - if (!(alen & 1 || (osize / arr.length) & 1)) { + if (arr.dtype == DTYPE_DICTIONARY) + { + if (!(alen & 1 || (osize / arr.length) & 1)) + { status = ApdDICT_KEYVALPAIR; goto free_alist; } int i; - for (i = 1; i < alen; i += 2) { - if (alist[i]->class != CLASS_S) { + for (i = 1; i < alen; i += 2) + { + if (alist[i]->class != CLASS_S) + { status = ApdDICT_KEYCLS; goto free_alist; } @@ -148,14 +162,17 @@ free_alist:; } int Tdi1List(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ return Tdi1Apd(DTYPE_LIST, narg, list, out_ptr); } int Tdi1Tuple(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ return Tdi1Apd(DTYPE_TUPLE, narg, list, out_ptr); } int Tdi1Dict(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ return Tdi1Apd(DTYPE_DICTIONARY, narg, list, out_ptr); } diff --git a/tdishr/TdiArray.c b/tdishr/TdiArray.c index 6a16ce351e..872f0932d4 100644 --- a/tdishr/TdiArray.c +++ b/tdishr/TdiArray.c @@ -66,46 +66,57 @@ extern int CvtConvertFloat(); #include #include -inline int tdi_n_elements(const mdsdsc_t *const dsc_ptr, int *const status) { +inline int tdi_n_elements(const mdsdsc_t *const dsc_ptr, int *const status) +{ int count; if (dsc_ptr->dtype == DTYPE_MISSING) count = 0; - else { - switch (dsc_ptr->class) { - default: { + else + { + switch (dsc_ptr->class) + { + default: + { count = 0; *status = TdiINVCLADSC; - } break; - case CLASS_A: { + } + break; + case CLASS_A: + { array_coeff *aptr = (array_coeff *)dsc_ptr; - if (aptr->length != 0) { + if (aptr->length != 0) + { count = aptr->arsize / aptr->length; - } else if (aptr->dtype == DTYPE_T && aptr->aflags.coeff == 1 && - aptr->dimct > 0) { + } + else if (aptr->dtype == DTYPE_T && aptr->aflags.coeff == 1 && + aptr->dimct > 0) + { count = aptr->m[0]; int i; for (i = 1; i < aptr->dimct; i++) count *= aptr->m[i]; - } else + } + else count = 0; - } break; + } + break; case CLASS_S: - case CLASS_D: { + case CLASS_D: + { count = 1; - } break; + } + break; } } return count; } extern int Tdi1Array(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; - array_coeff arr = {1, DTYPE_B, CLASS_A, (char *)0, 0, - 0, {0, 1, 1, 1, 0}, MAX_DIMS, 0, 0, - {0}}; - array_int cvt = {sizeof(int), DTYPE_L, CLASS_A, (int *)0, 0, - 0, {0, 1, 1, 0, 0}, 1, 0}; + array_coeff arr = {1, DTYPE_B, CLASS_A, (char *)0, 0, 0, {0, 1, 1, 1, 0}, MAX_DIMS, 0, 0, {0}}; + array_int cvt = {sizeof(int), DTYPE_L, CLASS_A, (int *)0, 0, 0, {0, 1, 1, 0, 0}, 1, 0}; struct TdiFunctionStruct *fun_ptr = (struct TdiFunctionStruct *)&TdiRefFunction[opcode]; struct descriptor_xd tmp = EMPTY_XD; @@ -118,80 +129,91 @@ extern int Tdi1Array(opcode_t opcode, int narg, struct descriptor *list[], ****************************************/ if (narg <= 0 || list[0] == 0) arr.class = CLASS_S; - else { + else + { status = TdiData(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - ndim = tdi_n_elements(tmp.pointer, &status); - if - STATUS_OK { - if (ndim > MAX_DIMS) - status = TdiNDIM_OVER; - else { - if (ndim == 0) - arr.class = CLASS_S; - else { - arr.dimct = (unsigned char)ndim; - arr.aflags.coeff = (unsigned char)(tmp.pointer->class == CLASS_A); - arr.a0 = 0; - cvt.pointer = (int *)&arr.m[0]; - cvt.arsize = sizeof(int) * ndim; - status = TdiConvert(tmp.pointer, &cvt); - } + if (STATUS_OK) + ndim = tdi_n_elements(tmp.pointer, &status); + if (STATUS_OK) + { + if (ndim > MAX_DIMS) + status = TdiNDIM_OVER; + else + { + if (ndim == 0) + arr.class = CLASS_S; + else + { + arr.dimct = (unsigned char)ndim; + arr.aflags.coeff = (unsigned char)(tmp.pointer->class == CLASS_A); + arr.a0 = 0; + cvt.pointer = (int *)&arr.m[0]; + cvt.arsize = sizeof(int) * ndim; + status = TdiConvert(tmp.pointer, &cvt); } } + } } /***************************** Data type from opcode or mold. *****************************/ - if - STATUS_OK { - if (narg <= 1 || list[1] == 0) { - dtype = fun_ptr->o1; - length = TdiREF_CAT[dtype].length; - } else { - switch (list[1]->class) { - case CLASS_S: - case CLASS_D: - case CLASS_A: - case CLASS_CA: { - dtype = list[1]->dtype; - length = list[1]->length; - } break; - default: { - status = TdiData(list[1], &tmp MDS_END_ARG); - if - STATUS_OK { - dtype = tmp.pointer->dtype; - length = tmp.pointer->length; - } - } break; + if (STATUS_OK) + { + if (narg <= 1 || list[1] == 0) + { + dtype = fun_ptr->o1; + length = TdiREF_CAT[dtype].length; + } + else + { + switch (list[1]->class) + { + case CLASS_S: + case CLASS_D: + case CLASS_A: + case CLASS_CA: + { + dtype = list[1]->dtype; + length = list[1]->length; + } + break; + default: + { + status = TdiData(list[1], &tmp MDS_END_ARG); + if (STATUS_OK) + { + dtype = tmp.pointer->dtype; + length = tmp.pointer->length; } } + break; + } } + } MdsFree1Dx(&tmp, NULL); /***************************** Size is product of dimensions. *****************************/ - if - STATUS_OK { - if (arr.class == CLASS_A) { - for (arr.arsize = 1, j = ndim; --j >= 0;) - arr.arsize *= arr.m[j]; - status = - MdsGet1DxA((struct descriptor_a *)&arr, &length, &dtype, out_ptr); - } else - status = MdsGet1DxS(&length, &dtype, out_ptr); + if (STATUS_OK) + { + if (arr.class == CLASS_A) + { + for (arr.arsize = 1, j = ndim; --j >= 0;) + arr.arsize *= arr.m[j]; + status = + MdsGet1DxA((struct descriptor_a *)&arr, &length, &dtype, out_ptr); } + else + status = MdsGet1DxS(&length, &dtype, out_ptr); + } /********************* Put some data into it. *********************/ - if - STATUS_OK - status = (*fun_ptr->f3)(out_ptr->pointer); + if (STATUS_OK) + status = (*fun_ptr->f3)(out_ptr->pointer); return status; } @@ -205,7 +227,8 @@ int Tdi3Array(/*int *out_ptr*/) { return MDSplusSUCCESS; } /*--------------------------------------------------------------------- Create a ramp of integers starting from zero. */ -int Tdi3Ramp(struct descriptor *out_ptr) { +int Tdi3Ramp(struct descriptor *out_ptr) +{ INIT_STATUS; static const int i0 = 0, i1 = 1; static const struct descriptor con0 = {sizeof(int), DTYPE_L, CLASS_S, @@ -214,29 +237,31 @@ int Tdi3Ramp(struct descriptor *out_ptr) { (char *)&i1}; int i, n; -#define LoadRamp(type) \ - { \ - type *ptr = (type *)out_ptr->pointer; \ - for (i = 0; i < n; i++) \ - ptr[i] = (type)i; \ - break; \ +#define LoadRamp(type) \ + { \ + type *ptr = (type *)out_ptr->pointer; \ + for (i = 0; i < n; i++) \ + ptr[i] = (type)i; \ + break; \ } -#define LoadRampF(type, dtype, native) \ - { \ - type *ptr = (type *)out_ptr->pointer; \ - type tmp; \ - for (i = 0; i < n; i++) { \ - tmp = (type)i; \ - if (native == dtype) \ - ptr[i] = tmp; \ - else \ - CvtConvertFloat(&tmp, native, &ptr[i], dtype); \ - } \ - break; \ +#define LoadRampF(type, dtype, native) \ + { \ + type *ptr = (type *)out_ptr->pointer; \ + type tmp; \ + for (i = 0; i < n; i++) \ + { \ + tmp = (type)i; \ + if (native == dtype) \ + ptr[i] = tmp; \ + else \ + CvtConvertFloat(&tmp, native, &ptr[i], dtype); \ + } \ + break; \ } N_ELEMENTS(out_ptr, n); - switch (out_ptr->dtype) { + switch (out_ptr->dtype) + { case DTYPE_B: LoadRamp(int8_t) case DTYPE_BU : LoadRamp(uint8_t) case DTYPE_W : LoadRamp(int16_t) case DTYPE_WU : LoadRamp(uint16_t) case DTYPE_L @@ -251,24 +276,25 @@ int Tdi3Ramp(struct descriptor *out_ptr) { WARNING this depends on order of operations in ADD routine. Make a zero and a one. Add 1 to this starter, but offset. **********************************************************/ - default : { + default: + { struct descriptor new = *out_ptr; new.class = CLASS_S; if (n > 0) status = TdiConvert(&con0, &new); - if (n > 1) { + if (n > 1) + { int step = new.length; new.pointer += step; - if - STATUS_OK - status = TdiConvert(&con1, &new); - if (n > 2) { + if (STATUS_OK) + status = TdiConvert(&con1, &new); + if (n > 2) + { struct descriptor_a modify = *(struct descriptor_a *)out_ptr; modify.pointer += step; modify.arsize -= step; - if - STATUS_OK - status = Tdi3Add(out_ptr, &new, &modify); + if (STATUS_OK) + status = Tdi3Add(out_ptr, &new, &modify); } } } @@ -297,14 +323,16 @@ const double norm = .5 / 2147483648.; to add one random bit to rand32 ***********************************/ #define rand16(bit) rand() -static uint32_t rand32(uint32_t *bit) { +static uint32_t rand32(uint32_t *bit) +{ *bit = *bit << 1; if ((*bit & 0x7fffffff) == 0) *bit = rand() << 1 | 1; return ((uint32_t)rand() & 0x7fffffff) | (*bit & 0x80000000); } #else // assume RAND_MAX==0x7fff==32767 -static uint32_t rand16(uint32_t *bit) { +static uint32_t rand16(uint32_t *bit) +{ *bit = *bit << 1; if ((*bit & 0x7fff) == 0) *bit = rand() << 1 | 1; @@ -316,30 +344,33 @@ static uint32_t rand16(uint32_t *bit) { static pthread_once_t once = PTHREAD_ONCE_INIT; static void once_random() { srand(time(0)); } -int Tdi3Random(struct descriptor_a *out_ptr) { +int Tdi3Random(struct descriptor_a *out_ptr) +{ pthread_once(&once, once_random); INIT_STATUS; uint32_t bit = 0; int i, n; N_ELEMENTS(out_ptr, n); - switch (out_ptr->dtype) { + switch (out_ptr->dtype) + { default: status = TdiINVDTYDSC; break; -#define LoadRandom(type, randx) \ - { \ - type *ptr = (type *)out_ptr->pointer; \ - for (i = 0; i < n; i++) \ - ptr[i] = (type)randx(&bit); \ +#define LoadRandom(type, randx) \ + { \ + type *ptr = (type *)out_ptr->pointer; \ + for (i = 0; i < n; i++) \ + ptr[i] = (type)randx(&bit); \ } -#define LoadRandomFloat(dtype, type, value) \ - { \ - type *ptr = (type *)out_ptr->pointer; \ - for (i = 0; i < n; i++) { \ - double val = value; \ - CvtConvertFloat(&val, DTYPE_NATIVE_DOUBLE, &ptr[i], dtype); \ - } \ +#define LoadRandomFloat(dtype, type, value) \ + { \ + type *ptr = (type *)out_ptr->pointer; \ + for (i = 0; i < n; i++) \ + { \ + double val = value; \ + CvtConvertFloat(&val, DTYPE_NATIVE_DOUBLE, &ptr[i], dtype); \ + } \ } case DTYPE_O: case DTYPE_OU: @@ -398,7 +429,8 @@ int Tdi3Random(struct descriptor_a *out_ptr) { /*--------------------------------------------------------------------- Create an array of zeroes. */ -int Tdi3Zero(struct descriptor_a *out_ptr) { +int Tdi3Zero(struct descriptor_a *out_ptr) +{ static const int i0 = 0; static const struct descriptor con0 = {sizeof(int), DTYPE_L, CLASS_S, (char *)&i0}; diff --git a/tdishr/TdiBinary.c b/tdishr/TdiBinary.c index 719b591739..80dfd98c85 100644 --- a/tdishr/TdiBinary.c +++ b/tdishr/TdiBinary.c @@ -69,9 +69,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int TdiBinary(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr, unsigned int *out_count) { + struct descriptor *out_ptr, unsigned int *out_count) +{ struct descriptor_a *a; - switch (out_ptr->class) { + switch (out_ptr->class) + { case CLASS_S: case CLASS_D: *out_count = 1; @@ -85,7 +87,8 @@ int TdiBinary(struct descriptor *in1_ptr, struct descriptor *in2_ptr, return TdiINVCLADSC; } - switch (in1_ptr->class) { + switch (in1_ptr->class) + { case CLASS_S: case CLASS_D: break; @@ -98,7 +101,8 @@ int TdiBinary(struct descriptor *in1_ptr, struct descriptor *in2_ptr, return TdiINVCLADSC; } - switch (in2_ptr->class) { + switch (in2_ptr->class) + { case CLASS_S: case CLASS_D: break; diff --git a/tdishr/TdiBound.c b/tdishr/TdiBound.c index 30a582fd1e..efe022ad39 100644 --- a/tdishr/TdiBound.c +++ b/tdishr/TdiBound.c @@ -62,7 +62,8 @@ static const dtype_t dtype_l = DTYPE_L; static const length_t size_l = (length_t)sizeof(int); int Tdi1Bound(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; array_bounds *pa; struct descriptor_xd sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, @@ -74,55 +75,58 @@ int Tdi1Bound(opcode_t opcode, int narg, struct descriptor *list[], pa = (array_bounds *)dat[0].pointer; if (pa && pa->class == CLASS_APD) // size lists status = SsINTERNAL; - if - STATUS_OK { - if (pa) - switch (pa->class) { - case CLASS_D: - case CLASS_S: - if (opcode == OPC_SHAPE || opcode == OPC_ESHAPE) - rank = 0; - else - rank = 1; - break; - case CLASS_A: - case CLASS_CA: - case CLASS_APD: - rank = pa->aflags.coeff ? pa->dimct : 1; - break; - default: - status = TdiINVCLADSC; - break; - } - else - status = TdiNULL_PTR; - } - if (narg > 1 && list[1] != 0) { - if - STATUS_OK - status = TdiGetLong(list[1], &dim); + if (STATUS_OK) + { + if (pa) + switch (pa->class) + { + case CLASS_D: + case CLASS_S: + if (opcode == OPC_SHAPE || opcode == OPC_ESHAPE) + rank = 0; + else + rank = 1; + break; + case CLASS_A: + case CLASS_CA: + case CLASS_APD: + rank = pa->aflags.coeff ? pa->dimct : 1; + break; + default: + status = TdiINVCLADSC; + break; + } + else + status = TdiNULL_PTR; + } + if (narg > 1 && list[1] != 0) + { + if (STATUS_OK) + status = TdiGetLong(list[1], &dim); if (STATUS_OK && dim >= rank) status = TdiBAD_INDEX; - if - STATUS_OK - status = MdsGet1DxS(&size_l, &dtype_l, out_ptr); - } else if (opcode == OPC_SIZE) { + if (STATUS_OK) + status = MdsGet1DxS(&size_l, &dtype_l, out_ptr); + } + else if (opcode == OPC_SIZE) + { dim = -1; - if - STATUS_OK - status = MdsGet1DxS(&size_l, &dtype_l, out_ptr); + if (STATUS_OK) + status = MdsGet1DxS(&size_l, &dtype_l, out_ptr); if (rank == 0 && STATUS_OK) *(int *)out_ptr->pointer->pointer = pa->dtype != DTYPE_MISSING; - } else { + } + else + { array adsc = *(array *)&adsc0; dim = -1; adsc.arsize = sizeof(int) * rank; - if - STATUS_OK - status = - MdsGet1DxA((struct descriptor_a *)&adsc, &size_l, &dtype_l, out_ptr); + if (STATUS_OK) + status = + MdsGet1DxA((struct descriptor_a *)&adsc, &size_l, &dtype_l, out_ptr); } - if (STATUS_OK && rank > 0) { + if (STATUS_OK && rank > 0) + { TdiRefFunction[opcode].f3(pa, dim, out_ptr->pointer->pointer); if (STATUS_OK && pa->dtype == DTYPE_DICTIONARY) *(int *)out_ptr->pointer->pointer /= 2; // count pairs @@ -136,12 +140,14 @@ int Tdi1Bound(opcode_t opcode, int narg, struct descriptor *list[], /*-------------------------------------------------------------- F90 inquiry for declared lower bound(s) of an array. */ -void Tdi3Lbound(array_bounds *pa, int dim, int *pbound) { +void Tdi3Lbound(array_bounds *pa, int dim, int *pbound) +{ int dimct, j; if (!IS_ARRAY_DSC(pa)) *pbound = 0; - else if (pa->aflags.coeff) { + else if (pa->aflags.coeff) + { dimct = pa->dimct; if (pa->aflags.bounds) if (dim < 0) @@ -154,7 +160,8 @@ void Tdi3Lbound(array_bounds *pa, int dim, int *pbound) { *pbound++ = 0; else *pbound = 0; - } else + } + else *pbound = 0; return; } @@ -162,12 +169,14 @@ void Tdi3Lbound(array_bounds *pa, int dim, int *pbound) { /*-------------------------------------------------------------- F90 inquiry for declared shape of an array. */ -void Tdi3Shape(array_bounds *pa, int dim, int *pbound) { +void Tdi3Shape(array_bounds *pa, int dim, int *pbound) +{ int dimct, j; if (!IS_ARRAY_DSC(pa)) *pbound = -1; - else if (pa->aflags.coeff) { + else if (pa->aflags.coeff) + { dimct = pa->dimct; if (pa->aflags.bounds) if (dim < 0) @@ -180,7 +189,8 @@ void Tdi3Shape(array_bounds *pa, int dim, int *pbound) { *pbound++ = pa->m[j]; else *pbound = pa->m[dim]; - } else + } + else *pbound = (int)pa->arsize / (int)pa->length; return; } @@ -188,27 +198,33 @@ void Tdi3Shape(array_bounds *pa, int dim, int *pbound) { /*-------------------------------------------------------------- F90 inquiry for the size of one axis or the total of all axes. */ -int Tdi3Size(array_bounds *pa, int dim, int *pbound) { +int Tdi3Size(array_bounds *pa, int dim, int *pbound) +{ int dimct, j; if (!IS_ARRAY_DSC(pa)) *pbound = pa->dtype == DTYPE_MISSING ? 0 : 1; - else if (pa->aflags.coeff) { + else if (pa->aflags.coeff) + { *pbound = 1; dimct = pa->dimct; - if (pa->aflags.bounds) { + if (pa->aflags.bounds) + { if (dim < 0) for (j = 0; j < dimct; ++j) *pbound *= pa->m[dimct + 2 * j + 1] - pa->m[dimct + 2 * j] + 1; else *pbound = pa->m[dimct + 2 * dim + 1] - pa->m[dimct + 2 * dim] + 1; - } else { + } + else + { if (dim < 0) for (j = 0; j < dimct; ++j) *pbound *= pa->m[j]; else *pbound = pa->m[dim]; } - } else + } + else *pbound = ((int)pa->length > 0) ? (int)pa->arsize / (int)pa->length : 0; return 1; } @@ -216,11 +232,13 @@ int Tdi3Size(array_bounds *pa, int dim, int *pbound) { /*-------------------------------------------------------------- F90 inquiry for declared upper bound(s) of an array. */ -void Tdi3Ubound(array_bounds *pa, int dim, int *pbound) { +void Tdi3Ubound(array_bounds *pa, int dim, int *pbound) +{ int dimct, j; if (!IS_ARRAY_DSC(pa)) *pbound = pa->dtype == DTYPE_MISSING ? -1 : 0; - else if (pa->aflags.coeff) { + else if (pa->aflags.coeff) + { dimct = pa->dimct; if (pa->aflags.bounds) if (dim < 0) @@ -233,7 +251,8 @@ void Tdi3Ubound(array_bounds *pa, int dim, int *pbound) { *pbound++ = pa->m[j] - 1; else *pbound = pa->m[dim] - 1; - } else + } + else *pbound = (int)pa->arsize / (int)pa->length - 1; return; } @@ -242,7 +261,8 @@ void Tdi3Ubound(array_bounds *pa, int dim, int *pbound) { Non-F90 inquiry for Effective bounds. */ int Tdi1Ebound(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; array_bounds *pa = 0; struct descriptor_xd sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, @@ -253,47 +273,50 @@ int Tdi1Ebound(opcode_t opcode, int narg, struct descriptor *list[], unsigned int dim, rank = 0; status = TdiGetArgs(opcode, 1, list, sig, uni, dat, cats); - if - STATUS_OK { - pa = (array_bounds *)dat[0].pointer; - if (pa) - switch (pa->class) { - case CLASS_D: - case CLASS_S: - rank = 1; - break; - case CLASS_A: - rank = pa->aflags.coeff ? pa->dimct : 1; - break; - default: - status = TdiINVCLADSC; - break; - } - else - status = TdiNULL_PTR; - } - if (narg > 1 && list[1] != 0) { - if - STATUS_OK - status = TdiGetLong(list[1], &dim); + if (STATUS_OK) + { + pa = (array_bounds *)dat[0].pointer; + if (pa) + switch (pa->class) + { + case CLASS_D: + case CLASS_S: + rank = 1; + break; + case CLASS_A: + rank = pa->aflags.coeff ? pa->dimct : 1; + break; + default: + status = TdiINVCLADSC; + break; + } + else + status = TdiNULL_PTR; + } + if (narg > 1 && list[1] != 0) + { + if (STATUS_OK) + status = TdiGetLong(list[1], &dim); if (STATUS_OK && dim >= rank) status = TdiBAD_INDEX; - if - STATUS_OK - status = (*TdiRefFunction[opcode].f3)(sig[0].pointer, pa, dim, out_ptr); - } else { + if (STATUS_OK) + status = (*TdiRefFunction[opcode].f3)(sig[0].pointer, pa, dim, out_ptr); + } + else + { if (STATUS_OK && rank > MAX_DIMS) status = TdiNDIM_OVER; - else { - for (dim = 0; STATUS_OK && dim < rank; ++dim) { + else + { + for (dim = 0; STATUS_OK && dim < rank; ++dim) + { outs[dim] = EMPTY_XD; status = (*TdiRefFunction[opcode].f3)(sig[0].pointer, pa, dim, &outs[dim]); new[dim] = (struct descriptor *)&outs[dim]; } - if - STATUS_OK - status = TdiIntrinsic(OPC_VECTOR, rank, new, out_ptr); + if (STATUS_OK) + status = TdiIntrinsic(OPC_VECTOR, rank, new, out_ptr); if (opcode == OPC_ESIZE && STATUS_OK) status = TdiProduct(out_ptr, out_ptr MDS_END_ARG); for (; (int)--dim >= 0;) @@ -310,18 +333,20 @@ int Tdi1Ebound(opcode_t opcode, int narg, struct descriptor *list[], Effective lower bound. */ int Tdi3Elbound(struct descriptor_signal *psig, array_bounds *pa, int dim, - struct descriptor_xd *pout) { + struct descriptor_xd *pout) +{ INIT_STATUS; - if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) { + if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) + { status = TdiItoX(psig->dimensions[dim], TdiItoXSpecial, pout MDS_END_ARG); - if - STATUS_OK - pout->pointer->class = CLASS_S; - } else { + if (STATUS_OK) + pout->pointer->class = CLASS_S; + } + else + { status = MdsGet1DxS(&size_l, &dtype_l, pout); - if - STATUS_OK - Tdi3Lbound(pa, dim, (int *)pout->pointer->pointer); + if (STATUS_OK) + Tdi3Lbound(pa, dim, (int *)pout->pointer->pointer); } return status; } @@ -330,20 +355,23 @@ int Tdi3Elbound(struct descriptor_signal *psig, array_bounds *pa, int dim, Effective upper bound. */ int Tdi3Eubound(struct descriptor_signal *psig, array_bounds *pa, int dim, - struct descriptor_xd *pout) { + struct descriptor_xd *pout) +{ INIT_STATUS; - if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) { + if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) + { status = TdiItoX(psig->dimensions[dim], TdiItoXSpecial, pout MDS_END_ARG); - if - STATUS_OK { - pout->pointer->class = CLASS_S; - pout->pointer->pointer += pout->pointer->length; - } - } else { + if (STATUS_OK) + { + pout->pointer->class = CLASS_S; + pout->pointer->pointer += pout->pointer->length; + } + } + else + { status = MdsGet1DxS(&size_l, &dtype_l, pout); - if - STATUS_OK - Tdi3Ubound(pa, dim, (int *)pout->pointer->pointer); + if (STATUS_OK) + Tdi3Ubound(pa, dim, (int *)pout->pointer->pointer); } return status; } @@ -352,23 +380,26 @@ int Tdi3Eubound(struct descriptor_signal *psig, array_bounds *pa, int dim, Effective shape. */ int Tdi3Eshape(struct descriptor_signal *psig, array_bounds *pa, int dim, - struct descriptor_xd *pout) { + struct descriptor_xd *pout) +{ INIT_STATUS; struct descriptor hold; - if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) { + if (psig && dim < psig->ndesc - 2 && psig->dimensions[dim]) + { status = TdiItoX(psig->dimensions[dim], TdiItoXSpecial, pout MDS_END_ARG); - if - STATUS_OK { - pout->pointer->class = CLASS_S; - hold = *pout->pointer; - hold.pointer += hold.length; - status = Tdi3Subtract(&hold, pout->pointer, pout->pointer); - } - } else { + if (STATUS_OK) + { + pout->pointer->class = CLASS_S; + hold = *pout->pointer; + hold.pointer += hold.length; + status = Tdi3Subtract(&hold, pout->pointer, pout->pointer); + } + } + else + { status = MdsGet1DxS(&size_l, &dtype_l, pout); - if - STATUS_OK - Tdi3Shape(pa, dim, (int *)pout->pointer->pointer); + if (STATUS_OK) + Tdi3Shape(pa, dim, (int *)pout->pointer->pointer); } return status; } @@ -377,6 +408,7 @@ int Tdi3Eshape(struct descriptor_signal *psig, array_bounds *pa, int dim, Effective size. */ int Tdi3Esize(struct descriptor_signal *psig, array_bounds *pa, int dim, - struct descriptor_xd *pout) { + struct descriptor_xd *pout) +{ return Tdi3Eshape(psig, pa, dim, pout); } diff --git a/tdishr/TdiBuild.c b/tdishr/TdiBuild.c index fa8451c442..ae471d8a81 100644 --- a/tdishr/TdiBuild.c +++ b/tdishr/TdiBuild.c @@ -47,7 +47,8 @@ extern int TdiMasterData(); */ int Tdi1AsIs(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = MdsCopyDxXd(list[0], out_ptr); @@ -75,7 +76,8 @@ int Tdi1AsIs(opcode_t opcode __attribute__((unused)), No arrays of descriptors. */ int Tdi1Build(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *ptr; struct TdiFunctionStruct *fun_ptr = @@ -88,9 +90,11 @@ int Tdi1Build(opcode_t opcode, int narg, struct descriptor *list[], build.length = 0; build.dtype = fun_ptr->o1; build.ndesc = (uint8_t)narg; - if (fun_ptr->o2 != fun_ptr->o1) { + if (fun_ptr->o2 != fun_ptr->o1) + { status = TdiGetLong(list[0], &modif); - switch (fun_ptr->o2) { + switch (fun_ptr->o2) + { case DTYPE_BU: build.length = 1; modif_c = (uint8_t)modif; @@ -107,17 +111,18 @@ int Tdi1Build(opcode_t opcode, int narg, struct descriptor *list[], } --build.ndesc; j = 1; - } else + } + else j = 0; - for (k = 0; j < narg; ++j, ++k) { + for (k = 0; j < narg; ++j, ++k) + { ptr = list[j]; while (ptr && ptr->dtype == DTYPE_DSC) ptr = (struct descriptor *)ptr->pointer; build.arguments[k] = ptr; } - if - STATUS_OK - status = MdsCopyDxXd((struct descriptor *)&build, out_ptr); + if (STATUS_OK) + status = MdsCopyDxXd((struct descriptor *)&build, out_ptr); return status; } @@ -128,7 +133,8 @@ int Tdi1Build(opcode_t opcode, int narg, struct descriptor *list[], WARNING: BUILD_PATH and BUILD_EVENT should be called MAKE_xxx. */ int Tdi1BuildPath(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd sig[1], uni[1], dat[1]; struct TdiCatStruct cats[2]; @@ -136,20 +142,18 @@ int Tdi1BuildPath(opcode_t opcode, int narg, struct descriptor *list[], status = TdiGetArgs(opcode, narg, list, sig, uni, dat, cats); cats[1].out_dtype = cats[1].in_dtype; cats[1].out_cat = cats[1].in_cat; - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); /********************************* Change from text to path or event. *********************************/ - if - STATUS_OK { - dat->pointer->dtype = TdiRefFunction[opcode].o1; - status = MdsCopyDxXd((struct descriptor *)dat, out_ptr); - } - if - STATUS_OK - status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + { + dat->pointer->dtype = TdiRefFunction[opcode].o1; + status = MdsCopyDxXd((struct descriptor *)dat, out_ptr); + } + if (STATUS_OK) + status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); if (sig->pointer) MdsFree1Dx(sig, NULL); if (uni->pointer) @@ -167,7 +171,8 @@ int Tdi1BuildPath(opcode_t opcode, int narg, struct descriptor *list[], So BUILD_xxx(x,y,...) is the same as MAKE_xxx(AS_IS(x),AS_IS(y),...). */ int Tdi1Make(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *ptr; int j, k, modif; @@ -181,9 +186,11 @@ int Tdi1Make(opcode_t opcode, int narg, struct descriptor *list[], build.length = 0; build.dtype = fun_ptr->o1; build.ndesc = (unsigned char)narg; - if (fun_ptr->o2 != fun_ptr->o1) { + if (fun_ptr->o2 != fun_ptr->o1) + { status = TdiGetLong(list[0], &modif); - switch (fun_ptr->o2) { + switch (fun_ptr->o2) + { case DTYPE_BU: build.length = 1; modif_c = (uint8_t)modif; @@ -200,9 +207,11 @@ int Tdi1Make(opcode_t opcode, int narg, struct descriptor *list[], } --build.ndesc; j = 1; - } else + } + else j = 0; - for (k = 0; j < narg && STATUS_OK; ++j, ++k) { + for (k = 0; j < narg && STATUS_OK; ++j, ++k) + { xd[k] = EMPTY_XD; if (list[j]) status = TdiEvaluate(list[j], &xd[k] MDS_END_ARG); @@ -213,9 +222,8 @@ int Tdi1Make(opcode_t opcode, int narg, struct descriptor *list[], ptr = 0; build.arguments[k] = ptr; } - if - STATUS_OK - status = MdsCopyDxXd((struct descriptor *)&build, out_ptr); + if (STATUS_OK) + status = MdsCopyDxXd((struct descriptor *)&build, out_ptr); for (; --k >= 0;) MdsFree1Dx(&xd[k], NULL); return status; diff --git a/tdishr/TdiCall.c b/tdishr/TdiCall.c index 20f343cd2c..0db735847d 100644 --- a/tdishr/TdiCall.c +++ b/tdishr/TdiCall.c @@ -66,16 +66,20 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif static inline int interlude(dtype_t rtype, mdsdsc_t **newdsc, - int (*routine)(), void **result, int *max) { - switch (rtype) { - case DTYPE_MISSING: { + int (*routine)(), void **result, int *max) +{ + switch (rtype) + { + case DTYPE_MISSING: + { LibCallg(newdsc, routine); break; } case DTYPE_C: case DTYPE_T: case DTYPE_POINTER: - case DTYPE_DSC: { + case DTYPE_DSC: + { void *(*called_p)() = (void *(*)())LibCallg; void **result_p = (void *)result; *max = sizeof(void *); @@ -87,7 +91,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") case DTYPE_FC: case DTYPE_FSC: case DTYPE_Q: - case DTYPE_QU: { // 8 bytes + case DTYPE_QU: + { // 8 bytes int64_t (*called_q)() = (int64_t(*)())LibCallg; int64_t *result_q = (int64_t *)result; *max = sizeof(int64_t); @@ -96,7 +101,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") } // case DTYPE_F: // case DTYPE_FS: - default: { // 4 bytes + default: + { // 4 bytes int32_t (*called_int)() = (int32_t(*)())LibCallg; int32_t *result_int = (int32_t *)result; *max = sizeof(int32_t); @@ -106,7 +112,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") return 1; } -int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { +int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; mds_function_t *pfun; mdsdsc_xd_t image = EMPTY_XD, entry = EMPTY_XD, tmp[255]; @@ -120,73 +127,88 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { status = TdiNDIM_OVER; else status = TdiData(list[0], &image MDS_END_ARG); - if - STATUS_OK - status = TdiData(list[1], &entry MDS_END_ARG); - if - STATUS_OK - status = TdiFindImageSymbol(image.pointer, entry.pointer, &routine); - if - STATUS_NOT_OK - printf("%s\n", LibFindImageSymbolErrString()); + if (STATUS_OK) + status = TdiData(list[1], &entry MDS_END_ARG); + if (STATUS_OK) + status = TdiFindImageSymbol(image.pointer, entry.pointer, &routine); + if (STATUS_NOT_OK) + printf("%s\n", LibFindImageSymbolErrString()); MdsFree1Dx(&entry, NULL); MdsFree1Dx(&image, NULL); *(int *)&newdsc[0] = narg - 2; - for (j = 2; j < narg && STATUS_OK; ++j) { + for (j = 2; j < narg && STATUS_OK; ++j) + { for (pfun = (struct descriptor_function *)list[j]; pfun && pfun->dtype == DTYPE_DSC;) pfun = (struct descriptor_function *)pfun->pointer; - if (pfun && pfun->dtype == DTYPE_FUNCTION) { + if (pfun && pfun->dtype == DTYPE_FUNCTION) + { code = *(unsigned short *)pfun->pointer; - if (code == OPC_DESCR) { + if (code == OPC_DESCR) + { tmp[ntmp] = EMPTY_XD; status = TdiData(pfun->arguments[0], &tmp[ntmp] MDS_END_ARG); newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer; origin[ntmp++] = (unsigned char)j; - } else if (code == OPC_REF) { + } + else if (code == OPC_REF) + { tmp[ntmp] = EMPTY_XD; status = TdiData(pfun->arguments[0], &tmp[ntmp] MDS_END_ARG); - if (tmp[ntmp].pointer) { - if (tmp[ntmp].pointer->dtype == DTYPE_T) { + if (tmp[ntmp].pointer) + { + if (tmp[ntmp].pointer->dtype == DTYPE_T) + { DESCRIPTOR(zero, "\0"); TdiConcat(&tmp[ntmp], &zero, &tmp[ntmp] MDS_END_ARG); } newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer->pointer; } origin[ntmp++] = (unsigned char)j; - } else if (code == OPC_VAL) { + } + else if (code == OPC_VAL) + { int ans; EMPTYXD(xd); status = TdiData(pfun->arguments[0], &xd MDS_END_ARG); - if (STATUS_OK && xd.pointer && xd.pointer->dtype == DTYPE_POINTER) { + if (STATUS_OK && xd.pointer && xd.pointer->dtype == DTYPE_POINTER) + { *(void **)&newdsc[j - 1] = *(void **)xd.pointer->pointer; - } else { + } + else + { status = TdiGetLong(pfun->arguments[0], &ans); *(long *)&newdsc[j - 1] = ans; } MdsFree1Dx(&xd, 0); - } else if (code == OPC_XD) { + } + else if (code == OPC_XD) + { tmp[ntmp] = EMPTY_XD; status = TdiEvaluate(pfun->arguments[0], newdsc[j - 1] = (mdsdsc_t *)&tmp[ntmp] MDS_END_ARG); origin[ntmp++] = (unsigned char)j; - } else + } + else goto fort; } /******************************************** Default is DESCR for text and REF for others. ********************************************/ - else { + else + { fort: tmp[ntmp] = EMPTY_XD; if (list[j]) status = TdiData(list[j], &tmp[ntmp] MDS_END_ARG); newdsc[j - 1] = tmp[ntmp].pointer; - if (newdsc[j - 1]) { + if (newdsc[j - 1]) + { if (newdsc[j - 1]->dtype != DTYPE_T) newdsc[j - 1] = (mdsdsc_t *)newdsc[j - 1]->pointer; - else { + else + { DESCRIPTOR(zero_dsc, "\0"); TdiConcat(&tmp[ntmp], &zero_dsc, &tmp[ntmp] MDS_END_ARG); newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer->pointer; @@ -195,68 +217,72 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { origin[ntmp++] = (unsigned char)j; } } - if - STATUS_OK - status = interlude(rtype, newdsc, routine, (void **)result, &max); + if (STATUS_OK) + status = interlude(rtype, newdsc, routine, (void **)result, &max); if (!out_ptr) goto skip; - if - STATUS_OK - switch (rtype) { - case DTYPE_MISSING: - break; - case DTYPE_DSC: - dx.pointer = *(char **)result; - if (*(void **)result) - switch ((*(mdsdsc_t **)result)->class) { - case CLASS_XD: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = **(mdsdsc_xd_t **)result; - **(mdsdsc_xd_t **)result = EMPTY_XD; - goto skip; - case CLASS_D: - MdsFree1Dx(out_ptr, NULL); - *(mdsdsc_t *)out_ptr = **(mdsdsc_t **)result; - (*(mdsdsc_t **)result)->length = 0; - (*(mdsdsc_t **)result)->pointer = NULL; + if (STATUS_OK) + switch (rtype) + { + case DTYPE_MISSING: + break; + case DTYPE_DSC: + dx.pointer = *(char **)result; + if (*(void **)result) + switch ((*(mdsdsc_t **)result)->class) + { + case CLASS_XD: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = **(mdsdsc_xd_t **)result; + **(mdsdsc_xd_t **)result = EMPTY_XD; + goto skip; + case CLASS_D: + MdsFree1Dx(out_ptr, NULL); + *(mdsdsc_t *)out_ptr = **(mdsdsc_t **)result; + (*(mdsdsc_t **)result)->length = 0; + (*(mdsdsc_t **)result)->pointer = NULL; + goto skip; + default: + break; + } + break; + case DTYPE_C: /* like T but with free */ + case DTYPE_T: + case DTYPE_PATH: + case DTYPE_EVENT: + if (!*(char **)result) goto skip; - default: - break; + dx.length = (length_t)strlen(dx.pointer = *(char **)result); + break; + case DTYPE_NID: + dx.length = sizeof(int); + break; + case DTYPE_POINTER: + dx.length = sizeof(void *); + break; + default: + { + if ((int)rtype < TdiCAT_MAX) + { + if ((dx.length = TdiREF_CAT[(int)rtype].length) > max) + status = TdiTOO_BIG; } - break; - case DTYPE_C: /* like T but with free */ - case DTYPE_T: - case DTYPE_PATH: - case DTYPE_EVENT: - if (!*(char **)result) - goto skip; - dx.length = (length_t)strlen(dx.pointer = *(char **)result); - break; - case DTYPE_NID: - dx.length = sizeof(int); - break; - case DTYPE_POINTER: - dx.length = sizeof(void *); - break; - default: { - if ((int)rtype < TdiCAT_MAX) { - if ((dx.length = TdiREF_CAT[(int)rtype].length) > max) - status = TdiTOO_BIG; - } else - status = TdiINVDTYDSC; - } - } - if - STATUS_OK - status = MdsCopyDxXd(&dx, out_ptr); + else + status = TdiINVDTYDSC; + } + } + if (STATUS_OK) + status = MdsCopyDxXd(&dx, out_ptr); if (rtype == DTYPE_C) free(*(char **)result); // free result skip: - for (j = 0; j < ntmp; ++j) { + for (j = 0; j < ntmp; ++j) + { for (pfun = (mds_function_t *)list[origin[j]]; pfun && pfun->dtype == DTYPE_DSC;) pfun = (mds_function_t *)pfun->pointer; - if (pfun && pfun->dtype == DTYPE_FUNCTION) { + if (pfun && pfun->dtype == DTYPE_FUNCTION) + { code = *(length_t *)pfun->pointer; if (code == OPC_DESCR || code == OPC_REF || code == OPC_XD) pfun = (mds_function_t *)pfun->arguments[0]; diff --git a/tdishr/TdiChar.c b/tdishr/TdiChar.c index b1a1e3cab6..00e91ce93d 100644 --- a/tdishr/TdiChar.c +++ b/tdishr/TdiChar.c @@ -44,25 +44,26 @@ static const struct descriptor false_dsc = {1, DTYPE_T, CLASS_S, F8X elemental, adjust string left, if there are blanks at left, and add blanks at right. string = ADJUSTL(string) */ -int Tdi3Adjustl(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Adjustl(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *ps1 = in_ptr->pointer, *pe1 = ps1; char *ps2 = out_ptr->pointer, *pe2 = ps2; int step = out_ptr->length, n; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - for (; --n >= 0;) { - pe1 += step; - pe2 += step; - while (ps1 < pe1 && (*ps1 == ' ' || *ps1 == '\t')) - ps1++; - while (ps1 < pe1) - *ps2++ = *ps1++; - while (ps2 < pe2) - *ps2++ = ' '; - } + if (STATUS_OK) + for (; --n >= 0;) + { + pe1 += step; + pe2 += step; + while (ps1 < pe1 && (*ps1 == ' ' || *ps1 == '\t')) + ps1++; + while (ps1 < pe1) + *ps2++ = *ps1++; + while (ps2 < pe2) + *ps2++ = ' '; + } return status; } @@ -70,25 +71,26 @@ int Tdi3Adjustl(struct descriptor *in_ptr, struct descriptor *out_ptr) { F8X elemental, adjust string right, if there are blanks at right and add blanks at left. string = ADJUSTR(string) */ -int Tdi3Adjustr(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Adjustr(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *ps1 = in_ptr->pointer, *pe1; char *ps2 = out_ptr->pointer, *pe2; int step = out_ptr->length, n, last; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - for (last = n * step - 1, pe1 = ps1 += last, pe2 = ps2 += last; --n >= 0;) { - ps1 -= step; - ps2 -= step; - while (ps1 < pe1 && (*pe1 == ' ' || *pe1 == '\t')) - pe1--; - while (ps1 < pe1) - *pe2-- = *pe1--; - while (ps2 < pe2) - *pe2-- = ' '; - } + if (STATUS_OK) + for (last = n * step - 1, pe1 = ps1 += last, pe2 = ps2 += last; --n >= 0;) + { + ps1 -= step; + ps2 -= step; + while (ps1 < pe1 && (*pe1 == ' ' || *pe1 == '\t')) + pe1--; + while (ps1 < pe1) + *pe2-- = *pe1--; + while (ps2 < pe2) + *pe2-- = ' '; + } return status; } @@ -98,7 +100,8 @@ int Tdi3Adjustr(struct descriptor *in_ptr, struct descriptor *out_ptr) { */ int Tdi3Char(struct descriptor *in_ptr, struct descriptor *kind_ptr __attribute__((unused)), - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; char *p1 = in_ptr->pointer; char *p2 = out_ptr->pointer; @@ -118,7 +121,8 @@ int Tdi3Char(struct descriptor *in_ptr, string = string // string ... */ int Tdi3Concat(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ char *p1 = in1_ptr->pointer, *pt1; char *p2 = in2_ptr->pointer, *pt2; char *p3 = out_ptr->pointer; @@ -129,14 +133,14 @@ int Tdi3Concat(struct descriptor *in1_ptr, struct descriptor *in2_ptr, int status = MDSplusSUCCESS, n; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - for (; --n >= 0; p1 += step1, p2 += step2) { - for (j1 = size1, pt1 = p1; --j1 >= 0;) - *p3++ = *pt1++; - for (j2 = size2, pt2 = p2; --j2 >= 0;) - *p3++ = *pt2++; - } + if (STATUS_OK) + for (; --n >= 0; p1 += step1, p2 += step2) + { + for (j1 = size1, pt1 = p1; --j1 >= 0;) + *p3++ = *pt1++; + for (j2 = size2, pt2 = p2; --j2 >= 0;) + *p3++ = *pt2++; + } return status; } @@ -147,7 +151,8 @@ int Tdi3Concat(struct descriptor *in1_ptr, struct descriptor *in2_ptr, Need to trim the result. */ int Tdi3Element(struct descriptor *number_ptr, struct descriptor *delim_ptr, - struct descriptor *source_ptr, struct descriptor *out_ptr) { + struct descriptor *source_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *pnumber = number_ptr->pointer; int number, n; @@ -162,13 +167,13 @@ int Tdi3Element(struct descriptor *number_ptr, struct descriptor *delim_ptr, source_dsc.class = CLASS_S; delim_dsc.class = CLASS_S; out_dsc.class = CLASS_S; - for (; STATUS_OK && --n >= 0;) { + for (; STATUS_OK && --n >= 0;) + { static const unsigned short zero = 0; number = *(int *)pnumber, pnumber += number_step; status = StrElement(&out_dsc, &number, &delim_dsc, &source_dsc); - if - STATUS_NOT_OK - status = StrCopyR(&out_dsc, &zero, ""); + if (STATUS_NOT_OK) + status = StrCopyR(&out_dsc, &zero, ""); source_dsc.pointer += source_step; delim_dsc.pointer += delim_step; out_dsc.pointer += out_dsc.length; @@ -182,7 +187,8 @@ int Tdi3Element(struct descriptor *number_ptr, struct descriptor *delim_ptr, Limitation: length must be a scalar, I think. */ int Tdi3Extract(struct descriptor *start_ptr, struct descriptor *length_ptr, - struct descriptor *source_ptr, struct descriptor *out_ptr) { + struct descriptor *source_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *pstart = start_ptr->pointer, *plength = length_ptr->pointer; int start, length, n; @@ -195,7 +201,8 @@ int Tdi3Extract(struct descriptor *start_ptr, struct descriptor *length_ptr, N_ELEMENTS(out_ptr, n); source_dsc.class = CLASS_S; out_dsc.class = CLASS_S; - for (; STATUS_OK && --n >= 0;) { + for (; STATUS_OK && --n >= 0;) + { start = *(int *)pstart + 1, pstart += start_step; length = *(int *)plength, plength += length_step; status = StrLenExtr(&out_dsc, &source_dsc, &start, &length); @@ -210,7 +217,8 @@ int Tdi3Extract(struct descriptor *start_ptr, struct descriptor *length_ptr, byte = IACHAR(ascii-text) byte = ICHAR(text) */ -int Tdi3Ichar(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Ichar(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ return Tdi3Char(in_ptr, NULL, out_ptr); } @@ -223,7 +231,8 @@ int Tdi3Ichar(struct descriptor *in_ptr, struct descriptor *out_ptr) { first R, left to right */ int Tdi3Index(struct descriptor *str_ptr, struct descriptor *sub_ptr, - struct descriptor *bac_ptr, struct descriptor *out_ptr) { + struct descriptor *bac_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; struct descriptor str_dsc = *str_ptr; struct descriptor sub_dsc = *sub_ptr; @@ -237,13 +246,16 @@ int Tdi3Index(struct descriptor *str_ptr, struct descriptor *sub_ptr, N_ELEMENTS(out_ptr, n); str_dsc.class = CLASS_S; sub_dsc.class = CLASS_S; - while (--n >= 0) { - if (*bac_dsc.pointer & 1) { + while (--n >= 0) + { + if (*bac_dsc.pointer & 1) + { int m, limit = str_dsc.length - sub_dsc.length; for (m = 0; j = m - 1, m++ <= limit;) if ((m = StrPosition(&str_dsc, &sub_dsc, &m)) <= 0) break; - } else + } + else j = StrPosition(&str_dsc, &sub_dsc, 0) - 1; *out_point++ = j; str_dsc.pointer += str_step; @@ -257,14 +269,16 @@ int Tdi3Index(struct descriptor *str_ptr, struct descriptor *sub_ptr, F8X elemental, find length of string with trailing blanks and tabs removed. Example: LEN_TRIM([" A B "," "]) is [4,0] */ -int Tdi3LenTrim(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3LenTrim(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *p1 = in_ptr->pointer, *pe1; int *p2 = (int *)out_ptr->pointer; int step = in_ptr->length, n; N_ELEMENTS(out_ptr, n); - for (; --n >= 0; p1 += step) { + for (; --n >= 0; p1 += step) + { pe1 = p1 + step; for (; p1 <= --pe1;) if (*pe1 != ' ' && *pe1 != '\t') @@ -281,7 +295,8 @@ int Tdi3LenTrim(struct descriptor *in_ptr, struct descriptor *out_ptr) { */ int Tdi3Repeat(struct descriptor *in1_ptr, struct descriptor *in2_ptr __attribute__((unused)), - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; int n, j, size = in1_ptr->length, ncopies = (int)out_ptr->length / size; char *p1 = in1_ptr->pointer, *p3 = out_ptr->pointer; @@ -302,7 +317,8 @@ int Tdi3Repeat(struct descriptor *in1_ptr, first R, left to right */ int Tdi3Scan(struct descriptor *str_ptr, struct descriptor *set_ptr, - struct descriptor *bac_ptr, struct descriptor *out_ptr) { + struct descriptor *bac_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; struct descriptor str_dsc = *str_ptr; struct descriptor set_dsc = *set_ptr; @@ -318,8 +334,10 @@ int Tdi3Scan(struct descriptor *str_ptr, struct descriptor *set_ptr, N_ELEMENTS(out_ptr, n); str_dsc.class = CLASS_S; set_dsc.class = CLASS_S; - while (--n >= 0) { - if (*bac_dsc.pointer & 1) { + while (--n >= 0) + { + if (*bac_dsc.pointer & 1) + { /******************************************************************** FIND_LAST_IN_SET by checking INDEX(set, char) from right to left. ********************************************************************/ @@ -328,7 +346,8 @@ int Tdi3Scan(struct descriptor *str_ptr, struct descriptor *set_ptr, if (StrPosition(&set_dsc, &tmp_dsc, 0) != 0) break; j = tmp_dsc.pointer - str_dsc.pointer; - } else + } + else j = StrFindFirstInSet(&str_dsc, &set_dsc) - 1; *out_point++ = j; str_dsc.pointer += str_step; @@ -342,7 +361,8 @@ int Tdi3Scan(struct descriptor *str_ptr, struct descriptor *set_ptr, Elemental function to convert a string or builtin name to its opcode. Gives -1 if not found. */ -int Tdi3StringOpcode(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3StringOpcode(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int len, n; unsigned short step = in_ptr->length; @@ -353,25 +373,25 @@ int Tdi3StringOpcode(struct descriptor *in_ptr, struct descriptor *out_ptr) { tmp_dsc.length = step; tmp_dsc.pointer = in_ptr->pointer; N_ELEMENTS(out_ptr, n); - for (; --n >= 0; tmp_dsc.pointer += step) { + for (; --n >= 0; tmp_dsc.pointer += step) + { /**************************************************** Case insensitive and ignore trailing blanks and tabs. ****************************************************/ status = StrUpcase((struct descriptor *)&one_dsc, (struct descriptor *)&tmp_dsc); - if - STATUS_OK - status = StrTrim((struct descriptor *)&one_dsc, - (struct descriptor *)&one_dsc, 0); - if - STATUS_NOT_OK - break; + if (STATUS_OK) + status = StrTrim((struct descriptor *)&one_dsc, + (struct descriptor *)&one_dsc, 0); + if (STATUS_NOT_OK) + break; /****************************** Ignore leading Opc designator. ******************************/ len = one_dsc.length; str_ptr = one_dsc.pointer; - if (len > 4 && strncmp(str_ptr, "Opc", 4) == 0) { + if (len > 4 && strncmp(str_ptr, "Opc", 4) == 0) + { str_ptr += 4; len -= 4; } @@ -386,7 +406,8 @@ int Tdi3StringOpcode(struct descriptor *in_ptr, struct descriptor *out_ptr) { string = TRANSLATE(string, translation, match) */ int Tdi3Translate(struct descriptor *str_ptr, struct descriptor *tra_ptr, - struct descriptor *mat_ptr, struct descriptor *out_ptr) { + struct descriptor *mat_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; status = StrTranslate(out_ptr, str_ptr, tra_ptr, mat_ptr); @@ -397,7 +418,8 @@ int Tdi3Translate(struct descriptor *str_ptr, struct descriptor *tra_ptr, Convert a string to uppercase. string = UPCASE(string) */ -int Tdi3Upcase(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Upcase(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; status = StrUpcase(out_ptr, in_ptr); @@ -412,7 +434,8 @@ int Tdi3Upcase(struct descriptor *in_ptr, struct descriptor *out_ptr) { VERIFY("ABBA", "A", $TRUE) is 2 offset from left of last non-A */ int Tdi3Verify(struct descriptor *str_ptr, struct descriptor *set_ptr, - struct descriptor *bac_ptr, struct descriptor *out_ptr) { + struct descriptor *bac_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; struct descriptor str_dsc = *str_ptr; struct descriptor set_dsc = *set_ptr; @@ -428,8 +451,10 @@ int Tdi3Verify(struct descriptor *str_ptr, struct descriptor *set_ptr, N_ELEMENTS(out_ptr, n); str_dsc.class = CLASS_S; set_dsc.class = CLASS_S; - while (--n >= 0) { - if (*bac_dsc.pointer & 1) { + while (--n >= 0) + { + if (*bac_dsc.pointer & 1) + { /******************************************************************** FIND_LAST_NOT_IN_SET by checking INDEX(set, char) from right to left. ********************************************************************/ @@ -438,7 +463,8 @@ int Tdi3Verify(struct descriptor *str_ptr, struct descriptor *set_ptr, if (StrPosition(&set_dsc, &tmp_dsc, 0) == 0) break; j = tmp_dsc.pointer - str_dsc.pointer; - } else + } + else j = StrFindFirstNotInSet(&str_dsc, &set_dsc) - 1; *out_point++ = j; str_dsc.pointer += step_str; diff --git a/tdishr/TdiCompile.c b/tdishr/TdiCompile.c index f8351aed99..1af4d5294b 100644 --- a/tdishr/TdiCompile.c +++ b/tdishr/TdiCompile.c @@ -50,9 +50,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define DEBUG #ifdef DEBUG - #define DBG(...) fprintf(stderr,__VA_ARGS__) +#define DBG(...) fprintf(stderr, __VA_ARGS__) #else - #define DBG(...) {/**/} +#define DBG(...) \ + { /**/ \ + } #endif extern int Tdi1Evaluate(); @@ -66,7 +68,8 @@ extern int tdi_yacc(); supports (`) on COMPILE */ -static void cleanup_compile(TDITHREADSTATIC_ARG){ +static void cleanup_compile(TDITHREADSTATIC_ARG) +{ LibResetVmZone(&TDI_REFZONE.l_zone); tdipop_buffer_state(TDI_SCANNER); TDI_BUFFER = TDI_REFZONE.a_begin = NULL; @@ -75,13 +78,10 @@ static void cleanup_compile(TDITHREADSTATIC_ARG){ extern void tdi_push_new_buffer(mdsdsc_t *text_ptr, TDITHREADSTATIC_ARG); -static inline void add_compile_info(int status,TDITHREADSTATIC_ARG) { - if(!(status==TdiSYNTAX - || status==TdiEXTRANEOUS - || status==TdiUNBALANCE - || status==TreeNOT_OPEN - || status==TreeNNF - || status==TdiBOMB)) return; +static inline void add_compile_info(int status, TDITHREADSTATIC_ARG) +{ + if (!(status == TdiSYNTAX || status == TdiEXTRANEOUS || status == TdiUNBALANCE || status == TreeNOT_OPEN || status == TreeNNF || status == TdiBOMB)) + return; static const DESCRIPTOR(compile_err, "%TDI Error compiling region marked by ^\n"); if (!TDI_REFZONE.a_begin || TDI_INTRINSIC_MSG.length >= MAXMESS) return; @@ -91,73 +91,78 @@ static inline void add_compile_info(int status,TDITHREADSTATIC_ARG) { char *e = TDI_REFZONE.a_end; char *c = MINMAX(b, TDI_REFZONE.a_cur, e); char *x = MINMAX(b, b + TDI_REFZONE.l_ok, c); - int xc = MINMAX(0, c-x, MAXLINE); - int ce = MINMAX(0, e-c, MAXLINE); - int bx = MINMAX(0, x-b, MAXLINE); - if (xc+ce > MAXLINE) + int xc = MINMAX(0, c - x, MAXLINE); + int ce = MINMAX(0, e - c, MAXLINE); + int bx = MINMAX(0, x - b, MAXLINE); + if (xc + ce > MAXLINE) ce = MINMAX(0, ce, MAXFRAC); - if (bx+xc+ce > MAXLINE) + if (bx + xc + ce > MAXLINE) bx = MINMAX(0, bx, MAXFRAC); - int len = bx+xc+2; - mdsdsc_t marker = { len, DTYPE_T, CLASS_S, memset(malloc(len+1),' ',len) }; - mdsdsc_t region = { bx+xc+ce, DTYPE_T, CLASS_S, x-bx }; - marker.pointer[bx]='^'; - marker.pointer[0] = marker.pointer[len-1]='\n'; - if (xc>0) - marker.pointer[bx+xc]='^'; - else if (bx>0) - marker.pointer[bx]='^'; - StrAppend(&TDI_INTRINSIC_MSG,(mdsdsc_t *)&compile_err); - StrAppend(&TDI_INTRINSIC_MSG,(mdsdsc_t *)®ion); - StrAppend(&TDI_INTRINSIC_MSG,(mdsdsc_t *)&marker); + int len = bx + xc + 2; + mdsdsc_t marker = {len, DTYPE_T, CLASS_S, memset(malloc(len + 1), ' ', len)}; + mdsdsc_t region = {bx + xc + ce, DTYPE_T, CLASS_S, x - bx}; + marker.pointer[bx] = '^'; + marker.pointer[0] = marker.pointer[len - 1] = '\n'; + if (xc > 0) + marker.pointer[bx + xc] = '^'; + else if (bx > 0) + marker.pointer[bx] = '^'; + StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)&compile_err); + StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)®ion); + StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)&marker); free(marker.pointer); } -static inline int compile(mdsdsc_t * text_ptr, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) { +static inline int compile(mdsdsc_t *text_ptr, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) +{ int status; if (!TDI_REFZONE.l_zone && IS_NOT_OK(status = LibCreateVmZone(&TDI_REFZONE.l_zone))) return status; - pthread_cleanup_push((void*)cleanup_compile,(void*)TDITHREADSTATIC_VAR); + pthread_cleanup_push((void *)cleanup_compile, (void *)TDITHREADSTATIC_VAR); tdi_push_new_buffer(text_ptr, TDITHREADSTATIC_VAR); TDI_COMPILE_REC = TRUE; - TDI_REFZONE.l_status = TdiBOMB; // In case we bomb out - TDI_REFZONE.l_narg = narg - 1; - TDI_REFZONE.l_iarg = 0; - TDI_REFZONE.a_list = list; + TDI_REFZONE.l_status = TdiBOMB; // In case we bomb out + TDI_REFZONE.l_narg = narg - 1; + TDI_REFZONE.l_iarg = 0; + TDI_REFZONE.a_list = list; if (tdi_yacc(TDITHREADSTATIC_VAR) && IS_OK(TDI_REFZONE.l_status)) status = TdiSYNTAX; else status = TDI_REFZONE.l_status; - /************************ + /************************ Move from temporary zone. ************************/ - if STATUS_OK { + if (STATUS_OK) + { if (TDI_REFZONE.a_result == 0) MdsFree1Dx(out_ptr, NULL); else status = MdsCopyDxXd((mdsdsc_t *)TDI_REFZONE.a_result, out_ptr); } - add_compile_info(status,TDITHREADSTATIC_VAR); + add_compile_info(status, TDITHREADSTATIC_VAR); pthread_cleanup_pop(1); return status; } -int Tdi1Compile(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr){ +int Tdi1Compile(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ int status; TDITHREADSTATIC_INIT; - if (TDI_COMPILE_REC) { + if (TDI_COMPILE_REC) + { fprintf(stderr, "Error: Recursive calls to TDI Compile\n"); return TdiRECURSIVE; } INIT_AND_FREEXD_ON_EXIT(tmp); - status = Tdi1Evaluate(opcode, 1, list, &tmp);// using Tdi1Evaluate over TdiEvaluate saves 3 stack levels + status = Tdi1Evaluate(opcode, 1, list, &tmp); // using Tdi1Evaluate over TdiEvaluate saves 3 stack levels mdsdsc_t *text_ptr = tmp.pointer; if (STATUS_OK && text_ptr->dtype != DTYPE_T) status = TdiINVDTYDSC; else if (STATUS_OK && text_ptr->length > 0) - status = compile(text_ptr,narg,list,out_ptr,TDITHREADSTATIC_VAR); + status = compile(text_ptr, narg, list, out_ptr, TDITHREADSTATIC_VAR); FREEXD_NOW(&tmp); - if STATUS_NOT_OK MdsFree1Dx(out_ptr, NULL); + if (STATUS_NOT_OK) + MdsFree1Dx(out_ptr, NULL); return status; } @@ -165,15 +170,17 @@ int Tdi1Compile(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_pt Compile and evaluate an expression. result = EXECUTE(string, [arg1,...]) */ -int Tdi1Execute(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr){ +int Tdi1Execute(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; FREEXD_ON_EXIT(out_ptr); INIT_AND_FREEXD_ON_EXIT(tmp); status = Tdi1Compile(opcode, narg, list, &tmp); - if STATUS_OK + if (STATUS_OK) status = Tdi1Evaluate(opcode, 1, &tmp.pointer, out_ptr); FREEXD_NOW(&tmp); - if STATUS_NOT_OK MdsFree1Dx(out_ptr, NULL); + if (STATUS_NOT_OK) + MdsFree1Dx(out_ptr, NULL); FREE_CANCEL(out_ptr); return status; } diff --git a/tdishr/TdiCompileDependency.c b/tdishr/TdiCompileDependency.c index 950ccc901f..a32a55b0bf 100644 --- a/tdishr/TdiCompileDependency.c +++ b/tdishr/TdiCompileDependency.c @@ -31,7 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tdirefstandard.h" int Tdi1CompileDependency(/*opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr*/) + struct descriptor_xd *out_ptr*/ +) { return 1; } diff --git a/tdishr/TdiConstant.c b/tdishr/TdiConstant.c index 196a449c5d..7b09debbdb 100644 --- a/tdishr/TdiConstant.c +++ b/tdishr/TdiConstant.c @@ -40,7 +40,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") int Tdi1Constant(opcode_t opcode, int narg __attribute__((unused)), mdsdsc_t *list[] __attribute__((unused)), - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ return MdsCopyDxXd(((mdsdsc_t * (*)()) * TdiRefFunction[opcode].f3)(), out_ptr); @@ -86,59 +87,64 @@ typedef void *MISSING; typedef uint8_t BU; typedef float FS; typedef double FT; -typedef struct { +typedef struct +{ float x, y; } FSC; typedef unsigned int FROP; #define DTYPE_FROP DTYPE_F -#define DATUM(type, x, data) \ - mdsdsc_t *Tdi3##x() { \ - static const type val = data; \ - static const mdsdsc_t constant = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&val}; \ - return (mdsdsc_t *)&constant; \ +#define DATUM(type, x, data) \ + mdsdsc_t *Tdi3##x() \ + { \ + static const type val = data; \ + static const mdsdsc_t constant = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&val}; \ + return (mdsdsc_t *)&constant; \ } -#define UNITS(type, x, data, units) \ - mdsdsc_t *Tdi3##x() { \ - static const type val = data; \ - static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&val}; \ - static const DESCRIPTOR(units_d, units); \ - static const DESCRIPTOR_WITH_UNITS(constant, &val_d, &units_d); \ - return (mdsdsc_t *)&constant; \ +#define UNITS(type, x, data, units) \ + mdsdsc_t *Tdi3##x() \ + { \ + static const type val = data; \ + static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&val}; \ + static const DESCRIPTOR(units_d, units); \ + static const DESCRIPTOR_WITH_UNITS(constant, &val_d, &units_d); \ + return (mdsdsc_t *)&constant; \ } -#define CAST_ERROR(type, x) \ - (((x) - (double)(type)(x)) < 0 ? ((double)(type)(x) - (x)) \ +#define CAST_ERROR(type, x) \ + (((x) - (double)(type)(x)) < 0 ? ((double)(type)(x) - (x)) \ : ((x) - (double)(type)(x))) -#define DERR(type, x, data, error) \ - mdsdsc_t *Tdi3##x() { \ - static const type val = data; \ - static const type err = CAST_ERROR(type, data) + error; \ - static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&val}; \ - static const mdsdsc_t err_d = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&err}; \ - static const DESCRIPTOR_WITH_ERROR(constant, &val_d, &err_d); \ - return (mdsdsc_t *)&constant; \ +#define DERR(type, x, data, error) \ + mdsdsc_t *Tdi3##x() \ + { \ + static const type val = data; \ + static const type err = CAST_ERROR(type, data) + error; \ + static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&val}; \ + static const mdsdsc_t err_d = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&err}; \ + static const DESCRIPTOR_WITH_ERROR(constant, &val_d, &err_d); \ + return (mdsdsc_t *)&constant; \ } -#define UERR(type, x, data, error, units) \ - mdsdsc_t *Tdi3##x() { \ - static const type val = data; \ - static const type err = CAST_ERROR(type, data) + error; \ - static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&val}; \ - static const mdsdsc_t err_d = {sizeof(type), DTYPE_##type, CLASS_S, \ - (char *)&err}; \ - static const DESCRIPTOR(units_d, units); \ - static const DESCRIPTOR_WITH_ERROR(werr_d, &val_d, &err_d); \ - static const DESCRIPTOR_WITH_UNITS(constant, &werr_d, &units_d); \ - return (mdsdsc_t *)&constant; \ +#define UERR(type, x, data, error, units) \ + mdsdsc_t *Tdi3##x() \ + { \ + static const type val = data; \ + static const type err = CAST_ERROR(type, data) + error; \ + static const mdsdsc_t val_d = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&val}; \ + static const mdsdsc_t err_d = {sizeof(type), DTYPE_##type, CLASS_S, \ + (char *)&err}; \ + static const DESCRIPTOR(units_d, units); \ + static const DESCRIPTOR_WITH_ERROR(werr_d, &val_d, &err_d); \ + static const DESCRIPTOR_WITH_UNITS(constant, &werr_d, &units_d); \ + return (mdsdsc_t *)&constant; \ } #ifdef M_PI @@ -154,8 +160,10 @@ typedef unsigned int FROP; #define GAS_DATA 8.31446261815324 #define GN_DATA 9.80665 #define H_DATA 6.62607015e-34 -#define I_DATA \ - { 0., 1. } +#define I_DATA \ + { \ + 0., 1. \ + } #define K_DATA 1.3806505e-23 #define MU0_DATA (4e-7 * PI_DATA) #define NA_DATA 6.02214076e23 @@ -180,12 +188,12 @@ typedef unsigned int FROP; #define MP_ERROR 51e-38 /*negligible*/ // values by relation #define NEGLIGIBLE 0 -#define A0_DATA \ +#define A0_DATA \ ((EPS0_DATA * H_DATA * H_DATA) / (PI_DATA * E_DATA * E_DATA * ME_DATA)) -#define RE_DATA \ - ((MU0_DATA * C_DATA * C_DATA * E_DATA * E_DATA) / \ +#define RE_DATA \ + ((MU0_DATA * C_DATA * C_DATA * E_DATA * E_DATA) / \ (4 * PI_DATA * ME_DATA * C_DATA * C_DATA)) -#define RYDBERG_DATA \ +#define RYDBERG_DATA \ ((ALPHA_DATA * ALPHA_DATA * ME_DATA * C_DATA) / (2 * H_DATA)) DATUM(BU, False, 0) /* logically false */ diff --git a/tdishr/TdiConvert.c b/tdishr/TdiConvert.c index a5ee08fee1..f064f827b2 100644 --- a/tdishr/TdiConvert.c +++ b/tdishr/TdiConvert.c @@ -38,458 +38,748 @@ extern int IsRoprand(); #ifdef min #undef min #endif -#define min(a,b) (((a) < (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) #ifdef max #undef max #endif -#define max(a,b) (((a) < (b)) ? (b) : (a)) +#define max(a, b) (((a) < (b)) ? (b) : (a)) /****** Identity conversions handled before big switch *********/ -#define BU_BU(lena,pa,lenb,pb,numb) -#define WU_WU(lena,pa,lenb,pb,numb) -#define LU_LU(lena,pa,lenb,pb,numb) -#define QU_QU(lena,pa,lenb,pb,numb) -#define OU_OU(lena,pa,lenb,pb,numb) -#define B_B(lena,pa,lenb,pb,numb) -#define W_W(lena,pa,lenb,pb,numb) -#define L_L(lena,pa,lenb,pb,numb) -#define Q_Q(lena,pa,lenb,pb,numb) -#define O_O(lena,pa,lenb,pb,numb) -#define F_F(lena,pa,lenb,pb,numb) -#define FS_FS(lena,pa,lenb,pb,numb) -#define D_D(lena,pa,lenb,pb,numb) -#define G_G(lena,pa,lenb,pb,numb) -#define FT_FT(lena,pa,lenb,pb,numb) -#define FC_FC(lena,pa,lenb,pb,numb) -#define FSC_FSC(lena,pa,lenb,pb,numb) -#define DC_DC(lena,pa,lenb,pb,numb) -#define GC_GC(lena,pa,lenb,pb,numb) -#define FTC_FTC(lena,pa,lenb,pb,numb) +#define BU_BU(lena, pa, lenb, pb, numb) +#define WU_WU(lena, pa, lenb, pb, numb) +#define LU_LU(lena, pa, lenb, pb, numb) +#define QU_QU(lena, pa, lenb, pb, numb) +#define OU_OU(lena, pa, lenb, pb, numb) +#define B_B(lena, pa, lenb, pb, numb) +#define W_W(lena, pa, lenb, pb, numb) +#define L_L(lena, pa, lenb, pb, numb) +#define Q_Q(lena, pa, lenb, pb, numb) +#define O_O(lena, pa, lenb, pb, numb) +#define F_F(lena, pa, lenb, pb, numb) +#define FS_FS(lena, pa, lenb, pb, numb) +#define D_D(lena, pa, lenb, pb, numb) +#define G_G(lena, pa, lenb, pb, numb) +#define FT_FT(lena, pa, lenb, pb, numb) +#define FC_FC(lena, pa, lenb, pb, numb) +#define FSC_FSC(lena, pa, lenb, pb, numb) +#define DC_DC(lena, pa, lenb, pb, numb) +#define GC_GC(lena, pa, lenb, pb, numb) +#define FTC_FTC(lena, pa, lenb, pb, numb) /************* Straight binary conversions *************************/ -#define CONVERT_BINARY(ti,to,pa,pb,numb) { ti *ip = (ti *)pa; to *op = (to *)pb; while (numb-- > 0) *op++ = (to)*ip++; status = MDSplusSUCCESS;} -#define BU_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned char,unsigned short,pa,pb,numb) -#define BU_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned char,unsigned int,pa,pb,numb) -#define BU_B(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned char,char,pa,pb,numb) -#define BU_W(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned char,short,pa,pb,numb) -#define BU_L(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned char,int,pa,pb,numb) -#define WU_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned short,unsigned char,pa,pb,numb) -#define WU_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned short,unsigned int,pa,pb,numb) -#define WU_B(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned short,char,pa,pb,numb) -#define WU_W(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned short,short,pa,pb,numb) -#define WU_L(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned short,int,pa,pb,numb) -#define LU_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned int,unsigned char,pa,pb,numb) -#define LU_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned int,unsigned short,pa,pb,numb) -#define LU_B(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned int,char,pa,pb,numb) -#define LU_W(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned int,short,pa,pb,numb) -#define LU_L(lena,pa,lenb,pb,numb) CONVERT_BINARY(unsigned int,int,pa,pb,numb) -#define B_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY(char,unsigned char,pa,pb,numb) -#define B_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY(char,unsigned short,pa,pb,numb) -#define B_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY(char,unsigned int,pa,pb,numb) -#define B_W(lena,pa,lenb,pb,numb) CONVERT_BINARY(char,short,pa,pb,numb) -#define B_L(lena,pa,lenb,pb,numb) CONVERT_BINARY(char,int,pa,pb,numb) -#define W_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY(short,unsigned char,pa,pb,numb) -#define W_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY(short,unsigned short,pa,pb,numb) -#define W_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY(short,unsigned int,pa,pb,numb) -#define W_B(lena,pa,lenb,pb,numb) CONVERT_BINARY(short,char,pa,pb,numb) -#define W_L(lena,pa,lenb,pb,numb) CONVERT_BINARY(short,int,pa,pb,numb) -#define L_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY(int,unsigned char,pa,pb,numb) -#define L_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY(int,unsigned short,pa,pb,numb) -#define L_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY(int,unsigned int,pa,pb,numb) -#define L_B(lena,pa,lenb,pb,numb) CONVERT_BINARY(int,char,pa,pb,numb) -#define L_W(lena,pa,lenb,pb,numb) CONVERT_BINARY(int,short,pa,pb,numb) +#define CONVERT_BINARY(ti, to, pa, pb, numb) \ + { \ + ti *ip = (ti *)pa; \ + to *op = (to *)pb; \ + while (numb-- > 0) \ + *op++ = (to)*ip++; \ + status = MDSplusSUCCESS; \ + } +#define BU_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned char, unsigned short, pa, pb, numb) +#define BU_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned char, unsigned int, pa, pb, numb) +#define BU_B(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned char, char, pa, pb, numb) +#define BU_W(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned char, short, pa, pb, numb) +#define BU_L(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned char, int, pa, pb, numb) +#define WU_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned short, unsigned char, pa, pb, numb) +#define WU_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned short, unsigned int, pa, pb, numb) +#define WU_B(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned short, char, pa, pb, numb) +#define WU_W(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned short, short, pa, pb, numb) +#define WU_L(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned short, int, pa, pb, numb) +#define LU_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned int, unsigned char, pa, pb, numb) +#define LU_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned int, unsigned short, pa, pb, numb) +#define LU_B(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned int, char, pa, pb, numb) +#define LU_W(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned int, short, pa, pb, numb) +#define LU_L(lena, pa, lenb, pb, numb) CONVERT_BINARY(unsigned int, int, pa, pb, numb) +#define B_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY(char, unsigned char, pa, pb, numb) +#define B_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY(char, unsigned short, pa, pb, numb) +#define B_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY(char, unsigned int, pa, pb, numb) +#define B_W(lena, pa, lenb, pb, numb) CONVERT_BINARY(char, short, pa, pb, numb) +#define B_L(lena, pa, lenb, pb, numb) CONVERT_BINARY(char, int, pa, pb, numb) +#define W_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY(short, unsigned char, pa, pb, numb) +#define W_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY(short, unsigned short, pa, pb, numb) +#define W_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY(short, unsigned int, pa, pb, numb) +#define W_B(lena, pa, lenb, pb, numb) CONVERT_BINARY(short, char, pa, pb, numb) +#define W_L(lena, pa, lenb, pb, numb) CONVERT_BINARY(short, int, pa, pb, numb) +#define L_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY(int, unsigned char, pa, pb, numb) +#define L_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY(int, unsigned short, pa, pb, numb) +#define L_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY(int, unsigned int, pa, pb, numb) +#define L_B(lena, pa, lenb, pb, numb) CONVERT_BINARY(int, char, pa, pb, numb) +#define L_W(lena, pa, lenb, pb, numb) CONVERT_BINARY(int, short, pa, pb, numb) /************* Extended binary conversions *************************/ #ifdef WORDS_BIGENDIAN -#define CONVERT_BINARY_ZETEND(ti,pa,pb,numb,nints) { int i; ti *ip = (ti *)pa; unsigned int *op = (unsigned int *)pb; \ - while (numb-- > 0) {for(i=1;i 0) {int extend = (*ip < 0) ? -1 : 0; for(i=1;i 0) {for (i=0;i 0) {for (i=0;i 0) {for (i=0;i 0) \ + { \ + for (i = 1; i < nints; i++) \ + *op++ = (unsigned int)0; \ + *op++ = (unsigned int)*ip++; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_SETEND(ti, pa, pb, numb, nints) \ + { \ + int i; \ + ti *ip = (ti *)pa; \ + int *op = (int *)pb; \ + while (numb-- > 0) \ + { \ + int extend = (*ip < 0) ? -1 : 0; \ + for (i = 1; i < nints; i++) \ + *op++ = extend; \ + *op++ = (int)*ip++; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lenb; i++) \ + *pb++ = pa[i + lena - lenb]; \ + pa += lena; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_LARGER_ZEXTEND(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lena; i++) \ + pb[lenb - i - 1] = pa[lena - i - 1]; \ + for (i = lena; i < lenb; i++) \ + pb[lenb - i - 1] = (char)0; \ + pb += lenb; \ + pa += lena; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_LARGER_SEXTEND(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lena; i++) \ + pb[lenb - i - 1] = pa[lena - i - 1]; \ + for (i = lena; i < lenb; i++) \ + pb[lenb - i - 1] = (char)((pa[0] < 0) ? -1 : 0); \ + pb += lenb; \ + pa += lena; \ + } \ + status = MDSplusSUCCESS; \ + } #else -#define CONVERT_BINARY_ZETEND(ti,pa,pb,numb,nints) { int i; ti *ip = (ti *)pa; unsigned int *op = (unsigned int *)pb; \ - while (numb-- > 0) {*op++ = (unsigned int)*ip++; for(i=1;i 0) {int extend = (*ip < 0) ? -1 : 0; *op++ = (int)*ip++; for(i=1;i 0) {for (i=0;i 0) {for (i=0;i 0) {for (i=0;i 0) \ + { \ + *op++ = (unsigned int)*ip++; \ + for (i = 1; i < nints; i++) \ + *op++ = (unsigned int)0; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_SETEND(ti, pa, pb, numb, nints) \ + { \ + int i; \ + ti *ip = (ti *)pa; \ + int *op = (int *)pb; \ + while (numb-- > 0) \ + { \ + int extend = (*ip < 0) ? -1 : 0; \ + *op++ = (int)*ip++; \ + for (i = 1; i < nints; i++) \ + *op++ = extend; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lenb; i++) \ + *pb++ = pa[i]; \ + pa += lena; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_LARGER_ZEXTEND(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lena; i++) \ + *pb++ = *pa++; \ + for (i = lena; i < lenb; i++) \ + *pb++ = (char)0; \ + } \ + status = MDSplusSUCCESS; \ + } +#define CONVERT_BINARY_LARGER_SEXTEND(pa, pb, numb, lena, lenb) \ + { \ + int i; \ + while (numb-- > 0) \ + { \ + for (i = 0; i < lena; i++) \ + *pb++ = *pa++; \ + for (i = lena; i < lenb; i++) \ + *pb++ = (char)((pa[-1] < 0) ? -1 : 0); \ + } \ + status = MDSplusSUCCESS; \ + } #endif -#define BU_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned char,pa,pb,numb,2) -#define BU_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned char,pa,pb,numb,4) -#define WU_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned short,pa,pb,numb,2) -#define WU_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned short,pa,pb,numb,4) -#define LU_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned int,pa,pb,numb,2) -#define LU_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned int,pa,pb,numb,4) -#define B_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(char,pa,pb,numb,2) -#define B_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(char,pa,pb,numb,4) -#define W_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(short,pa,pb,numb,2) -#define W_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(short,pa,pb,numb,4) -#define L_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(int,pa,pb,numb,2) -#define L_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(int,pa,pb,numb,4) -#define BU_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned char,pa,pb,numb,2) -#define BU_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned char,pa,pb,numb,4) -#define WU_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned short,pa,pb,numb,2) -#define WU_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned short,pa,pb,numb,4) -#define LU_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned int,pa,pb,numb,2) -#define LU_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_ZETEND(unsigned int,pa,pb,numb,4) -#define B_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(char,pa,pb,numb,2) -#define B_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(char,pa,pb,numb,4) -#define W_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(short,pa,pb,numb,2) -#define W_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(short,pa,pb,numb,4) -#define L_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(int,pa,pb,numb,2) -#define L_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_SETEND(int,pa,pb,numb,4) -#define QU_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_B(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_W(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_L(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_B(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_W(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_L(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_B(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_W(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_L(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_BU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_WU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_LU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_B(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_W(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_L(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_LARGER_ZEXTEND(pa,pb,numb,lena,lenb) -#define QU_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define QU_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_LARGER_ZEXTEND(pa,pb,numb,lena,lenb) -#define OU_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define OU_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define Q_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_LARGER_SEXTEND(pa,pb,numb,lena,lenb) -#define Q_O(lena,pa,lenb,pb,numb) CONVERT_BINARY_LARGER_SEXTEND(pa,pb,numb,lena,lenb) -#define O_QU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_OU(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) -#define O_Q(lena,pa,lenb,pb,numb) CONVERT_BINARY_SMALLER(pa,pb,numb,lena,lenb) +#define BU_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned char, pa, pb, numb, 2) +#define BU_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned char, pa, pb, numb, 4) +#define WU_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned short, pa, pb, numb, 2) +#define WU_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned short, pa, pb, numb, 4) +#define LU_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned int, pa, pb, numb, 2) +#define LU_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned int, pa, pb, numb, 4) +#define B_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(char, pa, pb, numb, 2) +#define B_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(char, pa, pb, numb, 4) +#define W_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(short, pa, pb, numb, 2) +#define W_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(short, pa, pb, numb, 4) +#define L_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(int, pa, pb, numb, 2) +#define L_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(int, pa, pb, numb, 4) +#define BU_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned char, pa, pb, numb, 2) +#define BU_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned char, pa, pb, numb, 4) +#define WU_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned short, pa, pb, numb, 2) +#define WU_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned short, pa, pb, numb, 4) +#define LU_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned int, pa, pb, numb, 2) +#define LU_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_ZETEND(unsigned int, pa, pb, numb, 4) +#define B_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(char, pa, pb, numb, 2) +#define B_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(char, pa, pb, numb, 4) +#define W_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(short, pa, pb, numb, 2) +#define W_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(short, pa, pb, numb, 4) +#define L_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(int, pa, pb, numb, 2) +#define L_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_SETEND(int, pa, pb, numb, 4) +#define QU_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_B(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_W(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_L(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_B(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_W(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_L(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_B(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_W(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_L(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_BU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_WU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_LU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_B(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_W(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_L(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_LARGER_ZEXTEND(pa, pb, numb, lena, lenb) +#define QU_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define QU_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_LARGER_ZEXTEND(pa, pb, numb, lena, lenb) +#define OU_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define OU_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define Q_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_LARGER_SEXTEND(pa, pb, numb, lena, lenb) +#define Q_O(lena, pa, lenb, pb, numb) CONVERT_BINARY_LARGER_SEXTEND(pa, pb, numb, lena, lenb) +#define O_QU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_OU(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) +#define O_Q(lena, pa, lenb, pb, numb) CONVERT_BINARY_SMALLER(pa, pb, numb, lena, lenb) /*********** Binary to Floating Point ****************************/ -#define CONVERT_FLOAT(pb,numb,otype) if (otype != DTYPE_NATIVE_FLOAT) {int i=numb; float *op = (float *)pb; \ - while (i-- > 0) {float tmp = *op; CvtConvertFloat(&tmp, DTYPE_NATIVE_FLOAT, op++, otype, 0);}} +#define CONVERT_FLOAT(pb, numb, otype) \ + if (otype != DTYPE_NATIVE_FLOAT) \ + { \ + int i = numb; \ + float *op = (float *)pb; \ + while (i-- > 0) \ + { \ + float tmp = *op; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_FLOAT, op++, otype, 0); \ + } \ + } -#define CONVERT_DOUBLE(pb,numb,otype) if (otype != DTYPE_NATIVE_DOUBLE) {int i=numb; double *op = (double *)pb; \ - while (i-- > 0) {double tmp = *op; CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, op++, otype, 0);}} +#define CONVERT_DOUBLE(pb, numb, otype) \ + if (otype != DTYPE_NATIVE_DOUBLE) \ + { \ + int i = numb; \ + double *op = (double *)pb; \ + while (i-- > 0) \ + { \ + double tmp = *op; \ + CvtConvertFloat(&tmp, DTYPE_NATIVE_DOUBLE, op++, otype, 0); \ + } \ + } -#define BINARY_TO_FLOAT(ti,pa,pb,numb,otype) \ - {int i=numb; ti *ip=(ti*)pa; float *op=(float*)pb; while (i-- > 0) *op++ =(float)*ip++; status = MDSplusSUCCESS; CONVERT_FLOAT(pb,numb,otype)} +#define BINARY_TO_FLOAT(ti, pa, pb, numb, otype) \ + { \ + int i = numb; \ + ti *ip = (ti *)pa; \ + float *op = (float *)pb; \ + while (i-- > 0) \ + *op++ = (float)*ip++; \ + status = MDSplusSUCCESS; \ + CONVERT_FLOAT(pb, numb, otype) \ + } -#define BINARY_TO_DOUBLE(ti,pa,pb,numb,otype) \ - {int i=numb; ti *ip=(ti*)pa; double *op=(double*)pb; while (i-- > 0) *op++ =(double)*ip++; status = MDSplusSUCCESS;\ - CONVERT_DOUBLE(pb,numb,otype)} +#define BINARY_TO_DOUBLE(ti, pa, pb, numb, otype) \ + { \ + int i = numb; \ + ti *ip = (ti *)pa; \ + double *op = (double *)pb; \ + while (i-- > 0) \ + *op++ = (double)*ip++; \ + status = MDSplusSUCCESS; \ + CONVERT_DOUBLE(pb, numb, otype) \ + } -#define BINARY_TO_FLOATC(ti,pa,pb,numb,otype) \ - {int i=numb; ti *ip=(ti*)pa; float *op=(float*)pb; while (i-- > 0) {*op++ =(float)*ip++; *op++ = (float)0.0;} status = MDSplusSUCCESS; \ - CONVERT_FLOAT(pb,numb*2,otype)} +#define BINARY_TO_FLOATC(ti, pa, pb, numb, otype) \ + { \ + int i = numb; \ + ti *ip = (ti *)pa; \ + float *op = (float *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (float)*ip++; \ + *op++ = (float)0.0; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_FLOAT(pb, numb * 2, otype) \ + } -#define BINARY_TO_DOUBLEC(ti,pa,pb,numb,otype) \ - {int i=numb; ti *ip=(ti*)pa; double *op=(double*)pb; while (i-- > 0) {*op++ =(double)*ip++; *op++ = (double)0.0;} status = MDSplusSUCCESS; \ - CONVERT_DOUBLE(pb,numb*2,otype)} +#define BINARY_TO_DOUBLEC(ti, pa, pb, numb, otype) \ + { \ + int i = numb; \ + ti *ip = (ti *)pa; \ + double *op = (double *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (double)*ip++; \ + *op++ = (double)0.0; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_DOUBLE(pb, numb * 2, otype) \ + } -#define BU_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned char, pa, pb, numb, DTYPE_F) -#define BU_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_D) -#define BU_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_G) -#define BU_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned char, pa, pb, numb, DTYPE_F) -#define BU_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_D) -#define BU_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_G) -#define BU_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned char, pa, pb, numb, DTYPE_FS) -#define BU_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_FT) -#define BU_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned char, pa, pb, numb, DTYPE_FSC) -#define BU_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_FTC) -#define WU_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned short, pa, pb, numb, DTYPE_F) -#define WU_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_D) -#define WU_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_G) -#define WU_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned short, pa, pb, numb, DTYPE_F) -#define WU_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_D) -#define WU_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_G) -#define WU_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned short, pa, pb, numb, DTYPE_FS) -#define WU_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_FT) -#define WU_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned short, pa, pb, numb, DTYPE_FSC) -#define WU_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_FTC) -#define LU_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned int, pa, pb, numb, DTYPE_F) -#define LU_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_D) -#define LU_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_G) -#define LU_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned int, pa, pb, numb, DTYPE_F) -#define LU_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_D) -#define LU_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_G) -#define LU_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(unsigned int, pa, pb, numb, DTYPE_FS) -#define LU_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_FT) -#define LU_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(unsigned int, pa, pb, numb, DTYPE_FSC) -#define LU_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_FTC) -#define B_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(char, pa, pb, numb, DTYPE_F) -#define B_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_D) -#define B_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_G) -#define B_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(char, pa, pb, numb, DTYPE_F) -#define B_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_D) -#define B_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_G) -#define B_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(char, pa, pb, numb, DTYPE_FS) -#define B_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_FT) -#define B_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(char, pa, pb, numb, DTYPE_FSC) -#define B_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_FTC) -#define W_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(short, pa, pb, numb, DTYPE_F) -#define W_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_D) -#define W_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_G) -#define W_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(short, pa, pb, numb, DTYPE_F) -#define W_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_D) -#define W_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_G) -#define W_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(short, pa, pb, numb, DTYPE_FS) -#define W_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_FT) -#define W_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(short, pa, pb, numb, DTYPE_FSC) -#define W_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_FTC) -#define L_F(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(int, pa, pb, numb, DTYPE_F) -#define L_D(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_D) -#define L_G(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_G) -#define L_FC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(int, pa, pb, numb, DTYPE_F) -#define L_DC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_D) -#define L_GC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_G) -#define L_FS(lena,pa,lenb,pb,numb) BINARY_TO_FLOAT(int, pa, pb, numb, DTYPE_FS) -#define L_FT(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_FT) -#define L_FSC(lena,pa,lenb,pb,numb) BINARY_TO_FLOATC(int, pa, pb, numb, DTYPE_FSC) -#define L_FTC(lena,pa,lenb,pb,numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_FTC) +#define BU_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned char, pa, pb, numb, DTYPE_F) +#define BU_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_D) +#define BU_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_G) +#define BU_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned char, pa, pb, numb, DTYPE_F) +#define BU_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_D) +#define BU_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_G) +#define BU_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned char, pa, pb, numb, DTYPE_FS) +#define BU_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned char, pa, pb, numb, DTYPE_FT) +#define BU_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned char, pa, pb, numb, DTYPE_FSC) +#define BU_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned char, pa, pb, numb, DTYPE_FTC) +#define WU_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned short, pa, pb, numb, DTYPE_F) +#define WU_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_D) +#define WU_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_G) +#define WU_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned short, pa, pb, numb, DTYPE_F) +#define WU_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_D) +#define WU_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_G) +#define WU_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned short, pa, pb, numb, DTYPE_FS) +#define WU_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned short, pa, pb, numb, DTYPE_FT) +#define WU_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned short, pa, pb, numb, DTYPE_FSC) +#define WU_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned short, pa, pb, numb, DTYPE_FTC) +#define LU_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned int, pa, pb, numb, DTYPE_F) +#define LU_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_D) +#define LU_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_G) +#define LU_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned int, pa, pb, numb, DTYPE_F) +#define LU_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_D) +#define LU_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_G) +#define LU_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(unsigned int, pa, pb, numb, DTYPE_FS) +#define LU_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(unsigned int, pa, pb, numb, DTYPE_FT) +#define LU_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(unsigned int, pa, pb, numb, DTYPE_FSC) +#define LU_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(unsigned int, pa, pb, numb, DTYPE_FTC) +#define B_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(char, pa, pb, numb, DTYPE_F) +#define B_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_D) +#define B_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_G) +#define B_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(char, pa, pb, numb, DTYPE_F) +#define B_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_D) +#define B_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_G) +#define B_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(char, pa, pb, numb, DTYPE_FS) +#define B_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(char, pa, pb, numb, DTYPE_FT) +#define B_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(char, pa, pb, numb, DTYPE_FSC) +#define B_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(char, pa, pb, numb, DTYPE_FTC) +#define W_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(short, pa, pb, numb, DTYPE_F) +#define W_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_D) +#define W_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_G) +#define W_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(short, pa, pb, numb, DTYPE_F) +#define W_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_D) +#define W_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_G) +#define W_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(short, pa, pb, numb, DTYPE_FS) +#define W_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(short, pa, pb, numb, DTYPE_FT) +#define W_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(short, pa, pb, numb, DTYPE_FSC) +#define W_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(short, pa, pb, numb, DTYPE_FTC) +#define L_F(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(int, pa, pb, numb, DTYPE_F) +#define L_D(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_D) +#define L_G(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_G) +#define L_FC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(int, pa, pb, numb, DTYPE_F) +#define L_DC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_D) +#define L_GC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_G) +#define L_FS(lena, pa, lenb, pb, numb) BINARY_TO_FLOAT(int, pa, pb, numb, DTYPE_FS) +#define L_FT(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLE(int, pa, pb, numb, DTYPE_FT) +#define L_FSC(lena, pa, lenb, pb, numb) BINARY_TO_FLOATC(int, pa, pb, numb, DTYPE_FSC) +#define L_FTC(lena, pa, lenb, pb, numb) BINARY_TO_DOUBLEC(int, pa, pb, numb, DTYPE_FTC) /**************** Long Binary to Floating Point *******************************/ -#define LBINARY_TO_FLOAT(pa,pb,numb,size,is_signed,otype) \ - {int i=numb; unsigned int *ip=(unsigned int*)pa; float *op=(float*)pb;\ - while (i-- > 0) {*op++ =(float)WideIntToDouble(ip,size,is_signed); ip += size;} status = MDSplusSUCCESS; CONVERT_FLOAT(pb,numb,otype)} +#define LBINARY_TO_FLOAT(pa, pb, numb, size, is_signed, otype) \ + { \ + int i = numb; \ + unsigned int *ip = (unsigned int *)pa; \ + float *op = (float *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (float)WideIntToDouble(ip, size, is_signed); \ + ip += size; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_FLOAT(pb, numb, otype) \ + } -#define LBINARY_TO_DOUBLE(pa,pb,numb,size,is_signed,otype) \ - {int i=numb; unsigned int *ip=(unsigned int*)pa; double *op=(double*)pb;\ - while (i-- > 0) {*op++ =(double)WideIntToDouble(ip,size,is_signed); ip += size;} status = MDSplusSUCCESS; CONVERT_DOUBLE(pb,numb,otype)} +#define LBINARY_TO_DOUBLE(pa, pb, numb, size, is_signed, otype) \ + { \ + int i = numb; \ + unsigned int *ip = (unsigned int *)pa; \ + double *op = (double *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (double)WideIntToDouble(ip, size, is_signed); \ + ip += size; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_DOUBLE(pb, numb, otype) \ + } -#define LBINARY_TO_FLOATC(pa,pb,numb,size,is_signed,otype) \ - {int i=numb; unsigned int *ip=(unsigned int*)pa; float *op=(float*)pb;\ - while (i-- > 0) {*op++ =(float)WideIntToDouble(ip,size,is_signed); *op++ = (float)0.0; ip += size;} status = MDSplusSUCCESS; \ - CONVERT_FLOAT(pb,numb*2,otype)} +#define LBINARY_TO_FLOATC(pa, pb, numb, size, is_signed, otype) \ + { \ + int i = numb; \ + unsigned int *ip = (unsigned int *)pa; \ + float *op = (float *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (float)WideIntToDouble(ip, size, is_signed); \ + *op++ = (float)0.0; \ + ip += size; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_FLOAT(pb, numb * 2, otype) \ + } -#define LBINARY_TO_DOUBLEC(pa,pb,numb,size,is_signed,otype) \ - {int i=numb; unsigned int *ip=(unsigned int*)pa; double *op=(double*)pb;\ - while (i-- > 0) {*op++ =(double)WideIntToDouble(ip,size,is_signed); *op++ = (double)0.0; ip += size;} status = MDSplusSUCCESS; \ - CONVERT_DOUBLE(pb,numb*2,otype)} +#define LBINARY_TO_DOUBLEC(pa, pb, numb, size, is_signed, otype) \ + { \ + int i = numb; \ + unsigned int *ip = (unsigned int *)pa; \ + double *op = (double *)pb; \ + while (i-- > 0) \ + { \ + *op++ = (double)WideIntToDouble(ip, size, is_signed); \ + *op++ = (double)0.0; \ + ip += size; \ + } \ + status = MDSplusSUCCESS; \ + CONVERT_DOUBLE(pb, numb * 2, otype) \ + } -#define QU_F(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,2,0,DTYPE_F) -#define QU_FS(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,2,0,DTYPE_FS) -#define QU_D(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,0,DTYPE_D) -#define QU_G(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,0,DTYPE_G) -#define QU_FT(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,0,DTYPE_FT) -#define QU_FC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,2,0,DTYPE_F) -#define QU_FSC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,2,0,DTYPE_FS) -#define QU_DC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,0,DTYPE_D) -#define QU_GC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,0,DTYPE_G) -#define QU_FTC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,0,DTYPE_FT) -#define OU_F(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,4,0,DTYPE_F) -#define OU_FS(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,4,0,DTYPE_FS) -#define OU_D(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,0,DTYPE_D) -#define OU_G(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,0,DTYPE_G) -#define OU_FT(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,0,DTYPE_FT) -#define OU_FC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,4,0,DTYPE_F) -#define OU_FSC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,4,0,DTYPE_FS) -#define OU_DC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,0,DTYPE_D) -#define OU_GC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,0,DTYPE_G) -#define OU_FTC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,0,DTYPE_FT) -#define Q_F(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,2,1,DTYPE_F) -#define Q_FS(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,2,1,DTYPE_FS) -#define Q_D(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,1,DTYPE_D) -#define Q_G(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,1,DTYPE_G) -#define Q_FT(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,2,1,DTYPE_FT) -#define Q_FC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,2,1,DTYPE_F) -#define Q_FSC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,2,1,DTYPE_FS) -#define Q_DC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,1,DTYPE_D) -#define Q_GC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,1,DTYPE_G) -#define Q_FTC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,2,1,DTYPE_FT) -#define O_F(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,4,1,DTYPE_F) -#define O_FS(lena,pa,lenb,pb,numb) LBINARY_TO_FLOAT(pa,pb,numb,4,1,DTYPE_FS) -#define O_D(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,1,DTYPE_D) -#define O_G(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,1,DTYPE_G) -#define O_FT(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLE(pa,pb,numb,4,1,DTYPE_FT) -#define O_FC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,4,1,DTYPE_F) -#define O_FSC(lena,pa,lenb,pb,numb) LBINARY_TO_FLOATC(pa,pb,numb,4,1,DTYPE_FS) -#define O_DC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,1,DTYPE_D) -#define O_GC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,1,DTYPE_G) -#define O_FTC(lena,pa,lenb,pb,numb) LBINARY_TO_DOUBLEC(pa,pb,numb,4,1,DTYPE_FT) +#define QU_F(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 2, 0, DTYPE_F) +#define QU_FS(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 2, 0, DTYPE_FS) +#define QU_D(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 0, DTYPE_D) +#define QU_G(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 0, DTYPE_G) +#define QU_FT(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 0, DTYPE_FT) +#define QU_FC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 2, 0, DTYPE_F) +#define QU_FSC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 2, 0, DTYPE_FS) +#define QU_DC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 0, DTYPE_D) +#define QU_GC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 0, DTYPE_G) +#define QU_FTC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 0, DTYPE_FT) +#define OU_F(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 4, 0, DTYPE_F) +#define OU_FS(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 4, 0, DTYPE_FS) +#define OU_D(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 0, DTYPE_D) +#define OU_G(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 0, DTYPE_G) +#define OU_FT(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 0, DTYPE_FT) +#define OU_FC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 4, 0, DTYPE_F) +#define OU_FSC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 4, 0, DTYPE_FS) +#define OU_DC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 0, DTYPE_D) +#define OU_GC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 0, DTYPE_G) +#define OU_FTC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 0, DTYPE_FT) +#define Q_F(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 2, 1, DTYPE_F) +#define Q_FS(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 2, 1, DTYPE_FS) +#define Q_D(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 1, DTYPE_D) +#define Q_G(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 1, DTYPE_G) +#define Q_FT(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 2, 1, DTYPE_FT) +#define Q_FC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 2, 1, DTYPE_F) +#define Q_FSC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 2, 1, DTYPE_FS) +#define Q_DC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 1, DTYPE_D) +#define Q_GC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 1, DTYPE_G) +#define Q_FTC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 2, 1, DTYPE_FT) +#define O_F(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 4, 1, DTYPE_F) +#define O_FS(lena, pa, lenb, pb, numb) LBINARY_TO_FLOAT(pa, pb, numb, 4, 1, DTYPE_FS) +#define O_D(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 1, DTYPE_D) +#define O_G(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 1, DTYPE_G) +#define O_FT(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLE(pa, pb, numb, 4, 1, DTYPE_FT) +#define O_FC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 4, 1, DTYPE_F) +#define O_FSC(lena, pa, lenb, pb, numb) LBINARY_TO_FLOATC(pa, pb, numb, 4, 1, DTYPE_FS) +#define O_DC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 1, DTYPE_D) +#define O_GC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 1, DTYPE_G) +#define O_FTC(lena, pa, lenb, pb, numb) LBINARY_TO_DOUBLEC(pa, pb, numb, 4, 1, DTYPE_FT) /*************** Float to Binary ****************************************/ -#define FLOAT_TO_BINARY(itype,pa,pb,numb,to,mino,maxo) \ - {int i=numb; float *ip=(float*)pa; to *op=(to*)pb; \ - while (i-- > 0) { float tmp; \ - if (itype != DTYPE_NATIVE_FLOAT) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT,0); else tmp = *ip++; \ - *op++ = (to)max((float)((to)mino),min((float)((to)maxo),tmp));} status = MDSplusSUCCESS;} +#define FLOAT_TO_BINARY(itype, pa, pb, numb, to, mino, maxo) \ + { \ + int i = numb; \ + float *ip = (float *)pa; \ + to *op = (to *)pb; \ + while (i-- > 0) \ + { \ + float tmp; \ + if (itype != DTYPE_NATIVE_FLOAT) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT, 0); \ + else \ + tmp = *ip++; \ + *op++ = (to)max((float)((to)mino), min((float)((to)maxo), tmp)); \ + } \ + status = MDSplusSUCCESS; \ + } -#define DOUBLE_TO_BINARY(itype,pa,pb,numb,to,mino,maxo) \ - {int i=numb; double *ip=(double*)pa; to *op=(to*)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_DOUBLE) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = *ip++; \ - *op++ = (to)max((double)((to)mino),min((double)((to)maxo),tmp));} status = MDSplusSUCCESS;} +#define DOUBLE_TO_BINARY(itype, pa, pb, numb, to, mino, maxo) \ + { \ + int i = numb; \ + double *ip = (double *)pa; \ + to *op = (to *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_DOUBLE) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = *ip++; \ + *op++ = (to)max((double)((to)mino), min((double)((to)maxo), tmp)); \ + } \ + status = MDSplusSUCCESS; \ + } -#define FLOATC_TO_BINARY(itype,pa,pb,numb,to,mino,maxo) \ - {int i=numb; float *ip=(float*)pa; to *op=(to*)pb; \ - while (i-- > 0) { float tmp; \ - if (itype != DTYPE_NATIVE_FLOAT) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT,0); else tmp = *ip++; \ - *op++ = (to)max((float)((to)mino),min((float)((to)maxo),tmp)); ip++;} status = MDSplusSUCCESS;} +#define FLOATC_TO_BINARY(itype, pa, pb, numb, to, mino, maxo) \ + { \ + int i = numb; \ + float *ip = (float *)pa; \ + to *op = (to *)pb; \ + while (i-- > 0) \ + { \ + float tmp; \ + if (itype != DTYPE_NATIVE_FLOAT) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT, 0); \ + else \ + tmp = *ip++; \ + *op++ = (to)max((float)((to)mino), min((float)((to)maxo), tmp)); \ + ip++; \ + } \ + status = MDSplusSUCCESS; \ + } -#define DOUBLEC_TO_BINARY(itype,pa,pb,numb,to,mino,maxo) \ - {int i=numb; double *ip=(double*)pa; to *op=(to*)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_DOUBLE) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = *ip++; \ - *op++ = (to)max((double)((to)mino),min((double)((to)maxo),tmp)); ip++;} status = MDSplusSUCCESS;} +#define DOUBLEC_TO_BINARY(itype, pa, pb, numb, to, mino, maxo) \ + { \ + int i = numb; \ + double *ip = (double *)pa; \ + to *op = (to *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_DOUBLE) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = *ip++; \ + *op++ = (to)max((double)((to)mino), min((double)((to)maxo), tmp)); \ + ip++; \ + } \ + status = MDSplusSUCCESS; \ + } -#define F_BU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned char,0,0xff) -#define F_WU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned short,0,0xffff) -#define F_LU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned int,0,0xffffffff) -#define F_B(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,char,0x80,0x7f) -#define F_W(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,short,0x8000,0x7fff) -#define F_L(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_F,pa,pb,numb,int,0x80000000,0x7fffffff) -#define FS_BU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned char,0,0xff) -#define FS_WU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned short,0,0xffff) -#define FS_LU(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned int,0,0xffffffff) -#define FS_B(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,char,0x80,0x7f) -#define FS_W(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,short,0x8000,0x7fff) -#define FS_L(lena,pa,lenb,pb,numb) FLOAT_TO_BINARY(DTYPE_FS,pa,pb,numb,int,0x80000000,0x7fffffff) -#define D_BU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned char,0,0xff) -#define D_WU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned short,0,0xffff) -#define D_LU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned int,0,0xffffffff) -#define D_B(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,char,0x80,0x7f) -#define D_W(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,short,0x8000,0x7fff) -#define D_L(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_D,pa,pb,numb,int,0x80000000,0x7fffffff) -#define G_BU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned char,0,0xff) -#define G_WU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned short,0,0xffff) -#define G_LU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned int,0,0xffffffff) -#define G_B(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,char,0x80,0x7f) -#define G_W(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,short,0x8000,0x7fff) -#define G_L(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_G,pa,pb,numb,int,0x80000000,0x7fffffff) -#define FT_BU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned char,0,0xff) -#define FT_WU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned short,0,0xffff) -#define FT_LU(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned int,0,0xffffffff) -#define FT_B(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,char,0x80,0x7f) -#define FT_W(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,short,0x8000,0x7fff) -#define FT_L(lena,pa,lenb,pb,numb) DOUBLE_TO_BINARY(DTYPE_FT,pa,pb,numb,int,0x80000000,0x7fffffff) -#define FC_BU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned char,0,0xff) -#define FC_WU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned short,0,0xffff) -#define FC_LU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,unsigned int,0,0xffffffff) -#define FC_B(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,char,0x80,0x7f) -#define FC_W(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,short,0x8000,0x7fff) -#define FC_L(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_F,pa,pb,numb,int,0x80000000,0x7fffffff) -#define FSC_BU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned char,0,0xff) -#define FSC_WU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned short,0,0xffff) -#define FSC_LU(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,unsigned int,0,0xffffffff) -#define FSC_B(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,char,0x80,0x7f) -#define FSC_W(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,short,0x8000,0x7fff) -#define FSC_L(lena,pa,lenb,pb,numb) FLOATC_TO_BINARY(DTYPE_FS,pa,pb,numb,int,0x80000000,0x7fffffff) -#define DC_BU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned char,0,0xff) -#define DC_WU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned short,0,0xffff) -#define DC_LU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,unsigned int,0,0xffffffff) -#define DC_B(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,char,0x80,0x7f) -#define DC_W(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,short,0x8000,0x7fff) -#define DC_L(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_D,pa,pb,numb,int,0x80000000,0x7fffffff) -#define GC_BU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned char,0,0xff) -#define GC_WU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned short,0,0xffff) -#define GC_LU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,unsigned int,0,0xffffffff) -#define GC_B(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,char,0x80,0x7f) -#define GC_W(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,short,0x8000,0x7fff) -#define GC_L(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_G,pa,pb,numb,int,0x80000000,0x7fffffff) -#define FTC_BU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned char,0,0xff) -#define FTC_WU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned short,0,0xffff) -#define FTC_LU(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,unsigned int,0,0xffffffff) -#define FTC_B(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,char,0x80,0x7f) -#define FTC_W(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,short,0x8000,0x7fff) -#define FTC_L(lena,pa,lenb,pb,numb) DOUBLEC_TO_BINARY(DTYPE_FT,pa,pb,numb,int,0x80000000,0x7fffffff) +#define F_BU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned char, 0, 0xff) +#define F_WU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned short, 0, 0xffff) +#define F_LU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define F_B(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, char, 0x80, 0x7f) +#define F_W(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, short, 0x8000, 0x7fff) +#define F_L(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_F, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define FS_BU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned char, 0, 0xff) +#define FS_WU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned short, 0, 0xffff) +#define FS_LU(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define FS_B(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, char, 0x80, 0x7f) +#define FS_W(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, short, 0x8000, 0x7fff) +#define FS_L(lena, pa, lenb, pb, numb) FLOAT_TO_BINARY(DTYPE_FS, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define D_BU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned char, 0, 0xff) +#define D_WU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned short, 0, 0xffff) +#define D_LU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define D_B(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, char, 0x80, 0x7f) +#define D_W(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, short, 0x8000, 0x7fff) +#define D_L(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_D, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define G_BU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned char, 0, 0xff) +#define G_WU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned short, 0, 0xffff) +#define G_LU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define G_B(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, char, 0x80, 0x7f) +#define G_W(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, short, 0x8000, 0x7fff) +#define G_L(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_G, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define FT_BU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned char, 0, 0xff) +#define FT_WU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned short, 0, 0xffff) +#define FT_LU(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define FT_B(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, char, 0x80, 0x7f) +#define FT_W(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, short, 0x8000, 0x7fff) +#define FT_L(lena, pa, lenb, pb, numb) DOUBLE_TO_BINARY(DTYPE_FT, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define FC_BU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned char, 0, 0xff) +#define FC_WU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned short, 0, 0xffff) +#define FC_LU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define FC_B(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, char, 0x80, 0x7f) +#define FC_W(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, short, 0x8000, 0x7fff) +#define FC_L(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_F, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define FSC_BU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned char, 0, 0xff) +#define FSC_WU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned short, 0, 0xffff) +#define FSC_LU(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define FSC_B(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, char, 0x80, 0x7f) +#define FSC_W(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, short, 0x8000, 0x7fff) +#define FSC_L(lena, pa, lenb, pb, numb) FLOATC_TO_BINARY(DTYPE_FS, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define DC_BU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned char, 0, 0xff) +#define DC_WU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned short, 0, 0xffff) +#define DC_LU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define DC_B(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, char, 0x80, 0x7f) +#define DC_W(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, short, 0x8000, 0x7fff) +#define DC_L(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_D, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define GC_BU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned char, 0, 0xff) +#define GC_WU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned short, 0, 0xffff) +#define GC_LU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define GC_B(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, char, 0x80, 0x7f) +#define GC_W(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, short, 0x8000, 0x7fff) +#define GC_L(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_G, pa, pb, numb, int, 0x80000000, 0x7fffffff) +#define FTC_BU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned char, 0, 0xff) +#define FTC_WU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned short, 0, 0xffff) +#define FTC_LU(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, unsigned int, 0, 0xffffffff) +#define FTC_B(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, char, 0x80, 0x7f) +#define FTC_W(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, short, 0x8000, 0x7fff) +#define FTC_L(lena, pa, lenb, pb, numb) DOUBLEC_TO_BINARY(DTYPE_FT, pa, pb, numb, int, 0x80000000, 0x7fffffff) /*********** Float to Long Binary ********************/ -#define FLOAT_TO_LBINARY(itype,pa,pb,numb,size) \ - {int i=numb; float *ip=(float*)pa; unsigned int *op=(unsigned int *)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_FLOAT) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = (double)*ip++; \ - DoubleToWideInt(&tmp, size, op); op += size;} status = MDSplusSUCCESS;} +#define FLOAT_TO_LBINARY(itype, pa, pb, numb, size) \ + { \ + int i = numb; \ + float *ip = (float *)pa; \ + unsigned int *op = (unsigned int *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_FLOAT) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = (double)*ip++; \ + DoubleToWideInt(&tmp, size, op); \ + op += size; \ + } \ + status = MDSplusSUCCESS; \ + } -#define DOUBLE_TO_LBINARY(itype,pa,pb,numb,size) \ - {int i=numb; double *ip=(double*)pa; unsigned int *op=(unsigned int *)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_DOUBLE) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = *ip++; \ - DoubleToWideInt(&tmp, size, op); op += size;} status = MDSplusSUCCESS;} +#define DOUBLE_TO_LBINARY(itype, pa, pb, numb, size) \ + { \ + int i = numb; \ + double *ip = (double *)pa; \ + unsigned int *op = (unsigned int *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_DOUBLE) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = *ip++; \ + DoubleToWideInt(&tmp, size, op); \ + op += size; \ + } \ + status = MDSplusSUCCESS; \ + } -#define FLOATC_TO_LBINARY(itype,pa,pb,numb,size) \ - {int i=numb; float *ip=(float*)pa; unsigned int *op=(unsigned int *)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_FLOAT) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = (double)*ip++; \ - DoubleToWideInt(&tmp, size, op); op += size; ip++;} status = MDSplusSUCCESS;} +#define FLOATC_TO_LBINARY(itype, pa, pb, numb, size) \ + { \ + int i = numb; \ + float *ip = (float *)pa; \ + unsigned int *op = (unsigned int *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_FLOAT) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = (double)*ip++; \ + DoubleToWideInt(&tmp, size, op); \ + op += size; \ + ip++; \ + } \ + status = MDSplusSUCCESS; \ + } -#define DOUBLEC_TO_LBINARY(itype,pa,pb,numb,size) \ - {int i=numb; double *ip=(double*)pa; unsigned int *op=(unsigned int *)pb; \ - while (i-- > 0) { double tmp; \ - if (itype != DTYPE_NATIVE_DOUBLE) CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE,0); else tmp = *ip++; \ - DoubleToWideInt(&tmp, size, op); op += size; ip++;} status = MDSplusSUCCESS;} +#define DOUBLEC_TO_LBINARY(itype, pa, pb, numb, size) \ + { \ + int i = numb; \ + double *ip = (double *)pa; \ + unsigned int *op = (unsigned int *)pb; \ + while (i-- > 0) \ + { \ + double tmp; \ + if (itype != DTYPE_NATIVE_DOUBLE) \ + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); \ + else \ + tmp = *ip++; \ + DoubleToWideInt(&tmp, size, op); \ + op += size; \ + ip++; \ + } \ + status = MDSplusSUCCESS; \ + } -#define F_QU(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_F,pa,pb,numb,2) -#define F_OU(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_F,pa,pb,numb,4) -#define F_Q(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_F,pa,pb,numb,2) -#define F_O(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_F,pa,pb,numb,4) -#define FS_QU(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_FS,pa,pb,numb,2) -#define FS_OU(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_FS,pa,pb,numb,4) -#define FS_Q(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_FS,pa,pb,numb,2) -#define FS_O(lena,pa,lenb,pb,numb) FLOAT_TO_LBINARY(DTYPE_FS,pa,pb,numb,4) -#define D_QU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_D,pa,pb,numb,2) -#define D_OU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_D,pa,pb,numb,4) -#define D_Q(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_D,pa,pb,numb,2) -#define D_O(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_D,pa,pb,numb,4) -#define G_QU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_G,pa,pb,numb,2) -#define G_OU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_G,pa,pb,numb,4) -#define G_Q(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_G,pa,pb,numb,2) -#define G_O(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_G,pa,pb,numb,4) -#define FT_QU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_FT,pa,pb,numb,2) -#define FT_OU(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_FT,pa,pb,numb,4) -#define FT_Q(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_FT,pa,pb,numb,2) -#define FT_O(lena,pa,lenb,pb,numb) DOUBLE_TO_LBINARY(DTYPE_FT,pa,pb,numb,4) -#define FC_QU(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_F,pa,pb,numb,2) -#define FC_OU(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_F,pa,pb,numb,4) -#define FC_Q(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_F,pa,pb,numb,2) -#define FC_O(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_F,pa,pb,numb,4) -#define FSC_QU(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_FS,pa,pb,numb,2) -#define FSC_OU(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_FS,pa,pb,numb,4) -#define FSC_Q(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_FS,pa,pb,numb,2) -#define FSC_O(lena,pa,lenb,pb,numb) FLOATC_TO_LBINARY(DTYPE_FS,pa,pb,numb,4) -#define DC_QU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_D,pa,pb,numb,2) -#define DC_OU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_D,pa,pb,numb,4) -#define DC_Q(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_D,pa,pb,numb,2) -#define DC_O(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_D,pa,pb,numb,4) -#define GC_QU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_G,pa,pb,numb,2) -#define GC_OU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_G,pa,pb,numb,4) -#define GC_Q(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_G,pa,pb,numb,2) -#define GC_O(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_G,pa,pb,numb,4) -#define FTC_QU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_FT,pa,pb,numb,2) -#define FTC_OU(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_FT,pa,pb,numb,4) -#define FTC_Q(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_FT,pa,pb,numb,2) -#define FTC_O(lena,pa,lenb,pb,numb) DOUBLEC_TO_LBINARY(DTYPE_FT,pa,pb,numb,4) +#define F_QU(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_F, pa, pb, numb, 2) +#define F_OU(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_F, pa, pb, numb, 4) +#define F_Q(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_F, pa, pb, numb, 2) +#define F_O(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_F, pa, pb, numb, 4) +#define FS_QU(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_FS, pa, pb, numb, 2) +#define FS_OU(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_FS, pa, pb, numb, 4) +#define FS_Q(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_FS, pa, pb, numb, 2) +#define FS_O(lena, pa, lenb, pb, numb) FLOAT_TO_LBINARY(DTYPE_FS, pa, pb, numb, 4) +#define D_QU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_D, pa, pb, numb, 2) +#define D_OU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_D, pa, pb, numb, 4) +#define D_Q(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_D, pa, pb, numb, 2) +#define D_O(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_D, pa, pb, numb, 4) +#define G_QU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_G, pa, pb, numb, 2) +#define G_OU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_G, pa, pb, numb, 4) +#define G_Q(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_G, pa, pb, numb, 2) +#define G_O(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_G, pa, pb, numb, 4) +#define FT_QU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_FT, pa, pb, numb, 2) +#define FT_OU(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_FT, pa, pb, numb, 4) +#define FT_Q(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_FT, pa, pb, numb, 2) +#define FT_O(lena, pa, lenb, pb, numb) DOUBLE_TO_LBINARY(DTYPE_FT, pa, pb, numb, 4) +#define FC_QU(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_F, pa, pb, numb, 2) +#define FC_OU(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_F, pa, pb, numb, 4) +#define FC_Q(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_F, pa, pb, numb, 2) +#define FC_O(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_F, pa, pb, numb, 4) +#define FSC_QU(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_FS, pa, pb, numb, 2) +#define FSC_OU(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_FS, pa, pb, numb, 4) +#define FSC_Q(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_FS, pa, pb, numb, 2) +#define FSC_O(lena, pa, lenb, pb, numb) FLOATC_TO_LBINARY(DTYPE_FS, pa, pb, numb, 4) +#define DC_QU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_D, pa, pb, numb, 2) +#define DC_OU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_D, pa, pb, numb, 4) +#define DC_Q(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_D, pa, pb, numb, 2) +#define DC_O(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_D, pa, pb, numb, 4) +#define GC_QU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_G, pa, pb, numb, 2) +#define GC_OU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_G, pa, pb, numb, 4) +#define GC_Q(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_G, pa, pb, numb, 2) +#define GC_O(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_G, pa, pb, numb, 4) +#define FTC_QU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_FT, pa, pb, numb, 2) +#define FTC_OU(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_FT, pa, pb, numb, 4) +#define FTC_Q(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_FT, pa, pb, numb, 2) +#define FTC_O(lena, pa, lenb, pb, numb) DOUBLEC_TO_LBINARY(DTYPE_FT, pa, pb, numb, 4) /************ Float to Float *************************/ typedef union { @@ -501,141 +791,179 @@ typedef union { char i; } binary_double; -#define FLOAT_TO_FLOAT(itype,it,pa,otype,ot,pb,numb) \ - {int i=numb; \ - binary_##it *ip=(binary_##it*)pa; \ - binary_##ot *op=(binary_##ot*)pb; \ - while (i-- > 0) { \ - binary_##it tmp = *ip++; \ - CvtConvertFloat(&tmp, itype, op++, otype,0);} status = MDSplusSUCCESS;} +#define FLOAT_TO_FLOAT(itype, it, pa, otype, ot, pb, numb) \ + { \ + int i = numb; \ + binary_##it *ip = (binary_##it *)pa; \ + binary_##ot *op = (binary_##ot *)pb; \ + while (i-- > 0) \ + { \ + binary_##it tmp = *ip++; \ + CvtConvertFloat(&tmp, itype, op++, otype, 0); \ + } \ + status = MDSplusSUCCESS; \ + } -#define FLOAT_TO_COMPLEX(itype,it,pa,otype,ot,pb,numb) \ - {int i=numb; binary_##it *ip=(binary_##it*)pa; binary_##ot *op=(binary_##ot*)pb; \ - binary_##ot zero = {0.0};\ - while (i-- > 0) { if (itype == otype) *op++ = *(binary_##ot *)ip++; else { \ - binary_##it tmp = *ip++; CvtConvertFloat(&tmp, itype, op++, otype,0);} \ - *op++ = zero;\ - } status = MDSplusSUCCESS;} +#define FLOAT_TO_COMPLEX(itype, it, pa, otype, ot, pb, numb) \ + { \ + int i = numb; \ + binary_##it *ip = (binary_##it *)pa; \ + binary_##ot *op = (binary_##ot *)pb; \ + binary_##ot zero = {0.0}; \ + while (i-- > 0) \ + { \ + if (itype == otype) \ + *op++ = *(binary_##ot *)ip++; \ + else \ + { \ + binary_##it tmp = *ip++; \ + CvtConvertFloat(&tmp, itype, op++, otype, 0); \ + } \ + *op++ = zero; \ + } \ + status = MDSplusSUCCESS; \ + } -#define COMPLEX_TO_FLOAT(itype,it,pa,otype,ot,pb,numb) \ - {int i=numb; binary_##it *ip=(binary_##it*)pa; binary_##ot *op=(binary_##ot*)pb; \ - while (i-- > 0) { if (itype == otype) *op++ = *(binary_##ot *)ip++; else { \ - binary_##it tmp = *ip++; CvtConvertFloat(&tmp, itype, op++, otype,0);} ip++;} status = MDSplusSUCCESS;} +#define COMPLEX_TO_FLOAT(itype, it, pa, otype, ot, pb, numb) \ + { \ + int i = numb; \ + binary_##it *ip = (binary_##it *)pa; \ + binary_##ot *op = (binary_##ot *)pb; \ + while (i-- > 0) \ + { \ + if (itype == otype) \ + *op++ = *(binary_##ot *)ip++; \ + else \ + { \ + binary_##it tmp = *ip++; \ + CvtConvertFloat(&tmp, itype, op++, otype, 0); \ + } \ + ip++; \ + } \ + status = MDSplusSUCCESS; \ + } -#define COMPLEX_TO_COMPLEX(itype,it,pa,otype,ot,pb,numb) FLOAT_TO_FLOAT(itype,it,pa,otype,ot,pb,numb*2) +#define COMPLEX_TO_COMPLEX(itype, it, pa, otype, ot, pb, numb) FLOAT_TO_FLOAT(itype, it, pa, otype, ot, pb, numb * 2) -#define F_FS(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_F,float,pa,DTYPE_FS,float,pb,numb) -#define F_D(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_F,float,pa,DTYPE_D,double,pb,numb) -#define F_G(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_F,float,pa,DTYPE_G,double,pb,numb) -#define F_FT(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_F,float,pa,DTYPE_FT,double,pb,numb) -#define F_FC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_F,float,pb,numb) -#define F_FSC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_FS,float,pb,numb) -#define F_DC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_D,double,pb,numb) -#define F_GC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_G,double,pb,numb) -#define F_FTC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_FT,double,pb,numb) -#define FS_F(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_F,float,pb,numb) -#define FS_D(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_D,double,pb,numb) -#define FS_G(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_G,double,pb,numb) -#define FS_FT(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_FT,double,pb,numb) -#define FS_FC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_F,float,pb,numb) -#define FS_FSC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_FS,float,pb,numb) -#define FS_DC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_D,double,pb,numb) -#define FS_GC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_G,double,pb,numb) -#define FS_FTC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_FT,double,pb,numb) -#define D_F(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_D,double,pa,DTYPE_F,float,pb,numb) -#define D_FS(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_D,double,pa,DTYPE_FS,float,pb,numb) -#define D_G(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_D,double,pa,DTYPE_G,double,pb,numb) -#define D_FT(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_D,double,pa,DTYPE_FT,double,pb,numb) -#define D_FC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_F,float,pb,numb) -#define D_FSC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_FS,float,pb,numb) -#define D_DC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_D,double,pb,numb) -#define D_GC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_G,double,pb,numb) -#define D_FTC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_FT,double,pb,numb) -#define G_F(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_G,double,pa,DTYPE_F,float,pb,numb) -#define G_FS(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_G,double,pa,DTYPE_FS,float,pb,numb) -#define G_D(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_G,double,pa,DTYPE_D,double,pb,numb) -#define G_FT(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_G,double,pa,DTYPE_FT,double,pb,numb) -#define G_FC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_F,float,pb,numb) -#define G_FSC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_FS,float,pb,numb) -#define G_DC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_D,double,pb,numb) -#define G_GC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_G,double,pb,numb) -#define G_FTC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_FT,double,pb,numb) -#define FT_F(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_F,float,pb,numb) -#define FT_FS(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_FS,float,pb,numb) -#define FT_D(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_D,double,pb,numb) -#define FT_G(lena,pa,lenb,pb,numb) FLOAT_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_G,double,pb,numb) -#define FT_FC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_F,float,pb,numb) -#define FT_FSC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_FS,float,pb,numb) -#define FT_DC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_D,double,pb,numb) -#define FT_GC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_G,double,pb,numb) -#define FT_FTC(lena,pa,lenb,pb,numb) FLOAT_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_FT,double,pb,numb) -#define FC_F(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_F,float,pa,DTYPE_F,float,pb,numb) -#define FC_FS(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_F,float,pa,DTYPE_FS,float,pb,numb) -#define FC_D(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_F,float,pa,DTYPE_D,double,pb,numb) -#define FC_G(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_F,float,pa,DTYPE_G,double,pb,numb) -#define FC_FT(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_F,float,pa,DTYPE_FT,double,pb,numb) -#define FC_FSC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_FS,float,pb,numb) -#define FC_DC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_D,double,pb,numb) -#define FC_GC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_G,double,pb,numb) -#define FC_FTC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_F,float,pa,DTYPE_FT,double,pb,numb) -#define FSC_F(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_F,float,pb,numb) -#define FSC_FS(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_FS,float,pb,numb) -#define FSC_D(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_D,double,pb,numb) -#define FSC_G(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_G,float,pb,numb) -#define FSC_FT(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FS,float,pa,DTYPE_FT,double,pb,numb) -#define FSC_FC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_F,float,pb,numb) -#define FSC_DC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_D,double,pb,numb) -#define FSC_GC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_G,double,pb,numb) -#define FSC_FTC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FS,float,pa,DTYPE_FT,double,pb,numb) -#define DC_F(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_D,double,pa,DTYPE_F,float,pb,numb) -#define DC_FS(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_D,double,pa,DTYPE_FS,float,pb,numb) -#define DC_D(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_D,double,pa,DTYPE_D,double,pb,numb) -#define DC_G(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_D,double,pa,DTYPE_G,double,pb,numb) -#define DC_FT(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_D,double,pa,DTYPE_FT,double,pb,numb) -#define DC_FC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_F,float,pb,numb) -#define DC_FSC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_FS,float,pb,numb) -#define DC_GC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_G,double,pb,numb) -#define DC_FTC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_D,double,pa,DTYPE_FT,double,pb,numb) -#define GC_F(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_G,double,pa,DTYPE_F,float,pb,numb) -#define GC_FS(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_G,double,pa,DTYPE_FS,float,pb,numb) -#define GC_D(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_G,double,pa,DTYPE_D,double,pb,numb) -#define GC_G(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_G,double,pa,DTYPE_G,double,pb,numb) -#define GC_FT(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_G,double,pa,DTYPE_FT,double,pb,numb) -#define GC_FC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_F,float,pb,numb) -#define GC_FSC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_FS,float,pb,numb) -#define GC_DC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_D,double,pb,numb) -#define GC_FTC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_G,double,pa,DTYPE_FT,double,pb,numb) -#define FTC_F(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_F,float,pb,numb) -#define FTC_FS(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_FS,float,pb,numb) -#define FTC_D(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_D,double,pb,numb) -#define FTC_G(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_G,double,pb,numb) -#define FTC_FT(lena,pa,lenb,pb,numb) COMPLEX_TO_FLOAT(DTYPE_FT,double,pa,DTYPE_FT,double,pb,numb) -#define FTC_FC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_F,float,pb,numb) -#define FTC_FSC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_FS,float,pb,numb) -#define FTC_DC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_D,double,pb,numb) -#define FTC_GC(lena,pa,lenb,pb,numb) COMPLEX_TO_COMPLEX(DTYPE_FT,double,pa,DTYPE_G,double,pb,numb) +#define F_FS(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_F, float, pa, DTYPE_FS, float, pb, numb) +#define F_D(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_F, float, pa, DTYPE_D, double, pb, numb) +#define F_G(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_F, float, pa, DTYPE_G, double, pb, numb) +#define F_FT(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_F, float, pa, DTYPE_FT, double, pb, numb) +#define F_FC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_F, float, pb, numb) +#define F_FSC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_FS, float, pb, numb) +#define F_DC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_D, double, pb, numb) +#define F_GC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_G, double, pb, numb) +#define F_FTC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_FT, double, pb, numb) +#define FS_F(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_F, float, pb, numb) +#define FS_D(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_D, double, pb, numb) +#define FS_G(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_G, double, pb, numb) +#define FS_FT(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_FT, double, pb, numb) +#define FS_FC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_F, float, pb, numb) +#define FS_FSC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_FS, float, pb, numb) +#define FS_DC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_D, double, pb, numb) +#define FS_GC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_G, double, pb, numb) +#define FS_FTC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_FT, double, pb, numb) +#define D_F(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_D, double, pa, DTYPE_F, float, pb, numb) +#define D_FS(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_D, double, pa, DTYPE_FS, float, pb, numb) +#define D_G(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_D, double, pa, DTYPE_G, double, pb, numb) +#define D_FT(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_D, double, pa, DTYPE_FT, double, pb, numb) +#define D_FC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_F, float, pb, numb) +#define D_FSC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_FS, float, pb, numb) +#define D_DC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_D, double, pb, numb) +#define D_GC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_G, double, pb, numb) +#define D_FTC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_FT, double, pb, numb) +#define G_F(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_G, double, pa, DTYPE_F, float, pb, numb) +#define G_FS(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_G, double, pa, DTYPE_FS, float, pb, numb) +#define G_D(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_G, double, pa, DTYPE_D, double, pb, numb) +#define G_FT(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_G, double, pa, DTYPE_FT, double, pb, numb) +#define G_FC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_F, float, pb, numb) +#define G_FSC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_FS, float, pb, numb) +#define G_DC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_D, double, pb, numb) +#define G_GC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_G, double, pb, numb) +#define G_FTC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_FT, double, pb, numb) +#define FT_F(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_F, float, pb, numb) +#define FT_FS(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_FS, float, pb, numb) +#define FT_D(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_D, double, pb, numb) +#define FT_G(lena, pa, lenb, pb, numb) FLOAT_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_G, double, pb, numb) +#define FT_FC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_F, float, pb, numb) +#define FT_FSC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_FS, float, pb, numb) +#define FT_DC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_D, double, pb, numb) +#define FT_GC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_G, double, pb, numb) +#define FT_FTC(lena, pa, lenb, pb, numb) FLOAT_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_FT, double, pb, numb) +#define FC_F(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_F, float, pa, DTYPE_F, float, pb, numb) +#define FC_FS(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_F, float, pa, DTYPE_FS, float, pb, numb) +#define FC_D(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_F, float, pa, DTYPE_D, double, pb, numb) +#define FC_G(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_F, float, pa, DTYPE_G, double, pb, numb) +#define FC_FT(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_F, float, pa, DTYPE_FT, double, pb, numb) +#define FC_FSC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_FS, float, pb, numb) +#define FC_DC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_D, double, pb, numb) +#define FC_GC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_G, double, pb, numb) +#define FC_FTC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_F, float, pa, DTYPE_FT, double, pb, numb) +#define FSC_F(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_F, float, pb, numb) +#define FSC_FS(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_FS, float, pb, numb) +#define FSC_D(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_D, double, pb, numb) +#define FSC_G(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_G, float, pb, numb) +#define FSC_FT(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FS, float, pa, DTYPE_FT, double, pb, numb) +#define FSC_FC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_F, float, pb, numb) +#define FSC_DC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_D, double, pb, numb) +#define FSC_GC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_G, double, pb, numb) +#define FSC_FTC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FS, float, pa, DTYPE_FT, double, pb, numb) +#define DC_F(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_D, double, pa, DTYPE_F, float, pb, numb) +#define DC_FS(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_D, double, pa, DTYPE_FS, float, pb, numb) +#define DC_D(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_D, double, pa, DTYPE_D, double, pb, numb) +#define DC_G(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_D, double, pa, DTYPE_G, double, pb, numb) +#define DC_FT(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_D, double, pa, DTYPE_FT, double, pb, numb) +#define DC_FC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_F, float, pb, numb) +#define DC_FSC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_FS, float, pb, numb) +#define DC_GC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_G, double, pb, numb) +#define DC_FTC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_D, double, pa, DTYPE_FT, double, pb, numb) +#define GC_F(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_G, double, pa, DTYPE_F, float, pb, numb) +#define GC_FS(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_G, double, pa, DTYPE_FS, float, pb, numb) +#define GC_D(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_G, double, pa, DTYPE_D, double, pb, numb) +#define GC_G(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_G, double, pa, DTYPE_G, double, pb, numb) +#define GC_FT(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_G, double, pa, DTYPE_FT, double, pb, numb) +#define GC_FC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_F, float, pb, numb) +#define GC_FSC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_FS, float, pb, numb) +#define GC_DC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_D, double, pb, numb) +#define GC_FTC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_G, double, pa, DTYPE_FT, double, pb, numb) +#define FTC_F(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_F, float, pb, numb) +#define FTC_FS(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_FS, float, pb, numb) +#define FTC_D(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_D, double, pb, numb) +#define FTC_G(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_G, double, pb, numb) +#define FTC_FT(lena, pa, lenb, pb, numb) COMPLEX_TO_FLOAT(DTYPE_FT, double, pa, DTYPE_FT, double, pb, numb) +#define FTC_FC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_F, float, pb, numb) +#define FTC_FSC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_FS, float, pb, numb) +#define FTC_DC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_D, double, pb, numb) +#define FTC_GC(lena, pa, lenb, pb, numb) COMPLEX_TO_COMPLEX(DTYPE_FT, double, pa, DTYPE_G, double, pb, numb) /************* Text *****************/ -#define MEMCPYFILL32(op,text,len,n) do{\ - const int nfill = len - n;\ - if (nfill <= 0)\ - memcpy(op, text - nfill, len);\ - else\ - {\ - memcpy(op + nfill, text, n);\ - memset(op, ' ', nfill);\ - }\ -}while(0) +#define MEMCPYFILL32(op, text, len, n) \ + do \ + { \ + const int nfill = len - n; \ + if (nfill <= 0) \ + memcpy(op, text - nfill, len); \ + else \ + { \ + memcpy(op + nfill, text, n); \ + memset(op, ' ', nfill); \ + } \ + } while (0) -#define TO_TEXT(pa,it,pb,numb,cvt) do{\ - it *ip = (it*)pa; char *op = (char *)pb; int i=numb;\ - while(i-- > 0)\ - {\ - char text[64]; int n=cvt;\ - MEMCPYFILL32(op,text,lenb,n);\ - op += lenb;\ - }\ - status = MDSplusSUCCESS;\ -}while(0) +#define TO_TEXT(pa, it, pb, numb, cvt) \ + do \ + { \ + it *ip = (it *)pa; \ + char *op = (char *)pb; \ + int i = numb; \ + while (i-- > 0) \ + { \ + char text[64]; \ + int n = cvt; \ + MEMCPYFILL32(op, text, lenb, n); \ + op += lenb; \ + } \ + status = MDSplusSUCCESS; \ + } while (0) /******************* CODE *********************/ void DoubleToWideInt(); @@ -654,13 +982,17 @@ static void FLOAT_TO_TEXT(int itype, char *pa, char *pb, int numb, int lenb, cha float *ip = (float *)pa; char *op = (char *)pb; int i = numb; - while (i-- > 0) { + while (i-- > 0) + { char text[64]; int n; - if (IsRoprand(itype, ip)) { + if (IsRoprand(itype, ip)) + { n = sprintf(text, "$ROPRAND"); ip++; - } else { + } + else + { char *pe; int width; int prec; @@ -669,21 +1001,22 @@ static void FLOAT_TO_TEXT(int itype, char *pa, char *pb, int numb, int lenb, cha width = lenb < 13 ? lenb : 13; prec = width - 7; if (prec < 0) - prec = 0; + prec = 0; n = sprintf(text, "%#*.*G", width, prec, tmp); pe = strchr(text, 'E'); if (pe) - *pe = sym; - else { - if (text[0] == ' ') - mem_shift(text, 1, n - 1); - if (text[0] == ' ') - mem_shift(text, 1, n - 2); - text[n - 2] = sym; - text[n - 1] = '0'; + *pe = sym; + else + { + if (text[0] == ' ') + mem_shift(text, 1, n - 1); + if (text[0] == ' ') + mem_shift(text, 1, n - 2); + text[n - 2] = sym; + text[n - 1] = '0'; } } - MEMCPYFILL32(op,text,lenb,n); + MEMCPYFILL32(op, text, lenb, n); op += lenb; } } @@ -693,42 +1026,47 @@ static void DOUBLE_TO_TEXT(int itype, char *pa, char *pb, int numb, int lenb, ch double *ip = (double *)pa; char *op = (char *)pb; int i = numb; - while (i-- > 0) { + while (i-- > 0) + { char text[64]; int n; - if (IsRoprand(itype, ip)) { + if (IsRoprand(itype, ip)) + { n = sprintf(text, "$ROPRAND"); ip++; - } else { + } + else + { char *pe; int width; int prec; double tmp; if (itype != DTYPE_NATIVE_DOUBLE) - CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); else - tmp = *ip++; + tmp = *ip++; width = lenb < 23 ? lenb : 23; prec = width - 7; if (prec < 0) - prec = 0; + prec = 0; n = sprintf(text, "%#*.*G", width, prec, tmp); pe = strchr(text, 'E'); if (pe) - *pe = sym; - else { - int i; - if (text[0] == ' ') - for (i = 0; i < (n - 1); i++) - text[i] = text[i + 1]; /* memcpy(text,text+1,n-1); */ - if (text[0] == ' ') - for (i = 0; i < (n - 2); i++) - text[i] = text[i + 1]; /* memcpy(text,text+1,n-2); */ - text[n - 2] = sym; - text[n - 1] = '0'; + *pe = sym; + else + { + int i; + if (text[0] == ' ') + for (i = 0; i < (n - 1); i++) + text[i] = text[i + 1]; /* memcpy(text,text+1,n-1); */ + if (text[0] == ' ') + for (i = 0; i < (n - 2); i++) + text[i] = text[i + 1]; /* memcpy(text,text+1,n-2); */ + text[n - 2] = sym; + text[n - 1] = '0'; } } - MEMCPYFILL32(op,text,lenb,n); + MEMCPYFILL32(op, text, lenb, n); op += lenb; } } @@ -738,43 +1076,49 @@ static void FLOATC_TO_TEXT(int itype, char *pa, char *pb, int numb, int lenb, ch float *ip = (float *)pa; char *op = (char *)pb; int i = numb; - while (i-- > 0) { + while (i-- > 0) + { char text[64]; int n; int part; - for (part = 0; part < 2; part++) { + for (part = 0; part < 2; part++) + { int len = (lenb - 1) / 2; char *opl = op; if ((len * 2 + 1) != lenb) - *opl++ = ' '; + *opl++ = ' '; opl[len] = ','; - if (IsRoprand(itype, ip)) { - n = sprintf(text, "$ROPRAND"); - ip++; - } else { - int width; - int prec; - float tmp; - char *pe; - if (itype != DTYPE_NATIVE_FLOAT) - CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT, 0); - else - tmp = *ip++; - width = len < 13 ? len : 13; - prec = width - 7; - if (prec < 0) - prec = 0; - n = sprintf(text, "%#*.*G", width, prec, tmp); - pe = strchr(text, 'E'); - if (pe) - *pe = sym; - else { - strcpy(text, text + 2); - text[n - 2] = sym; - text[n - 1] = '0'; - } + if (IsRoprand(itype, ip)) + { + n = sprintf(text, "$ROPRAND"); + ip++; } - MEMCPYFILL32(opl,text,len,n); + else + { + int width; + int prec; + float tmp; + char *pe; + if (itype != DTYPE_NATIVE_FLOAT) + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_FLOAT, 0); + else + tmp = *ip++; + width = len < 13 ? len : 13; + prec = width - 7; + if (prec < 0) + prec = 0; + n = sprintf(text, "%#*.*G", width, prec, tmp); + pe = strchr(text, 'E'); + if (pe) + *pe = sym; + else + { + strcpy(text, text + 2); + text[n - 2] = sym; + text[n - 1] = '0'; + } + } + MEMCPYFILL32(opl, text, len, n); } op += lenb; } @@ -785,135 +1129,192 @@ static void DOUBLEC_TO_TEXT(int itype, char *pa, char *pb, int numb, int lenb, c double *ip = (double *)pa; char *op = (char *)pb; int i = numb; - while (i-- > 0) { + while (i-- > 0) + { char text[64]; int n; int part; - for (part = 0; part < 2; part++) { + for (part = 0; part < 2; part++) + { int len = (lenb - 1) / 2; char *opl = op; if ((len * 2 + 1) != lenb) - *opl++ = ' '; + *opl++ = ' '; opl[len] = ','; - if (IsRoprand(itype, ip)) { - n = sprintf(text, "$ROPRAND"); - ip++; - } else { - int width; - int prec; - double tmp; - char *pe; - if (itype != DTYPE_NATIVE_DOUBLE) - CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); - else - tmp = *ip++; - width = len < 23 ? len : 23; - prec = width - 7; - if (prec < 0) - prec = 0; - n = sprintf(text, "%#*.*G", width, prec, tmp); - pe = strchr(text, 'E'); - if (pe) - *pe = sym; - else { - strcpy(text, text + 2); - text[n - 2] = sym; - text[n - 1] = '0'; - } + if (IsRoprand(itype, ip)) + { + n = sprintf(text, "$ROPRAND"); + ip++; + } + else + { + int width; + int prec; + double tmp; + char *pe; + if (itype != DTYPE_NATIVE_DOUBLE) + CvtConvertFloat(ip++, itype, &tmp, DTYPE_NATIVE_DOUBLE, 0); + else + tmp = *ip++; + width = len < 23 ? len : 23; + prec = width - 7; + if (prec < 0) + prec = 0; + n = sprintf(text, "%#*.*G", width, prec, tmp); + pe = strchr(text, 'E'); + if (pe) + *pe = sym; + else + { + strcpy(text, text + 2); + text[n - 2] = sym; + text[n - 1] = '0'; + } } - MEMCPYFILL32(opl,text,len,n); + MEMCPYFILL32(opl, text, len, n); } op += lenb; } } -#define BU_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, uint8_t,pb,numb,sprintf(text,"%"PRIu8, *ip++)) -#define WU_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, uint16_t,pb,numb,sprintf(text,"%"PRIu16,*ip++)) -#define LU_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, uint32_t,pb,numb,sprintf(text,"%"PRIu32,*ip++)) -#define QU_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, uint64_t,pb,numb,sprintf(text,"%"PRIu64,*ip++)) -#define B_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, int8_t,pb,numb,sprintf(text,"%"PRId8, *ip++)) -#define W_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, int16_t,pb,numb,sprintf(text,"%"PRId16,*ip++)) -#define L_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, int32_t,pb,numb,sprintf(text,"%"PRId32,*ip++)) -#define Q_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, int64_t,pb,numb,sprintf(text,"%"PRId64,*ip++)) -#define OU_T(lena,pa,lenb,pb,numb) TO_TEXT(pa,uint128_t,pb,numb,sprintf(text,"%s",uint128_deco(ip++,int128_buf))) -#define O_T(lena,pa,lenb,pb,numb) TO_TEXT(pa, int128_t,pb,numb,sprintf(text,"%s", int128_deco(ip++,int128_buf))) +#define BU_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, uint8_t, pb, numb, sprintf(text, "%" PRIu8, *ip++)) +#define WU_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, uint16_t, pb, numb, sprintf(text, "%" PRIu16, *ip++)) +#define LU_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, uint32_t, pb, numb, sprintf(text, "%" PRIu32, *ip++)) +#define QU_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, uint64_t, pb, numb, sprintf(text, "%" PRIu64, *ip++)) +#define B_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, int8_t, pb, numb, sprintf(text, "%" PRId8, *ip++)) +#define W_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, int16_t, pb, numb, sprintf(text, "%" PRId16, *ip++)) +#define L_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, int32_t, pb, numb, sprintf(text, "%" PRId32, *ip++)) +#define Q_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, int64_t, pb, numb, sprintf(text, "%" PRId64, *ip++)) +#define OU_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, uint128_t, pb, numb, sprintf(text, "%s", uint128_deco(ip++, int128_buf))) +#define O_T(lena, pa, lenb, pb, numb) TO_TEXT(pa, int128_t, pb, numb, sprintf(text, "%s", int128_deco(ip++, int128_buf))) #if DTYPE_F == DTYPE_NATIVE_FLOAT -#define F_T(lena,pa,lenb,pb,numb) FLOAT_TO_TEXT(DTYPE_F,pa,pb,numb,lenb,'E'); status=1 -#define FS_T(lena,pa,lenb,pb,numb) FLOAT_TO_TEXT(DTYPE_FS,pa,pb,numb,lenb,'S'); status=1 -#define D_T(lena,pa,lenb,pb,numb) DOUBLE_TO_TEXT(DTYPE_D,pa,pb,numb,lenb,'D'); status=1 -#define FT_T(lena,pa,lenb,pb,numb) DOUBLE_TO_TEXT(DTYPE_FT,pa,pb,numb,lenb,'T'); status=1 -#define FC_T(lena,pa,lenb,pb,numb) FLOATC_TO_TEXT(DTYPE_F,pa,pb,numb,lenb,'E'); status=1 -#define FSC_T(lena,pa,lenb,pb,numb) FLOATC_TO_TEXT(DTYPE_FS,pa,pb,numb,lenb,'S'); status=1 -#define DC_T(lena,pa,lenb,pb,numb) DOUBLEC_TO_TEXT(DTYPE_D,pa,pb,numb,lenb,'D'); status=1 -#define FTC_T(lena,pa,lenb,pb,numb) DOUBLEC_TO_TEXT(DTYPE_FT,pa,pb,numb,lenb,'T'); status=1 +#define F_T(lena, pa, lenb, pb, numb) \ + FLOAT_TO_TEXT(DTYPE_F, pa, pb, numb, lenb, 'E'); \ + status = 1 +#define FS_T(lena, pa, lenb, pb, numb) \ + FLOAT_TO_TEXT(DTYPE_FS, pa, pb, numb, lenb, 'S'); \ + status = 1 +#define D_T(lena, pa, lenb, pb, numb) \ + DOUBLE_TO_TEXT(DTYPE_D, pa, pb, numb, lenb, 'D'); \ + status = 1 +#define FT_T(lena, pa, lenb, pb, numb) \ + DOUBLE_TO_TEXT(DTYPE_FT, pa, pb, numb, lenb, 'T'); \ + status = 1 +#define FC_T(lena, pa, lenb, pb, numb) \ + FLOATC_TO_TEXT(DTYPE_F, pa, pb, numb, lenb, 'E'); \ + status = 1 +#define FSC_T(lena, pa, lenb, pb, numb) \ + FLOATC_TO_TEXT(DTYPE_FS, pa, pb, numb, lenb, 'S'); \ + status = 1 +#define DC_T(lena, pa, lenb, pb, numb) \ + DOUBLEC_TO_TEXT(DTYPE_D, pa, pb, numb, lenb, 'D'); \ + status = 1 +#define FTC_T(lena, pa, lenb, pb, numb) \ + DOUBLEC_TO_TEXT(DTYPE_FT, pa, pb, numb, lenb, 'T'); \ + status = 1 #else -#define F_T(lena,pa,lenb,pb,numb) FLOAT_TO_TEXT(DTYPE_F,pa,pb,numb,lenb,'F'); status=1 -#define FS_T(lena,pa,lenb,pb,numb) FLOAT_TO_TEXT(DTYPE_FS,pa,pb,numb,lenb,'E'); status=1 -#define D_T(lena,pa,lenb,pb,numb) DOUBLE_TO_TEXT(DTYPE_D,pa,pb,numb,lenb,'V'); status=1 -#define FT_T(lena,pa,lenb,pb,numb) DOUBLE_TO_TEXT(DTYPE_FT,pa,pb,numb,lenb,'D'); status=1 -#define FC_T(lena,pa,lenb,pb,numb) FLOATC_TO_TEXT(DTYPE_F,pa,pb,numb,lenb,'F'); status=1 -#define FSC_T(lena,pa,lenb,pb,numb) FLOATC_TO_TEXT(DTYPE_FS,pa,pb,numb,lenb,'E'); status=1 -#define DC_T(lena,pa,lenb,pb,numb) DOUBLEC_TO_TEXT(DTYPE_D,pa,pb,numb,lenb,'V'); status=1 -#define FTC_T(lena,pa,lenb,pb,numb) DOUBLEC_TO_TEXT(DTYPE_FT,pa,pb,numb,lenb,'D'); status=1 +#define F_T(lena, pa, lenb, pb, numb) \ + FLOAT_TO_TEXT(DTYPE_F, pa, pb, numb, lenb, 'F'); \ + status = 1 +#define FS_T(lena, pa, lenb, pb, numb) \ + FLOAT_TO_TEXT(DTYPE_FS, pa, pb, numb, lenb, 'E'); \ + status = 1 +#define D_T(lena, pa, lenb, pb, numb) \ + DOUBLE_TO_TEXT(DTYPE_D, pa, pb, numb, lenb, 'V'); \ + status = 1 +#define FT_T(lena, pa, lenb, pb, numb) \ + DOUBLE_TO_TEXT(DTYPE_FT, pa, pb, numb, lenb, 'D'); \ + status = 1 +#define FC_T(lena, pa, lenb, pb, numb) \ + FLOATC_TO_TEXT(DTYPE_F, pa, pb, numb, lenb, 'F'); \ + status = 1 +#define FSC_T(lena, pa, lenb, pb, numb) \ + FLOATC_TO_TEXT(DTYPE_FS, pa, pb, numb, lenb, 'E'); \ + status = 1 +#define DC_T(lena, pa, lenb, pb, numb) \ + DOUBLEC_TO_TEXT(DTYPE_D, pa, pb, numb, lenb, 'V'); \ + status = 1 +#define FTC_T(lena, pa, lenb, pb, numb) \ + DOUBLEC_TO_TEXT(DTYPE_FT, pa, pb, numb, lenb, 'D'); \ + status = 1 #endif -#define G_T(lena,pa,lenb,pb,numb) DOUBLE_TO_TEXT(DTYPE_G,pa,pb,numb,lenb,'G'); status=1 -#define GC_T(lena,pa,lenb,pb,numb) DOUBLEC_TO_TEXT(DTYPE_G,pa,pb,numb,lenb,'G'); status=1 +#define G_T(lena, pa, lenb, pb, numb) \ + DOUBLE_TO_TEXT(DTYPE_G, pa, pb, numb, lenb, 'G'); \ + status = 1 +#define GC_T(lena, pa, lenb, pb, numb) \ + DOUBLEC_TO_TEXT(DTYPE_G, pa, pb, numb, lenb, 'G'); \ + status = 1 /******* Text to Text ***************/ -#define TEXT_TO_TEXT(pa,lena,pb,lenb,numb) \ - {char *ip = (char*)pa; char *op = (char *)pb; int i=numb; while(i-- > 0) {\ - int nfill; nfill = lenb - lena; \ - if (ip) \ - memcpy(op, ip, (nfill <= 0) ? lenb : lena); \ - if (nfill > 0) memset(op+lena,32,nfill); op += lenb; ip += lena;} status = MDSplusSUCCESS;} +#define TEXT_TO_TEXT(pa, lena, pb, lenb, numb) \ + { \ + char *ip = (char *)pa; \ + char *op = (char *)pb; \ + int i = numb; \ + while (i-- > 0) \ + { \ + int nfill; \ + nfill = lenb - lena; \ + if (ip) \ + memcpy(op, ip, (nfill <= 0) ? lenb : lena); \ + if (nfill > 0) \ + memset(op + lena, 32, nfill); \ + op += lenb; \ + ip += lena; \ + } \ + status = MDSplusSUCCESS; \ + } -#define T_T(lena,pa,lenb,pb,numb) TEXT_TO_TEXT(pa,lena,pb,lenb,numb) +#define T_T(lena, pa, lenb, pb, numb) TEXT_TO_TEXT(pa, lena, pb, lenb, numb) /******* No Text to numeric conversions handled here *********/ -#define T_BU(lena,pa,lenb,pb,numb) -#define T_WU(lena,pa,lenb,pb,numb) -#define T_LU(lena,pa,lenb,pb,numb) -#define T_QU(lena,pa,lenb,pb,numb) -#define T_OU(lena,pa,lenb,pb,numb) -#define T_B(lena,pa,lenb,pb,numb) -#define T_W(lena,pa,lenb,pb,numb) -#define T_L(lena,pa,lenb,pb,numb) -#define T_Q(lena,pa,lenb,pb,numb) -#define T_O(lena,pa,lenb,pb,numb) -#define T_F(lena,pa,lenb,pb,numb) -#define T_D(lena,pa,lenb,pb,numb) -#define T_G(lena,pa,lenb,pb,numb) -#define T_FC(lena,pa,lenb,pb,numb) -#define T_DC(lena,pa,lenb,pb,numb) -#define T_GC(lena,pa,lenb,pb,numb) -#define T_FS(lena,pa,lenb,pb,numb) -#define T_FT(lena,pa,lenb,pb,numb) -#define T_FSC(lena,pa,lenb,pb,numb) -#define T_FTC(lena,pa,lenb,pb,numb) +#define T_BU(lena, pa, lenb, pb, numb) +#define T_WU(lena, pa, lenb, pb, numb) +#define T_LU(lena, pa, lenb, pb, numb) +#define T_QU(lena, pa, lenb, pb, numb) +#define T_OU(lena, pa, lenb, pb, numb) +#define T_B(lena, pa, lenb, pb, numb) +#define T_W(lena, pa, lenb, pb, numb) +#define T_L(lena, pa, lenb, pb, numb) +#define T_Q(lena, pa, lenb, pb, numb) +#define T_O(lena, pa, lenb, pb, numb) +#define T_F(lena, pa, lenb, pb, numb) +#define T_D(lena, pa, lenb, pb, numb) +#define T_G(lena, pa, lenb, pb, numb) +#define T_FC(lena, pa, lenb, pb, numb) +#define T_DC(lena, pa, lenb, pb, numb) +#define T_GC(lena, pa, lenb, pb, numb) +#define T_FS(lena, pa, lenb, pb, numb) +#define T_FT(lena, pa, lenb, pb, numb) +#define T_FSC(lena, pa, lenb, pb, numb) +#define T_FTC(lena, pa, lenb, pb, numb) -#define defcase(a,b) case MAXTYPE*DTYPE_##a+DTYPE_##b : a##_##b(lena,pa,lenb,pb,numb); break; -#define defset(a) \ - defcase(a,BU) \ - defcase(a,WU) \ - defcase(a,LU) \ - defcase(a,QU) \ - defcase(a,OU) \ - defcase(a,B) \ - defcase(a,W) \ - defcase(a,L) \ - defcase(a,Q) \ - defcase(a,O) \ - defcase(a,F) \ - defcase(a,D) \ - defcase(a,G) \ - defcase(a,FC) \ - defcase(a,DC) \ - defcase(a,GC) \ - defcase(a,T) \ - defcase(a,FS) \ - defcase(a,FT) \ - defcase(a,FSC) \ - defcase(a,FTC) +#define defcase(a, b) \ + case MAXTYPE *DTYPE_##a + DTYPE_##b: \ + a##_##b(lena, pa, lenb, pb, numb); \ + break; +#define defset(a) \ + defcase(a, BU) \ + defcase(a, WU) \ + defcase(a, LU) \ + defcase(a, QU) \ + defcase(a, OU) \ + defcase(a, B) \ + defcase(a, W) \ + defcase(a, L) \ + defcase(a, Q) \ + defcase(a, O) \ + defcase(a, F) \ + defcase(a, D) \ + defcase(a, G) \ + defcase(a, FC) \ + defcase(a, DC) \ + defcase(a, GC) \ + defcase(a, T) \ + defcase(a, FS) \ + defcase(a, FT) \ + defcase(a, FSC) \ + defcase(a, FTC) EXPORT int TdiConvert(struct descriptor_a *pdin, struct descriptor_a *pdout) { @@ -929,47 +1330,54 @@ EXPORT int TdiConvert(struct descriptor_a *pdin, struct descriptor_a *pdout) register int numb = classb ? (int)pdout->arsize / max(lenb, 1) : 1L; int n; int status = TdiINVDTYDSC; - /** no output **/ + /** no output **/ if (numb <= 0 || lenb <= 0) return 1; - /** set zero or blanks **/ - if (numa <= 0 || dtypea == DTYPE_Z) { + /** set zero or blanks **/ + if (numa <= 0 || dtypea == DTYPE_Z) + { memset((void *)pb, (int)((dtypeb == DTYPE_T) ? ' ' : 0), numb * lenb); return 1; } - /** incomplete fill (was an error in olden times) **/ - if (classa && (n = numb - numa) > 0) { + /** incomplete fill (was an error in olden times) **/ + if (classa && (n = numb - numa) > 0) + { memset((void *)(pb + numa * lenb), (int)((dtypeb == DTYPE_T) ? ' ' : 0), n * lenb); numb = numa; } - /** identical types just copies, even unknowns **/ - /** vector=>either is int copy, scalar=>either is many copies **/ - if (dtypea == dtypeb && lena == lenb) { - same:if (classa) + /** identical types just copies, even unknowns **/ + /** vector=>either is int copy, scalar=>either is many copies **/ + if (dtypea == dtypeb && lena == lenb) + { + same: + if (classa) memmove((void *)pb, (void *)pa, numb * lenb); else - switch (lenb) { + switch (lenb) + { case 1: - for (; --numb >= 0; pb += 1) - *pb = *pa; + for (; --numb >= 0; pb += 1) + *pb = *pa; case 2: - for (; --numb >= 0; pb += 2) - *(short *)pb = *(short *)pa; + for (; --numb >= 0; pb += 2) + *(short *)pb = *(short *)pa; case 4: - for (; --numb >= 0; pb += 4) - *(int *)pb = *(int *)pa; + for (; --numb >= 0; pb += 4) + *(int *)pb = *(int *)pa; default: - for (; --numb >= 0; pb += lenb) - memmove((void *)pb, (void *)pa, lenb); + for (; --numb >= 0; pb += lenb) + memmove((void *)pb, (void *)pa, lenb); } status = MDSplusSUCCESS; - } else if (dtypeb >= MAXTYPE) + } + else if (dtypeb >= MAXTYPE) status = TdiINVDTYDSC; - /** scalar => vector convert once as scalar and copy as needed **/ - else if (!classa && classb) { + /** scalar => vector convert once as scalar and copy as needed **/ + else if (!classa && classb) + { struct descriptor scalarb; scalarb = *(struct descriptor *)pdout; scalarb.class = CLASS_S; @@ -978,34 +1386,35 @@ EXPORT int TdiConvert(struct descriptor_a *pdin, struct descriptor_a *pdout) pb += lenb; --numb; goto same; - } else { - /** big branch **/ + } + else + { + /** big branch **/ INT128_BUF(int128_buf); n = MAXTYPE * dtypea + dtypeb; - switch (n) { + switch (n) + { defset(BU) - defset(WU) - defset(LU) - defset(QU) - defset(OU) - defset(B) - defset(W) - defset(L) - defset(Q) - defset(O) - defset(F) - defset(D) - defset(G) - defset(FC) - defset(DC) - defset(GC) - defset(T) - defset(FS) - defset(FT) - defset(FSC) - defset(FTC) - default: - return TdiINVDTYDSC; + defset(WU) + defset(LU) + defset(QU) + defset(OU) + defset(B) + defset(W) + defset(L) + defset(Q) + defset(O) + defset(F) + defset(D) + defset(G) + defset(FC) + defset(DC) + defset(GC) + defset(T) + defset(FS) + defset(FT) + defset(FSC) + defset(FTC) default : return TdiINVDTYDSC; } } return status; @@ -1040,8 +1449,7 @@ void DoubleToWideInt(double *in, int size, unsigned int *out) int i; double factor; double tmp; - for (i = size - 1, tmp = negative ? -1 - *in : *in, factor = - pow(2.0, 32. * (size - 1)); i >= 0; tmp -= out[i--] * factor, factor /= TWO_32) + for (i = size - 1, tmp = negative ? -1 - *in : *in, factor = pow(2.0, 32. * (size - 1)); i >= 0; tmp -= out[i--] * factor, factor /= TWO_32) out[i] = (unsigned int)((tmp / factor) + .49999999999); if (negative) for (i = 0; i < size; i++) @@ -1056,5 +1464,4 @@ void DoubleToWideInt(double *in, int size, unsigned int *out) out[i] = tmp[size - i - 1]; } #endif - } diff --git a/tdishr/TdiCull.c b/tdishr/TdiCull.c index a1da4e43b4..cf1d862aec 100644 --- a/tdishr/TdiCull.c +++ b/tdishr/TdiCull.c @@ -66,19 +66,23 @@ static const DESCRIPTOR_RANGE(EMPTY_RANGE, 0, 0, (struct descriptor *)&value); /********************************************** Redo culled array or scalar. */ -int TdiRecull(struct descriptor_xd *out_ptr) { +int TdiRecull(struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_a *px = (struct descriptor_a *)out_ptr->pointer; /**************************** Culled scalar is null vector. ****************************/ - if (px->class != CLASS_A) { + if (px->class != CLASS_A) + { DESCRIPTOR_A(arr0, 0, 0, 0, 0); arr0.length = px->length; arr0.dtype = px->dtype; status = MdsCopyDxXd((struct descriptor *)&arr0, out_ptr); - } else { + } + else + { px->dimct = 1; px->aflags.coeff = 0; px->aflags.bounds = 0; @@ -89,18 +93,19 @@ int TdiRecull(struct descriptor_xd *out_ptr) { /*--------------------------------------------- Remove out-of-bounds integer-limited elements. */ -int TdiIcull(int left, int right, struct descriptor_a *px) { +int TdiIcull(int left, int right, struct descriptor_a *px) +{ INIT_STATUS; int *pi = (int *)px->pointer, *po = pi; int n; N_ELEMENTS(px, n); - if - STATUS_OK - for (; --n >= 0; ++pi) - if (*pi >= left && *pi <= right) - *po++ = *pi; - if (pi != po) { + if (STATUS_OK) + for (; --n >= 0; ++pi) + if (*pi >= left && *pi <= right) + *po++ = *pi; + if (pi != po) + { /******************************** Scalars must be nulled elsewhere. ********************************/ @@ -114,20 +119,21 @@ int TdiIcull(int left, int right, struct descriptor_a *px) { /*--------------------------------------------- Replace out-of-bounds integer-limited elements. */ -int TdiIextend(int left, int right, struct descriptor_a *px) { +int TdiIextend(int left, int right, struct descriptor_a *px) +{ INIT_STATUS; int *pi = (int *)px->pointer; int n; N_ELEMENTS(px, n); - if - STATUS_OK - for (; --n >= 0; ++pi) { - if (*pi < left) - *pi = left; - else if (*pi > right) - *pi = right; - } + if (STATUS_OK) + for (; --n >= 0; ++pi) + { + if (*pi < left) + *pi = left; + else if (*pi > right) + *pi = right; + } return status; } @@ -135,25 +141,28 @@ int TdiIextend(int left, int right, struct descriptor_a *px) { Remove elements not satisfying mask. */ static int rcull(struct descriptor *pnew __attribute__((unused)), - struct descriptor_a *pmask, struct descriptor_a *px) { + struct descriptor_a *pmask, struct descriptor_a *px) +{ INIT_STATUS; char *pm = pmask->pointer, *pi = px->pointer, *po = pi; int n, len = px->length; N_ELEMENTS(px, n); - if - STATUS_OK - for (; --n >= 0; pi += len) - if (*pm++) { - if (po < pi) - memcpy(po, pi, len); - po += len; - } - if (pi != po) { + if (STATUS_OK) + for (; --n >= 0; pi += len) + if (*pm++) + { + if (po < pi) + memcpy(po, pi, len); + po += len; + } + if (pi != po) + { status = SsINTERNAL; /******************************** Scalars must be nulled elsewhere. ********************************/ - if (px->class == CLASS_A) { + if (px->class == CLASS_A) + { px->arsize = (unsigned int)((char *)po - px->pointer); px->dimct = 1; px->aflags.coeff = 0; @@ -167,16 +176,16 @@ static int rcull(struct descriptor *pnew __attribute__((unused)), Replace elements not in mask. */ static int rextend(struct descriptor *pnew, struct descriptor_a *pmask, - struct descriptor_a *px) { + struct descriptor_a *px) +{ INIT_STATUS; char *pn = pnew->pointer, *pm = pmask->pointer, *pi = px->pointer; int n, len = px->length; N_ELEMENTS(px, n); - if - STATUS_OK - for (; --n >= 0; pi += len) - if (!*pm++) - memcpy(pi, pn, len); + if (STATUS_OK) + for (; --n >= 0; pi += len) + if (!*pm++) + memcpy(pi, pn, len); return status; } @@ -186,7 +195,8 @@ static int rextend(struct descriptor *pnew, struct descriptor_a *pmask, static int work(int rroutine(struct descriptor *, struct descriptor_a *, struct descriptor_a *), opcode_t opcode, int narg, struct descriptor *list[3], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; struct descriptor_xd in = EMPTY_XD, tmp = EMPTY_XD, units = EMPTY_XD; @@ -203,11 +213,11 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, DTYPE_DIMENSION, 0}; static const unsigned char omitd[] = {DTYPE_WITH_UNITS, DTYPE_DIMENSION, 0}; status = tdi_get_data(omits, list[0], &in); - if (STATUS_OK && in.pointer->dtype == DTYPE_WITH_UNITS) { + if (STATUS_OK && in.pointer->dtype == DTYPE_WITH_UNITS) + { status = TdiUnits(in.pointer, &units MDS_END_ARG); - if - STATUS_OK - status = tdi_get_data(&omits[1], &in, &in); + if (STATUS_OK) + status = tdi_get_data(&omits[1], &in, &in); } if (STATUS_OK && narg > 1 && list[1]) status = TdiGetLong(list[1], &dim); @@ -217,7 +227,8 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, /***************************** Convert signal to a dimension. *****************************/ - if (STATUS_OK && in.pointer->dtype == DTYPE_SIGNAL) { + if (STATUS_OK && in.pointer->dtype == DTYPE_SIGNAL) + { tmp = in; in = EMPTY_XD; psig = (struct descriptor_signal *)tmp.pointer; @@ -225,68 +236,66 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, status = TdiBAD_INDEX; else status = tdi_get_data(omitd, psig->dimensions[dim], &in); - if (STATUS_OK && in.pointer->dtype == DTYPE_WITH_UNITS) { + if (STATUS_OK && in.pointer->dtype == DTYPE_WITH_UNITS) + { status = TdiUnits(in.pointer, &units MDS_END_ARG); - if - STATUS_OK - status = tdi_get_data(&omitd[1], &in, &in); - } else + if (STATUS_OK) + status = tdi_get_data(&omitd[1], &in, &in); + } + else MdsFree1Dx(&units, NULL); dim = 0; } /************************* Get dimension information. *************************/ - if - STATUS_OK - switch (in.pointer->dtype) { - case DTYPE_MISSING: - if (narg > 2 && list[2]) - status = MdsCopyDxXd(list[2], out_ptr); - else - MdsFree1Dx(out_ptr, NULL); - break; - case DTYPE_T: - if (!(narg > 2 && list[2])) { - if - STATUS_OK - status = TdiData(&in, out_ptr MDS_END_ARG); + if (STATUS_OK) + switch (in.pointer->dtype) + { + case DTYPE_MISSING: + if (narg > 2 && list[2]) + status = MdsCopyDxXd(list[2], out_ptr); + else + MdsFree1Dx(out_ptr, NULL); break; - } - MdsFree1Dx(out_ptr, NULL); - status = TdiGetArgs(opcode, 1, &list[2], sig, uni, dat, cats); - if (STATUS_OK && units.pointer == 0) - status = MdsCopyDxXd((struct descriptor *)&uni[0], &units); - if - STATUS_OK - status = TdiIsIn(dat[0].pointer, &in, &tmp MDS_END_ARG); - if - STATUS_OK - status = rroutine(dat[0].pointer, (struct descriptor_a *)tmp.pointer, - (struct descriptor_a *)dat[0].pointer); - if (status == SsINTERNAL) - status = TdiRecull(&dat[0]); - MdsFree1Dx(&sig[0], NULL); - MdsFree1Dx(&uni[0], NULL); - if - STATUS_OK - *out_ptr = dat[0]; - break; - default: - if (!(narg > 2 && list[2])) { - if - STATUS_OK - status = TdiData(&in, out_ptr MDS_END_ARG); + case DTYPE_T: + if (!(narg > 2 && list[2])) + { + if (STATUS_OK) + status = TdiData(&in, out_ptr MDS_END_ARG); + break; + } + MdsFree1Dx(out_ptr, NULL); + status = TdiGetArgs(opcode, 1, &list[2], sig, uni, dat, cats); + if (STATUS_OK && units.pointer == 0) + status = MdsCopyDxXd((struct descriptor *)&uni[0], &units); + if (STATUS_OK) + status = TdiIsIn(dat[0].pointer, &in, &tmp MDS_END_ARG); + if (STATUS_OK) + status = rroutine(dat[0].pointer, (struct descriptor_a *)tmp.pointer, + (struct descriptor_a *)dat[0].pointer); + if (status == SsINTERNAL) + status = TdiRecull(&dat[0]); + MdsFree1Dx(&sig[0], NULL); + MdsFree1Dx(&uni[0], NULL); + if (STATUS_OK) + *out_ptr = dat[0]; break; - } - /******************************** + default: + if (!(narg > 2 && list[2])) + { + if (STATUS_OK) + status = TdiData(&in, out_ptr MDS_END_ARG); + break; + } + /******************************** Special conversion to get limits. Could use some tests to speed up. ********************************/ - MdsFree1Dx(out_ptr, NULL); - status = TdiItoX(in.pointer, TdiItoXSpecial, &tmp MDS_END_ARG); - if - STATUS_OK { + MdsFree1Dx(out_ptr, NULL); + status = TdiItoX(in.pointer, TdiItoXSpecial, &tmp MDS_END_ARG); + if (STATUS_OK) + { pwu = (struct descriptor_with_units *)tmp.pointer; if (pwu->dtype == DTYPE_WITH_UNITS) dx0 = *pwu->data; @@ -305,14 +314,16 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, TDI_RANGE_PTRS[0] = &dx0; TDI_RANGE_PTRS[1] = &dx1; TDI_RANGE_PTRS[2] = 0; - if (in.pointer->dtype == DTYPE_DIMENSION) { + if (in.pointer->dtype == DTYPE_DIMENSION) + { TDI_RANGE_PTRS[2] = in.pointer; /************************************************************ Dimensions conversion with missing increment uses all values. ************************************************************/ if (new[2]->dtype == DTYPE_RANGE && (new[2]->ndesc == 2 || - (new[2]->ndesc == 3 && new[2]->deltaval == 0))) { + (new[2]->ndesc == 3 && new[2]->deltaval == 0))) + { fake_range = EMPTY_RANGE; fake_range.begin = new[2]->begin; fake_range.ending = new[2]->ending; @@ -322,45 +333,40 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, status = TdiGetArgs(opcode, 3, new, sig, uni, dat, cats); memcpy(TDI_RANGE_PTRS, keep, sizeof(keep)); } - if - STATUS_OK - status = Tdi2Range(3, uni, dat, cats, 0); - if (STATUS_OK && units.pointer == 0) - status = MdsCopyDxXd((struct descriptor *)&uni[0], &units); - if - STATUS_OK - status = TdiCvtArgs(3, dat, cats); - if - STATUS_OK - status = TdiGe(dat[2].pointer, dat[0].pointer, &tmp MDS_END_ARG); - if - STATUS_OK - s1 = (status = rroutine(dat[0].pointer, (struct descriptor_a *)tmp.pointer, - (struct descriptor_a *)dat[2].pointer)) == - SsINTERNAL; - if (STATUS_OK || s1 == SsINTERNAL) - status = TdiLe(dat[2].pointer, dat[1].pointer, &tmp MDS_END_ARG); - if - STATUS_OK - s1 |= (status = rroutine(dat[1].pointer, (struct descriptor_a *)tmp.pointer, - (struct descriptor_a *)dat[2].pointer)) == - SsINTERNAL; - if (STATUS_OK && s1) - status = TdiRecull(&dat[2]); - MdsFree1Dx(&sig[0], NULL); - MdsFree1Dx(&sig[1], NULL); - MdsFree1Dx(&sig[2], NULL); - MdsFree1Dx(&uni[0], NULL); - MdsFree1Dx(&uni[1], NULL); - MdsFree1Dx(&uni[2], NULL); - MdsFree1Dx(&dat[0], NULL); - MdsFree1Dx(&dat[1], NULL); - if - STATUS_OK - *out_ptr = dat[2]; - else MdsFree1Dx(&dat[2], NULL); - break; - } + if (STATUS_OK) + status = Tdi2Range(3, uni, dat, cats, 0); + if (STATUS_OK && units.pointer == 0) + status = MdsCopyDxXd((struct descriptor *)&uni[0], &units); + if (STATUS_OK) + status = TdiCvtArgs(3, dat, cats); + if (STATUS_OK) + status = TdiGe(dat[2].pointer, dat[0].pointer, &tmp MDS_END_ARG); + if (STATUS_OK) + s1 = (status = rroutine(dat[0].pointer, (struct descriptor_a *)tmp.pointer, + (struct descriptor_a *)dat[2].pointer)) == + SsINTERNAL; + if (STATUS_OK || s1 == SsINTERNAL) + status = TdiLe(dat[2].pointer, dat[1].pointer, &tmp MDS_END_ARG); + if (STATUS_OK) + s1 |= (status = rroutine(dat[1].pointer, (struct descriptor_a *)tmp.pointer, + (struct descriptor_a *)dat[2].pointer)) == + SsINTERNAL; + if (STATUS_OK && s1) + status = TdiRecull(&dat[2]); + MdsFree1Dx(&sig[0], NULL); + MdsFree1Dx(&sig[1], NULL); + MdsFree1Dx(&sig[2], NULL); + MdsFree1Dx(&uni[0], NULL); + MdsFree1Dx(&uni[1], NULL); + MdsFree1Dx(&uni[2], NULL); + MdsFree1Dx(&dat[0], NULL); + MdsFree1Dx(&dat[1], NULL); + if (STATUS_OK) + *out_ptr = dat[2]; + else + MdsFree1Dx(&dat[2], NULL); + break; + } MdsFree1Dx(&tmp, NULL); MdsFree1Dx(&in, NULL); if (STATUS_OK && units.pointer) @@ -371,12 +377,14 @@ static int work(int rroutine(struct descriptor *, struct descriptor_a *, /***********************************************/ int Tdi1Cull(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ return work(rcull, opcode, narg, list, out_ptr); } /***********************************************/ int Tdi1Extend(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ return work(rextend, opcode, narg, list, out_ptr); } diff --git a/tdishr/TdiCvtArgs.c b/tdishr/TdiCvtArgs.c index 32de201e31..3aac9a5b36 100644 --- a/tdishr/TdiCvtArgs.c +++ b/tdishr/TdiCvtArgs.c @@ -43,7 +43,8 @@ extern int TdiGetShape(); extern void UseNativeFloat(); int TdiCvtArgs(int narg, struct descriptor_xd dat[1], - struct TdiCatStruct cats[1]) { + struct TdiCatStruct cats[1]) +{ INIT_STATUS; int j, cmode = -1; unsigned char jd; @@ -56,13 +57,20 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], Get length from table. Keep old text length. *************************/ - for (j = 0, cptr = cats; STATUS_OK && j <= narg; ++j, ++cptr) { - if (cptr->out_cat != cptr->in_cat) { - if (cptr->out_cat != TdiREF_CAT[DTYPE_T].cat) { - if (TdiREF_CAT[cptr->out_dtype].cat != cptr->out_cat) { - if (cats[j].out_cat & 0x400) { - if (cats[j].out_cat & TdiCAT_COMPLEX) { - switch (cats[j].out_dtype) { + for (j = 0, cptr = cats; STATUS_OK && j <= narg; ++j, ++cptr) + { + if (cptr->out_cat != cptr->in_cat) + { + if (cptr->out_cat != TdiREF_CAT[DTYPE_T].cat) + { + if (TdiREF_CAT[cptr->out_dtype].cat != cptr->out_cat) + { + if (cats[j].out_cat & 0x400) + { + if (cats[j].out_cat & TdiCAT_COMPLEX) + { + switch (cats[j].out_dtype) + { case DTYPE_F: cats[j].out_dtype = DTYPE_FC; break; @@ -81,8 +89,11 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], default: UseNativeFloat(cptr); } - } else { - switch (cats[j].out_dtype) { + } + else + { + switch (cats[j].out_dtype) + { case DTYPE_FC: cats[j].out_dtype = DTYPE_F; break; @@ -102,9 +113,12 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], UseNativeFloat(cptr); } } - } else { + } + else + { for (jd = 0; jd < TdiCAT_MAX && TdiREF_CAT[jd].cat != cptr->out_cat; - ++jd) { + ++jd) + { ; } if (jd >= TdiCAT_MAX) @@ -114,19 +128,23 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], } } cptr->digits = TdiREF_CAT[cptr->out_dtype].length; - } else + } + else cptr->out_dtype = DTYPE_T; - } else if (cptr->out_cat != TdiREF_CAT[DTYPE_T].cat) + } + else if (cptr->out_cat != TdiREF_CAT[DTYPE_T].cat) cptr->digits = TDIREF_CAT(cptr->out_dtype).length; } /******************** Do input conversions. ********************/ - for (j = 0, cptr = cats; STATUS_OK && j < narg; ++j, ++cptr) { + for (j = 0, cptr = cats; STATUS_OK && j < narg; ++j, ++cptr) + { struct descriptor_a *aptr = (struct descriptor_a *)dat[j].pointer; - if (cptr->in_dtype == cptr->out_dtype && cptr->digits == aptr->length) { + if (cptr->in_dtype == cptr->out_dtype && cptr->digits == aptr->length) + { ; } @@ -136,7 +154,8 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], else if ((cptr->in_cat ^ cptr->out_cat) == SIGNEDNESS) aptr->dtype = cptr->out_dtype; - else { + else + { /***************************************** Convert overlay for same length. For example: L into F. @@ -144,12 +163,16 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], NEED to revise if other array classes. ASSUMES array-descriptor sized readable. *****************************************/ - if (aptr->length == cptr->digits) { - if (aptr->class == CLASS_A) { + if (aptr->length == cptr->digits) + { + if (aptr->class == CLASS_A) + { struct descriptor_a arr = *aptr; aptr->dtype = cptr->out_dtype; status = TdiConvert(&arr, aptr MDS_END_ARG); - } else { + } + else + { struct descriptor d = *(struct descriptor *)aptr; aptr->dtype = cptr->out_dtype; status = TdiConvert(&d, aptr MDS_END_ARG); @@ -159,13 +182,13 @@ int TdiCvtArgs(int narg, struct descriptor_xd dat[1], /************************** Make new space and convert. **************************/ - else { + else + { struct descriptor_xd xd = EMPTY_XD; status = TdiGetShape(1, &dat[j], cptr->digits, cptr->out_dtype, &cmode, &xd); - if - STATUS_OK - status = TdiConvert(aptr, xd.pointer MDS_END_ARG); + if (STATUS_OK) + status = TdiConvert(aptr, xd.pointer MDS_END_ARG); MdsFree1Dx(&dat[j], NULL); dat[j] = xd; } diff --git a/tdishr/TdiCvtDxDx.c b/tdishr/TdiCvtDxDx.c index 9df0816bb8..84b6474298 100644 --- a/tdishr/TdiCvtDxDx.c +++ b/tdishr/TdiCvtDxDx.c @@ -39,7 +39,8 @@ extern int TdiConvert(); extern int TdiGetShape(); int TdiCvtDxDx(struct descriptor *in_ptr, unsigned char *dtype_ptr, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; /********************************* @@ -58,14 +59,14 @@ int TdiCvtDxDx(struct descriptor *in_ptr, unsigned char *dtype_ptr, /****************************** Make space and convert into it. ******************************/ - else { + else + { int mode = -1; struct descriptor_xd xs = {0, DTYPE_DSC, CLASS_XS, 0, 0}; xs.pointer = in_ptr; status = TdiGetShape(1, &xs, 0, *dtype_ptr, &mode, out_ptr); - if - STATUS_OK - status = TdiConvert(in_ptr, out_ptr->pointer); + if (STATUS_OK) + status = TdiConvert(in_ptr, out_ptr->pointer); } return status; } diff --git a/tdishr/TdiDecompile.c b/tdishr/TdiDecompile.c index fabd8a5d54..12bd8aeba0 100644 --- a/tdishr/TdiDecompile.c +++ b/tdishr/TdiDecompile.c @@ -63,7 +63,8 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, EXPORT int Tdi1Decompile(opcode_t opcode __attribute__((unused)), int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; struct descriptor_d answer = {0, DTYPE_T, CLASS_D, 0}; @@ -72,22 +73,20 @@ EXPORT int Tdi1Decompile(opcode_t opcode __attribute__((unused)), int narg, status = TdiGetLong(list[1], &TDI_DECOMPILE_MAX); else TDI_DECOMPILE_MAX = 0xffff; - if - STATUS_OK - status = Tdi0Decompile(list[0], 9999, &answer); - while (status == StrSTRTOOLON && TDI_DECOMPILE_MAX > 10) { + if (STATUS_OK) + status = Tdi0Decompile(list[0], 9999, &answer); + while (status == StrSTRTOOLON && TDI_DECOMPILE_MAX > 10) + { TDI_DECOMPILE_MAX /= 10; if (TDI_DECOMPILE_MAX > 100) TDI_DECOMPILE_MAX = 100; StrFree1Dx(&answer); status = Tdi0Decompile(list[0], 9999, &answer); } - if - STATUS_OK - TdiDecompileDeindent(&answer); - if - STATUS_OK - status = MdsCopyDxXd((struct descriptor *)&answer, out_ptr); + if (STATUS_OK) + TdiDecompileDeindent(&answer); + if (STATUS_OK) + status = MdsCopyDxXd((struct descriptor *)&answer, out_ptr); StrFree1Dx(&answer); return status; } @@ -121,7 +120,8 @@ static const DESCRIPTOR(RIGHT_PAREN, ")"); static const DESCRIPTOR(SET_RANGE, "Set_Range("); static const DESCRIPTOR(STAR, "*"); -int TdiSingle(int val, struct descriptor_d *out_ptr) { +int TdiSingle(int val, struct descriptor_d *out_ptr) +{ struct descriptor val_dsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; val_dsc.pointer = (char *)&val; return Tdi0Decompile(&val_dsc, P_ARG, out_ptr); @@ -131,7 +131,8 @@ int TdiSingle(int val, struct descriptor_d *out_ptr) { Handle arrays and arrays of pointers to descriptors. */ static int tdi_vector(struct descriptor *in_ptr, int level, char **item_ptr_ptr, - struct descriptor_d *out_ptr) { + struct descriptor_d *out_ptr) +{ array_bounds_desc *a_ptr = (array_bounds_desc *)in_ptr; int n = a_ptr->aflags.coeff ? a_ptr->m[level] @@ -142,22 +143,26 @@ static int tdi_vector(struct descriptor *in_ptr, int level, char **item_ptr_ptr, else status = MDSplusSUCCESS; if (level > 0) - for (j = n; --j >= 0 && STATUS_OK;) { + for (j = n; --j >= 0 && STATUS_OK;) + { status = tdi_vector(in_ptr, level - 1, item_ptr_ptr, out_ptr); if (j > 0 && STATUS_OK) status = StrAppend(out_ptr, (struct descriptor *)&COMMA_SPACE); } - else { + else + { struct descriptor one = *in_ptr; int length = a_ptr->length; char *pitem = *item_ptr_ptr; one.class = CLASS_S; - for (j = 0; STATUS_OK && j < n; pitem += length) { + for (j = 0; STATUS_OK && j < n; pitem += length) + { if (a_ptr->class == CLASS_APD) status = Tdi0Decompile(a_ptr->pointer[j], P_ARG, out_ptr); else - switch (one.dtype) { + switch (one.dtype) + { case DTYPE_BU: status = TdiSingle(*(unsigned char *)pitem, out_ptr); break; @@ -175,7 +180,8 @@ static int tdi_vector(struct descriptor *in_ptr, int level, char **item_ptr_ptr, status = Tdi0Decompile(&one, P_ARG, out_ptr); break; } - if (++j < n && STATUS_OK) { + if (++j < n && STATUS_OK) + { if (j & 1 || a_ptr->dtype != DTYPE_DICTIONARY) status = StrAppend(out_ptr, (struct descriptor *)&COMMA); else @@ -192,7 +198,8 @@ static int tdi_vector(struct descriptor *in_ptr, int level, char **item_ptr_ptr, /****************** Squeeze out spaces. ******************/ -static int noblanks(struct descriptor *cdsc_ptr) { +static int noblanks(struct descriptor *cdsc_ptr) +{ int n = cdsc_ptr->length; char *pwas = cdsc_ptr->pointer, *pnow = pwas; @@ -209,19 +216,20 @@ static int noblanks(struct descriptor *cdsc_ptr) { Neater floating point numbers. *****************************/ static int closeup(char repl, struct descriptor *pfloat, - struct descriptor *pdc) { + struct descriptor *pdc) +{ int status, sum, j, shift; char *pwas = pdc->pointer; char *plim = pwas + pdc->length; char *pdec, *plast, *pexp, *ppass; status = TdiConvert(pfloat, pdc); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; *plim = '\0'; - while (pwas < plim) { + while (pwas < plim) + { ppass = pwas; /**************************** Skip spaces and leading zero. @@ -236,7 +244,8 @@ static int closeup(char repl, struct descriptor *pfloat, *pwas++ = ' '; pdec = 0; plast = pwas; - while (pwas) { + while (pwas) + { if (*pwas == '0' || *pwas == ' ') ; else if (*pwas > '0' && *pwas <= '9') @@ -247,7 +256,8 @@ static int closeup(char repl, struct descriptor *pfloat, break; pwas++; } - if (pwas >= plim) { + if (pwas >= plim) + { char *pwas_save = pwas; if (pdec && (pdec < (pwas - 1))) for (pwas--; *pwas == '0'; pwas--) @@ -260,16 +270,21 @@ static int closeup(char repl, struct descriptor *pfloat, /********************************* Zero and $ROPRAND should be quick. *********************************/ - if (plast == pdec) { + if (plast == pdec) + { if (*pdec == '$') for (; pwas < plim && *pwas != ',';) pwas++; - else { + else + { pwas = ppass; *pwas++ = '0'; - if (repl == 'E') { + if (repl == 'E') + { *pwas++ = '.'; - } else { + } + else + { *pwas++ = repl; *pwas++ = '0'; } @@ -284,7 +299,8 @@ static int closeup(char repl, struct descriptor *pfloat, We hit the exponent. *******************/ pexp = pwas; - switch (*pwas) { + switch (*pwas) + { case 'E': case 'F': case 'D': @@ -303,7 +319,8 @@ static int closeup(char repl, struct descriptor *pfloat, *pwas++ = repl; break; case '-': - if (plast == pwas - 1) { + if (plast == pwas - 1) + { for (pwas = ppass; pwas < pexp; pwas++) *pwas = *(pwas + 1); pdec--; @@ -328,13 +345,18 @@ static int closeup(char repl, struct descriptor *pfloat, sum = 0; while (pwas < plim && *pwas != ',') sum = sum * 10 + (*pwas++ - '0'); - if (*(pexp + 1) == '-') { + if (*(pexp + 1) == '-') + { shift = (30002 - sum) % 3 + 1; sum = sum + shift; - } else if (sum <= 4) { + } + else if (sum <= 4) + { shift = sum; sum = 0; - } else { + } + else + { shift = (sum - 1) % 3 + 1; sum = sum - shift; } @@ -348,7 +370,8 @@ static int closeup(char repl, struct descriptor *pfloat, *pdec = *(pdec + 1); if (plast > pdec) *pdec = '.'; - else { + else + { plast = pdec; if (pdec < pexp) *pdec = (char)((sum == 0 && repl == 'E') ? '.' : ' '); @@ -356,10 +379,13 @@ static int closeup(char repl, struct descriptor *pfloat, for (; ++plast < pexp;) *plast = ' '; - if (sum == 0 && repl == 'E') { + if (sum == 0 && repl == 'E') + { while (pexp < plim && *pexp != ',') *pexp++ = ' '; - } else { + } + else + { pdec = pwas; if (sum == 0) *--pdec = '0'; @@ -375,7 +401,8 @@ static int closeup(char repl, struct descriptor *pfloat, if (pwas != plim) status = TdiNOT_NUMBER; noblanks(pdc); - if ((pdc->length == 1) && (pdc->pointer[0] == '.')) { + if ((pdc->length == 1) && (pdc->pointer[0] == '.')) + { pdc->length++; pdc->pointer[0] = '0'; pdc->pointer[1] = '.'; @@ -384,7 +411,8 @@ static int closeup(char repl, struct descriptor *pfloat, } int Tdi0Decompile(struct descriptor *in_ptr, int prec, - struct descriptor_d *out_ptr) { + struct descriptor_d *out_ptr) +{ TDITHREADSTATIC_INIT; char c0[85], *cptr, *bptr; struct descriptor cdsc = {11, DTYPE_T, CLASS_S, 0}; @@ -399,33 +427,35 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, return StrAppend(out_ptr, (struct descriptor *)&STAR); dtype_t dtype = (dtype_t)in_ptr->dtype; - switch (in_ptr->class) { + switch (in_ptr->class) + { default: status = StrAppend(out_ptr, (struct descriptor *)&CLASS); - if - STATUS_OK - status = TdiSingle(in_ptr->class, out_ptr); + if (STATUS_OK) + status = TdiSingle(in_ptr->class, out_ptr); break; case CLASS_XD: case CLASS_XS: case CLASS_S: case CLASS_D: - switch (dtype) { + switch (dtype) + { default: status = StrAppend(out_ptr, (struct descriptor *)&DTYPE); - if - STATUS_OK - status = TdiSingle(dtype, out_ptr); + if (STATUS_OK) + status = TdiSingle(dtype, out_ptr); break; /**************************************** Printing characters are added as a block. ****************************************/ - case DTYPE_T: { + case DTYPE_T: + { DESCRIPTOR(QUOTE, "\""); cdsc.length = 2; t2.pointer = cptr = in_ptr->pointer; - for (n1 = n2 = 0, j = in_ptr->length; --j >= 0; cptr++) { + for (n1 = n2 = 0, j = in_ptr->length; --j >= 0; cptr++) + { if (*cptr == '\'') n1++; else if (*cptr == '\"') @@ -435,11 +465,13 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, QUOTE.pointer = &n1c; status = StrAppend(out_ptr, (struct descriptor *)"E); cptr = in_ptr->pointer; - for (j = in_ptr->length; --j >= 0; cptr++) { + for (j = in_ptr->length; --j >= 0; cptr++) + { if (*cptr == n1c) c0[1] = n1c; else - switch (*cptr) { + switch (*cptr) + { /****************** Special characters. ******************/ @@ -484,28 +516,24 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, status = StrAppend(out_ptr, (struct descriptor *)&t2); t2.pointer = cptr + 1; c0[0] = '\\'; - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&cdsc); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&cdsc); cdsc.length = 2; } if (STATUS_OK && (t2.length = (unsigned short)(cptr - t2.pointer)) > 0) status = StrAppend(out_ptr, (struct descriptor *)&t2); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)"E); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)"E); break; } case DTYPE_L: /*cdsc.length = 11; */ status = TdiConvert(in_ptr, &cdsc); - if - STATUS_OK - status = noblanks(&cdsc); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&cdsc); + if (STATUS_OK) + status = noblanks(&cdsc); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&cdsc); break; case DTYPE_B: case DTYPE_W: @@ -518,18 +546,17 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, case DTYPE_OU: cdsc.length = (unsigned short)(TdiREF_CAT[dtype].digits); status = TdiConvert(in_ptr, &cdsc); - if - STATUS_OK - status = noblanks(&cdsc); - if - STATUS_OK { - struct descriptor sdsc = {0, DTYPE_T, CLASS_S, 0}; - sdsc.length = (unsigned short)strlen(TdiREF_CAT[dtype].name); - sdsc.pointer = TdiREF_CAT[dtype].name; - status = - StrConcat((struct descriptor *)out_ptr, - (struct descriptor *)out_ptr, &cdsc, &sdsc MDS_END_ARG); - } + if (STATUS_OK) + status = noblanks(&cdsc); + if (STATUS_OK) + { + struct descriptor sdsc = {0, DTYPE_T, CLASS_S, 0}; + sdsc.length = (unsigned short)strlen(TdiREF_CAT[dtype].name); + sdsc.pointer = TdiREF_CAT[dtype].name; + status = + StrConcat((struct descriptor *)out_ptr, + (struct descriptor *)out_ptr, &cdsc, &sdsc MDS_END_ARG); + } break; case DTYPE_D: case DTYPE_F: @@ -539,9 +566,8 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, case DTYPE_FT: cdsc.length = (unsigned short)(TdiREF_CAT[dtype].digits); status = closeup((char)TdiREF_CAT[dtype].fname[0], in_ptr, &cdsc); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&cdsc); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&cdsc); break; case DTYPE_DC: dtype = DTYPE_D; @@ -558,7 +584,8 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, case DTYPE_FSC: dtype = DTYPE_FS; goto complex; - case DTYPE_FTC: { + case DTYPE_FTC: + { dtype = DTYPE_FT; goto complex; complex:; @@ -595,15 +622,19 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, /********* MDS types. *********/ - case DTYPE_NID: { + case DTYPE_NID: + { char *path = TreeGetMinimumPath(0, *(int *)in_ptr->pointer); - if (path != NULL) { + if (path != NULL) + { DESCRIPTOR_FROM_CSTRING(path_d, path); status = StrAppend(out_ptr, (struct descriptor *)&path_d); TreeFree(path); - } else + } + else status = TreeFAILURE; - } break; + } + break; case DTYPE_PATH: /***************************************************** Convert forward refs to nid to reduce to minimum path. @@ -614,17 +645,16 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, char *path = MdsDescrToCstring((struct descriptor *)in_ptr); status = TreeFindNode(path, &nid); MdsFree(path); - if - STATUS_OK - path = TreeGetMinimumPath(0, nid); + if (STATUS_OK) + path = TreeGetMinimumPath(0, nid); if (path == NULL) status = TreeFAILURE; - if - STATUS_OK { - DESCRIPTOR_FROM_CSTRING(path_d, path); - status = StrAppend(out_ptr, (struct descriptor *)&path_d); - TreeFree(path); - } + if (STATUS_OK) + { + DESCRIPTOR_FROM_CSTRING(path_d, path); + status = StrAppend(out_ptr, (struct descriptor *)&path_d); + TreeFree(path); + } else status = StrAppend(out_ptr, (struct descriptor *)in_ptr); } @@ -636,7 +666,8 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, StrConcat((struct descriptor *)out_ptr, (struct descriptor *)out_ptr, &BUILD_EVENT, &t2, &CLOSE_EVENT MDS_END_ARG); break; - case DTYPE_POINTER: { + case DTYPE_POINTER: + { char outstr[11 + 2 * in_ptr->length]; struct descriptor out = {0, DTYPE_T, CLASS_S, outstr}; if (in_ptr->length == 4) @@ -661,20 +692,22 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, /********************************** Compressed data should be expanded. **********************************/ - case CLASS_CA: { + case CLASS_CA: + { struct descriptor_xd tmp = EMPTY_XD; status = Tdi1Evaluate(OPC_EVALUATE, 1, &in_ptr, &tmp); - if - STATUS_OK - status = Tdi0Decompile(tmp.pointer, prec, out_ptr); + if (STATUS_OK) + status = Tdi0Decompile(tmp.pointer, prec, out_ptr); MdsFree1Dx(&tmp, NULL); - } break; + } + break; /****************** Arrays in brackets. ******************/ case CLASS_APD: - case CLASS_A: { + case CLASS_A: + { array_bounds_desc *a_ptr = (array_bounds_desc *)in_ptr; int length = a_ptr->length; int coeff = a_ptr->aflags.coeff; @@ -685,7 +718,8 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, /************************************** Special data types made easier to read. **************************************/ - switch (dtype) { + switch (dtype) + { case DTYPE_BU: bptr = "Byte_Unsigned("; break; @@ -714,14 +748,17 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, bptr = 0; break; } - if (bptr) { + if (bptr) + { struct descriptor text = {0, DTYPE_T, CLASS_S, 0}; text.length = (unsigned short)strlen(bptr); text.pointer = bptr; status = StrAppend(out_ptr, (struct descriptor *)&text); } - if (in_ptr->class == CLASS_APD) { - if (count > 0 && STATUS_OK) { + if (in_ptr->class == CLASS_APD) + { + if (count > 0 && STATUS_OK) + { if (in_ptr->dtype == DTYPE_DICTIONARY) status = StrAppend(out_ptr, (struct descriptor *)&COMMA_SPACE); else @@ -731,65 +768,68 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, /***************************************** Specify bounds of array. SET_RANGE(l:u,... *****************************************/ - else if (a_ptr->aflags.bounds) { + else if (a_ptr->aflags.bounds) + { status = StrAppend(out_ptr, (struct descriptor *)&SET_RANGE); - for (j = 0; j < dimct; ++j) { - if - STATUS_OK - status = TdiSingle(a_ptr->m[dimct + 2 * j], out_ptr); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&COLON); - if - STATUS_OK - status = TdiSingle(a_ptr->m[dimct + 2 * j + 1], out_ptr); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&COMMA); + for (j = 0; j < dimct; ++j) + { + if (STATUS_OK) + status = TdiSingle(a_ptr->m[dimct + 2 * j], out_ptr); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&COLON); + if (STATUS_OK) + status = TdiSingle(a_ptr->m[dimct + 2 * j + 1], out_ptr); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&COMMA); } } /****************************************** Specify shape of array. SET_RANGE(size, ... ******************************************/ - else if (more) { + else if (more) + { status = StrAppend(out_ptr, (struct descriptor *)&SET_RANGE); - for (j = 0; j < dimct; ++j) { - if - STATUS_OK - status = TdiSingle(coeff ? a_ptr->m[j] : count, out_ptr); - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&COMMA); + for (j = 0; j < dimct; ++j) + { + if (STATUS_OK) + status = TdiSingle(coeff ? a_ptr->m[j] : count, out_ptr); + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&COMMA); } } /********************************* Specify data of array. [value,...] *********************************/ - if (more) { - if - STATUS_OK { - if (in_ptr->class == CLASS_APD) { - status = Tdi0Decompile(((mdsdsc_t **)in_ptr->pointer)[0], P_ARG, - out_ptr); - if (in_ptr->dtype == DTYPE_DICTIONARY && STATUS_OK) { - status = StrAppend(out_ptr, (mdsdsc_t *)&COMMA); - if - STATUS_OK + if (more) + { + if (STATUS_OK) + { + if (in_ptr->class == CLASS_APD) + { + status = Tdi0Decompile(((mdsdsc_t **)in_ptr->pointer)[0], P_ARG, + out_ptr); + if (in_ptr->dtype == DTYPE_DICTIONARY && STATUS_OK) + { + status = StrAppend(out_ptr, (mdsdsc_t *)&COMMA); + if (STATUS_OK) status = Tdi0Decompile(((mdsdsc_t **)in_ptr->pointer)[1], P_ARG, out_ptr); - } - } else { - struct descriptor one = *in_ptr; - one.class = CLASS_S; - status = Tdi0Decompile(&one, P_ARG, out_ptr); } } - if - STATUS_OK - status = StrAppend(out_ptr, (struct descriptor *)&MORE); - } else { + else + { + struct descriptor one = *in_ptr; + one.class = CLASS_S; + status = Tdi0Decompile(&one, P_ARG, out_ptr); + } + } + if (STATUS_OK) + status = StrAppend(out_ptr, (struct descriptor *)&MORE); + } + else + { char *pitem = (char *)a_ptr->pointer; status = tdi_vector((struct descriptor *)a_ptr, dimct - 1, &pitem, out_ptr); @@ -799,10 +839,10 @@ int Tdi0Decompile(struct descriptor *in_ptr, int prec, status = StrAppend(out_ptr, (struct descriptor *)&RIGHT_PAREN); if (bptr && STATUS_OK) status = StrAppend(out_ptr, (struct descriptor *)&RIGHT_PAREN); - } break; + } + break; } /*switch class */ - if - STATUS_NOT_OK - tdi_trace(out_ptr); + if (STATUS_NOT_OK) + tdi_trace(out_ptr); return status; } diff --git a/tdishr/TdiDecompileDependency.c b/tdishr/TdiDecompileDependency.c index 9353ea02e5..cc8da8d0eb 100644 --- a/tdishr/TdiDecompileDependency.c +++ b/tdishr/TdiDecompileDependency.c @@ -61,30 +61,37 @@ static const DESCRIPTOR(LEFT_PAREN, "("); static const DESCRIPTOR(RIGHT_PAREN, ")"); static int DependencyGet(int prec, struct descriptor_r *pin, - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ INIT_STATUS; int now = 0; struct descriptor *pwhich = 0; - switch (pin->dtype) { + switch (pin->dtype) + { case DTYPE_EVENT: status = StrConcat((struct descriptor *)pout, (struct descriptor *)pout, &LEFT_ANGLE, pin, &RIGHT_ANGLE MDS_END_ARG); break; - case DTYPE_NID: { + case DTYPE_NID: + { char *path = TreeGetMinimumPath(0, *(int *)pin->pointer); - if (path != NULL) { + if (path != NULL) + { DESCRIPTOR_FROM_CSTRING(path_d, path); status = StrAppend(pout, &path_d); TreeFree(path); - } else + } + else status = TreeFAILURE; - } break; + } + break; case DTYPE_PATH: status = StrAppend(pout, (struct descriptor *)pin); break; case DTYPE_DEPENDENCY: - switch (*(treedep_t *)pin->pointer) { + switch (*(treedep_t *)pin->pointer) + { case TreeDEPENDENCY_AND: now = P_AND; pwhich = (struct descriptor *)&AND; @@ -99,22 +106,20 @@ static int DependencyGet(int prec, struct descriptor_r *pin, } if (STATUS_OK && now < prec) status = StrAppend(pout, (struct descriptor *)&LEFT_PAREN); - if - STATUS_OK - status = - DependencyGet(now - 1, (struct descriptor_r *)pin->dscptrs[0], pout); - if - STATUS_OK - status = StrAppend(pout, pwhich); - if - STATUS_OK - status = - DependencyGet(now + 1, (struct descriptor_r *)pin->dscptrs[1], pout); + if (STATUS_OK) + status = + DependencyGet(now - 1, (struct descriptor_r *)pin->dscptrs[0], pout); + if (STATUS_OK) + status = StrAppend(pout, pwhich); + if (STATUS_OK) + status = + DependencyGet(now + 1, (struct descriptor_r *)pin->dscptrs[1], pout); if (STATUS_OK && now < prec) status = StrAppend(pout, (struct descriptor *)&RIGHT_PAREN); break; case DTYPE_CONDITION: - switch (*((treecond_t *)pin->pointer)) { + switch (*((treecond_t *)pin->pointer)) + { case TreeNEGATE_CONDITION: pwhich = (struct descriptor *)&NEGATE; break; @@ -128,13 +133,11 @@ static int DependencyGet(int prec, struct descriptor_r *pin, status = TdiINV_OPC; break; } - if - STATUS_OK - status = StrAppend(pout, pwhich); - if - STATUS_OK - status = - DependencyGet(P_UNARY, (struct descriptor_r *)pin->dscptrs[0], pout); + if (STATUS_OK) + status = StrAppend(pout, pwhich); + if (STATUS_OK) + status = + DependencyGet(P_UNARY, (struct descriptor_r *)pin->dscptrs[0], pout); break; default: status = TdiINVDTYDSC; @@ -147,7 +150,8 @@ static int DependencyGet(int prec, struct descriptor_r *pin, int Tdi1DecompileDependency(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_d answer = {0, DTYPE_T, CLASS_D, 0}; struct descriptor *pdep = list[0]; @@ -156,9 +160,8 @@ int Tdi1DecompileDependency(opcode_t opcode __attribute__((unused)), pdep = (struct descriptor *)pdep->pointer; if (pdep) status = DependencyGet(P_WEAK, (struct descriptor_r *)pdep, &answer); - if - STATUS_OK - status = MdsCopyDxXd((struct descriptor *)&answer, out_ptr); + if (STATUS_OK) + status = MdsCopyDxXd((struct descriptor *)&answer, out_ptr); StrFree1Dx(&answer); return status; } diff --git a/tdishr/TdiDecompileR.c b/tdishr/TdiDecompileR.c index bf944146d6..0186c29373 100644 --- a/tdishr/TdiDecompileR.c +++ b/tdishr/TdiDecompileR.c @@ -47,7 +47,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int Tdi0Decompile(); extern int TdiSingle(); -static const struct op_rec { +static const struct op_rec +{ char *symbol; opcode_t opcode; char prec, lorr; @@ -124,14 +125,16 @@ static const char *bname[] = { "Opaque", /*217 */ }; -static int Append(const char *const pstr, struct descriptor_d *pd) { +static int Append(const char *const pstr, struct descriptor_d *pd) +{ struct descriptor dstr = {0, DTYPE_T, CLASS_S, 0}; dstr.length = (length_t)strlen(pstr); dstr.pointer = (char *)pstr; return StrAppend(pd, &dstr); } -void TdiDecompileDeindent(struct descriptor_d *pout) { +void TdiDecompileDeindent(struct descriptor_d *pout) +{ char *start = pout->pointer, *fin = start + pout->length - 1; if (!start) @@ -142,7 +145,8 @@ void TdiDecompileDeindent(struct descriptor_d *pout) { return; } -static int Indent(int step, struct descriptor_d *pout) { +static int Indent(int step, struct descriptor_d *pout) +{ TDITHREADSTATIC_INIT; #ifdef _WIN32 const char *newline = "\r\n\t\t\t\t\t\t\t"; @@ -161,91 +165,91 @@ static int Indent(int step, struct descriptor_d *pout) { return MDSplusSUCCESS; } -static int OneStatement(struct descriptor_r *pin, struct descriptor_d *pout) { +static int OneStatement(struct descriptor_r *pin, struct descriptor_d *pout) +{ INIT_STATUS; if (pin) status = Tdi0Decompile(pin, P_STMT, pout); - if - STATUS_OK - TdiDecompileDeindent(pout); - if - STATUS_OK - switch (pout->pointer[pout->length - 1]) { - default: - status = Append(";", pout); - break; - case ';': - case '}': - break; - } - if - STATUS_OK - status = Indent(0, pout); + if (STATUS_OK) + TdiDecompileDeindent(pout); + if (STATUS_OK) + switch (pout->pointer[pout->length - 1]) + { + default: + status = Append(";", pout); + break; + case ';': + case '}': + break; + } + if (STATUS_OK) + status = Indent(0, pout); return status; } static int MultiStatement(int nstmt, struct descriptor_r *pin[], - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ int status = MDSplusSUCCESS, j; - if (nstmt == 0) { + if (nstmt == 0) + { status = Append(";", pout); - if - STATUS_OK - status = Indent(0, pout); - } else + if (STATUS_OK) + status = Indent(0, pout); + } + else for (j = 0; j < nstmt && STATUS_OK; j++) status = OneStatement(pin[j], pout); return status; } static int CompoundStatement(int nstmt, struct descriptor_r *pin[], - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ INIT_STATUS; status = Append("{", pout); - if (nstmt > 0) { - if - STATUS_OK - status = Indent(1, pout); - if - STATUS_OK - status = MultiStatement(nstmt, pin, pout); - if - STATUS_OK - TdiDecompileDeindent(pout); - if - STATUS_OK - status = Indent(-1, pout); + if (nstmt > 0) + { + if (STATUS_OK) + status = Indent(1, pout); + if (STATUS_OK) + status = MultiStatement(nstmt, pin, pout); + if (STATUS_OK) + TdiDecompileDeindent(pout); + if (STATUS_OK) + status = Indent(-1, pout); } - if - STATUS_OK - status = Append("}", pout); + if (STATUS_OK) + status = Append("}", pout); return status; } static int Arguments(int first, char *left, char *right, - struct descriptor_r *pin, struct descriptor_d *pout) { + struct descriptor_r *pin, struct descriptor_d *pout) +{ int j, status, last = pin->ndesc - 1; if (left) status = Append(left, pout); else status = MDSplusSUCCESS; - for (j = first; STATUS_OK && j <= last; j++) { + for (j = first; STATUS_OK && j <= last; j++) + { status = Tdi0Decompile(pin->dscptrs[j], P_ARG, pout); if (STATUS_OK && j < last) status = Append(", ", pout); } - if - STATUS_OK - status = Append(right, pout); + if (STATUS_OK) + status = Append(right, pout); return status; } int Tdi0Decompile_R(struct descriptor_r *pin, int prec, - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ INIT_STATUS; struct descriptor_r *r_ptr; char *ptext; @@ -256,7 +260,8 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, unsigned int dtype; opcode_t opcode; - switch (pin->dtype) { + switch (pin->dtype) + { default: status = Append("%Unknown%", pout); break; @@ -280,13 +285,12 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case DTYPE_OPAQUE: build: status = Append("Build_", pout); - if - STATUS_OK - status = Append(bname[pin->dtype - DTYPE_PARAM], pout); - if - STATUS_OK - status = Append("(", pout); - if (pin->length) { + if (STATUS_OK) + status = Append(bname[pin->dtype - DTYPE_PARAM], pout); + if (STATUS_OK) + status = Append("(", pout); + if (pin->length) + { if (pin->length == 1) opcode = (opcode_t)(*(unsigned char *)pin->pointer); else if (pin->length == 2) @@ -295,16 +299,13 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, opcode = (opcode_t)(*(unsigned int *)pin->pointer); else opcode = (opcode_t)-1; - if - STATUS_OK - status = TdiSingle(opcode, pout); - if - STATUS_OK - status = Append(", ", pout); + if (STATUS_OK) + status = TdiSingle(opcode, pout); + if (STATUS_OK) + status = Append(", ", pout); } - if - STATUS_OK - status = Arguments(0, 0, ")", pin, pout); + if (STATUS_OK) + status = Arguments(0, 0, ")", pin, pout); break; case DTYPE_RANGE: @@ -327,20 +328,19 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, Functions, subscripts, and constructors. *****************************************/ else - switch (opcode) { + switch (opcode) + { default: /*intrinsic(arg, ...) */ cannot: status = Append(fun_ptr->name, pout); - if - STATUS_OK - status = Arguments(0, "(", ")", pin, pout); + if (STATUS_OK) + status = Arguments(0, "(", ")", pin, pout); break; case OPC_FUN: /*fun ident(arg, ...) stmt */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("Fun ", pout); + if (STATUS_OK) + status = Append("Fun ", pout); if (STATUS_NOT_OK) break; r_ptr = (struct descriptor_r *)pin->dscptrs[0]; @@ -348,13 +348,11 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, status = StrAppend(pout, (struct descriptor *)r_ptr); else status = Tdi0Decompile(r_ptr, P_SUBS, pout); - if - STATUS_OK - status = Arguments(2, " (", ") ", pin, pout); - if - STATUS_OK - status = CompoundStatement(1, (struct descriptor_r **)&pin->dscptrs[1], - pout); + if (STATUS_OK) + status = Arguments(2, " (", ") ", pin, pout); + if (STATUS_OK) + status = CompoundStatement(1, (struct descriptor_r **)&pin->dscptrs[1], + pout); if (STATUS_OK && prec < P_STMT) status = Append(")", pout); break; @@ -365,32 +363,29 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case OPC_PRIVATE: /*private ident */ case OPC_PUBLIC: /*public ident */ status = Append(fun_ptr->name, pout); - if - STATUS_OK - status = Append(" ", pout); + if (STATUS_OK) + status = Append(" ", pout); r_ptr = (struct descriptor_r *)pin->dscptrs[0]; - if - STATUS_OK { - if (r_ptr->dtype == DTYPE_T) - status = StrAppend(pout, (struct descriptor *)r_ptr); - else - status = Tdi0Decompile(r_ptr, P_SUBS, pout); - } + if (STATUS_OK) + { + if (r_ptr->dtype == DTYPE_T) + status = StrAppend(pout, (struct descriptor *)r_ptr); + else + status = Tdi0Decompile(r_ptr, P_SUBS, pout); + } break; case OPC_EXT_FUNCTION: /*_label(arg, ...)*/ if (pin->dscptrs[0] != 0 || pin->dscptrs[1] == 0 || pin->dscptrs[1]->dtype != DTYPE_T) goto cannot; status = StrAppend(pout, pin->dscptrs[1]); - if - STATUS_OK - status = Arguments(2, "(", ")", pin, pout); + if (STATUS_OK) + status = Arguments(2, "(", ")", pin, pout); break; case OPC_SUBSCRIPT: /*postfix[subscript, ...] */ status = Tdi0Decompile(pin->dscptrs[0], P_SUBS, pout); - if - STATUS_OK - status = Arguments(1, "[", "]", pin, pout); + if (STATUS_OK) + status = Arguments(1, "[", "]", pin, pout); break; case OPC_VECTOR: /*[elem, ...] */ status = Arguments(0, "[", "]", pin, pout); @@ -415,9 +410,8 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, status = Append(pop->symbol, pout); if (STATUS_OK && prec <= newone) status = Append("(", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], newone + lorr, pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], newone + lorr, pout); if (STATUS_OK && prec <= newone) status = Append(")", pout); if (STATUS_OK && lorr < 0) @@ -468,41 +462,38 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, break; newone = pop->prec; lorr = pop->lorr; - if (opcode == OPC_EQUALS_FIRST) { + if (opcode == OPC_EQUALS_FIRST) + { newone = binary[2].prec; lorr = binary[2].lorr; } if (prec <= newone) status = Append("(", pout); - if (opcode == OPC_CONDITIONAL) { - if - STATUS_OK - status = Tdi0Decompile(r_ptr->dscptrs[2], newone - lorr, pout); - if - STATUS_OK - status = Append(pop->symbol, pout); - if - STATUS_OK - status = Tdi0Decompile(r_ptr->dscptrs[0], newone, pout); - if - STATUS_OK - status = Append(" : ", pout); - if - STATUS_OK - status = Tdi0Decompile(r_ptr->dscptrs[1], newone + lorr, pout); - } else { - if - STATUS_OK - status = Tdi0Decompile(r_ptr->dscptrs[0], newone - lorr, pout); - for (m = 1; m < narg; m++) { - if - STATUS_OK + if (opcode == OPC_CONDITIONAL) + { + if (STATUS_OK) + status = Tdi0Decompile(r_ptr->dscptrs[2], newone - lorr, pout); + if (STATUS_OK) status = Append(pop->symbol, pout); + if (STATUS_OK) + status = Tdi0Decompile(r_ptr->dscptrs[0], newone, pout); + if (STATUS_OK) + status = Append(" : ", pout); + if (STATUS_OK) + status = Tdi0Decompile(r_ptr->dscptrs[1], newone + lorr, pout); + } + else + { + if (STATUS_OK) + status = Tdi0Decompile(r_ptr->dscptrs[0], newone - lorr, pout); + for (m = 1; m < narg; m++) + { + if (STATUS_OK) + status = Append(pop->symbol, pout); if (STATUS_OK && pin != r_ptr) status = Append("= ", pout); - if - STATUS_OK - status = Tdi0Decompile(r_ptr->dscptrs[m], newone + lorr, pout); + if (STATUS_OK) + status = Tdi0Decompile(r_ptr->dscptrs[m], newone + lorr, pout); } } if (STATUS_OK && prec <= newone) @@ -517,44 +508,36 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case OPC_CONTINUE: /*continue; */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append(fun_ptr->name, pout); - if - STATUS_OK - status = OneStatement(0, pout); + if (STATUS_OK) + status = Append(fun_ptr->name, pout); + if (STATUS_OK) + status = OneStatement(0, pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_CASE: /*case (xxx) stmt ... */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("Case (", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); - if - STATUS_OK - status = Append(") ", pout); - if - STATUS_OK - status = MultiStatement(narg - 1, - (struct descriptor_r **)&pin->dscptrs[1], pout); + if (STATUS_OK) + status = Append("Case (", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); + if (STATUS_OK) + status = Append(") ", pout); + if (STATUS_OK) + status = MultiStatement(narg - 1, + (struct descriptor_r **)&pin->dscptrs[1], pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_DEFAULT: /*case default stmt ... */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("Case Default ", pout); - if - STATUS_OK - status = MultiStatement(narg, (struct descriptor_r **)&pin->dscptrs[0], - pout); + if (STATUS_OK) + status = Append("Case Default ", pout); + if (STATUS_OK) + status = MultiStatement(narg, (struct descriptor_r **)&pin->dscptrs[0], + pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; @@ -562,68 +545,52 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, (exp,stmt,...) */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("DO {", pout); - if - STATUS_OK - status = MultiStatement(narg - 1, - (struct descriptor_r **)&pin->dscptrs[1], pout); - if - STATUS_OK - status = Append("} While ", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); - if - STATUS_OK - status = MultiStatement(0, (struct descriptor_r **)0, pout); + if (STATUS_OK) + status = Append("DO {", pout); + if (STATUS_OK) + status = MultiStatement(narg - 1, + (struct descriptor_r **)&pin->dscptrs[1], pout); + if (STATUS_OK) + status = Append("} While ", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); + if (STATUS_OK) + status = MultiStatement(0, (struct descriptor_r **)0, pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_FOR: /*for (init;test;step) stmt */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("For (", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); - if - STATUS_OK - status = Append("; ", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[1], P_STMT, pout); - if - STATUS_OK - status = Append("; ", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[2], P_STMT, pout); - if - STATUS_OK - status = Append(") ", pout); - if - STATUS_OK - status = CompoundStatement( - narg - 3, (struct descriptor_r **)&pin->dscptrs[3], pout); + if (STATUS_OK) + status = Append("For (", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); + if (STATUS_OK) + status = Append("; ", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[1], P_STMT, pout); + if (STATUS_OK) + status = Append("; ", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[2], P_STMT, pout); + if (STATUS_OK) + status = Append(") ", pout); + if (STATUS_OK) + status = CompoundStatement( + narg - 3, (struct descriptor_r **)&pin->dscptrs[3], pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_GOTO: /*goto xxx; */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("GoTo ", pout); - if - STATUS_OK - status = StrAppend(pout, pin->dscptrs[0]); - if - STATUS_OK - status = OneStatement(0, pout); + if (STATUS_OK) + status = Append("GoTo ", pout); + if (STATUS_OK) + status = StrAppend(pout, pin->dscptrs[0]); + if (STATUS_OK) + status = OneStatement(0, pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; @@ -631,25 +598,21 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case OPC_WHERE: /*where (exp) stmt elsewhere stmt */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append((opcode == OPC_IF) ? "If (" : "Where (", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); - if - STATUS_OK - status = Append(") ", pout); - if - STATUS_OK - status = CompoundStatement(1, (struct descriptor_r **)&pin->dscptrs[1], - pout); - if (STATUS_OK && narg >= 3) { + if (STATUS_OK) + status = Append((opcode == OPC_IF) ? "If (" : "Where (", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); + if (STATUS_OK) + status = Append(") ", pout); + if (STATUS_OK) + status = CompoundStatement(1, (struct descriptor_r **)&pin->dscptrs[1], + pout); + if (STATUS_OK && narg >= 3) + { status = Append((opcode == OPC_IF) ? " Else " : " ElseWhere ", pout); - if - STATUS_OK - status = CompoundStatement( - 1, (struct descriptor_r **)&pin->dscptrs[2], pout); + if (STATUS_OK) + status = CompoundStatement( + 1, (struct descriptor_r **)&pin->dscptrs[2], pout); } if (prec < P_STMT && STATUS_OK) status = Append(")", pout); @@ -657,47 +620,38 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case OPC_LABEL: /*xxx : stmt ... */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("Label ", pout); - if - STATUS_OK - status = StrAppend(pout, pin->dscptrs[0]); - if - STATUS_OK - status = Append(" : ", pout); - if - STATUS_OK - status = MultiStatement(narg - 1, - (struct descriptor_r **)&pin->dscptrs[1], pout); + if (STATUS_OK) + status = Append("Label ", pout); + if (STATUS_OK) + status = StrAppend(pout, pin->dscptrs[0]); + if (STATUS_OK) + status = Append(" : ", pout); + if (STATUS_OK) + status = MultiStatement(narg - 1, + (struct descriptor_r **)&pin->dscptrs[1], pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_RETURN: /*return (optional-exp); */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append("Return (", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->ndesc ? pin->dscptrs[0] : 0, P_STMT, pout); - if - STATUS_OK - status = Append(")", pout); - if - STATUS_OK - status = OneStatement(0, pout); + if (STATUS_OK) + status = Append("Return (", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->ndesc ? pin->dscptrs[0] : 0, P_STMT, pout); + if (STATUS_OK) + status = Append(")", pout); + if (STATUS_OK) + status = OneStatement(0, pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; case OPC_STATEMENT: /*{stmt ...} */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = MultiStatement(narg, (struct descriptor_r **)&pin->dscptrs[0], - pout); + if (STATUS_OK) + status = MultiStatement(narg, (struct descriptor_r **)&pin->dscptrs[0], + pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; @@ -705,19 +659,15 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, case OPC_WHILE: /*while (exp) stmt */ if (prec < P_STMT) status = Append("(", pout); - if - STATUS_OK - status = Append((opcode == OPC_SWITCH) ? "Switch (" : "While (", pout); - if - STATUS_OK - status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); - if - STATUS_OK - status = Append(") ", pout); - if - STATUS_OK - status = CompoundStatement( - narg - 1, (struct descriptor_r **)&pin->dscptrs[1], pout); + if (STATUS_OK) + status = Append((opcode == OPC_SWITCH) ? "Switch (" : "While (", pout); + if (STATUS_OK) + status = Tdi0Decompile(pin->dscptrs[0], P_STMT, pout); + if (STATUS_OK) + status = Append(") ", pout); + if (STATUS_OK) + status = CompoundStatement( + narg - 1, (struct descriptor_r **)&pin->dscptrs[1], pout); if (prec < P_STMT && STATUS_OK) status = Append(")", pout); break; @@ -733,7 +683,8 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, goto build; status = StrConcat((struct descriptor *)pout, (struct descriptor *)pout, pin->dscptrs[0], &ARROW, pin->dscptrs[1] MDS_END_ARG); - if (STATUS_OK && pin->length && pin->pointer) { + if (STATUS_OK && pin->length && pin->pointer) + { dtype = *(char *)pin->pointer; if (dtype < TdiCAT_MAX) ptext = TdiREF_CAT[dtype].name; @@ -744,13 +695,11 @@ int Tdi0Decompile_R(struct descriptor_r *pin, int prec, else ptext = "%Unknown%"; status = Append(":", pout); - if - STATUS_OK - status = Append(ptext, pout); + if (STATUS_OK) + status = Append(ptext, pout); } - if - STATUS_OK - status = Arguments(2, "(", ")", pin, pout); + if (STATUS_OK) + status = Arguments(2, "(", ")", pin, pout); break; } /******************* diff --git a/tdishr/TdiDecompress.c b/tdishr/TdiDecompress.c index 45ae310e6e..1d7fda6e8f 100644 --- a/tdishr/TdiDecompress.c +++ b/tdishr/TdiDecompress.c @@ -49,7 +49,8 @@ extern int TdiFindImageSymbol(); extern int TdiMasterData(); int Tdi1Decompress(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd sig[4] = {EMPTY_XD}, uni[4] = {EMPTY_XD}, dat[4] = {EMPTY_XD}; @@ -58,61 +59,62 @@ int Tdi1Decompress(opcode_t opcode, int narg, struct descriptor *list[], int bit = 0; status = TdiGetArgs(opcode, narg, list, sig, uni, dat, cats); - if - STATUS_OK - status = Tdi2Vector(narg - 2, &uni[2], &dat[2], &cats[2]); - if - STATUS_OK { - struct descriptor_a *pa = (struct descriptor_a *)dat[2].pointer; - int nitems; - if (pa->length <= 0) { - switch (pa->dtype) { - case DTYPE_B: - case DTYPE_BU: - pa->length = 1; - break; - case DTYPE_W: - case DTYPE_WU: - pa->length = 2; - break; - case DTYPE_L: - case DTYPE_LU: - case DTYPE_F: - case DTYPE_FS: - pa->length = 4; - break; - case DTYPE_D: - case DTYPE_G: - case DTYPE_FT: - case DTYPE_Q: - case DTYPE_QU: - pa->length = 8; - break; - case DTYPE_O: - case DTYPE_OU: - pa->length = 16; - break; - default: - return TdiINVDTYDSC; - } + if (STATUS_OK) + status = Tdi2Vector(narg - 2, &uni[2], &dat[2], &cats[2]); + if (STATUS_OK) + { + struct descriptor_a *pa = (struct descriptor_a *)dat[2].pointer; + int nitems; + if (pa->length <= 0) + { + switch (pa->dtype) + { + case DTYPE_B: + case DTYPE_BU: + pa->length = 1; + break; + case DTYPE_W: + case DTYPE_WU: + pa->length = 2; + break; + case DTYPE_L: + case DTYPE_LU: + case DTYPE_F: + case DTYPE_FS: + pa->length = 4; + break; + case DTYPE_D: + case DTYPE_G: + case DTYPE_FT: + case DTYPE_Q: + case DTYPE_QU: + pa->length = 8; + break; + case DTYPE_O: + case DTYPE_OU: + pa->length = 16; + break; + default: + return TdiINVDTYDSC; } - nitems = (int)pa->arsize / (int)pa->length; + } + nitems = (int)pa->arsize / (int)pa->length; - if (cats[1].in_dtype == DTYPE_MISSING) - symbol = MdsXpand; - else - status = TdiFindImageSymbol(dat[0].pointer, dat[1].pointer, &symbol); - if - STATUS_OK + if (cats[1].in_dtype == DTYPE_MISSING) + symbol = MdsXpand; + else + status = TdiFindImageSymbol(dat[0].pointer, dat[1].pointer, &symbol); + if (STATUS_OK) status = MdsGet1DxA(pa, &pa->length, &pa->dtype, out_ptr); - if - STATUS_OK { - out_ptr->pointer->class = CLASS_A; - status = (*symbol)(&nitems, dat[3].pointer, out_ptr->pointer, &bit); - } + if (STATUS_OK) + { + out_ptr->pointer->class = CLASS_A; + status = (*symbol)(&nitems, dat[3].pointer, out_ptr->pointer, &bit); } + } status = TdiMasterData(narg - 2, &sig[2], &uni[2], &cmode, out_ptr); - for (j = narg; --j >= 0;) { + for (j = narg; --j >= 0;) + { if (sig[j].pointer) MdsFree1Dx(&sig[j], NULL); if (uni[j].pointer) diff --git a/tdishr/TdiDefFunction.c b/tdishr/TdiDefFunction.c index cc6b68a541..847b5e12cc 100644 --- a/tdishr/TdiDefFunction.c +++ b/tdishr/TdiDefFunction.c @@ -34,30 +34,32 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #define COM -#define OPC(name, NAME, ...) \ - extern EXPORT int Tdi##name(struct descriptor *first, ...) { \ - if (first == MdsEND_ARG) \ - return TdiNO_OUTPTR; \ - int nargs; \ - struct descriptor *arglist[256]; \ - arglist[0] = (void *)first; \ - VA_LIST_MDS_END_ARG(arglist, nargs, 1, 0, first); \ - if (nargs > 255) \ - return TdiNO_OUTPTR; \ - return TdiIntrinsic(OPC_##NAME, nargs - 1, arglist, \ - (struct descriptor_xd *)arglist[nargs - 1]); \ - } \ - extern EXPORT int _Tdi##name(void **ctx, struct descriptor *first, ...) { \ - if (first == MdsEND_ARG) \ - return TdiNO_OUTPTR; \ - int nargs; \ - struct descriptor *arglist[256]; \ - arglist[0] = (void *)first; \ - VA_LIST_MDS_END_ARG(arglist, nargs, 1, 0, first); \ - if (nargs > 255) \ - return TdiNO_OUTPTR; \ - return _TdiIntrinsic(ctx, OPC_##NAME, nargs - 1, arglist, \ - (struct descriptor_xd *)arglist[nargs - 1]); \ +#define OPC(name, NAME, ...) \ + extern EXPORT int Tdi##name(struct descriptor *first, ...) \ + { \ + if (first == MdsEND_ARG) \ + return TdiNO_OUTPTR; \ + int nargs; \ + struct descriptor *arglist[256]; \ + arglist[0] = (void *)first; \ + VA_LIST_MDS_END_ARG(arglist, nargs, 1, 0, first); \ + if (nargs > 255) \ + return TdiNO_OUTPTR; \ + return TdiIntrinsic(OPC_##NAME, nargs - 1, arglist, \ + (struct descriptor_xd *)arglist[nargs - 1]); \ + } \ + extern EXPORT int _Tdi##name(void **ctx, struct descriptor *first, ...) \ + { \ + if (first == MdsEND_ARG) \ + return TdiNO_OUTPTR; \ + int nargs; \ + struct descriptor *arglist[256]; \ + arglist[0] = (void *)first; \ + VA_LIST_MDS_END_ARG(arglist, nargs, 1, 0, first); \ + if (nargs > 255) \ + return TdiNO_OUTPTR; \ + return _TdiIntrinsic(ctx, OPC_##NAME, nargs - 1, arglist, \ + (struct descriptor_xd *)arglist[nargs - 1]); \ } #include diff --git a/tdishr/TdiDim.c b/tdishr/TdiDim.c index 0c1c9edb56..ebabea7f11 100644 --- a/tdishr/TdiDim.c +++ b/tdishr/TdiDim.c @@ -91,86 +91,90 @@ extern int Tdi3Subtract(); extern int CvtConvertFloat(); static const int roprand = 0x8000; -typedef struct { +typedef struct +{ int longword[4]; } octaword; extern int TdiGtO(); extern int TdiLtO(); -#define SetupArgs \ - struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ - struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina1->arsize / ina1->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in2->class) { \ - case CLASS_S: \ - case CLASS_D: \ - if (scalars && (nout > 1)) \ - return TdiINV_SIZE; \ - scalars |= 2; \ - break; \ - case CLASS_A: \ - if (ina2->arsize / ina2->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ +#define SetupArgs \ + struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ + struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina1->arsize / ina1->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in2->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + if (scalars && (nout > 1)) \ + return TdiINV_SIZE; \ + scalars |= 2; \ + break; \ + case CLASS_A: \ + if (ina2->arsize / ina2->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ } -#define conv(data_type) \ - { \ - DESCRIPTOR_A(i1, sizeof(double), data_type, 0, 0); \ - DESCRIPTOR_A(i2, sizeof(double), data_type, 0, 0); \ - DESCRIPTOR_A(o, sizeof(double), data_type, 0, 0); \ - double *i1p = malloc(((scalars & 1) ? 1 : nout) * sizeof(double)); \ - double *i2p = malloc(((scalars & 1) ? 1 : nout) * sizeof(double)); \ - double *op = malloc(nout * sizeof(double)); \ - i1.arsize = (scalars & 1) ? 1 : nout; \ - i2.arsize = (scalars & 2) ? 1 : nout; \ - o.arsize = nout; \ - i1.pointer = (char *)i1p; \ - i2.pointer = (char *)i2p; \ - o.pointer = (char *)op; \ - TdiConvert(in1, &i1); \ - TdiConvert(in2, &i2); \ - { \ - struct descriptor_a *in1 = (struct descriptor_a *)&i1; \ - struct descriptor_a *in2 = (struct descriptor_a *)&i2; \ +#define conv(data_type) \ + { \ + DESCRIPTOR_A(i1, sizeof(double), data_type, 0, 0); \ + DESCRIPTOR_A(i2, sizeof(double), data_type, 0, 0); \ + DESCRIPTOR_A(o, sizeof(double), data_type, 0, 0); \ + double *i1p = malloc(((scalars & 1) ? 1 : nout) * sizeof(double)); \ + double *i2p = malloc(((scalars & 1) ? 1 : nout) * sizeof(double)); \ + double *op = malloc(nout * sizeof(double)); \ + i1.arsize = (scalars & 1) ? 1 : nout; \ + i2.arsize = (scalars & 2) ? 1 : nout; \ + o.arsize = nout; \ + i1.pointer = (char *)i1p; \ + i2.pointer = (char *)i2p; \ + o.pointer = (char *)op; \ + TdiConvert(in1, &i1); \ + TdiConvert(in2, &i2); \ + { \ + struct descriptor_a *in1 = (struct descriptor_a *)&i1; \ + struct descriptor_a *in2 = (struct descriptor_a *)&i2; \ struct descriptor_a *out = (struct descriptor_a *)&o; -#define unconv \ - } \ - TdiConvert(&o, out); \ - free(i1p); \ - free(i2p); \ - free(op); \ +#define unconv \ + } \ + TdiConvert(&o, out); \ + free(i1p); \ + free(i2p); \ + free(op); \ } #ifdef WORDS_BIGENDIAN @@ -180,10 +184,12 @@ extern int TdiLtO(); #endif int Tdi3Ibset(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ int size; SetupArgs TdiConvert(in1, out); - switch (in1->dtype) { + switch (in1->dtype) + { case DTYPE_B: case DTYPE_BU: size = sizeof(char); @@ -229,10 +235,12 @@ int Tdi3Ibset(struct descriptor *in1, struct descriptor *in2, { int *in2p = (int *)in2->pointer; char *outp = (char *)out->pointer; - switch (scalars) { + switch (scalars) + { case 0: case 1: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *(outp + _offset) |= 1 << (*in2p % 8); in2p++; @@ -240,7 +248,8 @@ int Tdi3Ibset(struct descriptor *in1, struct descriptor *in2, } break; case 2: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *(outp + _offset) |= 1 << (*in2p % 8); outp += size; @@ -256,10 +265,12 @@ int Tdi3Ibset(struct descriptor *in1, struct descriptor *in2, } int Tdi3Ibclr(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ int size; SetupArgs TdiConvert(in1, out); - switch (in1->dtype) { + switch (in1->dtype) + { case DTYPE_B: case DTYPE_BU: size = sizeof(char); @@ -305,10 +316,12 @@ int Tdi3Ibclr(struct descriptor *in1, struct descriptor *in2, { int *in2p = (int *)in2->pointer; char *outp = (char *)out->pointer; - switch (scalars) { + switch (scalars) + { case 0: case 1: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *(outp + _offset) &= ~(1 << (*in2p % 8)); in2p++; @@ -316,7 +329,8 @@ int Tdi3Ibclr(struct descriptor *in1, struct descriptor *in2, } break; case 2: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *(outp + _offset) &= ~(1 << (*in2p % 8)); outp += size; @@ -332,9 +346,11 @@ int Tdi3Ibclr(struct descriptor *in1, struct descriptor *in2, } int Tdi3Btest(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ int size; - SetupArgs switch (in1->dtype) { + SetupArgs switch (in1->dtype) + { case DTYPE_B: case DTYPE_BU: size = sizeof(char); @@ -381,9 +397,11 @@ int Tdi3Btest(struct descriptor *in1, struct descriptor *in2, char *in1p = (char *)in1->pointer; int *in2p = (int *)in2->pointer; char *outp = (char *)out->pointer; - switch (scalars) { + switch (scalars) + { case 0: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *outp = (char)((*(in1p + *in2p / 8) & (1 << (*in2p % 8))) > 0); in1p += size; @@ -392,7 +410,8 @@ int Tdi3Btest(struct descriptor *in1, struct descriptor *in2, } break; case 1: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *outp = (char)((*(in1p + *in2p / 8) & (1 << (*in2p % 8))) > 0); outp++; @@ -400,7 +419,8 @@ int Tdi3Btest(struct descriptor *in1, struct descriptor *in2, } break; case 2: - while (nout--) { + while (nout--) + { if (*in2p < size * 8) *outp = (char)((*(in1p + *in2p / 8) & (1 << (*in2p % 8))) > 0); in1p++; @@ -417,9 +437,11 @@ int Tdi3Btest(struct descriptor *in1, struct descriptor *in2, } int Tdi3Complex(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ int size, isize; - SetupArgs switch (in1->dtype) { + SetupArgs switch (in1->dtype) + { case DTYPE_B: case DTYPE_BU: case DTYPE_W: @@ -461,9 +483,11 @@ int Tdi3Complex(struct descriptor *in1, struct descriptor *in2, char *in1p = (char *)in1->pointer; char *in2p = (char *)in2->pointer; char *outp = (char *)out->pointer; - switch (scalars) { + switch (scalars) + { case 0: - while (nout--) { + while (nout--) + { memmove(outp, in1p, size); outp += size; memmove(outp, in2p, size); @@ -473,7 +497,8 @@ int Tdi3Complex(struct descriptor *in1, struct descriptor *in2, } break; case 1: - while (nout--) { + while (nout--) + { memmove(outp, in1p, size); outp += size; memmove(outp, in2p, size); @@ -482,7 +507,8 @@ int Tdi3Complex(struct descriptor *in1, struct descriptor *in2, } break; case 2: - while (nout--) { + while (nout--) + { memmove(outp, in1p, size); outp += size; memmove(outp, in2p, size); @@ -500,85 +526,101 @@ int Tdi3Complex(struct descriptor *in1, struct descriptor *in2, return 1; } -#define Operate(type, testit) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - *outp++ = *((testit) ? in1p : in2p); \ - in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - *outp++ = *((testit) ? in1p : in2p); \ - in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - *outp++ = *((testit) ? in1p : in2p); \ - in1p++; \ - } \ - break; \ - } \ - break; \ +#define Operate(type, testit) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + *outp++ = *((testit) ? in1p : in2p); \ + in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + *outp++ = *((testit) ? in1p : in2p); \ + in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + *outp++ = *((testit) ? in1p : in2p); \ + in1p++; \ + } \ + break; \ + } \ + break; \ } -#define OperateF(type, dtype, native, testit) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - type a, b; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ - CvtConvertFloat(in2p, dtype, &b, native, 0)) { \ - type ans = (testit) ? a : b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ - CvtConvertFloat(in2p, dtype, &b, native, 0)) { \ - type ans = (testit) ? a : b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ - CvtConvertFloat(in2p, dtype, &b, native, 0)) { \ - type ans = (testit) ? a : b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - in1p++; \ - } \ - break; \ - } \ - break; \ +#define OperateF(type, dtype, native, testit) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + type a, b; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ + CvtConvertFloat(in2p, dtype, &b, native, 0)) \ + { \ + type ans = (testit) ? a : b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ + CvtConvertFloat(in2p, dtype, &b, native, 0)) \ + { \ + type ans = (testit) ? a : b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ + CvtConvertFloat(in2p, dtype, &b, native, 0)) \ + { \ + type ans = (testit) ? a : b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + in1p++; \ + } \ + break; \ + } \ + break; \ } int Tdi3Max(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_T: return TdiINVDTYDSC; case DTYPE_B: @@ -603,8 +645,10 @@ int Tdi3Max(struct descriptor *in1, struct descriptor *in2, } int Tdi3Min(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_T: return TdiINVDTYDSC; case DTYPE_B: @@ -629,14 +673,17 @@ int Tdi3Min(struct descriptor *in1, struct descriptor *in2, } int Tdi3Dim(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { + struct descriptor *out) +{ INIT_STATUS; - typedef struct { + typedef struct + { double l[2]; } octaword_aligned; static const octaword_aligned zero = {{0}}; - switch (in1->dtype) { + switch (in1->dtype) + { default: break; case DTYPE_FC: @@ -649,10 +696,10 @@ int Tdi3Dim(struct descriptor *in1, struct descriptor *in2, return TdiINVDTYDSC; } status = Tdi3Subtract(in1, in2, out); - if - STATUS_NOT_OK - return status; - switch (in1->dtype) { + if (STATUS_NOT_OK) + return status; + switch (in1->dtype) + { default: break; case DTYPE_BU: @@ -680,74 +727,83 @@ int Tdi3Dim(struct descriptor *in1, struct descriptor *in2, } #undef Operate -#define Operate(type1, type2) \ - { \ - type1 *in1p = (type1 *)in1->pointer; \ - type2 *in2p = (type2 *)in2->pointer; \ - type1 *outp = (type1 *)out->pointer; \ - switch (scalars) { \ - case 0: \ - while (nout--) { \ - if (*in2p > 0) \ - *outp++ = (type1)(*in1p++ << *in2p++); \ - else \ - *outp++ = (type1)(*in1p++ >> (-(*in2p++))); \ - } \ - break; \ - case 1: \ - while (nout--) { \ - if (*in2p > 0) \ - *outp++ = (type1)(*in1p << *in2p++); \ - else \ - *outp++ = (type1)(*in1p >> (-(*in2p++))); \ - } \ - break; \ - case 2: \ - while (nout--) { \ - if (*in2p > 0) \ - *outp++ = (type1)(*in1p++ << *in2p); \ - else \ - *outp++ = (type1)(*in1p++ >> (-(*in2p))); \ - } \ - break; \ - case 3: { \ - if (*in2p > 0) \ - *outp = (type1)(*in1p << *in2p); \ - else \ - *outp = (type1)(*in1p >> (-(*in2p))); \ - } break; \ - } \ - break; \ +#define Operate(type1, type2) \ + { \ + type1 *in1p = (type1 *)in1->pointer; \ + type2 *in2p = (type2 *)in2->pointer; \ + type1 *outp = (type1 *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + while (nout--) \ + { \ + if (*in2p > 0) \ + *outp++ = (type1)(*in1p++ << *in2p++); \ + else \ + *outp++ = (type1)(*in1p++ >> (-(*in2p++))); \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + if (*in2p > 0) \ + *outp++ = (type1)(*in1p << *in2p++); \ + else \ + *outp++ = (type1)(*in1p >> (-(*in2p++))); \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + if (*in2p > 0) \ + *outp++ = (type1)(*in1p++ << *in2p); \ + else \ + *outp++ = (type1)(*in1p++ >> (-(*in2p))); \ + } \ + break; \ + case 3: \ + { \ + if (*in2p > 0) \ + *outp = (type1)(*in1p << *in2p); \ + else \ + *outp = (type1)(*in1p >> (-(*in2p))); \ + } \ + break; \ + } \ + break; \ } -#define Operate128(type, fun) \ - { \ - type##_t *in1p = (type##_t *)in1->pointer; \ - int128_t *in2p = (int128_t *)in2->pointer; \ - type##_t *outp = (type##_t *)out->pointer; \ - switch (scalars) { \ - case 0: \ - while (nout--) \ - type##_##fun(in1p++, (in2p++)->low, outp++); \ - break; \ - case 1: \ - while (nout--) \ - type##_##fun(in1p, (in2p++)->low, outp++); \ - break; \ - case 2: \ - while (nout--) \ - type##_##fun(in1p++, (in2p)->low, outp++); \ - break; \ - case 3: \ - type##_##fun(in1p, (in2p)->low, outp); \ - break; \ - } \ - break; \ +#define Operate128(type, fun) \ + { \ + type##_t *in1p = (type##_t *)in1->pointer; \ + int128_t *in2p = (int128_t *)in2->pointer; \ + type##_t *outp = (type##_t *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + while (nout--) \ + type##_##fun(in1p++, (in2p++)->low, outp++); \ + break; \ + case 1: \ + while (nout--) \ + type##_##fun(in1p, (in2p++)->low, outp++); \ + break; \ + case 2: \ + while (nout--) \ + type##_##fun(in1p++, (in2p)->low, outp++); \ + break; \ + case 3: \ + type##_##fun(in1p, (in2p)->low, outp); \ + break; \ + } \ + break; \ } int Tdi3Ishft(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_BU: case DTYPE_B: Operate(uint8_t, int8_t) case DTYPE_WU : case DTYPE_W @@ -760,45 +816,55 @@ int Tdi3Ishft(struct descriptor *in1, struct descriptor *in2, } #undef Operate -#define in2p_to_n(type1, type2, in2p) \ - type2 n = *in2p % (sizeof(type1) * CHAR_BIT); \ - if (n < 0) \ +#define in2p_to_n(type1, type2, in2p) \ + type2 n = *in2p % (sizeof(type1) * CHAR_BIT); \ + if (n < 0) \ n += (sizeof(type1) * CHAR_BIT) -#define Operate(type1, type2, operator) \ - { \ - type1 *in1p = (type1 *)in1->pointer; \ - type2 *in2p = (type2 *)in2->pointer; \ - type1 *outp = (type1 *)out->pointer; \ - switch (scalars) { \ - case 0: \ - while (nout--) { \ - in2p_to_n(type1, type2, in2p++); \ - *outp++ = (type1)(*in1p++ operator n); \ - } \ - break; \ - case 1: \ - while (nout--) { \ - in2p_to_n(type1, type2, in2p++); \ - *outp++ = (type1)(*in1p operator n); \ - } \ - break; \ - case 2: { \ - in2p_to_n(type1, type2, in2p); \ - while (nout--) { \ - *outp++ = (type1)(*in1p++ operator n); \ - } \ - } break; \ - case 3: { \ - in2p_to_n(type1, type2, in2p); \ - *outp = (type1)(*in1p operator n); \ - } break; \ - } \ - break; \ +#define Operate(type1, type2, operator) \ + { \ + type1 *in1p = (type1 *)in1->pointer; \ + type2 *in2p = (type2 *)in2->pointer; \ + type1 *outp = (type1 *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + while (nout--) \ + { \ + in2p_to_n(type1, type2, in2p++); \ + *outp++ = (type1)(*in1p++ operator n); \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + in2p_to_n(type1, type2, in2p++); \ + *outp++ = (type1)(*in1p operator n); \ + } \ + break; \ + case 2: \ + { \ + in2p_to_n(type1, type2, in2p); \ + while (nout--) \ + { \ + *outp++ = (type1)(*in1p++ operator n); \ + } \ + } \ + break; \ + case 3: \ + { \ + in2p_to_n(type1, type2, in2p); \ + *outp = (type1)(*in1p operator n); \ + } \ + break; \ + } \ + break; \ } int Tdi3ShiftRight(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, int8_t, >>) case DTYPE_BU : Operate(uint8_t, int8_t, >>) case DTYPE_W @@ -815,8 +881,10 @@ int Tdi3ShiftRight(struct descriptor *in1, struct descriptor *in2, } int Tdi3ShiftLeft(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, int8_t, <<) case DTYPE_BU : Operate(uint8_t, int8_t, <<) case DTYPE_W diff --git a/tdishr/TdiDivide.c b/tdishr/TdiDivide.c index e8a98727fa..3c206fbb4d 100644 --- a/tdishr/TdiDivide.c +++ b/tdishr/TdiDivide.c @@ -61,200 +61,226 @@ int Tdi3Divide(struct descriptor *in1, struct descriptor *in2, struct descriptor extern int CvtConvertFloat(); static const int roprand = 0x8000; -#define SetupArgs \ - struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ - struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina1->arsize / ina1->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in2->class) { \ - case CLASS_S: \ - case CLASS_D: \ - if (scalars && (nout > 1)) \ - return TdiINV_SIZE; \ - scalars |= 2; \ - break; \ - case CLASS_A: \ - if (ina2->arsize / ina2->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ +#define SetupArgs \ + struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ + struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina1->arsize / ina1->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in2->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + if (scalars && (nout > 1)) \ + return TdiINV_SIZE; \ + scalars |= 2; \ + break; \ + case CLASS_A: \ + if (ina2->arsize / ina2->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ } -#define Operate(type) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ - in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ - in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ - in1p++; \ - } \ - break; \ - } \ - break; \ +#define Operate(type) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ + in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ + in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + *outp++ = (type)(*in2p ? *in1p / *in2p : 0); \ + in1p++; \ + } \ + break; \ + } \ + break; \ } -#define OperateFone(type, dtype, native) \ - if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ - CvtConvertFloat(in2p, dtype, &b, native, 0) && b != 0.0) { \ - ans = a / b; \ - CvtConvertFloat(&ans, native, outp++, dtype, 0); \ - } else \ +#define OperateFone(type, dtype, native) \ + if (CvtConvertFloat(in1p, dtype, &a, native, 0) && \ + CvtConvertFloat(in2p, dtype, &b, native, 0) && b != 0.0) \ + { \ + ans = a / b; \ + CvtConvertFloat(&ans, native, outp++, dtype, 0); \ + } \ + else \ CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); -#define OperateF(type, dtype, native) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - type a, b, ans; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - OperateFone(type, dtype, native) in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - OperateFone(type, dtype, native) in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - OperateFone(type, dtype, native) in1p++; \ - } \ - break; \ - } \ - break; \ +#define OperateF(type, dtype, native) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + type a, b, ans; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + OperateFone(type, dtype, native) in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + OperateFone(type, dtype, native) in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + OperateFone(type, dtype, native) in1p++; \ + } \ + break; \ + } \ + break; \ } -#define Operate128(type) \ - { \ - type##_t *in1p = (type##_t *)in1->pointer; \ - type##_t *in2p = (type##_t *)in2->pointer; \ - type##_t *outp = (type##_t *)out->pointer; \ - switch (scalars) { \ - case 0: \ - while (nout--) \ - type##_div(in1p++, in2p++, outp++); \ - break; \ - case 1: \ - while (nout--) \ - type##_div(in1p, in2p++, outp++); \ - break; \ - case 2: \ - while (nout--) \ - type##_div(in1p, in2p++, outp++); \ - break; \ - case 3: \ - type##_div(in1p, in2p, outp); \ - break; \ - } \ - break; \ +#define Operate128(type) \ + { \ + type##_t *in1p = (type##_t *)in1->pointer; \ + type##_t *in2p = (type##_t *)in2->pointer; \ + type##_t *outp = (type##_t *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + while (nout--) \ + type##_div(in1p++, in2p++, outp++); \ + break; \ + case 1: \ + while (nout--) \ + type##_div(in1p, in2p++, outp++); \ + break; \ + case 2: \ + while (nout--) \ + type##_div(in1p, in2p++, outp++); \ + break; \ + case 3: \ + type##_div(in1p, in2p, outp); \ + break; \ + } \ + break; \ } -#define OperateCone(type, dtype) \ - if (CvtConvertFloat(&in1p[0], dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in1p[1], dtype, &b, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in2p[0], dtype, &c, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&in2p[1], dtype, &d, DTYPE_NATIVE_DOUBLE, 0)) { \ - double abs_c = (c > 0.0) ? c : -c; \ - double abs_d = (d > 0.0) ? d : -d; \ - double r, den, e, f; \ - if (abs_c >= abs_d) { \ - r = d / c; \ - den = c + r * d; \ - e = (a + b * r) / den; \ - f = (b - a * r) / den; \ - } else { \ - r = c / d; \ - den = d + r * c; \ - e = (a * r + b) / den; \ - f = (b * r - a) / den; \ - } \ - CvtConvertFloat(&e, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - CvtConvertFloat(&f, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - } else { \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ +#define OperateCone(type, dtype) \ + if (CvtConvertFloat(&in1p[0], dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in1p[1], dtype, &b, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in2p[0], dtype, &c, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&in2p[1], dtype, &d, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + double abs_c = (c > 0.0) ? c : -c; \ + double abs_d = (d > 0.0) ? d : -d; \ + double r, den, e, f; \ + if (abs_c >= abs_d) \ + { \ + r = d / c; \ + den = c + r * d; \ + e = (a + b * r) / den; \ + f = (b - a * r) / den; \ + } \ + else \ + { \ + r = c / d; \ + den = d + r * c; \ + e = (a * r + b) / den; \ + f = (b * r - a) / den; \ + } \ + CvtConvertFloat(&e, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + CvtConvertFloat(&f, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + } \ + else \ + { \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ } -#define OperateC(type, dtype) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - double a, b, c, d; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - OperateCone(type, dtype) in1p += 2; \ - in2p += 2; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - OperateCone(type, dtype) in2p += 2; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - OperateCone(type, dtype) in1p += 2; \ - } \ - break; \ - } \ - break; \ +#define OperateC(type, dtype) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + double a, b, c, d; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + OperateCone(type, dtype) in1p += 2; \ + in2p += 2; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + OperateCone(type, dtype) in2p += 2; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + OperateCone(type, dtype) in1p += 2; \ + } \ + break; \ + } \ + break; \ } int Tdi3Divide(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(char) case DTYPE_BU : Operate(unsigned char) case DTYPE_W : Operate(short) case DTYPE_WU : Operate(unsigned short) case DTYPE_L diff --git a/tdishr/TdiDoTask.c b/tdishr/TdiDoTask.c index 0f5489ae96..4509d91ede 100644 --- a/tdishr/TdiDoTask.c +++ b/tdishr/TdiDoTask.c @@ -66,7 +66,8 @@ extern int TdiCall(); ****/ static int Doit(struct descriptor_routine *ptask, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; int dtype, ndesc, j; void **arglist[256]; @@ -74,8 +75,10 @@ static int Doit(struct descriptor_routine *ptask, while (ndesc > 3 && ptask->arguments[ndesc - 4] == 0) ndesc--; dtype = ptask->length ? *(unsigned char *)ptask->pointer : DTYPE_L; - switch (ptask->dtype) { - case DTYPE_METHOD: { + switch (ptask->dtype) + { + case DTYPE_METHOD: + { struct descriptor_method *pmethod = (struct descriptor_method *)ptask; *(int *)&arglist[0] = ndesc + 1; /*** skip timeout,method,object ***/ @@ -91,22 +94,23 @@ static int Doit(struct descriptor_routine *ptask, FREED_ON_EXIT(&method_d); arglist[2] = (void *)&method_d; status = TdiData(pmethod->method, &method_d MDS_END_ARG); - if - STATUS_OK - status = TdiGetNid(pmethod->object, &nid); + if (STATUS_OK) + status = TdiGetNid(pmethod->object, &nid); status = (int)(intptr_t)LibCallg(arglist, TreeDoMethod); FREED_NOW(&method_d); status = TdiPutLong(&status, out_ptr); break; } /*case DTYPE_PROCEDURE : break; */ - case DTYPE_PROGRAM: { + case DTYPE_PROGRAM: + { struct descriptor_program *prog_task = (struct descriptor_program *)ptask; if (prog_task->program && prog_task->program->dtype == DTYPE_T) status = LibSpawn(prog_task->program, 1, 0) ? MDSplusERROR : MDSplusSUCCESS; status = TdiPutLong(&status, out_ptr); - } break; + } + break; case DTYPE_ROUTINE: status = TdiCall(dtype, ndesc - 1, &ptask->image, out_ptr); break; @@ -122,7 +126,8 @@ static int Doit(struct descriptor_routine *ptask, * mdstcpip/ProcessMessage.c * Problems with the implementation are likely to be fixed in all locations. */ -typedef struct { +typedef struct +{ void **ctx; int status; #ifndef _WIN32 @@ -131,13 +136,15 @@ typedef struct { struct descriptor_xd *const task_xd; } worker_args_t; -typedef struct { +typedef struct +{ worker_args_t *const wa; struct descriptor_xd *const xdp; void *pc; } worker_cleanup_t; -static void WorkerCleanup(void *args) { +static void WorkerCleanup(void *args) +{ worker_cleanup_t *const wc = (worker_cleanup_t *)args; if (wc->pc) TreeCtxPop(wc->pc); @@ -148,7 +155,8 @@ static void WorkerCleanup(void *args) { free_xd(wc->wa->task_xd); } -static int WorkerThread(void *args) { +static int WorkerThread(void *args) +{ EMPTYXD(xd); worker_cleanup_t wc = {(worker_args_t *)args, &xd, NULL}; pthread_cleanup_push(WorkerCleanup, (void *)&wc); @@ -156,14 +164,15 @@ static int WorkerThread(void *args) { struct descriptor_routine *ptask = (struct descriptor_routine *)wc.wa->task_xd->pointer; wc.wa->status = Doit(ptask, wc.xdp); - if - IS_OK(wc.wa->status) wc.wa->status = *(int *)xd.pointer->pointer; + if (IS_OK(wc.wa->status)) + wc.wa->status = *(int *)xd.pointer->pointer; pthread_cleanup_pop(1); return wc.wa->status; } static int StartWorker(struct descriptor_xd *task_xd, - struct descriptor_xd *out_ptr, const float timeout) { + struct descriptor_xd *out_ptr, const float timeout) +{ INIT_STATUS; #ifdef _WIN32 worker_args_t wa = { @@ -178,14 +187,16 @@ static int StartWorker(struct descriptor_xd *task_xd, #ifdef _WIN32 HANDLE hWorker = CreateThread(NULL, DEFAULT_STACKSIZE * 16, (void *)WorkerThread, &wa, 0, NULL); - if (!hWorker) { + if (!hWorker) + { errno = GetLastError(); perror("ERROR CreateThread"); status = MDSplusFATAL; goto end; } int canceled = B_FALSE; - if (WaitForSingleObject(hWorker, (int)(timeout * 1000)) == WAIT_TIMEOUT) { + if (WaitForSingleObject(hWorker, (int)(timeout * 1000)) == WAIT_TIMEOUT) + { fflush(stdout); fprintf(stderr, "Timeout, terminating Worker\n"); TerminateThread(hWorker, 2); @@ -198,7 +209,8 @@ static int StartWorker(struct descriptor_xd *task_xd, pthread_t Worker = 0; _CONDITION_LOCK(wa.condition); CREATE_THREAD(Worker, *16, WorkerThread, &wa); - if (c_status) { + if (c_status) + { perror("ERROR pthread_create"); _CONDITION_UNLOCK(wa.condition); pthread_cond_destroy(&WorkerRunning.cond); @@ -213,15 +225,19 @@ static int StartWorker(struct descriptor_xd *task_xd, tp.tv_sec += (time_t)(ns / 1000000000); int err = pthread_cond_timedwait(&WorkerRunning.cond, &WorkerRunning.mutex, &tp); - if (err) { + if (err) + { fflush(stdout); fprintf(stderr, "Timeout, terminating Worker .."); pthread_cancel(Worker); _CONDITION_WAIT_1SEC(wa.condition, ); fflush(stdout); - if (WorkerRunning.value) { + if (WorkerRunning.value) + { fprintf(stderr, " ok\n"); - } else { + } + else + { fprintf(stderr, " failed - sending SIGCHLD\n"); pthread_kill(Worker, SIGCHLD); } @@ -242,7 +258,8 @@ end:; int Tdi1DoTask(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; EMPTYXD(task_xd); int freetask; @@ -250,29 +267,33 @@ int Tdi1DoTask(opcode_t opcode __attribute__((unused)), freetask = 1; struct descriptor_routine *ptask; status = TdiTaskOf(list[0], &task_xd MDS_END_ARG); - if - STATUS_NOT_OK - goto cleanup; + if (STATUS_NOT_OK) + goto cleanup; ptask = (struct descriptor_routine *)task_xd.pointer; - if (!ptask) { + if (!ptask) + { status = TdiNULL_PTR; goto cleanup; } - switch (ptask->dtype) { + switch (ptask->dtype) + { case DTYPE_L: - case DTYPE_LU: { + case DTYPE_LU: + { status = *(int *)ptask->pointer; status = TdiPutLong(&status, out_ptr); goto cleanup; } case DTYPE_W: - case DTYPE_WU: { + case DTYPE_WU: + { status = (int)*(short *)ptask->pointer; status = TdiPutLong(&status, out_ptr); goto cleanup; } case DTYPE_B: - case DTYPE_BU: { + case DTYPE_BU: + { status = (int)*(char *)ptask->pointer; status = TdiPutLong(&status, out_ptr); goto cleanup; @@ -288,15 +309,16 @@ int Tdi1DoTask(opcode_t opcode __attribute__((unused)), } float timeout = (float)0.; - if - STATUS_OK - status = TdiGetFloat(ptask->time_out, &timeout); - if - STATUS_NOT_OK goto cleanup; - if (timeout > 0.) { + if (STATUS_OK) + status = TdiGetFloat(ptask->time_out, &timeout); + if (STATUS_NOT_OK) + goto cleanup; + if (timeout > 0.) + { freetask = 0; status = StartWorker(&task_xd, out_ptr, timeout); - } else + } + else status = Doit(ptask, out_ptr); cleanup:; FREEXD_IF(&task_xd, freetask); diff --git a/tdishr/TdiDtypeRange.c b/tdishr/TdiDtypeRange.c index e1a646bffb..38ca0411ad 100644 --- a/tdishr/TdiDtypeRange.c +++ b/tdishr/TdiDtypeRange.c @@ -69,7 +69,8 @@ extern int TdiNint(); extern struct descriptor *TdiItoXSpecial; int Tdi1DtypeRange(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; length_t len; @@ -97,7 +98,8 @@ int Tdi1DtypeRange(opcode_t opcode, int narg, struct descriptor *list[], **********************************************/ if (new[2] && new[2]->dtype == DTYPE_FUNCTION &&*(unsigned short *)new[2]->pointer == - OPC_$VALUE) { + OPC_$VALUE) + { DESCRIPTOR_RANGE(range, 0, 0, 0); range.begin = &dx0; range.ending = &dx1; @@ -106,26 +108,27 @@ int Tdi1DtypeRange(opcode_t opcode, int narg, struct descriptor *list[], if (new[0] == 0 && new[1] == 0) return TdiItoX(TDI_RANGE_PTRS[2], out_ptr MDS_END_ARG); status = TdiXtoI(TDI_RANGE_PTRS[2], TdiItoXSpecial, &limits MDS_END_ARG); - if - STATUS_OK { - dx0 = *limits.pointer; - dx0.class = CLASS_S; - dx1 = dx0; - dx1.pointer += dx1.length; - - dat[0] = dat[1] = EMPTY_XD; - if (new[0]) { - status = TdiXtoI(TDI_RANGE_PTRS[2], new[0], &dat[0] MDS_END_ARG); - range.begin = dat[0].pointer; - } + if (STATUS_OK) + { + dx0 = *limits.pointer; + dx0.class = CLASS_S; + dx1 = dx0; + dx1.pointer += dx1.length; + + dat[0] = dat[1] = EMPTY_XD; + if (new[0]) + { + status = TdiXtoI(TDI_RANGE_PTRS[2], new[0], &dat[0] MDS_END_ARG); + range.begin = dat[0].pointer; } - if (new[1] && STATUS_OK) { + } + if (new[1] && STATUS_OK) + { status = TdiXtoI(TDI_RANGE_PTRS[2], new[1], &dat[1] MDS_END_ARG); range.ending = dat[1].pointer; } - if - STATUS_OK - status = TdiItoX(TDI_RANGE_PTRS[2], &range, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiItoX(TDI_RANGE_PTRS[2], &range, out_ptr MDS_END_ARG); MdsFree1Dx(&dat[1], NULL); MdsFree1Dx(&dat[0], NULL); MdsFree1Dx(&limits, NULL); @@ -141,25 +144,21 @@ int Tdi1DtypeRange(opcode_t opcode, int narg, struct descriptor *list[], /****************************************** Fetch signals and data and data's category. ******************************************/ - if - STATUS_OK - status = TdiGetArgs(opcode, nnew, new, sig, uni, dat, cats); - if - STATUS_OK - for (j = nnew; --j >= 0;) - if (dat[j].pointer->dtype == DTYPE_MISSING) - status = TdiNULL_PTR; + if (STATUS_OK) + status = TdiGetArgs(opcode, nnew, new, sig, uni, dat, cats); + if (STATUS_OK) + for (j = nnew; --j >= 0;) + if (dat[j].pointer->dtype == DTYPE_MISSING) + status = TdiNULL_PTR; /****************************************** Adjust category needed to match data types. Do any conversions to match types. ******************************************/ - if - STATUS_OK - status = Tdi2Range(nnew, uni, dat, cats, 0); - if - STATUS_OK - status = TdiCvtArgs(nnew, dat, cats); + if (STATUS_OK) + status = Tdi2Range(nnew, uni, dat, cats, 0); + if (STATUS_OK) + status = TdiCvtArgs(nnew, dat, cats); dtype = cats[nnew].out_dtype; len = cats[nnew].digits; @@ -169,78 +168,76 @@ int Tdi1DtypeRange(opcode_t opcode, int narg, struct descriptor *list[], Total number of elements is sum of above. WARNING 3$ routines require type match. ********************************************/ - if - STATUS_OK - status = TdiSubtract(&dat[1], dat[0].pointer, &nelem MDS_END_ARG); + if (STATUS_OK) + status = TdiSubtract(&dat[1], dat[0].pointer, &nelem MDS_END_ARG); if (new[2] && STATUS_OK) status = TdiDivide(&nelem, dat[2].pointer, &nelem MDS_END_ARG); - if - STATUS_OK - status = TdiDim(&nelem, &minus_one, &nelem MDS_END_ARG); - if (STATUS_OK && nelem.pointer->dtype != DTYPE_L) { + if (STATUS_OK) + status = TdiDim(&nelem, &minus_one, &nelem MDS_END_ARG); + if (STATUS_OK && nelem.pointer->dtype != DTYPE_L) + { status = TdiNint(&nelem, &nelem MDS_END_ARG); if (STATUS_OK && nelem.pointer->dtype != DTYPE_L) status = TdiLong(&nelem, &nelem MDS_END_ARG); } - if - STATUS_OK { N_ELEMENTS(nelem.pointer, nseg); } - if - STATUS_OK - for (j = nseg, pl = (int *)nelem.pointer->pointer, tot = 0; --j >= 0;) - tot += *pl++; + if (STATUS_OK) + { + N_ELEMENTS(nelem.pointer, nseg); + } + if (STATUS_OK) + for (j = nseg, pl = (int *)nelem.pointer->pointer, tot = 0; --j >= 0;) + tot += *pl++; /************************** Output array size is known. Get the array and stuff it. **************************/ arr.arsize = tot; - if - STATUS_OK - status = MdsGet1DxA((struct descriptor_a *)&arr, &len, &dtype, out_ptr); - if - STATUS_OK { - DESCRIPTOR_A(x_dsc, 0, 0, 0, 0); - struct descriptor begin = {0, 0, CLASS_S, 0}; - struct descriptor delta = {0, 0, CLASS_S, 0}; - int incb = dat[0].pointer->class == CLASS_A; - int incs = new[2] && dat[2].pointer->class == CLASS_A; - - x_dsc.length = len; - x_dsc.dtype = dtype; - x_dsc.pointer = out_ptr->pointer->pointer; - begin.length = len; - begin.dtype = dtype; - begin.pointer = dat[0].pointer->pointer; - delta.length = len; - delta.dtype = dtype; - delta.pointer = new[2] ? dat[2].pointer->pointer : 0; - for (j = nseg, pl = (int *)nelem.pointer->pointer; --j >= 0;) { - x_dsc.arsize = *pl * len; - if - STATUS_OK + if (STATUS_OK) + status = MdsGet1DxA((struct descriptor_a *)&arr, &len, &dtype, out_ptr); + if (STATUS_OK) + { + DESCRIPTOR_A(x_dsc, 0, 0, 0, 0); + struct descriptor begin = {0, 0, CLASS_S, 0}; + struct descriptor delta = {0, 0, CLASS_S, 0}; + int incb = dat[0].pointer->class == CLASS_A; + int incs = new[2] && dat[2].pointer->class == CLASS_A; + + x_dsc.length = len; + x_dsc.dtype = dtype; + x_dsc.pointer = out_ptr->pointer->pointer; + begin.length = len; + begin.dtype = dtype; + begin.pointer = dat[0].pointer->pointer; + delta.length = len; + delta.dtype = dtype; + delta.pointer = new[2] ? dat[2].pointer->pointer : 0; + for (j = nseg, pl = (int *)nelem.pointer->pointer; --j >= 0;) + { + x_dsc.arsize = *pl * len; + if (STATUS_OK) status = Tdi3Ramp(&x_dsc); - if (new[2] && STATUS_OK) - status = Tdi3Multiply(&x_dsc, &delta, &x_dsc); - if - STATUS_OK + if (new[2] && STATUS_OK) + status = Tdi3Multiply(&x_dsc, &delta, &x_dsc); + if (STATUS_OK) status = Tdi3Add(&x_dsc, &begin, &x_dsc); - if (incb) - begin.pointer += len; - if (incs) - delta.pointer += len; - x_dsc.pointer += x_dsc.arsize; - ++pl; - } + if (incb) + begin.pointer += len; + if (incs) + delta.pointer += len; + x_dsc.pointer += x_dsc.arsize; + ++pl; } + } MdsFree1Dx(&nelem, NULL); MdsFree1Dx(&limits, NULL); - if - STATUS_OK - status = TdiMasterData(0, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(0, sig, uni, &cmode, out_ptr); - for (j = nnew; --j >= 0;) { + for (j = nnew; --j >= 0;) + { if (sig[j].pointer) MdsFree1Dx(&sig[j], NULL); if (uni[j].pointer) diff --git a/tdishr/TdiEq.c b/tdishr/TdiEq.c index d1e920b1e2..0bee6dfb4f 100644 --- a/tdishr/TdiEq.c +++ b/tdishr/TdiEq.c @@ -102,23 +102,24 @@ extern int Tdi3Not(); #define min(a, b) ((a) < (b)) ? (a) : (b) #define max(a, b) ((a) < (b)) ? (b) : (a) -#define compare(type, op) \ - if (s1) \ - for (i = 0; i < out_count; i++) \ - out[i] = (char)(in1[0] op in2[i]); \ - else if (s2) \ - for (i = 0; i < out_count; i++) \ - out[i] = (char)(in1[i] op in2[0]); \ - else \ - for (i = 0; i < out_count; i++) \ - out[i] = (char)(in1[i] op in2[i]); \ +#define compare(type, op) \ + if (s1) \ + for (i = 0; i < out_count; i++) \ + out[i] = (char)(in1[0] op in2[i]); \ + else if (s2) \ + for (i = 0; i < out_count; i++) \ + out[i] = (char)(in1[i] op in2[0]); \ + else \ + for (i = 0; i < out_count; i++) \ + out[i] = (char)(in1[i] op in2[i]); \ break; #define test(type) \ { \ type *in1 = (type *)(in1_ptr->pointer), *in2 = (type *)(in2_ptr->pointer); \ char *out = out_ptr->pointer; \ - switch (op) { \ + switch (op) \ + { \ case OP_EQ: \ compare(type, ==) case OP_GE : compare(type, >=) case OP_GT \ : compare(type, >) case OP_LE : compare(type, <=) case OP_LT \ @@ -127,13 +128,13 @@ extern int Tdi3Not(); } \ break; -#define comparef(type, dtype, native, op) \ - for (i = 0; i < out_count; i++, in1 += in1_inc, in2 += in2_inc) \ - if (CvtConvertFloat(in1, dtype, &a, native, 0) && \ - CvtConvertFloat(in2, dtype, &b, native, 0)) \ - out[i] = (char)(a op b); \ - else \ - out[i] = (char)0; \ +#define comparef(type, dtype, native, op) \ + for (i = 0; i < out_count; i++, in1 += in1_inc, in2 += in2_inc) \ + if (CvtConvertFloat(in1, dtype, &a, native, 0) && \ + CvtConvertFloat(in2, dtype, &b, native, 0)) \ + out[i] = (char)(a op b); \ + else \ + out[i] = (char)0; \ break; #define testf(type, dtype, native) \ @@ -143,7 +144,8 @@ extern int Tdi3Not(); char *out = out_ptr->pointer; \ int in1_inc = s1 ? 0 : 1; \ int in2_inc = s2 ? 0 : 1; \ - switch (op) { \ + switch (op) \ + { \ case OP_EQ: \ comparef(type, dtype, native, ==) case OP_GE \ : comparef(type, dtype, native, >=) case OP_GT \ @@ -159,29 +161,35 @@ extern int Tdi3Not(); compare_n compares multi-longword data types. For signed integer, all long words are compared using unsigned except for top longword. */ -#define compare_n(type, op, longwords, signed) \ - for (i = 0; i < out_count; i++) { \ - l = longwords * i; \ - for (j = longwords - 1; j >= 0; j--) \ - if (!j || in1[s1 ? j : l + j] != in2[s2 ? j : l + j]) { \ - if (!(signed) || !(j != longwords - 1)) { \ - out[i] = (char)(in1[s1 ? j : l + j] op in2[s2 ? j : l + j]); \ - break; \ - } else { \ - i1 = (int *)(in1 + (s1 ? j : l + j)), \ - i2 = (int *)(in2 + (s2 ? j : l + j)); \ - out[i] = (char)(*i1 op * i2); \ - break; \ - } \ - } \ - } \ +#define compare_n(type, op, longwords, signed) \ + for (i = 0; i < out_count; i++) \ + { \ + l = longwords * i; \ + for (j = longwords - 1; j >= 0; j--) \ + if (!j || in1[s1 ? j : l + j] != in2[s2 ? j : l + j]) \ + { \ + if (!(signed) || !(j != longwords - 1)) \ + { \ + out[i] = (char)(in1[s1 ? j : l + j] op in2[s2 ? j : l + j]); \ + break; \ + } \ + else \ + { \ + i1 = (int *)(in1 + (s1 ? j : l + j)), \ + i2 = (int *)(in2 + (s2 ? j : l + j)); \ + out[i] = (char)(*i1 op * i2); \ + break; \ + } \ + } \ + } \ break; #define testn(type, longwords, signed) \ { \ type *in1 = (type *)(in1_ptr->pointer), *in2 = (type *)(in2_ptr->pointer); \ char *out = out_ptr->pointer; \ - switch (op) { \ + switch (op) \ + { \ case OP_EQ: \ compare_n(type, ==, longwords, signed) case OP_GE \ : compare_n(type, >=, longwords, signed) case OP_GT \ @@ -201,45 +209,58 @@ extern int Tdi3Not(); Unequal strings are compared by using spaces to fill the smaller string. (All this emulates the CMPC macro instruction.) */ -#define compare_c(type, op, breakout, equal_until_last, not_op) \ - for (i = 0; i < out_count; i++) { \ - minlen = min(in1_ptr->length, in2_ptr->length); \ - maxlen = max(in1_ptr->length, in2_ptr->length); \ - k = 0; \ - out[i] = not_op 1; \ - while (k < maxlen) { \ - if (k >= minlen) { \ - type *in = (type *)((k >= in1_ptr->length) ? in2 : in1); \ - if (!(equal_until_last & (k < maxlen - 1 && ' ' == in[k]))) { \ - if (!((in == in2) ? (' ' op in[k]) : (in[k] op ' '))) { \ - out[i] = not_op 0; \ - break; \ - } else { \ - breakout \ - } \ - } \ - } else if (!(equal_until_last & (k < maxlen - 1 && in1[k] == in2[k]))) { \ - if (!(in1[k] op in2[k])) { \ - out[i] = not_op 0; \ - break; \ - } else { \ - breakout \ - } \ - } \ - k++; \ - } \ - if (!s1) \ - in1 = (type *)((char *)(in1) + in1_ptr->length); \ - if (!s2) \ - in2 = (type *)((char *)(in2) + in2_ptr->length); \ - } \ +#define compare_c(type, op, breakout, equal_until_last, not_op) \ + for (i = 0; i < out_count; i++) \ + { \ + minlen = min(in1_ptr->length, in2_ptr->length); \ + maxlen = max(in1_ptr->length, in2_ptr->length); \ + k = 0; \ + out[i] = not_op 1; \ + while (k < maxlen) \ + { \ + if (k >= minlen) \ + { \ + type *in = (type *)((k >= in1_ptr->length) ? in2 : in1); \ + if (!(equal_until_last & (k < maxlen - 1 && ' ' == in[k]))) \ + { \ + if (!((in == in2) ? (' ' op in[k]) : (in[k] op ' '))) \ + { \ + out[i] = not_op 0; \ + break; \ + } \ + else \ + { \ + breakout \ + } \ + } \ + } \ + else if (!(equal_until_last & (k < maxlen - 1 && in1[k] == in2[k]))) \ + { \ + if (!(in1[k] op in2[k])) \ + { \ + out[i] = not_op 0; \ + break; \ + } \ + else \ + { \ + breakout \ + } \ + } \ + k++; \ + } \ + if (!s1) \ + in1 = (type *)((char *)(in1) + in1_ptr->length); \ + if (!s2) \ + in2 = (type *)((char *)(in2) + in2_ptr->length); \ + } \ break; #define testc(type) \ { \ type *in1 = (type *)(in1_ptr->pointer), *in2 = (type *)(in2_ptr->pointer); \ char *out = out_ptr->pointer; \ - switch (op) { \ + switch (op) \ + { \ case OP_EQ: \ compare_c(type, ==, ;, 0, (char)) case OP_GE \ : compare_c(type, <, break;, 1, (char)!) case OP_GT \ @@ -252,7 +273,8 @@ extern int Tdi3Not(); break; int Tdi3_Eq(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr, int op) { + struct descriptor *out_ptr, int op) +{ INIT_STATUS; int out_count = 1; register int i, j, k; @@ -261,11 +283,11 @@ int Tdi3_Eq(struct descriptor *in1_ptr, struct descriptor *in2_ptr, int s2 = (in2_ptr->class != CLASS_A); status = TdiBinary(in1_ptr, in2_ptr, out_ptr, &out_count); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; - switch (in1_ptr->dtype) { + switch (in1_ptr->dtype) + { case DTYPE_T: testc(unsigned char) case DTYPE_BU : test(uint8_t) case DTYPE_WU : test(uint16_t) case DTYPE_LU : test(uint32_t) case DTYPE_QU @@ -278,12 +300,14 @@ int Tdi3_Eq(struct descriptor *in1_ptr, struct descriptor *in2_ptr, : testf(double, DTYPE_G, DTYPE_NATIVE_DOUBLE) case DTYPE_D : testf(double, DTYPE_D, DTYPE_NATIVE_DOUBLE) case DTYPE_FT : testf(double, DTYPE_FT, DTYPE_NATIVE_DOUBLE) case DTYPE_FC - : case DTYPE_FSC : if (op != OP_EQ && op != OP_NE) { + : case DTYPE_FSC : if (op != OP_EQ && op != OP_NE) + { status = TdiINVDTYDSC; break; } testn(int, 2, 0) case DTYPE_GC : case DTYPE_DC : case DTYPE_FTC - : if (op != OP_EQ && op != OP_NE) { + : if (op != OP_EQ && op != OP_NE) + { status = TdiINVDTYDSC; break; } @@ -293,35 +317,40 @@ int Tdi3_Eq(struct descriptor *in1_ptr, struct descriptor *in2_ptr, } int Tdi3Eq(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_EQ); } int Tdi3Ge(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_GE); } int Tdi3Gt(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_GT); } int Tdi3Le(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_LE); } int Tdi3Lt(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_LT); } int Tdi3Ne(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ int status = Tdi3_Eq(in1_ptr, in2_ptr, out_ptr, OP_EQ); - if - STATUS_OK - status = Tdi3Not(out_ptr, out_ptr); + if (STATUS_OK) + status = Tdi3Not(out_ptr, out_ptr); return status; } diff --git a/tdishr/TdiEvaluate.c b/tdishr/TdiEvaluate.c index 8274d77e80..69032c2b1c 100644 --- a/tdishr/TdiEvaluate.c +++ b/tdishr/TdiEvaluate.c @@ -72,17 +72,20 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), if (list[0] == 0) return MdsCopyDxXd(&missing, out_ptr); - switch (list[0]->class) { + switch (list[0]->class) + { case CLASS_XD: /*************************************************** If input is an class XD and dtype DSC and points to real stuff, we can just copy its descriptor. Release any lingering output unless it is our input. ***************************************************/ - if (list[0]->dtype == DTYPE_DSC) { + if (list[0]->dtype == DTYPE_DSC) + { if (list[0]->pointer == 0) return TdiNULL_PTR; - switch (((struct descriptor *)(list[0]->pointer))->dtype) { + switch (((struct descriptor *)(list[0]->pointer))->dtype) + { case DTYPE_DSC: case DTYPE_IDENT: case DTYPE_NID: @@ -91,7 +94,8 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), case DTYPE_CALL: break; default: - switch (((struct descriptor *)(list[0]->pointer))->class) { + switch (((struct descriptor *)(list[0]->pointer))->class) + { case CLASS_APD: break; default: @@ -112,7 +116,8 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), case CLASS_S: case CLASS_D: case CLASS_XS: - switch (list[0]->dtype) { + switch (list[0]->dtype) + { case DTYPE_DSC: status = TdiEvaluate(list[0]->pointer, out_ptr MDS_END_ARG); break; @@ -122,21 +127,20 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), case DTYPE_NID: pnid = (int *)list[0]->pointer; status = TdiGetRecord(*pnid, out_ptr); - if - STATUS_OK - status = TdiEvaluate(out_ptr, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiEvaluate(out_ptr, out_ptr MDS_END_ARG); break; - case DTYPE_PATH: { + case DTYPE_PATH: + { char *path = MdsDescrToCstring(list[0]); status = TreeFindNode(path, &nid); MdsFree(path); - if - STATUS_OK - status = TdiGetRecord(nid, out_ptr); - if - STATUS_OK - status = TdiEvaluate(out_ptr, out_ptr MDS_END_ARG); - } break; + if (STATUS_OK) + status = TdiGetRecord(nid, out_ptr); + if (STATUS_OK) + status = TdiEvaluate(out_ptr, out_ptr MDS_END_ARG); + } + break; default: if (list[0]->dtype < 160) status = SsINTERNAL; @@ -146,7 +150,8 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), } break; case CLASS_R: - switch (list[0]->dtype) { + switch (list[0]->dtype) + { case DTYPE_FUNCTION: pfun = (struct descriptor_function *)list[0]; status = TdiIntrinsic(*(unsigned short *)pfun->pointer, pfun->ndesc, @@ -192,9 +197,8 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), Must expand compressed data. 24-Apr-1991 ***************************************/ status = TdiEvaluate(list[0]->pointer, out_ptr MDS_END_ARG); - if - STATUS_OK - status = TdiImpose(list[0], out_ptr); + if (STATUS_OK) + status = TdiImpose(list[0], out_ptr); break; case CLASS_A: /************************* @@ -205,16 +209,18 @@ EXPORT int Tdi1Evaluate(opcode_t opcode __attribute__((unused)), break; case CLASS_APD: if (list[0]->dtype == DTYPE_DICTIONARY || list[0]->dtype == DTYPE_TUPLE || - list[0]->dtype == DTYPE_LIST || list[0]->dtype == DTYPE_OPAQUE) { + list[0]->dtype == DTYPE_LIST || list[0]->dtype == DTYPE_OPAQUE) + { status = SsINTERNAL; - } else { + } + else + { status = Tdi1Vector(0, (int)((struct descriptor_a *)list[0])->arsize / (int)list[0]->length, list[0]->pointer, out_ptr); - if - STATUS_OK - status = TdiImpose(list[0], out_ptr); + if (STATUS_OK) + status = TdiImpose(list[0], out_ptr); } break; default: diff --git a/tdishr/TdiExponent.c b/tdishr/TdiExponent.c index 8ba1b6c5af..8edf2f09b5 100644 --- a/tdishr/TdiExponent.c +++ b/tdishr/TdiExponent.c @@ -35,36 +35,36 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int IsRoprand(); #define F_FLOAT_EXPONENT(val) (((*(int *)val) >> 7) & 0xFF) -#define F_FLOAT_SET_EXPONENT(val, exp) \ +#define F_FLOAT_SET_EXPONENT(val, exp) \ (*(int *)val = (*(int *)val & ~(0xff << 7)) | (((exp)&0xff) << 7)) #define F_FLOAT_BIAS 0x80 #define F_FLOAT_PREC 23 #define FS_FLOAT_EXPONENT(val) (((*(int *)val) >> 23) & 0xFF) -#define FS_FLOAT_SET_EXPONENT(val, exp) \ +#define FS_FLOAT_SET_EXPONENT(val, exp) \ (*(int *)val = (*(int *)val & ~(0xff << 23)) | (((exp)&0xff) << 23)) #define FS_FLOAT_BIAS 0x80 #define FS_FLOAT_PREC 23 #define G_FLOAT_EXPONENT(val) (((*(int *)val) >> 4) & 0x7FF) -#define G_FLOAT_SET_EXPONENT(val, exp) \ +#define G_FLOAT_SET_EXPONENT(val, exp) \ (*(int *)val = (*(int *)val & ~(0x7ff << 4)) | (((exp)&0x7ff) << 4)) #define G_FLOAT_BIAS 0x400 #define G_FLOAT_PREC 52 #define D_FLOAT_EXPONENT(val) (((*(int *)val) >> 7) & 0xFF) -#define D_FLOAT_SET_EXPONENT(val, exp) \ +#define D_FLOAT_SET_EXPONENT(val, exp) \ (*(int *)val = (*(int *)val & ~(0xff << 7)) | (((exp)&0xff) << 7)) #define D_FLOAT_BIAS 0x80 #define D_FLOAT_PREC 55 #define FT_FLOAT_EXPONENT(val) ((((int *)val)[1] >> 20) & 0x7FF) -#define FT_FLOAT_SET_EXPONENT(val, exp) \ +#define FT_FLOAT_SET_EXPONENT(val, exp) \ (((int *)val)[1] = (((int *)val)[1] & ~(0x7ff << 20)) | (((exp)&0x7ff) << 20)) #define FT_FLOAT_BIAS 0x400 #define FT_FLOAT_PREC 52 -#define compute_exponent(dtype) \ - for (; --n >= 0; pi += step, ++po) \ - *po = dtype##_FLOAT_EXPONENT(pi) \ - ? dtype##_FLOAT_EXPONENT(pi) - dtype##_FLOAT_BIAS \ - : 0; \ +#define compute_exponent(dtype) \ + for (; --n >= 0; pi += step, ++po) \ + *po = dtype##_FLOAT_EXPONENT(pi) \ + ? dtype##_FLOAT_EXPONENT(pi) - dtype##_FLOAT_BIAS \ + : 0; \ break; /*------------------------------------------------------------------- @@ -73,29 +73,30 @@ extern int IsRoprand(); EXPONENT(1.0) is 1, EXPONENT(4.1) is 3, EXPONENT(0.0) is 0, EXPONENT(ROPRAND) is 0. integer = EXPONENT(real) */ -int Tdi3Exponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Exponent(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int n, step = in_ptr->length; char *pi = in_ptr->pointer; int *po = (int *)out_ptr->pointer; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - switch (in_ptr->dtype) { - case DTYPE_FC: - case DTYPE_FSC: - case DTYPE_DC: - case DTYPE_GC: - case DTYPE_FTC: - status = TdiNO_CMPLX; - break; - case DTYPE_F: - compute_exponent(F) case DTYPE_FS : compute_exponent(FS) case DTYPE_D - : compute_exponent(D) case DTYPE_G : compute_exponent(G) case DTYPE_FT - : compute_exponent(FT) default : status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (in_ptr->dtype) + { + case DTYPE_FC: + case DTYPE_FSC: + case DTYPE_DC: + case DTYPE_GC: + case DTYPE_FTC: + status = TdiNO_CMPLX; + break; + case DTYPE_F: + compute_exponent(F) case DTYPE_FS : compute_exponent(FS) case DTYPE_D + : compute_exponent(D) case DTYPE_G : compute_exponent(G) case DTYPE_FT + : compute_exponent(FT) default : status = TdiINVDTYDSC; + break; + } return status; } @@ -104,7 +105,8 @@ int Tdi3Exponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { FINITE(expression) VAX dependent. */ -int Tdi3Finite(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Finite(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *pin = in_ptr->pointer; char *pout = out_ptr->pointer; @@ -112,7 +114,8 @@ int Tdi3Finite(struct descriptor *in_ptr, struct descriptor *out_ptr) { int n; N_ELEMENTS(out_ptr, n); - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_F: for (; --n >= 0; pin += step) *pout++ = (char)!IsRoprand(DTYPE_F, pin); @@ -178,31 +181,34 @@ int Tdi3Finite(struct descriptor *in_ptr, struct descriptor *out_ptr) { ?:. */ -#define do_complex(type, dtype) \ - if (cmplx) { \ - for (; --n >= 0; inp += inp_inc, rep += rep_inc, outp += out_inc) { \ - *(type *)outp = IsRoprand(dtype, inp) ? *(type *)rep : *(type *)inp; \ - *(type *)(outp + 4) = IsRoprand(dtype, inp + sizeof(type)) \ - ? *(float *)(rep + sizeof(type)) \ - : *(float *)(inp + sizeof(type)); \ - } \ - break; \ - } \ - n += n; \ +#define do_complex(type, dtype) \ + if (cmplx) \ + { \ + for (; --n >= 0; inp += inp_inc, rep += rep_inc, outp += out_inc) \ + { \ + *(type *)outp = IsRoprand(dtype, inp) ? *(type *)rep : *(type *)inp; \ + *(type *)(outp + 4) = IsRoprand(dtype, inp + sizeof(type)) \ + ? *(float *)(rep + sizeof(type)) \ + : *(float *)(inp + sizeof(type)); \ + } \ + break; \ + } \ + n += n; \ inp_inc >>= 1; -#define do_simple(type, dtype) \ - for (; --n >= 0; inp += inp_inc, rep += rep_inc, outp += out_inc) \ - *(type *)outp = IsRoprand(dtype, inp) ? *(type *)rep : *(type *)inp; \ +#define do_simple(type, dtype) \ + for (; --n >= 0; inp += inp_inc, rep += rep_inc, outp += out_inc) \ + *(type *)outp = IsRoprand(dtype, inp) ? *(type *)rep : *(type *)inp; \ break; -#define do_fix(type, dtype) \ - case DTYPE##dtype##C: \ - do_complex(type, DTYPE##dtype) case DTYPE##dtype \ +#define do_fix(type, dtype) \ + case DTYPE##dtype##C: \ + do_complex(type, DTYPE##dtype) case DTYPE##dtype \ : do_simple(type, DTYPE##dtype) int Tdi3FixRoprand(struct descriptor *old_ptr, struct descriptor *rep_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; char *inp = old_ptr->pointer; char *rep = rep_ptr->pointer; @@ -213,7 +219,8 @@ int Tdi3FixRoprand(struct descriptor *old_ptr, struct descriptor *rep_ptr, int n, cmplx; N_ELEMENTS(out_ptr, n); - switch (rep_ptr->dtype) { + switch (rep_ptr->dtype) + { case DTYPE_F: case DTYPE_FS: case DTYPE_D: @@ -225,25 +232,26 @@ int Tdi3FixRoprand(struct descriptor *old_ptr, struct descriptor *rep_ptr, cmplx = 1; break; } - if - STATUS_OK - switch (out_ptr->dtype) { - do_fix(float, _F) do_fix(float, _FS) do_fix(double, _D) do_fix(double, _G) - do_fix(double, _FT) default : break; - } + if (STATUS_OK) + switch (out_ptr->dtype) + { + do_fix(float, _F) do_fix(float, _FS) do_fix(double, _D) do_fix(double, _G) + do_fix(double, _FT) default : break; + } return status; } -#define do_fraction(dtype, copydouble) \ - case DTYPE_##dtype##C: \ - n += n; \ - inc >>= 1; \ - case DTYPE_##dtype: \ - for (; --n >= 0; inp += inc, outp += inc) { \ - *(int *)outp = *(int *)inp; \ - copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ - dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_BIAS); \ - } \ +#define do_fraction(dtype, copydouble) \ + case DTYPE_##dtype##C: \ + n += n; \ + inc >>= 1; \ + case DTYPE_##dtype: \ + for (; --n >= 0; inp += inc, outp += inc) \ + { \ + *(int *)outp = *(int *)inp; \ + copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ + dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_BIAS); \ + } \ break; /*------------------------------------------------------------------- @@ -251,37 +259,39 @@ int Tdi3FixRoprand(struct descriptor *old_ptr, struct descriptor *rep_ptr, fraction. This is computer-dependent. VAX base=2. FRACTION(3.0) is .75, FRACTION(0.0) is 0.0, FRACTION(ROPRAND) is ROPRAND. real = FRACTION(real) */ -int Tdi3Fraction(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Fraction(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; char *inp = in_ptr->pointer; char *outp = out_ptr->pointer; int inc = out_ptr->length, n; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - switch (out_ptr->dtype) { - do_fraction(F, ;) do_fraction(FS, ;) - do_fraction(G, ((int *)outp)[1] = ((int *)inp)[1];) - do_fraction(D, ((int *)outp)[1] = ((int *)inp)[1];) - do_fraction(FT, ((int *)outp)[1] = ((int *)inp)[1];) default - : status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (out_ptr->dtype) + { + do_fraction(F, ;) do_fraction(FS, ;) + do_fraction(G, ((int *)outp)[1] = ((int *)inp)[1];) + do_fraction(D, ((int *)outp)[1] = ((int *)inp)[1];) + do_fraction(FT, ((int *)outp)[1] = ((int *)inp)[1];) default + : status = TdiINVDTYDSC; + break; + } return status; } -#define do_rrspacing(dtype, copydouble) \ - case DTYPE_##dtype##C: \ - n += n; \ - inc >>= 1; \ - case DTYPE_##dtype: \ - for (; --n >= 0; inp += inc, outp += inc) { \ - *(int *)outp = *(int *)inp; \ - copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ - dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_PREC + 1 + \ - dtype##_FLOAT_BIAS); \ - } \ +#define do_rrspacing(dtype, copydouble) \ + case DTYPE_##dtype##C: \ + n += n; \ + inc >>= 1; \ + case DTYPE_##dtype: \ + for (; --n >= 0; inp += inc, outp += inc) \ + { \ + *(int *)outp = *(int *)inp; \ + copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ + dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_PREC + 1 + \ + dtype##_FLOAT_BIAS); \ + } \ break; /*------------------------------------------------------------------- @@ -289,7 +299,8 @@ int Tdi3Fraction(struct descriptor *in_ptr, struct descriptor *out_ptr) { base**exponent * fraction. This is computer-dependent. VAX base=2. abs(X*b^(prec-offset)). RRSPACING(3.0) is .75*2^24. real = RRSPACING(real) */ -int Tdi3RrSpacing(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3RrSpacing(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int n; int inc = out_ptr->length; @@ -297,32 +308,33 @@ int Tdi3RrSpacing(struct descriptor *in_ptr, struct descriptor *out_ptr) { char *outp = out_ptr->pointer; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - switch (in_ptr->dtype) { - do_rrspacing(F, ;) do_rrspacing(FS, ;) - do_rrspacing(G, ((int *)outp)[1] = ((int *)inp)[1];) - do_rrspacing(D, ((int *)outp)[1] = ((int *)inp)[1];) - do_rrspacing(FT, ((int *)outp)[1] = ((int *)inp)[1];) default - : status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (in_ptr->dtype) + { + do_rrspacing(F, ;) do_rrspacing(FS, ;) + do_rrspacing(G, ((int *)outp)[1] = ((int *)inp)[1];) + do_rrspacing(D, ((int *)outp)[1] = ((int *)inp)[1];) + do_rrspacing(FT, ((int *)outp)[1] = ((int *)inp)[1];) default + : status = TdiINVDTYDSC; + break; + } return status; } -#define do_scale(dtype, copydouble) \ - case DTYPE_##dtype##C: \ - n += n; \ - inp_inc >>= 1; \ - outp_inc >>= 1; \ - inp2_inc >>= 1; \ - case DTYPE_##dtype: \ - for (; --n >= 0; inp += inp_inc, outp += outp_inc, inp2 += inp2_inc) { \ - *(int *)outp = *(int *)inp; \ - copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ - dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_EXPONENT(outp) + \ - *(int *)inp2); \ - } \ +#define do_scale(dtype, copydouble) \ + case DTYPE_##dtype##C: \ + n += n; \ + inp_inc >>= 1; \ + outp_inc >>= 1; \ + inp2_inc >>= 1; \ + case DTYPE_##dtype: \ + for (; --n >= 0; inp += inp_inc, outp += outp_inc, inp2 += inp2_inc) \ + { \ + *(int *)outp = *(int *)inp; \ + copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ + dtype##_FLOAT_SET_EXPONENT(outp, dtype##_FLOAT_EXPONENT(outp) + \ + *(int *)inp2); \ + } \ break; /*------------------------------------------------------------------- F8X elemental to scale number of model: sign * base**exponent * @@ -331,7 +343,8 @@ int Tdi3RrSpacing(struct descriptor *in_ptr, struct descriptor *out_ptr) { integer) NEED overflow detection, complex. */ int Tdi3Scale(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; int n; int inp_inc = (in1_ptr->class == CLASS_A) ? in1_ptr->length : 0; @@ -346,16 +359,16 @@ int Tdi3Scale(struct descriptor *in1_ptr, struct descriptor *in2_ptr, inp_inc = 0; if (in2_ptr->class != CLASS_A) inp2_inc = 0; - if - STATUS_OK - switch (in1_ptr->dtype) { - do_scale(F, ;) do_scale(FS, ;) - do_scale(G, ((int *)outp)[1] = ((int *)inp)[1];) - do_scale(D, ((int *)outp)[1] = ((int *)inp)[1];) - do_scale(FT, ((int *)outp)[1] = ((int *)inp)[1];) default - : status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (in1_ptr->dtype) + { + do_scale(F, ;) do_scale(FS, ;) + do_scale(G, ((int *)outp)[1] = ((int *)inp)[1];) + do_scale(D, ((int *)outp)[1] = ((int *)inp)[1];) + do_scale(FT, ((int *)outp)[1] = ((int *)inp)[1];) default + : status = TdiINVDTYDSC; + break; + } return status; } @@ -366,7 +379,8 @@ int Tdi3Scale(struct descriptor *in1_ptr, struct descriptor *in2_ptr, outp_inc >>= 1; \ inp2_inc >>= 1; \ case DTYPE_##dtype: \ - for (; --n >= 0; inp += inp_inc, outp += outp_inc, inp2 += inp2_inc) { \ + for (; --n >= 0; inp += inp_inc, outp += outp_inc, inp2 += inp2_inc) \ + { \ *(int *)outp = *(int *)inp; \ copydouble if (dtype##_FLOAT_EXPONENT(outp) != 0) \ dtype##_FLOAT_SET_EXPONENT(outp, *(int *)inp2 + dtype##_FLOAT_BIAS); \ @@ -380,7 +394,8 @@ int Tdi3Scale(struct descriptor *in1_ptr, struct descriptor *in2_ptr, NEED overflow detection. */ int Tdi3SetExponent(struct descriptor *in1_ptr, struct descriptor *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ INIT_STATUS; int n; int inp_inc = (in1_ptr->class == CLASS_A) ? in1_ptr->length : 0; @@ -391,30 +406,31 @@ int Tdi3SetExponent(struct descriptor *in1_ptr, struct descriptor *in2_ptr, char *outp = out_ptr->pointer; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - switch (in1_ptr->dtype) { - do_setexponent(F, ;) do_setexponent(FS, ;) - do_setexponent(G, ((int *)outp)[1] = ((int *)inp)[1];) - do_setexponent(D, ((int *)outp)[1] = ((int *)inp)[1];) - do_setexponent(FT, ((int *)outp)[1] = ((int *)inp)[1];) default - : status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (in1_ptr->dtype) + { + do_setexponent(F, ;) do_setexponent(FS, ;) + do_setexponent(G, ((int *)outp)[1] = ((int *)inp)[1];) + do_setexponent(D, ((int *)outp)[1] = ((int *)inp)[1];) + do_setexponent(FT, ((int *)outp)[1] = ((int *)inp)[1];) default + : status = TdiINVDTYDSC; + break; + } return status; } -#define do_spacing(dtype, zerodouble) \ - case DTYPE_##dtype##C: \ - n += n; \ - inc >>= 1; \ - case DTYPE_##dtype: \ - for (; --n >= 0; inp += inc, outp += inc) { \ - test = dtype##_FLOAT_EXPONENT(inp) - dtype##_FLOAT_PREC - 1; \ - *(int *)outp = 0; \ - zerodouble if (test >= 1) dtype##_FLOAT_SET_EXPONENT(outp, test); \ - else dtype##_FLOAT_SET_EXPONENT(outp, 1); \ - } \ +#define do_spacing(dtype, zerodouble) \ + case DTYPE_##dtype##C: \ + n += n; \ + inc >>= 1; \ + case DTYPE_##dtype: \ + for (; --n >= 0; inp += inc, outp += inc) \ + { \ + test = dtype##_FLOAT_EXPONENT(inp) - dtype##_FLOAT_PREC - 1; \ + *(int *)outp = 0; \ + zerodouble if (test >= 1) dtype##_FLOAT_SET_EXPONENT(outp, test); \ + else dtype##_FLOAT_SET_EXPONENT(outp, 1); \ + } \ break; /*------------------------------------------------------------------- @@ -423,7 +439,8 @@ int Tdi3SetExponent(struct descriptor *in1_ptr, struct descriptor *in2_ptr, base=2. base^(exp-prec) SPACING(3.0) is 2^22. real = SPACING(real) NEED overflow detection. */ -int Tdi3Spacing(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Spacing(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int n, test; int inc = out_ptr->length; @@ -431,14 +448,14 @@ int Tdi3Spacing(struct descriptor *in_ptr, struct descriptor *out_ptr) { char *outp = out_ptr->pointer; N_ELEMENTS(out_ptr, n); - if - STATUS_OK - switch (in_ptr->dtype) { - do_spacing(F, ;) do_spacing(FS, ;) do_spacing(G, ((int *)outp)[1] = 0;) - do_spacing(D, ((int *)outp)[1] = 0;) - do_spacing(FT, ((int *)outp)[1] = 0;) default : status = - TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (in_ptr->dtype) + { + do_spacing(F, ;) do_spacing(FS, ;) do_spacing(G, ((int *)outp)[1] = 0;) + do_spacing(D, ((int *)outp)[1] = 0;) + do_spacing(FT, ((int *)outp)[1] = 0;) default : status = + TdiINVDTYDSC; + break; + } return status; } diff --git a/tdishr/TdiExpt.c b/tdishr/TdiExpt.c index 2ec13c5435..977ad051d9 100644 --- a/tdishr/TdiExpt.c +++ b/tdishr/TdiExpt.c @@ -39,7 +39,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Default path name. */ int Tdi3MdsDefault(struct descriptor *in_ptr __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ char value[4096]; static const dtype_t dtype = DTYPE_T; int retlen, status; @@ -49,14 +50,13 @@ int Tdi3MdsDefault(struct descriptor *in_ptr __attribute__((unused)), lst[0].pointer = (uint8_t *)value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); - if - STATUS_OK { - len = (length_t)retlen; - status = MdsGet1DxS(&len, &dtype, out_ptr); - } - if - STATUS_OK - memcpy(out_ptr->pointer->pointer, value, len); + if (STATUS_OK) + { + len = (length_t)retlen; + status = MdsGet1DxS(&len, &dtype, out_ptr); + } + if (STATUS_OK) + memcpy(out_ptr->pointer->pointer, value, len); return status; } @@ -64,7 +64,8 @@ int Tdi3MdsDefault(struct descriptor *in_ptr __attribute__((unused)), Experiment name. */ int Tdi3Expt(struct descriptor *in_ptr __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ char value[39 - 7]; int retlen, status; static const dtype_t dtype = DTYPE_T; @@ -74,14 +75,13 @@ int Tdi3Expt(struct descriptor *in_ptr __attribute__((unused)), lst[0].pointer = (unsigned char *)value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); - if - STATUS_OK { - len = (length_t)retlen; - status = MdsGet1DxS(&len, &dtype, out_ptr); - } - if - STATUS_OK - memcpy(out_ptr->pointer->pointer, value, len); + if (STATUS_OK) + { + len = (length_t)retlen; + status = MdsGet1DxS(&len, &dtype, out_ptr); + } + if (STATUS_OK) + memcpy(out_ptr->pointer->pointer, value, len); return status; } @@ -89,7 +89,8 @@ int Tdi3Expt(struct descriptor *in_ptr __attribute__((unused)), Shot number identifier. */ int Tdi3Shot(struct descriptor *in_ptr __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ int value; int retlen, status; static const dtype_t dtype = DTYPE_L; @@ -99,14 +100,13 @@ int Tdi3Shot(struct descriptor *in_ptr __attribute__((unused)), lst[0].pointer = (unsigned char *)&value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); - if - STATUS_OK { - len = (length_t)retlen; - status = MdsGet1DxS(&len, &dtype, out_ptr); - } - if - STATUS_OK - *(int *)out_ptr->pointer->pointer = value; + if (STATUS_OK) + { + len = (length_t)retlen; + status = MdsGet1DxS(&len, &dtype, out_ptr); + } + if (STATUS_OK) + *(int *)out_ptr->pointer->pointer = value; return status; } @@ -114,7 +114,8 @@ int Tdi3Shot(struct descriptor *in_ptr __attribute__((unused)), Shot number identifier converted to string. */ int Tdi3Shotname(struct descriptor *in_ptr __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ int value; int retlen, status; struct dbi_itm lst[] = {{sizeof(value), DbiSHOTID, 0, 0}, @@ -124,13 +125,13 @@ int Tdi3Shotname(struct descriptor *in_ptr __attribute__((unused)), lst[0].pointer = (unsigned char *)&value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); - if (value != -1) { + if (value != -1) + { sprintf(string, "%d", value); dmodel.pointer = string; dmodel.length = (unsigned short)strlen(string); } - if - STATUS_OK - status = MdsCopyDxXd((struct descriptor *)&dmodel, out_ptr); + if (STATUS_OK) + status = MdsCopyDxXd((struct descriptor *)&dmodel, out_ptr); return status; } diff --git a/tdishr/TdiExtFunction.c b/tdishr/TdiExtFunction.c index de4bf0087d..b33476cab7 100644 --- a/tdishr/TdiExtFunction.c +++ b/tdishr/TdiExtFunction.c @@ -67,23 +67,27 @@ extern int TdiEvaluate(); static const struct descriptor_d EMPTY_D = {0, DTYPE_T, CLASS_D, 0}; int TdiFindImageSymbol(struct descriptor_d *image, struct descriptor_d *entry, - int (**symbol)()) { + int (**symbol)()) +{ return LibFindImageSymbol(image, entry, symbol); } extern int TdiFindSymbol(); -struct _tmp { +struct _tmp +{ int n; struct descriptor_xd a[253]; }; -static void tmp_cleanup(void *tmp_in) { +static void tmp_cleanup(void *tmp_in) +{ struct _tmp *tmp = (struct _tmp *)tmp_in; for (; --tmp->n >= 0;) MdsFree1Dx(&tmp->a[tmp->n], NULL); } int Tdi1ExtFunction(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ int status; struct descriptor_d image = EMPTY_D, entry = EMPTY_D; FREED_ON_EXIT(&image); @@ -91,21 +95,20 @@ int Tdi1ExtFunction(opcode_t opcode __attribute__((unused)), int narg, status = MDSplusSUCCESS; if (list[0]) status = TdiData(list[0], &image MDS_END_ARG); - if - STATUS_OK - status = TdiData(list[1], &entry MDS_END_ARG); + if (STATUS_OK) + status = TdiData(list[1], &entry MDS_END_ARG); if (STATUS_NOT_OK) goto done; /************************** Quickly do known functions. **************************/ int (*routine)(); - if (image.length == 0) { + if (image.length == 0) + { status = StrUpcase((struct descriptor *)&entry, (struct descriptor *)&entry); - if - STATUS_OK - status = TdiDoFun(&entry, narg - 2, &list[2], out_ptr); + if (STATUS_OK) + status = TdiDoFun(&entry, narg - 2, &list[2], out_ptr); goto done; } @@ -113,67 +116,77 @@ int Tdi1ExtFunction(opcode_t opcode __attribute__((unused)), int narg, /********************************************** Requires: image found and routine symbol found. **********************************************/ - if - STATUS_OK { - int j = 0; - struct _tmp tmp = {0}; - pthread_cleanup_push(tmp_cleanup, (void *)&tmp); - status = MDSplusSUCCESS; - struct descriptor_function *pfun; - struct descriptor *new[256]; - *(int *)&new[0] = narg - 1; - new[narg - 1] = (struct descriptor *)out_ptr; - unsigned short code; - for (j = 2; j < narg && STATUS_OK; ++j) { - pfun = (struct descriptor_function *)(new[j - 1] = list[j]); - if (pfun) { - if (pfun->dtype == DTYPE_FUNCTION) { - /**************************************** + if (STATUS_OK) + { + int j = 0; + struct _tmp tmp = {0}; + pthread_cleanup_push(tmp_cleanup, (void *)&tmp); + status = MDSplusSUCCESS; + struct descriptor_function *pfun; + struct descriptor *new[256]; + *(int *)&new[0] = narg - 1; + new[narg - 1] = (struct descriptor *)out_ptr; + unsigned short code; + for (j = 2; j < narg && STATUS_OK; ++j) + { + pfun = (struct descriptor_function *)(new[j - 1] = list[j]); + if (pfun) + { + if (pfun->dtype == DTYPE_FUNCTION) + { + /**************************************** Special forms used for VMS and LIB calls. ****************************************/ - code = *(unsigned short *)pfun->pointer; - if (code == OPC_DESCR) { - tmp.a[tmp.n] = EMPTY_XD; - status = TdiData(pfun->arguments[0], &tmp.a[tmp.n] MDS_END_ARG); - new[j - 1] = (struct descriptor *)tmp.a[tmp.n++].pointer; - } else if (code == OPC_REF) { - tmp.a[tmp.n] = EMPTY_XD; - status = TdiData(pfun->arguments[0], &tmp.a[tmp.n] MDS_END_ARG); - if - STATUS_NOT_OK break; // .pointer == NULL - new[j - 1] = (struct descriptor *)tmp.a[tmp.n++].pointer->pointer; - } else if (code == OPC_VAL) - status = TdiGetLong(pfun->arguments[0], &new[j - 1]); - else if (code == OPC_PRIVATE || code == OPC_PUBLIC) - goto ident; - } else if (pfun->dtype == DTYPE_IDENT) { - ident:; - /************************************ + code = *(unsigned short *)pfun->pointer; + if (code == OPC_DESCR) + { + tmp.a[tmp.n] = EMPTY_XD; + status = TdiData(pfun->arguments[0], &tmp.a[tmp.n] MDS_END_ARG); + new[j - 1] = (struct descriptor *)tmp.a[tmp.n++].pointer; + } + else if (code == OPC_REF) + { + tmp.a[tmp.n] = EMPTY_XD; + status = TdiData(pfun->arguments[0], &tmp.a[tmp.n] MDS_END_ARG); + if (STATUS_NOT_OK) + break; // .pointer == NULL + new[j - 1] = (struct descriptor *)tmp.a[tmp.n++].pointer->pointer; + } + else if (code == OPC_VAL) + status = TdiGetLong(pfun->arguments[0], &new[j - 1]); + else if (code == OPC_PRIVATE || code == OPC_PUBLIC) + goto ident; + } + else if (pfun->dtype == DTYPE_IDENT) + { + ident:; + /************************************ Handle multiple outputs to variables. So far only DSQL needs this. ************************************/ - unsigned char test; - struct descriptor dtest = {sizeof(test), DTYPE_BU, CLASS_S, 0}; - dtest.pointer = (char *)&test; - status = TdiAllocated(pfun, &dtest MDS_END_ARG); - if (status && !test) { - status = tdi_put_ident(pfun, 0); - } + unsigned char test; + struct descriptor dtest = {sizeof(test), DTYPE_BU, CLASS_S, 0}; + dtest.pointer = (char *)&test; + status = TdiAllocated(pfun, &dtest MDS_END_ARG); + if (status && !test) + { + status = tdi_put_ident(pfun, 0); } } } - /************************* + } + /************************* Same form as system calls. Watch, may not be XD. *************************/ - if - STATUS_OK { - struct descriptor_s out = {sizeof(void *), DTYPE_POINTER, CLASS_S, - LibCallg(&new[0], routine)}; - MdsCopyDxXd((struct descriptor *)&out, out_ptr); - } - pthread_cleanup_pop(1); + if (STATUS_OK) + { + struct descriptor_s out = {sizeof(void *), DTYPE_POINTER, CLASS_S, + LibCallg(&new[0], routine)}; + MdsCopyDxXd((struct descriptor *)&out, out_ptr); } + pthread_cleanup_pop(1); + } else printf("%s\n", LibFindImageSymbolErrString()); done:; diff --git a/tdishr/TdiExtPython.c b/tdishr/TdiExtPython.c index 39fd089d43..e07f27b47c 100644 --- a/tdishr/TdiExtPython.c +++ b/tdishr/TdiExtPython.c @@ -39,33 +39,35 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //#define DEBUG #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) -#define DEBUG_GIL_CHECK \ - if (PyGILState_Check) \ - fprintf(stderr, \ - "INFO: thread 0x%" PRIxPTR " holds GIL 0x%" PRIxPTR ": %c\n", \ - (uintptr_t)pthread_self(), (uintptr_t)GIL, \ +#define DEBUG_GIL_CHECK \ + if (PyGILState_Check) \ + fprintf(stderr, \ + "INFO: thread 0x%" PRIxPTR " holds GIL 0x%" PRIxPTR ": %c\n", \ + (uintptr_t)pthread_self(), (uintptr_t)GIL, \ "ny"[PyGILState_Check() != 0]); #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #define DEBUG_GIL_CHECK #endif #ifdef _WIN32 -#define USE_EXECFILE /* windows cannot use PyRun_File because if crashes on \ +#define USE_EXECFILE /* windows cannot use PyRun_File because if crashes on \ _lockfile */ #else //#define USE_EXECFILE /* for debugging purpose */ #endif -#define loadrtn2(sym, name, check) \ - do { \ - sym = dlsym(handle, name); \ - if (check && !sym) { \ - fprintf(stderr, "\n\nError finding python routine: %s\n\n", name); \ - return; \ - } \ +#define loadrtn2(sym, name, check) \ + do \ + { \ + sym = dlsym(handle, name); \ + if (check && !sym) \ + { \ + fprintf(stderr, "\n\nError finding python routine: %s\n\n", name); \ + return; \ + } \ } while (0) //" #define loadrtn(sym, check) loadrtn2(sym, #sym, check) @@ -115,13 +117,15 @@ static PyObject *pointerToObject = NULL; static PyObject *makeData = NULL; static PyObject *MDSplusException = NULL; -inline static void initialize() { +inline static void initialize() +{ int old_state = PTHREAD_CANCEL_DISABLE; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state); void *handle; char *lib; char *envsym = getenv("PyLib"); - if (!envsym || (envsym[0] == '\0')) { // NULL or empty + if (!envsym || (envsym[0] == '\0')) + { // NULL or empty #ifdef _WIN32 envsym = "python27"; const char *aspath = "C:\\Python27\\python27.dll"; @@ -143,31 +147,39 @@ inline static void initialize() { handle = dlopen(0, RTLD_NOLOAD); loadrtn(Py_InitializeEx, 0); /*** If not, load the python library ***/ - if (!Py_InitializeEx) { + if (!Py_InitializeEx) + { #else { #endif #ifdef _WIN32 if (strlen(envsym) > 6 && (envsym[1] == ':' || - strncmp(envsym + strlen(envsym) - 4, ".dll", 4) == 0)) { + strncmp(envsym + strlen(envsym) - 4, ".dll", 4) == 0)) + { lib = strcpy((char *)malloc(strlen(envsym) + 1), envsym); - } else { + } + else + { lib = strcpy((char *)malloc(strlen(envsym) + 5), envsym); strcat(lib, ".dll"); } #else if (strlen(envsym) > 6 && - (envsym[0] == '/' || strncmp(envsym, "lib", 3) == 0)) { + (envsym[0] == '/' || strncmp(envsym, "lib", 3) == 0)) + { lib = strcpy((char *)malloc(strlen(envsym) + 1), envsym); - } else { + } + else + { lib = strcpy((char *)malloc(strlen(envsym) + 7), "lib"); strcat(lib, envsym); strcat(lib, ".so"); } #endif handle = dlopen(lib, RTLD_NOW | RTLD_GLOBAL); - if (!handle) { + if (!handle) + { fprintf(stderr, "\n\nUnable to load python library: %s\nError: %s\n\n", lib, dlerror()); free(lib); @@ -179,11 +191,13 @@ inline static void initialize() { } int (*Py_IsInitialized)(); loadrtn(Py_IsInitialized, 1); - if (!Py_IsInitialized()) { // eg when called from python itself - Py_InitializeEx(0); // 1: register signals; 0: don't + if (!Py_IsInitialized()) + { // eg when called from python itself + Py_InitializeEx(0); // 1: register signals; 0: don't int (*PyEval_ThreadsInitialized)() = NULL; loadrtn(PyEval_ThreadsInitialized, 1); - if (!PyEval_ThreadsInitialized()) { + if (!PyEval_ThreadsInitialized()) + { void (*PyEval_InitThreads)(); loadrtn(PyEval_InitThreads, 1); PyEval_InitThreads(); // pyhton3.7 calls PyEval_InitThreads during @@ -231,10 +245,12 @@ inline static void initialize() { pthread_setcancelstate(old_state, NULL); } -static void PyGILState_Cleanup(void *GIL) { +static void PyGILState_Cleanup(void *GIL) +{ DBG("PyGILState_Cleanup(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, (uintptr_t)pthread_self()); - if (PyGILState_Check && PyGILState_Check()) { + if (PyGILState_Check && PyGILState_Check()) + { fprintf(stderr, "FATAL: thread 0x%" PRIxPTR " still holds 0xGIL %" PRIxPTR "; ABORT\n", @@ -244,48 +260,57 @@ static void PyGILState_Cleanup(void *GIL) { } #define PYTHON_OPEN \ - if (PyGILState_Ensure) { \ + if (PyGILState_Ensure) \ + { \ PyThreadState *GIL = PyGILState_Ensure(); \ DBG("PyGILState_Ensured(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ (uintptr_t)pthread_self()); \ pthread_cleanup_push(PyGILState_Cleanup, (void *)GIL); //" -#define PYTHON_CLOSE \ - PyGILState_Release(GIL); \ - DBG("PyGILState_Released(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ - (uintptr_t)pthread_self()); \ - pthread_cleanup_pop(0); \ - DEBUG_GIL_CHECK; \ +#define PYTHON_CLOSE \ + PyGILState_Release(GIL); \ + DBG("PyGILState_Released(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ + (uintptr_t)pthread_self()); \ + pthread_cleanup_pop(0); \ + DEBUG_GIL_CHECK; \ } //" -static void importMDSplus() { // used in once +static void importMDSplus() +{ // used in once initialize(); - PYTHON_OPEN { + PYTHON_OPEN + { PyObject *MDSplus = PyImport_ImportModule("MDSplus"); - if (MDSplus) { + if (MDSplus) + { pointerToObject = PyObject_GetAttrString(MDSplus, "pointerToObject"); - if (!pointerToObject) { + if (!pointerToObject) + { fprintf(stderr, "Error loading function MDSplus.pointerToObject(); no " "argument support\n"); if (PyErr_Occurred()) PyErr_Print(); } makeData = PyObject_GetAttrString(MDSplus, "makeData"); - if (!makeData) { + if (!makeData) + { fprintf(stderr, "Error loading function MDSplus.makeData(); no return " "value support\n"); if (PyErr_Occurred()) PyErr_Print(); } MDSplusException = PyObject_GetAttrString(MDSplus, "MDSplusException"); - if (!MDSplusException) { + if (!MDSplusException) + { fprintf(stderr, "Error loading class MDSplus.MDSplusException; only " "limited error handling\n"); if (PyErr_Occurred()) PyErr_Print(); } Py_DecRef(MDSplus); // release file lock - } else { + } + else + { fprintf(stderr, "Error loading package MDSplus, check your PYTHONPATH; " "very limited functionality\n"); if (PyErr_Occurred()) @@ -295,24 +320,28 @@ static void importMDSplus() { // used in once PYTHON_CLOSE; } -static inline void importMDSplus_once() { +static inline void importMDSplus_once() +{ static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, &importMDSplus); } static inline PyObject *args_to_tuple(const int nargs, - const mdsdsc_t *const *const args) { + const mdsdsc_t *const *const args) +{ /* Convert descriptor argument list to a tuple of python objects. */ if (!pointerToObject) return PyTuple_New(0); // no arguments PyObject *ans = PyTuple_New(nargs); int idx; - for (idx = 0; idx < nargs; idx++) { + for (idx = 0; idx < nargs; idx++) + { PyObject *arg = PyObject_CallFunction( pointerToObject, (sizeof(void *) == 8) ? "L" : "l", args[idx]); if (arg) PyTuple_SetItem(ans, idx, arg); - else { + else + { fprintf(stderr, "Error getting Object from arg %d\n", idx); if (PyErr_Occurred()) PyErr_Print(); @@ -323,11 +352,13 @@ static inline PyObject *args_to_tuple(const int nargs, } static inline void get_answer(const PyObject *const value, - mdsdsc_xd_t *const outptr) { + mdsdsc_xd_t *const outptr) +{ if (!makeData) return; // no return value PyObject *dataObj = PyObject_CallFunctionObjArgs(makeData, value, NULL); - if (!dataObj) { + if (!dataObj) + { printf("Error converting answer to MDSplus datatype\n"); if (PyErr_Occurred()) PyErr_Print(); @@ -335,7 +366,8 @@ static inline void get_answer(const PyObject *const value, } PyObject *descr = PyObject_GetAttrString(dataObj, "descriptor"); Py_DecRef(dataObj); - if (!descr) { + if (!descr) + { printf("Error getting descriptor\n"); if (PyErr_Occurred()) PyErr_Print(); @@ -345,7 +377,8 @@ static inline void get_answer(const PyObject *const value, if (descr != Py_None) descrPtr = PyObject_GetAttrString(descr, "addressof"); Py_DecRef(descr); - if (!descrPtr) { + if (!descrPtr) + { printf("Error getting address of descriptor\n"); if (PyErr_Occurred()) PyErr_Print(); @@ -357,21 +390,25 @@ static inline void get_answer(const PyObject *const value, static inline int is_callable(const PyObject *const fun, const char *const funname, - const char *const fullpath) { - if (!fun) { + const char *const fullpath) +{ + if (!fun) + { printf("Error finding function called '%s' in module %s\n", funname, funname); if (PyErr_Occurred()) PyErr_Print(); return FALSE; } - if (!PyCallable_Check(fun)) { + if (!PyCallable_Check(fun)) + { printf("Error, item called '%s' in '%s' is not callable\n", funname, fullpath); Py_DecRef(fun); return FALSE; } - if ((strcasecmp("py", funname) == 0) && (MdsSandboxEnabled() == 1)) { + if ((strcasecmp("py", funname) == 0) && (MdsSandboxEnabled() == 1)) + { printf("Error, item called '%s' in '%s' is not callable. The py() function " "is currently disabled\n", funname, fullpath); @@ -383,16 +420,19 @@ static inline int is_callable(const PyObject *const fun, } #ifdef USE_EXECFILE -static inline PyObject *get_exec_file(const PyObject *const __main__) { +static inline PyObject *get_exec_file(const PyObject *const __main__) +{ PyObject *execfile = PyObject_GetAttrString(__main__, "execfile"); - if (!execfile) { // not defined yet, so we define it + if (!execfile) + { // not defined yet, so we define it PyErr_Clear(); char def[] = "import __main__\ndef execfile(filename):\n with " "open(filename,'r') as f:\n " "exec(compile(f.read(),filename,'exec'),__main__.__dict__,__" "main__.__dict__)\0"; int flags = 0; - if (PyRun_SimpleStringFlags(def, &flags)) { + if (PyRun_SimpleStringFlags(def, &flags)) + { fprintf(stderr, "Error defining execfile\n"); if (PyErr_Occurred()) PyErr_Print(); @@ -406,11 +446,13 @@ static inline PyObject *get_exec_file(const PyObject *const __main__) { static inline void add__file__fun(const PyObject *const tdi_functions, const char *const filename, - const PyObject *const __file__) { + const PyObject *const __file__) +{ char *__file__fun = malloc(strlen(filename) + 9); strcpy(__file__fun, "__file__"); strcat(__file__fun, filename); - if (PyModule_AddObject(tdi_functions, __file__fun, __file__)) { + if (PyModule_AddObject(tdi_functions, __file__fun, __file__)) + { fprintf(stderr, "Failed putting %s\n", __file__fun); if (PyErr_Occurred()) PyErr_Print(); @@ -419,10 +461,12 @@ static inline void add__file__fun(const PyObject *const tdi_functions, } static inline int load_python_fun(const char *const fullpath, - char **const funname) { + char **const funname) +{ // get __main__ PyObject *__main__ = PyImport_AddModule("__main__"); - if (!__main__) { + if (!__main__) + { fprintf(stderr, "Error getting __main__ module'\n"); if (PyErr_Occurred()) PyErr_Print(); @@ -436,7 +480,8 @@ static inline int load_python_fun(const char *const fullpath, // add __file__= to globals if (PyModule_AddObject( __main__, "__file__", - PyString_FromString(fullpath))) { // no need to deref PyString + PyString_FromString(fullpath))) + { // no need to deref PyString fprintf(stderr, "Failed adding __file__='%s'\n", fullpath); if (PyErr_Occurred()) PyErr_Print(); @@ -446,7 +491,8 @@ static inline int load_python_fun(const char *const fullpath, PyObject *ans = PyObject_CallFunctionObjArgs(execfile, __file__, NULL); Py_DecRef(execfile); Py_DecRef(ans); - if (!ans) { + if (!ans) + { #else int err; INIT_AND_FCLOSE_ON_EXIT(fp); @@ -454,7 +500,8 @@ static inline int load_python_fun(const char *const fullpath, fp = _Py_fopen_obj(__file__, "r"); else fp = fopen(fullpath, "r"); - if (!fp) { + if (!fp) + { fprintf(stderr, "Error opening file '%s'\n", fullpath); Py_DecRef(__file__); return MDSplusERROR; @@ -462,7 +509,8 @@ static inline int load_python_fun(const char *const fullpath, int flags = 0; err = PyRun_SimpleFileExFlags(fp, fullpath, 1, &flags); FCLOSE_CANCEL(fp); - if (err) { + if (err) + { #endif fprintf(stderr, "Error compiling file '%s'\n", fullpath); if (PyErr_Occurred()) @@ -481,7 +529,8 @@ static inline int load_python_fun(const char *const fullpath, *funname = memcpy(malloc(mlen + 1), p, mlen); funname[0][mlen] = '\0'; PyObject *pyFunction = PyObject_GetAttrString(__main__, *funname); - if (!is_callable(pyFunction, *funname, fullpath)) { + if (!is_callable(pyFunction, *funname, fullpath)) + { free(*funname); *funname = NULL; Py_DecRef(__file__); @@ -501,9 +550,11 @@ static inline int load_python_fun(const char *const fullpath, static inline int call_python_fun(const char *const filename, const int nargs, const mdsdsc_t *const *const args, - mdsdsc_xd_t *const out_ptr) { + mdsdsc_xd_t *const out_ptr) +{ PyObject *tdi_functions = PyImport_AddModule("tdi_functions"); - if (tdi_functions) { + if (tdi_functions) + { PyObject *__main__ = PyImport_AddModule("__main__"); char *__file__fun = malloc(strlen(filename) + 9); strcpy(__file__fun, "__file__"); @@ -512,19 +563,22 @@ static inline int call_python_fun(const char *const filename, const int nargs, free(__file__fun); if (__file__) PyModule_AddObject(__main__, "__file__", __file__); - else { // silently fail and set __file__ to None + else + { // silently fail and set __file__ to None PyModule_AddObject(__main__, "__file__", Py_None); if (PyErr_Occurred()) PyErr_Clear(); } - } else + } + else fprintf(stderr, "Failed getting module tdi_functions\n"); if (PyErr_Occurred()) PyErr_Print(); if ((strcasecmp("py", filename) == 0) && (MdsSandboxEnabled() == 1)) return MDSplusSANDBOX; PyObject *pyFunction = PyObject_GetAttrString(tdi_functions, filename); - if (!pyFunction) { + if (!pyFunction) + { if (PyErr_Occurred()) PyErr_Print(); return MDSplusERROR; @@ -533,36 +587,42 @@ static inline int call_python_fun(const char *const filename, const int nargs, PyObject *ans = PyObject_CallObject(pyFunction, pyArgs); Py_DecRef(pyFunction); Py_DecRef(pyArgs); - if (ans) { + if (ans) + { get_answer(ans, out_ptr); Py_DecRef(ans); return MDSplusSUCCESS; } PyObject *exc = PyErr_Occurred(); - if (exc) { + if (exc) + { PyErr_Print(); - if (MDSplusException && PyObject_IsSubclass(exc, MDSplusException)) { + if (MDSplusException && PyObject_IsSubclass(exc, MDSplusException)) + { PyObject *status_obj = PyObject_GetAttrString(exc, "status"); int status = (int)PyLong_AsLong(status_obj); Py_DecRef(status_obj); - if - STATUS_NOT_OK { - char *fac_out = NULL, *msgnam_out = NULL, *text_out = NULL; - const char *f = "WSEIF???"; - MdsGetStdMsg(status, (const char **)&fac_out, - (const char **)&msgnam_out, (const char **)&text_out); - printf("%%%s-%c-%s: %s\n", fac_out, f[status & 7], msgnam_out, - text_out); - } + if (STATUS_NOT_OK) + { + char *fac_out = NULL, *msgnam_out = NULL, *text_out = NULL; + const char *f = "WSEIF???"; + MdsGetStdMsg(status, (const char **)&fac_out, + (const char **)&msgnam_out, (const char **)&text_out); + printf("%%%s-%c-%s: %s\n", fac_out, f[status & 7], msgnam_out, + text_out); + } return status; - } else { + } + else + { fprintf(stderr, "Error calling fun in %s\n", filename); return MDSplusERROR; } } return MDSplusSUCCESS; } -int tdi_load_python_fun(const char *const filepath, char **const funname) { +int tdi_load_python_fun(const char *const filepath, char **const funname) +{ int status; importMDSplus_once(); PYTHON_OPEN; @@ -573,7 +633,8 @@ int tdi_load_python_fun(const char *const filepath, char **const funname) { int tdi_call_python_fun(const char *const filename, const int nargs, const mdsdsc_t *const *const args, - mdsdsc_xd_t *const out_ptr) { + mdsdsc_xd_t *const out_ptr) +{ int status; importMDSplus_once(); PYTHON_OPEN; diff --git a/tdishr/TdiFaultHandler.c b/tdishr/TdiFaultHandler.c index 74051be668..9ada79f7f3 100644 --- a/tdishr/TdiFaultHandler.c +++ b/tdishr/TdiFaultHandler.c @@ -27,7 +27,8 @@ int TdiFaultHandler() { return 1; } int TdiFaultHandlerNoFixup() { return 1; } -int TdiFaultClear() { +int TdiFaultClear() +{ TdiFault = 0; return 1; } diff --git a/tdishr/TdiGetArgs.c b/tdishr/TdiGetArgs.c index b8097ead18..8fbfb8e6e4 100644 --- a/tdishr/TdiGetArgs.c +++ b/tdishr/TdiGetArgs.c @@ -55,7 +55,8 @@ extern int Tdi2Cmplx(); int TdiGetSignalUnitsData(struct descriptor *in_ptr, struct descriptor_xd *signal_ptr, struct descriptor_xd *units_ptr, - struct descriptor_xd *data_ptr) { + struct descriptor_xd *data_ptr) +{ static const unsigned char omitsu[] = {DTYPE_SIGNAL, DTYPE_WITH_UNITS, 0}; static const unsigned char omits[] = {DTYPE_SIGNAL, 0}; static const unsigned char omitu[] = {DTYPE_WITH_UNITS, 0}; @@ -64,70 +65,69 @@ int TdiGetSignalUnitsData(struct descriptor *in_ptr, TDITHREADSTATIC_INIT; MdsFree1Dx(signal_ptr, NULL); status = tdi_get_data(omitsu, in_ptr, data_ptr); - if - STATUS_OK - switch (data_ptr->pointer->dtype) { - case DTYPE_SIGNAL: - *signal_ptr = *data_ptr; - *data_ptr = EMPTY_XD; - keep = TDI_SELF_PTR; - TDI_SELF_PTR = (struct descriptor_xd *)signal_ptr->pointer; - status = tdi_get_data( - omitu, ((struct descriptor_signal *)signal_ptr->pointer)->data, - data_ptr); - if - STATUS_OK - switch (data_ptr->pointer->dtype) { + if (STATUS_OK) + switch (data_ptr->pointer->dtype) + { + case DTYPE_SIGNAL: + *signal_ptr = *data_ptr; + *data_ptr = EMPTY_XD; + keep = TDI_SELF_PTR; + TDI_SELF_PTR = (struct descriptor_xd *)signal_ptr->pointer; + status = tdi_get_data( + omitu, ((struct descriptor_signal *)signal_ptr->pointer)->data, + data_ptr); + if (STATUS_OK) + switch (data_ptr->pointer->dtype) + { + case DTYPE_WITH_UNITS: + tmp = *data_ptr; + *data_ptr = EMPTY_XD; + status = TdiData(((struct descriptor_with_units *)tmp.pointer)->units, + units_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiData(((struct descriptor_with_units *)tmp.pointer)->data, + data_ptr MDS_END_ARG); + MdsFree1Dx(&tmp, NULL); + break; + default: + MdsFree1Dx(units_ptr, NULL); + break; + } + TDI_SELF_PTR = keep; + break; case DTYPE_WITH_UNITS: tmp = *data_ptr; *data_ptr = EMPTY_XD; - status = TdiData(((struct descriptor_with_units *)tmp.pointer)->units, - units_ptr MDS_END_ARG); - if - STATUS_OK - status = TdiData(((struct descriptor_with_units *)tmp.pointer)->data, - data_ptr MDS_END_ARG); + status = TdiUnits(tmp.pointer, units_ptr MDS_END_ARG); + if (STATUS_OK) + status = tdi_get_data(omits, tmp.pointer, data_ptr); + if (STATUS_OK) + switch (data_ptr->pointer->dtype) + { + case DTYPE_SIGNAL: + *signal_ptr = *data_ptr; + *data_ptr = EMPTY_XD; + status = TdiData(signal_ptr->pointer, data_ptr MDS_END_ARG); + break; + default: + break; + } MdsFree1Dx(&tmp, NULL); break; default: MdsFree1Dx(units_ptr, NULL); break; } - TDI_SELF_PTR = keep; - break; - case DTYPE_WITH_UNITS: - tmp = *data_ptr; - *data_ptr = EMPTY_XD; - status = TdiUnits(tmp.pointer, units_ptr MDS_END_ARG); - if - STATUS_OK - status = tdi_get_data(omits, tmp.pointer, data_ptr); - if - STATUS_OK - switch (data_ptr->pointer->dtype) { - case DTYPE_SIGNAL: - *signal_ptr = *data_ptr; - *data_ptr = EMPTY_XD; - status = TdiData(signal_ptr->pointer, data_ptr MDS_END_ARG); - break; - default: - break; - } - MdsFree1Dx(&tmp, NULL); - break; - default: - MdsFree1Dx(units_ptr, NULL); - break; - } return status; } -void UseNativeFloat(struct TdiCatStruct *cat) { +void UseNativeFloat(struct TdiCatStruct *cat) +{ dtype_t type; tdicat_t tcat; -#define CHECK(TYPE) \ - tcat = TdiREF_CAT[type = TYPE].cat; \ - if ((tcat & ~(TdiCAT_WIDE_EXP)) == (cat->out_cat & ~(TdiCAT_WIDE_EXP))) \ +#define CHECK(TYPE) \ + tcat = TdiREF_CAT[type = TYPE].cat; \ + if ((tcat & ~(TdiCAT_WIDE_EXP)) == (cat->out_cat & ~(TdiCAT_WIDE_EXP))) \ goto found; CHECK(DTYPE_NATIVE_FLOAT); CHECK(DTYPE_NATIVE_DOUBLE); @@ -143,7 +143,8 @@ found:; int TdiGetArgs(opcode_t opcode, int narg, struct descriptor *list[], struct descriptor_xd sig[], struct descriptor_xd uni[], - struct descriptor_xd dat[], struct TdiCatStruct cats[]) { + struct descriptor_xd dat[], struct TdiCatStruct cats[]) +{ INIT_STATUS; struct TdiCatStruct *cptr; struct TdiFunctionStruct *fun_ptr = @@ -157,11 +158,11 @@ int TdiGetArgs(opcode_t opcode, int narg, struct descriptor *list[], /*************************** Get signal, units, and data. ***************************/ - for (j = 0; j < narg; ++j) { + for (j = 0; j < narg; ++j) + { sig[j] = uni[j] = dat[j] = EMPTY_XD; - if - STATUS_OK - status = TdiGetSignalUnitsData(list[j], &sig[j], &uni[j], &dat[j]); + if (STATUS_OK) + status = TdiGetSignalUnitsData(list[j], &sig[j], &uni[j], &dat[j]); } /****************************** @@ -169,50 +170,55 @@ int TdiGetArgs(opcode_t opcode, int narg, struct descriptor *list[], Adjust out in f2 routine. Make in into out in CVT_ARGS. ******************************/ - if - STATUS_OK - for (nd = 0, nc = 0, j = 0; j < narg; ++j) { - struct descriptor *dat_ptr = dat[j].pointer; + if (STATUS_OK) + for (nd = 0, nc = 0, j = 0; j < narg; ++j) + { + struct descriptor *dat_ptr = dat[j].pointer; - cptr = &cats[j]; - cptr->out_dtype = cptr->in_dtype = jd = dat_ptr->dtype; - if (jd > nd && (nd = jd) >= TdiCAT_MAX) { - status = TdiINVDTYDSC; - break; + cptr = &cats[j]; + cptr->out_dtype = cptr->in_dtype = jd = dat_ptr->dtype; + if (jd > nd && (nd = jd) >= TdiCAT_MAX) + { + status = TdiINVDTYDSC; + break; + } + cptr->out_cat = + (unsigned short)(((cptr->in_cat = TdiREF_CAT[jd].cat) | i1) & i2); + if (jd != DTYPE_MISSING) + nc |= cptr->out_cat; + if ((cptr->digits = TdiREF_CAT[jd].digits) == 0) + cptr->digits = dat_ptr->length; + } + if (STATUS_OK) + for (j = 0; j < narg; j++) + { + if (fun_ptr->i1 == fun_ptr->i2) + { + cats[j].out_dtype = fun_ptr->i2; + cats[j].out_cat = i2; + } + else if (cats[j].out_cat & 0x400 && use_native) + UseNativeFloat(&cats[j]); } - cptr->out_cat = - (unsigned short)(((cptr->in_cat = TdiREF_CAT[jd].cat) | i1) & i2); - if (jd != DTYPE_MISSING) - nc |= cptr->out_cat; - if ((cptr->digits = TdiREF_CAT[jd].digits) == 0) - cptr->digits = dat_ptr->length; - } - if - STATUS_OK - for (j = 0; j < narg; j++) { - if (fun_ptr->i1 == fun_ptr->i2) { - cats[j].out_dtype = fun_ptr->i2; - cats[j].out_cat = i2; - } else if (cats[j].out_cat & 0x400 && use_native) - UseNativeFloat(&cats[j]); - } /*********************************************** Output cat and dtype are guesses, checked later. ***********************************************/ - if - STATUS_OK { - cptr = &cats[narg]; - cptr->in_dtype = nd; - cptr->out_dtype = nd; - cptr->in_cat = TdiREF_CAT[nd].cat; - cptr->out_cat = (unsigned short)((nc | o1) & o2); - cptr->digits = TdiREF_CAT[nd].digits; - if (fun_ptr->o1 == fun_ptr->o2) { - cptr->out_dtype = cptr->in_dtype = fun_ptr->o2; - cptr->out_cat = cptr->in_cat = o2; - } else if (cptr->out_cat & 0x400 && use_native) - UseNativeFloat(cptr); + if (STATUS_OK) + { + cptr = &cats[narg]; + cptr->in_dtype = nd; + cptr->out_dtype = nd; + cptr->in_cat = TdiREF_CAT[nd].cat; + cptr->out_cat = (unsigned short)((nc | o1) & o2); + cptr->digits = TdiREF_CAT[nd].digits; + if (fun_ptr->o1 == fun_ptr->o2) + { + cptr->out_dtype = cptr->in_dtype = fun_ptr->o2; + cptr->out_cat = cptr->in_cat = o2; } + else if (cptr->out_cat & 0x400 && use_native) + UseNativeFloat(cptr); + } return status; } diff --git a/tdishr/TdiGetData.c b/tdishr/TdiGetData.c index 8a5c0dd002..1d7a63ca01 100644 --- a/tdishr/TdiGetData.c +++ b/tdishr/TdiGetData.c @@ -70,15 +70,19 @@ extern int TdiData(); extern int TdiUnits(); extern int Tdi2Add(); -static void fixup_dollar_nodes(int nid, mdsdsc_t *out_ptr) { - if (out_ptr) { - switch (out_ptr->class) { +static void fixup_dollar_nodes(int nid, mdsdsc_t *out_ptr) +{ + if (out_ptr) + { + switch (out_ptr->class) + { default: break; case CLASS_S: case CLASS_D: if ((out_ptr->dtype == DTYPE_IDENT) && (out_ptr->length == 5) && - (strncasecmp((const char *)out_ptr->pointer, "$node", 5) == 0)) { + (strncasecmp((const char *)out_ptr->pointer, "$node", 5) == 0)) + { out_ptr->dtype = DTYPE_NID; out_ptr->length = 4; *(int *)out_ptr->pointer = nid; @@ -88,7 +92,8 @@ static void fixup_dollar_nodes(int nid, mdsdsc_t *out_ptr) { case CLASS_XD: fixup_dollar_nodes(nid, (mdsdsc_t *)out_ptr->pointer); break; - case CLASS_R: { + case CLASS_R: + { mdsdsc_r_t *ptr = (mdsdsc_r_t *)out_ptr; int i; for (i = 0; i < ptr->ndesc; i++) @@ -99,7 +104,8 @@ static void fixup_dollar_nodes(int nid, mdsdsc_t *out_ptr) { } } -int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) { +int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; array_bounds *pout = (array_bounds *)out_ptr->pointer; array_bounds arr; @@ -107,44 +113,52 @@ int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) { if (pout == 0) return 1; - switch (pout->class) { + switch (pout->class) + { case CLASS_A: case CLASS_CA: dimct = in_ptr->dimct; if (dimct > MAX_DIMS) return TdiNDIM_OVER; in_size = sizeof(struct descriptor_a); - if (in_ptr->aflags.coeff) { + if (in_ptr->aflags.coeff) + { in_size += sizeof(void *) + dimct * sizeof(int); if (in_ptr->aflags.bounds) in_size += dimct * sizeof(int); } dimct = pout->dimct; memcpy(&arr, in_ptr, in_size); - if (in_ptr->class == CLASS_APD) { + if (in_ptr->class == CLASS_APD) + { arr.length = pout->length; arr.dtype = pout->dtype; } arr.class = pout->class; - if (in_ptr->aflags.coeff) { + if (in_ptr->aflags.coeff) + { /******************************* For CA it is a relative pointer. *******************************/ - if (in_ptr->class == CLASS_CA) { + if (in_ptr->class == CLASS_CA) + { arr.a0 = pout->pointer + *(int *)&arr.a0; - } else + } + else arr.a0 = pout->pointer + (arr.a0 - arr.pointer); } arr.pointer = pout->pointer; out_size = sizeof(struct descriptor_a); - if (pout->aflags.coeff) { + if (pout->aflags.coeff) + { out_size += sizeof(void *) + dimct * sizeof(int); if (pout->aflags.bounds) out_size += dimct * sizeof(int); } if (in_size <= out_size && pout->class == CLASS_A) memcpy(pout, &arr, in_size); - else { + else + { mdsdsc_xd_t tmp = *out_ptr; *out_ptr = EMPTY_XD; status = MdsCopyDxXd((mdsdsc_t *)&arr, out_ptr); @@ -153,14 +167,17 @@ int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) { break; case CLASS_S: case CLASS_D: - if (in_ptr->class == CLASS_CA) { + if (in_ptr->class == CLASS_CA) + { DESCRIPTOR_A(simple, 0, 0, 0, 0); simple.length = in_ptr->length; simple.dtype = in_ptr->dtype; simple.pointer = in_ptr->pointer; simple.arsize = in_ptr->length; status = TdiImpose((mdsdsc_a_t *)&simple, out_ptr); - } else { + } + else + { DESCRIPTOR_A(simple, 0, 0, 0, 0); simple.length = pout->length; simple.dtype = pout->dtype; @@ -182,7 +199,8 @@ int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) { static const mdsdsc_t missing_dsc = {0, DTYPE_MISSING, CLASS_S, 0}; static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, - mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) { + mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) +{ int nid, *pnid; dtype_t dtype = 0; mds_signal_t *keep; @@ -190,39 +208,45 @@ static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, mdsdsc_r_t *pin = (mdsdsc_r_t *)their_ptr; INIT_STATUS; TDI_GETDATA_REC++; - if (TDI_GETDATA_REC > 1800) { + if (TDI_GETDATA_REC > 1800) + { status = TdiRECURSIVE; goto end; } - while (pin && (dtype = pin->dtype) == DTYPE_DSC) { + while (pin && (dtype = pin->dtype) == DTYPE_DSC) + { pin = (mdsdsc_r_t *)pin->pointer; TDI_GETDATA_REC++; - if (TDI_GETDATA_REC > 1800) { + if (TDI_GETDATA_REC > 1800) + { status = TdiRECURSIVE; goto end; } } if (!pin) status = MdsCopyDxXd(&missing_dsc, &hold); - else { + else + { int i; for (i = 0; omits[i] && omits[i] != dtype; i++) ; if (omits[i]) status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); else - switch (pin->class) { + switch (pin->class) + { case CLASS_CA: - if (pin->pointer) { + if (pin->pointer) + { status = get_data(omits, (mdsdsc_t *)pin->pointer, &hold, TDITHREADSTATIC_VAR); /********************* Why is this needed????????????? * *************************************/ - if - STATUS_OK - status = TdiImpose((mdsdsc_a_t *)pin, &hold); + if (STATUS_OK) + status = TdiImpose((mdsdsc_a_t *)pin, &hold); /***************************************************************************************/ - } else + } + else status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); break; case CLASS_APD: @@ -231,45 +255,48 @@ static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, case CLASS_S: case CLASS_D: case CLASS_A: - switch (dtype) { + switch (dtype) + { /*********************** Evaluate on these types. ***********************/ case DTYPE_IDENT: status = tdi_get_ident(pin, &hold); redo: - if - STATUS_OK - status = - get_data(omits, (mdsdsc_t *)&hold, &hold, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = + get_data(omits, (mdsdsc_t *)&hold, &hold, TDITHREADSTATIC_VAR); break; case DTYPE_NID: pnid = (int *)pin->pointer; status = TdiGetRecord(*pnid, &hold); goto redo; - case DTYPE_PATH: { + case DTYPE_PATH: + { char *path = MdsDescrToCstring((mdsdsc_t *)pin); status = TreeFindNode(path, &nid); MdsFree(path); - if - STATUS_OK - status = TdiGetRecord(nid, &hold); + if (STATUS_OK) + status = TdiGetRecord(nid, &hold); } goto redo; /************************************** VMS types come here. Renames their XD. *************************************/ default: - if (their_ptr->class == CLASS_XD) { + if (their_ptr->class == CLASS_XD) + { hold = *(mdsdsc_xd_t *)their_ptr; *(mdsdsc_xd_t *)their_ptr = EMPTY_XD; - } else + } + else status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); break; } break; case CLASS_R: - switch (dtype) { + switch (dtype) + { case DTYPE_FUNCTION: status = TdiIntrinsic(*(opcode_t *)pin->pointer, pin->ndesc, pin->dscptrs, &hold); @@ -298,20 +325,22 @@ static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, /*************** Windowless axis. ***************/ - case DTYPE_SLOPE: { + case DTYPE_SLOPE: + { int seg; EMPTYXD(times); - for (seg = 0; (status & 1) && (seg < pin->ndesc / 3); seg++) { + for (seg = 0; (status & 1) && (seg < pin->ndesc / 3); seg++) + { mdsdsc_t *args[] = {*(pin->dscptrs + (seg * 3 + 1)), *(pin->dscptrs + (seg * 3 + 2)), *(pin->dscptrs + (seg * 3))}; status = TdiIntrinsic(OPC_DTYPE_RANGE, 3, &args, ×); - if - STATUS_OK { - args[0] = (mdsdsc_t *)&hold; - args[1] = (mdsdsc_t *)× - status = TdiIntrinsic(OPC_VECTOR, 2, &args, &hold); - } + if (STATUS_OK) + { + args[0] = (mdsdsc_t *)&hold; + args[1] = (mdsdsc_t *)× + status = TdiIntrinsic(OPC_VECTOR, 2, &args, &hold); + } } goto redo; } @@ -351,16 +380,17 @@ static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, Watch out for input same as output. **********************************/ MdsFree1Dx(out_ptr, NULL); - if - STATUS_OK - *out_ptr = hold; - else MdsFree1Dx(&hold, NULL); + if (STATUS_OK) + *out_ptr = hold; + else + MdsFree1Dx(&hold, NULL); end:; TDI_GETDATA_REC = 0; return status; } int tdi_get_data(const dtype_t omits[], mdsdsc_t *their_ptr, - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; return get_data(omits, their_ptr, out_ptr, TDITHREADSTATIC_VAR); } @@ -370,13 +400,15 @@ int tdi_get_data(const dtype_t omits[], mdsdsc_t *their_ptr, Useful internal and external function. C only: status = TdiGetFloat(&in_dsc, &float) */ -extern EXPORT int TdiGetFloat(mdsdsc_t *in_ptr, float *val_ptr) { +extern EXPORT int TdiGetFloat(mdsdsc_t *in_ptr, float *val_ptr) +{ INIT_STATUS; if (in_ptr == 0) *val_ptr = (float)0.0; else if (in_ptr->dtype < 160 && in_ptr->dtype != DTYPE_DSC) - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_A: if (((mdsdsc_a_t *)in_ptr)->arsize != in_ptr->length) return TdiNOT_NUMBER; @@ -386,7 +418,8 @@ extern EXPORT int TdiGetFloat(mdsdsc_t *in_ptr, float *val_ptr) { MDS_ATTR_FALLTHROUGH case CLASS_S: case CLASS_D: - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: *val_ptr = (float)*(unsigned char *)in_ptr->pointer; break; @@ -405,32 +438,35 @@ extern EXPORT int TdiGetFloat(mdsdsc_t *in_ptr, float *val_ptr) { case DTYPE_L: *val_ptr = (float)*(int *)in_ptr->pointer; break; - default: { + default: + { mdsdsc_t val_dsc = {sizeof(float), DTYPE_NATIVE_FLOAT, CLASS_S, 0}; val_dsc.pointer = (char *)val_ptr; status = TdiConvert(in_ptr, &val_dsc MDS_END_ARG); - } break; + } + break; } break; default: status = TdiINVCLADSC; break; } - else { + else + { mdsdsc_xd_t tmp = EMPTY_XD; status = TdiData(in_ptr, &tmp MDS_END_ARG); - if - STATUS_OK - switch (tmp.pointer->class) { - case CLASS_S: - case CLASS_D: - case CLASS_A: - status = TdiGetFloat(tmp.pointer, val_ptr); - break; - default: - status = TdiINVCLADSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->class) + { + case CLASS_S: + case CLASS_D: + case CLASS_A: + status = TdiGetFloat(tmp.pointer, val_ptr); + break; + default: + status = TdiINVCLADSC; + break; + } MdsFree1Dx(&tmp, NULL); } return status; @@ -441,13 +477,15 @@ extern EXPORT int TdiGetFloat(mdsdsc_t *in_ptr, float *val_ptr) { Useful internal and external function. C only: status = TdiGetLong(&in_dsc, &long) */ -extern EXPORT int TdiGetLong(mdsdsc_t *in_ptr, int *val_ptr) { +extern EXPORT int TdiGetLong(mdsdsc_t *in_ptr, int *val_ptr) +{ INIT_STATUS; if (in_ptr == 0) *val_ptr = 0; else if (in_ptr->dtype < 160 && in_ptr->dtype != DTYPE_DSC) - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_A: if (((mdsdsc_a_t *)in_ptr)->arsize != in_ptr->length) return TdiNOT_NUMBER; @@ -457,7 +495,8 @@ extern EXPORT int TdiGetLong(mdsdsc_t *in_ptr, int *val_ptr) { MDS_ATTR_FALLTHROUGH case CLASS_S: case CLASS_D: - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { case DTYPE_BU: *val_ptr = (int)*(unsigned char *)in_ptr->pointer; break; @@ -474,32 +513,35 @@ extern EXPORT int TdiGetLong(mdsdsc_t *in_ptr, int *val_ptr) { case DTYPE_LU: *val_ptr = *(int *)in_ptr->pointer; break; - default: { + default: + { mdsdsc_t val_dsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; val_dsc.pointer = (char *)val_ptr; status = TdiConvert(in_ptr, &val_dsc MDS_END_ARG); - } break; + } + break; } break; default: status = TdiINVCLADSC; break; } - else { + else + { mdsdsc_xd_t tmp = EMPTY_XD; status = TdiData(in_ptr, &tmp MDS_END_ARG); - if - STATUS_OK - switch (tmp.pointer->class) { - case CLASS_S: - case CLASS_D: - case CLASS_A: - status = TdiGetLong(tmp.pointer, val_ptr); - break; - default: - status = TdiINVCLADSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->class) + { + case CLASS_S: + case CLASS_D: + case CLASS_A: + status = TdiGetLong(tmp.pointer, val_ptr); + break; + default: + status = TdiINVCLADSC; + break; + } MdsFree1Dx(&tmp, NULL); } return status; @@ -510,28 +552,32 @@ extern EXPORT int TdiGetLong(mdsdsc_t *in_ptr, int *val_ptr) { Useful internal and external function. C only: status = TdiGetNid(&in_dsc, &nid) */ -extern EXPORT int TdiGetNid(mdsdsc_t *in_ptr, int *nid_ptr) { +extern EXPORT int TdiGetNid(mdsdsc_t *in_ptr, int *nid_ptr) +{ mdsdsc_xd_t tmp = EMPTY_XD; dtype_t omits[] = {DTYPE_NID, DTYPE_PATH, 0}; int status = tdi_get_data(omits, in_ptr, &tmp); - if - STATUS_OK { - switch (tmp.pointer->dtype) { - case DTYPE_T: - case DTYPE_PATH: { - char *path = MdsDescrToCstring(tmp.pointer); - status = TreeFindNode(path, nid_ptr); - MdsFree(path); - } break; - case DTYPE_NID: - *nid_ptr = *(unsigned int *)tmp.pointer->pointer; - break; - default: - status = TdiINVDTYDSC; - break; - } - MdsFree1Dx(&tmp, NULL); + if (STATUS_OK) + { + switch (tmp.pointer->dtype) + { + case DTYPE_T: + case DTYPE_PATH: + { + char *path = MdsDescrToCstring(tmp.pointer); + status = TreeFindNode(path, nid_ptr); + MdsFree(path); + } + break; + case DTYPE_NID: + *nid_ptr = *(unsigned int *)tmp.pointer->pointer; + break; + default: + status = TdiINVDTYDSC; + break; } + MdsFree1Dx(&tmp, NULL); + } return status; } @@ -547,7 +593,8 @@ extern EXPORT int TdiGetNid(mdsdsc_t *in_ptr, int *nid_ptr) { */ int Tdi1This(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), - mdsdsc_t *list[] __attribute__((unused)), mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[] __attribute__((unused)), mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; if (TDI_SELF_PTR) return MdsCopyDxXd((mdsdsc_t *)(TDI_SELF_PTR), out_ptr); @@ -563,10 +610,12 @@ int Tdi1This(opcode_t opcode __attribute__((unused)), */ int Tdi1Value(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), - mdsdsc_t *list[] __attribute__((unused)), mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[] __attribute__((unused)), mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; if (TDI_SELF_PTR) - switch (TDI_SELF_PTR->dtype) { + switch (TDI_SELF_PTR->dtype) + { case DTYPE_SIGNAL: return MdsCopyDxXd(((mds_signal_t *)TDI_SELF_PTR)->raw, out_ptr); case DTYPE_PARAM: @@ -587,7 +636,8 @@ int Tdi1Value(opcode_t opcode __attribute__((unused)), static const dtype_t no_omits[] = {0}; int Tdi1Data(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ return tdi_get_data(no_omits, list[0], out_ptr); } @@ -600,55 +650,58 @@ int Tdi1Data(opcode_t opcode __attribute__((unused)), UNITS(other) " " (single blank to keep IDL happy) */ int Tdi1Units(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ mdsdsc_r_t *rptr; mdsdsc_xd_t tmp = EMPTY_XD, uni[2]; struct TdiCatStruct cats[3]; int j; static const DESCRIPTOR(blank_dsc, " "); - static const dtype_t omits[] = {DTYPE_DIMENSION, DTYPE_RANGE, - DTYPE_SLOPE, DTYPE_WINDOW, + static const dtype_t omits[] = {DTYPE_DIMENSION, DTYPE_RANGE, + DTYPE_SLOPE, DTYPE_WINDOW, DTYPE_WITH_UNITS, 0}; int status = tdi_get_data(omits, list[0], &tmp); rptr = (mdsdsc_r_t *)tmp.pointer; - if - STATUS_OK - switch (rptr->dtype) { - case DTYPE_DIMENSION: - status = TdiUnits(((mds_dimension_t *)rptr)->axis, out_ptr MDS_END_ARG); - break; - case DTYPE_RANGE: - case DTYPE_SLOPE: - uni[1] = uni[0] = EMPTY_XD; - for (j = rptr->ndesc; --j >= 0 && STATUS_OK;) { - if (rptr->dscptrs[j]) - status = TdiUnits(rptr->dscptrs[j], &uni[1] MDS_END_ARG); - if (uni[1].pointer && STATUS_OK) - status = Tdi2Add(narg, uni, 0, cats, 0); + if (STATUS_OK) + switch (rptr->dtype) + { + case DTYPE_DIMENSION: + status = TdiUnits(((mds_dimension_t *)rptr)->axis, out_ptr MDS_END_ARG); + break; + case DTYPE_RANGE: + case DTYPE_SLOPE: + uni[1] = uni[0] = EMPTY_XD; + for (j = rptr->ndesc; --j >= 0 && STATUS_OK;) + { + if (rptr->dscptrs[j]) + status = TdiUnits(rptr->dscptrs[j], &uni[1] MDS_END_ARG); + if (uni[1].pointer && STATUS_OK) + status = Tdi2Add(narg, uni, 0, cats, 0); + } + MdsFree1Dx(&uni[1], NULL); + if (uni[0].pointer) + { + MdsFree1Dx(out_ptr, NULL); + *out_ptr = uni[0]; + } + else if (STATUS_OK) + status = MdsCopyDxXd((mdsdsc_t *)&blank_dsc, out_ptr); + break; + case DTYPE_WINDOW: + status = TdiUnits(((struct descriptor_window *)rptr)->value_at_idx0, + out_ptr MDS_END_ARG); + break; + case DTYPE_WITH_UNITS: + status = TdiData(((struct descriptor_with_units *)rptr)->units, + out_ptr MDS_END_ARG); + break; + case DTYPE_WITH_ERROR: + status = TdiData(((mds_with_error_t *)rptr)->data, out_ptr MDS_END_ARG); + break; + default: + status = MdsCopyDxXd((mdsdsc_t *)&blank_dsc, out_ptr); + break; } - MdsFree1Dx(&uni[1], NULL); - if (uni[0].pointer) { - MdsFree1Dx(out_ptr, NULL); - *out_ptr = uni[0]; - } else if - STATUS_OK - status = MdsCopyDxXd((mdsdsc_t *)&blank_dsc, out_ptr); - break; - case DTYPE_WINDOW: - status = TdiUnits(((struct descriptor_window *)rptr)->value_at_idx0, - out_ptr MDS_END_ARG); - break; - case DTYPE_WITH_UNITS: - status = TdiData(((struct descriptor_with_units *)rptr)->units, - out_ptr MDS_END_ARG); - break; - case DTYPE_WITH_ERROR: - status = TdiData(((mds_with_error_t *)rptr)->data, out_ptr MDS_END_ARG); - break; - default: - status = MdsCopyDxXd((mdsdsc_t *)&blank_dsc, out_ptr); - break; - } MdsFree1Dx(&tmp, NULL); return status; } @@ -661,34 +714,39 @@ int Tdi1Units(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1DataWithUnits(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ static const dtype_t omits[] = {DTYPE_WITH_UNITS, 0}; DESCRIPTOR_WITH_UNITS(dwu, &missing_dsc, 0); mdsdsc_xd_t data = EMPTY_XD, units = EMPTY_XD; int status = tdi_get_data(omits, list[0], out_ptr); - if - STATUS_OK { - struct descriptor_with_units *pwu = - (struct descriptor_with_units *)out_ptr->pointer; - if (pwu) { - if (pwu->dtype == DTYPE_WITH_UNITS) { - status = TdiData(pwu->data, &data MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + struct descriptor_with_units *pwu = + (struct descriptor_with_units *)out_ptr->pointer; + if (pwu) + { + if (pwu->dtype == DTYPE_WITH_UNITS) + { + status = TdiData(pwu->data, &data MDS_END_ARG); + if (STATUS_OK) status = TdiData(pwu->units, &units MDS_END_ARG); - dwu.data = data.pointer; - dwu.units = units.pointer; - } else { - data = *out_ptr; - *out_ptr = EMPTY_XD; - dwu.data = (mdsdsc_t *)pwu; - } - status = MdsCopyDxXd((mdsdsc_t *)&dwu, out_ptr); - MdsFree1Dx(&data, NULL); - MdsFree1Dx(&units, NULL); - } else - status = MdsCopyDxXd((mdsdsc_t *)&dwu, out_ptr); + dwu.data = data.pointer; + dwu.units = units.pointer; + } + else + { + data = *out_ptr; + *out_ptr = EMPTY_XD; + dwu.data = (mdsdsc_t *)pwu; + } + status = MdsCopyDxXd((mdsdsc_t *)&dwu, out_ptr); + MdsFree1Dx(&data, NULL); + MdsFree1Dx(&units, NULL); } + else + status = MdsCopyDxXd((mdsdsc_t *)&dwu, out_ptr); + } return status; } @@ -701,7 +759,8 @@ int Tdi1DataWithUnits(opcode_t opcode __attribute__((unused)), */ int Tdi1Validation(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; mdsdsc_r_t *rptr; mdsdsc_xd_t *keep; @@ -709,31 +768,31 @@ int Tdi1Validation(opcode_t opcode __attribute__((unused)), int status = get_data(omits, list[0], out_ptr, TDITHREADSTATIC_VAR); rptr = (mdsdsc_r_t *)out_ptr->pointer; - if - STATUS_OK - switch (rptr->dtype) { - case DTYPE_PARAM: - /****************************************** + if (STATUS_OK) + switch (rptr->dtype) + { + case DTYPE_PARAM: + /****************************************** We must set up for reference to our $VALUE. ******************************************/ - keep = TDI_SELF_PTR; - TDI_SELF_PTR = (mdsdsc_xd_t *)rptr; - status = get_data(no_omits, ((mds_param_t *)rptr)->validation, out_ptr, - TDITHREADSTATIC_VAR); - TDI_SELF_PTR = keep; - break; - default: - status = TdiINVDTYDSC; - break; - } + keep = TDI_SELF_PTR; + TDI_SELF_PTR = (mdsdsc_xd_t *)rptr; + status = get_data(no_omits, ((mds_param_t *)rptr)->validation, out_ptr, + TDITHREADSTATIC_VAR); + TDI_SELF_PTR = keep; + break; + default: + status = TdiINVDTYDSC; + break; + } return status; } -EXPORT int TdiGetRecord(int nid, mdsdsc_xd_t *out) { +EXPORT int TdiGetRecord(int nid, mdsdsc_xd_t *out) +{ INIT_STATUS; status = TreeGetRecord(nid, (mdsdsc_xd_t *)out); - if - STATUS_OK - fixup_dollar_nodes(nid, (mdsdsc_t *)out); + if (STATUS_OK) + fixup_dollar_nodes(nid, (mdsdsc_t *)out); return status; } diff --git a/tdishr/TdiGetDbi.c b/tdishr/TdiGetDbi.c index 8b69464019..58a8a7f268 100644 --- a/tdishr/TdiGetDbi.c +++ b/tdishr/TdiGetDbi.c @@ -41,10 +41,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include static const DESCRIPTOR(coloncolon, "::"); -#define EOL \ - { 0, DbiEND_OF_LIST, 0, 0 } +#define EOL \ + { \ + 0, DbiEND_OF_LIST, 0, 0 \ + } -static const struct item { +static const struct item +{ char *item_name; char item_code; dtype_t item_dtype; @@ -69,7 +72,8 @@ extern int tdi_get_data(); extern int TdiGetLong(); extern int _TdiEvaluate(); -static int compare(struct descriptor *s1, struct item s2[1]) { +static int compare(struct descriptor *s1, struct item s2[1]) +{ int cmp, len1 = s1->length, len2 = strlen(s2[0].item_name); char c0; @@ -84,7 +88,8 @@ static int compare(struct descriptor *s1, struct item s2[1]) { ; else if (len1 > len2) cmp = (c0 = s1->pointer[len2]) != ' ' && c0 != '\t'; - else if (len1 < len2) { + else if (len1 < len2) + { if ((s2 != &table[0] && strncmp(s1->pointer, s2[-1].item_name, len1) == 0) || (s2 != &table[numtab - 1] && @@ -95,7 +100,8 @@ static int compare(struct descriptor *s1, struct item s2[1]) { } int Tdi1GetDbi(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_d string = {0, DTYPE_T, CLASS_D, 0}; struct descriptor_xd tmp = EMPTY_XD; @@ -107,17 +113,16 @@ int Tdi1GetDbi(opcode_t opcode __attribute__((unused)), int narg, String of item to find. **********************/ status = TdiData(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiUpcase(&tmp, &string MDS_END_ARG); - if - STATUS_OK { - key_ptr = - (struct item *)bsearch(&string, table, numtab, siztab, - (int (*)(const void *, const void *))compare); - if (key_ptr == 0) - status = TdiBAD_INDEX; - } + if (STATUS_OK) + status = TdiUpcase(&tmp, &string MDS_END_ARG); + if (STATUS_OK) + { + key_ptr = + (struct item *)bsearch(&string, table, numtab, siztab, + (int (*)(const void *, const void *))compare); + if (key_ptr == 0) + status = TdiBAD_INDEX; + } StrFree1Dx(&string); MdsFree1Dx(&tmp, NULL); /********************************** @@ -131,34 +136,38 @@ int Tdi1GetDbi(opcode_t opcode __attribute__((unused)), int narg, Get the item asked for. Fixed length or varying. ***********************/ - if - STATUS_OK { - lst[1].code = key_ptr->item_code; - if ((lst[1].buffer_length = key_ptr->item_length) != 0) { - status = MdsGet1DxS((length_t *)&lst[1].buffer_length, - &key_ptr->item_dtype, out_ptr); - if - STATUS_OK { - lst[1].pointer = (unsigned char *)out_ptr->pointer->pointer; - status = TreeGetDbi(lst); - } - } else { - lst[1].buffer_length = 0; - lst[1].pointer = NULL; + if (STATUS_OK) + { + lst[1].code = key_ptr->item_code; + if ((lst[1].buffer_length = key_ptr->item_length) != 0) + { + status = MdsGet1DxS((length_t *)&lst[1].buffer_length, + &key_ptr->item_dtype, out_ptr); + if (STATUS_OK) + { + lst[1].pointer = (unsigned char *)out_ptr->pointer->pointer; status = TreeGetDbi(lst); - if - STATUS_OK { - struct descriptor ans = {0, DTYPE_T, CLASS_S, 0}; - if (lst[1].pointer) { - ans.length = strlen((char *)lst[1].pointer); - ans.pointer = (char *)lst[1].pointer; - } - status = MdsCopyDxXd(&ans, out_ptr); - if (ans.pointer) - TreeFree(ans.pointer); - } } } + else + { + lst[1].buffer_length = 0; + lst[1].pointer = NULL; + status = TreeGetDbi(lst); + if (STATUS_OK) + { + struct descriptor ans = {0, DTYPE_T, CLASS_S, 0}; + if (lst[1].pointer) + { + ans.length = strlen((char *)lst[1].pointer); + ans.pointer = (char *)lst[1].pointer; + } + status = MdsCopyDxXd(&ans, out_ptr); + if (ans.pointer) + TreeFree(ans.pointer); + } + } + } return status; } @@ -169,9 +178,11 @@ int Tdi1GetDbi(opcode_t opcode __attribute__((unused)), int narg, */ static int fixup_nid(int *pin, /* NID pointer */ int arg __attribute__((unused)), - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ char *path = TreeGetPath(*pin); - if (path != NULL) { + if (path != NULL) + { unsigned short len = (unsigned short)strlen(path); StrCopyR((struct descriptor *)pout, &len, path); TreeFree(path); @@ -181,11 +192,13 @@ static int fixup_nid(int *pin, /* NID pointer */ } static int fixup_path(struct descriptor *pin, int arg __attribute__((unused)), - struct descriptor_d *pout) { + struct descriptor_d *pout) +{ char *pathin = MdsDescrToCstring(pin); char *path = TreeAbsPath(pathin); MdsFree(pathin); - if (path != NULL) { + if (path != NULL) + { unsigned short len = (unsigned short)strlen(path); StrCopyR((struct descriptor *)pout, &len, path); TreeFree(path); @@ -195,7 +208,8 @@ static int fixup_path(struct descriptor *pin, int arg __attribute__((unused)), } int Tdi1Using(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int nid, shot; unsigned short stat1; @@ -207,12 +221,15 @@ int Tdi1Using(opcode_t opcode __attribute__((unused)), int narg, Use current if omitted. Must get expt if shot. **********************/ - if (narg > 1 && STATUS_OK) { - if (list[1]) { + if (narg > 1 && STATUS_OK) + { + if (list[1]) + { struct descriptor_xd xd = EMPTY_XD; status = tdi_get_data(omits, list[1], &xd); if (STATUS_OK && xd.pointer) - switch (xd.pointer->dtype) { + switch (xd.pointer->dtype) + { case DTYPE_T: case DTYPE_PATH: status = StrCopyDx((struct descriptor *)&def, xd.pointer); @@ -223,74 +240,81 @@ int Tdi1Using(opcode_t opcode __attribute__((unused)), int narg, } MdsFree1Dx(&xd, NULL); } - if (!list[1] || def.length == 0) { + if (!list[1] || def.length == 0) + { DBI_ITM def_itm[] = {{0, DbiDEFAULT, 0, 0}, EOL}; status = TreeGetDbi(def_itm); - if (def_itm[0].pointer == NULL) { + if (def_itm[0].pointer == NULL) + { static const DESCRIPTOR(top, "\\TOP"); StrCopyDx((struct descriptor *)&def, (struct descriptor *)&top); status = MDSplusSUCCESS; - } else { + } + else + { unsigned short len = (unsigned short)strlen((char *)def_itm[0].pointer); StrCopyR((struct descriptor *)&def, &len, def_itm[0].pointer); TreeFree(def_itm[0].pointer); } - if - STATUS_OK { - stat1 = StrPosition((struct descriptor *)&def, - (struct descriptor *)&coloncolon, 0) + - 1; - status = StrRight((struct descriptor *)&def, - (struct descriptor *)&def, &stat1); - } - if - STATUS_OK - *def.pointer = '\\'; + if (STATUS_OK) + { + stat1 = StrPosition((struct descriptor *)&def, + (struct descriptor *)&coloncolon, 0) + + 1; + status = StrRight((struct descriptor *)&def, + (struct descriptor *)&def, &stat1); + } + if (STATUS_OK) + *def.pointer = '\\'; } } void *dbid = NULL, **ctx = TreeCtx(); if ((narg > 2) && ((list[2] != 0) || ((narg > 3) && (list[3] != 0))) && - STATUS_OK) { + STATUS_OK) + { if (list[2]) status = TdiGetLong(list[2], &shot); - else { + else + { DBI_ITM shot_itm[] = {{sizeof(shot), DbiSHOTID, 0, 0}, EOL}; shot_itm[0].pointer = (unsigned char *)&shot; status = TreeGetDbi(shot_itm); } - if - STATUS_OK { - if (narg > 3 && list[3]) - status = TdiData(list[3], &expt MDS_END_ARG); - else { - DBI_ITM expt_itm[] = {{0, DbiNAME, 0, 0}, EOL}; - status = TreeGetDbi(expt_itm); - if (expt_itm[0].pointer) { - unsigned short len = - (unsigned short)strlen((char *)expt_itm[0].pointer); - StrCopyR((struct descriptor *)&expt, &len, expt_itm[0].pointer); - TreeFree(expt_itm[0].pointer); - } + if (STATUS_OK) + { + if (narg > 3 && list[3]) + status = TdiData(list[3], &expt MDS_END_ARG); + else + { + DBI_ITM expt_itm[] = {{0, DbiNAME, 0, 0}, EOL}; + status = TreeGetDbi(expt_itm); + if (expt_itm[0].pointer) + { + unsigned short len = + (unsigned short)strlen((char *)expt_itm[0].pointer); + StrCopyR((struct descriptor *)&expt, &len, expt_itm[0].pointer); + TreeFree(expt_itm[0].pointer); } } + } /********************* Set new tree and path. Allow some rel paths. *********************/ - if - STATUS_OK { - char *tree = MdsDescrToCstring((struct descriptor *)&expt); - ctx = &dbid; - status = _TreeOpen(ctx, tree, shot, 1); - MdsFree(tree); - } + if (STATUS_OK) + { + char *tree = MdsDescrToCstring((struct descriptor *)&expt); + ctx = &dbid; + status = _TreeOpen(ctx, tree, shot, 1); + MdsFree(tree); + } } - if (narg > 1) { + if (narg > 1) + { char *path = MdsDescrToCstring((struct descriptor *)&def); - if - STATUS_OK - status = _TreeSetDefault(*ctx, path, &nid); + if (STATUS_OK) + status = _TreeSetDefault(*ctx, path, &nid); MdsFree(path); if (narg > 2) StrFree1Dx(&expt); @@ -299,16 +323,15 @@ int Tdi1Using(opcode_t opcode __attribute__((unused)), int narg, /*********************** Evaluate with temporary. ***********************/ - if - STATUS_OK { - struct descriptor_xd tmp = EMPTY_XD; - status = _TdiEvaluate(ctx, list[0], &tmp MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + struct descriptor_xd tmp = EMPTY_XD; + status = _TdiEvaluate(ctx, list[0], &tmp MDS_END_ARG); + if (STATUS_OK) status = MdsCopyDxXdZ((struct descriptor *)&tmp, out_ptr, NULL, fixup_nid, NULL, fixup_path, NULL); - MdsFree1Dx(&tmp, NULL); - } + MdsFree1Dx(&tmp, NULL); + } if (dbid) TreeFreeDbid(dbid); return status; diff --git a/tdishr/TdiGetNci.c b/tdishr/TdiGetNci.c index 03d7ea49e8..8325328518 100644 --- a/tdishr/TdiGetNci.c +++ b/tdishr/TdiGetNci.c @@ -51,8 +51,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from existing code. */ #undef MAX -#define EOL \ - { 0, NciEND_OF_LIST, 0, 0 } +#define EOL \ + { \ + 0, NciEND_OF_LIST, 0, 0 \ + } #define NID_NUMBER -1 #define RECORDIDX -2 #include @@ -75,7 +77,8 @@ extern int TdiUpcase(); extern int Tdi1Vector(); int TdiGetRecord(int nid, struct descriptor_xd *out); -static const struct item { +static const struct item +{ char *item_name; unsigned int item_mask; unsigned int item_test; @@ -175,7 +178,8 @@ static const struct item { #define siztab sizeof(struct item) #define numtab (sizeof(table) / siztab) -static const struct usage_item { +static const struct usage_item +{ char *usage_name; usage_t usage_code; } usage_table[] = { @@ -237,7 +241,8 @@ static const struct usage_item { }, }; -static int compare(struct descriptor *s1, struct item s2[1]) { +static int compare(struct descriptor *s1, struct item s2[1]) +{ int cmp, len1 = s1->length, len2 = strlen(s2[0].item_name); char c0; @@ -252,7 +257,8 @@ static int compare(struct descriptor *s1, struct item s2[1]) { ; else if (len1 > len2) cmp = (c0 = s1->pointer[len2]) != ' ' && c0 != '\t'; - else if (len1 < len2) { + else if (len1 < len2) + { if ((s2 != &table[0] && strncmp(s1->pointer, s2[-1].item_name, len1) == 0) || (s2 != &table[numtab - 1] && @@ -263,7 +269,8 @@ static int compare(struct descriptor *s1, struct item s2[1]) { } inline static int treefindnodewild(char *dat_ptr, int len, int *nid, void *pctx, - int usage_mask) { + int usage_mask) +{ int status; char *path = NULL; FREE_ON_EXIT(path); @@ -275,7 +282,8 @@ inline static int treefindnodewild(char *dat_ptr, int len, int *nid, void *pctx, return status; } -inline static int treefindnode(char *dat_ptr, int len, int *nid) { +inline static int treefindnode(char *dat_ptr, int len, int *nid) +{ int status; char *path = NULL; FREE_ON_EXIT(path); @@ -288,7 +296,8 @@ inline static int treefindnode(char *dat_ptr, int len, int *nid) { } int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const struct descriptor_d EMPTY_D = {0, DTYPE_T, CLASS_D, 0}; static const DESCRIPTOR_A(arr0, 1, DTYPE_B, 0, 960); @@ -306,29 +315,33 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, void *pctx = NULL; unsigned short maxlen = 0; - if (list[0]) { + if (list[0]) + { status = tdi_get_data(omits, list[0], &nids); - if - STATUS_OK { - len = nids.pointer->length; - class = nids.pointer->class; - dtype = nids.pointer->dtype; - dat_ptr = nids.pointer->pointer; - N_ELEMENTS(nids.pointer, nelem); - /*** scalar non-text/path gives scalar if possible ***/ - /*** a non-array text/path element without wilds gives scalar if + if (STATUS_OK) + { + len = nids.pointer->length; + class = nids.pointer->class; + dtype = nids.pointer->dtype; + dat_ptr = nids.pointer->pointer; + N_ELEMENTS(nids.pointer, nelem); + /*** scalar non-text/path gives scalar if possible ***/ + /*** a non-array text/path element without wilds gives scalar if * possible ***/ - if (STATUS_OK && class != CLASS_A) - switch (dtype) { - case DTYPE_T: - case DTYPE_PATH: { - if - IS_NOT_OK(treefindnode(dat_ptr, len, &nid)) + if (STATUS_OK && class != CLASS_A) + switch (dtype) + { + case DTYPE_T: + case DTYPE_PATH: + { + if (IS_NOT_OK(treefindnode(dat_ptr, len, &nid))) class = CLASS_A; - } - } - } - } else { + } + } + } + } + else + { status = TreeGetDefaultNid(&nid); len = sizeof(nid); class = CLASS_S; @@ -339,95 +352,98 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, /********************** String of item to find. **********************/ - if - STATUS_OK - status = TdiData(list[1], &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiUpcase(&tmp, &string MDS_END_ARG); - if - STATUS_OK { - key_ptr = - (struct item *)bsearch(&string, table, numtab, siztab, - (int (*)(const void *, const void *))compare); - if (key_ptr == 0) - status = TdiBAD_INDEX; - } + if (STATUS_OK) + status = TdiData(list[1], &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiUpcase(&tmp, &string MDS_END_ARG); + if (STATUS_OK) + { + key_ptr = + (struct item *)bsearch(&string, table, numtab, siztab, + (int (*)(const void *, const void *))compare); + if (key_ptr == 0) + status = TdiBAD_INDEX; + } StrFree1Dx(&string); /******************** String of node usage. ********************/ - if (narg > 2 && list[2]) { + if (narg > 2 && list[2]) + { usage_mask = 0; - if - STATUS_OK - status = TdiData(list[2], &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiUpcase(&tmp, &tmp MDS_END_ARG); - if - STATUS_OK { - struct descriptor allow = *tmp.pointer; - int length; - struct descriptor usage = {0, DTYPE_T, CLASS_S, 0}; - int nallow; - N_ELEMENTS(tmp.pointer, nallow); - length = allow.length; - allow.class = CLASS_S; - for (; --nallow >= 0; allow.pointer += length) { - const struct usage_item *puse = - &usage_table[sizeof(usage_table) / sizeof(usage_table[0])]; - allow.length = length; - while (((char *)allow.pointer)[allow.length - 1] == ' ') - allow.length--; - for (; --puse >= &usage_table[0];) { - usage.length = - (unsigned short)strlen(usage.pointer = puse->usage_name); - if (StrCompare(&allow, &usage) == 0) { - usage_mask |= 1 << puse->usage_code; - break; - } + if (STATUS_OK) + status = TdiData(list[2], &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiUpcase(&tmp, &tmp MDS_END_ARG); + if (STATUS_OK) + { + struct descriptor allow = *tmp.pointer; + int length; + struct descriptor usage = {0, DTYPE_T, CLASS_S, 0}; + int nallow; + N_ELEMENTS(tmp.pointer, nallow); + length = allow.length; + allow.class = CLASS_S; + for (; --nallow >= 0; allow.pointer += length) + { + const struct usage_item *puse = + &usage_table[sizeof(usage_table) / sizeof(usage_table[0])]; + allow.length = length; + while (((char *)allow.pointer)[allow.length - 1] == ' ') + allow.length--; + for (; --puse >= &usage_table[0];) + { + usage.length = + (unsigned short)strlen(usage.pointer = puse->usage_name); + if (StrCompare(&allow, &usage) == 0) + { + usage_mask |= 1 << puse->usage_code; + break; } - if (puse < &usage_table[0]) - status = TdiBAD_INDEX; } + if (puse < &usage_table[0]) + status = TdiBAD_INDEX; } + } if (usage_mask & (1 << TreeUSAGE_ANY)) usage_mask = 0xffff; - } else + } + else usage_mask = 0xffff; /******************** Guess at holder size. ********************/ - if - STATUS_OK { - step = key_ptr->item_length == 0 ? sizeof(struct descriptor_xd) - : key_ptr->item_length; - status = MdsGet1DxA((struct descriptor_a *)&arr0, &step, - &key_ptr->item_dtype, &holdxd); - } - if - STATUS_OK { - holda_ptr = (struct descriptor_a *)holdxd.pointer; - hold_ptr = holda_ptr->pointer; - memset(hold_ptr, 255, holda_ptr->arsize); - } + if (STATUS_OK) + { + step = key_ptr->item_length == 0 ? sizeof(struct descriptor_xd) + : key_ptr->item_length; + status = MdsGet1DxA((struct descriptor_a *)&arr0, &step, + &key_ptr->item_dtype, &holdxd); + } + if (STATUS_OK) + { + holda_ptr = (struct descriptor_a *)holdxd.pointer; + hold_ptr = holda_ptr->pointer; + memset(hold_ptr, 255, holda_ptr->arsize); + } /************************************** Loop over arrays of NIDs or TEXT names. **************************************/ - for (; STATUS_OK && --nelem >= 0; dat_ptr += len) { + for (; STATUS_OK && --nelem >= 0; dat_ptr += len) + { /************** Convert to NID. **************/ wild = 0; more: - switch (dtype) { + switch (dtype) + { case DTYPE_PATH: case DTYPE_T: - if - STATUS_OK - status = treefindnodewild(dat_ptr, len, &nid, &pctx, usage_mask); - if (status == TreeNMN || status == TreeNNF) { + if (STATUS_OK) + status = treefindnodewild(dat_ptr, len, &nid, &pctx, usage_mask); + if (status == TreeNMN || status == TreeNNF) + { TreeFindNodeEnd(&pctx); pctx = NULL; if (status == TreeNMN) @@ -448,17 +464,17 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, /**************************** Double size when you run out. ****************************/ - if ((unsigned int)(outcount * step) >= holda_ptr->arsize) { + if ((unsigned int)(outcount * step) >= holda_ptr->arsize) + { holda_ptr->arsize *= 2; - if - STATUS_OK - status = MdsGet1DxA(holda_ptr, &step, &key_ptr->item_dtype, &tmp); - if - STATUS_OK { - memset(tmp.pointer->pointer, 255, holda_ptr->arsize); - memcpy(tmp.pointer->pointer, holda_ptr->pointer, - holda_ptr->arsize / 2); - } + if (STATUS_OK) + status = MdsGet1DxA(holda_ptr, &step, &key_ptr->item_dtype, &tmp); + if (STATUS_OK) + { + memset(tmp.pointer->pointer, 255, holda_ptr->arsize); + memcpy(tmp.pointer->pointer, holda_ptr->pointer, + holda_ptr->arsize / 2); + } MdsFree1Dx(&holdxd, NULL); holdxd = tmp; holda_ptr = (struct descriptor_a *)holdxd.pointer; @@ -472,25 +488,25 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, break; if (key_ptr->item_code == NID_NUMBER) *(int *)hold_ptr = nid; - else if (key_ptr->item_code == RECORDIDX) { + else if (key_ptr->item_code == RECORDIDX) + { *(struct descriptor_xd *)hold_ptr = EMPTY_XD; status = TdiGetRecord(nid, (struct descriptor_xd *)hold_ptr); } /******************************** Logical results for bit or value. ********************************/ - else if (key_ptr->item_mask) { + else if (key_ptr->item_mask) + { NCI_ITM masked[2] = {{sizeof(flag), 0, 0, 0}, EOL}; flag = 0; masked[0].code = key_ptr->item_code; masked[0].pointer = (unsigned char *)&flag; masked[0].return_length_address = &retlen; - if - STATUS_OK - status = TreeGetNci(nid, masked); - if - STATUS_OK - /* + if (STATUS_OK) + status = TreeGetNci(nid, masked); + if (STATUS_OK) + /* { char ans=0; switch (retlen) @@ -503,14 +519,15 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, & key_ptr->item_mask) == key_ptr->item_test); } */ - *(char *)hold_ptr = - (char)((flag & key_ptr->item_mask) == key_ptr->item_test); + *(char *)hold_ptr = + (char)((flag & key_ptr->item_mask) == key_ptr->item_test); } /************************* Only nid arrays are here. First get size, then data. *************************/ - else if (key_ptr->item_test) { + else if (key_ptr->item_test) + { const dtype_t dtype = DTYPE_NID; const length_t dlen = (length_t)sizeof(nid); array arr = *(array *)&arr0; @@ -520,35 +537,36 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, tested[0].return_length_address = &retlen; status = TreeGetNci(nid, tested); *(struct descriptor_xd *)hold_ptr = EMPTY_XD; - if - STATUS_OK - status = MdsGet1DxA((struct descriptor_a *)&arr, &dlen, &dtype, - (struct descriptor_xd *)hold_ptr); - if - STATUS_OK { - struct descriptor_a *aptr = - (struct descriptor_a *)(((struct descriptor_xd *)hold_ptr) - ->pointer); - NCI_ITM listed[2] = {{0, 0, 0, 0}, EOL}; - listed[0].buffer_length = (short)aptr->arsize; - listed[0].code = key_ptr->item_code; - listed[0].pointer = (char *)aptr->pointer; - listed[0].return_length_address = &retlen; - if (aptr->arsize) - status = TreeGetNci(nid, listed); - aptr->dtype = DTYPE_LU; - } + if (STATUS_OK) + status = MdsGet1DxA((struct descriptor_a *)&arr, &dlen, &dtype, + (struct descriptor_xd *)hold_ptr); + if (STATUS_OK) + { + struct descriptor_a *aptr = + (struct descriptor_a *)(((struct descriptor_xd *)hold_ptr) + ->pointer); + NCI_ITM listed[2] = {{0, 0, 0, 0}, EOL}; + listed[0].buffer_length = (short)aptr->arsize; + listed[0].code = key_ptr->item_code; + listed[0].pointer = (char *)aptr->pointer; + listed[0].return_length_address = &retlen; + if (aptr->arsize) + status = TreeGetNci(nid, listed); + aptr->dtype = DTYPE_LU; + } } /*************************** Do dynamic text arrays here. ***************************/ - else if (key_ptr->item_length == 0) { + else if (key_ptr->item_length == 0) + { NCI_ITM texted[2] = {{0, 0, 0, 0}, EOL}; texted[0].code = key_ptr->item_code; texted[0].return_length_address = &retlen; *(struct descriptor_d *)hold_ptr = EMPTY_D; status = TreeGetNci(nid, texted); - if (STATUS_OK && texted[0].pointer) { + if (STATUS_OK && texted[0].pointer) + { unsigned short len = (unsigned short)strlen((char *)texted[0].pointer); if (maxlen < len) maxlen = len; @@ -560,7 +578,8 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, Fixed length items can be done here. Skip len=0 NIDs (missing). ***********************************/ - else { + else + { NCI_ITM fixed[2] = {{0, 0, 0, 0}, EOL}; fixed[0].buffer_length = key_ptr->item_length; fixed[0].code = key_ptr->item_code; @@ -578,52 +597,57 @@ int Tdi1GetNci(opcode_t opcode __attribute__((unused)), int narg, } MdsFree1Dx(&nids, NULL); MdsFree1Dx(&tmp, NULL); - if - STATUS_OK { - holda_ptr->arsize = hold_ptr - holda_ptr->pointer; - if (key_ptr->item_length) { - if (outcount == 1 && class != CLASS_A) - holda_ptr->class = CLASS_S; - status = MdsCopyDxXd((struct descriptor *)holda_ptr, out_ptr); - } else if (outcount == 0) - MdsFree1Dx(out_ptr, NULL); - else if (outcount == 1 && class != CLASS_A) - status = MdsCopyDxXd((struct descriptor *)holda_ptr->pointer, out_ptr); - else if (maxlen > 0) { - array arr = *(array *)&arr0; - dtype_t dtype = DTYPE_T; - arr.arsize = outcount; - status = MdsGet1DxA((struct descriptor_a *)&arr, &maxlen, &dtype, - (struct descriptor_xd *)out_ptr); - if - STATUS_OK { - char *p; - struct descriptor_xd *dp; - int j; - memset(out_ptr->pointer->pointer, 32, outcount * maxlen); - for (j = 0, p = out_ptr->pointer->pointer, - dp = (struct descriptor_xd *)holda_ptr->pointer; - j < outcount; j++, p += maxlen, dp++) { - memcpy(p, dp->pointer, dp->length); - } - } - - } else { - length_t dlen = (length_t)sizeof(int *); - dtype_t dtype = DTYPE_L; - status = MdsGet1DxA(holda_ptr, &dlen, &dtype, &tmp); - if - STATUS_OK { - char **xd_ptr = (char **)tmp.pointer->pointer; - hold_ptr = holda_ptr->pointer; - for (j = outcount; --j >= 0; hold_ptr += step) - *xd_ptr++ = hold_ptr; - status = - Tdi1Vector(OPC_VECTOR, outcount, tmp.pointer->pointer, out_ptr); - } - MdsFree1Dx(&tmp, NULL); + if (STATUS_OK) + { + holda_ptr->arsize = hold_ptr - holda_ptr->pointer; + if (key_ptr->item_length) + { + if (outcount == 1 && class != CLASS_A) + holda_ptr->class = CLASS_S; + status = MdsCopyDxXd((struct descriptor *)holda_ptr, out_ptr); + } + else if (outcount == 0) + MdsFree1Dx(out_ptr, NULL); + else if (outcount == 1 && class != CLASS_A) + status = MdsCopyDxXd((struct descriptor *)holda_ptr->pointer, out_ptr); + else if (maxlen > 0) + { + array arr = *(array *)&arr0; + dtype_t dtype = DTYPE_T; + arr.arsize = outcount; + status = MdsGet1DxA((struct descriptor_a *)&arr, &maxlen, &dtype, + (struct descriptor_xd *)out_ptr); + if (STATUS_OK) + { + char *p; + struct descriptor_xd *dp; + int j; + memset(out_ptr->pointer->pointer, 32, outcount * maxlen); + for (j = 0, p = out_ptr->pointer->pointer, + dp = (struct descriptor_xd *)holda_ptr->pointer; + j < outcount; j++, p += maxlen, dp++) + { + memcpy(p, dp->pointer, dp->length); + } } } + else + { + length_t dlen = (length_t)sizeof(int *); + dtype_t dtype = DTYPE_L; + status = MdsGet1DxA(holda_ptr, &dlen, &dtype, &tmp); + if (STATUS_OK) + { + char **xd_ptr = (char **)tmp.pointer->pointer; + hold_ptr = holda_ptr->pointer; + for (j = outcount; --j >= 0; hold_ptr += step) + *xd_ptr++ = hold_ptr; + status = + Tdi1Vector(OPC_VECTOR, outcount, tmp.pointer->pointer, out_ptr); + } + MdsFree1Dx(&tmp, NULL); + } + } if (outcount && key_ptr->item_length == 0) for (j = outcount, hold_ptr -= step; --j >= 0; hold_ptr -= step) MdsFree1Dx((struct descriptor_xd *)hold_ptr, NULL); diff --git a/tdishr/TdiGetShape.c b/tdishr/TdiGetShape.c index 0645757fd1..6d036e9779 100644 --- a/tdishr/TdiGetShape.c +++ b/tdishr/TdiGetShape.c @@ -41,7 +41,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int TdiGetShape(int narg, struct descriptor_xd dat[1], length_t length, - dtype_t dtype, int *cmode_ptr, struct descriptor_xd *out_ptr) { + dtype_t dtype, int *cmode_ptr, struct descriptor_xd *out_ptr) +{ INIT_STATUS; length_t ulen; int cmode = -1, count = 0x7fffffff, j, len, nelem; @@ -50,17 +51,20 @@ int TdiGetShape(int narg, struct descriptor_xd dat[1], length_t length, /******************************* Find the smallest array, if any. *******************************/ - for (j = 0; j < narg; j++) { + for (j = 0; j < narg; j++) + { aptr = (struct descriptor_a *)dat[j].pointer; if (aptr) - switch (aptr->class) { + switch (aptr->class) + { case CLASS_S: case CLASS_D: break; case CLASS_A: nelem = ((int)aptr->length > 0) ? (int)aptr->arsize / (int)aptr->length : 0; - if (nelem < count) { + if (nelem < count) + { count = nelem; cmode = j; } @@ -74,17 +78,17 @@ int TdiGetShape(int narg, struct descriptor_xd dat[1], length_t length, /***************************** Get array or scalar as needed. *****************************/ - if - STATUS_OK { - if ((len = length) == 0 && dtype < TdiCAT_MAX) - len = TdiREF_CAT[dtype].length; - ulen = (length_t)len; - if (cmode < 0) - status = MdsGet1DxS(&ulen, &dtype, out_ptr); - else - status = MdsGet1DxA((struct descriptor_a *)dat[cmode].pointer, &ulen, - &dtype, out_ptr); - } + if (STATUS_OK) + { + if ((len = length) == 0 && dtype < TdiCAT_MAX) + len = TdiREF_CAT[dtype].length; + ulen = (length_t)len; + if (cmode < 0) + status = MdsGet1DxS(&ulen, &dtype, out_ptr); + else + status = MdsGet1DxA((struct descriptor_a *)dat[cmode].pointer, &ulen, + &dtype, out_ptr); + } *cmode_ptr = cmode; return status; } diff --git a/tdishr/TdiGetSlope.c b/tdishr/TdiGetSlope.c index 688aead210..ec86a923d8 100644 --- a/tdishr/TdiGetSlope.c +++ b/tdishr/TdiGetSlope.c @@ -63,7 +63,8 @@ extern int TdiSetRange(); int TdiGetSlope(struct descriptor_window *window_ptr, struct descriptor_slope *slope_ptr, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ struct descriptor_xd xat0 = EMPTY_XD; int ndesc = slope_ptr->ndesc; int nseg = (ndesc + 2) / 3; @@ -88,22 +89,20 @@ int TdiGetSlope(struct descriptor_window *window_ptr, k1 = HUGE; if (STATUS_OK && window_ptr) status = TdiData(window_ptr->value_at_idx0, &xat0); - else if - STATUS_OK - status = TdiData(window_ptr, &xat0); + else if (STATUS_OK) + status = TdiData(window_ptr, &xat0); /******************************************** Single slope with no begin or end. X[i] = (dX/di)*RANGE(startidx,endidx) + X[0]. ********************************************/ if ((ndesc < 2 || !slope_ptr->segment[0].begin) && - (ndesc < 3 || !slope_ptr->segment[0].ending)) { - if - STATUS_OK - status = TdiRange(&k0_dsc, &k1_dsc, out_ptr); - if - STATUS_OK - status = TdiMultiply(slope_ptr->segment[0].slope, out_ptr, out_ptr); + (ndesc < 3 || !slope_ptr->segment[0].ending)) + { + if (STATUS_OK) + status = TdiRange(&k0_dsc, &k1_dsc, out_ptr); + if (STATUS_OK) + status = TdiMultiply(slope_ptr->segment[0].slope, out_ptr, out_ptr); if (STATUS_OK && xat0.pointer) status = TdiAdd(&xat0, out_ptr, out_ptr); } @@ -113,38 +112,38 @@ int TdiGetSlope(struct descriptor_window *window_ptr, Get each slope, begin, and end. May omit first begin and last end. *********************************/ - else if - STATUS_OK { - struct descriptor left_dsc = {sizeof(left), DTYPE_L, CLASS_S, 0}; - struct descriptor right_dsc = {sizeof(right), DTYPE_L, CLASS_S, 0}; - DESCRIPTOR_RANGE(ramp, 0, 0, 0); - struct descriptor_xd(*pbegin)[], (*pend)[] = 0, (*pslope)[] = 0, - *(*pvlist)[] = 0, tmp1; - int(*pcnt)[] = 0; - int virt = - (sizeof(struct descriptor_xd) * 3 + sizeof(struct descriptor_xd *)) * - nseg + - sizeof(int) * (nseg + 1); + else if (STATUS_OK) + { + struct descriptor left_dsc = {sizeof(left), DTYPE_L, CLASS_S, 0}; + struct descriptor right_dsc = {sizeof(right), DTYPE_L, CLASS_S, 0}; + DESCRIPTOR_RANGE(ramp, 0, 0, 0); + struct descriptor_xd(*pbegin)[], (*pend)[] = 0, (*pslope)[] = 0, + *(*pvlist)[] = 0, tmp1; + int(*pcnt)[] = 0; + int virt = + (sizeof(struct descriptor_xd) * 3 + sizeof(struct descriptor_xd *)) * + nseg + + sizeof(int) * (nseg + 1); - left_dsc.pointer = (char *)&left; - right_dsc.pointer = (char *)&right; - ramp.begin = &left_dsc; - ramp.ending = &right_dsc; - /************************************** + left_dsc.pointer = (char *)&left; + right_dsc.pointer = (char *)&right; + ramp.begin = &left_dsc; + ramp.ending = &right_dsc; + /************************************** Dynamic allocation of descriptors. Memory for begin[nseg], end[nseg], slope[nseg], *vlist[nseg], cnt[nseg+1]. **************************************/ - status = (pbegin = malloc(virt)) != NULL; - if - STATUS_OK { - pend = (struct descriptor_xd(*)[]) & (*pbegin)[nseg]; - pslope = (struct descriptor_xd(*)[]) & (*pend)[nseg]; - pvlist = (struct descriptor_xd * (*)[]) & (*pslope)[nseg]; - pcnt = (int(*)[]) & (*pvlist)[nseg]; - } + status = (pbegin = malloc(virt)) != NULL; + if (STATUS_OK) + { + pend = (struct descriptor_xd(*)[]) & (*pbegin)[nseg]; + pslope = (struct descriptor_xd(*)[]) & (*pend)[nseg]; + pvlist = (struct descriptor_xd * (*)[]) & (*pslope)[nseg]; + pcnt = (int(*)[]) & (*pvlist)[nseg]; + } - /************************************************************************************* + /************************************************************************************* Find the number of points in interior segments, if any. For 1ms sampling, begin=0s, 1000 points, end=.999s, no sample is taken at 1s. Ideal expression: FLOOR((end - begin)/slope + 1) but not less than @@ -153,65 +152,61 @@ int TdiGetSlope(struct descriptor_window *window_ptr, close and round. Must be exact int. Expression: NINT((end - begin)/slope + 1) *************************************************************************************/ - tmp1 = EMPTY_XD; - for (jseg = 0; jseg < nseg; ++jseg) { - (*pslope)[jseg] = (*pbegin)[jseg] = (*pend)[jseg] = EMPTY_XD; - if - STATUS_OK + tmp1 = EMPTY_XD; + for (jseg = 0; jseg < nseg; ++jseg) + { + (*pslope)[jseg] = (*pbegin)[jseg] = (*pend)[jseg] = EMPTY_XD; + if (STATUS_OK) status = TdiEvaluate(slope_ptr->segment[jseg].slope, &(*pslope)[jseg]); - if (STATUS_OK && jseg * 3 + 1 < ndesc) - status = - TdiEvaluate(slope_ptr->segment[jseg].begin, &(*pbegin)[jseg]); - if (STATUS_OK && jseg * 3 + 2 < ndesc) - status = TdiEvaluate(slope_ptr->segment[jseg].ending, &(*pend)[jseg]); + if (STATUS_OK && jseg * 3 + 1 < ndesc) + status = + TdiEvaluate(slope_ptr->segment[jseg].begin, &(*pbegin)[jseg]); + if (STATUS_OK && jseg * 3 + 2 < ndesc) + status = TdiEvaluate(slope_ptr->segment[jseg].ending, &(*pend)[jseg]); - if (jseg == 0 && !slope_ptr->segment[0].begin) { - (*pcnt)[1] = HUGE; - continue; - } - if (jseg == nseg - 1 && !slope_ptr->segment[jseg].ending) { - (*pcnt)[nseg] = HUGE; - continue; - } + if (jseg == 0 && !slope_ptr->segment[0].begin) + { + (*pcnt)[1] = HUGE; + continue; + } + if (jseg == nseg - 1 && !slope_ptr->segment[jseg].ending) + { + (*pcnt)[nseg] = HUGE; + continue; + } - if - STATUS_OK + if (STATUS_OK) status = TdiSubtract((*pend)[jseg].pointer, (*pbegin)[jseg].pointer, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiDivide(&tmp1, (*pslope)[jseg].pointer, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiNint(&tmp1, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(&tmp1, &left); - (*pcnt)[jseg + 1] = MAX(left + 1, 0); - } + (*pcnt)[jseg + 1] = MAX(left + 1, 0); + } - /******************************************** + /******************************************** Find the segment with value at index 0. Use first segment where expression is true: (0 LE slope[0]) EQV (x[0] LT begin[kseg+1]]). WARNING use .pointer to not free it. ********************************************/ - if - STATUS_OK + if (STATUS_OK) status = TdiLe(0, (*pslope)[0].pointer, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(&tmp1, &left); - for (kseg = 0; STATUS_OK && kseg < nseg - 1; ++kseg) { - status = TdiLt(xat0.pointer, (*pbegin)[kseg + 1].pointer, &tmp1); - if - STATUS_OK + for (kseg = 0; STATUS_OK && kseg < nseg - 1; ++kseg) + { + status = TdiLt(xat0.pointer, (*pbegin)[kseg + 1].pointer, &tmp1); + if (STATUS_OK) status = TdiGetLong(&tmp1, &right); - if (left == right) - break; - } + if (left == right) + break; + } - /******************************************** + /******************************************** With index 0 in kseg, what is index at begin? left = (begin[kseg] - xat0)/slope[kseg] right = (end[0] - xat0)/slope[0]+1 for kseg=0. @@ -219,109 +214,105 @@ int TdiGetSlope(struct descriptor_window *window_ptr, index 0, thus round down, more negative. Then adjust and accumulate counts. ********************************************/ - if (kseg == 0 && !slope_ptr->segment[0].begin) { - if - STATUS_OK + if (kseg == 0 && !slope_ptr->segment[0].begin) + { + if (STATUS_OK) status = TdiSubtract((*pend)[0].pointer, &xat0, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiDivide(&tmp1, (*pslope)[0].pointer, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(&tmp1, &right); - (*pcnt)[0] = MAX(right + 1, 0) - (*pcnt)[1]; - } else { - /******************************************* + (*pcnt)[0] = MAX(right + 1, 0) - (*pcnt)[1]; + } + else + { + /******************************************* To make FLOOR work, must be floating divide. Generally, result is a negative number. *******************************************/ - if - STATUS_OK + if (STATUS_OK) status = TdiSubtract((*pbegin)[kseg].pointer, &xat0, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiFloat(&tmp1, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiDivide(&tmp1, (*pslope)[kseg].pointer, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiFloor(&tmp1, &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(&tmp1, &left); - /*************************************** + /*************************************** Definition of kseg gives cnt[kseg] <= 0. Check that cnt[kseg+1] >= 0. For xat0 near start[kseg+1], get cnt[kseg+1] = 0. ***************************************/ - (*pcnt)[0] = MAX(left, -(*pcnt)[kseg + 1]); - for (jseg = kseg; --jseg >= 0;) - (*pcnt)[0] -= (*pcnt)[jseg + 1]; - } - for (jseg = 0; jseg < nseg; ++jseg) - (*pcnt)[jseg + 1] += (*pcnt)[jseg]; - if (k0 < (*pcnt)[0]) - k0 = (*pcnt)[0]; - if (k1 >= (*pcnt)[nseg]) - k1 = (*pcnt)[nseg] - 1; + (*pcnt)[0] = MAX(left, -(*pcnt)[kseg + 1]); + for (jseg = kseg; --jseg >= 0;) + (*pcnt)[0] -= (*pcnt)[jseg + 1]; + } + for (jseg = 0; jseg < nseg; ++jseg) + (*pcnt)[jseg + 1] += (*pcnt)[jseg]; + if (k0 < (*pcnt)[0]) + k0 = (*pcnt)[0]; + if (k1 >= (*pcnt)[nseg]) + k1 = (*pcnt)[nseg] - 1; - /******************************** + /******************************** For each segment generate result. ASSUMES ramp < 0 is 0 elements. [*:0] * slope[0] + end[0] or [0:*] * slope[jseg] + begin[jseg] Reuse slope as segment dsc. ********************************/ - for (jseg = nseg; --jseg >= 0;) { - left = MAX(k0 - (*pcnt)[jseg], 0); - right = MIN((*pcnt)[jseg + 1] - 1, k1) - (*pcnt)[jseg]; - if (left > right) - (*pvlist)[jseg] = 0; - else if (jseg == 0 && !slope_ptr->segment[0].begin) { - left -= (*pcnt)[1] - (*pcnt)[0] - 1; - right -= (*pcnt)[1] - (*pcnt)[0] - 1; - if - STATUS_OK + for (jseg = nseg; --jseg >= 0;) + { + left = MAX(k0 - (*pcnt)[jseg], 0); + right = MIN((*pcnt)[jseg + 1] - 1, k1) - (*pcnt)[jseg]; + if (left > right) + (*pvlist)[jseg] = 0; + else if (jseg == 0 && !slope_ptr->segment[0].begin) + { + left -= (*pcnt)[1] - (*pcnt)[0] - 1; + right -= (*pcnt)[1] - (*pcnt)[0] - 1; + if (STATUS_OK) status = TdiMultiply(&ramp, &(*pslope)[0], &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiAdd(&tmp1, &(*pend)[0], &(*pslope)[0]); - (*pvlist)[0] = &(*pslope)[0]; - } else { - if - STATUS_OK + (*pvlist)[0] = &(*pslope)[0]; + } + else + { + if (STATUS_OK) status = TdiMultiply(&ramp, &(*pslope)[jseg], &tmp1); - if - STATUS_OK + if (STATUS_OK) status = TdiAdd(&tmp1, &(*pbegin)[jseg], &(*pslope)[jseg]); - (*pvlist)[jseg] = &(*pslope)[jseg]; - } + (*pvlist)[jseg] = &(*pslope)[jseg]; } + } - /************************ + /************************ Make segments into whole. ************************/ - if - STATUS_OK + if (STATUS_OK) status = Tdi1Vector(0, nseg, (*pvlist), out_ptr); - MdsFree1Dx(&tmp1, NULL); - for (jseg = nseg; --jseg >= 0;) { - MdsFree1Dx(&(*pslope)[jseg], NULL); - MdsFree1Dx(&(*pbegin)[jseg], NULL); - MdsFree1Dx(&(*pend)[jseg], NULL); - } - if (pbegin != NULL) - free(pbegin); + MdsFree1Dx(&tmp1, NULL); + for (jseg = nseg; --jseg >= 0;) + { + MdsFree1Dx(&(*pslope)[jseg], NULL); + MdsFree1Dx(&(*pbegin)[jseg], NULL); + MdsFree1Dx(&(*pend)[jseg], NULL); } + if (pbegin != NULL) + free(pbegin); + } MdsFree1Dx(&xat0, NULL); /********************************************* When first index is not 0, we must set bounds. *********************************************/ - if (window_ptr && STATUS_OK && k0 != 0) { + if (window_ptr && STATUS_OK && k0 != 0) + { DESCRIPTOR_RANGE(range, 0, 0, 0); range.begin = &k0_dsc; range.ending = &k1_dsc; diff --git a/tdishr/TdiIand.c b/tdishr/TdiIand.c index 27d0fa75e2..5442d9ca18 100644 --- a/tdishr/TdiIand.c +++ b/tdishr/TdiIand.c @@ -78,301 +78,347 @@ int Tdi3Iand(struct descriptor *in1, struct descriptor *in2, struct descriptor extern int CvtConvertFloat(); extern void DoubleToWideInt(); -#define Operate(type, operator) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - *outp++ = (type)(not(*in1p operator*in2p)); \ - in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - *outp++ = (type)(not(*in1p operator*in2p)); \ - in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - *outp++ = (type)(not(*in1p operator*in2p)); \ - in1p++; \ - } \ - break; \ - } \ - break; \ +#define Operate(type, operator) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + *outp++ = (type)(not(*in1p operator*in2p)); \ + in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + *outp++ = (type)(not(*in1p operator*in2p)); \ + in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + *outp++ = (type)(not(*in1p operator*in2p)); \ + in1p++; \ + } \ + break; \ + } \ + break; \ } -#define OperateSpecial(size, operator) \ - { \ - unsigned int *in1p = (unsigned int *)in1->pointer; \ - unsigned int *in2p = (unsigned int *)in2->pointer; \ - unsigned int *outp = (unsigned int *)out->pointer; \ - int i; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - for (i = 0; i < size; i++) \ - *outp++ = (char)(not(in1p[i] operator in2p[i])); \ - in1p += size; \ - in2p += size; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - for (i = 0; i < size; i++) \ - *outp++ = (char)(not(in1p[i] operator in2p[i])); \ - in2p += size; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - for (i = 0; i < size; i++) \ - *outp++ = (char)(not(in1p[i] operator in2p[i])); \ - in1p += size; \ - } \ - break; \ - } \ - break; \ +#define OperateSpecial(size, operator) \ + { \ + unsigned int *in1p = (unsigned int *)in1->pointer; \ + unsigned int *in2p = (unsigned int *)in2->pointer; \ + unsigned int *outp = (unsigned int *)out->pointer; \ + int i; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + for (i = 0; i < size; i++) \ + *outp++ = (char)(not(in1p[i] operator in2p[i])); \ + in1p += size; \ + in2p += size; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + for (i = 0; i < size; i++) \ + *outp++ = (char)(not(in1p[i] operator in2p[i])); \ + in2p += size; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + for (i = 0; i < size; i++) \ + *outp++ = (char)(not(in1p[i] operator in2p[i])); \ + in1p += size; \ + } \ + break; \ + } \ + break; \ } -#define OperateFloatOne(dtype, operator) \ - *outp++ = (CvtConvertFloat(in1p, dtype, &a, DTYPE_NATIVE_FLOAT, 0) && \ - CvtConvertFloat(in2p, dtype, &b, DTYPE_NATIVE_FLOAT, 0)) \ - ? not((unsigned int)a operator(unsigned int) b) \ +#define OperateFloatOne(dtype, operator) \ + *outp++ = (CvtConvertFloat(in1p, dtype, &a, DTYPE_NATIVE_FLOAT, 0) && \ + CvtConvertFloat(in2p, dtype, &b, DTYPE_NATIVE_FLOAT, 0)) \ + ? not((unsigned int)a operator(unsigned int) b) \ : (unsigned int)0; -#define OperateFloat(dtype, operator) \ - { \ - float *in1p = (float *)in1->pointer; \ - float *in2p = (float *)in2->pointer; \ - unsigned int *outp = (unsigned int *)out->pointer; \ - float a, b; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - OperateFloatOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - OperateFloatOne(dtype, operator) in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - OperateFloatOne(dtype, operator) in1p++; \ - } \ - break; \ - } \ - break; \ +#define OperateFloat(dtype, operator) \ + { \ + float *in1p = (float *)in1->pointer; \ + float *in2p = (float *)in2->pointer; \ + unsigned int *outp = (unsigned int *)out->pointer; \ + float a, b; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + OperateFloatOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + OperateFloatOne(dtype, operator) in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + OperateFloatOne(dtype, operator) in1p++; \ + } \ + break; \ + } \ + break; \ } -#define OperateFloatC(dtype, operator) \ - { \ - float *in1p = (float *)in1->pointer; \ - float *in2p = (float *)in2->pointer; \ - unsigned int *outp = (unsigned int *)out->pointer; \ - float a, b; \ - int j; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - for (j = 0; j < 2; j++) { \ - OperateFloatOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - case 1: \ - while (nout--) { \ - in1p = (float *)in1->pointer; \ - for (j = 0; j < 2; j++) { \ - OperateFloatOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - case 2: \ - while (nout--) { \ - in2p = (float *)in2->pointer; \ - for (j = 0; j < 2; j++) { \ - OperateFloatOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - } \ - break; \ +#define OperateFloatC(dtype, operator) \ + { \ + float *in1p = (float *)in1->pointer; \ + float *in2p = (float *)in2->pointer; \ + unsigned int *outp = (unsigned int *)out->pointer; \ + float a, b; \ + int j; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + for (j = 0; j < 2; j++) \ + { \ + OperateFloatOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + in1p = (float *)in1->pointer; \ + for (j = 0; j < 2; j++) \ + { \ + OperateFloatOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + in2p = (float *)in2->pointer; \ + for (j = 0; j < 2; j++) \ + { \ + OperateFloatOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + } \ + break; \ } -#define OperateDoubleOne(dtype, operator) \ - if (CvtConvertFloat(in1p, dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(in2p, dtype, &b, DTYPE_NATIVE_DOUBLE, 0)) { \ - unsigned int a_int[2], b_int[2]; \ - DoubleToWideInt(&a, 2, a_int); \ - DoubleToWideInt(&b, 2, b_int); \ - for (i = 0; i < 2; i++) { \ - *outp++ = not(a_int[i] operator b_int[i]); \ - } \ - } else { \ - *outp++ = (unsigned int)0; \ - *outp++ = (unsigned int)0; \ +#define OperateDoubleOne(dtype, operator) \ + if (CvtConvertFloat(in1p, dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(in2p, dtype, &b, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + unsigned int a_int[2], b_int[2]; \ + DoubleToWideInt(&a, 2, a_int); \ + DoubleToWideInt(&b, 2, b_int); \ + for (i = 0; i < 2; i++) \ + { \ + *outp++ = not(a_int[i] operator b_int[i]); \ + } \ + } \ + else \ + { \ + *outp++ = (unsigned int)0; \ + *outp++ = (unsigned int)0; \ } -#define OperateDouble(dtype, operator) \ - { \ - double *in1p = (double *)in1->pointer; \ - double *in2p = (double *)in2->pointer; \ - unsigned int *outp = (unsigned int *)out->pointer; \ - double a, b; \ - int i; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - OperateDoubleOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - OperateDoubleOne(dtype, operator) in2p++; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - OperateDoubleOne(dtype, operator) in1p++; \ - } \ - break; \ - } \ - break; \ +#define OperateDouble(dtype, operator) \ + { \ + double *in1p = (double *)in1->pointer; \ + double *in2p = (double *)in2->pointer; \ + unsigned int *outp = (unsigned int *)out->pointer; \ + double a, b; \ + int i; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + OperateDoubleOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + OperateDoubleOne(dtype, operator) in2p++; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + OperateDoubleOne(dtype, operator) in1p++; \ + } \ + break; \ + } \ + break; \ } -#define OperateDoubleC(dtype, operator) \ - { \ - double *in1p = (double *)in1->pointer; \ - double *in2p = (double *)in2->pointer; \ - unsigned int *outp = (unsigned int *)out->pointer; \ - double a, b; \ - int i; \ - int j; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - for (j = 0; j < 2; j++) { \ - OperateDoubleOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - case 1: \ - while (nout--) { \ - in1p = (double *)in1->pointer; \ - for (j = 0; j < 2; j++) { \ - OperateDoubleOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - case 2: \ - while (nout--) { \ - in2p = (double *)in2->pointer; \ - for (j = 0; j < 2; j++) { \ - OperateDoubleOne(dtype, operator) in1p++; \ - in2p++; \ - } \ - } \ - break; \ - } \ - break; \ +#define OperateDoubleC(dtype, operator) \ + { \ + double *in1p = (double *)in1->pointer; \ + double *in2p = (double *)in2->pointer; \ + unsigned int *outp = (unsigned int *)out->pointer; \ + double a, b; \ + int i; \ + int j; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + for (j = 0; j < 2; j++) \ + { \ + OperateDoubleOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + in1p = (double *)in1->pointer; \ + for (j = 0; j < 2; j++) \ + { \ + OperateDoubleOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + in2p = (double *)in2->pointer; \ + for (j = 0; j < 2; j++) \ + { \ + OperateDoubleOne(dtype, operator) in1p++; \ + in2p++; \ + } \ + } \ + break; \ + } \ + break; \ } -#define common(name, operator) \ - int Tdi3##name(struct descriptor *in1, struct descriptor *in2, \ - struct descriptor *out) { \ - struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ - struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina1->arsize / ina1->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in2->class) { \ - case CLASS_S: \ - case CLASS_D: \ - if (scalars && (nout > 1)) \ - return TdiINV_SIZE; \ - scalars |= 2; \ - break; \ - case CLASS_A: \ - if (ina2->arsize / ina2->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->dtype) { \ - case DTYPE_B: \ - case DTYPE_BU: \ - Operate(unsigned char, operator) case DTYPE_W : case DTYPE_WU \ - : Operate(unsigned short, operator) case DTYPE_L : case DTYPE_LU \ - : Operate(unsigned int, operator) case DTYPE_Q \ - : OperateSpecial(2, operator) case DTYPE_QU \ - : OperateSpecial(2, operator) case DTYPE_O \ - : OperateSpecial(4, operator) case DTYPE_OU \ - : OperateSpecial(4, operator) case DTYPE_F \ - : OperateFloat(DTYPE_F, operator) case DTYPE_FS \ - : OperateFloat(DTYPE_FS, operator) case DTYPE_G \ - : OperateDouble(DTYPE_G, operator) case DTYPE_D \ - : OperateDouble(DTYPE_D, operator) case DTYPE_FT \ - : OperateDouble(DTYPE_FT, operator) case DTYPE_FC \ - : OperateFloatC(DTYPE_F, operator) case DTYPE_FSC \ - : OperateFloatC(DTYPE_FS, operator) case DTYPE_GC \ - : OperateDoubleC(DTYPE_G, operator) case DTYPE_DC \ - : OperateDoubleC(DTYPE_D, operator) case DTYPE_FTC \ - : OperateDoubleC(DTYPE_FT, operator) default : return TdiINVDTYDSC; \ - } \ - return 1; \ +#define common(name, operator) \ + int Tdi3##name(struct descriptor *in1, struct descriptor *in2, \ + struct descriptor *out) \ + { \ + struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ + struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina1->arsize / ina1->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in2->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + if (scalars && (nout > 1)) \ + return TdiINV_SIZE; \ + scalars |= 2; \ + break; \ + case CLASS_A: \ + if (ina2->arsize / ina2->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->dtype) \ + { \ + case DTYPE_B: \ + case DTYPE_BU: \ + Operate(unsigned char, operator) case DTYPE_W : case DTYPE_WU \ + : Operate(unsigned short, operator) case DTYPE_L : case DTYPE_LU \ + : Operate(unsigned int, operator) case DTYPE_Q \ + : OperateSpecial(2, operator) case DTYPE_QU \ + : OperateSpecial(2, operator) case DTYPE_O \ + : OperateSpecial(4, operator) case DTYPE_OU \ + : OperateSpecial(4, operator) case DTYPE_F \ + : OperateFloat(DTYPE_F, operator) case DTYPE_FS \ + : OperateFloat(DTYPE_FS, operator) case DTYPE_G \ + : OperateDouble(DTYPE_G, operator) case DTYPE_D \ + : OperateDouble(DTYPE_D, operator) case DTYPE_FT \ + : OperateDouble(DTYPE_FT, operator) case DTYPE_FC \ + : OperateFloatC(DTYPE_F, operator) case DTYPE_FSC \ + : OperateFloatC(DTYPE_FS, operator) case DTYPE_GC \ + : OperateDoubleC(DTYPE_G, operator) case DTYPE_DC \ + : OperateDoubleC(DTYPE_D, operator) case DTYPE_FTC \ + : OperateDoubleC(DTYPE_FT, operator) default : return TdiINVDTYDSC; \ + } \ + return 1; \ } -#define not ~ -common(Inand, &) common(InandNot, &~) common(Inor, |) common(InorNot, | ~) +#define not(x)(~(x)) +common(Inand, &); +common(InandNot, &~); +common(Inor, |); +common(InorNot, | ~); #undef not -#define not - common(Iand, &) common(IandNot, &~) common(Ior, |) common(IorNot, | ~) - common(Ieor, ^) common(IeorNot, ^~) +#define not(x)(x) +common(Iand, &); +common(IandNot, &~); +common(Ior, |); +common(IorNot, | ~); +common(Ieor, ^); +common(IeorNot, ^~); #undef not diff --git a/tdishr/TdiIntrinsic.c b/tdishr/TdiIntrinsic.c index 28c29605ed..d95ee73632 100644 --- a/tdishr/TdiIntrinsic.c +++ b/tdishr/TdiIntrinsic.c @@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define PREC_COMMA 92 #define MAXLINE 120 #define MAXFRAC 40 -#define MINMAX(min, test, max) \ +#define MINMAX(min, test, max) \ ((min) >= (test) ? (min) : (test) < (max) ? (test) : (max)) #define OPC_ENUM @@ -64,7 +64,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -typedef struct _bounds { +typedef struct _bounds +{ int l; int u; } BOUNDS; @@ -76,7 +77,8 @@ extern int TdiConvert(); extern int TdiGetLong(); extern int SysGetMsg(); -static mdsdsc_t *fixed_array(mdsdsc_t *in) { +static mdsdsc_t *fixed_array(mdsdsc_t *in) +{ array_coeff *a = (array_coeff *)in; int dsize = sizeof(mdsdsc_a_t) + sizeof(int) + 3 * sizeof(int) * a->dimct; int i; @@ -98,7 +100,8 @@ Explain in 300 words or less. ****************************/ #define MAXMESS 1800 #define ADD(text) add(text, TDITHREADSTATIC_VAR) -static void add(char *const text, TDITHREADSTATIC_ARG) { +static void add(char *const text, TDITHREADSTATIC_ARG) +{ mdsdsc_d_t new = {0, DTYPE_T, CLASS_D, 0}; new.length = (length_t)strlen(text); new.pointer = text; @@ -106,7 +109,8 @@ static void add(char *const text, TDITHREADSTATIC_ARG) { StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)&new); } #define NUMB(count) numb(count, TDITHREADSTATIC_VAR) -static void numb(int count, TDITHREADSTATIC_ARG) { +static void numb(int count, TDITHREADSTATIC_ARG) +{ char val[16]; sprintf(val, "%d", count); ADD(val); @@ -115,16 +119,20 @@ static void numb(int count, TDITHREADSTATIC_ARG) { /*************************************************** Danger: this routine is used by DECOMPILE to report. ***************************************************/ -int tdi_trace(mdsdsc_xd_t *out_ptr) { +int tdi_trace(mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; if (TDI_INTRINSIC_MSG.length > MAXMESS) return MDSplusERROR; ADD("%TDI Decompile text_length"); NUMB(out_ptr->length); ADD(" partial text: "); - if (out_ptr->length < MAXLINE - 70) { + if (out_ptr->length < MAXLINE - 70) + { StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)out_ptr); - } else { + } + else + { *((char *)out_ptr->pointer + MAXLINE - 70) = '\0'; ADD((char *)out_ptr->pointer); } @@ -133,48 +141,58 @@ int tdi_trace(mdsdsc_xd_t *out_ptr) { #define TRACE(opcode, narg, list) trace(opcode, narg, list, TDITHREADSTATIC_VAR) static inline void trace(opcode_t opcode, int narg, mdsdsc_t *list[], - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ if (TDI_INTRINSIC_MSG.length >= MAXMESS) return; unsigned short now = TDI_INTRINSIC_MSG.length; int j; mdsdsc_d_t text = {0, DTYPE_T, CLASS_D, 0}; - if (opcode < TdiFUNCTION_MAX) { + if (opcode < TdiFUNCTION_MAX) + { struct TdiFunctionStruct *pfun = (struct TdiFunctionStruct *)&TdiRefFunction[opcode]; - if (narg < pfun->m1 || narg > pfun->m2) { + if (narg < pfun->m1 || narg > pfun->m2) + { if (pfun->m1 != pfun->m2) ADD("%TDI Requires "); NUMB(pfun->m1); - if (pfun->m1 != pfun->m2) { + if (pfun->m1 != pfun->m2) + { ADD(" to "); NUMB(pfun->m2); } ADD(" input arguments for "); - } else + } + else ADD("%TDI Error in "); ADD(pfun->name); - } else + } + else ADD("%TDI Unknown opcode "); ADD("("); - for (j = 0; j < narg;) { - if - IS_OK(Tdi0Decompile(list[j], PREC_COMMA, &text, 5)) { - if (TDI_INTRINSIC_MSG.length - now + text.length < MAXLINE - 2) - StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)&text); - else { - *(text.pointer + MAXFRAC) = '\0'; - ADD(text.pointer); - ADD(" ..."); - } + for (j = 0; j < narg;) + { + if (IS_OK(Tdi0Decompile(list[j], PREC_COMMA, &text, 5))) + { + if (TDI_INTRINSIC_MSG.length - now + text.length < MAXLINE - 2) + StrAppend(&TDI_INTRINSIC_MSG, (mdsdsc_t *)&text); + else + { + *(text.pointer + MAXFRAC) = '\0'; + ADD(text.pointer); + ADD(" ..."); } + } else ADD("BAD_INPUT"); StrFree1Dx(&text); - if (++j < narg) { + if (++j < narg) + { if (TDI_INTRINSIC_MSG.length - now < MAXLINE - MAXFRAC - 7) ADD(", "); - else { + else + { ADD(",\n"); now = TDI_INTRINSIC_MSG.length; ADD("%- "); @@ -184,13 +202,15 @@ static inline void trace(opcode_t opcode, int narg, mdsdsc_t *list[], ADD(")\n"); } -typedef struct { +typedef struct +{ int n; char f[256]; mdsdsc_t *a[256]; int *rec; } fixed_t; -static void cleanup_list(void *fixed_in) { +static void cleanup_list(void *fixed_in) +{ fixed_t *const fixed = (fixed_t *)fixed_in; while (--fixed->n >= 0) if (fixed->f[fixed->n]) @@ -199,7 +219,8 @@ static void cleanup_list(void *fixed_in) { } EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ int status; struct TdiFunctionStruct *fun_ptr = (struct TdiFunctionStruct *)&TdiRefFunction[opcode]; @@ -215,16 +236,20 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], status = TdiEXTRA_ARG; else if (TDI_INTRINSIC_REC > 1800) status = TdiRECURSIVE; - else { + else + { fixed_t fixed; TDI_INTRINSIC_REC++; pthread_cleanup_push(cleanup_list, &fixed); fixed.rec = &TDI_INTRINSIC_REC; for (fixed.n = 0; fixed.n < narg; fixed.n++) - if (list[fixed.n] != NULL && list[fixed.n]->class == CLASS_NCA) { + if (list[fixed.n] != NULL && list[fixed.n]->class == CLASS_NCA) + { fixed.f[fixed.n] = 1; fixed.a[fixed.n] = fixed_array(list[fixed.n]); - } else { + } + else + { fixed.f[fixed.n] = 0; fixed.a[fixed.n] = list[fixed.n]; } @@ -232,11 +257,13 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], pthread_cleanup_pop(1); } if (STATUS_OK || status == TdiBREAK || status == TdiCONTINUE || - status == TdiGOTO || status == TdiRETURN) { + status == TdiGOTO || status == TdiRETURN) + { if (!out_ptr) goto notmp; int stat1 = MDSplusSUCCESS; - switch (out_ptr->class) { + switch (out_ptr->class) + { default: status = TdiINVCLADSC; break; @@ -252,13 +279,15 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], if ((char *)out_ptr->pointer + out_ptr->l_length <= (char *)tmp.pointer || (char *)out_ptr->pointer >= (char *)tmp.pointer + tmp.l_length) MdsFree1Dx(out_ptr, NULL); - else if (out_ptr->l_length) { + else if (out_ptr->l_length) + { ADD("%TDI DANGER, part of old output descriptor was input to below.\n"); trace(opcode, narg, list, TDITHREADSTATIC_VAR); } if (tmp.class == CLASS_XD) *out_ptr = tmp; - else { + else + { stat1 = MdsCopyDxXd((mdsdsc_t *)&tmp, out_ptr); MdsFree1Dx(&tmp, NULL); } @@ -274,19 +303,21 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], if (dsc_ptr == 0) stat1 = StrFree1Dx((mdsdsc_d_t *)out_ptr); else - switch (dsc_ptr->class) { + switch (dsc_ptr->class) + { case CLASS_S: case CLASS_D: - if (out_ptr->length != dsc_ptr->length) { + if (out_ptr->length != dsc_ptr->length) + { stat1 = StrGet1Dx(&dsc_ptr->length, (mdsdsc_d_t *)out_ptr); } - if - IS_OK(stat1) { - out_ptr->dtype = dsc_ptr->dtype; - if ((out_ptr->length > 0) && (dsc_ptr != NULL)) - _MOVC3(out_ptr->length, dsc_ptr->pointer, - (char *)out_ptr->pointer); - } + if (IS_OK(stat1)) + { + out_ptr->dtype = dsc_ptr->dtype; + if ((out_ptr->length > 0) && (dsc_ptr != NULL)) + _MOVC3(out_ptr->length, dsc_ptr->pointer, + (char *)out_ptr->pointer); + } break; default: stat1 = TdiINVCLADSC; @@ -309,7 +340,8 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], stat1 = TdiConvert(&miss_dsc, out_ptr); MdsFree1Dx(&tmp, NULL); break; - case CLASS_NCA: { + case CLASS_NCA: + { mdsdsc_t *fixed_out_ptr = fixed_array((mdsdsc_t *)out_ptr); if (tmp.class == CLASS_XD) dsc_ptr = tmp.pointer; @@ -321,11 +353,11 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], stat1 = TdiConvert(&miss_dsc, out_ptr); MdsFree1Dx(&tmp, NULL); free(fixed_out_ptr); - } break; } - if - IS_OK(stat1) - goto done; + break; + } + if (IS_OK(stat1)) + goto done; status = stat1; } if (TDI_INTRINSIC_REC >= 0) @@ -342,7 +374,8 @@ done:; return status; } EXPORT int _TdiIntrinsic(void **ctx, opcode_t opcode, int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ int status; CTX_PUSH(ctx); status = TdiIntrinsic(opcode, narg, list, out_ptr); @@ -360,13 +393,15 @@ EXPORT int _TdiIntrinsic(void **ctx, opcode_t opcode, int narg, 8 return message before clear */ int Tdi1Debug(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; int option = -1; if (narg > 0 && list[0]) status = TdiGetLong(list[0], &option); - if (option & 1 && TDI_INTRINSIC_STAT != SsSUCCESS) { + if (option & 1 && TDI_INTRINSIC_STAT != SsSUCCESS) + { mdsdsc_t dmsg = {0, DTYPE_T, CLASS_S, 0}; dmsg.pointer = MdsGetMsg(TDI_INTRINSIC_STAT); dmsg.length = strlen(dmsg.pointer); @@ -379,10 +414,12 @@ int Tdi1Debug(opcode_t opcode __attribute__((unused)), int narg, &oldmsg MDS_END_ARG); StrFree1Dx(&oldmsg); } - if (TDI_INTRINSIC_MSG.length) { + if (TDI_INTRINSIC_MSG.length) + { if (option & 2) printf("%.*s", TDI_INTRINSIC_MSG.length, TDI_INTRINSIC_MSG.pointer); - if (option & 4) { + if (option & 4) + { if (option & 8) status = MdsCopyDxXd((mdsdsc_t *)&TDI_INTRINSIC_MSG, out_ptr); StrFree1Dx(&TDI_INTRINSIC_MSG); diff --git a/tdishr/TdiIo.c b/tdishr/TdiIo.c index d0825a2703..447726999f 100644 --- a/tdishr/TdiIo.c +++ b/tdishr/TdiIo.c @@ -48,7 +48,7 @@ static const DESCRIPTOR(dBAD, "/*bad*/"); In a shared library, cannot match extern stdout, etc. */ #define kprintf(unit, ctrl) (unit ? fprintf(unit, ctrl) : printf(ctrl)); -#define kprintf2(unit, ctrl, a1, a2) \ +#define kprintf2(unit, ctrl, a1, a2) \ (unit ? fprintf(unit, ctrl, a1, a2) : printf(ctrl, a1, a2)); extern int TdiData(); @@ -61,7 +61,8 @@ extern int TdiDecompile(); /*---------------------------------------------- Internal routine to output a long. */ -int TdiPutLong(int *data, struct descriptor_xd *out_ptr) { +int TdiPutLong(int *data, struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const dtype_t dtype = DTYPE_L; static const length_t len = (length_t)sizeof(int); @@ -69,16 +70,16 @@ int TdiPutLong(int *data, struct descriptor_xd *out_ptr) { if (out_ptr == 0) return 1; status = MdsGet1DxS(&len, &dtype, out_ptr); - if - STATUS_OK - *(int *)out_ptr->pointer->pointer = *data; + if (STATUS_OK) + *(int *)out_ptr->pointer->pointer = *data; return status; } /*---------------------------------------------- Internal routine to output a unit */ -static int TdiPutUnit(FILE *unit, struct descriptor_xd *out_ptr) { +static int TdiPutUnit(FILE *unit, struct descriptor_xd *out_ptr) +{ if (!unit) return MdsCopyDxXd(NULL, out_ptr); struct descriptor unit_d = {sizeof(void *), DTYPE_POINTER, CLASS_S, @@ -89,23 +90,28 @@ static int TdiPutUnit(FILE *unit, struct descriptor_xd *out_ptr) { /*---------------------------------------------- Internal routine to input a unit */ -static int TdiGetOutUnit(struct descriptor *in_ptr, FILE **unit) { +static int TdiGetOutUnit(struct descriptor *in_ptr, FILE **unit) +{ int status; INIT_AND_FREEXD_ON_EXIT(xd); status = TdiEvaluate(in_ptr, &xd MDS_END_ARG); struct descriptor *unit_d = xd.pointer; - if (unit_d && unit_d->class == CLASS_S) { - if (unit_d->dtype == DTYPE_L || unit_d->dtype == DTYPE_LU) { + if (unit_d && unit_d->class == CLASS_S) + { + if (unit_d->dtype == DTYPE_L || unit_d->dtype == DTYPE_LU) + { if (*(int *)unit_d->pointer == 2) *unit = stderr; else *unit = stdout; - } else if ((unit_d->dtype == DTYPE_POINTER || unit_d->dtype == DTYPE_T) && - unit_d->length == sizeof(void *)) + } + else if ((unit_d->dtype == DTYPE_POINTER || unit_d->dtype == DTYPE_T) && + unit_d->length == sizeof(void *)) *unit = *(FILE **)unit_d->pointer; else *unit = stdout; - } else + } + else *unit = stdout; FREEXD_NOW(); return status; @@ -114,7 +120,8 @@ static int TdiGetOutUnit(struct descriptor *in_ptr, FILE **unit) { /*---------------------------------------------- Internal routine to input a unit */ -static int TdiGetInUnit(struct descriptor *in_ptr, FILE **unit) { +static int TdiGetInUnit(struct descriptor *in_ptr, FILE **unit) +{ int status; INIT_AND_FREEXD_ON_EXIT(xd); status = TdiEvaluate(in_ptr, &xd MDS_END_ARG); @@ -134,29 +141,29 @@ static int TdiGetInUnit(struct descriptor *in_ptr, FILE **unit) { string = DATE_TIME([quadword time]) */ int Tdi1DateTime(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int time[2] = {0, 0}, *ptime; length_t len; static const dtype_t dtype = DTYPE_T; static const length_t length = 23; - if (narg > 0 && list[0]) { + if (narg > 0 && list[0]) + { struct descriptor dtime = {sizeof(time), DTYPE_Q, CLASS_S, 0}; dtime.pointer = (char *)time; status = TdiData(list[0], &dtime MDS_END_ARG); ptime = time; - } else + } + else ptime = 0; - if - STATUS_OK - status = MdsGet1DxS(&length, &dtype, out_ptr); - if - STATUS_OK - status = LibSysAscTim(&len, out_ptr->pointer, ptime); - if - STATUS_OK - out_ptr->pointer->length = len; + if (STATUS_OK) + status = MdsGet1DxS(&length, &dtype, out_ptr); + if (STATUS_OK) + status = LibSysAscTim(&len, out_ptr->pointer, ptime); + if (STATUS_OK) + out_ptr->pointer->length = len; return status; } @@ -165,7 +172,8 @@ int Tdi1DateTime(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1Fclose(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ FILE *unit; int err; @@ -181,7 +189,8 @@ int Tdi1Fclose(opcode_t opcode __attribute__((unused)), and origin: 0=absolute 1=relative 2=relative to end. */ int Tdi1Fseek(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; FILE *unit; int offset = 0, origin = 0, err; @@ -191,11 +200,11 @@ int Tdi1Fseek(opcode_t opcode __attribute__((unused)), int narg, status = TdiGetLong(list[1], &offset); if (STATUS_OK && narg > 2) status = TdiGetLong(list[2], &origin); - if - STATUS_OK { - err = fseek(unit, offset, origin); - status = TdiPutLong((int *)&err, out_ptr); - } + if (STATUS_OK) + { + err = fseek(unit, offset, origin); + status = TdiPutLong((int *)&err, out_ptr); + } return status; } @@ -205,7 +214,8 @@ int Tdi1Fseek(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1Ftell(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; FILE *unit; int pos; @@ -224,27 +234,25 @@ int Tdi1Ftell(opcode_t opcode __attribute__((unused)), */ int Tdi1Fopen(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; FILE *unit; struct descriptor_d dname = {0, DTYPE_T, CLASS_D, 0}; struct descriptor_d dmode = {0, DTYPE_T, CLASS_D, 0}; status = TdiData(list[0], &dname MDS_END_ARG); - if - STATUS_OK - status = TdiData(list[1], &dmode MDS_END_ARG); - if - STATUS_OK - status = StrAppend(&dname, (struct descriptor *)&dNUL); - if - STATUS_OK - status = StrAppend(&dmode, (struct descriptor *)&dNUL); - if - STATUS_OK { - unit = fopen(dname.pointer, dmode.pointer); - status = TdiPutUnit(unit, out_ptr); - } + if (STATUS_OK) + status = TdiData(list[1], &dmode MDS_END_ARG); + if (STATUS_OK) + status = StrAppend(&dname, (struct descriptor *)&dNUL); + if (STATUS_OK) + status = StrAppend(&dmode, (struct descriptor *)&dNUL); + if (STATUS_OK) + { + unit = fopen(dname.pointer, dmode.pointer); + status = TdiPutUnit(unit, out_ptr); + } StrFree1Dx(&dname); StrFree1Dx(&dmode); return status; @@ -255,7 +263,8 @@ int Tdi1Fopen(opcode_t opcode __attribute__((unused)), status = SPAWN([command_string],[input_file],[output_file]) */ int Tdi1Spawn(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int stat1; struct descriptor_d cmd = EMPTY_D; @@ -268,11 +277,11 @@ int Tdi1Spawn(opcode_t opcode __attribute__((unused)), int narg, status = TdiText(list[1], &inp MDS_END_ARG); if (narg > 2 && list[2] && STATUS_OK) status = TdiText(list[2], &out MDS_END_ARG); - if - STATUS_OK { - stat1 = LibSpawn((struct descriptor *)&cmd, 1, 0); - status = TdiPutLong(&stat1, out_ptr); - } + if (STATUS_OK) + { + stat1 = LibSpawn((struct descriptor *)&cmd, 1, 0); + status = TdiPutLong(&stat1, out_ptr); + } return status; } @@ -282,14 +291,14 @@ int Tdi1Spawn(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1Wait(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr __attribute__((unused))) { + struct descriptor_xd *out_ptr __attribute__((unused))) +{ INIT_STATUS; float time; status = TdiGetFloat(list[0], &time); - if - STATUS_OK - status = LibWait(&time); + if (STATUS_OK) + status = LibWait(&time); return status; } @@ -306,7 +315,8 @@ int Tdi1Wait(opcode_t opcode __attribute__((unused)), are decompiled and start and end with a new row. */ int Tdi1Write(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int j, stat1, bytes = 0, col = 0, len; FILE *unit = 0; @@ -317,87 +327,90 @@ int Tdi1Write(opcode_t opcode __attribute__((unused)), int narg, static const int width = 132; status = TdiGetOutUnit(list[0], &unit); - if - STATUS_OK - for (j = 1; j < narg; ++j) { - stat1 = TdiEvaluate(list[j], &tmp MDS_END_ARG); - if (!(stat1 & 1)) - pd = (struct descriptor *)&dBAD; - else if ((ptmp = tmp.pointer) == 0) - pd = (struct descriptor *)&dNUL; - else - switch (ptmp->dtype) { - case DTYPE_BU: - case DTYPE_B: - case DTYPE_WU: - case DTYPE_W: - case DTYPE_LU: - case DTYPE_L: - case DTYPE_QU: - case DTYPE_Q: - case DTYPE_OU: - case DTYPE_O: - case DTYPE_FC: - case DTYPE_F: - case DTYPE_DC: - case DTYPE_D: - case DTYPE_GC: - case DTYPE_G: - case DTYPE_HC: - case DTYPE_H: - case DTYPE_FSC: - case DTYPE_FS: - case DTYPE_FTC: - case DTYPE_FT: - stat1 = TdiText(&tmp, &tmp MDS_END_ARG); - if (!(stat1 & 1)) { - pd = (struct descriptor *)&dBAD; - break; - } - MDS_ATTR_FALLTHROUGH - case DTYPE_T: - ptmp = tmp.pointer; - len = ptmp->length; - pt = ptmp->pointer; - plim = pt + len; - switch (ptmp->class) { - case CLASS_S: - case CLASS_D: - if (col > 0 && col + len > width) - col = 0, bytes += kprintf(unit, "\n"); - col += len; - bytes += kprintf2(unit, "%.*s", len, pt); - continue; - case CLASS_A: - plim = pt + ((struct descriptor_a *)ptmp)->arsize; - if (col > 0) - col = 0, bytes += kprintf(unit, "\n"); - for (; pt < plim; pt += len) { + if (STATUS_OK) + for (j = 1; j < narg; ++j) + { + stat1 = TdiEvaluate(list[j], &tmp MDS_END_ARG); + if (!(stat1 & 1)) + pd = (struct descriptor *)&dBAD; + else if ((ptmp = tmp.pointer) == 0) + pd = (struct descriptor *)&dNUL; + else + switch (ptmp->dtype) + { + case DTYPE_BU: + case DTYPE_B: + case DTYPE_WU: + case DTYPE_W: + case DTYPE_LU: + case DTYPE_L: + case DTYPE_QU: + case DTYPE_Q: + case DTYPE_OU: + case DTYPE_O: + case DTYPE_FC: + case DTYPE_F: + case DTYPE_DC: + case DTYPE_D: + case DTYPE_GC: + case DTYPE_G: + case DTYPE_HC: + case DTYPE_H: + case DTYPE_FSC: + case DTYPE_FS: + case DTYPE_FTC: + case DTYPE_FT: + stat1 = TdiText(&tmp, &tmp MDS_END_ARG); + if (!(stat1 & 1)) + { + pd = (struct descriptor *)&dBAD; + break; + } + MDS_ATTR_FALLTHROUGH + case DTYPE_T: + ptmp = tmp.pointer; + len = ptmp->length; + pt = ptmp->pointer; + plim = pt + len; + switch (ptmp->class) + { + case CLASS_S: + case CLASS_D: if (col > 0 && col + len > width) col = 0, bytes += kprintf(unit, "\n"); col += len; bytes += kprintf2(unit, "%.*s", len, pt); + continue; + case CLASS_A: + plim = pt + ((struct descriptor_a *)ptmp)->arsize; + if (col > 0) + col = 0, bytes += kprintf(unit, "\n"); + for (; pt < plim; pt += len) + { + if (col > 0 && col + len > width) + col = 0, bytes += kprintf(unit, "\n"); + col += len; + bytes += kprintf2(unit, "%.*s", len, pt); + } + col = 0, bytes += kprintf(unit, "\n"); + continue; + default: + goto none; } - col = 0, bytes += kprintf(unit, "\n"); - continue; default: - goto none; + none: + stat1 = TdiDecompile(&tmp, &tmp MDS_END_ARG); + pd = (stat1 & 1) ? tmp.pointer : (struct descriptor *)&dBAD; + if (col > 0) + col = 0, bytes += kprintf(unit, "\n"); + break; } - default: - none: - stat1 = TdiDecompile(&tmp, &tmp MDS_END_ARG); - pd = (stat1 & 1) ? tmp.pointer : (struct descriptor *)&dBAD; - if (col > 0) - col = 0, bytes += kprintf(unit, "\n"); - break; - } - bytes += kprintf2(unit, "%.*s\n", pd->length, pd->pointer); - } + bytes += kprintf2(unit, "%.*s\n", pd->length, pd->pointer); + } if (col > 0) bytes += kprintf(unit, "\n"); - if - STATUS_OK - status = TdiPutLong((int *)&bytes, out_ptr); + if (STATUS_OK) + status = TdiPutLong((int *)&bytes, out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -410,22 +423,25 @@ int Tdi1Write(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1Read(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; FILE *unit = 0; status = TdiGetInUnit(list[0], &unit); - if - STATUS_OK { - char line[4096]; - char *ans; - struct descriptor line_d = {0, DTYPE_T, CLASS_S, 0}; - ans = fgets(line, sizeof(line), unit); - if (ans) { - line_d.length = strlen(line) - 1; - line_d.pointer = line; - status = MdsCopyDxXd(&line_d, out_ptr); - } else - status = MDSplusERROR; + if (STATUS_OK) + { + char line[4096]; + char *ans; + struct descriptor line_d = {0, DTYPE_T, CLASS_S, 0}; + ans = fgets(line, sizeof(line), unit); + if (ans) + { + line_d.length = strlen(line) - 1; + line_d.pointer = line; + status = MdsCopyDxXd(&line_d, out_ptr); } + else + status = MDSplusERROR; + } return status; } diff --git a/tdishr/TdiItoX.c b/tdishr/TdiItoX.c index b1380f2e8d..1429284670 100644 --- a/tdishr/TdiItoX.c +++ b/tdishr/TdiItoX.c @@ -114,7 +114,8 @@ static DESCRIPTOR_FUNCTION_0(vector0, &OpcVector); static DESCRIPTOR_A(duo, sizeof(int), DTYPE_L, 0, 2 * sizeof(int)); static DESCRIPTOR_RANGE(fake0, 0, 0, 0); int Tdi1ItoX(opcode_t opcode, int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; static const dtype_t omits[] = {DTYPE_WITH_UNITS, DTYPE_DIMENSION, 0}; @@ -141,7 +142,8 @@ int Tdi1ItoX(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t sig[3] = {EMPTY_XD}, uni[3] = {EMPTY_XD}, dat[3] = {EMPTY_XD}; mdsdsc_xd_t sig1 = EMPTY_XD, uni1 = EMPTY_XD; struct TdiCatStruct cats[4]; - FUNCTION(255 / 3) vec[3]; + FUNCTION(255 / 3) + vec[3]; dk0.pointer = (char *)&k0; dk1.pointer = (char *)&k1; keep[0] = TDI_RANGE_PTRS[0]; @@ -154,54 +156,54 @@ int Tdi1ItoX(opcode_t opcode, int narg, mdsdsc_t *list[], ************************************************************/ if (!flag) status = tdi_get_data(&omits[1], list[0], &dimen); - else { + else + { status = tdi_get_data(omits, list[0], &dimen); - if (STATUS_OK && dimen.pointer->dtype == DTYPE_WITH_UNITS) { + if (STATUS_OK && dimen.pointer->dtype == DTYPE_WITH_UNITS) + { status = TdiUnits(dimen.pointer, &units MDS_END_ARG); - if - STATUS_OK - status = tdi_get_data(&omits[1], &dimen, &dimen); + if (STATUS_OK) + status = tdi_get_data(&omits[1], &dimen, &dimen); } } - if - STATUS_OK - switch (dimen.pointer->dtype) { - /********************* + if (STATUS_OK) + switch (dimen.pointer->dtype) + { + /********************* They just have a list. *********************/ - default: - k0 = -HUGE; - k1 = HUGE; - pwin = 0; - axis = dimen; - dimen = EMPTY_XD; - status = TdiData(0, &xat0 MDS_END_ARG); - goto plain; - case DTYPE_DIMENSION: - pdim = (mds_dimension_t *)dimen.pointer; - status = TdiEvaluate(pdim->window, &window MDS_END_ARG); - pwin = (mds_window_t *)window.pointer; - if (STATUS_OK && pwin && pwin->dtype == DTYPE_WITH_UNITS) { - status = TdiEvaluate(((mds_with_units_t *)pwin)->data, &tmp MDS_END_ARG); - if - STATUS_OK - status = MdsCopyDxXd((mdsdsc_t *)&tmp, &window); - } - if - STATUS_OK - status = TdiEvaluate(pdim->axis, &axis MDS_END_ARG); - paxis = (mds_range_t *)axis.pointer; - if (STATUS_OK && paxis && paxis->dtype == DTYPE_WITH_UNITS) { - status = TdiEvaluate(((mds_with_units_t *)paxis)->data, &tmp MDS_END_ARG); - if - STATUS_OK - status = MdsCopyDxXd((mdsdsc_t *)&tmp, &axis); + default: + k0 = -HUGE; + k1 = HUGE; + pwin = 0; + axis = dimen; + dimen = EMPTY_XD; + status = TdiData(0, &xat0 MDS_END_ARG); + goto plain; + case DTYPE_DIMENSION: + pdim = (mds_dimension_t *)dimen.pointer; + status = TdiEvaluate(pdim->window, &window MDS_END_ARG); + pwin = (mds_window_t *)window.pointer; + if (STATUS_OK && pwin && pwin->dtype == DTYPE_WITH_UNITS) + { + status = TdiEvaluate(((mds_with_units_t *)pwin)->data, &tmp MDS_END_ARG); + if (STATUS_OK) + status = MdsCopyDxXd((mdsdsc_t *)&tmp, &window); + } + if (STATUS_OK) + status = TdiEvaluate(pdim->axis, &axis MDS_END_ARG); + paxis = (mds_range_t *)axis.pointer; + if (STATUS_OK && paxis && paxis->dtype == DTYPE_WITH_UNITS) + { + status = TdiEvaluate(((mds_with_units_t *)paxis)->data, &tmp MDS_END_ARG); + if (STATUS_OK) + status = MdsCopyDxXd((mdsdsc_t *)&tmp, &axis); + } + paxis = (mds_range_t *)axis.pointer; + pwin = (mds_window_t *)window.pointer; + break; } - paxis = (mds_range_t *)axis.pointer; - pwin = (mds_window_t *)window.pointer; - break; - } if (STATUS_OK && pwin && pwin->dtype == DTYPE_WINDOW) ; else @@ -214,92 +216,94 @@ They just have a list. status = TdiGetLong(pwin->endingidx, &k1); else k1 = HUGE; - if - STATUS_OK { /*bug 2/26/91 include status test both ways */ - if (pwin && pwin->value_at_idx0) - status = TdiData(pwin->value_at_idx0, &xat0 MDS_END_ARG); - else - status = TdiData(0, &xat0 MDS_END_ARG); - } + if (STATUS_OK) + { /*bug 2/26/91 include status test both ways */ + if (pwin && pwin->value_at_idx0) + status = TdiData(pwin->value_at_idx0, &xat0 MDS_END_ARG); + else + status = TdiData(0, &xat0 MDS_END_ARG); + } - if - STATUS_OK { - switch (paxis->dtype) { - case DTYPE_SLOPE: - pslope = (mds_slope_t *)paxis; - paxis = &fake; - fake = fake0; - switch (pslope->ndesc) { - case 3: - fake.ending = pslope->segment[0].ending; - MDS_ATTR_FALLTHROUGH - case 2: - fake.begin = pslope->segment[0].begin; - MDS_ATTR_FALLTHROUGH - case 1: - fake.deltaval = pslope->segment[0].slope; - break; - case 0: - status = TdiINVDTYDSC; - break; - default: - *(mds_function_t *)(fake.begin = (mdsdsc_t *)&vec[0]) = vector0; - *(mds_function_t *)(fake.ending = (mdsdsc_t *)&vec[1]) = vector0; - *(mds_function_t *)(fake.deltaval = (mdsdsc_t *)&vec[2]) = vector0; - nseg = ((pslope->ndesc + 1) / 3); - vec[0].ndesc = (unsigned char)nseg; - vec[1].ndesc = (unsigned char)nseg; - vec[2].ndesc = (unsigned char)nseg; - for (jseg = nseg; --jseg >= 0;) - if ((vec[0].arguments[jseg] = pslope->segment[jseg].begin) == 0) - vec[0].arguments[jseg] = (mdsdsc_t *)&dmbig; - for (jseg = nseg; --jseg >= 0;) - if ((vec[1].arguments[jseg] = pslope->segment[jseg].ending) == 0) - vec[1].arguments[jseg] = (mdsdsc_t *)&dbig; - for (jseg = nseg; --jseg >= 0;) - if ((vec[2].arguments[jseg] = pslope->segment[jseg].slope) == 0) - vec[1].arguments[jseg] = (mdsdsc_t *)&done; - break; - } - if (STATUS_NOT_OK) - break; - /********************* + if (STATUS_OK) + { + switch (paxis->dtype) + { + case DTYPE_SLOPE: + pslope = (mds_slope_t *)paxis; + paxis = &fake; + fake = fake0; + switch (pslope->ndesc) + { + case 3: + fake.ending = pslope->segment[0].ending; + MDS_ATTR_FALLTHROUGH + case 2: + fake.begin = pslope->segment[0].begin; + MDS_ATTR_FALLTHROUGH + case 1: + fake.deltaval = pslope->segment[0].slope; + break; + case 0: + status = TdiINVDTYDSC; + break; + default: + *(mds_function_t *)(fake.begin = (mdsdsc_t *)&vec[0]) = vector0; + *(mds_function_t *)(fake.ending = (mdsdsc_t *)&vec[1]) = vector0; + *(mds_function_t *)(fake.deltaval = (mdsdsc_t *)&vec[2]) = vector0; + nseg = ((pslope->ndesc + 1) / 3); + vec[0].ndesc = (unsigned char)nseg; + vec[1].ndesc = (unsigned char)nseg; + vec[2].ndesc = (unsigned char)nseg; + for (jseg = nseg; --jseg >= 0;) + if ((vec[0].arguments[jseg] = pslope->segment[jseg].begin) == 0) + vec[0].arguments[jseg] = (mdsdsc_t *)&dmbig; + for (jseg = nseg; --jseg >= 0;) + if ((vec[1].arguments[jseg] = pslope->segment[jseg].ending) == 0) + vec[1].arguments[jseg] = (mdsdsc_t *)&dbig; + for (jseg = nseg; --jseg >= 0;) + if ((vec[2].arguments[jseg] = pslope->segment[jseg].slope) == 0) + vec[1].arguments[jseg] = (mdsdsc_t *)&done; + break; + } + if (STATUS_NOT_OK) + break; + /********************* WARNING falls through. *********************/ - MDS_ATTR_FALLTHROUGH - case DTYPE_RANGE: - status = TdiGetArgs(opcode, nran = paxis->ndesc, &paxis->begin, sig, - uni, dat, cats); - nseg = HUGE; - if - STATUS_OK { /*bug 2/26/91 include status set in bracket */ - for (j1 = nran; --j1 >= 0;) - if (dat[j1].pointer->class == CLASS_A) { - jseg = ((mdsdsc_a_t *)dat[j1].pointer)->arsize / - (int)dat[j1].pointer->length; - if (nseg > jseg) - nseg = jseg; - } - if (nseg == HUGE) - nseg = 1; - if (nseg <= 0) - status = TdiNULL_PTR; + MDS_ATTR_FALLTHROUGH + case DTYPE_RANGE: + status = TdiGetArgs(opcode, nran = paxis->ndesc, &paxis->begin, sig, + uni, dat, cats); + nseg = HUGE; + if (STATUS_OK) + { /*bug 2/26/91 include status set in bracket */ + for (j1 = nran; --j1 >= 0;) + if (dat[j1].pointer->class == CLASS_A) + { + jseg = ((mdsdsc_a_t *)dat[j1].pointer)->arsize / + (int)dat[j1].pointer->length; + if (nseg > jseg) + nseg = jseg; } + if (nseg == HUGE) + nseg = 1; + if (nseg <= 0) + status = TdiNULL_PTR; + } - /************************ + /************************ * I_TO_X: combined units. * X_TO_I: no units. ************************/ - if - STATUS_OK + if (STATUS_OK) status = Tdi2Range(nran, uni, dat, cats, 0); - if (flag && units.pointer == 0 && uni[0].pointer && STATUS_OK) - status = MdsCopyDxXd((mdsdsc_t *)&uni[0], &units); - if (STATUS_NOT_OK) - goto firstbad; - tslo = nran > 2 && cats[2].in_dtype != DTYPE_MISSING; + if (flag && units.pointer == 0 && uni[0].pointer && STATUS_OK) + status = MdsCopyDxXd((mdsdsc_t *)&uni[0], &units); + if (STATUS_NOT_OK) + goto firstbad; + tslo = nran > 2 && cats[2].in_dtype != DTYPE_MISSING; - /************************************************************************* + /************************************************************************* * Simple range is best done quickly. * I_TO_X: X = I*delta+xat0. * X_TO_I: I = (X-xat0)/delta. @@ -313,260 +317,266 @@ WARNING falls through. * WARNING need to watch overflow of big_number/small_delta. * WARNING may need more careful rounding. *************************************************************************/ - big_beg = - cats[0].in_dtype == DTYPE_MISSING || - (cats[0].in_cat & TdiCAT_FLOAT && - ROPRAND_TYPED(dat[beg].pointer->dtype, dat[beg].pointer->pointer)); - big_end = cats[1].in_dtype == DTYPE_MISSING || - (cats[1].in_cat & TdiCAT_FLOAT && - ROPRAND_TYPED(dat[end].pointer->dtype, - dat[end].pointer->pointer + - dat[end].pointer->length * (nseg - 1))); - if (nseg == 1) { - dat[beg].pointer->class = CLASS_S; - dat[end].pointer->class = CLASS_S; - if (tslo) - dat[delta].pointer->class = CLASS_S; - if (big_beg && big_end) - goto select; - if (big_beg || big_end) - goto counted; - } - status = TdiCvtArgs(nran, dat, cats); - TdiFaultClear(0); - if - STATUS_OK + big_beg = + cats[0].in_dtype == DTYPE_MISSING || + (cats[0].in_cat & TdiCAT_FLOAT && + ROPRAND_TYPED(dat[beg].pointer->dtype, dat[beg].pointer->pointer)); + big_end = cats[1].in_dtype == DTYPE_MISSING || + (cats[1].in_cat & TdiCAT_FLOAT && + ROPRAND_TYPED(dat[end].pointer->dtype, + dat[end].pointer->pointer + + dat[end].pointer->length * (nseg - 1))); + if (nseg == 1) + { + dat[beg].pointer->class = CLASS_S; + dat[end].pointer->class = CLASS_S; + if (tslo) + dat[delta].pointer->class = CLASS_S; + if (big_beg && big_end) + goto select; + if (big_beg || big_end) + goto counted; + } + status = TdiCvtArgs(nran, dat, cats); + TdiFaultClear(0); + if (STATUS_OK) status = TdiSubtract(dat[end].pointer, dat[beg].pointer, &cnt MDS_END_ARG); - if (tslo && STATUS_OK) - status = TdiDivide(&cnt, dat[delta].pointer, &cnt MDS_END_ARG); - if (!(TdiFaultClear(0) & 1) && STATUS_OK) - status = TdiFixRoprand(&cnt, &dhuge, &cnt); - if - STATUS_OK + if (tslo && STATUS_OK) + status = TdiDivide(&cnt, dat[delta].pointer, &cnt MDS_END_ARG); + if (!(TdiFaultClear(0) & 1) && STATUS_OK) + status = TdiFixRoprand(&cnt, &dhuge, &cnt); + if (STATUS_OK) status = TdiDim(&cnt, &dmone, &cnt MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiMin(&cnt, &dhuge, &cnt MDS_END_ARG); - if (STATUS_OK && cnt.pointer->dtype != DTYPE_L) - status = TdiNint(&cnt, &cnt MDS_END_ARG); + if (STATUS_OK && cnt.pointer->dtype != DTYPE_L) + status = TdiNint(&cnt, &cnt MDS_END_ARG); - /********************************************************* + /********************************************************* * Find segment with value at index 0. Always 0 for nseg=1. * Find smallest kseg so that (beg[kseg+1]-xat0)/delta > 0. * Does not check beg[0], it might be ROPRAND. * We use the kseg-th value to find left, hold it a while. * Missing window assigns first axis point as index 0. *********************************************************/ - counted: - kseg = 0; - if (nseg > 1 || !big_beg) { - if - STATUS_OK + counted: + kseg = 0; + if (nseg > 1 || !big_beg) + { + if (STATUS_OK) status = TdiSubtract(dat[beg].pointer, xat0.pointer, &tmp MDS_END_ARG); - if (tslo && STATUS_OK) - status = TdiDivide(&tmp, dat[delta].pointer, &tmp MDS_END_ARG); - if (!(TdiFaultClear(0) & 1) && STATUS_OK) - status = TdiFixRoprand(&tmp, &dmhuge, &tmp); - } - left = -HUGE; - if (!pwin) - left = 0; /*bug 2/26/91 missing window */ - else if (nseg > 1) { - if - STATUS_OK + if (tslo && STATUS_OK) + status = TdiDivide(&tmp, dat[delta].pointer, &tmp MDS_END_ARG); + if (!(TdiFaultClear(0) & 1) && STATUS_OK) + status = TdiFixRoprand(&tmp, &dmhuge, &tmp); + } + left = -HUGE; + if (!pwin) + left = 0; /*bug 2/26/91 missing window */ + else if (nseg > 1) + { + if (STATUS_OK) status = TdiGt(tmp.pointer, 0, out_ptr MDS_END_ARG); - if - STATUS_OK { - plogical = out_ptr->pointer->pointer; - for (; kseg < nseg - 1 && !*++plogical; ++kseg) - ; - } + if (STATUS_OK) + { + plogical = out_ptr->pointer->pointer; + for (; kseg < nseg - 1 && !*++plogical; ++kseg) + ; } + } - /********************************************************************************************** + /********************************************************************************************** * With index 0 in kseg, what is index at beg? left[kseg] = *floor((beg[kseg]-xat0)/delta[kseg]). Trigger time xat0 implies next *clock is at index 0, thus round down, make more negative. Correct xat0 *for good beg of single segment. **********************************************************************************************/ - if ((kseg > 0 || !big_beg) && STATUS_OK) { - if (pwin) { - if (tmp.pointer->dtype == DTYPE_L) - left = *((int *)tmp.pointer->pointer + kseg); - else { - tst1 = *tmp.pointer; - tst1.class = CLASS_S; - tst1.pointer += tst1.length * kseg; - status = TdiFloor(&tst1, &uni1 MDS_END_ARG); - if - STATUS_OK + if ((kseg > 0 || !big_beg) && STATUS_OK) + { + if (pwin) + { + if (tmp.pointer->dtype == DTYPE_L) + left = *((int *)tmp.pointer->pointer + kseg); + else + { + tst1 = *tmp.pointer; + tst1.class = CLASS_S; + tst1.pointer += tst1.length * kseg; + status = TdiFloor(&tst1, &uni1 MDS_END_ARG); + if (STATUS_OK) status = TdiMax(&uni1, &dmhuge, &tmp MDS_END_ARG); - MdsFree1Dx(&uni1, NULL); - if - STATUS_OK + MdsFree1Dx(&uni1, NULL); + if (STATUS_OK) status = TdiMin(&tmp, &dhuge, &tmp MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(tmp.pointer, &left); - } } - if (kseg == 0 && left > 0) - left = 0; /* 1/7/92 trig before clock, use first time */ - if (nseg == 1) { - if (k0 < left) - k0 = left; - if (left <= -HUGE) - big_beg = 1; - else { - int1 = dk0; - int1.pointer = (char *)&left; - if - STATUS_OK + } + if (kseg == 0 && left > 0) + left = 0; /* 1/7/92 trig before clock, use first time */ + if (nseg == 1) + { + if (k0 < left) + k0 = left; + if (left <= -HUGE) + big_beg = 1; + else + { + int1 = dk0; + int1.pointer = (char *)&left; + if (STATUS_OK) status = MdsCopyDxXd(&int1, &tmp); - if (tslo && STATUS_OK) - status = - TdiMultiply(&tmp, dat[delta].pointer, &tmp MDS_END_ARG); - if - STATUS_OK + if (tslo && STATUS_OK) + status = + TdiMultiply(&tmp, dat[delta].pointer, &tmp MDS_END_ARG); + if (STATUS_OK) status = TdiSubtract(&dat[beg], &tmp, &xat0 MDS_END_ARG); - if (!big_end) - right = left + *(int *)cnt.pointer->pointer; - } + if (!big_end) + right = left + *(int *)cnt.pointer->pointer; } } + } - /****************************************************** + /****************************************************** * Then adjust and accumulate counts. * left = index of first beg, right = index of last end. * If beg[0] undefined, set beg[0]=end[0] with cnt[0]=1. * If both are undefined (nseg==1) xat0 will be used. ******************************************************/ - if (nseg > 1 && STATUS_OK) { - ptest = pcnt = (int *)cnt.pointer->pointer; - for (jseg = kseg; --jseg >= 0;) - left -= *ptest++; /*bug 2/26/91 increment ptest */ - if (k0 < left) - k0 = left; - if (left <= -HUGE) { - big_beg = 1; - right = left + HUGE; - *pcnt = 1; - memcpy(dat[beg].pointer->pointer, dat[end].pointer->pointer, - dat[end].pointer->length); - } else - right = left + *pcnt; + if (nseg > 1 && STATUS_OK) + { + ptest = pcnt = (int *)cnt.pointer->pointer; + for (jseg = kseg; --jseg >= 0;) + left -= *ptest++; /*bug 2/26/91 increment ptest */ + if (k0 < left) + k0 = left; + if (left <= -HUGE) + { + big_beg = 1; + right = left + HUGE; + *pcnt = 1; + memcpy(dat[beg].pointer->pointer, dat[end].pointer->pointer, + dat[end].pointer->length); } + else + right = left + *pcnt; + } - /***************************************************************** + /***************************************************************** When we can't get left side, use right of first segment for limit. *****************************************************************/ - if (kseg == 0 && big_beg && (nseg > 1 || !big_end)) { - if - STATUS_OK { - tst1 = *dat[end].pointer; - tst1.class = CLASS_S; - status = TdiSubtract(&tst1, xat0.pointer, &tmp MDS_END_ARG); - } - if (tslo && STATUS_OK) { - del1 = *dat[delta].pointer; - del1.class = CLASS_S; - status = TdiDivide(&tmp, &del1, &tmp MDS_END_ARG); + if (kseg == 0 && big_beg && (nseg > 1 || !big_end)) + { + if (STATUS_OK) + { + tst1 = *dat[end].pointer; + tst1.class = CLASS_S; + status = TdiSubtract(&tst1, xat0.pointer, &tmp MDS_END_ARG); + } + if (tslo && STATUS_OK) + { + del1 = *dat[delta].pointer; + del1.class = CLASS_S; + status = TdiDivide(&tmp, &del1, &tmp MDS_END_ARG); + } + if (STATUS_OK) + { + if (tmp.pointer->dtype == DTYPE_L) + right = *(int *)tmp.pointer->pointer; + else + { + if (!(TdiFaultClear(0) & 1)) + status = TdiFixRoprand(&tmp, &dhuge, &tmp); + if (STATUS_OK) + status = TdiFloor(&tmp, &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiMax(&tmp, &dmhuge, &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiMin(&tmp, &dhuge, &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiGetLong(&tmp, &right); } - if - STATUS_OK { - if (tmp.pointer->dtype == DTYPE_L) - right = *(int *)tmp.pointer->pointer; - else { - if (!(TdiFaultClear(0) & 1)) - status = TdiFixRoprand(&tmp, &dhuge, &tmp); - if - STATUS_OK - status = TdiFloor(&tmp, &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiMax(&tmp, &dmhuge, &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiMin(&tmp, &dhuge, &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiGetLong(&tmp, &right); - } - } - if (nseg == 1 && right < HUGE) { - int1 = dk0; - int1.pointer = (char *)&right; - if - STATUS_OK + } + if (nseg == 1 && right < HUGE) + { + int1 = dk0; + int1.pointer = (char *)&right; + if (STATUS_OK) status = MdsCopyDxXd(&int1, &tmp); - if (tslo && STATUS_OK) - status = TdiMultiply(&tmp, &del1, &tmp MDS_END_ARG); - if - STATUS_OK + if (tslo && STATUS_OK) + status = TdiMultiply(&tmp, &del1, &tmp MDS_END_ARG); + if (STATUS_OK) status = TdiSubtract(&tst1, &tmp, &xat0 MDS_END_ARG); - } - ++right; } + ++right; + } - /********************************************* + /********************************************* * Set the breakpoints to the sum of counts. * Correct xat0 for good end of single segment. *********************************************/ - if (nseg > 1) { - *pcnt = right - *pcnt; - for (jseg = nseg; --jseg > 0;) - j1 = *++pcnt, *pcnt = right, right += j1; - } - if (!big_end && k1 >= right) - k1 = right - 1; + if (nseg > 1) + { + *pcnt = right - *pcnt; + for (jseg = nseg; --jseg > 0;) + j1 = *++pcnt, *pcnt = right, right += j1; + } + if (!big_end && k1 >= right) + k1 = right - 1; - /******************************* + /******************************* * Bounds for ESHAPE/CULL/EXTEND. * Or see what points they want. * GET_ARGS does not free. *******************************/ - select: - if - STATUS_OK { - if (special) { - int limits[2]; - array_int dlimits = *(array_int *)&duo; - limits[0] = k0; - limits[1] = k1; - dlimits.pointer = limits; - status = MdsCopyDxXd((mdsdsc_t *)&dlimits, out_ptr); - } else if (arg1) { - mds_range_t *rptr = (mds_range_t *)list[1]; - MdsFree1Dx(out_ptr, NULL); - TDI_RANGE_PTRS[0] = &dk0; - TDI_RANGE_PTRS[1] = &dk1; - TDI_RANGE_PTRS[2] = flag ? 0 : dimen.pointer; - /****************************************************** + select: + if (STATUS_OK) + { + if (special) + { + int limits[2]; + array_int dlimits = *(array_int *)&duo; + limits[0] = k0; + limits[1] = k1; + dlimits.pointer = limits; + status = MdsCopyDxXd((mdsdsc_t *)&dlimits, out_ptr); + } + else if (arg1) + { + mds_range_t *rptr = (mds_range_t *)list[1]; + MdsFree1Dx(out_ptr, NULL); + TDI_RANGE_PTRS[0] = &dk0; + TDI_RANGE_PTRS[1] = &dk1; + TDI_RANGE_PTRS[2] = flag ? 0 : dimen.pointer; + /****************************************************** * For subscripts of signals, want range step to be all. ******************************************************/ - if (!flag && (rptr->dtype == DTYPE_RANGE) && - ((rptr->ndesc == 2) || - ((rptr->ndesc == 3) && (rptr->deltaval == 0)))) { - DESCRIPTOR_RANGE(fake_range, 0, 0, 0); - fake_range.begin = rptr->begin; - fake_range.ending = rptr->ending; - fake_range.deltaval = (mdsdsc_t *)&value; - rptr = &fake_range; - status = - TdiGetArgs(opcode, 1, &rptr, &sig1, &uni1, out_ptr, cats); - } else - status = - TdiGetArgs(opcode, 1, &rptr, &sig1, &uni1, out_ptr, cats); - TDI_RANGE_PTRS[0] = keep[0]; - TDI_RANGE_PTRS[1] = keep[1]; - TDI_RANGE_PTRS[2] = keep[2]; - arg1 = cats[0].in_dtype != DTYPE_MISSING; - } else - status = TdiDtypeRange(&dk0, &dk1, out_ptr MDS_END_ARG); + if (!flag && (rptr->dtype == DTYPE_RANGE) && + ((rptr->ndesc == 2) || + ((rptr->ndesc == 3) && (rptr->deltaval == 0)))) + { + DESCRIPTOR_RANGE(fake_range, 0, 0, 0); + fake_range.begin = rptr->begin; + fake_range.ending = rptr->ending; + fake_range.deltaval = (mdsdsc_t *)&value; + rptr = &fake_range; + status = + TdiGetArgs(opcode, 1, &rptr, &sig1, &uni1, out_ptr, cats); + } + else + status = + TdiGetArgs(opcode, 1, &rptr, &sig1, &uni1, out_ptr, cats); + TDI_RANGE_PTRS[0] = keep[0]; + TDI_RANGE_PTRS[1] = keep[1]; + TDI_RANGE_PTRS[2] = keep[2]; + arg1 = cats[0].in_dtype != DTYPE_MISSING; + } + else + status = TdiDtypeRange(&dk0, &dk1, out_ptr MDS_END_ARG); - /************************************************************ + /************************************************************ * Hinged, piecewise-linear segments with interpolation between end *and next beg. I = (X-end[0])/delta[0] + sumcnt[1]-1 *X<=end[0] (X-beg[1])/(beg[1]-end[0]) + sumcnt[1] X>end[0] @@ -580,7 +590,7 @@ When we can't get left side, use right of first segment for limit. * ... ************************************************************/ - /****************************************************************** + /****************************************************************** * Approximation neglecting between segment code: * I_TO_X: X = (I-cnt[j])*delta[j]+beg[j] for cnt[j] <= I < cnt[j+1] * X = I*delta[j]+xat0, with xat0 = beg[j]-cnt[j]*delta[j] @@ -590,76 +600,77 @@ When we can't get left side, use right of first segment for limit. * For multisegment, limit between-segment to its end. 11-Apr-91 *removed 22-may-91 for roprand ******************************************************************/ - } - if (nseg > 1 && (flag || arg1)) { - if - STATUS_OK + } + if (nseg > 1 && (flag || arg1)) + { + if (STATUS_OK) status = TdiBsearch(out_ptr->pointer, flag ? cnt.pointer : dat[beg].pointer, &done, &tmp MDS_END_ARG); - if (STATUS_OK && dat[beg].pointer->class == CLASS_A) - status = TdiMap(&dat[beg], tmp.pointer, &dat[beg] MDS_END_ARG); - if (STATUS_OK && dat[end].pointer->class == CLASS_A) - status = TdiMap(&dat[end], tmp.pointer, &dat[end] MDS_END_ARG); - if (STATUS_OK && cnt.pointer->class == CLASS_A) - status = TdiMap(&cnt, tmp.pointer, &cnt MDS_END_ARG); - if (tslo && STATUS_OK && dat[delta].pointer->class == CLASS_A) - status = TdiMap(&dat[delta], &tmp, &dat[delta] MDS_END_ARG); - if (tslo && STATUS_OK) - status = TdiMultiply(&cnt, dat[delta].pointer, &cnt MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK && dat[beg].pointer->class == CLASS_A) + status = TdiMap(&dat[beg], tmp.pointer, &dat[beg] MDS_END_ARG); + if (STATUS_OK && dat[end].pointer->class == CLASS_A) + status = TdiMap(&dat[end], tmp.pointer, &dat[end] MDS_END_ARG); + if (STATUS_OK && cnt.pointer->class == CLASS_A) + status = TdiMap(&cnt, tmp.pointer, &cnt MDS_END_ARG); + if (tslo && STATUS_OK && dat[delta].pointer->class == CLASS_A) + status = TdiMap(&dat[delta], &tmp, &dat[delta] MDS_END_ARG); + if (tslo && STATUS_OK) + status = TdiMultiply(&cnt, dat[delta].pointer, &cnt MDS_END_ARG); + if (STATUS_OK) status = TdiSubtract(&dat[beg], &cnt, &xat0 MDS_END_ARG); - } + } - if (flag) { - if (tslo && STATUS_OK) - status = TdiMultiply(out_ptr, &dat[delta], out_ptr MDS_END_ARG); - if - STATUS_OK + if (flag) + { + if (tslo && STATUS_OK) + status = TdiMultiply(out_ptr, &dat[delta], out_ptr MDS_END_ARG); + if (STATUS_OK) status = TdiAdd(out_ptr, &xat0, out_ptr MDS_END_ARG); - /* if (nseg > 1 && STATUS_OK) status = TdiMin(out_ptr, &dat[end], + /* if (nseg > 1 && STATUS_OK) status = TdiMin(out_ptr, &dat[end], * out_ptr MDS_END_ARG); */ - } else if (arg1) { - /* if (nseg > 1 && STATUS_OK) status = TdiMin(out_ptr, &dat[end], + } + else if (arg1) + { + /* if (nseg > 1 && STATUS_OK) status = TdiMin(out_ptr, &dat[end], * out_ptr MDS_END_ARG); */ - if - STATUS_OK + if (STATUS_OK) status = TdiSubtract(out_ptr, &xat0, out_ptr MDS_END_ARG); - if (tslo && STATUS_OK) - status = TdiDivide(out_ptr, &dat[delta], out_ptr MDS_END_ARG); - } - MdsFree1Dx(&cnt, NULL); - MdsFree1Dx(&uni1, NULL); + if (tslo && STATUS_OK) + status = TdiDivide(out_ptr, &dat[delta], out_ptr MDS_END_ARG); + } + MdsFree1Dx(&cnt, NULL); + MdsFree1Dx(&uni1, NULL); - /******************************************************************* + /******************************************************************* For full range, set bounds if lower is nonzero. For given list, order of operations is must preserve original shape. MAP preserves shape of second arg and single segment uses scalars. *******************************************************************/ - if (STATUS_OK && k0 != 0 && !arg1 && !special) { - DESCRIPTOR_RANGE(range, 0, 0, 0); - range.ndesc = 2; - range.begin = &dk0; - range.ending = &dk1; - status = TdiSetRange(&range, out_ptr, out_ptr MDS_END_ARG); - } + if (STATUS_OK && k0 != 0 && !arg1 && !special) + { + DESCRIPTOR_RANGE(range, 0, 0, 0); + range.ndesc = 2; + range.begin = &dk0; + range.ending = &dk1; + status = TdiSetRange(&range, out_ptr, out_ptr MDS_END_ARG); + } - /******************************** + /******************************** Embed result in units and signal. ********************************/ - if - STATUS_OK + if (STATUS_OK) status = TdiMasterData(narg > 1, &sig1, &units, &cmode, out_ptr); - MdsFree1Dx(&sig1, NULL); - firstbad: - for (; --nran >= 0;) { - MdsFree1Dx(&sig[nran], NULL); - MdsFree1Dx(&uni[nran], NULL); - MdsFree1Dx(&dat[nran], NULL); - } - break; - /************************************** + MdsFree1Dx(&sig1, NULL); + firstbad: + for (; --nran >= 0;) + { + MdsFree1Dx(&sig[nran], NULL); + MdsFree1Dx(&uni[nran], NULL); + MdsFree1Dx(&dat[nran], NULL); + } + break; + /************************************** General list of values for a dimension. I_TO_X: just map it, add xat0. X_TO_I: subtract xat0, sort, search, and map. @@ -668,108 +679,119 @@ Assumes one-dimensional axis. Cull with range doesn't work for text because it generates range. **************************************/ - default: - plain: - status = TdiData(&axis, &axis MDS_END_ARG); - paxis = (mds_range_t *)axis.pointer; - pmode = paxis->dtype == DTYPE_T ? NULL : &dmone; - j1 = paxis->length; - if - STATUS_OK + default: + plain: + status = TdiData(&axis, &axis MDS_END_ARG); + paxis = (mds_range_t *)axis.pointer; + pmode = paxis->dtype == DTYPE_T ? NULL : &dmone; + j1 = paxis->length; + if (STATUS_OK) status = TdiSort(paxis, &tmp MDS_END_ARG); - if ((pwin || flag || arg1) && STATUS_OK) { - status = TdiMap(paxis, tmp.pointer, &window MDS_END_ARG); - } - if (pwin) { - if - STATUS_OK + if ((pwin || flag || arg1) && STATUS_OK) + { + status = TdiMap(paxis, tmp.pointer, &window MDS_END_ARG); + } + if (pwin) + { + if (STATUS_OK) status = TdiBsearch(&xat0, paxis, pmode, &xat0 MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiGetLong(&xat0, &left); - if - STATUS_OK { - N_ELEMENTS(paxis, right); - left = -left; - right += left - 1; - if (k0 < left) - k0 = left; - if (k1 > right) - k1 = right; - } - } else { - if - STATUS_OK + if (STATUS_OK) + { + N_ELEMENTS(paxis, right); + left = -left; + right += left - 1; + if (k0 < left) + k0 = left; + if (k1 > right) + k1 = right; + } + } + else + { + if (STATUS_OK) status = TdiLbound(axis.pointer, &dk0 MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiUbound(axis.pointer, &dk1 MDS_END_ARG); + } + if (STATUS_OK) + { + if (special) + { + if (flag) + { + unsigned short num = (unsigned short)j1; + status = MdsGet1DxA((mdsdsc_a_t *)&duo, &num, &paxis->dtype, + out_ptr); + if (STATUS_OK) + { + memcpy(out_ptr->pointer->pointer, + (char *)window.pointer->pointer, j1); + memcpy(out_ptr->pointer->pointer + j1, + (char *)window.pointer->pointer + j1 * (k1 - k0), + j1); + } + } + else + { + int limits[2]; + array_int dlimits = *(array_int *)&duo; + limits[0] = k0; + limits[1] = k1; + dlimits.pointer = limits; + status = MdsCopyDxXd((mdsdsc_t *)&dlimits, out_ptr); + } + } + else if (!arg1) + { + if (flag) + status = MdsCopyDxXd((mdsdsc_t *)&axis, + out_ptr); /*unsorted values */ + else + status = TdiDtypeRange(&dk0, &dk1, + out_ptr MDS_END_ARG); /*plain indexes */ } - if - STATUS_OK { - if (special) { - if (flag) { - unsigned short num = (unsigned short)j1; - status = MdsGet1DxA((mdsdsc_a_t *)&duo, &num, &paxis->dtype, - out_ptr); - if - STATUS_OK { - memcpy(out_ptr->pointer->pointer, - (char *)window.pointer->pointer, j1); - memcpy(out_ptr->pointer->pointer + j1, - (char *)window.pointer->pointer + j1 * (k1 - k0), - j1); - } - } else { - int limits[2]; - array_int dlimits = *(array_int *)&duo; - limits[0] = k0; - limits[1] = k1; - dlimits.pointer = limits; - status = MdsCopyDxXd((mdsdsc_t *)&dlimits, out_ptr); - } - } else if (!arg1) { - if (flag) - status = MdsCopyDxXd((mdsdsc_t *)&axis, - out_ptr); /*unsorted values */ - else - status = TdiDtypeRange(&dk0, &dk1, - out_ptr MDS_END_ARG); /*plain indexes */ - } else { - if (flag) { - if (k0 != 0 && pwin) { - status = TdiSubtract( - list[1], &dk0, - &tmp MDS_END_ARG); /*offset of xat0 or array bound */ - status = TdiMap(&axis, &tmp, - out_ptr MDS_END_ARG); /*straight mapping */ - } else - status = TdiMap(&axis, list[1], - out_ptr MDS_END_ARG); /*straight mapping */ - } else { - status = TdiBsearch(list[1], &window, pmode, - out_ptr MDS_END_ARG); /*lookup */ - if (k0 != 0 && STATUS_OK) - status = - TdiAdd(out_ptr, &dk0, out_ptr MDS_END_ARG); /*offset */ - if - STATUS_OK - status = - TdiMap(&tmp, out_ptr, out_ptr MDS_END_ARG); /*unorder */ - } + else + { + if (flag) + { + if (k0 != 0 && pwin) + { + status = TdiSubtract( + list[1], &dk0, + &tmp MDS_END_ARG); /*offset of xat0 or array bound */ + status = TdiMap(&axis, &tmp, + out_ptr MDS_END_ARG); /*straight mapping */ } + else + status = TdiMap(&axis, list[1], + out_ptr MDS_END_ARG); /*straight mapping */ + } + else + { + status = TdiBsearch(list[1], &window, pmode, + out_ptr MDS_END_ARG); /*lookup */ + if (k0 != 0 && STATUS_OK) + status = + TdiAdd(out_ptr, &dk0, out_ptr MDS_END_ARG); /*offset */ + if (STATUS_OK) + status = + TdiMap(&tmp, out_ptr, out_ptr MDS_END_ARG); /*unorder */ } - if (STATUS_OK && k0 != 0 && out_ptr != NULL && - out_ptr->pointer != NULL && out_ptr->pointer->class == CLASS_A) { - DESCRIPTOR_RANGE(range, 0, 0, 0); - status = TdiSetRange(&range, out_ptr, out_ptr MDS_END_ARG); } - if - STATUS_OK - status = TdiMasterData(0, &sig1, &units, &cmode, out_ptr); - break; } + if (STATUS_OK && k0 != 0 && out_ptr != NULL && + out_ptr->pointer != NULL && out_ptr->pointer->class == CLASS_A) + { + DESCRIPTOR_RANGE(range, 0, 0, 0); + status = TdiSetRange(&range, out_ptr, out_ptr MDS_END_ARG); + } + if (STATUS_OK) + status = TdiMasterData(0, &sig1, &units, &cmode, out_ptr); + break; } + } MdsFree1Dx(&tmp, NULL); MdsFree1Dx(&units, NULL); MdsFree1Dx(&xat0, NULL); diff --git a/tdishr/TdiMakeFunctionTable.c b/tdishr/TdiMakeFunctionTable.c index 267ed90c42..4c7e1fdf6e 100644 --- a/tdishr/TdiMakeFunctionTable.c +++ b/tdishr/TdiMakeFunctionTable.c @@ -35,7 +35,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #define COM -#define OPC(name, builtin, f1, f2, f3, ...) \ +#define OPC(name, builtin, f1, f2, f3, ...) \ extern int Tdi1##f1(), Tdi2##f2(), Tdi3##f3(); #include "opcbuiltins.h" #undef OPC @@ -69,9 +69,9 @@ YY=highest. #include "tdiyacc.h" const struct TdiFunctionStruct TdiRefFunction[] = { -#define OPC(name, builtin, f1, f2, f3, i1, i2, o1, o2, m1, m2, token) \ - {#builtin, &Tdi1##f1, &Tdi2##f2, &Tdi3##f3, DTYPE_##i1, DTYPE_##i2, \ - DTYPE_##o1, DTYPE_##o2, m1, m2, LEX_##token}, +#define OPC(name, builtin, f1, f2, f3, i1, i2, o1, o2, m1, m2, token) \ + {#builtin, &Tdi1##f1, &Tdi2##f2, &Tdi3##f3, DTYPE_##i1, DTYPE_##i2, \ + DTYPE_##o1, DTYPE_##o2, m1, m2, LEX_##token}, #include "opcbuiltins.h" #undef OPC {0}}; diff --git a/tdishr/TdiMasterData.c b/tdishr/TdiMasterData.c index b78305e4c8..cccb4f09e1 100644 --- a/tdishr/TdiMasterData.c +++ b/tdishr/TdiMasterData.c @@ -44,7 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. int TdiMasterData(int nsig, struct descriptor_xd sig[1], struct descriptor_xd uni[1], int *cmode_ptr, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *pdu = uni[0].pointer; int cmode = -1, j; @@ -58,8 +59,10 @@ int TdiMasterData(int nsig, struct descriptor_xd sig[1], cmode = unsignaled, +n for signal *************************************************/ for (j = 0; j < nsig; j++) - if (sig[j].pointer) { - if (cmode >= 0) { + if (sig[j].pointer) + { + if (cmode >= 0) + { cmode = -1; break; } @@ -70,7 +73,8 @@ int TdiMasterData(int nsig, struct descriptor_xd sig[1], /*************************************** If we have a signal, embed units or data. ***************************************/ - if (cmode >= 0 && cmode < nsig) { + if (cmode >= 0 && cmode < nsig) + { EMPTYXD(tmp); struct descriptor_signal *sig_ptr = (struct descriptor_signal *)sig[cmode].pointer; @@ -81,18 +85,22 @@ int TdiMasterData(int nsig, struct descriptor_xd sig[1], /************************************ If we have units, embed data in them. ************************************/ - if (pdu) { + if (pdu) + { wu.data = out_ptr->pointer; wu.units = pdu; sig_ptr->data = (struct descriptor *)&wu; - } else + } + else sig_ptr->data = out_ptr->pointer; status = MdsCopyDxXd((struct descriptor *)sig_ptr, &tmp); sig_ptr->data = keep_ptr; sig_ptr->raw = raw_ptr; MdsFree1Dx(out_ptr, NULL); *out_ptr = tmp; - } else if (pdu) { + } + else if (pdu) + { EMPTYXD(tmp); DESCRIPTOR_WITH_UNITS(wu, 0, 0); wu.data = out_ptr->pointer; diff --git a/tdishr/TdiMath1.c b/tdishr/TdiMath1.c index 611c760054..c70f59bb96 100644 --- a/tdishr/TdiMath1.c +++ b/tdishr/TdiMath1.c @@ -70,107 +70,117 @@ static const int roprand = 0x8000; #define radians_to_degrees 57.295778 #define degrees_to_radians 0.017453293 -#define SetupArgs \ - struct descriptor_a *ina = (struct descriptor_a *)in; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina->arsize / ina->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ +#define SetupArgs \ + struct descriptor_a *ina = (struct descriptor_a *)in; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina->arsize / ina->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ } -#define Operate(type, dtype, function) \ - { \ - type *inp = (type *)in->pointer; \ - type *outp = (type *)out->pointer; \ - double in; \ - double ans; \ - while (nout--) { \ - errno = 0; \ - if (CvtConvertFloat(inp++, dtype, &in, DTYPE_NATIVE_DOUBLE, 0)) \ - ans = function(in); \ - else \ - errno = -1; \ - if (errno) \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - else \ - CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - } \ - break; \ +#define Operate(type, dtype, function) \ + { \ + type *inp = (type *)in->pointer; \ + type *outp = (type *)out->pointer; \ + double in; \ + double ans; \ + while (nout--) \ + { \ + errno = 0; \ + if (CvtConvertFloat(inp++, dtype, &in, DTYPE_NATIVE_DOUBLE, 0)) \ + ans = function(in); \ + else \ + errno = -1; \ + if (errno) \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + else \ + CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + } \ + break; \ } -#define OperateC2C(type, dtype, function) \ - { \ - type *inp = (type *)in->pointer; \ - type *outp = (type *)out->pointer; \ - double in[2]; \ - double ans[2]; \ - while (nout--) { \ - errno = 0; \ - if (CvtConvertFloat(&inp[0], dtype, &in[0], DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&inp[1], dtype, &in[1], DTYPE_NATIVE_DOUBLE, 0)) \ - function(in, ans); \ - else \ - errno = -1; \ - if (errno) { \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - } else { \ - CvtConvertFloat(&ans[0], DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - CvtConvertFloat(&ans[1], DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - } \ - inp += 2; \ - } \ - break; \ +#define OperateC2C(type, dtype, function) \ + { \ + type *inp = (type *)in->pointer; \ + type *outp = (type *)out->pointer; \ + double in[2]; \ + double ans[2]; \ + while (nout--) \ + { \ + errno = 0; \ + if (CvtConvertFloat(&inp[0], dtype, &in[0], DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&inp[1], dtype, &in[1], DTYPE_NATIVE_DOUBLE, 0)) \ + function(in, ans); \ + else \ + errno = -1; \ + if (errno) \ + { \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + } \ + else \ + { \ + CvtConvertFloat(&ans[0], DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + CvtConvertFloat(&ans[1], DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + } \ + inp += 2; \ + } \ + break; \ } -#define OperateC2S(type, dtype, function) \ - { \ - type *inp = (type *)in->pointer; \ - type *outp = (type *)out->pointer; \ - double in[2]; \ - double ans; \ - while (nout--) { \ - errno = 0; \ - if (CvtConvertFloat(&inp[0], dtype, &in[0], DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(&inp[1], dtype, &in[1], DTYPE_NATIVE_DOUBLE, 0)) \ - ans = function(in[1], in[0]); \ - else \ - errno = -1; \ - if (errno) \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ - else \ - CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - inp += 2; \ - } \ - break; \ +#define OperateC2S(type, dtype, function) \ + { \ + type *inp = (type *)in->pointer; \ + type *outp = (type *)out->pointer; \ + double in[2]; \ + double ans; \ + while (nout--) \ + { \ + errno = 0; \ + if (CvtConvertFloat(&inp[0], dtype, &in[0], DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(&inp[1], dtype, &in[1], DTYPE_NATIVE_DOUBLE, 0)) \ + ans = function(in[1], in[0]); \ + else \ + errno = -1; \ + if (errno) \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ + else \ + CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + inp += 2; \ + } \ + break; \ } #define mathsingle(name, function) \ - int Tdi3##name(struct descriptor *in, struct descriptor *out) { \ - SetupArgs switch (in->dtype) { \ + int Tdi3##name(struct descriptor *in, struct descriptor *out) \ + { \ + SetupArgs switch (in->dtype) \ + { \ case DTYPE_F: \ Operate(float, DTYPE_F, function) case DTYPE_FS \ : Operate(float, DTYPE_FS, function) case DTYPE_G \ @@ -183,8 +193,10 @@ static const int roprand = 0x8000; #define mathsinglewithkind(name, function) \ int Tdi3##name(struct descriptor *in, struct descriptor *kind, \ - struct descriptor *out) { \ - SetupArgs switch (in->dtype) { \ + struct descriptor *out) \ + { \ + SetupArgs switch (in->dtype) \ + { \ case DTYPE_F: \ Operate(float, DTYPE_F, function) case DTYPE_FS \ : Operate(float, DTYPE_FS, function) case DTYPE_G \ @@ -195,40 +207,45 @@ static const int roprand = 0x8000; return kind ? 1 : 1; \ } -#define mathboth(name, function) \ - int Tdi3##name(struct descriptor *in, struct descriptor *out) { \ - SetupArgs switch (in->dtype) { \ - case DTYPE_F: \ - Operate(float, DTYPE_F, function) case DTYPE_FS \ - : Operate(float, DTYPE_FS, function) case DTYPE_G \ - : Operate(double, DTYPE_G, function) case DTYPE_D \ - : Operate(double, DTYPE_D, function) case DTYPE_FT \ - : Operate(double, DTYPE_FT, function) case DTYPE_FC \ - : Operate(float, DTYPE_F, function) case DTYPE_FSC \ - : OperateC2C(float, DTYPE_FS, function##_complex) case DTYPE_GC \ - : OperateC2C(double, DTYPE_G, function##_complex) case DTYPE_DC \ - : OperateC2C(double, DTYPE_D, function##_complex) case DTYPE_FTC \ - : OperateC2C(double, DTYPE_FT, function##_complex) default \ - : return TdiINVDTYDSC; \ - } \ - return 1; \ +#define mathboth(name, function) \ + int Tdi3##name(struct descriptor *in, struct descriptor *out) \ + { \ + SetupArgs switch (in->dtype) \ + { \ + case DTYPE_F: \ + Operate(float, DTYPE_F, function) case DTYPE_FS \ + : Operate(float, DTYPE_FS, function) case DTYPE_G \ + : Operate(double, DTYPE_G, function) case DTYPE_D \ + : Operate(double, DTYPE_D, function) case DTYPE_FT \ + : Operate(double, DTYPE_FT, function) case DTYPE_FC \ + : Operate(float, DTYPE_F, function) case DTYPE_FSC \ + : OperateC2C(float, DTYPE_FS, function##_complex) case DTYPE_GC \ + : OperateC2C(double, DTYPE_G, function##_complex) case DTYPE_DC \ + : OperateC2C(double, DTYPE_D, function##_complex) case DTYPE_FTC \ + : OperateC2C(double, DTYPE_FT, function##_complex) default \ + : return TdiINVDTYDSC; \ + } \ + return 1; \ } -#define mathcomplex(name, function) \ - int Tdi3##name(struct descriptor *in, struct descriptor *out) { \ - SetupArgs switch (in->dtype) { \ - case DTYPE_FC: \ - OperateC2S(float, DTYPE_F, function) case DTYPE_FSC \ - : OperateC2S(float, DTYPE_FS, function) case DTYPE_GC \ - : OperateC2S(double, DTYPE_G, function) case DTYPE_DC \ - : OperateC2S(double, DTYPE_D, function) case DTYPE_FTC \ - : OperateC2S(double, DTYPE_FT, function) default \ - : return TdiINVDTYDSC; \ - } \ - return 1; \ +#define mathcomplex(name, function) \ + int Tdi3##name(struct descriptor *in, struct descriptor *out) \ + { \ + SetupArgs switch (in->dtype) \ + { \ + case DTYPE_FC: \ + OperateC2S(float, DTYPE_F, function) case DTYPE_FSC \ + : OperateC2S(float, DTYPE_FS, function) case DTYPE_GC \ + : OperateC2S(double, DTYPE_G, function) case DTYPE_DC \ + : OperateC2S(double, DTYPE_D, function) case DTYPE_FTC \ + : OperateC2S(double, DTYPE_FT, function) default \ + : return TdiINVDTYDSC; \ + } \ + return 1; \ } -static double anint(double val) { +static double anint(double val) +{ int tmp; val += (val > 0.0) ? .5 : -.5; tmp = (int)val; @@ -237,26 +254,30 @@ static double anint(double val) { static double trunc_Static(double val) { return (double)((int)val); } -static void cos_complex(double *in, double *out) { +static void cos_complex(double *in, double *out) +{ out[0] = cos(in[0]) * cosh(in[1]); out[1] = -sin(in[0]) * sinh(in[1]); return; } -static void sin_complex(double *in, double *out) { +static void sin_complex(double *in, double *out) +{ out[0] = sin(in[0]) * cosh(in[1]); out[1] = cos(in[0]) * sinh(in[1]); return; } -static void exp_complex(double *in, double *out) { +static void exp_complex(double *in, double *out) +{ out[0] = exp(in[0]); out[1] = out[0] * sin(in[1]); out[0] = out[0] * cos(in[1]); return; } -static double cabs_d(double in1, double in2) { +static double cabs_d(double in1, double in2) +{ double x = (in1 > 0) ? in1 : -in1; double y = (in2 > 0) ? in2 : -in2; if (x == 0.0) @@ -269,15 +290,20 @@ static double cabs_d(double in1, double in2) { return y * sqrt(1 + pow((x / y), 2.0)); } -static void sqrt_complex(double *in, double *out) { - if (in[0] == (double)0.0 && in[1] == (double)0.0) { +static void sqrt_complex(double *in, double *out) +{ + if (in[0] == (double)0.0 && in[1] == (double)0.0) + { out[0] = (double)0.0; out[1] = (double)0.0; - } else { + } + else + { out[0] = sqrt((fabs(in[0]) + cabs_d(in[0], in[1])) * .5); if (in[0] > 0.0) out[1] = in[1] / (out[0] + out[0]); - else { + else + { out[1] = (in[1] < 0.0) ? -out[0] : out[0]; out[0] = in[1] / (out[1] + out[1]); } @@ -285,7 +311,8 @@ static void sqrt_complex(double *in, double *out) { return; } -static void log_complex(double *in, double *out) { +static void log_complex(double *in, double *out) +{ double theta = 0; if (in[0] > 0.0) theta = 0.0; @@ -293,15 +320,20 @@ static void log_complex(double *in, double *out) { theta = M_PI; else if (in[0] < 0.0) theta = -M_PI; - else if (in[0] == 0 && in[1] == 0) { + else if (in[0] == 0 && in[1] == 0) + { out[0] = 0.0; out[1] = 0.0; return; - } else if (in[0] == 0.0 && in[1] > 0.0) { + } + else if (in[0] == 0.0 && in[1] > 0.0) + { out[0] = log(in[1]); out[1] = M_PI_2; return; - } else if (in[0] == 0.0) { + } + else if (in[0] == 0.0) + { out[0] = log(fabs(in[1])); out[1] = -M_PI_2; return; @@ -325,11 +357,13 @@ static double sind_Static(double in) { return sin(degrees_to_radians * in); } static double tand_Static(double in) { return tan(degrees_to_radians * in); } -static double atand2_Static(double in1, double in2) { +static double atand2_Static(double in1, double in2) +{ return radians_to_degrees * atan2(in1, in2); } -static double atanh_Static(double in) { +static double atanh_Static(double in) +{ double ans; if (in <= -1.0 || in >= 1.) CvtConvertFloat(&roprand, DTYPE_F, &ans, DTYPE_NATIVE_DOUBLE, 0); diff --git a/tdishr/TdiMath2.c b/tdishr/TdiMath2.c index e813e629b3..bea8dfade4 100644 --- a/tdishr/TdiMath2.c +++ b/tdishr/TdiMath2.c @@ -74,80 +74,89 @@ extern void DoubleToWideInt(); const double radians_to_degrees = 180. / M_PI; -#define SetupArgs \ - struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ - struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ - struct descriptor_a *outa = (struct descriptor_a *)out; \ - int scalars = 0; \ - int nout; \ - switch (out->class) { \ - case CLASS_S: \ - case CLASS_D: \ - nout = 1; \ - break; \ - case CLASS_A: \ - nout = outa->arsize / outa->length; \ - if (nout == 0) \ - return 1; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in1->class) { \ - case CLASS_S: \ - case CLASS_D: \ - scalars |= 1; \ - break; \ - case CLASS_A: \ - if (ina1->arsize / ina1->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ - } \ - switch (in2->class) { \ - case CLASS_S: \ - case CLASS_D: \ - if (scalars && (nout > 1)) \ - return TdiINV_SIZE; \ - scalars |= 2; \ - break; \ - case CLASS_A: \ - if (ina2->arsize / ina2->length < (unsigned int)nout) \ - return TdiINV_SIZE; \ - break; \ - default: \ - return TdiINVCLADSC; \ +#define SetupArgs \ + struct descriptor_a *ina1 = (struct descriptor_a *)in1; \ + struct descriptor_a *ina2 = (struct descriptor_a *)in2; \ + struct descriptor_a *outa = (struct descriptor_a *)out; \ + int scalars = 0; \ + int nout; \ + switch (out->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + nout = 1; \ + break; \ + case CLASS_A: \ + nout = outa->arsize / outa->length; \ + if (nout == 0) \ + return 1; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in1->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + scalars |= 1; \ + break; \ + case CLASS_A: \ + if (ina1->arsize / ina1->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ + } \ + switch (in2->class) \ + { \ + case CLASS_S: \ + case CLASS_D: \ + if (scalars && (nout > 1)) \ + return TdiINV_SIZE; \ + scalars |= 2; \ + break; \ + case CLASS_A: \ + if (ina2->arsize / ina2->length < (unsigned int)nout) \ + return TdiINV_SIZE; \ + break; \ + default: \ + return TdiINVCLADSC; \ } -#define Operate(type, operator) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) \ - *outp++ = (type)(*in1p++ operator*in2p++); \ - break; \ - case 1: { \ - type scalar = *in1p; \ - while (nout--) \ - *outp++ = (type)(scalar operator*in2p++); \ - } break; \ - case 2: { \ - type scalar = *in2p; \ - while (nout--) \ - *outp++ = (type)(*in1p++ operator scalar); \ - } break; \ - } \ - break; \ +#define Operate(type, operator) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + *outp++ = (type)(*in1p++ operator*in2p++); \ + break; \ + case 1: \ + { \ + type scalar = *in1p; \ + while (nout--) \ + *outp++ = (type)(scalar operator*in2p++); \ + } \ + break; \ + case 2: \ + { \ + type scalar = *in2p; \ + while (nout--) \ + *outp++ = (type)(*in1p++ operator scalar); \ + } \ + break; \ + } \ + break; \ } static const int roprand = 0x8000; -static inline double mod_float(double x, double m) { +static inline double mod_float(double x, double m) +{ if (m == 0.0) return x; double intpart; @@ -155,80 +164,90 @@ static inline double mod_float(double x, double m) { return x - intpart * m; } -#define OperateFloatOne(dtype, routine, p1, p2) \ - { \ - double a, b, ans; \ - if (CvtConvertFloat(p1, dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ - CvtConvertFloat(p2, dtype, &b, DTYPE_NATIVE_DOUBLE, 0)) { \ - ans = routine(a, b); \ - CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ - } else \ - CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ +#define OperateFloatOne(dtype, routine, p1, p2) \ + { \ + double a, b, ans; \ + if (CvtConvertFloat(p1, dtype, &a, DTYPE_NATIVE_DOUBLE, 0) && \ + CvtConvertFloat(p2, dtype, &b, DTYPE_NATIVE_DOUBLE, 0)) \ + { \ + ans = routine(a, b); \ + CvtConvertFloat(&ans, DTYPE_NATIVE_DOUBLE, outp++, dtype, 0); \ + } \ + else \ + CvtConvertFloat(&roprand, DTYPE_F, outp++, dtype, 0); \ } -#define OperateFloat(type, dtype, routine) \ - { \ - type *in1p = (type *)in1->pointer; \ - type *in2p = (type *)in2->pointer; \ - type *outp = (type *)out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) \ - OperateFloatOne(dtype, routine, in1p++, in2p++) break; \ - case 1: \ - while (nout--) \ - OperateFloatOne(dtype, routine, in1p, in2p++) break; \ - case 2: \ - while (nout--) \ - OperateFloatOne(dtype, routine, in1p++, in2p) break; \ - } \ - break; \ +#define OperateFloat(type, dtype, routine) \ + { \ + type *in1p = (type *)in1->pointer; \ + type *in2p = (type *)in2->pointer; \ + type *outp = (type *)out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + OperateFloatOne(dtype, routine, in1p++, in2p++) break; \ + case 1: \ + while (nout--) \ + OperateFloatOne(dtype, routine, in1p, in2p++) break; \ + case 2: \ + while (nout--) \ + OperateFloatOne(dtype, routine, in1p++, in2p) break; \ + } \ + break; \ } -static void mod_bin(int size, int is_signed, char *in1, char *in2, char *out) { +static void mod_bin(int size, int is_signed, char *in1, char *in2, char *out) +{ double in2_d = WideIntToDouble(in2, size / sizeof(int), is_signed); double in1_d = WideIntToDouble(in1, size / sizeof(int), is_signed); double ans = mod_float(in1_d, in2_d); DoubleToWideInt(&ans, size / sizeof(int), out); } -#define OperateBin(size, is_signed, routine) \ - { \ - char *in1p = in1->pointer; \ - char *in2p = in2->pointer; \ - char *outp = out->pointer; \ - switch (scalars) { \ - case 0: \ - case 3: \ - while (nout--) { \ - routine(size, is_signed, in1p, in2p, outp); \ - in1p += size; \ - in2p += size; \ - outp += size; \ - } \ - break; \ - case 1: \ - while (nout--) { \ - routine(size, is_signed, in1p, in2p, outp); \ - in2p += size; \ - outp += size; \ - } \ - break; \ - case 2: \ - while (nout--) { \ - routine(size, is_signed, in1p, in2p, outp); \ - in1p += size; \ - outp += size; \ - } \ - break; \ - } \ - break; \ +#define OperateBin(size, is_signed, routine) \ + { \ + char *in1p = in1->pointer; \ + char *in2p = in2->pointer; \ + char *outp = out->pointer; \ + switch (scalars) \ + { \ + case 0: \ + case 3: \ + while (nout--) \ + { \ + routine(size, is_signed, in1p, in2p, outp); \ + in1p += size; \ + in2p += size; \ + outp += size; \ + } \ + break; \ + case 1: \ + while (nout--) \ + { \ + routine(size, is_signed, in1p, in2p, outp); \ + in2p += size; \ + outp += size; \ + } \ + break; \ + case 2: \ + while (nout--) \ + { \ + routine(size, is_signed, in1p, in2p, outp); \ + in1p += size; \ + outp += size; \ + } \ + break; \ + } \ + break; \ } int Tdi3Mod(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_B: Operate(int8_t, %) case DTYPE_BU : Operate(uint8_t, %) case DTYPE_W : Operate(int16_t, %) case DTYPE_WU : Operate(uint16_t, %) case DTYPE_L @@ -252,8 +271,10 @@ int Tdi3Mod(struct descriptor *in1, struct descriptor *in2, } int Tdi3Atan2(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_F: OperateFloat(float, DTYPE_F, atan2); case DTYPE_FS: @@ -271,8 +292,10 @@ int Tdi3Atan2(struct descriptor *in1, struct descriptor *in2, } int Tdi3Atan2d(struct descriptor *in1, struct descriptor *in2, - struct descriptor *out) { - SetupArgs switch (in1->dtype) { + struct descriptor *out) +{ + SetupArgs switch (in1->dtype) + { case DTYPE_F: OperateFloat(float, DTYPE_F, radians_to_degrees *atan2); case DTYPE_FS: diff --git a/tdishr/TdiMatrix.c b/tdishr/TdiMatrix.c index 46752602ff..0698fb965b 100644 --- a/tdishr/TdiMatrix.c +++ b/tdishr/TdiMatrix.c @@ -46,11 +46,14 @@ extern int TdiMasterData(); static const struct descriptor missing = {0, DTYPE_MISSING, CLASS_S, 0}; -typedef struct { +typedef struct +{ int q[2]; } quadw; -static int copy(int len, int n, char *x, int incx, char *y, int incy) { - switch (len) { +static int copy(int len, int n, char *x, int incx, char *y, int incy) +{ + switch (len) + { case 1: for (; --n >= 0; x += incx, y += incy) *(char *)y = *(char *)x; @@ -76,7 +79,8 @@ static int copy(int len, int n, char *x, int incx, char *y, int incy) { } int Tdi1Diagonal(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; int cmode = -1, nside = 0; struct descriptor_xd fill = EMPTY_XD; @@ -89,35 +93,35 @@ int Tdi1Diagonal(opcode_t opcode, int narg, struct descriptor *list[], status = TdiGetArgs(opcode, 1, list, sig, uni, dat, cats); pv = (struct descriptor_a *)dat[0].pointer; - if - STATUS_OK { N_ELEMENTS(pv, nside); } - if - STATUS_OK { - proto.m[0] = nside; - proto.m[1] = nside; - proto.length = pv->length; - proto.arsize = pv->length * nside * nside; - if (narg > 1 && list[1]) { - status = TdiData(list[1], &fill MDS_END_ARG); - fillptr = fill.pointer; - } else - fillptr = (struct descriptor *)&missing; + if (STATUS_OK) + { + N_ELEMENTS(pv, nside); + } + if (STATUS_OK) + { + proto.m[0] = nside; + proto.m[1] = nside; + proto.length = pv->length; + proto.arsize = pv->length * nside * nside; + if (narg > 1 && list[1]) + { + status = TdiData(list[1], &fill MDS_END_ARG); + fillptr = fill.pointer; } - if - STATUS_OK - status = MdsGet1DxA((struct descriptor_a *)&proto, &pv->length, &pv->dtype, - out_ptr); + else + fillptr = (struct descriptor *)&missing; + } + if (STATUS_OK) + status = MdsGet1DxA((struct descriptor_a *)&proto, &pv->length, &pv->dtype, + out_ptr); po = (struct descriptor_a *)out_ptr->pointer; - if - STATUS_OK - status = TdiConvert(fillptr, po MDS_END_ARG); - if - STATUS_OK - status = copy(pv->length, nside, pv->pointer, pv->length, po->pointer, - pv->length * (nside + 1)); - if - STATUS_OK - status = TdiMasterData(0, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiConvert(fillptr, po MDS_END_ARG); + if (STATUS_OK) + status = copy(pv->length, nside, pv->pointer, pv->length, po->pointer, + pv->length * (nside + 1)); + if (STATUS_OK) + status = TdiMasterData(0, sig, uni, &cmode, out_ptr); MdsFree1Dx(&fill, NULL); MdsFree1Dx(&dat[0], NULL); MdsFree1Dx(&uni[0], NULL); diff --git a/tdishr/TdiMaxVal.c b/tdishr/TdiMaxVal.c index 26ca3cefe2..cb60787fd2 100644 --- a/tdishr/TdiMaxVal.c +++ b/tdishr/TdiMaxVal.c @@ -80,8 +80,8 @@ extern int Tdi3Divide(); #include #include -#define out(typ) \ - fprintf(stderr, "%3s: (%3d,%3d,%3d)\n", #typ, a->cnt_##typ, a->stp_##typ, \ +#define out(typ) \ + fprintf(stderr, "%3s: (%3d,%3d,%3d)\n", #typ, a->cnt_##typ, a->stp_##typ, \ a->stpm_##typ) extern int CvtConvertFloat(); @@ -96,18 +96,21 @@ const int roprand = 0x8000; #define DHUGE 1.7E308 #endif -int TdiLtO(unsigned int *in1, unsigned int *in2, int is_signed) { +int TdiLtO(unsigned int *in1, unsigned int *in2, int is_signed) +{ if (is_signed) return int128_lt((int128_t *)in1, (int128_t *)in2); return uint128_lt((uint128_t *)in1, (uint128_t *)in2); } -int TdiGtO(unsigned int *in1, unsigned int *in2, int is_signed) { +int TdiGtO(unsigned int *in1, unsigned int *in2, int is_signed) +{ if (is_signed) return int128_gt((int128_t *)in1, (int128_t *)in2); return uint128_gt((uint128_t *)in1, (uint128_t *)in2); } -typedef struct _args_t { +typedef struct _args_t +{ char *inp; char *outp; char *maskp; @@ -125,8 +128,10 @@ typedef struct _args_t { static inline int setupArgs(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int stp_dim, int stp_bef, - int stp_aft, args_t *a) { - switch (out->class) { + int stp_aft, args_t *a) +{ + switch (out->class) + { case CLASS_S: case CLASS_D: case CLASS_A: @@ -134,7 +139,8 @@ static inline int setupArgs(struct descriptor *in, struct descriptor *mask, default: return C_ERROR; } - switch (in->class) { + switch (in->class) + { case CLASS_S: case CLASS_D: case CLASS_A: @@ -142,7 +148,8 @@ static inline int setupArgs(struct descriptor *in, struct descriptor *mask, default: return C_ERROR; } - switch (mask->class) { + switch (mask->class) + { case CLASS_S: case CLASS_D: break; @@ -156,21 +163,21 @@ static inline int setupArgs(struct descriptor *in, struct descriptor *mask, return C_OK; } -#define SETUP_ARGS(args) \ - args_t args = {in->pointer, \ - out->pointer, \ - mask->pointer, \ - in->length, \ - stp_dim * in->length, \ - stp_bef * in->length, \ - stp_aft * in->length, \ - 0, \ - 0, \ - 0, \ - cnt_dim, \ - cnt_bef, \ - cnt_aft}; \ - if (setupArgs(in, mask, out, stp_dim, stp_bef, stp_aft, &args)) \ +#define SETUP_ARGS(args) \ + args_t args = {in->pointer, \ + out->pointer, \ + mask->pointer, \ + in->length, \ + stp_dim * in->length, \ + stp_bef * in->length, \ + stp_aft * in->length, \ + 0, \ + 0, \ + 0, \ + cnt_dim, \ + cnt_bef, \ + cnt_aft}; \ + if (setupArgs(in, mask, out, stp_dim, stp_bef, stp_aft, &args)) \ return TdiINVCLADSC; /******************************************** @@ -182,35 +189,41 @@ static int gt(const double in1, const double in2) { return in1 > in2; } static int lt(const double in1, const double in2) { return in1 < in2; } static double add(const double in1, const double in2) { return in1 + in2; } static double mul(const double in1, const double in2) { return in1 * in2; } -#define OP(type) \ - static int type##_lt(const char *in1, const char *in2) { \ - return *(type##_t *)in1 < *(type##_t *)in2; \ - } \ - static int type##_gt(const char *in1, const char *in2) { \ - return *(type##_t *)in1 > *(type##_t *)in2; \ - } \ - static void type##_add(const char *in1, const char *in2, char *out) { \ - type##_t *res = (type##_t *)out; \ - *res = (*(type##_t *)in1) + (*(type##_t *)in2); \ - } \ - static void type##_mul(const char *in1, const char *in2, char *out) { \ - type##_t *res = (type##_t *)out; \ - *res = (*(type##_t *)in1) * (*(type##_t *)in2); \ +#define OP(type) \ + static int type##_lt(const char *in1, const char *in2) \ + { \ + return *(type##_t *)in1 < *(type##_t *)in2; \ + } \ + static int type##_gt(const char *in1, const char *in2) \ + { \ + return *(type##_t *)in1 > *(type##_t *)in2; \ + } \ + static void type##_add(const char *in1, const char *in2, char *out) \ + { \ + type##_t *res = (type##_t *)out; \ + *res = (*(type##_t *)in1) + (*(type##_t *)in2); \ + } \ + static void type##_mul(const char *in1, const char *in2, char *out) \ + { \ + type##_t *res = (type##_t *)out; \ + *res = (*(type##_t *)in1) * (*(type##_t *)in2); \ } -#define AVG(type) \ - static void type##_avgadd(const char *in, char *inout) { \ - int64_t *sum = (int64_t *)inout; \ - *sum += (*(type##_t *)in); \ - } \ - static void type##_avgdiv(const char *in, const int count, char *out) { \ - type##_t *res = (type##_t *)out; \ - *res = (type##_t)((*(int64_t *)in) / count); \ +#define AVG(type) \ + static void type##_avgadd(const char *in, char *inout) \ + { \ + int64_t *sum = (int64_t *)inout; \ + *sum += (*(type##_t *)in); \ + } \ + static void type##_avgdiv(const char *in, const int count, char *out) \ + { \ + type##_t *res = (type##_t *)out; \ + *res = (type##_t)((*(int64_t *)in) / count); \ } -#define BITOP(bit) \ - OP(int##bit); \ +#define BITOP(bit) \ + OP(int##bit); \ OP(uint##bit) -#define BITAVG(bit) \ - AVG(int##bit); \ +#define BITAVG(bit) \ + AVG(int##bit); \ AVG(uint##bit) BITOP(8); BITOP(16); @@ -220,56 +233,69 @@ BITAVG(8); BITAVG(16); BITAVG(32); -static inline void int64_avgadd(const char *in, char *buf) { +static inline void int64_avgadd(const char *in, char *buf) +{ int128_t a = {.low = *(uint64_t *)in, .high = *(int64_t *)in < 0 ? -1 : 0}; int128_add(&a, (int128_t *)buf, (int128_t *)buf); } -static inline void int64_avgdiv(const char *in, const int count, char *out) { +static inline void int64_avgdiv(const char *in, const int count, char *out) +{ int128_t cnt = {.low = count, .high = 0}; int128_div((int128_t *)in, &cnt, &cnt); memcpy(out, &cnt.low, sizeof(int64_t)); } -static inline void uint64_avgadd(const char *in, char *buf) { +static inline void uint64_avgadd(const char *in, char *buf) +{ uint128_t a = {.low = *(uint64_t *)in, .high = 0}; uint128_add(&a, (uint128_t *)buf, (uint128_t *)buf); } -static inline void uint64_avgdiv(const char *in, const int count, char *out) { +static inline void uint64_avgdiv(const char *in, const int count, char *out) +{ uint128_t cnt = {.low = count, .high = 0}; uint128_div((uint128_t *)in, &cnt, &cnt); memcpy(out, &cnt.low, sizeof(uint64_t)); } /* missing versions for octaword */ -static inline void int128_avgadd(const char *in, char *buf) { +static inline void int128_avgadd(const char *in, char *buf) +{ int128_add((int128_t *)in, (int128_t *)buf, (int128_t *)buf); } -static inline void int128_avgdiv(const char *in, const int count, char *out) { +static inline void int128_avgdiv(const char *in, const int count, char *out) +{ int128_t cnt = {.low = count, .high = 0}; int128_div((int128_t *)in, &cnt, (int128_t *)out); } -static inline void uint128_avgadd(const char *in, char *buf) { +static inline void uint128_avgadd(const char *in, char *buf) +{ uint128_add((uint128_t *)in, (uint128_t *)buf, (uint128_t *)buf); } -static inline void uint128_avgdiv(const char *in, const int count, char *out) { +static inline void uint128_avgdiv(const char *in, const int count, char *out) +{ uint128_t cnt = {.low = count, .high = 0}; uint128_div((uint128_t *)in, &cnt, (uint128_t *)out); } static inline void -operateIloc(char *start, int testit(const char *, const char *), args_t *a) { +operateIloc(char *start, int testit(const char *, const char *), args_t *a) +{ int *outp = (int *)a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb++ < a->cnt_bef; - pib += a->stp_bef, pmb += a->stpm_bef, outp++) { // LOOP_BEFORE_LOC + pib += a->stp_bef, pmb += a->stpm_bef, outp++) + { // LOOP_BEFORE_LOC *outp = -1; char *result = start; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1 && testit(pid, result)) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1 && testit(pid, result)) + { result = pid; *outp = jd; } @@ -277,30 +303,37 @@ operateIloc(char *start, int testit(const char *, const char *), args_t *a) { } } } -#define OperateIloc(type, start, testit) \ - do { \ - type strt = start; \ - operateIloc((char *)&strt, testit, &args); \ +#define OperateIloc(type, start, testit) \ + do \ + { \ + type strt = start; \ + operateIloc((char *)&strt, testit, &args); \ } while (0) static inline void OperateFloc(char dtype, double start, int operator(const double, const double), - args_t *a) { + args_t *a) +{ int *outp = (int *)a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb++ < a->cnt_bef; - pib += a->stp_bef, pmb += a->stpm_bef, outp++) { // LOOP_BEFORE_LOC + pib += a->stp_bef, pmb += a->stpm_bef, outp++) + { // LOOP_BEFORE_LOC *outp = -1; double result = start; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double val; if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0) && - operator(val, result)) { + operator(val, result)) + { result = val; *outp = jd; } @@ -309,7 +342,8 @@ static inline void OperateFloc(char dtype, double start, } } } -static inline void OperateTloc(int testit(), args_t *a) { +static inline void OperateTloc(int testit(), args_t *a) +{ char testval; struct descriptor s_d = {a->length, DTYPE_T, CLASS_S, 0}; struct descriptor o_d = {1, DTYPE_B, CLASS_S, &testval}; @@ -318,17 +352,22 @@ static inline void OperateTloc(int testit(), args_t *a) { char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb++ < a->cnt_bef; - pib += a->stp_bef, pmb += a->stpm_bef, outp++) { // LOOP_BEFORE_LOC + pib += a->stp_bef, pmb += a->stpm_bef, outp++) + { // LOOP_BEFORE_LOC struct descriptor result = {a->length, DTYPE_T, CLASS_S, pib}; *outp = -1; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { s_d.pointer = pid; testit(&s_d, &result, &o_d); - if (testval) { + if (testval) + { result.pointer = pid; *outp = jd; } @@ -340,9 +379,11 @@ static inline void OperateTloc(int testit(), args_t *a) { int Tdi3MaxLoc(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_T: OperateTloc(Tdi3Gt, &args); break; @@ -399,70 +440,88 @@ int Tdi3MaxLoc(struct descriptor *in, struct descriptor *mask, int Tdi3MinLoc(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { - case DTYPE_T: { + switch (in->dtype) + { + case DTYPE_T: + { OperateTloc(Tdi3Lt, &args); break; } - case DTYPE_B: { + case DTYPE_B: + { OperateIloc(int8_t, 127, int8_lt); break; } - case DTYPE_BU: { + case DTYPE_BU: + { OperateIloc(uint8_t, -1, uint8_lt); break; } - case DTYPE_W: { + case DTYPE_W: + { OperateIloc(int16_t, 32767, int16_lt); break; } - case DTYPE_WU: { + case DTYPE_WU: + { OperateIloc(uint16_t, -1, uint16_lt); break; } - case DTYPE_L: { + case DTYPE_L: + { OperateIloc(int32_t, 0x7fffffff, int32_lt); break; } - case DTYPE_LU: { + case DTYPE_LU: + { OperateIloc(uint32_t, -1, uint32_lt); break; } - case DTYPE_Q: { + case DTYPE_Q: + { OperateIloc(int64_t, int64_max, int64_lt); break; } - case DTYPE_QU: { + case DTYPE_QU: + { OperateIloc(uint64_t, -1, uint64_lt); break; } - case DTYPE_O: { + case DTYPE_O: + { OperateIloc(int128_t, int128_max, (void *)int128_lt); break; } - case DTYPE_OU: { + case DTYPE_OU: + { OperateIloc(uint128_t, uint128_max, (void *)uint128_lt); break; } - case DTYPE_F: { + case DTYPE_F: + { OperateFloc(DTYPE_F, DHUGE, lt, &args); break; } - case DTYPE_FS: { + case DTYPE_FS: + { OperateFloc(DTYPE_FS, DHUGE, lt, &args); break; } - case DTYPE_G: { + case DTYPE_G: + { OperateFloc(DTYPE_G, DHUGE, lt, &args); break; } - case DTYPE_D: { + case DTYPE_D: + { OperateFloc(DTYPE_D, DHUGE, lt, &args); break; } - case DTYPE_FT: { + case DTYPE_FT: + { OperateFloc(DTYPE_FT, DHUGE, lt, &args); break; } @@ -473,18 +532,22 @@ int Tdi3MinLoc(struct descriptor *in, struct descriptor *mask, } static inline void -operateIval(char *start, int testit(const char *, const char *), args_t *a) { +operateIval(char *start, int testit(const char *, const char *), args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL char *result = start; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM if (*pmd & 1 && testit(pid, result)) result = pid; } @@ -492,26 +555,32 @@ operateIval(char *start, int testit(const char *, const char *), args_t *a) { } } } -#define OperateIval(type, start, testit) \ - do { \ - type strt = start; \ - operateIval((char *)&strt, testit, &args); \ +#define OperateIval(type, start, testit) \ + do \ + { \ + type strt = start; \ + operateIval((char *)&strt, testit, &args); \ } while (0) static inline void OperateFval(char dtype, double start, int operator(const double, const double), - args_t *a) { + args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL double result = start; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double val; if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0) && operator(val, result)) @@ -522,7 +591,8 @@ static inline void OperateFval(char dtype, double start, } } } -static inline void OperateTval(int testit(), args_t *a) { +static inline void OperateTval(int testit(), args_t *a) +{ char testval; struct descriptor s_d = {a->length, DTYPE_T, CLASS_S, 0}; struct descriptor o_d = {1, DTYPE_B, CLASS_S, &testval}; @@ -532,13 +602,17 @@ static inline void OperateTval(int testit(), args_t *a) { char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL result.pointer = pib; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { s_d.pointer = pid; testit(&s_d, &result, &o_d); if (testval) @@ -552,9 +626,11 @@ static inline void OperateTval(int testit(), args_t *a) { int Tdi3MaxVal(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_T: OperateTval(Tdi3Gt, &args); break; @@ -611,9 +687,11 @@ int Tdi3MaxVal(struct descriptor *in, struct descriptor *mask, int Tdi3MinVal(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_T: OperateTval(Tdi3Lt, &args); break; @@ -672,21 +750,26 @@ int Tdi3MinVal(struct descriptor *in, struct descriptor *mask, static inline void OperateImean(size_t buflen, void avgadd(const char *, char *), void avgdiv(const char *, const int, char *), - args_t *a) { + args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; char *buf = malloc(buflen); for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL int count = 0; memset(buf, 0, buflen); for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { avgadd(pid, buf); count++; } @@ -699,25 +782,33 @@ static inline void OperateImean(size_t buflen, } free(buf); } -static inline void OperateFmean(char dtype, args_t *a) { +static inline void OperateFmean(char dtype, args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL int count = 0; double result = 0; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double val; - if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) { + if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) + { result += val; count++; - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, outp, dtype, 0); goto loop_dim_done; } @@ -729,28 +820,36 @@ static inline void OperateFmean(char dtype, args_t *a) { } } } -static inline void OperateCmean(char dtype, args_t *a) { +static inline void OperateCmean(char dtype, args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL int count = 0; double resultr = 0, resulti = 0; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double valr, vali; if (CvtConvertFloat(pid, dtype, &valr, DTYPE_NATIVE_DOUBLE, 0) && CvtConvertFloat(pid + a->length / 2, dtype, &vali, - DTYPE_NATIVE_DOUBLE, 0)) { + DTYPE_NATIVE_DOUBLE, 0)) + { resultr += valr; resulti += vali; count++; - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, outp, dtype, 0); CvtConvertFloat(&roprand, DTYPE_F, outp + a->length / 2, dtype, 0); goto loop_dim_done; @@ -769,9 +868,11 @@ static inline void OperateCmean(char dtype, args_t *a) { int Tdi3Mean(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_B: OperateImean(8, int8_avgadd, int8_avgdiv, &args); break; @@ -841,19 +942,23 @@ int Tdi3Mean(struct descriptor *in, struct descriptor *mask, /*loops for sum and product*/ static inline void OperateIfun(char init, void fun(const char *, const char *, char *), - args_t *a) { + args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL memset(outp, 0, a->length); outp[0] = init; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM if (*pmd & 1) fun(pid, outp, outp); } @@ -862,23 +967,31 @@ static inline void OperateIfun(char init, } static inline void OperateFfun(double init, char dtype, double fun(const double, const double), - args_t *a) { + args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL double result = init; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double val; - if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) { + if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) + { result = fun(val, result); - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, outp, dtype, 0); goto loop_dim_done; } @@ -891,26 +1004,34 @@ static inline void OperateFfun(double init, char dtype, } static inline void OperateCfun(double init, char dtype, double fun(const double, const double), - args_t *a) { + args_t *a) +{ char *outp = a->outp; int ja, jb, jd; char *pid, *pib, *pia; char *pmd, *pmb, *pma; for (ja = 0; pia = a->inp, pma = a->maskp, ja < a->cnt_aft; - ja++, pia += a->stp_aft, pma += a->stpm_aft) { // LOOP_AFTER + ja++, pia += a->stp_aft, pma += a->stpm_aft) + { // LOOP_AFTER for (jb = 0, pib = pia, pmb = pma; jb < a->cnt_bef; jb++, pib += a->stp_bef, - pmb += a->stpm_bef, outp += a->length) { // LOOP_BEFORE_VAL + pmb += a->stpm_bef, outp += a->length) + { // LOOP_BEFORE_VAL double resultr = init, resulti = init; for (jd = 0, pid = pib, pmd = pmb; jd < a->cnt_dim; - jd++, pid += a->stp_dim, pmd += a->stpm_dim) { // LOOP_DIM - if (*pmd & 1) { + jd++, pid += a->stp_dim, pmd += a->stpm_dim) + { // LOOP_DIM + if (*pmd & 1) + { double valr, vali; if (CvtConvertFloat(pid, dtype, &valr, DTYPE_NATIVE_DOUBLE, 0) && CvtConvertFloat(pid + a->length / 2, dtype, &vali, - DTYPE_NATIVE_DOUBLE, 0)) { + DTYPE_NATIVE_DOUBLE, 0)) + { resultr = fun(valr, resultr); resulti = fun(vali, resulti); - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, outp, dtype, 0); CvtConvertFloat(&roprand, DTYPE_F, outp + a->length / 2, dtype, 0); goto loop_dim_done; @@ -927,9 +1048,11 @@ static inline void OperateCfun(double init, char dtype, int Tdi3Product(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_B: OperateIfun(1, int8_mul, &args); break; @@ -998,9 +1121,11 @@ int Tdi3Product(struct descriptor *in, struct descriptor *mask, int Tdi3Sum(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, int cnt_aft, - int stp_dim, int stp_bef, int stp_aft) { + int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_B: OperateIfun(0, int8_add, &args); break; @@ -1068,7 +1193,8 @@ int Tdi3Sum(struct descriptor *in, struct descriptor *mask, } static inline void OperateIaccum(void add(const char *, const char *, char *), - args_t *a) { + args_t *a) +{ int ja, jb, jd; char *poa, *pob, *pod; char *pia, *pib, *pid; @@ -1076,15 +1202,19 @@ static inline void OperateIaccum(void add(const char *, const char *, char *), char *result = malloc(a->length); for (ja = 0, poa = a->outp, pia = a->inp, pma = a->maskp; ja++ < a->cnt_aft; poa += a->stp_aft, pia += a->stp_aft, - pma += a->stpm_aft) { // LOOP_AFTER_ARRAY + pma += a->stpm_aft) + { // LOOP_AFTER_ARRAY for (jb = 0, pob = poa, pib = pia, pmb = pma; jb++ < a->cnt_bef; pob += a->stp_bef, pib += a->stp_bef, - pmb += a->stpm_bef) { // LOOP_BEFORE_ARRAY + pmb += a->stpm_bef) + { // LOOP_BEFORE_ARRAY memset(result, 0, a->length); for (jd = 0, pod = pob, pid = pib, pmd = pmb; jd++ < a->cnt_dim; pod += a->stp_dim, pid += a->stp_dim, - pmd += a->stpm_dim) { // LOOP_DIM_ARRAY - if (*pmd & 1) { + pmd += a->stpm_dim) + { // LOOP_DIM_ARRAY + if (*pmd & 1) + { add(pid, result, result); memcpy(pod, result, a->length); } @@ -1093,27 +1223,35 @@ static inline void OperateIaccum(void add(const char *, const char *, char *), } free(result); } -static inline void OperateFaccum(char dtype, args_t *a) { +static inline void OperateFaccum(char dtype, args_t *a) +{ int ja, jb, jd; char *poa, *pob, *pod; char *pia, *pib, *pid; char *pma, *pmb, *pmd; for (ja = 0, poa = a->outp, pia = a->inp, pma = a->maskp; ja++ < a->cnt_aft; poa += a->stp_aft, pia += a->stp_aft, - pma += a->stpm_aft) { // LOOP_AFTER_ARRAY + pma += a->stpm_aft) + { // LOOP_AFTER_ARRAY for (jb = 0, pob = poa, pib = pia, pmb = pma; jb++ < a->cnt_bef; pob += a->stp_bef, pib += a->stp_bef, - pmb += a->stpm_bef) { // LOOP_BEFORE_ARRAY + pmb += a->stpm_bef) + { // LOOP_BEFORE_ARRAY double result = 0; for (jd = 0, pod = pob, pid = pib, pmd = pmb; jd++ < a->cnt_dim; pod += a->stp_dim, pid += a->stp_dim, - pmd += a->stpm_dim) { // LOOP_DIM_ARRAY - if (*pmd & 1) { + pmd += a->stpm_dim) + { // LOOP_DIM_ARRAY + if (*pmd & 1) + { double val; - if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) { + if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0)) + { result += val; CvtConvertFloat(&result, DTYPE_NATIVE_DOUBLE, pod, dtype, 0); - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, pod, dtype, 0); } } @@ -1122,32 +1260,40 @@ static inline void OperateFaccum(char dtype, args_t *a) { } } -static inline void OperateCaccum(char dtype, args_t *a) { +static inline void OperateCaccum(char dtype, args_t *a) +{ int ja, jb, jd; char *poa, *pob, *pod; char *pia, *pib, *pid; char *pma, *pmb, *pmd; for (ja = 0, poa = a->outp, pia = a->inp, pma = a->maskp; ja++ < a->cnt_aft; poa += a->stp_aft, pia += a->stp_aft, - pma += a->stpm_aft) { // LOOP_AFTER_ARRAY + pma += a->stpm_aft) + { // LOOP_AFTER_ARRAY for (jb = 0, pob = poa, pib = pia, pmb = pma; jb++ < a->cnt_bef; pob += a->stp_bef, pib += a->stp_bef, - pmb += a->stpm_bef) { // LOOP_BEFORE_ARRAY + pmb += a->stpm_bef) + { // LOOP_BEFORE_ARRAY double result = 0, resulti = 0; for (jd = 0, pod = pob, pid = pib, pmd = pmb; jd++ < a->cnt_dim; pod += a->stp_dim, pid += a->stp_dim, - pmd += a->stpm_dim) { // LOOP_DIM_ARRAY - if (*pmd & 1) { + pmd += a->stpm_dim) + { // LOOP_DIM_ARRAY + if (*pmd & 1) + { double val, vali; if (CvtConvertFloat(pid, dtype, &val, DTYPE_NATIVE_DOUBLE, 0) && CvtConvertFloat(pid + a->length, dtype, &vali, - DTYPE_NATIVE_DOUBLE, 0)) { + DTYPE_NATIVE_DOUBLE, 0)) + { result += val; resulti += vali; CvtConvertFloat(&result, DTYPE_NATIVE_DOUBLE, pod, dtype, 0); CvtConvertFloat(&resulti, DTYPE_NATIVE_DOUBLE, pod + a->length / 2, dtype, 0); - } else { + } + else + { CvtConvertFloat(&roprand, DTYPE_F, pod, dtype, 0); CvtConvertFloat(&roprand, DTYPE_F, pod + a->length / 2, dtype, 0); } @@ -1159,9 +1305,11 @@ static inline void OperateCaccum(char dtype, args_t *a) { int Tdi3Accumulate(struct descriptor *in, struct descriptor *mask, struct descriptor *out, int cnt_dim, int cnt_bef, - int cnt_aft, int stp_dim, int stp_bef, int stp_aft) { + int cnt_aft, int stp_dim, int stp_bef, int stp_aft) +{ SETUP_ARGS(args); - switch (in->dtype) { + switch (in->dtype) + { case DTYPE_B: OperateIaccum(int8_add, &args); break; diff --git a/tdishr/TdiMinMax.c b/tdishr/TdiMinMax.c index 47cda040a9..1c56a88d17 100644 --- a/tdishr/TdiMinMax.c +++ b/tdishr/TdiMinMax.c @@ -39,14 +39,16 @@ extern int TdiData(); extern int TdiGetLong(); int Tdi1MinMax(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp, *newlist[2]; int j; newlist[0] = &tmp; status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - for (j = 1; STATUS_OK && j < narg; j++) { + for (j = 1; STATUS_OK && j < narg; j++) + { tmp = *out_ptr; *out_ptr = EMPTY_XD; newlist[1] = (struct descriptor_xd *)list[j]; @@ -66,32 +68,36 @@ int Tdi1MinMax(opcode_t opcode, int narg, struct descriptor *list[], conformed. */ int Tdi1Conditional(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = TdiData(list[2], out_ptr MDS_END_ARG); - if - STATUS_OK { - if (out_ptr->pointer && out_ptr->pointer->class == CLASS_A) { - struct descriptor_xd tmp = *out_ptr; - struct descriptor *new[3]; - new[0] = list[0]; - new[1] = list[1]; - new[2] = (struct descriptor *)&tmp; - *out_ptr = EMPTY_XD; - status = Tdi1Same(opcode, narg, new, out_ptr); - MdsFree1Dx(&tmp, NULL); - } else { - int truth; - status = TdiGetLong(out_ptr, &truth); - if - STATUS_OK { - if (truth & 1) - status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - else - status = TdiEvaluate(list[1], out_ptr MDS_END_ARG); - } + if (STATUS_OK) + { + if (out_ptr->pointer && out_ptr->pointer->class == CLASS_A) + { + struct descriptor_xd tmp = *out_ptr; + struct descriptor *new[3]; + new[0] = list[0]; + new[1] = list[1]; + new[2] = (struct descriptor *)&tmp; + *out_ptr = EMPTY_XD; + status = Tdi1Same(opcode, narg, new, out_ptr); + MdsFree1Dx(&tmp, NULL); + } + else + { + int truth; + status = TdiGetLong(out_ptr, &truth); + if (STATUS_OK) + { + if (truth & 1) + status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); + else + status = TdiEvaluate(list[1], out_ptr MDS_END_ARG); } } + } return status; } diff --git a/tdishr/TdiPack.c b/tdishr/TdiPack.c index dc8c1cdaa1..5b490dab36 100644 --- a/tdishr/TdiPack.c +++ b/tdishr/TdiPack.c @@ -56,7 +56,8 @@ extern int Tdi2Pack(); extern int TdiConvert(); int Tdi1Pack(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; int lena, lenm, numa, numm, numv = 0, bytes, j, cmode = -1; char *pi, *pm, *po; @@ -67,86 +68,94 @@ int Tdi1Pack(opcode_t opcode, int narg, struct descriptor *list[], status = TdiGetArgs(opcode, narg, list, sig, uni, dat, cats); if (STATUS_OK && dat[0].pointer->class != CLASS_A) status = TdiINVCLADSC; - if - STATUS_OK - status = Tdi2Pack(narg, uni, dat, cats, 0); - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); - if - STATUS_OK { - struct descriptor_a *parr = (struct descriptor_a *)dat[0].pointer; - bytes = parr->arsize; - lena = parr->length; - if (narg > 2) { - if (dat[2].pointer->class != CLASS_A) - numv = -2; - else if (dat[2].pointer->dtype != DTYPE_MISSING) - numv = (int)((struct descriptor_a *)dat[2].pointer)->arsize / lena; - } else - numv = -1; + if (STATUS_OK) + status = Tdi2Pack(narg, uni, dat, cats, 0); + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK) + { + struct descriptor_a *parr = (struct descriptor_a *)dat[0].pointer; + bytes = parr->arsize; + lena = parr->length; + if (narg > 2) + { + if (dat[2].pointer->class != CLASS_A) + numv = -2; + else if (dat[2].pointer->dtype != DTYPE_MISSING) + numv = (int)((struct descriptor_a *)dat[2].pointer)->arsize / lena; + } + else + numv = -1; - /******************************************************************************* + /******************************************************************************* * Array MASK: Conform ARRAY to MASK (we use smaller). Result is condensed *ARRAY. Scalar MASK: Result is ARRAY for true or null for false. *******************************************************************************/ - if (dat[1].pointer->class == CLASS_A) { - lenm = dat[1].pointer->length; - numa = bytes / lena; - numm = (int)((struct descriptor_a *)dat[1].pointer)->arsize / lenm; + if (dat[1].pointer->class == CLASS_A) + { + lenm = dat[1].pointer->length; + numa = bytes / lena; + numm = (int)((struct descriptor_a *)dat[1].pointer)->arsize / lenm; #ifdef WORDS_BIGENDIAN - pm = dat[1].pointer->pointer + lenm - 1; + pm = dat[1].pointer->pointer + lenm - 1; #else - pm = dat[1].pointer->pointer; + pm = dat[1].pointer->pointer; #endif - if (numa < numm) - numm = numa; - if (numv >= 0 && numm > numv) - numm = numv; - pi = parr->pointer; - po = pi; - for (; --numm >= 0; pm += lenm, pi += lena) - if (*pm & 1) { - if (po < pi) // only copy if memory does not overlap - memcpy(po, pi, lena); - po += lena; - }; - bytes = po - dat[0].pointer->pointer; - } else if (!(*dat[1].pointer->pointer & 1)) - bytes = 0; + if (numa < numm) + numm = numa; + if (numv >= 0 && numm > numv) + numm = numv; + pi = parr->pointer; + po = pi; + for (; --numm >= 0; pm += lenm, pi += lena) + if (*pm & 1) + { + if (po < pi) // only copy if memory does not overlap + memcpy(po, pi, lena); + po += lena; + }; + bytes = po - dat[0].pointer->pointer; + } + else if (!(*dat[1].pointer->pointer & 1)) + bytes = 0; - /********************************************* + /********************************************* * Possibly augmented by VECTOR. * (-2) If it is a scalar, fill out ARRAY. * (++) If it is a vector, copy to VECTOR. * (-1) If missing/too short, use partial XD. *********************************************/ - parr->aflags.coeff = 0; - parr->aflags.bounds = 0; - parr->dimct = 1; - MdsFree1Dx(out_ptr, NULL); - if (numv == -2) { - parr->pointer += bytes; - parr->arsize -= bytes; - status = TdiConvert(dat[2].pointer, parr MDS_END_ARG); - parr->pointer -= bytes; - parr->arsize += bytes; - *out_ptr = dat[0]; - dat[0] = EMPTY_XD; - } else if (bytes < numv * lena) { - memcpy(dat[2].pointer->pointer, parr->pointer, bytes); - *out_ptr = dat[2]; - dat[2] = EMPTY_XD; - } else { - parr->arsize = bytes; - *out_ptr = dat[0]; - dat[0] = EMPTY_XD; - } + parr->aflags.coeff = 0; + parr->aflags.bounds = 0; + parr->dimct = 1; + MdsFree1Dx(out_ptr, NULL); + if (numv == -2) + { + parr->pointer += bytes; + parr->arsize -= bytes; + status = TdiConvert(dat[2].pointer, parr MDS_END_ARG); + parr->pointer -= bytes; + parr->arsize += bytes; + *out_ptr = dat[0]; + dat[0] = EMPTY_XD; + } + else if (bytes < numv * lena) + { + memcpy(dat[2].pointer->pointer, parr->pointer, bytes); + *out_ptr = dat[2]; + dat[2] = EMPTY_XD; } - if - STATUS_OK - status = TdiMasterData(0, sig, uni, &cmode, out_ptr); - for (j = narg; --j >= 0;) { + else + { + parr->arsize = bytes; + *out_ptr = dat[0]; + dat[0] = EMPTY_XD; + } + } + if (STATUS_OK) + status = TdiMasterData(0, sig, uni, &cmode, out_ptr); + for (j = narg; --j >= 0;) + { MdsFree1Dx(&sig[j], NULL); MdsFree1Dx(&uni[j], NULL); MdsFree1Dx(&dat[j], NULL); diff --git a/tdishr/TdiPower.c b/tdishr/TdiPower.c index a2b226bcc6..632aab7c3e 100644 --- a/tdishr/TdiPower.c +++ b/tdishr/TdiPower.c @@ -47,7 +47,8 @@ extern int Tdi3Exp(); extern int Tdi3Divide(); int Tdi3Power(struct descriptor *x, struct descriptor *y, - struct descriptor_a *z) { + struct descriptor_a *z) +{ INIT_STATUS; int yy; char uno[32]; @@ -57,34 +58,36 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, For real/complex exponent, z = EXP(LOG(x)*y) Need HC routines, not available on VAX. *******************************************/ - if (y->dtype != DTYPE_L) { - if (x->class != CLASS_A && z->class == CLASS_A) { + if (y->dtype != DTYPE_L) + { + if (x->class != CLASS_A && z->class == CLASS_A) + { status = TdiConvert(x, z); status = Tdi3Log(z, z); - } else + } + else status = Tdi3Log(x, z); - if - STATUS_OK - status = Tdi3Multiply(y, z, z); - if - STATUS_OK - status = Tdi3Exp(z, z); + if (STATUS_OK) + status = Tdi3Multiply(y, z, z); + if (STATUS_OK) + status = Tdi3Exp(z, z); } /****************************************** Scalar integer exponent, look once at bits. Clobbers x and x&z must be different. ******************************************/ - else if (y->class != CLASS_A) { - if ((yy = *(int *)y->pointer) <= 0) { + else if (y->class != CLASS_A) + { + if ((yy = *(int *)y->pointer) <= 0) + { if (yy == 0) return TdiConvert(&one_dsc, z); yy = -yy; duno = *x; duno.pointer = uno; status = TdiConvert(&one_dsc, &duno); - if - STATUS_OK - status = Tdi3Divide(&duno, x, x); + if (STATUS_OK) + status = Tdi3Divide(&duno, x, x); } for (; !(yy & 1) && STATUS_OK; yy >>= 1) status = Tdi3Multiply(x, x, x); @@ -92,7 +95,8 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, _MOVC3(z->length, x->pointer, z->pointer); else _MOVC3(z->arsize, x->pointer, z->pointer); - for (; (yy >>= 1) > 0 && STATUS_OK;) { + for (; (yy >>= 1) > 0 && STATUS_OK;) + { status = Tdi3Multiply(x, x, x); if (yy & 1 && STATUS_OK) status = Tdi3Multiply(x, z, z); @@ -102,7 +106,8 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, Must do it the hard way. Copy to keep scalar base. ************************/ - else { + else + { char xx[32]; struct descriptor dx = {0, 0, CLASS_S, 0}; char *px = x->pointer; @@ -119,13 +124,15 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, dz.class = CLASS_S; duno = dx; duno.pointer = uno; - if - STATUS_OK - status = TdiConvert(&one_dsc, &duno); - for (; --n >= 0 && STATUS_OK; px += incx, dz.pointer += incz) { + if (STATUS_OK) + status = TdiConvert(&one_dsc, &duno); + for (; --n >= 0 && STATUS_OK; px += incx, dz.pointer += incz) + { _MOVC3(dx.length, px, xx); - if ((int)(yy = *py++) <= 0) { - if (yy == 0) { + if ((int)(yy = *py++) <= 0) + { + if (yy == 0) + { _MOVC3(dz.length, uno, dz.pointer); continue; } @@ -135,7 +142,8 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, for (; !(yy & 1) && STATUS_OK; yy >>= 1) status = Tdi3Multiply(&dx, &dx, &dx); _MOVC3(dz.length, dx.pointer, dz.pointer); - for (; (yy >>= 1) > 0 && STATUS_OK;) { + for (; (yy >>= 1) > 0 && STATUS_OK;) + { status = Tdi3Multiply(&dx, &dx, &dx); if (yy & 1 && STATUS_OK) status = Tdi3Multiply(&dx, &dz, &dz); @@ -149,12 +157,14 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, Tdi3Merge.C Assign value from either true or false source according to mask. */ -typedef struct { +typedef struct +{ int q0, q1; } lquad; int Tdi3Merge(struct descriptor_a *pdtrue, struct descriptor_a *pdfalse, - struct descriptor_a *pdmask, struct descriptor_a *pdout) { + struct descriptor_a *pdmask, struct descriptor_a *pdout) +{ INIT_STATUS; int len = pdout->length; char *po = pdout->pointer; @@ -177,45 +187,47 @@ int Tdi3Merge(struct descriptor_a *pdtrue, struct descriptor_a *pdfalse, lquad *pq; N_ELEMENTS(pdout, n); - if - STATUS_OK - switch (len) { - case 1: - for (pc = (char *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) - if (*pm & 1) - *pc++ = *(char *)pt; - else - *pc++ = *(char *)pf; - break; - case 2: - for (ps = (short *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) - if (*pm & 1) - *ps++ = *(short *)pt; - else - *ps++ = *(short *)pf; - break; - case 4: - for (pl = (int *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) - if (*pm & 1) - *pl++ = *(int *)pt; - else - *pl++ = *(int *)pf; - break; - case 8: - for (pq = (lquad *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) - if (*pm & 1) - *pq++ = *(lquad *)pt; - else - *pq++ = *(lquad *)pf; + if (STATUS_OK) + switch (len) + { + case 1: + for (pc = (char *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) + if (*pm & 1) + *pc++ = *(char *)pt; + else + *pc++ = *(char *)pf; + break; + case 2: + for (ps = (short *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) + if (*pm & 1) + *ps++ = *(short *)pt; + else + *ps++ = *(short *)pf; + break; + case 4: + for (pl = (int *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) + if (*pm & 1) + *pl++ = *(int *)pt; + else + *pl++ = *(int *)pf; + break; + case 8: + for (pq = (lquad *)po; --n >= 0; pm += stepm, pt += stept, pf += stepf) + if (*pm & 1) + *pq++ = *(lquad *)pt; + else + *pq++ = *(lquad *)pf; + break; + default: + { + int sm = stepm, st = stept, sf = stepf; + for (; --n >= 0; pm += sm, pt += st, pf += sf, po += len) + if (*pm & 1) + _MOVC3(len, pt, po); + else + _MOVC3(len, pf, po); + } break; - default: { - int sm = stepm, st = stept, sf = stepf; - for (; --n >= 0; pm += sm, pt += st, pf += sf, po += len) - if (*pm & 1) - _MOVC3(len, pt, po); - else - _MOVC3(len, pf, po); - } break; - } + } return status; } diff --git a/tdishr/TdiReshape.c b/tdishr/TdiReshape.c index 82ceab9332..85a8fe1c60 100644 --- a/tdishr/TdiReshape.c +++ b/tdishr/TdiReshape.c @@ -32,7 +32,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int Tdi1Reshape(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ if (narg < 1) return TdiMISS_ARG; int status; @@ -43,14 +44,18 @@ int Tdi1Reshape(opcode_t opcode, int narg, struct descriptor *list[], return TdiINVCLADSC; array_coeff *arr = (array_coeff *)out_ptr->pointer; int i; - switch (opcode) { + switch (opcode) + { default: return TdiNO_OPC; case OPC_RESHAPE: return TdiNO_OPC; - case OPC_FLATTEN: { - if (arr->dimct > 1) { - for (i = 1; i < arr->dimct; i++) { + case OPC_FLATTEN: + { + if (arr->dimct > 1) + { + for (i = 1; i < arr->dimct; i++) + { arr->m[0] *= arr->m[i]; arr->m[i] = 0; } @@ -59,25 +64,33 @@ int Tdi1Reshape(opcode_t opcode, int narg, struct descriptor *list[], } break; } - case OPC_SQUEEZE: { + case OPC_SQUEEZE: + { int j = 0; // calculate old bounds location bound_t *bounds = arr->aflags.bounds ? (bound_t *)&arr->m[arr->dimct] : NULL; - for (i = 0; i < arr->dimct; i++) { - if (arr->m[i] == 1) { + for (i = 0; i < arr->dimct; i++) + { + if (arr->m[i] == 1) + { j++; - } else { + } + else + { arr->m[i - j] = arr->m[i]; - if (bounds) { + if (bounds) + { bounds[i - j] = bounds[i]; } } } arr->dimct = arr->dimct - j; - if (bounds) { // move bounds + if (bounds) + { // move bounds const int end = arr->dimct * (1 + sizeof(bound_t) / sizeof(int32_t)); - for (i = arr->dimct; i < end; i++) { + for (i = arr->dimct; i < end; i++) + { arr->m[i] = arr->m[i + j]; } } diff --git a/tdishr/TdiSame.c b/tdishr/TdiSame.c index 6a7cbc49e2..d59345a103 100644 --- a/tdishr/TdiSame.c +++ b/tdishr/TdiSame.c @@ -51,7 +51,8 @@ extern int TdiMasterData(); extern int TdiFaultHandler(); int Tdi1Same(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd sig[3] = {EMPTY_XD}, uni[3] = {EMPTY_XD}, dat[3] = {EMPTY_XD}; @@ -75,64 +76,65 @@ int Tdi1Same(opcode_t opcode, int narg, struct descriptor *list[], /****************************************** Adjust category needed to match data types. ******************************************/ - if - STATUS_OK - status = - (*fun_ptr->f2)(narg, uni, dat, cats, &routine, fun_ptr->o1, fun_ptr->o2); + if (STATUS_OK) + status = + (*fun_ptr->f2)(narg, uni, dat, cats, &routine, fun_ptr->o1, fun_ptr->o2); /****************************** Do the needed type conversions. ******************************/ - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); /****************** Find correct shape. ******************/ - if - STATUS_OK - status = TdiGetShape(narg, dat, cats[narg].digits, cats[narg].out_dtype, - &cmode, out_ptr); + if (STATUS_OK) + status = TdiGetShape(narg, dat, cats[narg].digits, cats[narg].out_dtype, + &cmode, out_ptr); /******************************** Act on data, linear arguments. No action for simple conversions. Default is for MIN/MAX pairwise. ********************************/ - if - STATUS_OK { - if (routine == &Tdi3undef || routine == 0) { - MdsFree1Dx(out_ptr, NULL); - *out_ptr = dat[0]; - dat[0] = EMPTY_XD; - } else { - switch (fun_ptr->m2) { - case 1: - status = (*routine)(dat[0].pointer, out_ptr->pointer); - break; - default: - case 2: - status = (*routine)(dat[0].pointer, dat[1].pointer, out_ptr->pointer); - break; - case 3: - status = (*routine)(dat[0].pointer, dat[1].pointer, dat[2].pointer, - out_ptr->pointer); - break; - } + if (STATUS_OK) + { + if (routine == &Tdi3undef || routine == 0) + { + MdsFree1Dx(out_ptr, NULL); + *out_ptr = dat[0]; + dat[0] = EMPTY_XD; + } + else + { + switch (fun_ptr->m2) + { + case 1: + status = (*routine)(dat[0].pointer, out_ptr->pointer); + break; + default: + case 2: + status = (*routine)(dat[0].pointer, dat[1].pointer, out_ptr->pointer); + break; + case 3: + status = (*routine)(dat[0].pointer, dat[1].pointer, dat[2].pointer, + out_ptr->pointer); + break; } } + } /******************** Embed data in signal. ********************/ - if - STATUS_OK - status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); /******************** Free all temporaries. ********************/ - for (j = narg; --j >= 0;) { + for (j = narg; --j >= 0;) + { if (sig[j].pointer) MdsFree1Dx(&sig[j], NULL); if (uni[j].pointer) diff --git a/tdishr/TdiScalar.c b/tdishr/TdiScalar.c index a8b0234548..785f8aeab5 100644 --- a/tdishr/TdiScalar.c +++ b/tdishr/TdiScalar.c @@ -58,7 +58,8 @@ extern int TdiPower(); #define _factor ((float).30103) int Tdi1Scalar(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd sig[2] = {EMPTY_XD}, uni[2] = {EMPTY_XD}, dat[2] = {EMPTY_XD}; @@ -77,37 +78,34 @@ int Tdi1Scalar(opcode_t opcode, int narg, struct descriptor *list[], /****************************************** Adjust category needed to match data types. ******************************************/ - if - STATUS_OK - status = (*fun_ptr->f2)(narg, uni, dat, cats, &routine); + if (STATUS_OK) + status = (*fun_ptr->f2)(narg, uni, dat, cats, &routine); /****************************** Do the needed type conversions. ******************************/ - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); /****************** Find correct shape. ******************/ - if - STATUS_OK - status = TdiGetShape(0, dat, 0, cats[narg].out_dtype, &cmode, out_ptr); + if (STATUS_OK) + status = TdiGetShape(0, dat, 0, cats[narg].out_dtype, &cmode, out_ptr); /***************************** Act on data, linear arguments. *****************************/ - if - STATUS_OK - switch (fun_ptr->m2) { - case 1: - status = (*routine)(dat[0].pointer, out_ptr->pointer); - break; - case 2: - status = (*routine)(dat[0].pointer, dat[1].pointer, out_ptr->pointer); - break; - } + if (STATUS_OK) + switch (fun_ptr->m2) + { + case 1: + status = (*routine)(dat[0].pointer, out_ptr->pointer); + break; + case 2: + status = (*routine)(dat[0].pointer, dat[1].pointer, out_ptr->pointer); + break; + } if (STATUS_OK && (opcode == OPC_DOT_PRODUCT || fun_ptr->f2 == Tdi2Keep)) status = TdiMasterData(0, sig, uni, &cmode, out_ptr); @@ -115,7 +113,8 @@ int Tdi1Scalar(opcode_t opcode, int narg, struct descriptor *list[], /******************** Free all temporaries. ********************/ - for (j = narg; --j >= 0;) { + for (j = narg; --j >= 0;) + { if (sig[j].pointer) MdsFree1Dx(&sig[j], NULL); if (uni[j].pointer) @@ -133,10 +132,12 @@ int Tdi1Scalar(opcode_t opcode, int narg, struct descriptor *list[], NEED handling of bit and packed types. */ -int Tdi3BitSize(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3BitSize(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_A: case CLASS_S: case CLASS_D: @@ -157,10 +158,12 @@ int Tdi3BitSize(struct descriptor *in_ptr, struct descriptor *out_ptr) { DIGITS(3.0) is 24, DIGITS(4) 31. integer = DIGITS(number) */ -int Tdi3Digits(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Digits(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ int status = MDSplusSUCCESS, n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -212,21 +215,22 @@ int Tdi3Digits(struct descriptor *in_ptr, struct descriptor *out_ptr) { real = EPSILON(real-model) */ -int Tdi3Epsilon(struct descriptor *x_ptr, struct descriptor *out_ptr) { +int Tdi3Epsilon(struct descriptor *x_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; double digits_d; struct descriptor digits = {sizeof(digits_d), DTYPE_NATIVE_DOUBLE, CLASS_S, 0}; digits.pointer = (char *)&digits_d; status = TdiDigits(x_ptr, &digits MDS_END_ARG); - if - STATUS_OK { - static const double two_d = 2.; - static const struct descriptor two = {sizeof(two_d), DTYPE_NATIVE_DOUBLE, - CLASS_S, (char *)&two_d}; - digits_d = 1. - digits_d; - status = TdiPower(&two, &digits, out_ptr MDS_END_ARG); - } + if (STATUS_OK) + { + static const double two_d = 2.; + static const struct descriptor two = {sizeof(two_d), DTYPE_NATIVE_DOUBLE, + CLASS_S, (char *)&two_d}; + digits_d = 1. - digits_d; + status = TdiPower(&two, &digits, out_ptr MDS_END_ARG); + } return status; } @@ -258,15 +262,17 @@ static const unsigned int FSC_HUGE[] = {0x7F7FFFFF}; static const unsigned int FT_HUGE[] = {0xFFFFFFFF, 0x7FF7FFFF}; static const unsigned int FTC_HUGE[] = {0xFFFFFFFF, 0x7FF7FFFF}; -#define CASE(dtype) \ - case DTYPE_##dtype: \ - memcpy(out_ptr->pointer, dtype##_HUGE, sizeof(dtype##_HUGE)); \ +#define CASE(dtype) \ + case DTYPE_##dtype: \ + memcpy(out_ptr->pointer, dtype##_HUGE, sizeof(dtype##_HUGE)); \ break; -int Tdi3Huge(struct descriptor *x_ptr, struct descriptor *out_ptr) { +int Tdi3Huge(struct descriptor *x_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; - switch (x_ptr->dtype) { + switch (x_ptr->dtype) + { default: status = TdiINVDTYDSC; break; @@ -301,10 +307,12 @@ int Tdi3Huge(struct descriptor *x_ptr, struct descriptor *out_ptr) { NEED handling of bit and packed types. */ -int Tdi3Len(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Len(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_A: case CLASS_S: case CLASS_D: @@ -322,10 +330,12 @@ int Tdi3Len(struct descriptor *in_ptr, struct descriptor *out_ptr) { fraction. This is computer-dependent. VAX base=2. MAXEXPONENT(3.0) is +127, MAXEXPONENT(4g0) +1023. integer = MAXEXPONENT(real) */ -int Tdi3MaxExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3MaxExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ int status = MDSplusSUCCESS, n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -356,10 +366,12 @@ int Tdi3MaxExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { fraction. This is computer-dependent. VAX base=2. MINEXPONENT(3.0) is -127, MINEXPONENT(4g0) -1023. integer = MINEXPONENT(real) */ -int Tdi3MinExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3MinExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ int status = MDSplusSUCCESS, n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -391,10 +403,12 @@ int Tdi3MinExponent(struct descriptor *in_ptr, struct descriptor *out_ptr) { power of 10) This is computer-dependent. VAX base=2. PRECISION(3.0) is 6, PRECISION(4g0) 15. integer = PRECISION(real) */ -int Tdi3Precision(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Precision(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ int status = MDSplusSUCCESS, n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -428,11 +442,13 @@ int Tdi3Precision(struct descriptor *in_ptr, struct descriptor *out_ptr) { RADIX(3.0) is 2, RADIX(4) is 2. integer = RADIX(number) */ -int Tdi3Radix(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Radix(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -469,10 +485,12 @@ int Tdi3Radix(struct descriptor *in_ptr, struct descriptor *out_ptr) { base=2. VAX huge < 1/tiny. RANGE(3.0) is 38, RANGE(4g0) 307. integer = RANGE(real) */ -int Tdi3Range(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Range(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ int status = MDSplusSUCCESS, n; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: n = 0; status = TdiINVDTYDSC; @@ -502,7 +520,8 @@ int Tdi3Range(struct descriptor *in_ptr, struct descriptor *out_ptr) { F90 extension inquiry for declared number of dimensions of an array. Returns zero for a scalar. */ -int Tdi3Rank(struct descriptor_a *arr_ptr, struct descriptor *out_ptr) { +int Tdi3Rank(struct descriptor_a *arr_ptr, struct descriptor *out_ptr) +{ int n; if (arr_ptr->class == CLASS_A) @@ -518,28 +537,29 @@ int Tdi3Rank(struct descriptor_a *arr_ptr, struct descriptor *out_ptr) { /*--------------------------------------------------- Return kind (dtype) of smallest integer with sufficient range. */ -int Tdi3SelectedIntKind(struct descriptor *pdr, struct descriptor *pout) { +int Tdi3SelectedIntKind(struct descriptor *pdr, struct descriptor *pout) +{ int range, status; float frange; status = TdiGetLong(pdr, &range); - if - STATUS_OK { - frange = range / _factor; - if (frange <= 07) - range = DTYPE_B; - else if (frange <= 15) - range = DTYPE_W; - else if (frange <= 31) - range = DTYPE_L; - else if (frange <= 63) - range = DTYPE_Q; - else if (frange <= 127) - range = DTYPE_O; - else - range = -1; - *(int *)pout->pointer = range; - } + if (STATUS_OK) + { + frange = range / _factor; + if (frange <= 07) + range = DTYPE_B; + else if (frange <= 15) + range = DTYPE_W; + else if (frange <= 31) + range = DTYPE_L; + else if (frange <= 63) + range = DTYPE_Q; + else if (frange <= 127) + range = DTYPE_O; + else + range = -1; + *(int *)pout->pointer = range; + } return status; } @@ -548,28 +568,28 @@ int Tdi3SelectedIntKind(struct descriptor *pdr, struct descriptor *pout) { range. */ int Tdi3SelectedRealKind(struct descriptor *pdp, struct descriptor *pdr, - struct descriptor *pout) { + struct descriptor *pout) +{ int prec, range, status; float fprec, frange; status = TdiGetLong(pdp, &prec); - if - STATUS_OK - status = TdiGetLong(pdr, &range); - if - STATUS_OK { - fprec = prec / _factor; - frange = range / _factor; - if (fprec <= 23 && frange <= 127) - range = DTYPE_NATIVE_FLOAT; - else if (fprec <= 52 && frange <= 1023) - range = DTYPE_NATIVE_DOUBLE; - else if (fprec <= 55 && frange <= 127) - range = DTYPE_D; - else - range = 0; - *(int *)pout->pointer = range; - } + if (STATUS_OK) + status = TdiGetLong(pdr, &range); + if (STATUS_OK) + { + fprec = prec / _factor; + frange = range / _factor; + if (fprec <= 23 && frange <= 127) + range = DTYPE_NATIVE_FLOAT; + else if (fprec <= 52 && frange <= 1023) + range = DTYPE_NATIVE_DOUBLE; + else if (fprec <= 55 && frange <= 127) + range = DTYPE_D; + else + range = 0; + *(int *)pout->pointer = range; + } return status; } @@ -578,11 +598,13 @@ int Tdi3SelectedRealKind(struct descriptor *pdp, struct descriptor *pdr, int = SIZEOF(expression) NEED handling of bit and packed types. */ -int Tdi3SizeOf(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3SizeOf(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; int size = 0; - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_A: size = ((struct descriptor_a *)in_ptr)->arsize; break; @@ -609,10 +631,12 @@ static const unsigned int G_TINY[] = {0x10, 0}; static const unsigned int FS_TINY[] = {0x800000}; static const unsigned int FT_TINY[] = {0, 0x100000}; -int Tdi3Tiny(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Tiny(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; - switch (in_ptr->dtype) { + switch (in_ptr->dtype) + { default: status = TdiINVDTYDSC; break; @@ -644,7 +668,8 @@ int Tdi3Tiny(struct descriptor *in_ptr, struct descriptor *out_ptr) { Dot product of two vectors. */ int Tdi3DotProduct(struct descriptor_a *in1_ptr, struct descriptor_a *in2_ptr, - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ int lsum; /*need wsum and bsum when supported */ char *p1 = in1_ptr->pointer; int inc1 = in1_ptr->class == CLASS_A ? in1_ptr->length : 0; @@ -657,7 +682,8 @@ int Tdi3DotProduct(struct descriptor_a *in1_ptr, struct descriptor_a *in2_ptr, N_ELEMENTS(in2_ptr, n2); if (n > n2) n = n2; - switch (out_ptr->dtype) { + switch (out_ptr->dtype) + { case DTYPE_B: case DTYPE_BU: for (lsum = 0; --n >= 0; p1 += inc1, p2 += inc2) @@ -686,20 +712,20 @@ int Tdi3DotProduct(struct descriptor_a *in1_ptr, struct descriptor_a *in2_ptr, break; MDS_ATTR_FALLTHROUGH default: - if (inc1) { + if (inc1) + { status = Tdi3Multiply(in1_ptr, in2_ptr, in1_ptr); - if - STATUS_OK - status = TdiSum(in1_ptr, &tmp MDS_END_ARG); - } else { + if (STATUS_OK) + status = TdiSum(in1_ptr, &tmp MDS_END_ARG); + } + else + { status = Tdi3Multiply(in1_ptr, in2_ptr, in2_ptr); - if - STATUS_OK - status = TdiSum(in2_ptr, &tmp MDS_END_ARG); + if (STATUS_OK) + status = TdiSum(in2_ptr, &tmp MDS_END_ARG); } - if - STATUS_OK - _MOVC3(out_ptr->length, tmp.pointer->pointer, out_ptr->pointer); + if (STATUS_OK) + _MOVC3(out_ptr->length, tmp.pointer->pointer, out_ptr->pointer); break; } MdsFree1Dx(&tmp, 0); diff --git a/tdishr/TdiSetRange.c b/tdishr/TdiSetRange.c index 5ed6a54169..2dd16a7ac4 100644 --- a/tdishr/TdiSetRange.c +++ b/tdishr/TdiSetRange.c @@ -55,7 +55,8 @@ extern int TdiConvert(); extern int TdiMasterData(); int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const DESCRIPTOR_A(arr0, 1, DTYPE_BU, 0, 1); struct descriptor_xd sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, @@ -71,42 +72,47 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], ******************/ status = TdiGetArgs(opcode, 1, &list[narg - 1], sig, uni, dat, cats); - if - STATUS_OK { - memcpy(&arr, &arr0, sizeof(arr0)); - arr.a0 = NULL; - pa = (array_bounds *)dat[0].pointer; - if (pa == 0) - status = TdiNULL_PTR; - /******************* + if (STATUS_OK) + { + memcpy(&arr, &arr0, sizeof(arr0)); + arr.a0 = NULL; + pa = (array_bounds *)dat[0].pointer; + if (pa == 0) + status = TdiNULL_PTR; + /******************* Accept scalars also. *******************/ - else - switch (pa->class) { - case CLASS_S: - case CLASS_D: - bounds = coeff = ndim = 0; - break; - case CLASS_A: - if ((coeff = pa->aflags.coeff) == 1) { - ndim = pa->dimct; - bounds = pa->aflags.bounds; - } else { - bounds = 0; - ndim = 1; - } - break; - default: - status = TdiINVCLADSC; - break; + else + switch (pa->class) + { + case CLASS_S: + case CLASS_D: + bounds = coeff = ndim = 0; + break; + case CLASS_A: + if ((coeff = pa->aflags.coeff) == 1) + { + ndim = pa->dimct; + bounds = pa->aflags.bounds; } - } + else + { + bounds = 0; + ndim = 1; + } + break; + default: + status = TdiINVCLADSC; + break; + } + } arr.dimct = (unsigned char)(dimct = narg - 1); /****************************** For each input, check defaults. ******************************/ - for (j = 0; j < dimct; ++j) { + for (j = 0; j < dimct; ++j) + { /********************* Omitted, use original. @@ -118,11 +124,11 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], /***************** Get data or range. *****************/ - else { + else + { unsigned char omits[] = {(unsigned char)DTYPE_RANGE, 0}; - if - STATUS_OK - status = tdi_get_data(omits, list[j], &tmp); + if (STATUS_OK) + status = tdi_get_data(omits, list[j], &tmp); if (STATUS_NOT_OK) break; prange = (struct descriptor_range *)tmp.pointer; @@ -130,14 +136,17 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], /********************************** Simple limit is number of elements. **********************************/ - if (prange->dtype != DTYPE_RANGE) { + if (prange->dtype != DTYPE_RANGE) + { lo = 0; status = TdiGetLong(&tmp, &hi); --hi; - } else if (!(prange->ndesc == 2 || - (prange->ndesc == 3 && prange->deltaval == 0))) + } + else if (!(prange->ndesc == 2 || + (prange->ndesc == 3 && prange->deltaval == 0))) status = TdiINVDTYDSC; - else { + else + { if (prange->begin) status = TdiGetLong(prange->begin, &lo); else @@ -152,11 +161,14 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], /*************************** Fill in defaults, if we can. ***************************/ - if (STATUS_OK && (defhi || deflo)) { + if (STATUS_OK && (defhi || deflo)) + { if (j >= ndim) status = TdiINVDTYDSC; - else if (defhi) { - if (deflo) { + else if (defhi) + { + if (deflo) + { if (bounds) lo = pa->m[dimct + 2 * j]; else @@ -166,7 +178,9 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], hi = pa->m[j] - 1 + lo; else hi = (int)pa->arsize / (int)pa->length - 1 + lo; - } else { + } + else + { if (coeff) lo = hi + 1 - pa->m[j]; else @@ -174,7 +188,8 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], } } - if (lo != 0) { + if (lo != 0) + { arr.aflags.bounds = 1; arr.a0 = pa->pointer; arr.pointer = arr.a0 + lo; @@ -186,26 +201,24 @@ int Tdi1SetRange(opcode_t opcode, int narg, struct descriptor *list[], } MdsFree1Dx(&tmp, NULL); - if - STATUS_OK { - arr.aflags.coeff = (unsigned char)(dimct > 1 || arr.aflags.bounds); - status = MdsGet1DxA((struct descriptor_a *)&arr, &pa->length, &pa->dtype, - out_ptr); - } + if (STATUS_OK) + { + arr.aflags.coeff = (unsigned char)(dimct > 1 || arr.aflags.bounds); + status = MdsGet1DxA((struct descriptor_a *)&arr, &pa->length, &pa->dtype, + out_ptr); + } /*********************** Copy/expand data to new. ***********************/ - if - STATUS_OK - status = TdiConvert(pa, out_ptr->pointer MDS_END_ARG); + if (STATUS_OK) + status = TdiConvert(pa, out_ptr->pointer MDS_END_ARG); /****************************** Embed result in signal, if any. Then free input. ******************************/ - if - STATUS_OK - status = TdiMasterData(1, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(1, sig, uni, &cmode, out_ptr); if (sig[0].pointer) MdsFree1Dx(&sig[0], NULL); if (uni[0].pointer) diff --git a/tdishr/TdiShowVm.c b/tdishr/TdiShowVm.c index 1d89884e57..38a04391fd 100644 --- a/tdishr/TdiShowVm.c +++ b/tdishr/TdiShowVm.c @@ -35,7 +35,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int TdiGetLong(); -int Tdi1ShowVm() { +int Tdi1ShowVm() +{ /* INIT_STATUS; int code, contex = 0, j = 1, mask, zone_id = 0; @@ -48,7 +49,7 @@ int Tdi1ShowVm() { status = TdiGetLong(list[1], &mask); else mask = -1; - while STATUS_OK { + while (STATUS_OK) { status = LibFindVmZone(&contex, &zone_id); if (STATUS_OK && zone_id && j & mask) status = LibShowVmZone(&zone_id, &code); diff --git a/tdishr/TdiSort.c b/tdishr/TdiSort.c index 987a83d89e..7e3aa1542b 100644 --- a/tdishr/TdiSort.c +++ b/tdishr/TdiSort.c @@ -84,21 +84,32 @@ extern int TdiSortVal(); Equality test where different. */ #define NEQ_BU GTR_BU -static int GTR_BU(unsigned char *a, unsigned char *b) { return *a - *b; } +static int GTR_BU(unsigned char *a, unsigned char *b) +{ + return *a - *b; +} #define NEQ_WU GTR_WU -static int GTR_WU(unsigned short *a, unsigned short *b) { return *a - *b; } +static int GTR_WU(unsigned short *a, unsigned short *b) +{ + return *a - *b; +} #define NEQ_LU NEQ_L -static int GTR_LU(unsigned int *a, unsigned int *b) { return *a > *b; } +static int GTR_LU(unsigned int *a, unsigned int *b) +{ + return *a > *b; +} #define NEQ_QU NEQ_Q -static int GTR_QU(unsigned int a[2], unsigned int b[2]) { +static int GTR_QU(unsigned int a[2], unsigned int b[2]) +{ return a[1] > b[1] || (a[1] == b[1] && a[0] > b[0]); } #define NEQ_OU NEQ_O -static int GTR_OU(unsigned int a[4], unsigned int b[4]) { +static int GTR_OU(unsigned int a[4], unsigned int b[4]) +{ return a[3] > b[3] || (a[3] == b[3] && (a[2] > b[2] || @@ -106,28 +117,38 @@ static int GTR_OU(unsigned int a[4], unsigned int b[4]) { } #define NEQ_B GTR_B -static int GTR_B(char *a, char *b) { return *a - *b; } +static int GTR_B(char *a, char *b) +{ + return *a - *b; +} #define NEQ_W GTR_W -static int GTR_W(short *a, short *b) { return *a - *b; } +static int GTR_W(short *a, short *b) +{ + return *a - *b; +} static int NEQ_L(int *a, int *b) { return *a != *b; } static int GTR_L(int *a, int *b) { return *a > *b; } -static int NEQ_Q(unsigned int a[2], unsigned int b[2]) { +static int NEQ_Q(unsigned int a[2], unsigned int b[2]) +{ return a[0] != b[0] || a[1] != b[1]; } -static int GTR_Q(unsigned int a[2], unsigned int b[2]) { +static int GTR_Q(unsigned int a[2], unsigned int b[2]) +{ return (int)a[1] > (int)b[1] || (a[1] == b[1] && a[0] > b[0]); } -static int NEQ_O(unsigned int a[4], unsigned int b[4]) { +static int NEQ_O(unsigned int a[4], unsigned int b[4]) +{ return a[0] != b[0] || a[1] != b[1] || a[2] != b[2] || a[3] != b[3]; } -static int GTR_O(unsigned int a[4], unsigned int b[4]) { +static int GTR_O(unsigned int a[4], unsigned int b[4]) +{ return (int)a[3] > (int)b[3] || (a[3] == b[3] && (a[2] > b[2] || @@ -136,7 +157,8 @@ static int GTR_O(unsigned int a[4], unsigned int b[4]) { extern int CvtConvertFloat(); -static int GtrFloat(int dtype, void *a, void *b) { +static int GtrFloat(int dtype, void *a, void *b) +{ int ans = 0; float a_local; float b_local; @@ -146,7 +168,8 @@ static int GtrFloat(int dtype, void *a, void *b) { return ans; } -static int GtrDouble(int dtype, void *a, void *b) { +static int GtrDouble(int dtype, void *a, void *b) +{ int ans = 0; double a_local; double b_local; @@ -157,57 +180,78 @@ static int GtrDouble(int dtype, void *a, void *b) { } #define NEQ_F NEQ_L -static int GTR_F(void *a, void *b) { return GtrFloat(DTYPE_F, a, b); } +static int GTR_F(void *a, void *b) +{ + return GtrFloat(DTYPE_F, a, b); +} #define NEQ_FS NEQ_L -static int GTR_FS(void *a, void *b) { return GtrFloat(DTYPE_FS, a, b); } +static int GTR_FS(void *a, void *b) +{ + return GtrFloat(DTYPE_FS, a, b); +} #define NEQ_D NEQ_Q -static int GTR_D(void *a, void *b) { return GtrDouble(DTYPE_D, a, b); } +static int GTR_D(void *a, void *b) +{ + return GtrDouble(DTYPE_D, a, b); +} #define NEQ_G NEQ_Q -static int GTR_G(void *a, void *b) { return GtrDouble(DTYPE_G, a, b); } +static int GTR_G(void *a, void *b) +{ + return GtrDouble(DTYPE_G, a, b); +} #define NEQ_FT NEQ_Q -static int GTR_FT(void *a, void *b) { return GtrDouble(DTYPE_FT, a, b); } +static int GTR_FT(void *a, void *b) +{ + return GtrDouble(DTYPE_FT, a, b); +} #define NEQ_FC NEQ_Q -static int GTR_FC(float *a, float *b) { +static int GTR_FC(float *a, float *b) +{ if (NEQ_F((int *)a, (int *)b)) return GTR_F(&a[0], &b[0]); return GTR_F(&a[1], &b[1]); } #define NEQ_FSC NEQ_Q -static int GTR_FSC(float *a, float *b) { +static int GTR_FSC(float *a, float *b) +{ if (NEQ_FS((int *)a, (int *)b)) return GTR_FS(&a[0], &b[0]); return GTR_FS(&a[1], &b[1]); } #define NEQ_DC NEQ_O -static int GTR_DC(double *a, double *b) { +static int GTR_DC(double *a, double *b) +{ if (NEQ_D((unsigned int *)a, (unsigned int *)b)) return GTR_D(&a[0], &b[0]); return GTR_D(&a[1], &b[1]); } #define NEQ_GC NEQ_O -static int GTR_GC(double *a, double *b) { +static int GTR_GC(double *a, double *b) +{ if (NEQ_G((unsigned int *)a, (unsigned int *)b)) return GTR_G(&a[0], &b[0]); return GTR_G(&a[1], &b[1]); } #define NEQ_FTC NEQ_O -static int GTR_FTC(double *a, double *b) { +static int GTR_FTC(double *a, double *b) +{ if (NEQ_FT((unsigned int *)a, (unsigned int *)b)) return GTR_FT(&a[0], &b[0]); return GTR_FT(&a[1], &b[1]); } #define NEQ_T GTR_T -static int GTR_T(unsigned char *a, unsigned char *b, int len) { +static int GTR_T(unsigned char *a, unsigned char *b, int len) +{ register char *pa = (char *)a, *pb = (char *)b; register int n = len; for (; --n >= 0;) @@ -217,7 +261,8 @@ static int GTR_T(unsigned char *a, unsigned char *b, int len) { } int Tdi1Bsearch(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; int inc, hi, lo = -2, mid, *poutput; int upcase = 0, cmode = -1, len, mode = 0, ni = 0, nt = 0; @@ -230,195 +275,207 @@ int Tdi1Bsearch(opcode_t opcode, int narg, struct descriptor *list[], status = TdiGetArgs(opcode, 2, list, sig, uni, dat, cats); if (narg > 2 && STATUS_OK) status = TdiGetLong(list[2], &mode); - if - STATUS_OK - status = Tdi2Bsearch(2, uni, dat, cats); - if - STATUS_OK - status = TdiCvtArgs(2, dat, cats); - if - STATUS_OK { N_ELEMENTS(dat[0].pointer, ni); } - if - STATUS_OK { N_ELEMENTS(dat[1].pointer, nt); } - if - STATUS_OK - status = TdiGetShape(1, &dat[0], sizeof(int), DTYPE_L, &cmode, out_ptr); - if - STATUS_OK { - if (ni <= 0) { /* null output */ - } else if (nt <= 0) { - status = TdiNULL_PTR; /* cannot lookup */ - } else { - switch (dat[0].pointer->dtype) { - case DTYPE_BU: - neq = (int (*)()) & NEQ_BU; - gtr = (int (*)()) & GTR_BU; - break; - case DTYPE_WU: - neq = (int (*)()) & NEQ_WU; - gtr = (int (*)()) & GTR_WU; - break; - case DTYPE_NID: - case DTYPE_LU: - neq = (int (*)()) & NEQ_LU; - gtr = (int (*)()) & GTR_LU; - break; - case DTYPE_QU: - neq = (int (*)()) & NEQ_QU; - gtr = (int (*)()) & GTR_QU; - break; - case DTYPE_OU: - neq = (int (*)()) & NEQ_OU; - gtr = (int (*)()) & GTR_OU; - break; - - case DTYPE_B: - neq = (int (*)()) & NEQ_B; - gtr = (int (*)()) & GTR_B; - break; - case DTYPE_W: - neq = (int (*)()) & NEQ_W; - gtr = (int (*)()) & GTR_W; - break; - case DTYPE_L: - neq = (int (*)()) & NEQ_L; - gtr = (int (*)()) & GTR_L; - break; - case DTYPE_Q: - neq = (int (*)()) & NEQ_Q; - gtr = (int (*)()) & GTR_Q; - break; - case DTYPE_O: - neq = (int (*)()) & NEQ_O; - gtr = (int (*)()) & GTR_O; - break; - - case DTYPE_F: - neq = (int (*)()) & NEQ_F; - gtr = (int (*)()) & GTR_F; - break; - case DTYPE_FS: - neq = (int (*)()) & NEQ_FS; - gtr = (int (*)()) & GTR_FS; - break; - case DTYPE_D: - neq = (int (*)()) & NEQ_D; - gtr = (int (*)()) & GTR_D; - break; - case DTYPE_G: - neq = (int (*)()) & NEQ_G; - gtr = (int (*)()) & GTR_G; - break; - case DTYPE_FT: - neq = (int (*)()) & NEQ_FT; - gtr = (int (*)()) & GTR_FT; - break; - - case DTYPE_FC: - neq = (int (*)()) & NEQ_FC; - gtr = (int (*)()) & GTR_FC; - break; - case DTYPE_FSC: - neq = (int (*)()) & NEQ_FSC; - gtr = (int (*)()) & GTR_FSC; - break; - case DTYPE_DC: - neq = (int (*)()) & NEQ_DC; - gtr = (int (*)()) & GTR_DC; - break; - case DTYPE_GC: - neq = (int (*)()) & NEQ_GC; - gtr = (int (*)()) & GTR_GC; - break; - case DTYPE_FTC: - neq = (int (*)()) & NEQ_FTC; - gtr = (int (*)()) & GTR_FTC; - break; - - case DTYPE_PATH: - case DTYPE_EVENT: - case DTYPE_T: - neq = (int (*)()) & NEQ_T; - gtr = (int (*)()) & GTR_T; - if (narg > 3) - status = TdiGetLong(list[3], &upcase); - if (upcase & 1) { - if - STATUS_OK + if (STATUS_OK) + status = Tdi2Bsearch(2, uni, dat, cats); + if (STATUS_OK) + status = TdiCvtArgs(2, dat, cats); + if (STATUS_OK) + { + N_ELEMENTS(dat[0].pointer, ni); + } + if (STATUS_OK) + { + N_ELEMENTS(dat[1].pointer, nt); + } + if (STATUS_OK) + status = TdiGetShape(1, &dat[0], sizeof(int), DTYPE_L, &cmode, out_ptr); + if (STATUS_OK) + { + if (ni <= 0) + { /* null output */ + } + else if (nt <= 0) + { + status = TdiNULL_PTR; /* cannot lookup */ + } + else + { + switch (dat[0].pointer->dtype) + { + case DTYPE_BU: + neq = (int (*)()) & NEQ_BU; + gtr = (int (*)()) & GTR_BU; + break; + case DTYPE_WU: + neq = (int (*)()) & NEQ_WU; + gtr = (int (*)()) & GTR_WU; + break; + case DTYPE_NID: + case DTYPE_LU: + neq = (int (*)()) & NEQ_LU; + gtr = (int (*)()) & GTR_LU; + break; + case DTYPE_QU: + neq = (int (*)()) & NEQ_QU; + gtr = (int (*)()) & GTR_QU; + break; + case DTYPE_OU: + neq = (int (*)()) & NEQ_OU; + gtr = (int (*)()) & GTR_OU; + break; + + case DTYPE_B: + neq = (int (*)()) & NEQ_B; + gtr = (int (*)()) & GTR_B; + break; + case DTYPE_W: + neq = (int (*)()) & NEQ_W; + gtr = (int (*)()) & GTR_W; + break; + case DTYPE_L: + neq = (int (*)()) & NEQ_L; + gtr = (int (*)()) & GTR_L; + break; + case DTYPE_Q: + neq = (int (*)()) & NEQ_Q; + gtr = (int (*)()) & GTR_Q; + break; + case DTYPE_O: + neq = (int (*)()) & NEQ_O; + gtr = (int (*)()) & GTR_O; + break; + + case DTYPE_F: + neq = (int (*)()) & NEQ_F; + gtr = (int (*)()) & GTR_F; + break; + case DTYPE_FS: + neq = (int (*)()) & NEQ_FS; + gtr = (int (*)()) & GTR_FS; + break; + case DTYPE_D: + neq = (int (*)()) & NEQ_D; + gtr = (int (*)()) & GTR_D; + break; + case DTYPE_G: + neq = (int (*)()) & NEQ_G; + gtr = (int (*)()) & GTR_G; + break; + case DTYPE_FT: + neq = (int (*)()) & NEQ_FT; + gtr = (int (*)()) & GTR_FT; + break; + + case DTYPE_FC: + neq = (int (*)()) & NEQ_FC; + gtr = (int (*)()) & GTR_FC; + break; + case DTYPE_FSC: + neq = (int (*)()) & NEQ_FSC; + gtr = (int (*)()) & GTR_FSC; + break; + case DTYPE_DC: + neq = (int (*)()) & NEQ_DC; + gtr = (int (*)()) & GTR_DC; + break; + case DTYPE_GC: + neq = (int (*)()) & NEQ_GC; + gtr = (int (*)()) & GTR_GC; + break; + case DTYPE_FTC: + neq = (int (*)()) & NEQ_FTC; + gtr = (int (*)()) & GTR_FTC; + break; + + case DTYPE_PATH: + case DTYPE_EVENT: + case DTYPE_T: + neq = (int (*)()) & NEQ_T; + gtr = (int (*)()) & GTR_T; + if (narg > 3) + status = TdiGetLong(list[3], &upcase); + if (upcase & 1) + { + if (STATUS_OK) status = StrUpcase(dat[0].pointer, dat[0].pointer); - if - STATUS_OK + if (STATUS_OK) status = StrUpcase(dat[1].pointer, dat[1].pointer); - } - break; - default: - if (ni > 0) - status = TdiINVDTYDSC; - break; } + break; + default: + if (ni > 0) + status = TdiINVDTYDSC; + break; } } - if - STATUS_OK { - len = dat[0].pointer->length; - pinput = dat[0].pointer->pointer; - ptable = dat[1].pointer->pointer; - poutput = (int *)out_ptr->pointer->pointer; - for (; --ni >= 0; pinput += len) { - /********************************** + } + if (STATUS_OK) + { + len = dat[0].pointer->length; + pinput = dat[0].pointer->pointer; + ptable = dat[1].pointer->pointer; + poutput = (int *)out_ptr->pointer->pointer; + for (; --ni >= 0; pinput += len) + { + /********************************** Out of bounds does straight search. **********************************/ - if (lo < -1 || lo >= nt) { - lo = -1; - hi = nt; - } - /********************************* + if (lo < -1 || lo >= nt) + { + lo = -1; + hi = nt; + } + /********************************* Expand search from previous point. Adjust upper limit above previous. *********************************/ - else if (lo < 0 || (*gtr)(ptable + len * lo, pinput, len) <= 0) { - inc = 1; - while ((hi = lo + inc) < nt && - (*gtr)(ptable + len * hi, pinput, len) <= 0) { - lo = hi; - inc <<= 1; - } - if (hi > nt) - hi = nt; + else if (lo < 0 || (*gtr)(ptable + len * lo, pinput, len) <= 0) + { + inc = 1; + while ((hi = lo + inc) < nt && + (*gtr)(ptable + len * hi, pinput, len) <= 0) + { + lo = hi; + inc <<= 1; } - /********************************* + if (hi > nt) + hi = nt; + } + /********************************* Adjust lower limit below previous. *********************************/ - else { - inc = 1; - while (hi = lo, - (lo -= inc) >= 0 && (*gtr)(ptable + len * lo, pinput, len) > 0) - inc <<= 1; - if (lo < 0) - lo = -1; - } - /***************** + else + { + inc = 1; + while (hi = lo, + (lo -= inc) >= 0 && (*gtr)(ptable + len * lo, pinput, len) > 0) + inc <<= 1; + if (lo < 0) + lo = -1; + } + /***************** The binary search. *****************/ - while (hi - lo > 1) { - mid = (hi + lo) >> 1; - if ((*gtr)(ptable + len * mid, pinput, len) <= 0) - lo = mid; - else - hi = mid; - } - /************** - Equality check. - **************/ - if (mode > 0 || - (lo >= 0 && (*neq)(pinput, ptable + len * lo, len) == 0)) - *poutput++ = lo; - else if (mode == 0) - *poutput++ = -1; + while (hi - lo > 1) + { + mid = (hi + lo) >> 1; + if ((*gtr)(ptable + len * mid, pinput, len) <= 0) + lo = mid; else - *poutput++ = lo + 1; + hi = mid; } + /************** + Equality check. + **************/ + if (mode > 0 || + (lo >= 0 && (*neq)(pinput, ptable + len * lo, len) == 0)) + *poutput++ = lo; + else if (mode == 0) + *poutput++ = -1; + else + *poutput++ = lo + 1; } + } if (sig[1].pointer) MdsFree1Dx(&sig[1], NULL); if (uni[1].pointer) @@ -427,9 +484,8 @@ int Tdi1Bsearch(opcode_t opcode, int narg, struct descriptor *list[], MdsFree1Dx(&uni[0], NULL); MdsFree1Dx(&dat[1], NULL); MdsFree1Dx(&dat[0], NULL); - if - STATUS_OK - status = TdiMasterData(1, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(1, sig, uni, &cmode, out_ptr); if (sig[0].pointer) MdsFree1Dx(&sig[0], NULL); return status; @@ -449,7 +505,8 @@ int Tdi1Bsearch(opcode_t opcode, int narg, struct descriptor *list[], indices of equal value elements. */ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; int64_t ran = 0; int i, j, keep, l, r, jstack, *ndx; @@ -464,86 +521,87 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], status = TdiGetArgs(opcode, 1, list, sig, uni, dat, cats); if (uni[0].pointer) MdsFree1Dx(&uni[0], NULL); - if - STATUS_OK - switch (dat[0].pointer->dtype) { - case DTYPE_BU: - gtr = (int (*)()) & GTR_BU; - break; - case DTYPE_WU: - gtr = (int (*)()) & GTR_WU; - break; - case DTYPE_LU: - gtr = (int (*)()) & GTR_LU; - break; - case DTYPE_QU: - gtr = (int (*)()) & GTR_QU; - break; - case DTYPE_OU: - gtr = (int (*)()) & GTR_OU; - break; - - case DTYPE_B: - gtr = (int (*)()) & GTR_B; - break; - case DTYPE_W: - gtr = (int (*)()) & GTR_W; - break; - case DTYPE_L: - gtr = (int (*)()) & GTR_L; - break; - case DTYPE_Q: - gtr = (int (*)()) & GTR_Q; - break; - case DTYPE_O: - gtr = (int (*)()) & GTR_O; - break; - - case DTYPE_F: - gtr = (int (*)()) & GTR_F; - break; - case DTYPE_FS: - gtr = (int (*)()) & GTR_FS; - break; - case DTYPE_D: - gtr = (int (*)()) & GTR_D; - break; - case DTYPE_G: - gtr = (int (*)()) & GTR_G; - break; - case DTYPE_FT: - gtr = (int (*)()) & GTR_FT; - break; - - case DTYPE_FC: - gtr = (int (*)()) & GTR_FC; - break; - case DTYPE_DC: - gtr = (int (*)()) & GTR_DC; - break; - case DTYPE_GC: - gtr = (int (*)()) & GTR_GC; - break; - case DTYPE_FTC: - gtr = (int (*)()) & GTR_FTC; - break; - - case DTYPE_T: - gtr = (int (*)()) & GTR_T; - if (narg > 1) - status = TdiGetLong(list[1], &upcase); - if (STATUS_OK && IS_OK(upcase)) - status = StrUpcase(dat[0].pointer, dat[0].pointer); - break; - default: - status = TdiINVDTYDSC; - break; + if (STATUS_OK) + switch (dat[0].pointer->dtype) + { + case DTYPE_BU: + gtr = (int (*)()) & GTR_BU; + break; + case DTYPE_WU: + gtr = (int (*)()) & GTR_WU; + break; + case DTYPE_LU: + gtr = (int (*)()) & GTR_LU; + break; + case DTYPE_QU: + gtr = (int (*)()) & GTR_QU; + break; + case DTYPE_OU: + gtr = (int (*)()) & GTR_OU; + break; + + case DTYPE_B: + gtr = (int (*)()) & GTR_B; + break; + case DTYPE_W: + gtr = (int (*)()) & GTR_W; + break; + case DTYPE_L: + gtr = (int (*)()) & GTR_L; + break; + case DTYPE_Q: + gtr = (int (*)()) & GTR_Q; + break; + case DTYPE_O: + gtr = (int (*)()) & GTR_O; + break; + + case DTYPE_F: + gtr = (int (*)()) & GTR_F; + break; + case DTYPE_FS: + gtr = (int (*)()) & GTR_FS; + break; + case DTYPE_D: + gtr = (int (*)()) & GTR_D; + break; + case DTYPE_G: + gtr = (int (*)()) & GTR_G; + break; + case DTYPE_FT: + gtr = (int (*)()) & GTR_FT; + break; + + case DTYPE_FC: + gtr = (int (*)()) & GTR_FC; + break; + case DTYPE_DC: + gtr = (int (*)()) & GTR_DC; + break; + case DTYPE_GC: + gtr = (int (*)()) & GTR_GC; + break; + case DTYPE_FTC: + gtr = (int (*)()) & GTR_FTC; + break; + + case DTYPE_T: + gtr = (int (*)()) & GTR_T; + if (narg > 1) + status = TdiGetLong(list[1], &upcase); + if (STATUS_OK && IS_OK(upcase)) + status = StrUpcase(dat[0].pointer, dat[0].pointer); + break; + default: + status = TdiINVDTYDSC; + break; + } + if (STATUS_OK) + status = TdiGetShape(1, &dat[0], sizeof(int), DTYPE_L, &cmode, out_ptr); + if (STATUS_OK) + { + N_ELEMENTS(dat[0].pointer, n); } - if - STATUS_OK - status = TdiGetShape(1, &dat[0], sizeof(int), DTYPE_L, &cmode, out_ptr); - if - STATUS_OK { N_ELEMENTS(dat[0].pointer, n); } if (STATUS_NOT_OK || n <= 0) goto done; @@ -559,12 +617,15 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], for (i = 0; i < n; ++i) *ndx++ = i; ndx = (int *)out_ptr->pointer->pointer; - for (;;) { + for (;;) + { /********************************************* Insertion sort for small ranges. Say, 7 to 13. *********************************************/ - while (r - l < 11) { - for (j = l; ++j <= r;) { + while (r - l < 11) + { + for (j = l; ++j <= r;) + { keep = *(ndx + j); pkeep = pinput + len * keep; for (i = j; @@ -597,7 +658,8 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], Those at lower location with lower value stick. Stuff misfits in opposite side. ************************************************/ - for (;;) { + for (;;) + { while (i < j && (*gtr)(pinput + len * *(ndx + j), pkeep, len) > 0) --j; if (i == j) @@ -615,11 +677,14 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], /********************************************************** With i as breakpoint, put larger block on stack for latter. **********************************************************/ - if (i - l <= r - i) { + if (i - l <= r - i) + { stack[jstack++] = i + 1; stack[jstack++] = r; r = i - 1; - } else { + } + else + { stack[jstack++] = l; stack[jstack++] = i - 1; l = i + 1; @@ -629,10 +694,10 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], if (uni[0].pointer) MdsFree1Dx(&uni[0], NULL); MdsFree1Dx(&dat[0], NULL); - if (sig[0].pointer) { - if - STATUS_OK - status = TdiMasterData(1, &sig[0], uni, &cmode, out_ptr); + if (sig[0].pointer) + { + if (STATUS_OK) + status = TdiMasterData(1, &sig[0], uni, &cmode, out_ptr); MdsFree1Dx(&sig[0], NULL); } return status; @@ -645,17 +710,16 @@ int Tdi1Sort(opcode_t opcode, int narg, struct descriptor *list[], Method: MAP(array, SORT(array, [upcase])) */ int Tdi1SortVal(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; status = TdiEvaluate(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = TdiSort(tmp.pointer, narg > 1 ? list[1] : 0, out_ptr MDS_END_ARG); - if - STATUS_OK - status = TdiMap(&tmp, out_ptr, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiSort(tmp.pointer, narg > 1 ? list[1] : 0, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiMap(&tmp, out_ptr, out_ptr MDS_END_ARG); if (tmp.pointer) MdsFree1Dx(&tmp, NULL); return status; @@ -667,95 +731,103 @@ int Tdi1SortVal(opcode_t opcode __attribute__((unused)), int narg, The signality is removed and units are joined by VECTOR. */ int Tdi1Union(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int j, n, len; char *pi, *po; status = TdiIntrinsic(OPC_VECTOR, narg, list, out_ptr); - if - STATUS_OK - status = TdiSortVal(out_ptr, out_ptr MDS_END_ARG); - if - STATUS_OK { - struct descriptor_with_units *pdwu = - (struct descriptor_with_units *)out_ptr->pointer; - struct descriptor_a *pdo = pdwu->dtype == DTYPE_WITH_UNITS - ? (struct descriptor_a *)pdwu->data - : (struct descriptor_a *)pdwu; - char *cptri, *cptro; - short *sptri, *sptro; - int *lptri, *lptro; - if (pdo->class != CLASS_A) - return status; - len = pdo->length; - po = pi = pdo->pointer; - n = (int)pdo->arsize / (int)pdo->length; - switch (len) { - case 1: - for (cptri = (char *)pi, cptro = (char *)po; --n > 0;) - if (*++cptri != *cptro) - *++cptro = *cptri; - po = (char *)cptro; - break; - case 2: - for (sptri = (short *)pi, sptro = (short *)po; --n > 0;) - if (*++sptri != *sptro) - *++sptro = *sptri; - po = (char *)sptro; - break; - case 4: - for (lptri = (int *)pi, lptro = (int *)po; --n > 0;) - if (*++lptri != *lptro) - *++lptro = *lptri; - po = (char *)lptro; - break; + if (STATUS_OK) + status = TdiSortVal(out_ptr, out_ptr MDS_END_ARG); + if (STATUS_OK) + { + struct descriptor_with_units *pdwu = + (struct descriptor_with_units *)out_ptr->pointer; + struct descriptor_a *pdo = pdwu->dtype == DTYPE_WITH_UNITS + ? (struct descriptor_a *)pdwu->data + : (struct descriptor_a *)pdwu; + char *cptri, *cptro; + short *sptri, *sptro; + int *lptri, *lptro; + if (pdo->class != CLASS_A) + return status; + len = pdo->length; + po = pi = pdo->pointer; + n = (int)pdo->arsize / (int)pdo->length; + switch (len) + { + case 1: + for (cptri = (char *)pi, cptro = (char *)po; --n > 0;) + if (*++cptri != *cptro) + *++cptro = *cptri; + po = (char *)cptro; + break; + case 2: + for (sptri = (short *)pi, sptro = (short *)po; --n > 0;) + if (*++sptri != *sptro) + *++sptro = *sptri; + po = (char *)sptro; + break; + case 4: + for (lptri = (int *)pi, lptro = (int *)po; --n > 0;) + if (*++lptri != *lptro) + *++lptro = *lptri; + po = (char *)lptro; + break; + default: + switch (len & 3) + { default: - switch (len & 3) { - default: - for (; --n > 0;) { - pi += len; - for (j = 0; j < len; j += 1) - if (*(char *)(pi + j) != *(char *)(po + j)) - break; - if (j < len) { - po += len; - _MOVC3(len, pi, po); - } + for (; --n > 0;) + { + pi += len; + for (j = 0; j < len; j += 1) + if (*(char *)(pi + j) != *(char *)(po + j)) + break; + if (j < len) + { + po += len; + _MOVC3(len, pi, po); } - break; - case 2: - for (; --n > 0;) { - pi += len; - for (j = 0; j < len; j += 2) - if (*(short *)(pi + j) != *(short *)(po + j)) - break; - if (j < len) { - po += len; - _MOVC3(len, pi, po); - } + } + break; + case 2: + for (; --n > 0;) + { + pi += len; + for (j = 0; j < len; j += 2) + if (*(short *)(pi + j) != *(short *)(po + j)) + break; + if (j < len) + { + po += len; + _MOVC3(len, pi, po); } - break; - case 0: - for (; --n > 0;) { - pi += len; - for (j = 0; j < len; j += 4) - if (*(int *)(pi + j) != *(int *)(po + j)) - break; - if (j < len) { - po += len; - _MOVC3(len, pi, po); - } + } + break; + case 0: + for (; --n > 0;) + { + pi += len; + for (j = 0; j < len; j += 4) + if (*(int *)(pi + j) != *(int *)(po + j)) + break; + if (j < len) + { + po += len; + _MOVC3(len, pi, po); } - break; } break; } - pdo->arsize = (po - pdo->pointer) + len; - pdo->aflags.coeff = 0; - pdo->aflags.bounds = 0; - pdo->dimct = 1; + break; } + pdo->arsize = (po - pdo->pointer) + len; + pdo->aflags.coeff = 0; + pdo->aflags.bounds = 0; + pdo->dimct = 1; + } return status; } @@ -768,16 +840,15 @@ int Tdi1Union(opcode_t opcode __attribute__((unused)), int narg, upcase compare in uppercase (for text only) */ int Tdi1IsIn(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *pupcase = narg > 2 ? list[2] : 0; status = TdiSortVal(list[1], pupcase, out_ptr MDS_END_ARG); - if - STATUS_OK - status = TdiBsearch(list[0], out_ptr, 0, pupcase, out_ptr MDS_END_ARG); - if - STATUS_OK - status = TdiGe(out_ptr, 0, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiBsearch(list[0], out_ptr, 0, pupcase, out_ptr MDS_END_ARG); + if (STATUS_OK) + status = TdiGe(out_ptr, 0, out_ptr MDS_END_ARG); return status; } diff --git a/tdishr/TdiSql.c b/tdishr/TdiSql.c index fd2e1e3fda..10a3b5af09 100644 --- a/tdishr/TdiSql.c +++ b/tdishr/TdiSql.c @@ -76,11 +76,13 @@ extern int TdiText(); #define MAXPARSE 16384 static const DESCRIPTOR(dunderscore, "_"); -typedef struct { +typedef struct +{ unsigned int l0; int l1; } quadw; -typedef struct { +typedef struct +{ int used; int c; struct descriptor **v; @@ -151,7 +153,8 @@ typedef const LPBYTE LPCBYTE; #endif /*********************************************************/ -static int TDISQL_LINK(char *name, int (**routine)()) { +static int TDISQL_LINK(char *name, int (**routine)()) +{ static const DESCRIPTOR(dimage, "MdsSql"); #ifdef __APPLE__ static const DESCRIPTOR(dimage2, "sybdb"); @@ -159,15 +162,15 @@ static int TDISQL_LINK(char *name, int (**routine)()) { DESCRIPTOR_FROM_CSTRING(dname, name); int status = TdiFindImageSymbol(&dimage, &dname, routine); #ifdef __APPLE__ - if - STATUS_NOT_OK - status = TdiFindImageSymbol(&dimage2, &dname, routine); + if (STATUS_NOT_OK) + status = TdiFindImageSymbol(&dimage2, &dname, routine); #endif return status; } /*********************************************************/ -static int TDISQL_LINKCPTR(char *name, char *(**routine)()) { +static int TDISQL_LINKCPTR(char *name, char *(**routine)()) +{ static const DESCRIPTOR(dimage, "MdsSql"); #ifdef __APPLE__ static const DESCRIPTOR(dimage2, "sybdb"); @@ -184,7 +187,8 @@ static int TDISQL_LINKCPTR(char *name, char *(**routine)()) { static int date = 0; static int NaN = 0; -static struct ans_buf { +static struct ans_buf +{ void *vptr; int size; int offset; @@ -193,11 +197,15 @@ static struct ans_buf { } *bufs = 0; static int num_bufs = 0; -static void FreeBuffers() { +static void FreeBuffers() +{ int i; - if (bufs) { - for (i = 0; i < num_bufs; i++) { - if (bufs[i].vptr) { + if (bufs) + { + for (i = 0; i < num_bufs; i++) + { + if (bufs[i].vptr) + { free(bufs[i].vptr); } } @@ -209,7 +217,8 @@ static void FreeBuffers() { #define INITIAL_GUESS 32767 -static void AppendAnswer(int idx, void *buffer, int len, int dtype) { +static void AppendAnswer(int idx, void *buffer, int len, int dtype) +{ int needed = len; /* if ((dtype == SYBDATETIME) || (dtype == SYBDATETIME4) && !date) dtype = @@ -225,7 +234,8 @@ static void AppendAnswer(int idx, void *buffer, int len, int dtype) { bufs[idx].offset=0; } */ - if (bufs[idx].size < (bufs[idx].offset + needed)) { + if (bufs[idx].size < (bufs[idx].offset + needed)) + { int new_size = (bufs[idx].size == 0) ? INITIAL_GUESS * len : 3 * bufs[idx].size; if (new_size < bufs[idx].offset + needed) @@ -235,13 +245,15 @@ static void AppendAnswer(int idx, void *buffer, int len, int dtype) { } memcpy((void *)((char *)bufs[idx].vptr + bufs[idx].offset), buffer, len); bufs[idx].offset += len; - if (dtype == DTYPE_T) { + if (dtype == DTYPE_T) + { char *cptr = bufs[idx].vptr; cptr[bufs[idx].offset++] = 1; } } -static void StoreAnswer(int idx, struct descriptor *dst, int type) { +static void StoreAnswer(int idx, struct descriptor *dst, int type) +{ INIT_STATUS; DESCRIPTOR_A(src, 0, 0, 0, 0); struct descriptor_xd xs = {0, DTYPE_DSC, CLASS_XS, 0, sizeof(src)}; @@ -252,7 +264,8 @@ static void StoreAnswer(int idx, struct descriptor *dst, int type) { type = SYBTEXT; src.pointer = bufs[idx].vptr; src.arsize = bufs[idx].offset; - switch (type) { + switch (type) + { case SYBFLT8: src.length = 8; src.dtype = DTYPE_FT; @@ -280,33 +293,40 @@ static void StoreAnswer(int idx, struct descriptor *dst, int type) { break; case SYBCHAR: case SYBTEXT: - case SYBMONEY: { + case SYBMONEY: + { int num = bufs[idx].offset / 32767 + 1; - if (num > 1) { + if (num > 1) + { src.length = 32767; src.dtype = DTYPE_T; - if (bufs[idx].size < 32767 * num) { + if (bufs[idx].size < 32767 * num) + { src.pointer = bufs[idx].vptr = realloc(bufs[idx].vptr, 32767 * num); bufs[idx].size = 32767 * num; } - if (bufs[idx].offset < 32767 * num) { + if (bufs[idx].offset < 32767 * num) + { memset(((char *)src.pointer) + bufs[idx].offset, 0, 32767 * num - bufs[idx].offset); } src.arsize = 32767 * num; - } else { + } + else + { t_dsc.length = bufs[idx].offset; t_dsc.pointer = bufs[idx].vptr; xs.pointer = &t_dsc; } - } break; + } + break; default: status = MDSplusERROR; } - if - STATUS_OK - status = tdi_put_ident(dst, &xs); - else status = tdi_put_ident(dst, &xd); + if (STATUS_OK) + status = tdi_put_ident(dst, &xs); + else + status = tdi_put_ident(dst, &xd); free(bufs[idx].vptr); bufs[idx].vptr = 0; bufs[idx].size = 0; @@ -330,8 +350,10 @@ ARGLIST *arg; char *buf; static struct descriptor name = {0, DTYPE_T, CLASS_S, 0}; - if (rows == 0) { - if (bufs) { + if (rows == 0) + { + if (bufs) + { FreeBuffers(); } if (ncol > 0) @@ -342,9 +364,12 @@ ARGLIST *arg; // if (used + ncol < arg->c) status = TdiEXTRA_ARG; // if (used + ncol > arg->c) status = TdiMISS_ARG; */ - } else - for (j = 0; j < MAX(ncol, num_bufs); ++j, ++used) { - if (rows < 0) { + } + else + for (j = 0; j < MAX(ncol, num_bufs); ++j, ++used) + { + if (rows < 0) + { /* dst = (struct descriptor *)(used + j > arg->c ? 0 : * *(argv+used)); // should'nt it be used > arg-> c ? */ dst = (struct descriptor @@ -354,21 +379,24 @@ ARGLIST *arg; used)); /* // should'nt it be used > arg-> c ? */ while (dst && dst->dtype == DTYPE_DSC) dst = (struct descriptor *)dst->pointer; - if (dst == 0) { /* // && (rblob || (pda->SQLTYPE & ~1) != + if (dst == 0) + { /* // && (rblob || (pda->SQLTYPE & ~1) != SQL_TYPE_SEGMENT_ID)) { */ name.pointer = SYB_dbcolname(dbproc, j + 1); name.length = strlen(name.pointer); status = StrConcat(dst = (struct descriptor *)&madeup, (struct descriptor *)&dunderscore, &name MDS_END_ARG); - if - STATUS_NOT_OK - break; + if (STATUS_NOT_OK) + break; dst->dtype = DTYPE_IDENT; } StoreAnswer(j, dst, bufs[j].syb_type); - } else { - if (j > num_bufs) { + } + else + { + if (j > num_bufs) + { num_bufs++; bufs = realloc(bufs, num_bufs * sizeof(struct ans_buf)); bufs[j].size = 0; @@ -377,7 +405,8 @@ ARGLIST *arg; } buf = SYB_dbdata(dbproc, j + 1); ind = buf == (void *)NULL; - if ((bufs[j].syb_type == 0) || (bufs[j].len == 0)) { + if ((bufs[j].syb_type == 0) || (bufs[j].len == 0)) + { bufs[j].syb_type = SYB_dbcoltype(dbproc, j + 1); bufs[j].len = SYB_dbdatlen(dbproc, j + 1); } @@ -391,20 +420,25 @@ ARGLIST *arg; rows < 0; type = SYB_dbcoltype(dbproc, j+1); */ type = bufs[j].syb_type; - switch (type) { + switch (type) + { case SYBCHAR: case SYBTEXT: - if (ind) { + if (ind) + { buf = &space; len = 1; - } else { + } + else + { len = SYB_dbdatlen(dbproc, j + 1); } dtype = DTYPE_T; AppendAnswer(j, buf, len, dtype); break; case SYBFLT8: - if (ind) { + if (ind) + { buf = (NaN) ? (char *)&nan_d_bits : (char *)&HUGE_D; bufs[j].len = 8; } @@ -412,7 +446,8 @@ ARGLIST *arg; AppendAnswer(j, buf, bufs[j].len, dtype); break; case SYBREAL: - if (ind) { + if (ind) + { buf = (NaN) ? (char *)&nan_f_bits : (char *)&HUGE_F; bufs[j].len = 4; } @@ -420,7 +455,8 @@ ARGLIST *arg; AppendAnswer(j, buf, bufs[j].len, dtype); break; case SYBINT4: - if (ind) { + if (ind) + { buf = (char *)&HUGE_L; bufs[j].len = 4; } @@ -428,7 +464,8 @@ ARGLIST *arg; AppendAnswer(j, buf, bufs[j].len, dtype); break; case SYBINT2: - if (ind) { + if (ind) + { buf = (char *)&HUGE_W; bufs[j].len = 2; } @@ -436,7 +473,8 @@ ARGLIST *arg; AppendAnswer(j, buf, bufs[j].len, dtype); break; case SYBINT1: - if (ind) { + if (ind) + { buf = (char *)&HUGE_B; bufs[j].len = 1; } @@ -447,7 +485,8 @@ ARGLIST *arg; case SYBDATETIME4: /***convert date to double***/ case SYBDATETIME: /***convert date to double***/ - if (date) { /*Julian day 3 million?? is 17-Nov-1858 */ + if (date) + { /*Julian day 3 million?? is 17-Nov-1858 */ dtype = DTYPE_FT; #ifdef OLD int yr, mo, da, hr, mi, se, th, leap; @@ -456,12 +495,13 @@ ARGLIST *arg; (unsigned char *)ddate, sizeof(ddate) - 1); static const char *moname = "JanFebMarAprMayJunJulAugSepOctNovDec"; - static const int day[] = {0, 31, 59, 90, 120, 151, + static const int day[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; char mon[4], *moptr, ampm[3]; len = sizeof(d_null); - if (status < 0) { + if (status < 0) + { buf = (char *)&d_null; break; } @@ -469,7 +509,8 @@ ARGLIST *arg; if (type == SYBDATETIME) sscanf(ddate, "%3s %2d %4d %2d:%2d:%2d:%3d%2s", mon, &da, &yr, &hr, &mi, &se, &th, ampm); - else { + else + { sscanf(ddate, "%3s %2d %4d %2d:%2d%2s", mon, &da, &yr, &hr, &mi, ampm); se = 0; @@ -492,11 +533,14 @@ ARGLIST *arg; buf = (char *)&d_ans; #else d_ans = d_null; - if (bufs[j].len == 8) { + if (bufs[j].len == 8) + { d_ans = (double)(((int *)buf)[0] + 15020) + ((double)((unsigned int *)buf)[1]) / 300. / 60. / 60. / 24.; - } else if (bufs[j].len == 4) { + } + else if (bufs[j].len == 4) + { d_ans = (double)(((unsigned short *)buf)[0] + 15020) + ((double)((unsigned short *)buf)[1]) / 60. / 24.; } @@ -504,36 +548,47 @@ ARGLIST *arg; len = sizeof(d_ans); #endif AppendAnswer(j, buf, len, dtype); - } else { + } + else + { /***convert to text***/ - if (!ind) { + if (!ind) + { INIT_STATUS; #ifdef WORDS_BIGENDIAN unsigned long hi = *(unsigned long *)buf; *(unsigned long *)buf = *((unsigned long *)buf + 1); *((unsigned long *)buf + 1) = hi; #endif - if (bufs[j].len != 0) { + if (bufs[j].len != 0) + { status = SYB_dbconvert(dbproc, type, buf, bufs[j].len, SYBCHAR, (unsigned char *)ddate, sizeof(ddate) - 1); - if (status >= 0) { + if (status >= 0) + { ddate[status] = '\0'; len = status; - } else { + } + else + { strcpy(ddate, "FAILED"); len = strlen(ddate); } buf = ddate; dtype = DTYPE_T; - } else { + } + else + { buf = (char *)default_date; dtype = DTYPE_T; len = strlen(default_date); } AppendAnswer(j, buf, len, dtype); - } else { + } + else + { buf = (char *)default_date; dtype = DTYPE_T; len = strlen(default_date); @@ -551,9 +606,10 @@ ARGLIST *arg; return status; } -#define bufchk \ - if (pout == pout_end) { \ - return 0; \ +#define bufchk \ + if (pout == pout_end) \ + { \ + return 0; \ } static int Gets(pin, pout, nmarks, arg) char *pin, *pout; @@ -563,33 +619,40 @@ ARGLIST *arg; struct descriptor_xd **argv = (struct descriptor_xd **)arg->v, tmp = EMPTY_XD; int used = arg->used, status, i; char *pout_end = pout + MAXPARSE; - while (*pin) { - bufchk switch (*pin) { + while (*pin) + { + bufchk switch (*pin) + { default: /* copy text */ *pout++ = *pin++; break; case '\'': /* quoted string */ - while ((*pout++ = *pin) != 0) { + while ((*pout++ = *pin) != 0) + { bufchk if (*++pin == '\'') break; } break; case '"': /* quoted string */ - while ((*pout++ = *pin) != 0) { + while ((*pout++ = *pin) != 0) + { bufchk if (*++pin == '"') break; } break; case '?': ++pin; /* parameter marker */ ++*nmarks; - if (used >= arg->c) { + if (used >= arg->c) + { /* sprintf(hold, "Expect >= %d parameters, %d given.", * arg->used, arg->c); */ return TdiMISS_ARG; } if (argv && ((status = TdiData(*argv, &tmp MDS_END_ARG)) & 1) && (tmp.pointer->length) && - ((status = TdiText(&tmp, &tmp MDS_END_ARG)) & 1)) { - for (i = 0; i < tmp.pointer->length; i++) { + ((status = TdiText(&tmp, &tmp MDS_END_ARG)) & 1)) + { + for (i = 0; i < tmp.pointer->length; i++) + { bufchk *pout++ = *(char *)(tmp.pointer->pointer + i); } MdsFree1Dx(&tmp, NULL); @@ -606,7 +669,8 @@ ARGLIST *arg; /*********************************************************/ int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; int rows = 0; ARGLIST user_args = {0}; @@ -618,7 +682,8 @@ int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int narg, user_args.c = narg - 1; user_args.v = &list[1]; - if (SQL_DYNAMIC == 0) { + if (SQL_DYNAMIC == 0) + { status = TDISQL_LINK("SQL_DYNAMIC", &SQL_DYNAMIC); if (STATUS_OK && (SQL_GETDBMSGTEXT == 0)) TDISQL_LINKCPTR("GetDBMsgText", &SQL_GETDBMSGTEXT); @@ -635,52 +700,59 @@ int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int narg, if (STATUS_OK && (SYB_dbdata == 0)) TDISQL_LINKCPTR("dbdata", &SYB_dbdata); } - if - STATUS_OK - status = TdiData(list[0], &dtext MDS_END_ARG); + if (STATUS_OK) + status = TdiData(list[0], &dtext MDS_END_ARG); status = StrConcat((struct descriptor *)&dtext, (struct descriptor *)&dtext, &zero MDS_END_ARG); /* see if the last argument is "/date" */ - if - STATUS_OK { - int ss = TdiData(list[narg - 1], &dq_text MDS_END_ARG); - if (ss) { - if (dq_text.length == 5) - date = (strncmp("/date", dq_text.pointer, 5) == 0); - else - date = 0; - StrFree1Dx(&dq_text); - } else + if (STATUS_OK) + { + int ss = TdiData(list[narg - 1], &dq_text MDS_END_ARG); + if (ss) + { + if (dq_text.length == 5) + date = (strncmp("/date", dq_text.pointer, 5) == 0); + else date = 0; + StrFree1Dx(&dq_text); } + else + date = 0; + } /* see if the 2nd to last argument is "/NaN" */ - if (STATUS_OK && (narg > 2)) { + if (STATUS_OK && (narg > 2)) + { int ss = TdiData(list[narg - 2], &dq_text MDS_END_ARG); - if (ss) { + if (ss) + { if (dq_text.length == 4) NaN = (strncmp("/NaN", dq_text.pointer, 4) == 0); else NaN = 0; StrFree1Dx(&dq_text); - } else + } + else NaN = 0; - } else + } + else NaN = 0; - if - STATUS_OK - status = SQL_DYNAMIC(Gets, /*routine to fill markers */ - Puts, /*routine to store selctions */ - dtext.pointer, /*text string descriptor */ - &user_args, /*value passed to GETS and PUTS */ - &rows); /*output, number of rows */ + if (STATUS_OK) + status = SQL_DYNAMIC(Gets, /*routine to fill markers */ + Puts, /*routine to store selctions */ + dtext.pointer, /*text string descriptor */ + &user_args, /*value passed to GETS and PUTS */ + &rows); /*output, number of rows */ StrFree1Dx(&dtext); - if - STATUS_OK { status = MdsCopyDxXd(&drows, out_ptr); } - else { + if (STATUS_OK) + { + status = MdsCopyDxXd(&drows, out_ptr); + } + else + { struct descriptor msg = {0, DTYPE_T, CLASS_S, 0}; msg.pointer = SQL_GETDBMSGTEXT(); msg.length = strlen(msg.pointer); @@ -690,13 +762,15 @@ int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int narg, } /*********************************************************/ -int Tdi1Isql() { +int Tdi1Isql() +{ fprintf(stderr, "ISQL function no longer supported\n"); return 0; } /*********************************************************/ -int Tdi1IsqlSet() { +int Tdi1IsqlSet() +{ fprintf(stderr, "ISQL function no longer supported\n"); return 0; } @@ -707,7 +781,8 @@ static const DESCRIPTOR( int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), const struct descriptor *list[] __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = MdsCopyDxXd((struct descriptor *)&msg, out_ptr); return status; @@ -716,7 +791,8 @@ int Tdi1Dsql(opcode_t opcode __attribute__((unused)), int Tdi1Isql(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), const struct descriptor *list[] __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = MdsCopyDxXd((struct descriptor *)&msg, out_ptr); return status; @@ -725,7 +801,8 @@ int Tdi1Isql(opcode_t opcode __attribute__((unused)), int Tdi1IsqlSet(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), const struct descriptor *list[] __attribute__((unused)), - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = MdsCopyDxXd((struct descriptor *)&msg, out_ptr); return status; diff --git a/tdishr/TdiSquare.c b/tdishr/TdiSquare.c index e745462e0a..da999cd939 100644 --- a/tdishr/TdiSquare.c +++ b/tdishr/TdiSquare.c @@ -38,7 +38,8 @@ extern int Tdi3Floor(); /*-------------------------------------------------------------- Square a number by multiplying. */ -int Tdi3Square(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Square(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ return Tdi3Multiply(in_ptr, in_ptr, out_ptr); } @@ -47,22 +48,22 @@ int Tdi3Square(struct descriptor *in_ptr, struct descriptor *out_ptr) { */ int Tdi3Cmplx(struct descriptor *x_ptr, struct descriptor *y_ptr, struct descriptor *mold_ptr __attribute__((unused)), - struct descriptor *out_ptr) { + struct descriptor *out_ptr) +{ return Tdi3Complex(x_ptr, y_ptr, out_ptr); } /*-------------------------------------------------------------- F90 elemental, round to higher integral value. In CC it is CEIL. */ -int Tdi3Ceiling(struct descriptor *in_ptr, struct descriptor *out_ptr) { +int Tdi3Ceiling(struct descriptor *in_ptr, struct descriptor *out_ptr) +{ INIT_STATUS; status = Tdi3UnaryMinus(in_ptr, out_ptr); - if - STATUS_OK - status = Tdi3Floor(out_ptr, out_ptr); - if - STATUS_OK - status = Tdi3UnaryMinus(out_ptr, out_ptr); + if (STATUS_OK) + status = Tdi3Floor(out_ptr, out_ptr); + if (STATUS_OK) + status = Tdi3UnaryMinus(out_ptr, out_ptr); return status; } diff --git a/tdishr/TdiStatement.c b/tdishr/TdiStatement.c index 46d670d4b3..12d9e3e41f 100644 --- a/tdishr/TdiStatement.c +++ b/tdishr/TdiStatement.c @@ -62,7 +62,8 @@ int Tdi1Break() { return TdiBREAK; } CASE within SWITCH. */ int Tdi1Case(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ return TdiIntrinsic(OPC_STATEMENT, narg - 1, &list[1], out_ptr); } @@ -71,7 +72,8 @@ int Tdi1Case(opcode_t opcode __attribute__((unused)), int narg, result = evaluation,...evaluation */ int Tdi1Comma(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int j; @@ -91,7 +93,8 @@ int Tdi1Continue() { return TdiCONTINUE; } CASE DEFAULT within SWITCH. */ int Tdi1Default(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ return TdiIntrinsic(OPC_STATEMENT, narg, &list[0], out_ptr); } @@ -100,11 +103,13 @@ int Tdi1Default(opcode_t opcode __attribute__((unused)), int narg, DO {statement} WHILE (expression); */ int Tdi1Do(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int test; - do { + do + { status = TdiIntrinsic(OPC_STATEMENT, narg - 1, &list[1], out_ptr); if (STATUS_OK || status == TdiCONTINUE) status = TdiGetLong(list[0], &test); @@ -119,23 +124,25 @@ int Tdi1Do(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], FOR ([init]; [test]; [update]) statement */ int Tdi1For(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int test; if (list[0]) status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - while - STATUS_OK { - if (list[1]) { - status = TdiGetLong(list[1], &test); - if (STATUS_NOT_OK || IS_NOT_OK(test)) - break; - } - status = TdiIntrinsic(OPC_STATEMENT, narg - 3, &list[3], out_ptr); - if (STATUS_OK || status == TdiCONTINUE) - status = TdiEvaluate(list[2], out_ptr MDS_END_ARG); + while (STATUS_OK) + { + if (list[1]) + { + status = TdiGetLong(list[1], &test); + if (STATUS_NOT_OK || IS_NOT_OK(test)) + break; } + status = TdiIntrinsic(OPC_STATEMENT, narg - 3, &list[3], out_ptr); + if (STATUS_OK || status == TdiCONTINUE) + status = TdiEvaluate(list[2], out_ptr MDS_END_ARG); + } if (status == TdiBREAK) status = MDSplusSUCCESS; return status; @@ -147,18 +154,19 @@ int Tdi1For(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], */ int Tdi1Goto(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - if - STATUS_OK { - if (out_ptr->pointer->class != CLASS_S) - status = TdiINVCLADSC; - else if (out_ptr->pointer->dtype != DTYPE_T) - status = TdiINVDTYDSC; - else - status = TdiGOTO; - } + if (STATUS_OK) + { + if (out_ptr->pointer->class != CLASS_S) + status = TdiINVCLADSC; + else if (out_ptr->pointer->dtype != DTYPE_T) + status = TdiINVDTYDSC; + else + status = TdiGOTO; + } return status; } @@ -167,23 +175,23 @@ int Tdi1Goto(opcode_t opcode __attribute__((unused)), false. IF (expression) statement ELSE statement */ int Tdi1If(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int test = 0; status = TdiGetLong(list[0], &test); - if - IS_OK(test) { - if - STATUS_OK + if (IS_OK(test)) + { + if (STATUS_OK) status = TdiEvaluate(list[1], out_ptr MDS_END_ARG); - while (status == TdiGOTO) - status = goto1(1, &list[1], out_ptr); - } - else if (narg > 2) { - if - STATUS_OK - status = TdiEvaluate(list[2], out_ptr MDS_END_ARG); + while (status == TdiGOTO) + status = goto1(1, &list[1], out_ptr); + } + else if (narg > 2) + { + if (STATUS_OK) + status = TdiEvaluate(list[2], out_ptr MDS_END_ARG); while (status == TdiGOTO) status = goto1(1, &list[2], out_ptr); } @@ -198,18 +206,18 @@ int Tdi1If(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], first_good = IF_ERROR(a,...) */ int Tdi1IfError(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int j; - for (j = 0; j < narg; ++j) { + for (j = 0; j < narg; ++j) + { status = TdiEvaluate(list[j], out_ptr MDS_END_ARG); - if - STATUS_OK - break; + if (STATUS_OK) + break; } - if - STATUS_NOT_OK - MdsFree1Dx(out_ptr, NULL); + if (STATUS_NOT_OK) + MdsFree1Dx(out_ptr, NULL); return status; } @@ -218,7 +226,8 @@ int Tdi1IfError(opcode_t opcode __attribute__((unused)), int narg, label : stmt */ int Tdi1Label(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ return TdiIntrinsic(OPC_STATEMENT, narg - 1, &list[1], out_ptr); } @@ -236,15 +245,15 @@ int Tdi1Rem() { return MDSplusSUCCESS; } } */ int Tdi1Return(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; if (narg > 0 && list[0]) status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); else status = MdsFree1Dx(out_ptr, NULL); - if - STATUS_OK - status = TdiRETURN; + if (STATUS_OK) + status = TdiRETURN; return status; } @@ -275,7 +284,8 @@ int Tdi1Return(opcode_t opcode __attribute__((unused)), int narg, WHERE (exp) stmt ELSEWHERE stmt {stmt ...} */ -static int goto1(int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { +static int goto1(int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ int status = SsINTERNAL; int j = 0, off, opcode; mdsdsc_t *pstr = (mdsdsc_t *)out_ptr; @@ -286,19 +296,23 @@ static int goto1(int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { while (pstr && pstr->dtype == DTYPE_DSC) pstr = (mdsdsc_t *)pstr->pointer; if (pstr && pstr->dtype == DTYPE_T) - for (j = 0; status == 0 && j < narg; ++j) { + for (j = 0; status == 0 && j < narg; ++j) + { mds_function_t *pfun = (mds_function_t *)list[j]; if (pfun && pfun->dtype == DTYPE_DSC) pfun = (mds_function_t *)pfun->pointer; - if (pfun && pfun->dtype == DTYPE_FUNCTION) { + if (pfun && pfun->dtype == DTYPE_FUNCTION) + { off = -1; opcode = *(unsigned short *)pfun->pointer; - if (opcode == OPC_LABEL) { + if (opcode == OPC_LABEL) + { if (StrCompare(pfun->arguments[0], pstr) == 0) break; off = 1; - } else if (opcode == OPC_DEFAULT || opcode == OPC_STATEMENT) + } + else if (opcode == OPC_DEFAULT || opcode == OPC_STATEMENT) off = 0; else if (opcode == OPC_CASE) off = 1; @@ -317,7 +331,8 @@ static int goto1(int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { {statement ... statement} */ int Tdi1Statement(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int j; @@ -343,79 +358,94 @@ int Tdi1Statement(opcode_t opcode __attribute__((unused)), int narg, NEED to handle vector cases and stepped ranges, NEED IS_IN. */ static int switch_case(const mdsdsc_t *ptest, const mdsdsc_t *arg, - int *test_ptr, mdsdsc_xd_t *out_ptr) { + int *test_ptr, mdsdsc_xd_t *out_ptr) +{ int status = MDSplusSUCCESS; mds_function_t *const fun = (mds_function_t *)arg; - if (fun && fun->dtype == DTYPE_FUNCTION && *fun->pointer == OPC_COMMA) { + if (fun && fun->dtype == DTYPE_FUNCTION && *fun->pointer == OPC_COMMA) + { int i; - for (i = 0; STATUS_OK && IS_NOT_OK(*test_ptr) && i < fun->ndesc; i++) { + for (i = 0; STATUS_OK && IS_NOT_OK(*test_ptr) && i < fun->ndesc; i++) + { status = switch_case(ptest, fun->arguments[i], test_ptr, out_ptr); } - } else { + } + else + { mdsdsc_xd_t xd = EMPTY_XD; status = TdiEvaluate(arg, &xd MDS_END_ARG); - if - STATUS_OK { - mds_range_t *pr = (mds_range_t *)xd.pointer; - if (pr && pr->dtype == DTYPE_RANGE) { - if (pr->begin) { - status = TdiGe(ptest, pr->begin, out_ptr MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + mds_range_t *pr = (mds_range_t *)xd.pointer; + if (pr && pr->dtype == DTYPE_RANGE) + { + if (pr->begin) + { + status = TdiGe(ptest, pr->begin, out_ptr MDS_END_ARG); + if (STATUS_OK) status = TdiGetLong(out_ptr, test_ptr); - } else - *test_ptr = 1; - if (STATUS_OK && IS_OK(*test_ptr) && pr->ending) - status = TdiLe(ptest, pr->ending, out_ptr MDS_END_ARG); - } else - status = TdiEq(ptest, pr, out_ptr MDS_END_ARG); - MdsFree1Dx(&xd, NULL); - if - STATUS_OK - status = TdiGetLong(out_ptr, test_ptr); + } + else + *test_ptr = 1; + if (STATUS_OK && IS_OK(*test_ptr) && pr->ending) + status = TdiLe(ptest, pr->ending, out_ptr MDS_END_ARG); } + else + status = TdiEq(ptest, pr, out_ptr MDS_END_ARG); + MdsFree1Dx(&xd, NULL); + if (STATUS_OK) + status = TdiGetLong(out_ptr, test_ptr); + } } return status; } static int switch1(const mdsdsc_t *ptest, int *jdefault, mds_function_t ***pdefault, const int narg, - mds_function_t *list[], mdsdsc_xd_t *out_ptr) { + mds_function_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int j, off, test = FALSE; mdsdsc_xd_t tmp = EMPTY_XD; for (j = 0; STATUS_OK && j < narg; ++j) - if (list[j] && list[j]->dtype == DTYPE_FUNCTION) { + if (list[j] && list[j]->dtype == DTYPE_FUNCTION) + { opcode_t opcode = *list[j]->pointer; off = -1; if (opcode == OPC_STATEMENT) off = 0; - else if (opcode == OPC_CASE) { - if (list[j]->ndesc == 0) { + else if (opcode == OPC_CASE) + { + if (list[j]->ndesc == 0) + { status = TdiMISS_ARG; break; } status = switch_case(ptest, list[j]->arguments[0], &test, out_ptr); - if (STATUS_OK && IS_OK(test)) { + if (STATUS_OK && IS_OK(test)) + { *jdefault = 0; break; } off = 1; - } else if (opcode == OPC_DEFAULT) { + } + else if (opcode == OPC_DEFAULT) + { *jdefault = narg - j; *pdefault = &list[j]; off = 0; } - if (off >= 0 && STATUS_OK) { + if (off >= 0 && STATUS_OK) + { status = switch1(ptest, jdefault, pdefault, list[j]->ndesc - off, (mds_function_t **)&list[j]->arguments[off], out_ptr); - if - STATUS_OK { - ++j; - break; - } + if (STATUS_OK) + { + ++j; + break; + } if (status == TdiCASE) status = MDSplusSUCCESS; } @@ -423,7 +453,8 @@ static int switch1(const mdsdsc_t *ptest, int *jdefault, MdsFree1Dx(&tmp, NULL); if (STATUS_OK && j >= narg) status = TdiCASE; - else { + else + { *jdefault = 0; /*suppress the default because it is a match */ for (; STATUS_OK && j < narg; ++j) status = TdiEvaluate(list[j], out_ptr MDS_END_ARG); @@ -432,33 +463,37 @@ static int switch1(const mdsdsc_t *ptest, int *jdefault, } int Tdi1Switch(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int jdefault = 0; mds_function_t **pdefault = NULL; mdsdsc_xd_t tmp = EMPTY_XD; mds_function_t *const fun = (mds_function_t *)list[0]; if (fun && fun->dtype == DTYPE_FUNCTION && *fun->pointer == OPC_COMMA && - narg == 2 && !list[1]) { + narg == 2 && !list[1]) + { // switch used in function form list = fun->arguments; narg = fun->ndesc; } status = TdiEvaluate(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = switch1(tmp.pointer, &jdefault, &pdefault, narg - 1, - (mds_function_t **)&list[1], out_ptr); + if (STATUS_OK) + status = switch1(tmp.pointer, &jdefault, &pdefault, narg - 1, + (mds_function_t **)&list[1], out_ptr); MdsFree1Dx(&tmp, NULL); - if (status == TdiCASE) { + if (status == TdiCASE) + { status = MDSplusSUCCESS; - for (; jdefault > 0 && STATUS_OK; --jdefault, ++pdefault) { + for (; jdefault > 0 && STATUS_OK; --jdefault, ++pdefault) + { status = TdiEvaluate(*(mdsdsc_t **)pdefault, out_ptr MDS_END_ARG); } } if (status == TdiBREAK) status = MDSplusSUCCESS; - else { + else + { while (status == TdiGOTO) status = goto1(narg - 1, &list[1], out_ptr); if (status == SsINTERNAL) @@ -472,10 +507,12 @@ int Tdi1Switch(opcode_t opcode __attribute__((unused)), int narg, WHILE (expression) statement */ int Tdi1While(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; int test; - while (STATUS_OK || status == TdiCONTINUE) { + while (STATUS_OK || status == TdiCONTINUE) + { status = TdiGetLong(list[0], &test); if (STATUS_NOT_OK || IS_NOT_OK(test)) break; diff --git a/tdishr/TdiSubscript.c b/tdishr/TdiSubscript.c index 7f9e54f3de..6e57ac328c 100644 --- a/tdishr/TdiSubscript.c +++ b/tdishr/TdiSubscript.c @@ -89,12 +89,14 @@ extern int TdiSubtract(); extern int TdiEq(); extern int TdiGetLong(); -typedef struct { +typedef struct +{ int x[2]; } quadw; int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; register char *pin, *pout; @@ -106,8 +108,7 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], struct descriptor_dimension *pdim; struct descriptor_xd *keeps = TDI_SELF_PTR; array_coeff *pdat, *pdi = 0; - array_coeff arr = {1, DTYPE_B, CLASS_A, 0, 0, 0, {0, 1, 1, 1, 0}, - MAX_DIMS, 1, 0, {0}}; + array_coeff arr = {1, DTYPE_B, CLASS_A, 0, 0, 0, {0, 1, 1, 1, 0}, MAX_DIMS, 1, 0, {0}}; struct descriptor ddim = {sizeof(dim), DTYPE_L, CLASS_S, 0}; struct descriptor_xd ii[MAX_DIMS], xx[MAX_DIMS]; struct descriptor_xd sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, @@ -115,33 +116,39 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], struct TdiCatStruct cats[2]; ddim.pointer = (char *)&dim; status = TdiGetArgs(opcode, 1, list, sig, uni, dat, cats); - if - STATUS_NOT_OK { - if (dat[0].pointer && dat[0].pointer->dtype == DTYPE_DICTIONARY) { - unsigned int idx; - int check; - DESCRIPTOR_LONG(ans, &check); - ARRAY(struct descriptor *) *apd = (void *)dat[0].pointer; - for (idx = 0; idx < ((apd->arsize / apd->length) - 1); idx += 2) { - if (IS_OK(TdiEq(apd->pointer[idx], list[1], &ans MDS_END_ARG)) && - check == 1) { - status = MdsCopyDxXd(apd->pointer[idx + 1], out_ptr); - goto baddat; - } - } - status = MdsCopyDxXd(NULL, out_ptr); - } else if (dat[0].pointer && dat[0].pointer->dtype == DTYPE_LIST) { - unsigned int idx; - ARRAY(struct descriptor *) *apd = (void *)dat[0].pointer; - status = TdiGetLong(list[1], &idx); - if - STATUS_NOT_OK goto baddat; - if (idx < apd->arsize / apd->length) { - status = MdsCopyDxXd(apd->pointer[idx], out_ptr); + if (STATUS_NOT_OK) + { + if (dat[0].pointer && dat[0].pointer->dtype == DTYPE_DICTIONARY) + { + unsigned int idx; + int check; + DESCRIPTOR_LONG(ans, &check); + ARRAY(struct descriptor *) *apd = (void *)dat[0].pointer; + for (idx = 0; idx < ((apd->arsize / apd->length) - 1); idx += 2) + { + if (IS_OK(TdiEq(apd->pointer[idx], list[1], &ans MDS_END_ARG)) && + check == 1) + { + status = MdsCopyDxXd(apd->pointer[idx + 1], out_ptr); + goto baddat; } } - goto baddat; + status = MdsCopyDxXd(NULL, out_ptr); + } + else if (dat[0].pointer && dat[0].pointer->dtype == DTYPE_LIST) + { + unsigned int idx; + ARRAY(struct descriptor *) *apd = (void *)dat[0].pointer; + status = TdiGetLong(list[1], &idx); + if (STATUS_NOT_OK) + goto baddat; + if (idx < apd->arsize / apd->length) + { + status = MdsCopyDxXd(apd->pointer[idx], out_ptr); + } } + goto baddat; + } psig = (struct descriptor_signal *)sig[0].pointer; pdat = (array_coeff *)dat[0].pointer; stride[0] = len = pdat->length; @@ -150,7 +157,8 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], Set up first element address. ****************************/ pin = pdat->pointer; - switch (pdat->class) { + switch (pdat->class) + { case CLASS_S: case CLASS_D: dimct = 1; @@ -158,10 +166,12 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], case CLASS_A: if ((bounded = pdat->aflags.bounds) == 1) pin = pdat->a0; - if ((dimct = pdat->dimct) > MAX_DIMS) { + if ((dimct = pdat->dimct) > MAX_DIMS) + { status = TdiNDIM_OVER; goto baddat; - } else if (pdat->aflags.coeff) + } + else if (pdat->aflags.coeff) for (j = 0; j < dimct; ++j) stride[j + 1] = stride[j] * pdat->m[j]; else @@ -171,7 +181,8 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], status = TdiINVCLADSC; goto baddat; } - if (narg - 1 > dimct || (psig && psig->ndesc - 2 > dimct)) { + if (narg - 1 > dimct || (psig && psig->ndesc - 2 > dimct)) + { status = TdiINV_SIZE; goto baddat; } @@ -184,29 +195,29 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], (2) dimension is candidate. (3) just the data. ***************************************/ - for (dim = 0; dim < dimct; ++dim) { + for (dim = 0; dim < dimct; ++dim) + { ii[dim] = EMPTY_XD; xx[dim] = EMPTY_XD; - if - STATUS_OK { - pdim = (struct descriptor_dimension *)psig; - if (psig && dim < psig->ndesc - 2 && - (pdim = (struct descriptor_dimension *)psig->dimensions[dim]) != - 0) { - TDI_SELF_PTR = (struct descriptor_xd *)psig; - status = TdiCull(psig, &ddim, dim + 1 < narg ? list[dim + 1] : 0, - &xx[dim] MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) + { + pdim = (struct descriptor_dimension *)psig; + if (psig && dim < psig->ndesc - 2 && + (pdim = (struct descriptor_dimension *)psig->dimensions[dim]) != + 0) + { + TDI_SELF_PTR = (struct descriptor_xd *)psig; + status = TdiCull(psig, &ddim, dim + 1 < narg ? list[dim + 1] : 0, + &xx[dim] MDS_END_ARG); + if (STATUS_OK) status = TdiXtoI(pdim, xx[dim].pointer, &ii[dim] MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiItoX(pdim, ii[dim].pointer, &xx[dim] MDS_END_ARG); - if - STATUS_OK { - EMPTYXD(xd); + if (STATUS_OK) + { + EMPTYXD(xd); - /* + /* int tmp_status = TdiMinVal(pdim, &xd MDS_END_ARG); if IS_OK(tmp_status) { @@ -215,70 +226,72 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], status = TdiSubtract(&ii[dim],&xd,&ii[dim] MDS_END_ARG); } */ - int tmp_status = TdiWindowOf(pdim, &xd MDS_END_ARG); - if - IS_OK(tmp_status) { - struct descriptor_window *pwin = - (struct descriptor_window *)xd.pointer; - if (pwin && pwin->startidx) - status = TdiSubtract(&ii[dim], pwin->startidx, - &ii[dim] MDS_END_ARG); - } - MdsFree1Dx(&xd, NULL); - } - TDI_SELF_PTR = keeps; - if (STATUS_OK && bounded) - pin += *(int *)&pdat->m[dim * 2 + dimct] * stride[dim]; - highdim = dim + 1; - } else if (pdim && pdim->dtype == DTYPE_DIMENSION && dim + 1 < narg && - list[dim + 1]) { - status = TdiCull(pdat, &ddim, list[dim + 1], &xx[dim] MDS_END_ARG); - if - STATUS_OK + int tmp_status = TdiWindowOf(pdim, &xd MDS_END_ARG); + if (IS_OK(tmp_status)) + { + struct descriptor_window *pwin = + (struct descriptor_window *)xd.pointer; + if (pwin && pwin->startidx) + status = TdiSubtract(&ii[dim], pwin->startidx, + &ii[dim] MDS_END_ARG); + } + MdsFree1Dx(&xd, NULL); + } + TDI_SELF_PTR = keeps; + if (STATUS_OK && bounded) + pin += *(int *)&pdat->m[dim * 2 + dimct] * stride[dim]; + highdim = dim + 1; + } + else if (pdim && pdim->dtype == DTYPE_DIMENSION && dim + 1 < narg && + list[dim + 1]) + { + status = TdiCull(pdat, &ddim, list[dim + 1], &xx[dim] MDS_END_ARG); + if (STATUS_OK) status = TdiData(xx[dim].pointer, &ii[dim] MDS_END_ARG); - } else { - int left, right; - struct descriptor dleft = {sizeof(int), DTYPE_L, CLASS_S, 0}; - struct descriptor dright = {sizeof(int), DTYPE_L, CLASS_S, 0}; - dleft.pointer = (char *)&left; - dright.pointer = (char *)&right; - status = TdiLbound(pdat, &ddim, &dleft MDS_END_ARG); - if - STATUS_OK + } + else + { + int left, right; + struct descriptor dleft = {sizeof(int), DTYPE_L, CLASS_S, 0}; + struct descriptor dright = {sizeof(int), DTYPE_L, CLASS_S, 0}; + dleft.pointer = (char *)&left; + dright.pointer = (char *)&right; + status = TdiLbound(pdat, &ddim, &dleft MDS_END_ARG); + if (STATUS_OK) status = TdiUbound(pdat, &ddim, &dright MDS_END_ARG); - if (dim + 1 < narg && list[dim + 1]) { - struct descriptor *keep[3]; - keep[0] = TDI_RANGE_PTRS[0]; - keep[1] = TDI_RANGE_PTRS[1]; - keep[2] = TDI_RANGE_PTRS[2]; - TDI_RANGE_PTRS[0] = (struct descriptor *)&dleft; - TDI_RANGE_PTRS[1] = (struct descriptor *)&dright; - TDI_RANGE_PTRS[2] = 0; - if - STATUS_OK + if (dim + 1 < narg && list[dim + 1]) + { + struct descriptor *keep[3]; + keep[0] = TDI_RANGE_PTRS[0]; + keep[1] = TDI_RANGE_PTRS[1]; + keep[2] = TDI_RANGE_PTRS[2]; + TDI_RANGE_PTRS[0] = (struct descriptor *)&dleft; + TDI_RANGE_PTRS[1] = (struct descriptor *)&dright; + TDI_RANGE_PTRS[2] = 0; + if (STATUS_OK) status = TdiData(list[dim + 1], &ii[dim] MDS_END_ARG); - TDI_RANGE_PTRS[0] = keep[0]; - TDI_RANGE_PTRS[1] = keep[1]; - TDI_RANGE_PTRS[2] = keep[2]; - if - STATUS_OK + TDI_RANGE_PTRS[0] = keep[0]; + TDI_RANGE_PTRS[1] = keep[1]; + TDI_RANGE_PTRS[2] = keep[2]; + if (STATUS_OK) status = TdiLong(&ii[dim], &ii[dim] MDS_END_ARG); - if - STATUS_OK + if (STATUS_OK) status = TdiIcull(left, right, ii[dim].pointer); - if (status == SsINTERNAL) - status = TdiRecull(&ii[dim]); - } else if - STATUS_OK - status = TdiDtypeRange(&dleft, &dright, &ii[dim] MDS_END_ARG); + if (status == SsINTERNAL) + status = TdiRecull(&ii[dim]); } + else if (STATUS_OK) + status = TdiDtypeRange(&dleft, &dright, &ii[dim] MDS_END_ARG); } + } if (STATUS_OK && ii[dim].pointer->class == CLASS_R) status = TdiData(&ii[dim], &ii[dim] MDS_END_ARG); if (STATUS_OK && ii[dim].pointer->dtype != DTYPE_L) status = TdiNint(&ii[dim], &ii[dim] MDS_END_ARG); - if (STATUS_OK && (pdi = (array_coeff *)ii[dim].pointer) != 0) { - if (pdi->class == CLASS_A) { + if (STATUS_OK && (pdi = (array_coeff *)ii[dim].pointer) != 0) + { + if (pdi->class == CLASS_A) + { highest = dim + 1; } N_ELEMENTS(pdi, arr.m[dim]); @@ -299,17 +312,19 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], if (psig) for (j = psig->ndesc; --j >= 0;) psig->dimensions[j] = xx[j].pointer; - if (highest <= 0) { + if (highest <= 0) + { length_t llen = 0; dtype_t dtype = DTYPE_MISSING; if (arr.arsize) status = MdsGet1DxS(&pdat->length, &pdat->dtype, out_ptr); else status = MdsGet1DxS(&llen, &dtype, out_ptr); - if - STATUS_OK - _MOVC3(len, pin, out_ptr->pointer->pointer); - } else { + if (STATUS_OK) + _MOVC3(len, pin, out_ptr->pointer->pointer); + } + else + { arr.dimct = (dimct_t)highest; arr.aflags.coeff = (unsigned char)(highest > 1); status = MdsGet1DxA((struct descriptor_a *)&arr, &pdat->length, @@ -335,8 +350,10 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], Find the index to increment, reset those that overflow. Must avoid reading beyond end of vector. ******************************************************/ - for (j = 0; ++j < highest;) { - if (++count[j] < ((int)(arr.m[j]))) { + for (j = 0; ++j < highest;) + { + if (++count[j] < ((int)(arr.m[j]))) + { pin += stride[j] * (*(px[j] + count[j]) - *(px[j] + count[j] - 1)); goto inner; } @@ -348,12 +365,12 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], Dimensions of new signal. ************************/ empty: - if - STATUS_OK - status = TdiMasterData(1, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(1, sig, uni, &cmode, out_ptr); badsub: - for (j = dimct; --j >= 0;) { + for (j = dimct; --j >= 0;) + { MdsFree1Dx(&ii[j], NULL); MdsFree1Dx(&xx[j], NULL); } @@ -372,7 +389,8 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], A is treated as a linear array and subscripting is to nearest integer. */ int Tdi1Map(opcode_t opcode, int narg __attribute__((unused)), - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; struct descriptor_xd dwu = EMPTY_XD, sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, @@ -403,7 +421,8 @@ int Tdi1Map(opcode_t opcode, int narg __attribute__((unused)), len = pa->length; abase = pa->pointer; left = 0; - if (pa->class == CLASS_A && pa->aflags.bounds) { + if (pa->class == CLASS_A && pa->aflags.bounds) + { abase = pa->a0; left = (pa->pointer - abase) / len; } @@ -417,9 +436,8 @@ int Tdi1Map(opcode_t opcode, int narg __attribute__((unused)), TDI_RANGE_PTRS[0] = &range[0]; TDI_RANGE_PTRS[1] = &range[1]; TDI_RANGE_PTRS[2] = 0; - if - STATUS_OK - status = TdiGetArgs(opcode, 1, &list[1], sig, uni, dat, cats); + if (STATUS_OK) + status = TdiGetArgs(opcode, 1, &list[1], sig, uni, dat, cats); TDI_RANGE_PTRS[0] = keep[0]; TDI_RANGE_PTRS[1] = keep[1]; TDI_RANGE_PTRS[2] = keep[2]; @@ -427,95 +445,100 @@ int Tdi1Map(opcode_t opcode, int narg __attribute__((unused)), MdsFree1Dx(&uni[0], NULL); uni[0].pointer = (struct descriptor *)pwu->units; - if - STATUS_OK - switch (dat[0].pointer->dtype) { - case DTYPE_MISSING: - MdsFree1Dx(out_ptr, NULL); - goto none; - case DTYPE_L: - case DTYPE_LU: - break; - case DTYPE_B: - case DTYPE_BU: - case DTYPE_W: - case DTYPE_WU: - case DTYPE_Q: - case DTYPE_QU: - case DTYPE_O: - case DTYPE_OU: - status = TdiLong(&dat[0], &dat[0] MDS_END_ARG); - break; - default: - status = TdiNint(&dat[0], &dat[0] MDS_END_ARG); - if (STATUS_OK && dat[0].pointer->dtype != DTYPE_L) + if (STATUS_OK) + switch (dat[0].pointer->dtype) + { + case DTYPE_MISSING: + MdsFree1Dx(out_ptr, NULL); + goto none; + case DTYPE_L: + case DTYPE_LU: + break; + case DTYPE_B: + case DTYPE_BU: + case DTYPE_W: + case DTYPE_WU: + case DTYPE_Q: + case DTYPE_QU: + case DTYPE_O: + case DTYPE_OU: status = TdiLong(&dat[0], &dat[0] MDS_END_ARG); - break; - } + break; + default: + status = TdiNint(&dat[0], &dat[0] MDS_END_ARG); + if (STATUS_OK && dat[0].pointer->dtype != DTYPE_L) + status = TdiLong(&dat[0], &dat[0] MDS_END_ARG); + break; + } /******************************** Shape of B with data type from A. ********************************/ - if - STATUS_OK - status = TdiGetShape(1, &dat[0], len, pa->dtype, &cmode, out_ptr); - if - STATUS_OK { - po = out_ptr->pointer->pointer; - status = TdiIextend(left, right, dat[0].pointer); - pindex = (int *)dat[0].pointer->pointer; - if - STATUS_OK { - N_ELEMENTS(dat[0].pointer, n); - if (n <= 0) { - mdsdsc_a_t *const arr = (mdsdsc_a_t *)out_ptr->pointer; - arr->arsize = 0; - arr->aflags.coeff = 0; - goto none; - } - } + if (STATUS_OK) + status = TdiGetShape(1, &dat[0], len, pa->dtype, &cmode, out_ptr); + if (STATUS_OK) + { + po = out_ptr->pointer->pointer; + status = TdiIextend(left, right, dat[0].pointer); + pindex = (int *)dat[0].pointer->pointer; + if (STATUS_OK) + { + N_ELEMENTS(dat[0].pointer, n); + if (n <= 0) + { + mdsdsc_a_t *const arr = (mdsdsc_a_t *)out_ptr->pointer; + arr->arsize = 0; + arr->aflags.coeff = 0; + goto none; + } } - if - STATUS_OK { - char *cptr = (char *)po; - short *sptr = (short *)po; - int *iptr = (int *)po; - quadw *qptr = (quadw *)po; - switch (len) { - case 0: - break; - case 1: - while (--n >= 0) { - *cptr++ = *((char *)abase + *pindex++); - } - break; - case 2: - while (--n >= 0) { - *sptr++ = *((short *)abase + *pindex++); - } - break; - case 4: - while (--n >= 0) { - *iptr++ = *((int *)abase + *pindex++); - } - break; - case 8: - while (--n >= 0) { - *qptr++ = *((quadw *)abase + *pindex++); - } - break; - default: - while (--n >= 0) { - _MOVC3(len, (char *)abase + (len * *pindex++), po); - po += len; - } - break; + } + if (STATUS_OK) + { + char *cptr = (char *)po; + short *sptr = (short *)po; + int *iptr = (int *)po; + quadw *qptr = (quadw *)po; + switch (len) + { + case 0: + break; + case 1: + while (--n >= 0) + { + *cptr++ = *((char *)abase + *pindex++); + } + break; + case 2: + while (--n >= 0) + { + *sptr++ = *((short *)abase + *pindex++); } + break; + case 4: + while (--n >= 0) + { + *iptr++ = *((int *)abase + *pindex++); + } + break; + case 8: + while (--n >= 0) + { + *qptr++ = *((quadw *)abase + *pindex++); + } + break; + default: + while (--n >= 0) + { + _MOVC3(len, (char *)abase + (len * *pindex++), po); + po += len; + } + break; } + } none: - if - STATUS_OK - status = TdiMasterData(1, sig, uni, &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(1, sig, uni, &cmode, out_ptr); if (sig[0].pointer) MdsFree1Dx(&sig[0], NULL); MdsFree1Dx(&dat[0], NULL); diff --git a/tdishr/TdiThreadStatic.c b/tdishr/TdiThreadStatic.c index ceaafb44fe..40693bd6cd 100644 --- a/tdishr/TdiThreadStatic.c +++ b/tdishr/TdiThreadStatic.c @@ -39,8 +39,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "tdilex.h" #include "../mdsshr/version.h" -static inline TDITHREADSTATIC_TYPE *buffer_alloc() { - TDITHREADSTATIC_ARG = (TDITHREADSTATIC_TYPE *) calloc(1,sizeof(TDITHREADSTATIC_TYPE)); +static inline TDITHREADSTATIC_TYPE *buffer_alloc() +{ + TDITHREADSTATIC_ARG = (TDITHREADSTATIC_TYPE *)calloc(1, sizeof(TDITHREADSTATIC_TYPE)); LibCreateVmZone(&TDI_VAR_PRIVATE.head_zone); LibCreateVmZone(&TDI_VAR_PRIVATE.data_zone); TDI_INTRINSIC_STAT = SsSUCCESS; @@ -50,7 +51,8 @@ static inline TDITHREADSTATIC_TYPE *buffer_alloc() { TDI_VAR_NEW_NARG_D.dtype = DTYPE_L; TDI_VAR_NEW_NARG_D.class = CLASS_S; TDI_VAR_NEW_NARG_D.pointer = (char *)&TDI_VAR_NEW_NARG; - for (; TDI_STACK_IDXf2)(narg, uni, dat, cats, 0); + if (STATUS_OK) + status = (*pfun->f2)(narg, uni, dat, cats, 0); /****************************** Do the needed type conversions. ******************************/ - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); /******************** Get dimension number. Get mask pointer. ********************/ - if (pfun->f2 == Tdi2Mask2) { + if (pfun->f2 == Tdi2Mask2) + { if (narg > 1 && cats[1].in_dtype != DTYPE_MISSING) pmask = dat[1].pointer; - } else if (narg > 1 && cats[1].in_dtype != DTYPE_MISSING) { - if - STATUS_OK - status = TdiGetLong(dat[1].pointer, &dim); + } + else if (narg > 1 && cats[1].in_dtype != DTYPE_MISSING) + { + if (STATUS_OK) + status = TdiGetLong(dat[1].pointer, &dim); if (STATUS_OK && dim < 0) status = TdiBAD_INDEX; - } else if (pfun->f2 == Tdi2Sign) + } + else if (pfun->f2 == Tdi2Sign) status = TdiBAD_INDEX; - if (pfun->f2 == Tdi2Mask3 || pfun->f2 == Tdi2Mask3L) { + if (pfun->f2 == Tdi2Mask3 || pfun->f2 == Tdi2Mask3L) + { if (narg > 2 && cats[2].in_dtype != DTYPE_MISSING) pmask = dat[2].pointer; - } else if (opcode == OPC_REPLICATE || opcode == OPC_SPREAD) { - if - STATUS_OK - status = TdiGetLong(dat[2].pointer, &ncopies); + } + else if (opcode == OPC_REPLICATE || opcode == OPC_SPREAD) + { + if (STATUS_OK) + status = TdiGetLong(dat[2].pointer, &ncopies); if (ncopies < 0) ncopies = 0; } @@ -177,70 +181,80 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { Get rank,counts, and steps. **************************/ pa = (array_bounds *)dat[0].pointer; - if - STATUS_OK - switch (pa->class) { - case CLASS_A: - rank = pa->aflags.coeff ? pa->dimct : 1; - if (rank > MAX_DIMS) - status = TdiNDIM_OVER; - /** Whole array. Unrestricted. Product of multipliers == size, unchecked **/ - else if (dim < 0) { - count_dim = (int)pa->arsize / (int)pa->length; - } - /** Array with multipliers **/ - else if (pa->aflags.coeff) { - if (dim < rank || (dim <= rank && opcode == OPC_SPREAD)) { - for (j = 0; j < dim; ++j) - count_bef *= pa->m[j]; - if (j < rank) - count_dim = pa->m[j]; - for (; ++j < rank;) - count_aft *= pa->m[j]; - } else - status = TdiBAD_INDEX; - } - /** Simple vector. A mistake for some? **/ - else { - j = (int)pa->arsize / (int)pa->length; - if (dim == 1 && opcode == OPC_SPREAD) - count_bef = j; - else if (dim > 0) - status = TdiBAD_INDEX; + if (STATUS_OK) + switch (pa->class) + { + case CLASS_A: + rank = pa->aflags.coeff ? pa->dimct : 1; + if (rank > MAX_DIMS) + status = TdiNDIM_OVER; + /** Whole array. Unrestricted. Product of multipliers == size, unchecked **/ + else if (dim < 0) + { + count_dim = (int)pa->arsize / (int)pa->length; + } + /** Array with multipliers **/ + else if (pa->aflags.coeff) + { + if (dim < rank || (dim <= rank && opcode == OPC_SPREAD)) + { + for (j = 0; j < dim; ++j) + count_bef *= pa->m[j]; + if (j < rank) + count_dim = pa->m[j]; + for (; ++j < rank;) + count_aft *= pa->m[j]; + } + else + status = TdiBAD_INDEX; + } + /** Simple vector. A mistake for some? **/ else - count_dim = j; - } - break; - case CLASS_S: - case CLASS_D: - rank = 0; - if (dim > 0 || (dim > 1 && opcode == OPC_SPREAD)) { - status = TdiBAD_INDEX; + { + j = (int)pa->arsize / (int)pa->length; + if (dim == 1 && opcode == OPC_SPREAD) + count_bef = j; + else if (dim > 0) + status = TdiBAD_INDEX; + else + count_dim = j; + } + break; + case CLASS_S: + case CLASS_D: + rank = 0; + if (dim > 0 || (dim > 1 && opcode == OPC_SPREAD)) + { + status = TdiBAD_INDEX; + } + break; + default: + status = TdiINVCLADSC; + break; } - break; - default: - status = TdiINVCLADSC; - break; - } - if - STATUS_OK { N_ELEMENTS(pmask, mul); } - if - STATUS_OK { - if (pmask->class == CLASS_A && mul < count_bef * count_dim * count_aft) - status = TdiMISMATCH; - step_dim = count_bef; - step_aft = count_dim * count_bef; - /************ + if (STATUS_OK) + { + N_ELEMENTS(pmask, mul); + } + if (STATUS_OK) + { + if (pmask->class == CLASS_A && mul < count_bef * count_dim * count_aft) + status = TdiMISMATCH; + step_dim = count_bef; + step_aft = count_dim * count_bef; + /************ Optimization. ************/ - if (dim == 0 && opcode != OPC_REPLICATE && opcode != OPC_SPREAD) { - count_bef = count_aft; - count_aft = 1; - step_bef = step_aft; - } else - step_bef = 1; + if (dim == 0 && opcode != OPC_REPLICATE && opcode != OPC_SPREAD) + { + count_bef = count_aft; + count_aft = 1; + step_bef = step_aft; } + else + step_bef = 1; + } /****************** Find correct shape. @@ -263,16 +277,17 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { ndim = psig->ndesc - 2; else ndim = -1; - if (opcode == OPC_FIRSTLOC || opcode == OPC_LASTLOC) { + if (opcode == OPC_FIRSTLOC || opcode == OPC_LASTLOC) + { status = MdsGet1DxA((mdsdsc_a_t *)pa, &digits, &out_dtype, out_ptr); - if - STATUS_OK - status = TdiConvert(&zero, out_ptr->pointer MDS_END_ARG); + if (STATUS_OK) + status = TdiConvert(&zero, out_ptr->pointer MDS_END_ARG); } /*************************** Shape multiplied for DIM-th. ***************************/ - else if (opcode == OPC_REPLICATE) { + else if (opcode == OPC_REPLICATE) + { if (dim < ndim) psig->dimensions[dim] = 0; pmask = (mdsdsc_t *)&ncopies; @@ -280,7 +295,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { if (rank == 0) _MOVC3(head, (char *)pa, (char *)&arr); /** simple and coefficient vector **/ - else { + else + { _MOVC3(head, (char *)pa, (char *)&arr); arr.m[dim] *= ncopies; } @@ -290,8 +306,10 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /************************************* Shape gets new dimension after DIM-th. *************************************/ - else if (opcode == OPC_SPREAD) { - if (ndim > dim) { + else if (opcode == OPC_SPREAD) + { + if (ndim > dim) + { EMPTYXD(tmpxd); *(mds_signal_t *)&tmpsig = *psig; ++tmpsig.ndesc; @@ -315,7 +333,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { else if (rank >= MAX_DIMS) status = TdiNDIM_OVER; /** coefficient vector **/ - else if (pa->aflags.coeff) { + else if (pa->aflags.coeff) + { _MOVC3(head, (char *)pa, (char *)&arr); _MOVC3((short)(sizeof(int) * (rank - dim) * 2), (char *)&arr.m[rank + 2 * dim], @@ -328,7 +347,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { arr.dimct++; } /** simple vector to 2-D **/ - else { + else + { _MOVC3(head, (char *)pa, (char *)&arr); arr.dimct = 2; arr.aflags.coeff = 1; @@ -337,21 +357,22 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { arr.m[dim] = ncopies; } arr.arsize *= ncopies; - if - STATUS_OK - status = MdsGet1DxA((mdsdsc_a_t *)&arr, &digits, &out_dtype, out_ptr); + if (STATUS_OK) + status = MdsGet1DxA((mdsdsc_a_t *)&arr, &digits, &out_dtype, out_ptr); } /*************** Overwrite input. ***************/ - else if (opcode == OPC_ACCUMULATE) { + else if (opcode == OPC_ACCUMULATE) + { MdsFree1Dx(out_ptr, NULL); *out_ptr = dat[0]; } /******************* Same shape as input. *******************/ - else if (pfun->f2 == Tdi2Sign) { + else if (pfun->f2 == Tdi2Sign) + { if (psig && rank <= ndim) pmask = psig->dimensions[dim]; else @@ -361,7 +382,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /**************** Subscript vector. ****************/ - else if (pfun->f2 == Tdi2Mask2) { + else if (pfun->f2 == Tdi2Mask2) + { psig = 0; _MOVC3(head, (char *)pa, (char *)&arr); arr.arsize = pa->length * rank; @@ -370,7 +392,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /******************* Rank reduced by one. *******************/ - else if (dim >= 0 && pa->aflags.coeff && rank > 1) { + else if (dim >= 0 && pa->aflags.coeff && rank > 1) + { if (dim < ndim) --psig->ndesc; for (j = dim; ++j < ndim;) @@ -388,7 +411,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /************* Scalar result. *************/ - else { + else + { psig = 0; status = MdsGet1DxS(&digits, &out_dtype, out_ptr); } @@ -400,10 +424,13 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { Simple array if 1D and no bounds. ****************************************/ pd = (array_bounds *)out_ptr->pointer; - if (pd->class == CLASS_A && pd->aflags.coeff) { - if (pd->aflags.bounds) { + if (pd->class == CLASS_A && pd->aflags.coeff) + { + if (pd->aflags.bounds) + { int a0 = 0, keep_bound = 0, dimct = pd->dimct, mul = pd->length; - for (j = 0; j < dimct; ++j) { + for (j = 0; j < dimct; ++j) + { keep_bound |= pd->m[dimct + 2 * j]; a0 += pd->m[dimct + 2 * j] * mul; mul *= pd->m[j]; @@ -425,17 +452,22 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /******************************* Offset list from overall offset. *******************************/ - if (pfun->f2 == Tdi2Mask2 && rank > 1) { + if (pfun->f2 == Tdi2Mask2 && rank > 1) + { int *pout = (int *)pd->pointer; int *pin = (int *)&pa->m[0]; - for (mul = *pout, j = rank; --j >= 0; ++pin) { - if (*pin > 0) { + for (mul = *pout, j = rank; --j >= 0; ++pin) + { + if (*pin > 0) + { *pout++ = mul % *pin; mul /= *pin; - } else + } + else *pout++ = 0; } - } else if (opcode == OPC_ACCUMULATE) + } + else if (opcode == OPC_ACCUMULATE) dat[0] = EMPTY_XD; else if (opcode == OPC_PRODUCT) MdsFree1Dx(&uni[0], NULL); @@ -446,7 +478,8 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { /******************** Free all temporaries. ********************/ - for (j = narg; --j >= 0;) { + for (j = narg; --j >= 0;) + { if (sig[j].pointer) MdsFree1Dx(&sig[j], NULL); if (uni[j].pointer) @@ -463,14 +496,17 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { */ int Tdi3All(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), mdsdsc_t *out_ptr, int count0, int count1, int count2, int step0, - int step1, int step2) { + int step1, int step2) +{ char *pi0, *pi1, *pi2, *pout = out_ptr->pointer; int j0, j1, j2; int leni = in_ptr->length, stepi0 = leni * step0, stepi1 = leni * step1, stepi2 = leni * step2; - for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) { - for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) { + for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) + { + for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) + { for (pi0 = pi1, j0 = count0; --j0 >= 0; pi0 += stepi0) if (!MaskTrue) break; @@ -486,14 +522,17 @@ int Tdi3All(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), */ int Tdi3Any(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), mdsdsc_t *out_ptr, int count0, int count1, int count2, int step0, - int step1, int step2) { + int step1, int step2) +{ char *pi0, *pi1, *pi2, *pout = out_ptr->pointer; int j0, j1, j2; int leni = in_ptr->length, stepi0 = leni * step0, stepi1 = leni * step1, stepi2 = leni * step2; - for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) { - for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) { + for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) + { + for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) + { for (pi0 = pi1, j0 = count0; --j0 >= 0; pi0 += stepi0) if (MaskTrue) break; @@ -510,15 +549,18 @@ int Tdi3Any(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), */ int Tdi3Count(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), mdsdsc_t *out_ptr, int count0, int count1, int count2, int step0, - int step1, int step2) { + int step1, int step2) +{ int result, *pout = (int *)out_ptr->pointer; char *pi0, *pi1, *pi2; int j0, j1, j2; int leni = in_ptr->length, stepi0 = leni * step0, stepi1 = leni * step1, stepi2 = leni * step2; - for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) { - for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) { + for (pi2 = in_ptr->pointer, j2 = count2; --j2 >= 0; pi2 += stepi2) + { + for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) + { result = 0; for (pi0 = pi1, j0 = count0; --j0 >= 0; pi0 += stepi0) if (MaskTrue) @@ -535,14 +577,17 @@ int Tdi3Count(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), */ int Tdi3FirstLoc(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), mdsdsc_t *out_ptr, int count0, int count1, int count2, - int step0, int step1, int step2) { + int step0, int step1, int step2) +{ char *pi0, *pi1, *pi2, *pin = in_ptr->pointer, *pout = out_ptr->pointer; int j0, j1, j2; int leni = in_ptr->length, stepi0 = leni * step0, stepi1 = leni * step1, stepi2 = leni * step2; - for (pi2 = pin, j2 = count2; --j2 >= 0; pi2 += stepi2) { - for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) { + for (pi2 = pin, j2 = count2; --j2 >= 0; pi2 += stepi2) + { + for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 += stepi1) + { for (pi0 = pi1, j0 = count0; --j0 >= 0; pi0 += stepi0) if (MaskTrue) break; @@ -559,15 +604,18 @@ int Tdi3FirstLoc(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), */ int Tdi3LastLoc(mdsdsc_t *in_ptr, mdsdsc_t *pmask __attribute__((unused)), mdsdsc_t *out_ptr, int count0, int count1, int count2, - int step0, int step1, int step2) { + int step0, int step1, int step2) +{ char *pi0, *pi1, *pi2, *pin = in_ptr->pointer, *pout = out_ptr->pointer; int j0, j1, j2; int leni = in_ptr->length, stepi0 = leni * step0, stepi1 = leni * step1, stepi2 = leni * step2; int size = leni * count0 * count1 * count2; - for (pi2 = pin + size - leni, j2 = count2; --j2 >= 0; pi2 -= stepi2) { - for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 -= stepi1) { + for (pi2 = pin + size - leni, j2 = count2; --j2 >= 0; pi2 -= stepi2) + { + for (pi1 = pi2, j1 = count1; --j1 >= 0; pi1 -= stepi1) + { for (pi0 = pi1, j0 = count0; --j0 >= 0; pi0 -= stepi0) if (MaskTrue) break; @@ -586,7 +634,8 @@ int Tdi3Replicate(mdsdsc_t *in_ptr, mdsdsc_t *pmask, mdsdsc_t *out_ptr, int count0 __attribute__((unused)), int count1 __attribute__((unused)), int count2, int step0 __attribute__((unused)), - int step1 __attribute__((unused)), int step2) { + int step1 __attribute__((unused)), int step2) +{ char *pin = in_ptr->pointer, *pout = out_ptr->pointer; int j0, j1, ncopies = *(int *)pmask; int step = in_ptr->length * step2; @@ -604,7 +653,8 @@ int Tdi3Replicate(mdsdsc_t *in_ptr, mdsdsc_t *pmask, mdsdsc_t *out_ptr, int Tdi3Spread(mdsdsc_t *in_ptr, mdsdsc_t *pmask, mdsdsc_t *out_ptr, int count0, int count1 __attribute__((unused)), int count2, int step0, int step1 __attribute__((unused)), - int step2 __attribute__((unused))) { + int step2 __attribute__((unused))) +{ char *pin = in_ptr->pointer, *pout = out_ptr->pointer; int j0, j1, ncopies = *(int *)pmask; int step = in_ptr->length * step0; diff --git a/tdishr/TdiTrim.c b/tdishr/TdiTrim.c index 0dbe66847b..e31c11bb75 100644 --- a/tdishr/TdiTrim.c +++ b/tdishr/TdiTrim.c @@ -44,7 +44,8 @@ extern int TdiCvtArgs(); extern int TdiMasterData(); int Tdi1Trim(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd sig[1] = {EMPTY_XD}, uni[1] = {EMPTY_XD}, dat[1] = {EMPTY_XD}; @@ -55,10 +56,10 @@ int Tdi1Trim(opcode_t opcode, int narg, struct descriptor *list[], uni[0] = EMPTY_XD; status = TdiGetArgs(opcode, narg, list, sig, uni, dat, cats); - if - STATUS_OK - status = TdiCvtArgs(narg, dat, cats); - if (STATUS_OK && narg > 0) { + if (STATUS_OK) + status = TdiCvtArgs(narg, dat, cats); + if (STATUS_OK && narg > 0) + { N_ELEMENTS(dat[0].pointer, j); if (STATUS_OK && j != 1) status = TdiINVCLADSC; @@ -66,13 +67,12 @@ int Tdi1Trim(opcode_t opcode, int narg, struct descriptor *list[], /*********************** Go off and do something. ***********************/ - if - STATUS_OK - status = (*fun_ptr->f3)(dat[0].pointer, out_ptr); - if - STATUS_OK - status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); - if (narg > 0) { + if (STATUS_OK) + status = (*fun_ptr->f3)(dat[0].pointer, out_ptr); + if (STATUS_OK) + status = TdiMasterData(narg, sig, uni, &cmode, out_ptr); + if (narg > 0) + { if (sig[0].pointer) MdsFree1Dx(&sig[0], NULL); if (uni[0].pointer) @@ -86,7 +86,8 @@ int Tdi1Trim(opcode_t opcode, int narg, struct descriptor *list[], /*-------------------------------------------------------------- F90 transformation, string trailing blanks removed. */ -int Tdi3Trim(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) { +int Tdi3Trim(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) +{ int n = in_ptr->length; char *t_ptr = in_ptr->pointer + n; @@ -101,37 +102,40 @@ int Tdi3Trim(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) { Convert opcode to builtin name. */ int Tdi3OpcodeBuiltin(struct descriptor *in_ptr, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ int ind = TdiFUNCTION_MAX; INIT_STATUS; static const dtype_t dtype = DTYPE_T; status = TdiGetLong(in_ptr, &ind); - if (STATUS_OK && ind < (int)TdiFUNCTION_MAX) { + if (STATUS_OK && ind < (int)TdiFUNCTION_MAX) + { char *name_ptr = TdiRefFunction[ind].name; struct descriptor str2 = {0, DTYPE_T, CLASS_S, 0}; str2.length = (length_t)strlen(name_ptr); str2.pointer = name_ptr; status = MdsGet1DxS(&str2.length, &dtype, out_ptr); - if - STATUS_OK - status = StrCopyDx(out_ptr->pointer, &str2); - } else if - STATUS_OK - status = TdiINV_OPC; + if (STATUS_OK) + status = StrCopyDx(out_ptr->pointer, &str2); + } + else if (STATUS_OK) + status = TdiINV_OPC; return status; } /*-------------------------------------------------------------- Convert opcode to string name. */ -int Tdi3OpcodeString(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) { +int Tdi3OpcodeString(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) +{ static const DESCRIPTOR(str1, "OPC" "$"); int ind = TdiFUNCTION_MAX; INIT_STATUS; static const dtype_t dtype = DTYPE_T; status = TdiGetLong(in_ptr, &ind); - if (STATUS_OK && ind < TdiFUNCTION_MAX) { + if (STATUS_OK && ind < TdiFUNCTION_MAX) + { char *name_ptr = TdiRefFunction[ind].name; struct descriptor str2 = {0, DTYPE_T, CLASS_S, 0}; length_t total; @@ -139,12 +143,11 @@ int Tdi3OpcodeString(struct descriptor *in_ptr, struct descriptor_xd *out_ptr) { str2.pointer = name_ptr; total = (length_t)(str1.length + str2.length); status = MdsGet1DxS(&total, &dtype, out_ptr); - if - STATUS_OK - status = StrConcat((struct descriptor *)out_ptr->pointer, - (struct descriptor *)&str1, &str2 MDS_END_ARG); - } else if - STATUS_OK - status = TdiINV_OPC; + if (STATUS_OK) + status = StrConcat((struct descriptor *)out_ptr->pointer, + (struct descriptor *)&str1, &str2 MDS_END_ARG); + } + else if (STATUS_OK) + status = TdiINV_OPC; return status; } diff --git a/tdishr/TdiUnary.c b/tdishr/TdiUnary.c index 2f9ac0a8aa..f3d2e12512 100644 --- a/tdishr/TdiUnary.c +++ b/tdishr/TdiUnary.c @@ -60,10 +60,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int TdiUnary(struct descriptor *in_ptr, struct descriptor *out_ptr, - unsigned int *out_count) { + unsigned int *out_count) +{ struct descriptor_a *a; - switch (out_ptr->class) { + switch (out_ptr->class) + { case CLASS_S: case CLASS_D: *out_count = 1; @@ -77,7 +79,8 @@ int TdiUnary(struct descriptor *in_ptr, struct descriptor *out_ptr, return TdiINVCLADSC; } - switch (in_ptr->class) { + switch (in_ptr->class) + { case CLASS_S: case CLASS_D: break; diff --git a/tdishr/TdiUndef.c b/tdishr/TdiUndef.c index e06f144c2b..a40e1061f2 100644 --- a/tdishr/TdiUndef.c +++ b/tdishr/TdiUndef.c @@ -29,7 +29,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#define UNDEF(x) \ +#define UNDEF(x) \ int x() { return TdiNO_OPC; } /*** PERMANENT ***/ UNDEF(Tdi1Else) diff --git a/tdishr/TdiVar.c b/tdishr/TdiVar.c index 4cb36d55f0..86ba73c847 100644 --- a/tdishr/TdiVar.c +++ b/tdishr/TdiVar.c @@ -74,14 +74,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #define DEBUG #ifdef DEBUG -#define DBG(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stdout, __VA_ARGS__); \ +#define DBG(...) \ + do \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stdout, __VA_ARGS__); \ } while (0) #else -#define DBG(...) \ - {} +#define DBG(...) \ + { \ + } #endif extern int TdiFaultHandler(); @@ -99,20 +101,23 @@ This uses the balanced binary tree routines. LOOKUP_TREE INSERT_TREE TRAVERSE_TREE Full descriptors cost memory, save time. *******************************************/ -typedef struct link { +typedef struct link +{ struct link *left, *right; /* binary tree links */ unsigned short reserved; /* tree flags */ mdsdsc_xd_t xd; /* data descriptor */ mdsdsc_t name_dsc; /* name descriptor */ unsigned char name[1]; /* unchanging name */ } node_type; -typedef struct { +typedef struct +{ node_type *head; /* changing binary-tree head */ void *head_zone; /* created on first call */ void *data_zone; /* created on first call */ int _public; /* is public */ } block_type; -typedef struct { +typedef struct +{ mdsdsc_t match; block_type *block_ptr; int count; @@ -128,10 +133,10 @@ const mdsdsc_t true_dsc = {sizeof(true), DTYPE_BU, CLASS_S, (char *)&true}; static pthread_mutex_t public_lock = PTHREAD_MUTEX_INITIALIZER; #define LOCK_PUBLIC pthread_mutex_lock(&public_lock) //;fprintf(stderr,"public locked by %ld\n",*(long int*)pthread_self()) -#define UNLOCK_PUBLIC_PUSH \ +#define UNLOCK_PUBLIC_PUSH \ pthread_cleanup_push((void *)pthread_mutex_unlock, &public_lock) -#define LOCK_PUBLIC_PUSH \ - LOCK_PUBLIC; \ +#define LOCK_PUBLIC_PUSH \ + LOCK_PUBLIC; \ UNLOCK_PUBLIC_PUSH #define UNLOCK_PUBLIC pthread_cleanup_pop(1) //;fprintf(stderr,"public unlocked by %ld\n",*(long int*)pthread_self()) @@ -143,7 +148,8 @@ static block_type _public = {0, 0, 0, 1}; const DESCRIPTOR(star, "*"); const DESCRIPTOR(percent, "%"); -mdsdsc_t *Tdi3Narg() { +mdsdsc_t *Tdi3Narg() +{ TDITHREADSTATIC_INIT; return &TDI_VAR_NEW_NARG_D; } @@ -151,16 +157,16 @@ mdsdsc_t *Tdi3Narg() { /*-------------------------------------------------------------- Put a byte to output. */ -int tdi_put_logical(uint8_t data, mdsdsc_xd_t *const out_ptr) { +int tdi_put_logical(uint8_t data, mdsdsc_xd_t *const out_ptr) +{ INIT_STATUS; length_t len = (length_t)sizeof(uint8_t); dtype_t dtype = DTYPE_BU; if (!out_ptr) return TdiNULL_PTR; status = MdsGet1DxS(&len, &dtype, out_ptr); - if - STATUS_OK - *(uint8_t *)out_ptr->pointer->pointer = data; + if (STATUS_OK) + *(uint8_t *)out_ptr->pointer->pointer = data; return status; } @@ -169,7 +175,8 @@ int tdi_put_logical(uint8_t data, mdsdsc_xd_t *const out_ptr) { */ static int compare(const mdsdsc_t *const key_ptr, const node_type *const node_ptr, - const block_type *const block_ptr __attribute__((unused))) { + const block_type *const block_ptr __attribute__((unused))) +{ return StrCaseBlindCompare(key_ptr, &node_ptr->name_dsc); } @@ -179,26 +186,28 @@ static int compare(const mdsdsc_t *const key_ptr, */ static int allocate(const mdsdsc_t *const key_ptr, node_type **const node_ptr_ptr, - block_type *const block_ptr) { + block_type *const block_ptr) +{ INIT_STATUS; unsigned int len = sizeof(struct link) - 1 + key_ptr->length; /******************************************************************* Must clear memory unless allocate is called only once for each node. *******************************************************************/ - if (block_ptr->data_zone == 0) { + if (block_ptr->data_zone == 0) + { LibCreateVmZone(&block_ptr->head_zone); LibCreateVmZone(&block_ptr->data_zone); } status = LibGetVm(&len, (void *)node_ptr_ptr, &block_ptr->head_zone); - if - STATUS_OK { - node_type *node_ptr = *node_ptr_ptr; - node_ptr->xd = EMPTY_XD; - node_ptr->name_dsc = *key_ptr; - node_ptr->name_dsc.pointer = (char *)&node_ptr->name[0]; - memcpy(node_ptr->name, key_ptr->pointer, key_ptr->length); - } + if (STATUS_OK) + { + node_type *node_ptr = *node_ptr_ptr; + node_ptr->xd = EMPTY_XD; + node_ptr->name_dsc = *key_ptr; + node_ptr->name_dsc.pointer = (char *)&node_ptr->name[0]; + memcpy(node_ptr->name, key_ptr->pointer, key_ptr->length); + } return status; } @@ -211,7 +220,8 @@ static int allocate(const mdsdsc_t *const key_ptr, #define _private (*(block_type *)&TDI_VAR_PRIVATE) static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, mdsdsc_t *const key_ptr, node_type **const node_ptr_ptr, - block_type **const block_ptr_ptr, TDITHREADSTATIC_ARG) { + block_type **const block_ptr_ptr, TDITHREADSTATIC_ARG) +{ INIT_STATUS; mdsdsc_t key_dsc; mdsdsc_d_t name_dsc; @@ -221,55 +231,72 @@ static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, if (ident_ptr == 0) status = TdiNULL_PTR; else - switch (ident_ptr->class) { + switch (ident_ptr->class) + { case CLASS_S: case CLASS_D: - switch (ident_ptr->dtype) { + switch (ident_ptr->dtype) + { /******************************************** The choice of default public/private is here. ********************************************/ case DTYPE_T: - case DTYPE_IDENT: { + case DTYPE_IDENT: + { key_dsc = *(mdsdsc_t *)ident_ptr; key_dsc.dtype = DTYPE_T; key_dsc.class = CLASS_S; - if (search & 1) { - if (search & 4) { + if (search & 1) + { + if (search & 4) + { status = LibLookupTree((void *)&_private.head, (void *)&key_dsc, compare, (void **)&node_ptr); - if - STATUS_OK { - if (node_ptr->xd.class != 0) { - if (block_ptr_ptr) - *block_ptr_ptr = &_private; - break; - } else { - status = TdiUNKNOWN_VAR; - } + if (STATUS_OK) + { + if (node_ptr->xd.class != 0) + { + if (block_ptr_ptr) + *block_ptr_ptr = &_private; + break; + } + else + { + status = TdiUNKNOWN_VAR; } - } else { + } + } + else + { if (block_ptr_ptr) *block_ptr_ptr = &_private; break; } } - if (search & 2) { - if (search & 4) { + if (search & 2) + { + if (search & 4) + { LOCK_PUBLIC_PUSH; status = LibLookupTree((void *)&_public.head, (void *)&key_dsc, compare, (void **)&node_ptr); - if - STATUS_OK { - if (node_ptr->xd.class != 0) { - if (block_ptr_ptr) - *block_ptr_ptr = &_public; - } else { - status = TdiUNKNOWN_VAR; - } + if (STATUS_OK) + { + if (node_ptr->xd.class != 0) + { + if (block_ptr_ptr) + *block_ptr_ptr = &_public; + } + else + { + status = TdiUNKNOWN_VAR; } + } UNLOCK_PUBLIC_IF(!(block_ptr_ptr && *block_ptr_ptr == &_public)); - } else if (block_ptr_ptr) { + } + else if (block_ptr_ptr) + { LOCK_PUBLIC; *block_ptr_ptr = &_public; } @@ -282,12 +309,14 @@ static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, } break; case CLASS_R: - if (ident_ptr->dtype != DTYPE_FUNCTION) { + if (ident_ptr->dtype != DTYPE_FUNCTION) + { status = TdiINVCLADTY; break; } code = *(unsigned short *)ident_ptr->pointer; - if (ident_ptr->ndesc < 1) { + if (ident_ptr->ndesc < 1) + { status = TdiMISS_ARG; break; } @@ -305,24 +334,26 @@ static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, &key_dsc, &node_ptr, block_ptr_ptr, TDITHREADSTATIC_VAR); else if (code == OPC_EQUALS || code == OPC_EQUALS_FIRST || code == OPC_POST_DEC || code == OPC_PRE_DEC || - code == OPC_POST_INC || code == OPC_PRE_INC) { + code == OPC_POST_INC || code == OPC_PRE_INC) + { INIT_AND_FREEXD_ON_EXIT(tmp); status = TdiEvaluate(ident_ptr, &tmp MDS_END_ARG); - if - STATUS_OK - status = - find_ident(search, (mdsdsc_r_t *)ident_ptr->dscptrs[0], &key_dsc, - &node_ptr, block_ptr_ptr, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = + find_ident(search, (mdsdsc_r_t *)ident_ptr->dscptrs[0], &key_dsc, + &node_ptr, block_ptr_ptr, TDITHREADSTATIC_VAR); FREEXD_NOW(tmp); - } else if (code == OPC_VAR) { + } + else if (code == OPC_VAR) + { name_dsc = EMPTY_D; status = TdiData(ident_ptr->dscptrs[0], &name_dsc MDS_END_ARG); - if - STATUS_OK - status = find_ident(search, (mdsdsc_r_t *)&name_dsc, &key_dsc, - &node_ptr, block_ptr_ptr, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = find_ident(search, (mdsdsc_r_t *)&name_dsc, &key_dsc, + &node_ptr, block_ptr_ptr, TDITHREADSTATIC_VAR); StrFree1Dx((mdsdsc_d_t *)&name_dsc); - } else + } + else status = TdiINV_OPC; break; default: @@ -331,12 +362,15 @@ static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, } if (status == LibKEYNOTFOU) status = TdiUNKNOWN_VAR; - if (STATUS_OK || status == TdiUNKNOWN_VAR) { + if (STATUS_OK || status == TdiUNKNOWN_VAR) + { if (key_ptr) *key_ptr = key_dsc; if (node_ptr_ptr) *node_ptr_ptr = node_ptr; - } else { + } + else + { if (node_ptr_ptr) *node_ptr_ptr = NULL; if (block_ptr_ptr) @@ -349,7 +383,8 @@ static int find_ident(const int search, const mdsdsc_r_t *const ident_ptr, Get active variable for VAR and EVALUATE. Copies to MDSSHR space. */ static int get_ident(const mdsdsc_t *const ident_ptr, - mdsdsc_xd_t *const data_ptr, TDITHREADSTATIC_ARG) { + mdsdsc_xd_t *const data_ptr, TDITHREADSTATIC_ARG) +{ node_type *node_ptr; block_type *block_ptr = NULL; INIT_STATUS; @@ -364,15 +399,16 @@ static int get_ident(const mdsdsc_t *const ident_ptr, block_ptr == &_public ? "public" : STATUS_OK ? "private" : "new", string, block_ptr); #endif - if - STATUS_OK - status = MdsCopyDxXd(node_ptr->xd.pointer, data_ptr); - else MdsFree1Dx(data_ptr, NULL); + if (STATUS_OK) + status = MdsCopyDxXd(node_ptr->xd.pointer, data_ptr); + else + MdsFree1Dx(data_ptr, NULL); UNLOCK_IF_PUBLIC(block_ptr); return status; } int tdi_get_ident(const mdsdsc_t *const ident_ptr, - mdsdsc_xd_t *const data_ptr) { + mdsdsc_xd_t *const data_ptr) +{ TDITHREADSTATIC_INIT; return get_ident(ident_ptr, data_ptr, TDITHREADSTATIC_VAR); } @@ -383,7 +419,8 @@ int tdi_get_ident(const mdsdsc_t *const ident_ptr, */ static inline int put_ident_inner(const mdsdsc_r_t *const ident_ptr, mdsdsc_xd_t *const data_ptr, - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ INIT_STATUS; block_type *block_ptr = NULL; UNLOCK_PUBLIC_PUSH; @@ -404,35 +441,38 @@ static inline int put_ident_inner(const mdsdsc_r_t *const ident_ptr, block_ptr == &_public ? "public" : STATUS_OK ? "private" : "new", string, block_ptr); #endif - if - STATUS_OK { - int zero = 0; - status = LibInsertTree((void **)&block_ptr->head, &upstr, &zero, compare, - allocate, (void *)&node_ptr, block_ptr); - } + if (STATUS_OK) + { + int zero = 0; + status = LibInsertTree((void **)&block_ptr->head, &upstr, &zero, compare, + allocate, (void *)&node_ptr, block_ptr); + } StrFree1Dx(&upstr); - if - STATUS_OK { - if (node_ptr->xd.class == 0) - node_ptr->xd = EMPTY_XD; - if (data_ptr) - status = MdsCopyDxXdZ(data_ptr->pointer, &node_ptr->xd, - &block_ptr->data_zone, NULL, NULL, NULL, NULL); - else { - MdsFree1Dx(&node_ptr->xd, &block_ptr->data_zone); - node_ptr->xd = NULL_XD; - } + if (STATUS_OK) + { + if (node_ptr->xd.class == 0) + node_ptr->xd = EMPTY_XD; + if (data_ptr) + status = MdsCopyDxXdZ(data_ptr->pointer, &node_ptr->xd, + &block_ptr->data_zone, NULL, NULL, NULL, NULL); + else + { + MdsFree1Dx(&node_ptr->xd, &block_ptr->data_zone); + node_ptr->xd = NULL_XD; } + } UNLOCK_IF_PUBLIC(block_ptr); return status; } static int put_ident(const mdsdsc_r_t *ident_ptr, mdsdsc_xd_t *const data_ptr, - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ while (ident_ptr->dtype == DTYPE_DSC) ident_ptr = (mdsdsc_r_t *)ident_ptr->pointer; return put_ident_inner(ident_ptr, data_ptr, TDITHREADSTATIC_VAR); } -int tdi_put_ident(const mdsdsc_r_t *ident_ptr, mdsdsc_xd_t *const data_ptr) { +int tdi_put_ident(const mdsdsc_r_t *ident_ptr, mdsdsc_xd_t *const data_ptr) +{ TDITHREADSTATIC_INIT; while (ident_ptr->dtype == DTYPE_DSC) ident_ptr = (mdsdsc_r_t *)ident_ptr->pointer; @@ -445,59 +485,64 @@ int tdi_put_ident(const mdsdsc_r_t *ident_ptr, mdsdsc_xd_t *const data_ptr) { PUBLIC or PRIVATE(ident or text) overrides block_ptr. */ static int wild_loop(int (*const doit)(), const mdsdsc_t *const arg, - user_type *const user_p, TDITHREADSTATIC_ARG) { + user_type *const user_p, TDITHREADSTATIC_ARG) +{ int status; UNLOCK_PUBLIC_PUSH; status = find_ident(3, (mdsdsc_r_t *)arg, &user_p->match, 0, &user_p->block_ptr, TDITHREADSTATIC_VAR); - if - STATUS_OK - status = StrUpcase(&user_p->match, &user_p->match); - if - STATUS_OK { - if (StrPosition(&user_p->match, (mdsdsc_t *)&star, 0) || - StrPosition(&user_p->match, (mdsdsc_t *)&percent, 0)) { - status = - LibTraverseTree((void **)&user_p->block_ptr->head, doit, user_p); - } else { - node_type *node_ptr; - status = - LibLookupTree((void **)&user_p->block_ptr->head, - (void *)&user_p->match, compare, (void **)&node_ptr); - if - STATUS_OK + if (STATUS_OK) + status = StrUpcase(&user_p->match, &user_p->match); + if (STATUS_OK) + { + if (StrPosition(&user_p->match, (mdsdsc_t *)&star, 0) || + StrPosition(&user_p->match, (mdsdsc_t *)&percent, 0)) + { + status = + LibTraverseTree((void **)&user_p->block_ptr->head, doit, user_p); + } + else + { + node_type *node_ptr; + status = + LibLookupTree((void **)&user_p->block_ptr->head, + (void *)&user_p->match, compare, (void **)&node_ptr); + if (STATUS_OK) status = (*doit)(node_ptr, user_p); - else if (status == LibKEYNOTFOU) status = MDSplusSUCCESS; - } + else if (status == LibKEYNOTFOU) + status = MDSplusSUCCESS; } + } UNLOCK_IF_PUBLIC(user_p->block_ptr); return status; } static int wild(int (*const doit)(), const int narg, mdsdsc_t *const list[], block_type *const block_ptr, mdsdsc_xd_t *const out_ptr, - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ INIT_STATUS; user_type user = {{0, DTYPE_T, CLASS_D, 0}, 0, 0}; user.block_ptr = block_ptr; if (narg == 0 || list[0] == 0) status = LibTraverseTree((void **)&block_ptr->head, doit, &user); - else { + else + { int j; for (j = 0; STATUS_OK && j < narg; ++j) status = wild_loop(doit, list[j], &user, TDITHREADSTATIC_VAR); } if (user.match.class == CLASS_D) StrFree1Dx((mdsdsc_d_t *)&user.match); - if - STATUS_OK - status = TdiPutLong(&user.count, out_ptr); + if (STATUS_OK) + status = TdiPutLong(&user.count, out_ptr); return status; } /*-------------------------------------------------------------- Release variables. */ -static int free_one(node_type *const node_ptr, user_type *const user_ptr) { +static int free_one(node_type *const node_ptr, user_type *const user_ptr) +{ block_type *block_ptr = user_ptr->block_ptr; INIT_STATUS; @@ -510,15 +555,15 @@ static int free_one(node_type *const node_ptr, user_type *const user_ptr) { status = MDSplusSUCCESS; else status = StrMatchWild(&node_ptr->name_dsc, &user_ptr->match); - if - STATUS_OK { - if (node_ptr->xd.l_length) - status = - LibFreeVm(&node_ptr->xd.l_length, (void *)&node_ptr->xd.pointer, - &block_ptr->data_zone); - node_ptr->xd = NULL_XD; - user_ptr->count++; - } + if (STATUS_OK) + { + if (node_ptr->xd.l_length) + status = + LibFreeVm(&node_ptr->xd.l_length, (void *)&node_ptr->xd.pointer, + &block_ptr->data_zone); + node_ptr->xd = NULL_XD; + user_ptr->count++; + } else status = MDSplusSUCCESS; return status; @@ -528,30 +573,30 @@ static int free_one(node_type *const node_ptr, user_type *const user_ptr) { Release all variables under a header and the headers too. Used to release the FUN variables. */ -static int free_all(node_type **const pnode, TDITHREADSTATIC_ARG) { +static int free_all(node_type **const pnode, TDITHREADSTATIC_ARG) +{ INIT_STATUS, stat2; unsigned int len; if ((*pnode)->xd.l_length) status = LibFreeVm(&(*pnode)->xd.l_length, (void *)&(*pnode)->xd.pointer, &_private.data_zone); - if ((*pnode)->left) { + if ((*pnode)->left) + { stat2 = free_all(&((*pnode)->left), TDITHREADSTATIC_VAR); - if - STATUS_OK - status = stat2; + if (STATUS_OK) + status = stat2; } - if ((*pnode)->right) { + if ((*pnode)->right) + { stat2 = free_all(&((*pnode)->right), TDITHREADSTATIC_VAR); - if - STATUS_OK - status = stat2; + if (STATUS_OK) + status = stat2; } len = sizeof(struct link) - 1 + (*pnode)->name_dsc.length; stat2 = LibFreeVm(&len, (void *)pnode, &_private.head_zone); *pnode = 0; - if - STATUS_OK - status = stat2; + if (STATUS_OK) + status = stat2; return status; } @@ -559,10 +604,12 @@ static int free_all(node_type **const pnode, TDITHREADSTATIC_ARG) { Release variables. */ int Tdi1Deallocate(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; - if (narg == 0 && _private.head) { + if (narg == 0 && _private.head) + { status = free_all(&_private.head, TDITHREADSTATIC_VAR); _private.head = NULL; return status; @@ -577,7 +624,8 @@ int Tdi1Deallocate(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1Allocated(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; mdsdsc_t key_dsc = EMPTDY_S; @@ -587,17 +635,15 @@ int Tdi1Allocated(opcode_t opcode __attribute__((unused)), UNLOCK_PUBLIC_PUSH; status = find_ident(3, (mdsdsc_r_t *)list[0], &key_dsc, 0, &block_ptr, TDITHREADSTATIC_VAR); - if - STATUS_OK - status = LibLookupTree((void **)&block_ptr->head, (void *)&key_dsc, compare, - (void **)&node_ptr); + if (STATUS_OK) + status = LibLookupTree((void **)&block_ptr->head, (void *)&key_dsc, compare, + (void **)&node_ptr); found = STATUS_OK && (node_ptr->xd.class != 0); UNLOCK_IF_PUBLIC(block_ptr); if ((status == LibKEYNOTFOU) || (status == TdiUNKNOWN_VAR)) status = MDSplusSUCCESS; - if - STATUS_OK - status = tdi_put_logical(found, out_ptr); + if (STATUS_OK) + status = tdi_put_logical(found, out_ptr); return status; } @@ -606,7 +652,8 @@ int Tdi1Allocated(opcode_t opcode __attribute__((unused)), */ int Tdi1Present(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; mdsdsc_t key_dsc = EMPTDY_S; @@ -616,28 +663,32 @@ int Tdi1Present(opcode_t opcode __attribute__((unused)), UNLOCK_PUBLIC_PUSH; status = find_ident(3, (mdsdsc_r_t *)list[0], &key_dsc, 0, &block_ptr, TDITHREADSTATIC_VAR); - if - STATUS_OK - status = LibLookupTree((void **)&block_ptr->head, (void *)&key_dsc, compare, - (void **)&node_ptr); + if (STATUS_OK) + status = LibLookupTree((void **)&block_ptr->head, (void *)&key_dsc, compare, + (void **)&node_ptr); UNLOCK_IF_PUBLIC(block_ptr); found = STATUS_OK; if (found) ; else if (status == LibKEYNOTFOU || status == TdiUNKNOWN_VAR) status = MDSplusSUCCESS; - if - STATUS_OK - status = tdi_put_logical((unsigned char)found, out_ptr); + if (STATUS_OK) + status = tdi_put_logical((unsigned char)found, out_ptr); return status; } /*************************************************************** Execute a function. Set up the arguments. */ -typedef enum { EXT_NONE, EXT_FUN, EXT_PY } ext_t; +typedef enum +{ + EXT_NONE, + EXT_FUN, + EXT_PY +} ext_t; -static inline ext_t matchext(const mdsdsc_d_t *const file) { +static inline ext_t matchext(const mdsdsc_d_t *const file) +{ if (file->length < 4) return EXT_NONE; char *p = file->pointer + file->length - 4; @@ -649,7 +700,8 @@ static inline ext_t matchext(const mdsdsc_d_t *const file) { return EXT_NONE; } static inline int findfile_fun(const mdsdsc_t *const entry, - char **const funfile, char **const pyfile) { + char **const funfile, char **const pyfile) +{ int status; INIT_AND_FREED_ON_EXIT(bufd, DTYPE_T); ext_t isext = EXT_NONE; @@ -666,57 +718,66 @@ static inline int findfile_fun(const mdsdsc_t *const entry, memcpy(tmp, ext, extlen); // adds "\0" } void *ctx = 0; - do { + do + { status = LibFindFileRecurseCaseBlind((mdsdsc_t *)&bufd, (mdsdsc_t *)&bufd, &ctx); } while (STATUS_OK && (isext = matchext(&bufd)) == EXT_NONE); LibFindFileEnd(&ctx); - if - STATUS_OK { - char *file = memcpy(malloc(bufd.length + 1), bufd.pointer, bufd.length); + if (STATUS_OK) + { + char *file = memcpy(malloc(bufd.length + 1), bufd.pointer, bufd.length); + file[bufd.length] = '\0'; + if (isext == EXT_PY) + { + *pyfile = file; + isext = EXT_FUN; + bufd.pointer = realloc(bufd.pointer, ++bufd.length); + memcpy(bufd.pointer + bufd.length - 4, ".FUN", 4); + } + else + { + *funfile = file; + isext = EXT_PY; + bufd.pointer = realloc(bufd.pointer, --bufd.length); + memcpy(bufd.pointer + bufd.length - 3, ".PY", 3); + } + if (IS_OK( + LibFindFileCaseBlind((mdsdsc_t *)&bufd, (mdsdsc_t *)&bufd, &ctx))) + { + file = memcpy(malloc(bufd.length + 1), bufd.pointer, bufd.length); file[bufd.length] = '\0'; - if (isext == EXT_PY) { + if (isext == EXT_PY) *pyfile = file; - isext = EXT_FUN; - bufd.pointer = realloc(bufd.pointer, ++bufd.length); - memcpy(bufd.pointer + bufd.length - 4, ".FUN", 4); - } else { + else *funfile = file; - isext = EXT_PY; - bufd.pointer = realloc(bufd.pointer, --bufd.length); - memcpy(bufd.pointer + bufd.length - 3, ".PY", 3); - } - if - IS_OK( - LibFindFileCaseBlind((mdsdsc_t *)&bufd, (mdsdsc_t *)&bufd, &ctx)) { - file = memcpy(malloc(bufd.length + 1), bufd.pointer, bufd.length); - file[bufd.length] = '\0'; - if (isext == EXT_PY) - *pyfile = file; - else - *funfile = file; - } - LibFindFileEnd(&ctx); } + LibFindFileEnd(&ctx); + } FREED_NOW(bufd); return status; } extern int TdiCompile(); -static int compile_fun(const mdsdsc_t *const entry, const char *const file) { +static int compile_fun(const mdsdsc_t *const entry, const char *const file) +{ if (!file) return TdiUNKNOWN_VAR; int status; INIT_AND_FREEXD_ON_EXIT(tmp); DBG("compile: %s\n", file); FILE *unit = fopen(file, "rb"); - if (unit) { + if (unit) + { fseek(unit, 0, SEEK_END); size_t flen = ftell(unit); - if (flen > 0xffff) { + if (flen > 0xffff) + { fclose(unit); status = TdiSTRTOOLON; - } else { + } + else + { fseek(unit, 0, SEEK_SET); mdsdsc_t dcs = {flen, DTYPE_T, CLASS_D, (char *)malloc(flen)}; FREED_ON_EXIT(&dcs); @@ -727,26 +788,30 @@ static int compile_fun(const mdsdsc_t *const entry, const char *const file) { status = TdiCompile(&dcs, &tmp MDS_END_ARG); FREED_NOW(&dcs); } - } else + } + else status = TdiUNKNOWN_VAR; - if - STATUS_OK { - mds_function_t *pfun = (mds_function_t *)tmp.pointer; - if (pfun->dtype == DTYPE_FUNCTION) { - unsigned short code = *(unsigned short *)pfun->pointer; - if (code == OPC_FUN) { - mds_function_t *pfun2 = (mds_function_t *)pfun->arguments[0]; - if (pfun2->dtype == DTYPE_FUNCTION) { - code = *(unsigned short *)pfun2->pointer; - if (code == OPC_PRIVATE || code == OPC_PUBLIC) - pfun2 = (mds_function_t *)pfun2->arguments[0]; - } - StrUpcase((mdsdsc_t *)pfun2, (mdsdsc_t *)pfun2); - if (StrCompare(entry, (mdsdsc_t *)pfun2) == 0) - status = TdiEvaluate(&tmp, &tmp MDS_END_ARG); + if (STATUS_OK) + { + mds_function_t *pfun = (mds_function_t *)tmp.pointer; + if (pfun->dtype == DTYPE_FUNCTION) + { + unsigned short code = *(unsigned short *)pfun->pointer; + if (code == OPC_FUN) + { + mds_function_t *pfun2 = (mds_function_t *)pfun->arguments[0]; + if (pfun2->dtype == DTYPE_FUNCTION) + { + code = *(unsigned short *)pfun2->pointer; + if (code == OPC_PRIVATE || code == OPC_PUBLIC) + pfun2 = (mds_function_t *)pfun2->arguments[0]; } + StrUpcase((mdsdsc_t *)pfun2, (mdsdsc_t *)pfun2); + if (StrCompare(entry, (mdsdsc_t *)pfun2) == 0) + status = TdiEvaluate(&tmp, &tmp MDS_END_ARG); } } + } FREEXD_NOW(&tmp); return status; } @@ -757,52 +822,58 @@ extern int tdi_call_python_fun(const char *const filename, const int nargs, const mdsdsc_r_t *const *const args, mdsdsc_xd_t *const out_ptr); static int find_fun(const mdsdsc_t *const ident_ptr, node_type **const node_ptr, - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ int status = find_ident(7, (mdsdsc_r_t *)ident_ptr, 0, node_ptr, 0, TDITHREADSTATIC_VAR); - if (status == TdiUNKNOWN_VAR) { + if (status == TdiUNKNOWN_VAR) + { INIT_AND_FREE_ON_EXIT(char *, pyfile); INIT_AND_FREE_ON_EXIT(char *, funfile); // check if we can find method as either .py or .fun status = findfile_fun(ident_ptr, &funfile, &pyfile); - if (pyfile) { + if (pyfile) + { char *funname; status = tdi_load_python_fun(pyfile, &funname); - if - STATUS_OK { - mdsdsc_t function = {strlen(funname), DTYPE_T, CLASS_S, funname}; - mdsdsc_xd_t tmp = EMPTY_XD; - status = MdsCopyDxXd((mdsdsc_t *)&function, &tmp); - free(funname); - if - STATUS_OK { - status = - put_ident((mdsdsc_r_t *)ident_ptr, &tmp, TDITHREADSTATIC_VAR); - MdsFree1Dx(&tmp, NULL); - } + if (STATUS_OK) + { + mdsdsc_t function = {strlen(funname), DTYPE_T, CLASS_S, funname}; + mdsdsc_xd_t tmp = EMPTY_XD; + status = MdsCopyDxXd((mdsdsc_t *)&function, &tmp); + free(funname); + if (STATUS_OK) + { + status = + put_ident((mdsdsc_r_t *)ident_ptr, &tmp, TDITHREADSTATIC_VAR); + MdsFree1Dx(&tmp, NULL); } - if - STATUS_NOT_OK // unable to load python method try tdi alternative - status = compile_fun(ident_ptr, funfile); - } else // not a python method, load tdi fun + } + if (STATUS_NOT_OK) + // unable to load python method try tdi alternative + status = compile_fun(ident_ptr, funfile); + } + else // not a python method, load tdi fun status = compile_fun(ident_ptr, funfile); FREE_NOW(funfile); FREE_NOW(pyfile); - if - STATUS_OK status = find_ident(7, (mdsdsc_r_t *)ident_ptr, 0, node_ptr, 0, - TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = find_ident(7, (mdsdsc_r_t *)ident_ptr, 0, node_ptr, 0, + TDITHREADSTATIC_VAR); } return status; } static pthread_mutex_t lock; -static void unlock(TDITHREADSTATIC_ARG) { +static void unlock(TDITHREADSTATIC_ARG) +{ TDI_VAR_REC = FALSE; pthread_mutex_unlock(&lock); } int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, const mdsdsc_r_t *const actual_arg_ptr[], - mdsdsc_xd_t *const out_ptr) { + mdsdsc_xd_t *const out_ptr) +{ TDITHREADSTATIC_INIT; node_type *node_ptr; /****************************************** @@ -812,19 +883,21 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, // look up method: check cached, check python, or load if (TDI_VAR_REC) status = find_fun(ident_ptr, &node_ptr, TDITHREADSTATIC_VAR); - else { + else + { pthread_mutex_lock(&lock); TDI_VAR_REC = TRUE; pthread_cleanup_push((void *)unlock, (void *)TDITHREADSTATIC_VAR); status = find_fun(ident_ptr, &node_ptr, TDITHREADSTATIC_VAR); pthread_cleanup_pop(1); } - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; const mdsdsc_r_t *formal_ptr = 0, *formal_arg_ptr, *actual_ptr; if ((formal_ptr = (mdsdsc_r_t *)node_ptr->xd.pointer) == 0) return TdiUNKNOWN_VAR; - if (formal_ptr->dtype == DTYPE_T) { + if (formal_ptr->dtype == DTYPE_T) + { char *funname = malloc(formal_ptr->length + 1); FREE_ON_EXIT(funname); memcpy(funname, formal_ptr->pointer, formal_ptr->length); @@ -848,18 +921,23 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, Only OPTIONAL arguments may be omitted. OUT arguments are not evaluated. **************************************/ - for (j = 0; j < nformal && STATUS_OK; ++j) { + for (j = 0; j < nformal && STATUS_OK; ++j) + { formal_arg_ptr = (mdsdsc_r_t *)formal_ptr->dscptrs[j + 2]; - if (formal_arg_ptr == 0) { + if (formal_arg_ptr == 0) + { status = TdiNULL_PTR; break; } - if (formal_arg_ptr->dtype == DTYPE_FUNCTION && formal_arg_ptr->ndesc == 1) { + if (formal_arg_ptr->dtype == DTYPE_FUNCTION && formal_arg_ptr->ndesc == 1) + { code = *(unsigned short *)formal_arg_ptr->pointer; opt = (code == OPC_OPTIONAL); - if (opt) { + if (opt) + { formal_arg_ptr = (mdsdsc_r_t *)formal_arg_ptr->dscptrs[0]; - if (formal_arg_ptr == 0) { + if (formal_arg_ptr == 0) + { status = TdiNULL_PTR; break; } @@ -869,22 +947,27 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, else code = *(unsigned short *)formal_arg_ptr->pointer; } - } else + } + else code = opt = 0; /**************************** [OPTIONAL] AS_IS IN INOUT OUT only. All other words are bad here. ****************************/ - if (code == OPC_IN || code == OPC_INOUT || code == OPC_OUT) { + if (code == OPC_IN || code == OPC_INOUT || code == OPC_OUT) + { formal_arg_ptr = (mdsdsc_r_t *)formal_arg_ptr->dscptrs[0]; - if (formal_arg_ptr->dtype != DTYPE_T) { + if (formal_arg_ptr->dtype != DTYPE_T) + { status = TdiINVDTYDSC; break; } - } else if (code == OPC_AS_IS) + } + else if (code == OPC_AS_IS) formal_arg_ptr = (mdsdsc_r_t *)formal_arg_ptr->dscptrs[0]; else if (formal_arg_ptr->dtype != DTYPE_IDENT && - (formal_arg_ptr->dtype != DTYPE_T || !opt)) { + (formal_arg_ptr->dtype != DTYPE_T || !opt)) + { status = TdiINVDTYDSC; break; } @@ -892,23 +975,33 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, OUT is present, but undefined. Eval others with old vari list. ******************************/ - if (j >= nactual || (actual_ptr = actual_arg_ptr[j]) == 0) { + if (j >= nactual || (actual_ptr = actual_arg_ptr[j]) == 0) + { if (!opt) status = TdiMISS_ARG; - } else if (code == OPC_OUT) { + } + else if (code == OPC_OUT) + { old_head = _private.head; _private.head = new_head; status = put_ident(formal_arg_ptr, 0, TDITHREADSTATIC_VAR); new_head = _private.head; _private.head = old_head; - } else { - if (code == OPC_AS_IS) { + } + else + { + if (code == OPC_AS_IS) + { status = MdsCopyDxXd((mdsdsc_t *)actual_ptr, &tmp); - } else if (actual_ptr->dtype == DTYPE_IDENT) { + } + else if (actual_ptr->dtype == DTYPE_IDENT) + { status = get_ident((mdsdsc_t *)actual_ptr, &tmp, TDITHREADSTATIC_VAR); if (opt && status == TdiUNKNOWN_VAR) status = MDSplusSUCCESS; - } else { + } + else + { status = TdiEvaluate(actual_ptr, &tmp MDS_END_ARG); if (!opt && STATUS_OK && tmp.pointer == 0) status = TdiMISS_ARG; @@ -918,9 +1011,8 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, **************************/ old_head = _private.head; _private.head = new_head; - if - STATUS_OK - status = put_ident(formal_arg_ptr, &tmp, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = put_ident(formal_arg_ptr, &tmp, TDITHREADSTATIC_VAR); new_head = _private.head; _private.head = old_head; } @@ -931,20 +1023,23 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, old_head = _private.head; _private.head = new_head; TDI_VAR_NEW_NARG = nactual; - if - STATUS_OK { - status = TdiEvaluate(formal_ptr->dscptrs[1], out_ptr MDS_END_ARG); - if (status == TdiRETURN) - status = MDSplusSUCCESS; - } + if (STATUS_OK) + { + status = TdiEvaluate(formal_ptr->dscptrs[1], out_ptr MDS_END_ARG); + if (status == TdiRETURN) + status = MDSplusSUCCESS; + } /***************************** Send outputs back up the line. *****************************/ - for (j = 0; j < nactual && STATUS_OK; ++j) { + for (j = 0; j < nactual && STATUS_OK; ++j) + { formal_arg_ptr = (mdsdsc_r_t *)formal_ptr->dscptrs[j + 2]; if (actual_arg_ptr[j] && formal_arg_ptr->dtype == DTYPE_FUNCTION && - formal_arg_ptr->ndesc == 1) { - if ((code = *(unsigned short *)formal_arg_ptr->pointer) == OPC_OPTIONAL) { + formal_arg_ptr->ndesc == 1) + { + if ((code = *(unsigned short *)formal_arg_ptr->pointer) == OPC_OPTIONAL) + { formal_arg_ptr = (mdsdsc_r_t *)formal_arg_ptr->dscptrs[0]; if (formal_arg_ptr->dtype != DTYPE_FUNCTION || formal_arg_ptr->ndesc != 1) @@ -952,7 +1047,8 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, else code = *(unsigned short *)formal_arg_ptr->pointer; } - if (code == OPC_INOUT || code == OPC_OUT) { + if (code == OPC_INOUT || code == OPC_OUT) + { status = find_ident(7, (mdsdsc_r_t *)formal_arg_ptr->dscptrs[0], 0, &node_ptr, 0, TDITHREADSTATIC_VAR); /************************** @@ -960,10 +1056,9 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, **************************/ new_head = _private.head; _private.head = old_head; - if - STATUS_OK - status = - put_ident(actual_arg_ptr[j], &node_ptr->xd, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = + put_ident(actual_arg_ptr[j], &node_ptr->xd, TDITHREADSTATIC_VAR); old_head = _private.head; _private.head = new_head; } @@ -981,17 +1076,18 @@ int TdiDoFun(const mdsdsc_t *const ident_ptr, const int nactual, */ int Tdi1Equals(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; TDITHREADSTATIC_INIT; status = TdiEvaluate(list[1], out_ptr MDS_END_ARG); /************************************ Place the data or clear the variable. ************************************/ - if - STATUS_OK - status = put_ident((mdsdsc_r_t *)list[0], out_ptr, TDITHREADSTATIC_VAR); - else put_ident((mdsdsc_r_t *)list[0], NULL, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = put_ident((mdsdsc_r_t *)list[0], out_ptr, TDITHREADSTATIC_VAR); + else + put_ident((mdsdsc_r_t *)list[0], NULL, TDITHREADSTATIC_VAR); return status; } @@ -1000,7 +1096,8 @@ int Tdi1Equals(opcode_t opcode __attribute__((unused)), */ int Tdi1EqualsFirst(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; if (list[0]->dtype != DTYPE_FUNCTION || @@ -1017,12 +1114,12 @@ int Tdi1EqualsFirst(opcode_t opcode __attribute__((unused)), */ int Tdi1PreDec(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ INIT_STATUS; status = TdiSubtract(list[0], &true_dsc, out_ptr MDS_END_ARG); - if - STATUS_OK - status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); + if (STATUS_OK) + status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); return status; } @@ -1031,11 +1128,11 @@ int Tdi1PreDec(opcode_t opcode __attribute__((unused)), */ int Tdi1PreInc(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ int status = TdiAdd(list[0], &true_dsc, out_ptr MDS_END_ARG); - if - STATUS_OK - status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); + if (STATUS_OK) + status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); return status; } @@ -1044,16 +1141,15 @@ int Tdi1PreInc(opcode_t opcode __attribute__((unused)), */ int Tdi1PostDec(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; EMPTYXD(tmp); int status = get_ident(list[0], out_ptr, TDITHREADSTATIC_VAR); - if - STATUS_OK - status = TdiSubtract(out_ptr->pointer, &true_dsc, &tmp MDS_END_ARG); - if - STATUS_OK - status = put_ident((mdsdsc_r_t *)list[0], &tmp, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = TdiSubtract(out_ptr->pointer, &true_dsc, &tmp MDS_END_ARG); + if (STATUS_OK) + status = put_ident((mdsdsc_r_t *)list[0], &tmp, TDITHREADSTATIC_VAR); MdsFree1Dx(&tmp, NULL); return status; } @@ -1063,16 +1159,15 @@ int Tdi1PostDec(opcode_t opcode __attribute__((unused)), */ int Tdi1PostInc(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; EMPTYXD(tmp); int status = get_ident(list[0], out_ptr, TDITHREADSTATIC_VAR); - if - STATUS_OK - status = TdiAdd(out_ptr->pointer, &true_dsc, &tmp MDS_END_ARG); - if - STATUS_OK - status = put_ident((mdsdsc_r_t *)list[0], &tmp, TDITHREADSTATIC_VAR); + if (STATUS_OK) + status = TdiAdd(out_ptr->pointer, &true_dsc, &tmp MDS_END_ARG); + if (STATUS_OK) + status = put_ident((mdsdsc_r_t *)list[0], &tmp, TDITHREADSTATIC_VAR); MdsFree1Dx(&tmp, NULL); return status; } @@ -1084,15 +1179,16 @@ int Tdi1PostInc(opcode_t opcode __attribute__((unused)), */ int Tdi1Private(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; node_type *node_ptr; int status = LibLookupTree((void **)&_private.head, (void *)list[0], compare, (void **)&node_ptr); - if - STATUS_OK - status = MdsCopyDxXd(node_ptr->xd.pointer, out_ptr); - else if (status == LibKEYNOTFOU) status = TdiUNKNOWN_VAR; + if (STATUS_OK) + status = MdsCopyDxXd(node_ptr->xd.pointer, out_ptr); + else if (status == LibKEYNOTFOU) + status = TdiUNKNOWN_VAR; return status; } @@ -1102,16 +1198,17 @@ int Tdi1Private(opcode_t opcode __attribute__((unused)), */ int Tdi1Public(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ int status; LOCK_PUBLIC_PUSH; node_type *node_ptr; status = LibLookupTree((void **)&_public.head, (void *)list[0], compare, (void **)&node_ptr); - if - STATUS_OK - status = MdsCopyDxXd(node_ptr->xd.pointer, out_ptr); - else if (status == LibKEYNOTFOU) status = TdiUNKNOWN_VAR; + if (STATUS_OK) + status = MdsCopyDxXd(node_ptr->xd.pointer, out_ptr); + else if (status == LibKEYNOTFOU) + status = TdiUNKNOWN_VAR; UNLOCK_PUBLIC; return status; } @@ -1120,17 +1217,18 @@ int Tdi1Public(opcode_t opcode __attribute__((unused)), Find by text expression. */ int Tdi1Var(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ int status; INIT_AND_FREEXD_ON_EXIT(tmp); status = TdiData(list[0], &tmp MDS_END_ARG); - if - STATUS_OK { - if (narg < 2 || list[1] == 0) - status = tdi_get_ident(tmp.pointer, out_ptr); - else - status = TdiEquals(tmp.pointer, list[1], out_ptr MDS_END_ARG); - } + if (STATUS_OK) + { + if (narg < 2 || list[1] == 0) + status = tdi_get_ident(tmp.pointer, out_ptr); + else + status = TdiEquals(tmp.pointer, list[1], out_ptr MDS_END_ARG); + } FREEXD_NOW(tmp); return status; } @@ -1138,7 +1236,8 @@ int Tdi1Var(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], /*************************************************************** Define a function by reconstruction. */ -int Tdi1Fun(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { +int Tdi1Fun(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ DESCRIPTOR_FUNCTION(hold, 0, 255); int j; opcode_t opcode_s = opcode; @@ -1148,9 +1247,8 @@ int Tdi1Fun(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { if ((hold.arguments[j] = list[j]) == 0) return TdiNULL_PTR; int status = MdsCopyDxXd((mdsdsc_t *)&hold, out_ptr); - if - STATUS_OK - status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); + if (STATUS_OK) + status = tdi_put_ident((mdsdsc_r_t *)list[0], out_ptr); return status; } @@ -1158,7 +1256,8 @@ int Tdi1Fun(opcode_t opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { Release the private variables. This to be used by functions. */ -int Tdi1ResetPrivate() { +int Tdi1ResetPrivate() +{ INIT_STATUS; TDITHREADSTATIC_INIT; _private.head = 0; @@ -1172,7 +1271,8 @@ int Tdi1ResetPrivate() { /*-------------------------------------------------------------- Release the public variables. */ -int Tdi1ResetPublic() { +int Tdi1ResetPublic() +{ int status; LOCK_PUBLIC_PUSH; status = MDSplusSUCCESS; @@ -1189,7 +1289,8 @@ int Tdi1ResetPublic() { Display a variable. */ static int show_one(const node_type *const node_ptr, - user_type *const user_ptr) { + user_type *const user_ptr) +{ INIT_STATUS; mdsdsc_d_t tmp = EMPTY_D; mdsdsc_r_t *rptr = (mdsdsc_r_t *)node_ptr->xd.pointer; @@ -1200,31 +1301,31 @@ static int show_one(const node_type *const node_ptr, status = MDSplusSUCCESS; else status = StrMatchWild(&node_ptr->name_dsc, &user_ptr->match); - if - STATUS_OK { - if (rptr) - status = TdiDecompile(rptr, &tmp MDS_END_ARG); - if - STATUS_OK { - if (rptr && rptr->dtype == DTYPE_FUNCTION && - *(unsigned short *)rptr->pointer == OPC_FUN) - printf("%.*s\n", tmp.length, tmp.pointer); - else if (tmp.length > 0) - printf("%s %.*s\t= %.*s\n", - user_ptr->block_ptr->_public ? "Public" : "Private", - node_ptr->name_dsc.length, node_ptr->name_dsc.pointer, - tmp.length, tmp.pointer); - else - printf("%s %.*s\t=\n", - user_ptr->block_ptr->_public ? "Public" : "Private", - node_ptr->name_dsc.length, node_ptr->name_dsc.pointer); - user_ptr->count++; - } + if (STATUS_OK) + { + if (rptr) + status = TdiDecompile(rptr, &tmp MDS_END_ARG); + if (STATUS_OK) + { + if (rptr && rptr->dtype == DTYPE_FUNCTION && + *(unsigned short *)rptr->pointer == OPC_FUN) + printf("%.*s\n", tmp.length, tmp.pointer); + else if (tmp.length > 0) + printf("%s %.*s\t= %.*s\n", + user_ptr->block_ptr->_public ? "Public" : "Private", + node_ptr->name_dsc.length, node_ptr->name_dsc.pointer, + tmp.length, tmp.pointer); else - printf("ERROR on %.*s\n", node_ptr->name_dsc.length, - node_ptr->name_dsc.pointer); - StrFree1Dx(&tmp); + printf("%s %.*s\t=\n", + user_ptr->block_ptr->_public ? "Public" : "Private", + node_ptr->name_dsc.length, node_ptr->name_dsc.pointer); + user_ptr->count++; } + else + printf("ERROR on %.*s\n", node_ptr->name_dsc.length, + node_ptr->name_dsc.pointer); + StrFree1Dx(&tmp); + } else status = MDSplusSUCCESS; return status; @@ -1234,7 +1335,8 @@ static int show_one(const node_type *const node_ptr, Display private variables. */ int Tdi1ShowPrivate(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ TDITHREADSTATIC_INIT; DBG("TdiShowPrivate: %" PRIxPTR "\n", (uintptr_t)(void *)_private.head); return wild((int (*)())show_one, narg, list, &_private, out_ptr, @@ -1245,7 +1347,8 @@ int Tdi1ShowPrivate(opcode_t opcode __attribute__((unused)), int narg, Display public variables. */ int Tdi1ShowPublic(opcode_t opcode __attribute__((unused)), int narg, - mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { + mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ int status; LOCK_PUBLIC_PUSH; TDITHREADSTATIC_INIT; @@ -1255,7 +1358,8 @@ int Tdi1ShowPublic(opcode_t opcode __attribute__((unused)), int narg, return status; } -extern EXPORT int TdiSaveContext(void *ptr[6]) { +extern EXPORT int TdiSaveContext(void *ptr[6]) +{ TDITHREADSTATIC_INIT; ptr[0] = (void *)_private.head; ptr[1] = _private.head_zone; @@ -1269,12 +1373,14 @@ extern EXPORT int TdiSaveContext(void *ptr[6]) { return 1; } -extern EXPORT int TdiDeleteContext(void *ptr[6]) { +extern EXPORT int TdiDeleteContext(void *ptr[6]) +{ if (ptr[1]) LibDeleteVmZone(&ptr[1]); if (ptr[2]) LibDeleteVmZone(&ptr[2]); - if (ptr[4] || ptr[5]) { + if (ptr[4] || ptr[5]) + { LOCK_PUBLIC_PUSH; if (ptr[4]) LibDeleteVmZone(&ptr[4]); @@ -1288,7 +1394,8 @@ extern EXPORT int TdiDeleteContext(void *ptr[6]) { /*------------------------------------------------------------- Restore variable context */ -extern EXPORT int TdiRestoreContext(void *const ptr[6]) { +extern EXPORT int TdiRestoreContext(void *const ptr[6]) +{ TDITHREADSTATIC_INIT; DBG("TdiRestoreContext: %" PRIxPTR "\n", (uintptr_t)ptr[0]); _private.head = (node_type *)ptr[0]; diff --git a/tdishr/TdiVector.c b/tdishr/TdiVector.c index c1e383a507..cf3d441081 100644 --- a/tdishr/TdiVector.c +++ b/tdishr/TdiVector.c @@ -47,7 +47,8 @@ extern int TdiMasterData(); extern int Tdi2Vector(); int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; array miss = {sizeof(char), DTYPE_MISSING, @@ -58,8 +59,7 @@ int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], {0, 1, 1, 0, 0}, 1, 0}; - array_coeff arr = {sizeof(char), DTYPE_BU, CLASS_A, (char *)0, 0, 0, - {0, 1, 1, 1, 0}, MAX_DIMS, 0, 0, {0}}; + array_coeff arr = {sizeof(char), DTYPE_BU, CLASS_A, (char *)0, 0, 0, {0, 1, 1, 1, 0}, MAX_DIMS, 0, 0, {0}}; struct descriptor_xd(*psig)[], (*puni)[] = 0, (*pdat)[] = 0; struct TdiCatStruct(*pcats)[] = 0; int cmode = -1, j, n, (*pnelem)[] = 0, jd, mind = MAX_DIMS, maxd = 0, @@ -76,47 +76,49 @@ int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], ************************************/ status = (psig = malloc(virt)) != NULL; - if - STATUS_OK { - puni = (struct descriptor_xd(*)[]) & (*psig)[narg]; - pdat = (struct descriptor_xd(*)[]) & (*puni)[narg]; - pnelem = (int(*)[]) & (*pdat)[narg]; - pcats = - (struct TdiCatStruct(*)[]) & (*pnelem)[narg]; /* narg+1 of these */ - } + if (STATUS_OK) + { + puni = (struct descriptor_xd(*)[]) & (*psig)[narg]; + pdat = (struct descriptor_xd(*)[]) & (*puni)[narg]; + pnelem = (int(*)[]) & (*pdat)[narg]; + pcats = + (struct TdiCatStruct(*)[]) & (*pnelem)[narg]; /* narg+1 of these */ + } /****************************************** Fetch signals and data and data's category. ******************************************/ - if - STATUS_OK - status = TdiGetArgs(opcode, narg, list, (*psig), (*puni), (*pdat), (*pcats)); + if (STATUS_OK) + status = TdiGetArgs(opcode, narg, list, (*psig), (*puni), (*pdat), (*pcats)); /***************************************** Save and accumulate lengths of all inputs. *****************************************/ - if - STATUS_OK - for (j = narg; --j >= 0;) { - array_coeff *pnew = (array_coeff *)(*pdat)[j].pointer; - if ((*pcats)[j].digits > (*pcats)[narg].digits) - (*pcats)[narg].digits = (*pcats)[j].digits; - if (pnew->dtype == DTYPE_MISSING) { - n = 0; - nmiss++; - } else { - N_ELEMENTS(pnew, n); - if (pnew->class == CLASS_A) - jd = pnew->aflags.coeff ? pnew->dimct : 1; + if (STATUS_OK) + for (j = narg; --j >= 0;) + { + array_coeff *pnew = (array_coeff *)(*pdat)[j].pointer; + if ((*pcats)[j].digits > (*pcats)[narg].digits) + (*pcats)[narg].digits = (*pcats)[j].digits; + if (pnew->dtype == DTYPE_MISSING) + { + n = 0; + nmiss++; + } else - jd = 0; - if (jd < mind) - mind = jd; - if (jd > maxd) - maxd = jd; + { + N_ELEMENTS(pnew, n); + if (pnew->class == CLASS_A) + jd = pnew->aflags.coeff ? pnew->dimct : 1; + else + jd = 0; + if (jd < mind) + mind = jd; + if (jd > maxd) + maxd = jd; + } + arr.arsize += (*pnelem)[j] = n; } - arr.arsize += (*pnelem)[j] = n; - } /******************************** If all dimensions match then add one. @@ -126,12 +128,16 @@ int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], Shape: [[3,1],[3,4]] is [3,5]. Shape: [[3],[3,4]] is [3,5]. ********************************/ - if (STATUS_OK) { - if (mind > 0 && mind >= maxd - 1 && mind < MAX_DIMS && nmiss == 0) { + if (STATUS_OK) + { + if (mind > 0 && mind >= maxd - 1 && mind < MAX_DIMS && nmiss == 0) + { n = 0; - for (j = 0; j < narg; ++j) { + for (j = 0; j < narg; ++j) + { array_coeff *pnew = (array_coeff *)(*pdat)[j].pointer; - if (pnew->aflags.coeff) { + if (pnew->aflags.coeff) + { jd = pnew->dimct; n += (jd == maxd) ? pnew->m[maxd - 1] : 1; if (j == 0) @@ -143,7 +149,9 @@ int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], mind = jd; if (mind < maxd - 1) goto simple; - } else { + } + else + { n++; if (j == 0) arr.m[0] = (*pnelem)[j]; @@ -157,67 +165,68 @@ int Tdi1Vector(opcode_t opcode, int narg, struct descriptor *list[], arr.m[maxd - 1] = n; else arr.m[maxd] = narg; - } else { + } + else + { simple: arr.dimct = 1; arr.aflags.coeff = 0; } } - if - STATUS_OK - status = Tdi2Vector(narg, (*puni), (*pdat), (*pcats), 0); + if (STATUS_OK) + status = Tdi2Vector(narg, (*puni), (*pdat), (*pcats), 0); /********************* Find type conversions. *********************/ - if - STATUS_OK - status = TdiCvtArgs(0, (*pdat), &(*pcats)[narg]); + if (STATUS_OK) + status = TdiCvtArgs(0, (*pdat), &(*pcats)[narg]); /*************************** Get an array to hold it all. Size is 1 so arsize = nelem. ***************************/ - if - STATUS_OK - status = MdsGet1DxA((struct descriptor_a *)&arr, &(*pcats)[narg].digits, - &(*pcats)[narg].out_dtype, out_ptr); + if (STATUS_OK) + status = MdsGet1DxA((struct descriptor_a *)&arr, &(*pcats)[narg].digits, + &(*pcats)[narg].out_dtype, out_ptr); /********************************* Accumulate all arrays and scalars. Recycle arr as temporary pointer. Class and flags are the same. *********************************/ - if - STATUS_OK { - struct descriptor *pout = out_ptr->pointer; - arr.length = pout->length; - arr.dtype = pout->dtype; - arr.pointer = pout->pointer; - for (j = 0; j < narg && STATUS_OK; ++j) { - arr.arsize = (*pnelem)[j] * arr.length; - status = TdiConvert((*pdat)[j].pointer, &arr MDS_END_ARG); - arr.pointer += arr.arsize; - } - if (arr.length == 0 && arr.dtype == DTYPE_T && arr.dimct == 1) { - arr.aflags.coeff = 1; - arr.a0 = arr.pointer; - arr.m[0] = narg; - status = MdsCopyDxXd((struct descriptor *)&arr, out_ptr); - } + if (STATUS_OK) + { + struct descriptor *pout = out_ptr->pointer; + arr.length = pout->length; + arr.dtype = pout->dtype; + arr.pointer = pout->pointer; + for (j = 0; j < narg && STATUS_OK; ++j) + { + arr.arsize = (*pnelem)[j] * arr.length; + status = TdiConvert((*pdat)[j].pointer, &arr MDS_END_ARG); + arr.pointer += arr.arsize; } + if (arr.length == 0 && arr.dtype == DTYPE_T && arr.dimct == 1) + { + arr.aflags.coeff = 1; + arr.a0 = arr.pointer; + arr.m[0] = narg; + status = MdsCopyDxXd((struct descriptor *)&arr, out_ptr); + } + } /************************* Remove signal, keep units. *************************/ - if - STATUS_OK - status = TdiMasterData(0, (*psig), (*puni), &cmode, out_ptr); + if (STATUS_OK) + status = TdiMasterData(0, (*psig), (*puni), &cmode, out_ptr); /******************** Free all temporaries. ********************/ - for (j = narg; --j >= 0;) { + for (j = narg; --j >= 0;) + { if ((*psig)[j].pointer) MdsFree1Dx(&(*psig)[j], NULL); if ((*puni)[j].pointer) diff --git a/tdishr/TdiXxx.c b/tdishr/TdiXxx.c index a375ae7a55..d64db4cfbd 100644 --- a/tdishr/TdiXxx.c +++ b/tdishr/TdiXxx.c @@ -49,13 +49,18 @@ static const struct descriptor_xd BAD = {0, DTYPE_DSC, CLASS_XS, /******************************** Units must match or one be empty. ********************************/ -static int either(struct descriptor_xd uni[2]) { +static int either(struct descriptor_xd uni[2]) +{ - if (uni[0].pointer == 0) { + if (uni[0].pointer == 0) + { uni[0] = uni[1]; uni[1] = EMPTY_XD; - } else if (uni[1].pointer) { - if (StrCompare(uni[0].pointer, uni[1].pointer)) { + } + else if (uni[1].pointer) + { + if (StrCompare(uni[0].pointer, uni[1].pointer)) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; } @@ -66,7 +71,8 @@ static int either(struct descriptor_xd uni[2]) { /******************************* Discard units unless mismatched. *******************************/ -static int only_mismatch(struct descriptor_xd uni[2]) { +static int only_mismatch(struct descriptor_xd uni[2]) +{ either(uni); if (uni[0].pointer && uni[0].pointer != (struct descriptor *)&bad) @@ -78,13 +84,17 @@ static int only_mismatch(struct descriptor_xd uni[2]) { Concatenate units. *****************/ static void multiply(struct descriptor_xd *left_ptr, - struct descriptor_xd *right_ptr) { + struct descriptor_xd *right_ptr) +{ INIT_STATUS; - if (left_ptr->pointer == 0) { + if (left_ptr->pointer == 0) + { *left_ptr = *right_ptr; *right_ptr = EMPTY_XD; - } else if (right_ptr->pointer) { + } + else if (right_ptr->pointer) + { /*NEED cleaver code here */ status = TdiConcat(left_ptr, &asterisk, right_ptr, left_ptr MDS_END_ARG); if (STATUS_NOT_OK) @@ -96,21 +106,23 @@ static void multiply(struct descriptor_xd *left_ptr, Reciprocate units. *****************/ static void divide(struct descriptor_xd *left_ptr, - struct descriptor_xd *right_ptr) { + struct descriptor_xd *right_ptr) +{ INIT_STATUS; - if (right_ptr->pointer) { + if (right_ptr->pointer) + { /*NEED cleaver code here */ /*NEED to fix up leading / or * */ status = TdiTranslate(right_ptr, &star_slash, &slash_star, right_ptr MDS_END_ARG); - if - STATUS_OK { - if (left_ptr->pointer) - status = TdiConcat(left_ptr, &slash, right_ptr, left_ptr MDS_END_ARG); - else - status = TdiConcat(&slash, right_ptr, left_ptr MDS_END_ARG); - } + if (STATUS_OK) + { + if (left_ptr->pointer) + status = TdiConcat(left_ptr, &slash, right_ptr, left_ptr MDS_END_ARG); + else + status = TdiConcat(&slash, right_ptr, left_ptr MDS_END_ARG); + } if (STATUS_NOT_OK) *left_ptr = BAD; } @@ -125,7 +137,8 @@ int Tdi2Abs(int narg __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ if ((cats[0].in_cat & TdiCAT_B) == TdiCAT_BU) *routine_ptr = NULL; @@ -141,7 +154,8 @@ int Tdi2Add(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ either(uni); cats[0].out_cat = cats[1].out_cat = cats[2].out_cat; @@ -157,7 +171,8 @@ int Tdi2Atan2(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ only_mismatch(uni); cats[0].out_cat = cats[1].out_cat = cats[2].out_cat; @@ -173,7 +188,8 @@ int Tdi2Any(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ if (uni[0].pointer) MdsFree1Dx(&uni[0], NULL); @@ -187,7 +203,8 @@ int Tdi2Adjust(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[narg].digits = cats[0].digits; return 1; @@ -200,14 +217,16 @@ int Tdi2Adjust(int narg, struct descriptor_xd uni[1] __attribute__((unused)), int Tdi2Aint(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ INIT_STATUS; /************************** Check for valid second arg. Prevent its conversion. **************************/ - if (narg > 1) { + if (narg > 1) + { int kind = -1; status = TdiGetLong(dat[1].pointer, &kind); if (kind < TdiCAT_MAX) @@ -233,7 +252,8 @@ int Tdi2Bsearch(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), int o1 __attribute__((unused)), - int o2 __attribute__((unused))) { + int o2 __attribute__((unused))) +{ either(uni); cats[1].out_cat = cats[0].out_cat |= cats[1].out_cat; @@ -251,10 +271,12 @@ int Tdi2Btest(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ int j; - for (j = narg; --j > 0;) { + for (j = narg; --j > 0;) + { cats[j].out_dtype = DTYPE_L; cats[j].out_cat = TdiREF_CAT[DTYPE_L].cat; } @@ -267,14 +289,16 @@ int Tdi2Btest(int narg, struct descriptor_xd uni[1] __attribute__((unused)), int Tdi2Char(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ INIT_STATUS; /************************** Check for valid second arg. Prevent its conversion. **************************/ - if (narg > 1) { + if (narg > 1) + { int kind = -1; status = TdiGetLong(dat[1].pointer, &kind); if (kind < TdiCAT_MAX) @@ -300,7 +324,8 @@ int Tdi2Char(int narg, struct descriptor_xd uni[1] __attribute__((unused)), int Tdi2Cmplx(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ INIT_STATUS; /******************************** @@ -311,10 +336,12 @@ int Tdi2Cmplx(int narg, struct descriptor_xd uni[1], ********************************/ if (narg > 1) either(uni); - if (narg > 2) { + if (narg > 2) + { int kind = -1; status = TdiGetLong(dat[2].pointer, &kind); - if (kind < TdiCAT_MAX) { + if (kind < TdiCAT_MAX) + { cats[narg].out_cat = (unsigned short)((TdiREF_CAT[cats[narg].out_dtype = (unsigned char)kind] .cat | @@ -324,8 +351,11 @@ int Tdi2Cmplx(int narg, struct descriptor_xd uni[1], cats[2].out_dtype = cats[2].in_dtype; cats[2].out_cat = cats[2].in_cat; cats[0].out_cat = cats[1].out_cat = cats[narg].out_cat; - } else if (narg == 1) { - switch (cats[0].out_dtype) { + } + else if (narg == 1) + { + switch (cats[0].out_dtype) + { default: break; case DTYPE_F: @@ -352,7 +382,8 @@ int Tdi2Cmplx(int narg, struct descriptor_xd uni[1], } if (narg < 2 || cats[1].in_dtype == DTYPE_MISSING) *routine_ptr = NULL; - else { + else + { if (cats[0].in_cat != cats[0].out_cat) cats[0].out_cat &= ~TdiCAT_COMPLEX; if (cats[1].in_cat != cats[1].out_cat) @@ -368,7 +399,8 @@ int Tdi2Concat(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ either(uni); cats[2].digits = (unsigned short)(cats[0].digits + cats[1].digits); @@ -384,7 +416,8 @@ int Tdi2Cvt(int narg __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[2].out_dtype = cats[0].out_dtype = cats[1].out_dtype; cats[2].out_cat = cats[0].out_cat = cats[1].out_cat; @@ -399,7 +432,8 @@ int Tdi2Dble(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[0].out_cat = cats[1].out_cat = cats[narg].out_cat = (unsigned short)(cats[narg].out_cat + @@ -414,7 +448,8 @@ int Tdi2Divide(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ divide(&uni[0], &uni[1]); cats[0].out_cat = cats[1].out_cat = cats[2].out_cat; @@ -428,7 +463,8 @@ int Tdi2Dprod(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ multiply(&uni[0], &uni[1]); cats[0].out_cat = cats[1].out_cat = cats[narg].out_cat = @@ -447,7 +483,8 @@ int Tdi2Eq(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ only_mismatch(uni); cats[0].out_cat = cats[1].out_cat = @@ -463,7 +500,8 @@ int Tdi2Element(int narg, struct descriptor_xd uni[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), int o1 __attribute__((unused)), - int o2 __attribute__((unused))) { + int o2 __attribute__((unused))) +{ MdsFree1Dx(&uni[0], NULL); uni[0] = uni[2]; @@ -480,7 +518,8 @@ int Tdi2Extract(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), int o1 __attribute__((unused)), - int o2 __attribute__((unused))) { + int o2 __attribute__((unused))) +{ int length, status; MdsFree1Dx(&uni[0], NULL); @@ -506,7 +545,8 @@ int Tdi2Fix(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ int cmplx, j; cmplx = cats[0].out_cat & TdiCAT_COMPLEX; @@ -526,7 +566,8 @@ int Tdi2Iand(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ either(uni); cats[0].out_cat = cats[1].out_cat = cats[narg].out_cat; @@ -545,7 +586,8 @@ int Tdi2Inverse(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), int o1 __attribute__((unused)), - int o2 __attribute__((unused))) { + int o2 __attribute__((unused))) +{ struct descriptor_xd tmp = uni[0]; uni[0] = EMPTY_XD; @@ -567,7 +609,8 @@ int Tdi2Keep(int narg __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ return 1; } @@ -578,14 +621,17 @@ int Tdi2Land(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ only_mismatch(uni); - if (cats[0].out_cat != DTYPE_BU) { + if (cats[0].out_cat != DTYPE_BU) + { cats[0].out_dtype = DTYPE_BU; cats[0].out_cat = TdiREF_CAT[DTYPE_BU].cat; } - if (cats[1].out_cat != DTYPE_BU) { + if (cats[1].out_cat != DTYPE_BU) + { cats[1].out_dtype = DTYPE_BU; cats[1].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -600,12 +646,14 @@ int Tdi2Long2(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ int j; cats[narg].out_dtype = cats[0].out_dtype; cats[narg].out_cat = cats[0].out_cat; - for (j = narg; --j > 0;) { + for (j = narg; --j > 0;) + { cats[j].out_dtype = DTYPE_L; cats[j].out_cat = TdiREF_CAT[DTYPE_L].cat; } @@ -620,11 +668,13 @@ int Tdi2Mask1(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ if (uni[0].pointer) MdsFree1Dx(&uni[0], NULL); - if (cats[0].out_cat != cats[0].in_cat) { + if (cats[0].out_cat != cats[0].in_cat) + { cats[0].out_dtype = DTYPE_BU; cats[0].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -639,12 +689,14 @@ int Tdi2Mask2(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ int j; if (uni[0].pointer) MdsFree1Dx(&uni[0], NULL); - for (j = narg; --j > 0;) { + for (j = narg; --j > 0;) + { cats[j].out_cat = (unsigned short)((cats[j].out_cat | TdiREF_CAT[DTYPE_BU].cat) & TdiREF_CAT[DTYPE_O].cat); @@ -662,14 +714,17 @@ int Tdi2Mask3(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[narg] = cats[0]; - if (narg > 2) { + if (narg > 2) + { cats[2].out_cat = (unsigned short)((cats[2].in_cat | TdiREF_CAT[DTYPE_BU].cat) & TdiREF_CAT[DTYPE_O].cat); - if (cats[2].out_cat != cats[2].in_cat) { + if (cats[2].out_cat != cats[2].in_cat) + { cats[2].out_dtype = DTYPE_BU; cats[2].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -685,15 +740,18 @@ int Tdi2Mask3L(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[narg].out_dtype = DTYPE_L; cats[narg].out_cat = TdiREF_CAT[DTYPE_L].cat; - if (narg > 2) { + if (narg > 2) + { cats[2].out_cat = (unsigned short)((cats[2].in_cat | TdiREF_CAT[DTYPE_BU].cat) & TdiREF_CAT[DTYPE_O].cat); - if (cats[2].out_cat != cats[2].in_cat) { + if (cats[2].out_cat != cats[2].in_cat) + { cats[2].out_dtype = DTYPE_BU; cats[2].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -709,7 +767,8 @@ int Tdi2Merge(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ either(uni); cats[narg].out_cat = cats[1].out_cat = cats[0].out_cat = @@ -734,7 +793,8 @@ int Tdi2Multiply(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), int o1 __attribute__((unused)), - int o2 __attribute__((unused))) { + int o2 __attribute__((unused))) +{ multiply(&uni[0], &uni[1]); cats[0].out_cat = cats[1].out_cat = cats[2].out_cat; @@ -749,9 +809,11 @@ int Tdi2None(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ - if (uni[0].pointer) { + if (uni[0].pointer) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; } @@ -765,13 +827,16 @@ int Tdi2Not(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ - if (uni[0].pointer) { + if (uni[0].pointer) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; } - if (cats[0].in_cat != cats[0].out_cat) { + if (cats[0].in_cat != cats[0].out_cat) + { cats[0].out_dtype = DTYPE_BU; cats[0].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -786,13 +851,16 @@ int Tdi2NoHc(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ - if (uni[0].pointer) { + if (uni[0].pointer) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; } - if (cats[narg].out_cat == TdiREF_CAT[DTYPE_HC].cat) { + if (cats[narg].out_cat == TdiREF_CAT[DTYPE_HC].cat) + { cats[narg].out_dtype = DTYPE_GC; cats[narg].out_cat = TdiREF_CAT[DTYPE_GC].cat; } @@ -807,9 +875,11 @@ int Tdi2Pack(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ - if (narg > 2 && uni[2].pointer) { + if (narg > 2 && uni[2].pointer) + { MdsFree1Dx(&uni[1], NULL); uni[1] = uni[2]; uni[2] = EMPTY_XD; @@ -820,7 +890,8 @@ int Tdi2Pack(int narg, struct descriptor_xd uni[1], cats[1].out_cat = (unsigned short)((cats[1].in_cat | TdiREF_CAT[DTYPE_BU].cat) & TdiREF_CAT[DTYPE_O].cat); - if (cats[1].out_cat != cats[1].in_cat) { + if (cats[1].out_cat != cats[1].in_cat) + { cats[1].out_dtype = DTYPE_BU; cats[1].out_cat = TdiREF_CAT[DTYPE_BU].cat; } @@ -834,22 +905,28 @@ int Tdi2Power(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ /****************************************** Permit any^long, real^same, complex^same. Integer exponents become long. Result=base. ******************************************/ - if (uni[0].pointer || uni[1].pointer) { + if (uni[0].pointer || uni[1].pointer) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; } - if (cats[1].out_cat < TdiCAT_F) { + if (cats[1].out_cat < TdiCAT_F) + { cats[1].out_dtype = DTYPE_L; cats[1].out_cat = TdiREF_CAT[DTYPE_L].cat; - } else { + } + else + { cats[0].out_cat |= cats[1].out_cat; - if (cats[0].out_cat == TdiREF_CAT[DTYPE_HC].cat) { + if (cats[0].out_cat == TdiREF_CAT[DTYPE_HC].cat) + { cats[0].out_dtype = DTYPE_GC; cats[0].out_cat = TdiREF_CAT[DTYPE_GC].cat; } @@ -867,13 +944,15 @@ int Tdi2Range(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ if (narg > 2) either(&uni[1]); either(uni); cats[2].out_cat = cats[1].out_cat = cats[0].out_cat = cats[narg].out_cat; - if (cats[2].out_cat == TdiREF_CAT[DTYPE_T].cat) { + if (cats[2].out_cat == TdiREF_CAT[DTYPE_T].cat) + { if (cats[0].digits < cats[1].digits) cats[0].digits = cats[1].digits; if (cats[0].digits < cats[2].digits) @@ -890,14 +969,16 @@ int Tdi2Range(int narg, struct descriptor_xd uni[1], int Tdi2Real(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ INIT_STATUS; /************************** Check for valid second arg. Prevent its conversion. **************************/ - if (narg > 1) { + if (narg > 1) + { int kind = -1; status = TdiGetLong(dat[1].pointer, &kind); if (kind < TdiCAT_MAX) @@ -919,17 +1000,18 @@ int Tdi2Real(int narg, struct descriptor_xd uni[1] __attribute__((unused)), int Tdi2Repeat(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ unsigned int ncopies, status; status = TdiGetLong(dat[1].pointer, &ncopies); - if - STATUS_OK { - if ((ncopies *= cats[0].digits) < 65535) - cats[narg].digits = (unsigned short)ncopies; - else - status = TdiTOO_BIG; - } + if (STATUS_OK) + { + if ((ncopies *= cats[0].digits) < 65535) + cats[narg].digits = (unsigned short)ncopies; + else + status = TdiTOO_BIG; + } cats[1].out_cat = cats[1].in_cat; return status; } @@ -942,7 +1024,8 @@ int Tdi2Shft(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[1].out_dtype = cats[0].out_dtype; cats[1].out_cat = cats[0].out_cat; @@ -958,7 +1041,8 @@ int Tdi2Sign(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ cats[narg].out_cat = cats[0].out_cat; return 1; @@ -971,7 +1055,8 @@ int Tdi2Square(int narg __attribute__((unused)), struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ struct descriptor_xd tmp = EMPTY_XD; INIT_STATUS; @@ -987,20 +1072,21 @@ int Tdi2Square(int narg __attribute__((unused)), struct descriptor_xd uni[1], int Tdi2String(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ unsigned int length, status; cats[1].out_dtype = cats[1].in_dtype; cats[1].out_cat = cats[1].in_cat; cats[1].digits = dat[1].length; status = TdiGetLong(dat[1].pointer, &length); - if - STATUS_OK { - if (length > 65535) - status = TdiTOO_BIG; - else if (length > 0) - cats[0].digits = cats[narg].digits = (unsigned short)length; - } + if (STATUS_OK) + { + if (length > 65535) + status = TdiTOO_BIG; + else if (length > 0) + cats[0].digits = cats[narg].digits = (unsigned short)length; + } return status; } @@ -1010,20 +1096,21 @@ int Tdi2String(int narg, struct descriptor_xd uni[1] __attribute__((unused)), int Tdi2Text(int narg, struct descriptor_xd uni[1] __attribute__((unused)), struct descriptor_xd dat[1], struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ unsigned int length, status; cats[1].out_dtype = cats[1].in_dtype; cats[1].out_cat = cats[1].in_cat; cats[1].digits = dat[1].length; status = TdiGetLong(dat[1].pointer, &length); - if - STATUS_OK { - if (length > 65535) - status = TdiTOO_BIG; - else if (length > 0) - cats[0].digits = cats[narg].digits = (unsigned short)length; - } + if (STATUS_OK) + { + if (length > 65535) + status = TdiTOO_BIG; + else if (length > 0) + cats[0].digits = cats[narg].digits = (unsigned short)length; + } return status; } @@ -1035,7 +1122,8 @@ int Tdi2Ttb(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1], int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ either(uni); if (narg > 2) @@ -1051,15 +1139,21 @@ int Tdi2Vector(int narg, struct descriptor_xd uni[1], struct descriptor_xd dat[1] __attribute__((unused)), struct TdiCatStruct cats[1] __attribute__((unused)), int (**routine_ptr)() __attribute__((unused)), - int o1 __attribute__((unused)), int o2 __attribute__((unused))) { + int o1 __attribute__((unused)), int o2 __attribute__((unused))) +{ int j; - for (j = narg; --j > 0;) { - if (uni[0].pointer == 0) { + for (j = narg; --j > 0;) + { + if (uni[0].pointer == 0) + { uni[0] = uni[j]; uni[j] = EMPTY_XD; - } else if (uni[j].pointer) { - if (StrCompare(uni[0].pointer, uni[j].pointer)) { + } + else if (uni[j].pointer) + { + if (StrCompare(uni[0].pointer, uni[j].pointer)) + { MdsFree1Dx(&uni[0], NULL); uni[0] = BAD; break; diff --git a/tdishr/TdiXxxOf.c b/tdishr/TdiXxxOf.c index 80a5be134f..d0d98adea9 100644 --- a/tdishr/TdiXxxOf.c +++ b/tdishr/TdiXxxOf.c @@ -48,13 +48,14 @@ extern int TdiTaskOf(); NEED to remember to use AS_IS to prevent FUNCTION evaluation. */ int Tdi1ArgOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; unsigned int iarg = 0; static const dtype_t omits[] = { - DTYPE_CALL, DTYPE_CONDITION, DTYPE_DEPENDENCY, DTYPE_FUNCTION, - DTYPE_METHOD, DTYPE_PROCEDURE, DTYPE_ROUTINE, 0}; + DTYPE_CALL, DTYPE_CONDITION, DTYPE_DEPENDENCY, DTYPE_FUNCTION, + DTYPE_METHOD, DTYPE_PROCEDURE, DTYPE_ROUTINE, 0}; status = tdi_get_data(omits, list[0], &tmp); if (STATUS_OK && narg > 1) @@ -63,45 +64,45 @@ int Tdi1ArgOf(opcode_t opcode __attribute__((unused)), int narg, status = TdiINVCLADSC; if (STATUS_OK && iarg >= ((struct descriptor_r *)tmp.pointer)->ndesc) status = TdiBAD_INDEX; - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CALL: - if (iarg + 2 >= ((struct descriptor_r *)tmp.pointer)->ndesc) - status = TdiBAD_INDEX; - else + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CALL: + if (iarg + 2 >= ((struct descriptor_r *)tmp.pointer)->ndesc) + status = TdiBAD_INDEX; + else + status = MdsCopyDxXd( + ((struct descriptor_call *)tmp.pointer)->arguments[iarg], out_ptr); + break; + case DTYPE_CONDITION: status = MdsCopyDxXd( - ((struct descriptor_call *)tmp.pointer)->arguments[iarg], out_ptr); - break; - case DTYPE_CONDITION: - status = MdsCopyDxXd( - ((struct descriptor_condition *)tmp.pointer)->condition, out_ptr); - break; - case DTYPE_DEPENDENCY: - status = MdsCopyDxXd( - ((struct descriptor_dependency *)tmp.pointer)->arguments[iarg], - out_ptr); - break; - case DTYPE_FUNCTION: - status = MdsCopyDxXd( - ((struct descriptor_function *)tmp.pointer)->arguments[iarg], out_ptr); - break; - case DTYPE_METHOD: - status = MdsCopyDxXd( - ((struct descriptor_method *)tmp.pointer)->arguments[iarg], out_ptr); - break; - case DTYPE_PROCEDURE: - status = MdsCopyDxXd( - ((struct descriptor_procedure *)tmp.pointer)->arguments[iarg], out_ptr); - break; - case DTYPE_ROUTINE: - status = MdsCopyDxXd( - ((struct descriptor_routine *)tmp.pointer)->arguments[iarg], out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + ((struct descriptor_condition *)tmp.pointer)->condition, out_ptr); + break; + case DTYPE_DEPENDENCY: + status = MdsCopyDxXd( + ((struct descriptor_dependency *)tmp.pointer)->arguments[iarg], + out_ptr); + break; + case DTYPE_FUNCTION: + status = MdsCopyDxXd( + ((struct descriptor_function *)tmp.pointer)->arguments[iarg], out_ptr); + break; + case DTYPE_METHOD: + status = MdsCopyDxXd( + ((struct descriptor_method *)tmp.pointer)->arguments[iarg], out_ptr); + break; + case DTYPE_PROCEDURE: + status = MdsCopyDxXd( + ((struct descriptor_procedure *)tmp.pointer)->arguments[iarg], out_ptr); + break; + case DTYPE_ROUTINE: + status = MdsCopyDxXd( + ((struct descriptor_routine *)tmp.pointer)->arguments[iarg], out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -114,28 +115,29 @@ int Tdi1ArgOf(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1AxisOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_DIMENSION, DTYPE_SLOPE, DTYPE_RANGE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_DIMENSION: - status = MdsCopyDxXd(((struct descriptor_dimension *)tmp.pointer)->axis, - out_ptr); - break; - case DTYPE_SLOPE: - case DTYPE_RANGE: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_DIMENSION: + status = MdsCopyDxXd(((struct descriptor_dimension *)tmp.pointer)->axis, + out_ptr); + break; + case DTYPE_SLOPE: + case DTYPE_RANGE: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -147,45 +149,45 @@ int Tdi1AxisOf(opcode_t opcode __attribute__((unused)), startidx_field = BEGIN_OF(window) */ int Tdi1BeginOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; unsigned int n = 0; static const dtype_t omits[] = {DTYPE_RANGE, DTYPE_SLOPE, DTYPE_WINDOW, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_RANGE: - if (narg > 1) - status = TdiEXTRA_ARG; - else - status = - MdsCopyDxXd(((struct descriptor_range *)tmp.pointer)->begin, out_ptr); - break; - case DTYPE_SLOPE: - if (narg > 1) - status = TdiGetLong(list[1], &n); - if (STATUS_OK && - 3 * n + 2 > ((struct descriptor_slope *)tmp.pointer)->ndesc) - status = TdiBAD_INDEX; - if - STATUS_OK - status = MdsCopyDxXd( - ((struct descriptor_slope *)tmp.pointer)->segment[n].begin, out_ptr); - break; - case DTYPE_WINDOW: - if (narg > 1) - status = TdiEXTRA_ARG; - else - status = MdsCopyDxXd(((struct descriptor_window *)tmp.pointer)->startidx, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_RANGE: + if (narg > 1) + status = TdiEXTRA_ARG; + else + status = + MdsCopyDxXd(((struct descriptor_range *)tmp.pointer)->begin, out_ptr); + break; + case DTYPE_SLOPE: + if (narg > 1) + status = TdiGetLong(list[1], &n); + if (STATUS_OK && + 3 * n + 2 > ((struct descriptor_slope *)tmp.pointer)->ndesc) + status = TdiBAD_INDEX; + if (STATUS_OK) + status = MdsCopyDxXd( + ((struct descriptor_slope *)tmp.pointer)->segment[n].begin, out_ptr); + break; + case DTYPE_WINDOW: + if (narg > 1) + status = TdiEXTRA_ARG; + else + status = MdsCopyDxXd(((struct descriptor_window *)tmp.pointer)->startidx, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -196,7 +198,8 @@ int Tdi1BeginOf(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1ClassOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *px = list[0]; unsigned char class; @@ -216,13 +219,13 @@ int Tdi1ClassOf(opcode_t opcode __attribute__((unused)), byte = CLASS(any) */ int Tdi1Class(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - if - STATUS_OK - status = Tdi1ClassOf(opcode, narg, &out_ptr->pointer, out_ptr); + if (STATUS_OK) + status = Tdi1ClassOf(opcode, narg, &out_ptr->pointer, out_ptr); return status; } @@ -232,15 +235,15 @@ int Tdi1Class(opcode_t opcode, int narg, struct descriptor *list[], */ int Tdi1CompletionOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; status = TdiDispatchOf(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->completion, - out_ptr); + if (STATUS_OK) + status = MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->completion, + out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -252,27 +255,28 @@ int Tdi1CompletionOf(opcode_t opcode __attribute__((unused)), int Tdi1CompletionMessageOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_ACTION, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_ACTION: - if (((struct descriptor_action *)tmp.pointer)->ndesc < 4) - status = MdsFree1Dx(out_ptr, NULL); - else - status = MdsCopyDxXd( - ((struct descriptor_action *)tmp.pointer)->completion_message, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_ACTION: + if (((struct descriptor_action *)tmp.pointer)->ndesc < 4) + status = MdsFree1Dx(out_ptr, NULL); + else + status = MdsCopyDxXd( + ((struct descriptor_action *)tmp.pointer)->completion_message, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -283,23 +287,24 @@ int Tdi1CompletionMessageOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ConditionOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_CONDITION, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CONDITION: - status = MdsCopyDxXd( - ((struct descriptor_condition *)tmp.pointer)->condition, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CONDITION: + status = MdsCopyDxXd( + ((struct descriptor_condition *)tmp.pointer)->condition, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -312,7 +317,8 @@ int Tdi1ConditionOf(opcode_t opcode __attribute__((unused)), same = DIM_OF(dimension) */ int Tdi1DimOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; array_bounds *pa; struct descriptor_xd tmp = EMPTY_XD; @@ -329,66 +335,73 @@ int Tdi1DimOf(opcode_t opcode __attribute__((unused)), int narg, status = TdiGetLong(list[1], &index); pa = (array_bounds *)tmp.pointer; - if - STATUS_OK - switch (pa->class) { - case CLASS_A: - dimct = pa->aflags.coeff ? pa->dimct : 1; - if (index >= dimct) - status = TdiBAD_INDEX; - /******************************************* + if (STATUS_OK) + switch (pa->class) + { + case CLASS_A: + dimct = pa->aflags.coeff ? pa->dimct : 1; + if (index >= dimct) + status = TdiBAD_INDEX; + /******************************************* After arsize is a0, multipliers, and bounds. NEED we reverse for non-FORTRAN? *******************************************/ - else if (pa->aflags.bounds) { - l = pa->m[dimct + 2 * index]; - u = pa->m[dimct + 2 * index + 1]; - } else if (pa->aflags.coeff) { - l = 0; - u = pa->m[index] - 1; - } else { - l = 0; - u = (int)pa->arsize / (int)pa->length - 1; - } - if - STATUS_OK { + else if (pa->aflags.bounds) + { + l = pa->m[dimct + 2 * index]; + u = pa->m[dimct + 2 * index + 1]; + } + else if (pa->aflags.coeff) + { + l = 0; + u = pa->m[index] - 1; + } + else + { + l = 0; + u = (int)pa->arsize / (int)pa->length - 1; + } + if (STATUS_OK) + { struct descriptor ldsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; struct descriptor udsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; ldsc.pointer = (char *)&l; udsc.pointer = (char *)&u; status = TdiBuildRange(&ldsc, &udsc, out_ptr MDS_END_ARG); } - break; - case CLASS_R: - switch (pa->dtype) { - case DTYPE_DIMENSION: - if (index > 0) - status = TdiBAD_INDEX; - else - status = MdsCopyDxXd((struct descriptor *)&tmp, out_ptr); break; - case DTYPE_SIGNAL: - if (index > ((struct descriptor_signal *)pa)->ndesc - 3 || - ((struct descriptor_signal *)pa)->dimensions[index] == 0) { - struct descriptor_s index_dsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; - index_dsc.pointer = (char *)&index; - status = tdi_get_data(&omits[1], &tmp, &tmp); - if - STATUS_OK - status = TdiDimOf(&tmp, &index_dsc, out_ptr MDS_END_ARG); - } else - status = MdsCopyDxXd( - ((struct descriptor_signal *)pa)->dimensions[index], out_ptr); + case CLASS_R: + switch (pa->dtype) + { + case DTYPE_DIMENSION: + if (index > 0) + status = TdiBAD_INDEX; + else + status = MdsCopyDxXd((struct descriptor *)&tmp, out_ptr); + break; + case DTYPE_SIGNAL: + if (index > ((struct descriptor_signal *)pa)->ndesc - 3 || + ((struct descriptor_signal *)pa)->dimensions[index] == 0) + { + struct descriptor_s index_dsc = {sizeof(int), DTYPE_L, CLASS_S, 0}; + index_dsc.pointer = (char *)&index; + status = tdi_get_data(&omits[1], &tmp, &tmp); + if (STATUS_OK) + status = TdiDimOf(&tmp, &index_dsc, out_ptr MDS_END_ARG); + } + else + status = MdsCopyDxXd( + ((struct descriptor_signal *)pa)->dimensions[index], out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } break; default: - status = TdiINVDTYDSC; + status = TdiINVCLADSC; break; } - break; - default: - status = TdiINVCLADSC; - break; - } MdsFree1Dx(&tmp, NULL); return status; } @@ -400,27 +413,28 @@ int Tdi1DimOf(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1DispatchOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_ACTION, DTYPE_DISPATCH, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_ACTION: - status = TdiDispatchOf(((struct descriptor_action *)tmp.pointer)->dispatch, - out_ptr MDS_END_ARG); - break; - case DTYPE_DISPATCH: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_ACTION: + status = TdiDispatchOf(((struct descriptor_action *)tmp.pointer)->dispatch, + out_ptr MDS_END_ARG); + break; + case DTYPE_DISPATCH: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -431,36 +445,40 @@ int Tdi1DispatchOf(opcode_t opcode __attribute__((unused)), descriptor = DSCPTR_OF(classAPD, [number]) */ int Tdi1DscptrOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_r *pr = (struct descriptor_r *)list[0]; unsigned int iarg = 0; while (pr && pr->dtype == DTYPE_DSC) pr = (struct descriptor_r *)pr->pointer; - if (pr) { + if (pr) + { if (narg > 1) status = TdiGetLong(list[1], &iarg); - if - STATUS_OK - switch (pr->class) { - case CLASS_R: - if (iarg >= pr->ndesc) - status = TdiBAD_INDEX; - else - status = MdsCopyDxXd(pr->dscptrs[iarg], out_ptr); - break; - case CLASS_APD: { - array_desc *pa = (array_desc *)pr; - if (iarg >= pa->arsize / pa->length) - status = TdiBAD_INDEX; - else - status = MdsCopyDxXd(pa->pointer[iarg], out_ptr); - } break; - default: - status = TdiINVCLADSC; + if (STATUS_OK) + switch (pr->class) + { + case CLASS_R: + if (iarg >= pr->ndesc) + status = TdiBAD_INDEX; + else + status = MdsCopyDxXd(pr->dscptrs[iarg], out_ptr); + break; + case CLASS_APD: + { + array_desc *pa = (array_desc *)pr; + if (iarg >= pa->arsize / pa->length) + status = TdiBAD_INDEX; + else + status = MdsCopyDxXd(pa->pointer[iarg], out_ptr); + } break; - } + default: + status = TdiINVCLADSC; + break; + } } return status; } @@ -470,16 +488,16 @@ int Tdi1DscptrOf(opcode_t opcode __attribute__((unused)), int narg, byte = DSCPTR(any) */ int Tdi1Dscptr(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD, *new[2]; new[0] = &tmp; new[1] = narg > 1 ? (struct descriptor_xd *)list[1] : (struct descriptor_xd *)0; status = TdiEvaluate(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = Tdi1DscptrOf(opcode, narg, (struct descriptor **)new, out_ptr); + if (STATUS_OK) + status = Tdi1DscptrOf(opcode, narg, (struct descriptor **)new, out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -490,7 +508,8 @@ int Tdi1Dscptr(opcode_t opcode, int narg, struct descriptor *list[], */ int Tdi1KindOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor *px = list[0]; unsigned char dtype; @@ -510,13 +529,13 @@ int Tdi1KindOf(opcode_t opcode __attribute__((unused)), byte = KIND(any) */ int Tdi1Kind(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - if - STATUS_OK - status = Tdi1KindOf(opcode, narg, &out_ptr->pointer, out_ptr); + if (STATUS_OK) + status = Tdi1KindOf(opcode, narg, &out_ptr->pointer, out_ptr); return status; } @@ -527,45 +546,45 @@ int Tdi1Kind(opcode_t opcode, int narg, struct descriptor *list[], endidx_field = END_OF(&window) */ int Tdi1EndOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; unsigned int n = 0; static const dtype_t omits[] = {DTYPE_RANGE, DTYPE_SLOPE, DTYPE_WINDOW, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_RANGE: - if (narg > 1) - status = TdiEXTRA_ARG; - else - status = MdsCopyDxXd(((struct descriptor_range *)tmp.pointer)->ending, - out_ptr); - break; - case DTYPE_SLOPE: - if (narg > 1) - status = TdiGetLong(list[1], &n); - if (STATUS_OK && - 3 * n + 3 > ((struct descriptor_slope *)tmp.pointer)->ndesc) - status = TdiBAD_INDEX; - if - STATUS_OK - status = MdsCopyDxXd( - ((struct descriptor_slope *)tmp.pointer)->segment[n].ending, out_ptr); - break; - case DTYPE_WINDOW: - if (narg > 1) - status = TdiEXTRA_ARG; - else - status = MdsCopyDxXd(((struct descriptor_window *)tmp.pointer)->endingidx, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_RANGE: + if (narg > 1) + status = TdiEXTRA_ARG; + else + status = MdsCopyDxXd(((struct descriptor_range *)tmp.pointer)->ending, + out_ptr); + break; + case DTYPE_SLOPE: + if (narg > 1) + status = TdiGetLong(list[1], &n); + if (STATUS_OK && + 3 * n + 3 > ((struct descriptor_slope *)tmp.pointer)->ndesc) + status = TdiBAD_INDEX; + if (STATUS_OK) + status = MdsCopyDxXd( + ((struct descriptor_slope *)tmp.pointer)->segment[n].ending, out_ptr); + break; + case DTYPE_WINDOW: + if (narg > 1) + status = TdiEXTRA_ARG; + else + status = MdsCopyDxXd(((struct descriptor_window *)tmp.pointer)->endingidx, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -576,24 +595,25 @@ int Tdi1EndOf(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1ErrorOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const DESCRIPTOR(none, ""); struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_WITH_ERROR, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_WITH_ERROR: - status = MdsCopyDxXd(((struct descriptor_with_error *)tmp.pointer)->error, - out_ptr); - break; - default: - status = MdsCopyDxXd((struct descriptor *)&none, out_ptr); - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_WITH_ERROR: + status = MdsCopyDxXd(((struct descriptor_with_error *)tmp.pointer)->error, + out_ptr); + break; + default: + status = MdsCopyDxXd((struct descriptor *)&none, out_ptr); + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -604,25 +624,26 @@ int Tdi1ErrorOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ErrorlogsOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_ACTION, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_ACTION: - if (((struct descriptor_action *)tmp.pointer)->ndesc < 3) - status = MdsFree1Dx(out_ptr, NULL); - else - status = MdsCopyDxXd(((struct descriptor_action *)tmp.pointer)->errorlogs, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_ACTION: + if (((struct descriptor_action *)tmp.pointer)->ndesc < 3) + status = MdsFree1Dx(out_ptr, NULL); + else + status = MdsCopyDxXd(((struct descriptor_action *)tmp.pointer)->errorlogs, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -633,23 +654,24 @@ int Tdi1ErrorlogsOf(opcode_t opcode __attribute__((unused)), */ int Tdi1HelpOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_PARAM, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_PARAM: - status = - MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->help, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_PARAM: + status = + MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->help, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -660,15 +682,15 @@ int Tdi1HelpOf(opcode_t opcode __attribute__((unused)), */ int Tdi1IdentOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; status = TdiDispatchOf(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = - MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->ident, out_ptr); + if (STATUS_OK) + status = + MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->ident, out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -681,31 +703,32 @@ int Tdi1IdentOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ImageOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_CALL, DTYPE_CONGLOM, DTYPE_ROUTINE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CALL: - status = - MdsCopyDxXd(((struct descriptor_call *)tmp.pointer)->image, out_ptr); - break; - case DTYPE_CONGLOM: - status = - MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->image, out_ptr); - break; - case DTYPE_ROUTINE: - status = - MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->image, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CALL: + status = + MdsCopyDxXd(((struct descriptor_call *)tmp.pointer)->image, out_ptr); + break; + case DTYPE_CONGLOM: + status = + MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->image, out_ptr); + break; + case DTYPE_ROUTINE: + status = + MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->image, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -716,26 +739,29 @@ int Tdi1ImageOf(opcode_t opcode __attribute__((unused)), */ int Tdi1InterruptOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; struct descriptor_dispatch *pd; char omits[] = {DTYPE_T, 0}; status = TdiDispatchOf(list[0], &tmp MDS_END_ARG); - if - STATUS_OK { - pd = (struct descriptor_dispatch *)tmp.pointer; - if (*(char *)pd->pointer != TreeSCHED_ASYNC) { - status = tdi_get_data(omits, pd->when, out_ptr); - if - STATUS_OK { - if (out_ptr->pointer == 0 || out_ptr->pointer->dtype != DTYPE_T) - status = TdiINVDTYDSC; - } - } else - status = TdiINV_OPC; + if (STATUS_OK) + { + pd = (struct descriptor_dispatch *)tmp.pointer; + if (*(char *)pd->pointer != TreeSCHED_ASYNC) + { + status = tdi_get_data(omits, pd->when, out_ptr); + if (STATUS_OK) + { + if (out_ptr->pointer == 0 || out_ptr->pointer->dtype != DTYPE_T) + status = TdiINVDTYDSC; + } } + else + status = TdiINV_OPC; + } else status = TdiINVDTYDSC; MdsFree1Dx(&tmp, NULL); @@ -748,23 +774,24 @@ int Tdi1InterruptOf(opcode_t opcode __attribute__((unused)), */ int Tdi1LanguageOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_PROCEDURE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_PROCEDURE: - status = MdsCopyDxXd(((struct descriptor_procedure *)tmp.pointer)->language, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_PROCEDURE: + status = MdsCopyDxXd(((struct descriptor_procedure *)tmp.pointer)->language, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -775,27 +802,28 @@ int Tdi1LanguageOf(opcode_t opcode __attribute__((unused)), */ int Tdi1MethodOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_METHOD, DTYPE_OPAQUE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_METHOD: - status = - MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->method, out_ptr); - break; - case DTYPE_OPAQUE: - status = MdsCopyDxXd(((struct descriptor_opaque *)tmp.pointer)->opaque_type, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_METHOD: + status = + MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->method, out_ptr); + break; + case DTYPE_OPAQUE: + status = MdsCopyDxXd(((struct descriptor_opaque *)tmp.pointer)->opaque_type, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -806,23 +834,24 @@ int Tdi1MethodOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ModelOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_CONGLOM, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CONGLOM: - status = - MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->model, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CONGLOM: + status = + MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->model, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -833,23 +862,24 @@ int Tdi1ModelOf(opcode_t opcode __attribute__((unused)), */ int Tdi1NameOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_CONGLOM, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CONGLOM: - status = - MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->name, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CONGLOM: + status = + MdsCopyDxXd(((struct descriptor_conglom *)tmp.pointer)->name, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -860,7 +890,8 @@ int Tdi1NameOf(opcode_t opcode __attribute__((unused)), */ int Tdi1NdescOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_r *pr = (struct descriptor_r *)list[0]; unsigned char ndesc; @@ -868,7 +899,8 @@ int Tdi1NdescOf(opcode_t opcode __attribute__((unused)), while (pr && pr->dtype == DTYPE_DSC) pr = (struct descriptor_r *)pr->pointer; if (pr) - switch (pr->class) { + switch (pr->class) + { case CLASS_R: ndesc = pr->ndesc; status = tdi_put_logical(ndesc, out_ptr); @@ -888,13 +920,13 @@ int Tdi1NdescOf(opcode_t opcode __attribute__((unused)), byte = NDESC(any) */ int Tdi1Ndesc(opcode_t opcode, int narg, struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; status = TdiEvaluate(list[0], out_ptr MDS_END_ARG); - if - STATUS_OK - status = Tdi1NdescOf(opcode, narg, &out_ptr->pointer, out_ptr); + if (STATUS_OK) + status = Tdi1NdescOf(opcode, narg, &out_ptr->pointer, out_ptr); return status; } @@ -904,23 +936,24 @@ int Tdi1Ndesc(opcode_t opcode, int narg, struct descriptor *list[], */ int Tdi1ObjectOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_METHOD, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_METHOD: - status = - MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->object, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_METHOD: + status = + MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->object, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -932,28 +965,29 @@ int Tdi1ObjectOf(opcode_t opcode __attribute__((unused)), int Tdi1PerformanceOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_ACTION, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_ACTION: - if (((struct descriptor_action *)tmp.pointer)->ndesc < 5) - status = MdsFree1Dx(out_ptr, NULL); - else - status = MdsCopyDxXd( - (struct descriptor *)((struct descriptor_action *)tmp.pointer) - ->performance, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_ACTION: + if (((struct descriptor_action *)tmp.pointer)->ndesc < 5) + status = MdsFree1Dx(out_ptr, NULL); + else + status = MdsCopyDxXd( + (struct descriptor *)((struct descriptor_action *)tmp.pointer) + ->performance, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -964,15 +998,15 @@ int Tdi1PerformanceOf(opcode_t opcode __attribute__((unused)), */ int Tdi1PhaseOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; status = TdiDispatchOf(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = - MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->phase, out_ptr); + if (STATUS_OK) + status = + MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->phase, out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -983,23 +1017,24 @@ int Tdi1PhaseOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ProcedureOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_PROCEDURE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_PROCEDURE: - status = MdsCopyDxXd( - ((struct descriptor_procedure *)tmp.pointer)->procedure, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_PROCEDURE: + status = MdsCopyDxXd( + ((struct descriptor_procedure *)tmp.pointer)->procedure, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1010,23 +1045,24 @@ int Tdi1ProcedureOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ProgramOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_PROGRAM, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_PROGRAM: - status = MdsCopyDxXd(((struct descriptor_program *)tmp.pointer)->program, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_PROGRAM: + status = MdsCopyDxXd(((struct descriptor_program *)tmp.pointer)->program, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1042,7 +1078,8 @@ int Tdi1ProgramOf(opcode_t opcode __attribute__((unused)), */ int Tdi1QualifiersOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; struct descriptor *pd; @@ -1056,29 +1093,30 @@ int Tdi1QualifiersOf(opcode_t opcode __attribute__((unused)), status = tdi_get_data(omits, list[0], &tmp); pd = tmp.pointer; - if - STATUS_OK - switch (pd->dtype) { - case DTYPE_CONGLOM: - status = - MdsCopyDxXd(((struct descriptor_conglom *)pd)->qualifiers, out_ptr); - break; - case DTYPE_CALL: - case DTYPE_CONDITION: - case DTYPE_DEPENDENCY: - case DTYPE_DISPATCH: - case DTYPE_FUNCTION: { - struct descriptor x = {0, 0, CLASS_S, 0}; - x.length = pd->length; - x.dtype = (char)(pd->length == 1 ? DTYPE_BU : DTYPE_WU); - x.pointer = pd->pointer; - status = MdsCopyDxXd(&x, out_ptr); - break; - } - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (pd->dtype) + { + case DTYPE_CONGLOM: + status = + MdsCopyDxXd(((struct descriptor_conglom *)pd)->qualifiers, out_ptr); + break; + case DTYPE_CALL: + case DTYPE_CONDITION: + case DTYPE_DEPENDENCY: + case DTYPE_DISPATCH: + case DTYPE_FUNCTION: + { + struct descriptor x = {0, 0, CLASS_S, 0}; + x.length = pd->length; + x.dtype = (char)(pd->length == 1 ? DTYPE_BU : DTYPE_WU); + x.pointer = pd->pointer; + status = MdsCopyDxXd(&x, out_ptr); + break; + } + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1090,24 +1128,25 @@ int Tdi1QualifiersOf(opcode_t opcode __attribute__((unused)), */ int Tdi1RawOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_SIGNAL, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_SIGNAL: - status = - MdsCopyDxXd(((struct descriptor_signal *)tmp.pointer)->raw, out_ptr); - break; - default: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_SIGNAL: + status = + MdsCopyDxXd(((struct descriptor_signal *)tmp.pointer)->raw, out_ptr); + break; + default: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1119,27 +1158,28 @@ int Tdi1RawOf(opcode_t opcode __attribute__((unused)), */ int Tdi1RoutineOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_CALL, DTYPE_ROUTINE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_CALL: - status = - MdsCopyDxXd(((struct descriptor_call *)tmp.pointer)->routine, out_ptr); - break; - case DTYPE_ROUTINE: - status = MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->routine, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_CALL: + status = + MdsCopyDxXd(((struct descriptor_call *)tmp.pointer)->routine, out_ptr); + break; + case DTYPE_ROUTINE: + status = MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->routine, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1150,7 +1190,8 @@ int Tdi1RoutineOf(opcode_t opcode __attribute__((unused)), slope_field = SLOPE_OF(slope,[n]) !deprecated! */ int Tdi1SlopeOf(opcode_t opcode __attribute__((unused)), int narg, - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const dtype_t one_val = 1; static const struct descriptor one = {sizeof(unsigned char), DTYPE_BU, @@ -1163,29 +1204,28 @@ int Tdi1SlopeOf(opcode_t opcode __attribute__((unused)), int narg, status = tdi_get_data(omits, list[0], &tmp); if (STATUS_OK && narg > 1) status = TdiGetLong(list[1], &n); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_RANGE: - if (n > 0) - status = TdiBAD_INDEX; - if (((struct descriptor_range *)tmp.pointer)->ndesc < 3) - MdsCopyDxXd(&one, out_ptr); - else - MdsCopyDxXd(((struct descriptor_r *)tmp.pointer)->dscptrs[2], out_ptr); - break; - case DTYPE_SLOPE: - if (3 * n + 1 > ((struct descriptor_r *)tmp.pointer)->ndesc) - status = TdiBAD_INDEX; - if - STATUS_OK - status = MdsCopyDxXd( - ((struct descriptor_slope *)tmp.pointer)->segment[n].slope, out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_RANGE: + if (n > 0) + status = TdiBAD_INDEX; + if (((struct descriptor_range *)tmp.pointer)->ndesc < 3) + MdsCopyDxXd(&one, out_ptr); + else + MdsCopyDxXd(((struct descriptor_r *)tmp.pointer)->dscptrs[2], out_ptr); + break; + case DTYPE_SLOPE: + if (3 * n + 1 > ((struct descriptor_r *)tmp.pointer)->ndesc) + status = TdiBAD_INDEX; + if (STATUS_OK) + status = MdsCopyDxXd( + ((struct descriptor_slope *)tmp.pointer)->segment[n].slope, out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1200,37 +1240,38 @@ int Tdi1SlopeOf(opcode_t opcode __attribute__((unused)), int narg, */ int Tdi1TaskOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; - static const dtype_t omits[] = {DTYPE_ACTION, DTYPE_METHOD, DTYPE_PROCEDURE, + static const dtype_t omits[] = {DTYPE_ACTION, DTYPE_METHOD, DTYPE_PROCEDURE, DTYPE_PROGRAM, DTYPE_ROUTINE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_ACTION: - status = TdiTaskOf(((struct descriptor_action *)tmp.pointer)->task, - out_ptr MDS_END_ARG); - break; - case DTYPE_METHOD: - case DTYPE_PROCEDURE: - case DTYPE_PROGRAM: - case DTYPE_ROUTINE: - case DTYPE_L: - case DTYPE_LU: - case DTYPE_W: - case DTYPE_WU: - case DTYPE_B: - case DTYPE_BU: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_ACTION: + status = TdiTaskOf(((struct descriptor_action *)tmp.pointer)->task, + out_ptr MDS_END_ARG); + break; + case DTYPE_METHOD: + case DTYPE_PROCEDURE: + case DTYPE_PROGRAM: + case DTYPE_ROUTINE: + case DTYPE_L: + case DTYPE_LU: + case DTYPE_W: + case DTYPE_WU: + case DTYPE_B: + case DTYPE_BU: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1244,36 +1285,37 @@ int Tdi1TaskOf(opcode_t opcode __attribute__((unused)), */ int Tdi1TimeoutOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_METHOD, DTYPE_PROCEDURE, DTYPE_PROGRAM, DTYPE_ROUTINE, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_METHOD: - status = MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->time_out, - out_ptr); - break; - case DTYPE_PROCEDURE: - status = MdsCopyDxXd(((struct descriptor_procedure *)tmp.pointer)->time_out, - out_ptr); - break; - case DTYPE_PROGRAM: - status = MdsCopyDxXd(((struct descriptor_program *)tmp.pointer)->time_out, - out_ptr); - break; - case DTYPE_ROUTINE: - status = MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->time_out, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_METHOD: + status = MdsCopyDxXd(((struct descriptor_method *)tmp.pointer)->time_out, + out_ptr); + break; + case DTYPE_PROCEDURE: + status = MdsCopyDxXd(((struct descriptor_procedure *)tmp.pointer)->time_out, + out_ptr); + break; + case DTYPE_PROGRAM: + status = MdsCopyDxXd(((struct descriptor_program *)tmp.pointer)->time_out, + out_ptr); + break; + case DTYPE_ROUTINE: + status = MdsCopyDxXd(((struct descriptor_routine *)tmp.pointer)->time_out, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1286,24 +1328,25 @@ int Tdi1TimeoutOf(opcode_t opcode __attribute__((unused)), */ int Tdi1UnitsOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; static const DESCRIPTOR(none, " "); struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_WITH_UNITS, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_WITH_UNITS: - status = MdsCopyDxXd(((struct descriptor_with_units *)tmp.pointer)->units, - out_ptr); - break; - default: - status = MdsCopyDxXd((struct descriptor *)&none, out_ptr); - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_WITH_UNITS: + status = MdsCopyDxXd(((struct descriptor_with_units *)tmp.pointer)->units, + out_ptr); + break; + default: + status = MdsCopyDxXd((struct descriptor *)&none, out_ptr); + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1314,23 +1357,24 @@ int Tdi1UnitsOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ValidationOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), - struct descriptor *list[], struct descriptor_xd *out_ptr) { + struct descriptor *list[], struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_PARAM, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_PARAM: - status = MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->validation, - out_ptr); - break; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_PARAM: + status = MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->validation, + out_ptr); + break; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1345,7 +1389,8 @@ int Tdi1ValidationOf(opcode_t opcode __attribute__((unused)), */ int Tdi1ValueOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_DIMENSION, @@ -1357,38 +1402,38 @@ int Tdi1ValueOf(opcode_t opcode __attribute__((unused)), 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_DIMENSION: - status = TdiValueOf(((struct descriptor_dimension *)tmp.pointer)->window, - out_ptr MDS_END_ARG); - break; - case DTYPE_PARAM: - status = - MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->value, out_ptr); - break; - case DTYPE_SIGNAL: - status = - MdsCopyDxXd(((struct descriptor_signal *)tmp.pointer)->data, out_ptr); - break; - case DTYPE_WINDOW: - status = MdsCopyDxXd( - ((struct descriptor_window *)tmp.pointer)->value_at_idx0, out_ptr); - break; - case DTYPE_WITH_UNITS: - status = MdsCopyDxXd(((struct descriptor_with_units *)tmp.pointer)->data, - out_ptr); - break; - case DTYPE_OPAQUE: - status = - MdsCopyDxXd(((struct descriptor_opaque *)tmp.pointer)->data, out_ptr); - break; - default: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_DIMENSION: + status = TdiValueOf(((struct descriptor_dimension *)tmp.pointer)->window, + out_ptr MDS_END_ARG); + break; + case DTYPE_PARAM: + status = + MdsCopyDxXd(((struct descriptor_param *)tmp.pointer)->value, out_ptr); + break; + case DTYPE_SIGNAL: + status = + MdsCopyDxXd(((struct descriptor_signal *)tmp.pointer)->data, out_ptr); + break; + case DTYPE_WINDOW: + status = MdsCopyDxXd( + ((struct descriptor_window *)tmp.pointer)->value_at_idx0, out_ptr); + break; + case DTYPE_WITH_UNITS: + status = MdsCopyDxXd(((struct descriptor_with_units *)tmp.pointer)->data, + out_ptr); + break; + case DTYPE_OPAQUE: + status = + MdsCopyDxXd(((struct descriptor_opaque *)tmp.pointer)->data, out_ptr); + break; + default: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + } MdsFree1Dx(&tmp, NULL); return status; } @@ -1399,15 +1444,15 @@ int Tdi1ValueOf(opcode_t opcode __attribute__((unused)), */ int Tdi1WhenOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; status = TdiDispatchOf(list[0], &tmp MDS_END_ARG); - if - STATUS_OK - status = - MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->when, out_ptr); + if (STATUS_OK) + status = + MdsCopyDxXd(((struct descriptor_dispatch *)tmp.pointer)->when, out_ptr); MdsFree1Dx(&tmp, NULL); return status; } @@ -1419,27 +1464,28 @@ int Tdi1WhenOf(opcode_t opcode __attribute__((unused)), */ int Tdi1WindowOf(opcode_t opcode __attribute__((unused)), int narg __attribute__((unused)), struct descriptor *list[], - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ INIT_STATUS; struct descriptor_xd tmp = EMPTY_XD; static const dtype_t omits[] = {DTYPE_DIMENSION, DTYPE_WINDOW, 0}; status = tdi_get_data(omits, list[0], &tmp); - if - STATUS_OK - switch (tmp.pointer->dtype) { - case DTYPE_DIMENSION: - status = MdsCopyDxXd(((struct descriptor_dimension *)tmp.pointer)->window, - out_ptr); - break; - case DTYPE_WINDOW: - MdsFree1Dx(out_ptr, NULL); - *out_ptr = tmp; - return status; - default: - status = TdiINVDTYDSC; - break; - } + if (STATUS_OK) + switch (tmp.pointer->dtype) + { + case DTYPE_DIMENSION: + status = MdsCopyDxXd(((struct descriptor_dimension *)tmp.pointer)->window, + out_ptr); + break; + case DTYPE_WINDOW: + MdsFree1Dx(out_ptr, NULL); + *out_ptr = tmp; + return status; + default: + status = TdiINVDTYDSC; + break; + } MdsFree1Dx(&tmp, NULL); return status; } diff --git a/tdishr/TdiYaccSubs.c b/tdishr/TdiYaccSubs.c index 4cf6ebeef0..d6048e0a6c 100644 --- a/tdishr/TdiYaccSubs.c +++ b/tdishr/TdiYaccSubs.c @@ -43,8 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #endif @@ -63,7 +63,8 @@ int tdi_yacc_RESOLVE(); $nnn is nnn-th argument. $0 is then the compile string itself. */ -int tdi_yacc_ARG(struct marker *mark_ptr, TDITHREADSTATIC_ARG) { +int tdi_yacc_ARG(struct marker *mark_ptr, TDITHREADSTATIC_ARG) +{ INIT_STATUS; mdsdsc_t *ptr; mdsdsc_xd_t junk = EMPTY_XD; @@ -72,7 +73,8 @@ int tdi_yacc_ARG(struct marker *mark_ptr, TDITHREADSTATIC_ARG) { if (len == 1) ++TDI_REFZONE.l_iarg; - else { + else + { TDI_REFZONE.l_iarg = 0; c_ptr = mark_ptr->rptr->pointer; for (; --len > 0;) @@ -88,9 +90,8 @@ int tdi_yacc_ARG(struct marker *mark_ptr, TDITHREADSTATIC_ARG) { *******************************/ status = MdsCopyDxXdZ(ptr, &junk, &TDI_REFZONE.l_zone, NULL, NULL, NULL, NULL); - if - STATUS_OK - mark_ptr->rptr = (mdsdsc_r_t *)junk.pointer; + if (STATUS_OK) + mark_ptr->rptr = (mdsdsc_r_t *)junk.pointer; return status; } @@ -103,7 +104,8 @@ static const DESCRIPTOR_FUNCTION_0(EMPTY_FUN, 0); int tdi_yacc_BUILD(int ndesc, int nused, opcode_t opcode, struct marker *out, struct marker *arg1, struct marker *arg2, struct marker *arg3, struct marker *arg4, - TDITHREADSTATIC_ARG) { + TDITHREADSTATIC_ARG) +{ mds_function_t *fun; int dsc_size = sizeof(mds_function_t) + sizeof(mdsdsc_t *) * (ndesc - 1); unsigned int vm_size = dsc_size + sizeof(unsigned short); @@ -118,7 +120,8 @@ int tdi_yacc_BUILD(int ndesc, int nused, opcode_t opcode, struct marker *out, fun->pointer = (opcode_t *)((char *)fun + dsc_size); *fun->pointer = opcode; fun->ndesc = (unsigned char)nused; - switch (nused) { + switch (nused) + { default: return TdiEXTRA_ARG; case 4: @@ -158,8 +161,10 @@ int tdi_yacc_BUILD(int ndesc, int nused, opcode_t opcode, struct marker *out, WARNING the pointer is changed. We do not free small stuff because we will throw it all away later. */ -int tdi_yacc_IMMEDIATE(mdsdsc_xd_t **dsc_ptr_ptr, TDITHREADSTATIC_ARG) { - if (TDI_STACK_IDX >= TDI_STACK_SIZE - 1) { +int tdi_yacc_IMMEDIATE(mdsdsc_xd_t **dsc_ptr_ptr, TDITHREADSTATIC_ARG) +{ + if (TDI_STACK_IDX >= TDI_STACK_SIZE - 1) + { fprintf(stderr, "Error: Too many recursive calls using '`': only %d supported\n", TDI_STACK_SIZE); @@ -182,13 +187,11 @@ int tdi_yacc_IMMEDIATE(mdsdsc_xd_t **dsc_ptr_ptr, TDITHREADSTATIC_ARG) { /******************* Copy it to our zone. *******************/ - if - STATUS_OK - status = MdsCopyDxXdZ(xd.pointer, &junk, &TDI_REFZONE.l_zone, NULL, NULL, - NULL, NULL); - if - STATUS_OK - *dsc_ptr_ptr = (mdsdsc_xd_t *)junk.pointer; + if (STATUS_OK) + status = MdsCopyDxXdZ(xd.pointer, &junk, &TDI_REFZONE.l_zone, NULL, NULL, + NULL, NULL); + if (STATUS_OK) + *dsc_ptr_ptr = (mdsdsc_xd_t *)junk.pointer; MdsFree1Dx(&xd, NULL); return status; } @@ -221,7 +224,8 @@ int tdi_yacc_IMMEDIATE(mdsdsc_xd_t **dsc_ptr_ptr, TDITHREADSTATIC_ARG) { What about DTYPE_MISSING? It is generated only by evaluation. */ -int tdi_yacc_RESOLVE(mds_function_t **out_ptr_ptr, TDITHREADSTATIC_ARG) { +int tdi_yacc_RESOLVE(mds_function_t **out_ptr_ptr, TDITHREADSTATIC_ARG) +{ mds_function_t *out_ptr = *out_ptr_ptr; struct TdiFunctionStruct *this_ptr; if (out_ptr == 0 || out_ptr->dtype != DTYPE_FUNCTION) @@ -240,15 +244,19 @@ int tdi_yacc_RESOLVE(mds_function_t **out_ptr_ptr, TDITHREADSTATIC_ARG) { Don't expand scalars. ******************/ if (this_ptr->f1 != Tdi1Build) - for (j = ndesc; --j >= 0;) { + for (j = ndesc; --j >= 0;) + { mdsdsc_t *tst = out_ptr->arguments[j]; while (tst != 0 && tst->dtype == DTYPE_DSC) tst = (mdsdsc_t *)tst->pointer; - if (opcode == OPC_SET_RANGE) { /*Set_Range(value,range,...,array) */ - if (j != ndesc - 1) { + if (opcode == OPC_SET_RANGE) + { /*Set_Range(value,range,...,array) */ + if (j != ndesc - 1) + { if (tst == 0 || tst->dtype == DTYPE_RANGE) continue; - } else if (tst && tst->class != CLASS_A) + } + else if (tst && tst->class != CLASS_A) return MDSplusSUCCESS; /*decide at runtime */ } if (tst && tst->dtype >= TdiCAT_MAX) diff --git a/tdishr/cvtdef.h b/tdishr/cvtdef.h index 8da17d6df7..6d5bcee803 100644 --- a/tdishr/cvtdef.h +++ b/tdishr/cvtdef.h @@ -11,7 +11,8 @@ #endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #define __unknown_params ... #else #define __unknown_params @@ -36,9 +37,9 @@ extern "C" { #define CvtCRAY 8 /* Cray Floating point data */ #define CvtIEEE_X 9 /* IEEE X Floating point data */ -extern unsigned long CvtConvertFloat(void *input_v, unsigned long input_t, - void *output_v, unsigned long output_t, - ...); + extern unsigned long CvtConvertFloat(void *input_v, unsigned long input_t, + void *output_v, unsigned long output_t, + ...); #ifdef __cplusplus } diff --git a/tdishr/roprand.h b/tdishr/roprand.h index 110b3429cb..db26c0f094 100644 --- a/tdishr/roprand.h +++ b/tdishr/roprand.h @@ -10,13 +10,13 @@ #define t_float_exp(val) (((*(int64_t *)val) >> 52) & 0x7ff) #define IsRoprandT(val) (t_float_exp(val) == 2047) -#define IsRoprand(dtype, val) \ - ((dtype == DTYPE_F) \ - ? IsRoprandF(val) \ - : ((dtype == DTYPE_D) \ - ? IsRoprandD(val) \ - : ((dtype == DTYPE_FS) \ - ? IsRoprandS(val) \ - : ((dtype == DTYPE_G) \ - ? IsRoprandG(val) \ +#define IsRoprand(dtype, val) \ + ((dtype == DTYPE_F) \ + ? IsRoprandF(val) \ + : ((dtype == DTYPE_D) \ + ? IsRoprandD(val) \ + : ((dtype == DTYPE_FS) \ + ? IsRoprandS(val) \ + : ((dtype == DTYPE_G) \ + ? IsRoprandG(val) \ : ((dtype == DTYPE_FT) ? IsRoprandT(val) : 1))))) diff --git a/tdishr/tdinelements.h b/tdishr/tdinelements.h index 6a9696bf3b..1218b92f7b 100644 --- a/tdishr/tdinelements.h +++ b/tdishr/tdinelements.h @@ -1,3 +1,3 @@ extern int tdi_n_elements(); -#define N_ELEMENTS(dsc_ptr, count) \ +#define N_ELEMENTS(dsc_ptr, count) \ count = tdi_n_elements((const mdsdsc_t *const)(dsc_ptr), &status) diff --git a/tdishr/tdirefcat.h b/tdishr/tdirefcat.h index bebfff8c7e..62a4ad5cad 100644 --- a/tdishr/tdirefcat.h +++ b/tdishr/tdirefcat.h @@ -4,6 +4,7 @@ Ken Klare, LANL CTR-7 (c)1989,1990 */ #include + #define TdiCAT_COMPLEX 0x1000 #define TdiCAT_WIDE_EXP 0x0800 #define TdiCAT_FLOAT 0x0700 @@ -16,21 +17,23 @@ #define TdiCAT_D (0x8000 | TdiCAT_FLOAT | 7) #define TdiCAT_FC (TdiCAT_COMPLEX | TdiCAT_F) typedef uint16_t tdicat_t; -struct TdiCatStruct { +struct TdiCatStruct +{ tdicat_t in_cat; dtype_t in_dtype; tdicat_t out_cat; dtype_t out_dtype; length_t digits; }; -struct TdiCatStruct_table { +struct TdiCatStruct_table +{ char *name; /*text for decompile */ tdicat_t cat; /*category code */ length_t length; /*size in bytes */ unsigned char digits; /*size of text conversion */ char *fname; /*exponent name for floating decompile */ }; -#include + extern const tdicat_t TdiCAT_MAX; extern const struct TdiCatStruct_table TdiREF_CAT[]; diff --git a/tdishr/tdireffunction.h b/tdishr/tdireffunction.h index 1c081ef387..3446255eb5 100644 --- a/tdishr/tdireffunction.h +++ b/tdishr/tdireffunction.h @@ -8,7 +8,8 @@ #include #include -struct TdiFunctionStruct { +struct TdiFunctionStruct +{ char *name; /*string to compile/decompile */ int (*f1)(); /*routine to check arguments */ int (*f2)(); /*routine to set conversions */ diff --git a/tdishr/tdirefstandard.h b/tdishr/tdirefstandard.h index 6e9c2955c2..8f8d5bc858 100644 --- a/tdishr/tdirefstandard.h +++ b/tdishr/tdirefstandard.h @@ -6,13 +6,12 @@ Ken Klare, LANL P-4 (c)1989,1991 */ #include -#include -static struct descriptor_xd const EMPTY_XD = {0, DTYPE_DSC, CLASS_XD, 0, 0}; - #include -/*#include */ -#define TdiRefStandard(name) \ - int name(int opcode, int narg, struct descriptor *list[], \ - struct descriptor_xd *out_ptr) { \ +static struct descriptor_xd const EMPTY_XD = {0, DTYPE_DSC, CLASS_XD, 0, 0}; + +#define TdiRefStandard(name) \ + int name(int opcode, int narg, struct descriptor *list[], \ + struct descriptor_xd *out_ptr) \ + { \ int status = 1; diff --git a/tdishr/tdirefzone.h b/tdishr/tdirefzone.h index 874791bccf..da7f97dbad 100644 --- a/tdishr/tdirefzone.h +++ b/tdishr/tdirefzone.h @@ -6,7 +6,8 @@ Ken Klare, LANL CTR-7 (c)1989,1990 */ -typedef struct { +typedef struct +{ char *a_begin; /*beginning of text */ char *a_cur; /*current character */ char *a_end; /*end of buffer + 1 */ @@ -23,7 +24,8 @@ typedef struct { #include "tdithreadstatic.h" #include -struct marker { +struct marker +{ struct descriptor_r *rptr; short builtin; unsigned short w_ok; @@ -40,45 +42,46 @@ Definitions needed by Lex and friends. /*-------------------------------------------------- Definitions needed by Lex and Yacc. --------------------------------------------------*/ -#define tdiyyerror(s) \ - do { \ - TDI_REFZONE.l_ok = tdiyyval.mark.w_ok; \ - return MDSplusERROR; \ +#define tdiyyerror(s) \ + do \ + { \ + TDI_REFZONE.l_ok = tdiyyval.mark.w_ok; \ + return MDSplusERROR; \ } while (0) -#define MAKE_S(dtype_in, bytes, out) \ - { \ - unsigned int dsc_size = sizeof(struct descriptor_s); \ - unsigned int vm_size = (dsc_size + (bytes)); \ - LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ - ((struct descriptor *)(out))->length = bytes; \ - ((struct descriptor *)(out))->dtype = dtype_in; \ - ((struct descriptor *)(out))->class = CLASS_S; \ - ((struct descriptor *)(out))->pointer = (char *)(out) + dsc_size; \ +#define MAKE_S(dtype_in, bytes, out) \ + { \ + unsigned int dsc_size = sizeof(struct descriptor_s); \ + unsigned int vm_size = (dsc_size + (bytes)); \ + LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ + ((struct descriptor *)(out))->length = bytes; \ + ((struct descriptor *)(out))->dtype = dtype_in; \ + ((struct descriptor *)(out))->class = CLASS_S; \ + ((struct descriptor *)(out))->pointer = (char *)(out) + dsc_size; \ } -#define MAKE_XD(dtype_in, bytes, out) \ - { \ - unsigned int dsc_size = sizeof(struct descriptor_xd); \ - unsigned int vm_size = dsc_size + (bytes); \ - LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ - ((struct descriptor_xd *)(out))->l_length = bytes; \ - ((struct descriptor_xd *)(out))->length = 0; \ - ((struct descriptor_xd *)(out))->dtype = dtype_in; \ - ((struct descriptor_xd *)(out))->class = CLASS_XD; \ - ((struct descriptor_xd *)(out))->pointer = \ - (struct descriptor *)((char *)(out) + dsc_size); \ +#define MAKE_XD(dtype_in, bytes, out) \ + { \ + unsigned int dsc_size = sizeof(struct descriptor_xd); \ + unsigned int vm_size = dsc_size + (bytes); \ + LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ + ((struct descriptor_xd *)(out))->l_length = bytes; \ + ((struct descriptor_xd *)(out))->length = 0; \ + ((struct descriptor_xd *)(out))->dtype = dtype_in; \ + ((struct descriptor_xd *)(out))->class = CLASS_XD; \ + ((struct descriptor_xd *)(out))->pointer = \ + (struct descriptor *)((char *)(out) + dsc_size); \ } -#define MAKE_R(ndesc, dtype_in, bytes, out) \ - { \ - unsigned int dsc_size = sizeof($RECORD(ndesc)); \ - unsigned int vm_size = dsc_size + (bytes); \ - LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ - ((struct descriptor *)(out))->length = bytes; \ - ((struct descriptor *)(out))->dtype = dtype_in; \ - ((struct descriptor *)(out))->class = CLASS_R; \ - ((struct descriptor *)(out))->pointer = (char *)(out) + dsc_size; \ +#define MAKE_R(ndesc, dtype_in, bytes, out) \ + { \ + unsigned int dsc_size = sizeof($RECORD(ndesc)); \ + unsigned int vm_size = dsc_size + (bytes); \ + LibGetVm(&vm_size, (void *)&(out), (void *)&TDI_REFZONE.l_zone); \ + ((struct descriptor *)(out))->length = bytes; \ + ((struct descriptor *)(out))->dtype = dtype_in; \ + ((struct descriptor *)(out))->class = CLASS_R; \ + ((struct descriptor *)(out))->pointer = (char *)(out) + dsc_size; \ } /********************************************** diff --git a/tdishr/tdithreadstatic.h b/tdishr/tdithreadstatic.h index 368a03ae59..08f0a7a13b 100644 --- a/tdishr/tdithreadstatic.h +++ b/tdishr/tdithreadstatic.h @@ -14,10 +14,12 @@ typedef union { int16_t cnt[4]; int64_t all; } balance_t; -typedef struct { +typedef struct +{ void *scanner; int stack_idx; - struct stack { + struct stack + { void *buffer; TdiRefZone_t refzone; // TdiCompile int compile_rec; // TdiCompile @@ -26,7 +28,8 @@ typedef struct { uint16_t decompile_max; // TdiDecompile balance_t balance; } stack[TDI_STACK_SIZE]; - struct { + struct + { void *head; void *head_zone; void *data_zone; diff --git a/tdishr/testing/build_test.c b/tdishr/testing/build_test.c index af5aedfc1a..afe42d731d 100644 --- a/tdishr/testing/build_test.c +++ b/tdishr/testing/build_test.c @@ -27,7 +27,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing.h" int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(build test); TEST1(1); END_TESTING; diff --git a/tdishr/yylex/TdiLex.l b/tdishr/yylex/TdiLex.l index 1d6a1680bb..6e6df859bf 100644 --- a/tdishr/yylex/TdiLex.l +++ b/tdishr/yylex/TdiLex.l @@ -349,7 +349,7 @@ static int lex_float(LEX_ARGS) { status = TdiEXTRANEOUS; yylval_param->mark.builtin = -1; - if STATUS_OK + if (STATUS_OK) return LEX_VALUE; TDI_REFZONE.l_status = status; return LEX_ERROR; @@ -645,7 +645,7 @@ static int lex_int(LEX_ARGS) { if (*qptr != qtst) status = TdiTOO_BIG; - if STATUS_OK { + if (STATUS_OK) { #ifdef WORDS_BIGENDIAN int i; char *ptr = yylval_param->mark.rptr->pointer; @@ -674,7 +674,7 @@ int tdi_lex_path(int len, char* str, struct marker *mark_ptr, TDITHREADSTATIC_AR if (TDI_REFZONE.l_rel_path) { MAKE_S(DTYPE_PATH, (unsigned short)len, mark_ptr->rptr); memcpy((char *)mark_ptr->rptr->pointer, str, len); - } else if IS_OK(TreeFindNode((char *)str_l, &nid)) { + } else if (IS_OK(TreeFindNode((char *)str_l, &nid))) { MAKE_S(DTYPE_NID, (unsigned short)sizeof(nid), mark_ptr->rptr); *(int *)mark_ptr->rptr->pointer = nid; } else { diff --git a/tdishr/yylex/TdiYacc.y b/tdishr/yylex/TdiYacc.y index febf334a65..78080b4239 100644 --- a/tdishr/yylex/TdiYacc.y +++ b/tdishr/yylex/TdiYacc.y @@ -116,7 +116,7 @@ int yydebug = YYDEBUG; //" #define YYMAXDEPTH 250 -#define __RUN(method) do{if IS_NOT_OK(TDI_REFZONE.l_status = method) {yyerror(TDITHREADSTATIC_VAR,"method failed"); return YY_ASIS;} else TDI_REFZONE.l_ok = TDI_REFZONE.a_cur - TDI_REFZONE.a_begin;}while(0) +#define __RUN(method) do{if (IS_NOT_OK(TDI_REFZONE.l_status = method)) {yyerror(TDITHREADSTATIC_VAR,"method failed"); return YY_ASIS;} else TDI_REFZONE.l_ok = TDI_REFZONE.a_cur - TDI_REFZONE.a_begin;}while(0) #define _RESOLVE(arg) __RUN(tdi_yacc_RESOLVE(&arg.rptr, TDITHREADSTATIC_VAR)) diff --git a/tdishr/yylex/outfiles b/tdishr/yylex/outfiles deleted file mode 100644 index 1faac10e0e..0000000000 --- a/tdishr/yylex/outfiles +++ /dev/null @@ -1 +0,0 @@ -tdishr/TdiLex.c diff --git a/tditest/tditest.c b/tditest/tditest.c index da3ba5bfc6..d04803aa47 100644 --- a/tditest/tditest.c +++ b/tditest/tditest.c @@ -50,13 +50,15 @@ const char *builtins[] = { #undef COM static char **character_names = NULL; -char *character_name_generator(const char *text, int state) { +char *character_name_generator(const char *text, int state) +{ // default to filepath completion if we are doing strings #ifndef _MACOSX if (rl_completion_quote_character) return NULL; #endif - if (!character_names) { + if (!character_names) + { void *ctx = NULL; uint16_t i; char req[] = "MDS_PATH:*.*"; @@ -66,7 +68,8 @@ char *character_name_generator(const char *text, int state) { character_names = malloc(sizeof(void *) * maxlen); memcpy(character_names, builtins, sizeof(builtins)); int status; - for (;;) { + for (;;) + { status = LibFindFileRecurseCaseBlind(&rqd, &ans, &ctx); if (STATUS_NOT_OK || !ctx || ans.length < 4) break; @@ -89,7 +92,8 @@ char *character_name_generator(const char *text, int state) { else continue; p[mlen] = '\0'; - if (curlen >= maxlen) { + if (curlen >= maxlen) + { maxlen *= 2; character_names = realloc(character_names, sizeof(void *) * maxlen); } @@ -102,13 +106,15 @@ char *character_name_generator(const char *text, int state) { } static int list_index, len; char *name; - if (!state) { + if (!state) + { list_index = 0; len = strlen(text); } // use case sensitivity to distinguish between builtins and tdi.funs while ((name = character_names[list_index++])) - if (strncmp(name, text, len) == 0) { + if (strncmp(name, text, len) == 0) + { if (name[0] == '$') // constants like $PI return strdup(name); size_t len = strlen(name); @@ -122,25 +128,32 @@ char *character_name_generator(const char *text, int state) { char **character_name_completion(const char *text, int start __attribute__((__unused__)), - int end __attribute__((__unused__))) { + int end __attribute__((__unused__))) +{ #ifndef _MACOSX rl_attempted_completion_over = !rl_completion_quote_character; #endif return rl_completion_matches(text, character_name_generator); } -static void keyboard_interrupt(int signo __attribute__((__unused__))) { +static void keyboard_interrupt(int signo __attribute__((__unused__))) +{ fprintf(stderr, "KeyboardInterrupt\n"); } #ifdef _WIN32 -static inline void set_readline_handlers() { signal(SIGINT, SIG_IGN); } -static inline void set_execute_handlers() { +static inline void set_readline_handlers() +{ + signal(SIGINT, SIG_IGN); +} +static inline void set_execute_handlers() +{ signal(SIGINT, keyboard_interrupt); } #else // _WIN32 static struct sigaction act; #ifdef HAVE_RL_SET_SIGNALS -static inline void set_readline_handlers() { +static inline void set_readline_handlers() +{ rl_catch_signals = 1; rl_set_signals(); } @@ -149,7 +162,8 @@ static inline void set_execute_handlers() { rl_clear_signals(); } #ifdef _MACOSX #define _rl_sigint SIG_IGN #else // _MACOSX -static void _rl_sigint(int signo __attribute__((__unused__))) { +static void _rl_sigint(int signo __attribute__((__unused__))) +{ // reset readline line buffer and state before printing new prompt rl_free_line_state(); rl_cleanup_after_signal(); @@ -159,63 +173,79 @@ static void _rl_sigint(int signo __attribute__((__unused__))) { printf("\n"); } #endif // !_MACOSX -static inline void set_readline_handlers() { +static inline void set_readline_handlers() +{ act.sa_handler = _rl_sigint; sigaction(SIGINT, &act, NULL); } -static inline void set_execute_handlers() { +static inline void set_execute_handlers() +{ act.sa_handler = keyboard_interrupt; sigaction(SIGINT, &act, NULL); } #endif // !HAVE_RL_SET_SIGNALS #endif // !_WIN32 -static char *getExpression(FILE *f_in) { +static char *getExpression(FILE *f_in) +{ char buf[MAXEXPR] = {0}; char *ans = NULL; size_t alen = 0; int append; if (f_in == NULL) set_readline_handlers(); - do { + do + { char *next; size_t nlen; - if (f_in == NULL) { + if (f_in == NULL) + { next = readline(""); if (next) nlen = strlen(next); else nlen = 0; - } else { + } + else + { next = fgets(buf, MAXEXPR, f_in); - if (next) { + if (next) + { nlen = strlen(next); if (next[nlen - 1] == '\n') next[--nlen] = '\0'; next = strdup(next); - } else + } + else nlen = 0; } - if (nlen <= 0) { - if (ans) { + if (nlen <= 0) + { + if (ans) + { free(next); next = ans; - } else + } + else ans = next; break; } append = next[nlen - 1] == '\\'; if (append) next[--nlen] = '\0'; - if (ans) { - if (nlen > 0) { + if (ans) + { + if (nlen > 0) + { ans = realloc(ans, alen + nlen + 1); memcpy(ans + alen, next, nlen + 1); alen = alen + nlen; } free(next); next = ans; - } else { + } + else + { ans = next; alen = nlen; } @@ -223,7 +253,8 @@ static char *getExpression(FILE *f_in) { return ans; } -static void print_help(int error) { +static void print_help(int error) +{ FILE *file = error ? stderr : stdout; fprintf( file, @@ -237,14 +268,17 @@ static void print_help(int error) { } static inline char *get_arg(const int argc, char **const args, const int inext, - const char *const arg) { - if (argc <= inext) { + const char *const arg) +{ + if (argc <= inext) + { fprintf(stderr, "Error %s requires a value but none given\n", arg); print_help(2); } return args[inext]; } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ FILE *f_in = NULL; FILE *f_out = NULL; int status = 1; @@ -261,9 +295,11 @@ int main(int argc, char **argv) { int quiet = FALSE; int verbose = FALSE; int i; - for (i = 1; argc > i; i++) { + for (i = 1; argc > i; i++) + { const char *arg = argv[i]; - if (*arg == '-') { + if (*arg == '-') + { arg++; if (*arg == '-') // --long word { @@ -278,14 +314,18 @@ int main(int argc, char **argv) { verbose = TRUE; else if (strcmp(argv[i], "server") == 0) server = get_arg(argc, argv, ++i, arg - 2); - else { + else + { fprintf(stderr, "Unknown parameter --%s:\n", arg); print_help(1); } - } else { + } + else + { for (; *arg; arg++) // -short letter { - switch (*arg) { + switch (*arg) + { case 'h': print_help(0); break; @@ -301,14 +341,17 @@ int main(int argc, char **argv) { case 's': server = get_arg(argc, argv, ++i, "-s"); break; - default: { + default: + { fprintf(stderr, "Unknown parameter -%c:\n", *arg); print_help(1); } } } } - } else { // input + } + else + { // input script = argv[i]; break; } @@ -317,49 +360,59 @@ int main(int argc, char **argv) { output_unit.length = sizeof(void *); output_unit.dtype = DTYPE_POINTER; output_unit.pointer = (char *)&f_out; - if (output) { + if (output) + { f_out = fopen(output, "w"); - if (!f_out) { + if (!f_out) + { printf("Error opening log file '%s'\n", output); exit(1); } if (verbose) fprintf(stderr, "Writing output to file '%s'\n", output); - } else + } + else f_out = stdout; - if (server) { + if (server) + { DESCRIPTOR_FROM_CSTRING(server_dsc, server); set_execute_handlers(); status = TdiExecute((mdsdsc_t *)&mdsconnect, (mdsdsc_t *)&server_dsc, &ans MDS_END_ARG); - if - STATUS_OK status = *(int *)ans.pointer->pointer; - if - STATUS_NOT_OK { - fprintf(stderr, "Error connecting to server '%s'\n", server); - exit(1); - } + if (STATUS_OK) + status = *(int *)ans.pointer->pointer; + if (STATUS_NOT_OK) + { + fprintf(stderr, "Error connecting to server '%s'\n", server); + exit(1); + } if (verbose) fprintf(stderr, "Connected to server '%s'\n", server); set_readline_handlers(); strcpy(error_out_c, "WRITE($,MDSVALUE('DEBUG(13)'))"); strcpy(clear_errors_c, "WRITE($,$),MDSVALUE('DEBUG(4)')"); - } else { + } + else + { strcpy(error_out_c, "WRITE($,DEBUG(13))"); strcpy(clear_errors_c, "WRITE($,DECOMPILE($)),DEBUG(4)"); } DESCRIPTOR_FROM_CSTRING(error_out, error_out_c); DESCRIPTOR_FROM_CSTRING(clear_errors, clear_errors_c); - if (script) { + if (script) + { f_in = fopen(script, "r"); - if (!f_in) { + if (!f_in) + { if (verbose) printf("Error opening input file '%s'\n", script); exit(1); } if (verbose) fprintf(stderr, "Executing script '%s'\n", script); - } else { + } + else + { #ifdef _WIN32 char *home = getenv("USERPROFILE"); #define S_SEP_S "%s\\%s" @@ -367,7 +420,8 @@ int main(int argc, char **argv) { char *home = getenv("HOME"); #define S_SEP_S "%s/%s" #endif - if (home) { + if (home) + { char *history = ".tditest"; history_file = malloc(strlen(history) + strlen(home) + 2); sprintf(history_file, S_SEP_S, home, history); @@ -385,13 +439,15 @@ int main(int argc, char **argv) { act.sa_handler = keyboard_interrupt; sigaction(SIGINT, &act, NULL); #endif - if (argc > i && !server) { + if (argc > i && !server) + { const int i0 = i; char buf[16]; set_execute_handlers(); mdsdsc_t argdsc = {0, DTYPE_T, CLASS_S, 0}; expr_dsc.pointer = buf; - for (; argc > i; i++) { + for (; argc > i; i++) + { expr_dsc.length = sprintf(expr_dsc.pointer, "_$%d=$;*", i - i0); argdsc.pointer = argv[i]; argdsc.length = strlen(argv[i]); @@ -400,13 +456,17 @@ int main(int argc, char **argv) { } set_readline_handlers(); while ((buf = command = getExpression(f_in)) && - strcasecmp(command, "exit") != 0 && strcasecmp(command, "quit") != 0) { + strcasecmp(command, "exit") != 0 && strcasecmp(command, "quit") != 0) + { int comment = command[0] == '#'; - if (!comment) { - if (f_in) { + if (!comment) + { + if (f_in) + { if (command[0] == '@') command++; - else if (!quiet) { + else if (!quiet) + { fprintf(f_out, "%s\n", command); fflush(f_out); } @@ -414,19 +474,22 @@ int main(int argc, char **argv) { set_execute_handlers(); expr_dsc.length = strlen(command); expr_dsc.pointer = command; - if (server) { + if (server) + { status = TdiExecute((mdsdsc_t *)&mdsvalue, (mdsdsc_t *)&expr_dsc, &ans MDS_END_ARG); if (STATUS_OK && !ans.pointer) status = 0; - } else + } + else status = TdiExecute((mdsdsc_t *)&expr_dsc, &ans MDS_END_ARG); - if (!quiet) { - if - STATUS_OK - TdiExecute((mdsdsc_t *)&clear_errors, &output_unit, &ans, - &ans MDS_END_ARG); - else TdiExecute((mdsdsc_t *)&error_out, &output_unit, &ans MDS_END_ARG); + if (!quiet) + { + if (STATUS_OK) + TdiExecute((mdsdsc_t *)&clear_errors, &output_unit, &ans, + &ans MDS_END_ARG); + else + TdiExecute((mdsdsc_t *)&error_out, &output_unit, &ans MDS_END_ARG); fflush(f_out); } set_readline_handlers(); @@ -435,7 +498,8 @@ int main(int argc, char **argv) { free(buf); } MdsFree1Dx(&ans, NULL); - if (history_file) { + if (history_file) + { if (verbose) fprintf(stderr, "Writing to history file '%s'\n", history_file); write_history(history_file); diff --git a/testing/backends/check/build_test.c b/testing/backends/check/build_test.c index a0752625ce..77f346fb96 100644 --- a/testing/backends/check/build_test.c +++ b/testing/backends/check/build_test.c @@ -31,7 +31,8 @@ void eprintf(const char *fmt, const char *file, int line, ...) CK_ATTRIBUTE_NORETURN; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ setup_messaging(); diff --git a/testing/backends/check/check.c b/testing/backends/check/check.c index 80a68715fc..947a9008ac 100644 --- a/testing/backends/check/check.c +++ b/testing/backends/check/check.c @@ -80,7 +80,8 @@ static void tr_init(TestResult *tr); static void suite_free(Suite *s); static void tcase_free(TCase *tc); -Suite *suite_create(const char *name) { +Suite *suite_create(const char *name) +{ Suite *s; s = (Suite *)emalloc(sizeof(Suite)); /* freed in suite_free */ @@ -92,7 +93,8 @@ Suite *suite_create(const char *name) { return s; } -int suite_tcase(Suite *s, const char *tcname) { +int suite_tcase(Suite *s, const char *tcname) +{ List *l; TCase *tc; @@ -100,7 +102,8 @@ int suite_tcase(Suite *s, const char *tcname) { return 0; l = s->tclst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { tc = (TCase *)check_list_val(l); if (strcmp(tcname, tc->name) == 0) return 1; @@ -109,20 +112,23 @@ int suite_tcase(Suite *s, const char *tcname) { return 0; } -static void suite_free(Suite *s) { +static void suite_free(Suite *s) +{ List *l; if (s == NULL) return; l = s->tclst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { tcase_free((TCase *)check_list_val(l)); } check_list_free(s->tclst); free(s); } -TCase *tcase_create(const char *name) { +TCase *tcase_create(const char *name) +{ char *env; double timeout_sec = DEFAULT_TIMEOUT; @@ -134,21 +140,25 @@ TCase *tcase_create(const char *name) { tc->name = name; env = getenv("CK_DEFAULT_TIMEOUT"); - if (env != NULL) { + if (env != NULL) + { char *endptr = NULL; double tmp = strtod(env, &endptr); - if (tmp >= 0 && endptr != env && (*endptr) == '\0') { + if (tmp >= 0 && endptr != env && (*endptr) == '\0') + { timeout_sec = tmp; } } env = getenv("CK_TIMEOUT_MULTIPLIER"); - if (env != NULL) { + if (env != NULL) + { char *endptr = NULL; double tmp = strtod(env, &endptr); - if (tmp >= 0 && endptr != env && (*endptr) == '\0') { + if (tmp >= 0 && endptr != env && (*endptr) == '\0') + { timeout_sec = timeout_sec * tmp; } } @@ -166,7 +176,8 @@ TCase *tcase_create(const char *name) { return tc; } -static void tcase_free(TCase *tc) { +static void tcase_free(TCase *tc) +{ check_list_apply(tc->tflst, free); check_list_apply(tc->unch_sflst, free); check_list_apply(tc->ch_sflst, free); @@ -181,14 +192,16 @@ static void tcase_free(TCase *tc) { free(tc); } -void suite_add_tcase(Suite *s, TCase *tc) { +void suite_add_tcase(Suite *s, TCase *tc) +{ if (s == NULL || tc == NULL) return; check_list_add_end(s->tclst, tc); } void _tcase_add_test(TCase *tc, TFun fn, const char *name, int _signal, - int allowed_exit_value, int start, int end) { + int allowed_exit_value, int start, int end) +{ TF *tf; if (tc == NULL || fn == NULL || name == NULL) @@ -205,7 +218,8 @@ void _tcase_add_test(TCase *tc, TFun fn, const char *name, int _signal, check_list_add_end(tc->tflst, tf); } -static Fixture *fixture_create(SFun fun, int ischecked) { +static Fixture *fixture_create(SFun fun, int ischecked) +{ Fixture *f; f = (Fixture *)emalloc(sizeof(Fixture)); @@ -215,17 +229,21 @@ static Fixture *fixture_create(SFun fun, int ischecked) { return f; } -void tcase_add_unchecked_fixture(TCase *tc, SFun setup, SFun teardown) { +void tcase_add_unchecked_fixture(TCase *tc, SFun setup, SFun teardown) +{ tcase_add_fixture(tc, setup, teardown, 0); } -void tcase_add_checked_fixture(TCase *tc, SFun setup, SFun teardown) { +void tcase_add_checked_fixture(TCase *tc, SFun setup, SFun teardown) +{ tcase_add_fixture(tc, setup, teardown, 1); } static void tcase_add_fixture(TCase *tc, SFun setup, SFun teardown, - int ischecked) { - if (setup) { + int ischecked) +{ + if (setup) + { if (ischecked) check_list_add_end(tc->ch_sflst, fixture_create(setup, ischecked)); else @@ -233,7 +251,8 @@ static void tcase_add_fixture(TCase *tc, SFun setup, SFun teardown, } /* Add teardowns at front so they are run in reverse order. */ - if (teardown) { + if (teardown) + { if (ischecked) check_list_add_front(tc->ch_tflst, fixture_create(teardown, ischecked)); else @@ -241,16 +260,20 @@ static void tcase_add_fixture(TCase *tc, SFun setup, SFun teardown, } } -void tcase_set_timeout(TCase *tc, double timeout) { +void tcase_set_timeout(TCase *tc, double timeout) +{ #if defined(HAVE_FORK) - if (timeout >= 0) { + if (timeout >= 0) + { char *env = getenv("CK_TIMEOUT_MULTIPLIER"); - if (env != NULL) { + if (env != NULL) + { char *endptr = NULL; double tmp = strtod(env, &endptr); - if (tmp >= 0 && endptr != env && (*endptr) == '\0') { + if (tmp >= 0 && endptr != env && (*endptr) == '\0') + { timeout = timeout * tmp; } } @@ -267,14 +290,16 @@ void tcase_set_timeout(TCase *tc, double timeout) { } void tcase_fn_start(const char *fname CK_ATTRIBUTE_UNUSED, const char *file, - int line) { + int line) +{ send_ctx_info(CK_CTX_TEST); send_loc_info(file, line); } void _mark_point(const char *file, int line) { send_loc_info(file, line); } -void _ck_assert_failed(const char *file, int line, const char *expr, ...) { +void _ck_assert_failed(const char *file, int line, const char *expr, ...) +{ const char *msg; va_list ap; char buf[BUFSIZ]; @@ -289,25 +314,32 @@ void _ck_assert_failed(const char *file, int line, const char *expr, ...) { * If a message was passed, format it with vsnprintf. * Otherwise, print the expression as is. */ - if (msg != NULL) { + if (msg != NULL) + { vsnprintf(buf, BUFSIZ, msg, ap); to_send = buf; - } else { + } + else + { to_send = expr; } va_end(ap); send_failure_info(to_send, CK_FAILURE); - if (cur_fork_status() == CK_FORK) { + if (cur_fork_status() == CK_FORK) + { #if defined(HAVE_FORK) && HAVE_FORK == 1 _exit(1); #endif /* HAVE_FORK */ - } else { + } + else + { longjmp(error_jmp_buffer, 1); } } -SRunner *srunner_create(Suite *s) { +SRunner *srunner_create(Suite *s) +{ SRunner *sr = (SRunner *)emalloc(sizeof(SRunner)); /* freed in srunner_free */ sr->slst = check_list_create(); @@ -335,14 +367,16 @@ SRunner *srunner_create(Suite *s) { return sr; } -void srunner_add_suite(SRunner *sr, Suite *s) { +void srunner_add_suite(SRunner *sr, Suite *s) +{ if (s == NULL) return; check_list_add_end(sr->slst, s); } -void srunner_free(SRunner *sr) { +void srunner_free(SRunner *sr) +{ List *l; TestResult *tr; @@ -351,13 +385,15 @@ void srunner_free(SRunner *sr) { free(sr->stats); l = sr->slst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { suite_free((Suite *)check_list_val(l)); } check_list_free(sr->slst); l = sr->resultlst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { tr = (TestResult *)check_list_val(l); tr_free(tr); } @@ -366,13 +402,15 @@ void srunner_free(SRunner *sr) { free(sr); } -int srunner_ntests_failed(SRunner *sr) { +int srunner_ntests_failed(SRunner *sr) +{ return sr->stats->n_failed + sr->stats->n_errors; } int srunner_ntests_run(SRunner *sr) { return sr->stats->n_checked; } -TestResult **srunner_failures(SRunner *sr) { +TestResult **srunner_failures(SRunner *sr) +{ int i = 0; TestResult **trarray; List *rlst; @@ -382,7 +420,8 @@ TestResult **srunner_failures(SRunner *sr) { rlst = sr->resultlst; for (check_list_front(rlst); !check_list_at_end(rlst); - check_list_advance(rlst)) { + check_list_advance(rlst)) + { TestResult *tr = (TestResult *)check_list_val(rlst); if (non_pass(tr->rtype)) @@ -391,7 +430,8 @@ TestResult **srunner_failures(SRunner *sr) { return trarray; } -TestResult **srunner_results(SRunner *sr) { +TestResult **srunner_results(SRunner *sr) +{ int i = 0; TestResult **trarray; List *rlst; @@ -400,7 +440,8 @@ TestResult **srunner_results(SRunner *sr) { rlst = sr->resultlst; for (check_list_front(rlst); !check_list_at_end(rlst); - check_list_advance(rlst)) { + check_list_advance(rlst)) + { trarray[i++] = (TestResult *)check_list_val(rlst); } return trarray; @@ -408,7 +449,8 @@ TestResult **srunner_results(SRunner *sr) { static int non_pass(int val) { return val != CK_PASS; } -TestResult *tr_create(void) { +TestResult *tr_create(void) +{ TestResult *tr; tr = (TestResult *)emalloc(sizeof(TestResult)); @@ -416,7 +458,8 @@ TestResult *tr_create(void) { return tr; } -static void tr_init(TestResult *tr) { +static void tr_init(TestResult *tr) +{ tr->ctx = CK_CTX_INVALID; tr->line = -1; tr->rtype = CK_TEST_RESULT_INVALID; @@ -427,7 +470,8 @@ static void tr_init(TestResult *tr) { tr->duration = -1; } -void tr_free(TestResult *tr) { +void tr_free(TestResult *tr) +{ free(tr->file); free(tr->msg); free(tr); @@ -447,7 +491,8 @@ const char *tr_tcname(TestResult *tr) { return tr->tcname; } static enum fork_status _fstat = CK_FORK; -void set_fork_status(enum fork_status fstat) { +void set_fork_status(enum fork_status fstat) +{ if (fstat == CK_FORK || fstat == CK_NOFORK || fstat == CK_FORK_GETENV) _fstat = fstat; else @@ -464,10 +509,12 @@ enum fork_status cur_fork_status(void) { return _fstat; } * The clockid_t that was found to work on the first call is * cached for subsequent calls. */ -clockid_t check_get_clockid() { +clockid_t check_get_clockid() +{ static clockid_t clockid = -1; - if (clockid == -1) { + if (clockid == -1) + { /* * Only check if we have librt available. Otherwise, the clockid * will be ignored anyway, as the clock_gettime() and @@ -478,10 +525,13 @@ clockid_t check_get_clockid() { #ifdef HAVE_LIBRT timer_t timerid; - if (timer_create(CLOCK_MONOTONIC, NULL, &timerid) == 0) { + if (timer_create(CLOCK_MONOTONIC, NULL, &timerid) == 0) + { timer_delete(timerid); clockid = CLOCK_MONOTONIC; - } else { + } + else + { clockid = CLOCK_REALTIME; } #else diff --git a/testing/backends/check/check.h b/testing/backends/check/check.h index d00c1f5fde..d22b90026e 100644 --- a/testing/backends/check/check.h +++ b/testing/backends/check/check.h @@ -33,13 +33,15 @@ */ #ifdef __cplusplus -#define CK_CPPSTART extern "C" { +#define CK_CPPSTART \ + extern "C" \ + { #define CK_CPPEND } CK_CPPSTART #endif #if defined(__GNUC__) && defined(__GNUC_MINOR__) -#define GCC_VERSION_AT_LEAST(major, minor) \ +#define GCC_VERSION_AT_LEAST(major, minor) \ ((__GNUC__ > (major)) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) #else #define GCC_VERSION_AT_LEAST(major, minor) 0 @@ -189,7 +191,7 @@ CK_DLL_EXP TCase *CK_EXPORT tcase_create(const char *name); * * @since 0.9.2 * */ -#define tcase_add_test_raise_signal(tc, tf, signal) \ +#define tcase_add_test_raise_signal(tc, tf, signal) \ _tcase_add_test((tc), (tf), "" #tf "", (signal), 0, 0, 1) /** @@ -204,7 +206,7 @@ CK_DLL_EXP TCase *CK_EXPORT tcase_create(const char *name); * * @since 0.9.7 */ -#define tcase_add_exit_test(tc, tf, expected_exit_value) \ +#define tcase_add_exit_test(tc, tf, expected_exit_value) \ _tcase_add_test((tc), (tf), "" #tf "", 0, (expected_exit_value), 0, 1) /** @@ -221,7 +223,7 @@ CK_DLL_EXP TCase *CK_EXPORT tcase_create(const char *name); * * @since 0.9.4 */ -#define tcase_add_loop_test(tc, tf, s, e) \ +#define tcase_add_loop_test(tc, tf, s, e) \ _tcase_add_test((tc), (tf), "" #tf "", 0, 0, (s), (e)) /** @@ -242,7 +244,7 @@ CK_DLL_EXP TCase *CK_EXPORT tcase_create(const char *name); * * @since 0.9.5 */ -#define tcase_add_loop_test_raise_signal(tc, tf, signal, s, e) \ +#define tcase_add_loop_test_raise_signal(tc, tf, signal, s, e) \ _tcase_add_test((tc), (tf), "" #tf "", (signal), 0, (s), (e)) /** @@ -263,7 +265,7 @@ CK_DLL_EXP TCase *CK_EXPORT tcase_create(const char *name); * * @since 0.9.7 */ -#define tcase_add_loop_exit_test(tc, tf, expected_exit_value, s, e) \ +#define tcase_add_loop_exit_test(tc, tf, expected_exit_value, s, e) \ _tcase_add_test((tc), (tf), "" #tf "", 0, (expected_exit_value), (s), (e)) /* Add a test function to a test case @@ -363,8 +365,9 @@ CK_DLL_EXP void CK_EXPORT tcase_fn_start(const char *fname, const char *file, * * @since 0.6.0 */ -#define START_TEST(__testname) \ - static void __testname(int _i CK_ATTRIBUTE_UNUSED) { \ +#define START_TEST(__testname) \ + static void __testname(int _i CK_ATTRIBUTE_UNUSED) \ + { \ tcase_fn_start("" #__testname, __FILE__, __LINE__); /** @@ -391,10 +394,10 @@ CK_DLL_EXP void CK_EXPORT tcase_fn_start(const char *fname, const char *file, * FIXME: these macros may conflict with C89 if expr is * FIXME: strcmp (str1, str2) due to excessive string length. */ -#define fail_if(expr, ...) \ - (expr) \ - ? _ck_assert_failed(__FILE__, __LINE__, "Failure '" #expr "' occurred", \ - ##__VA_ARGS__, NULL) \ +#define fail_if(expr, ...) \ + (expr) \ + ? _ck_assert_failed(__FILE__, __LINE__, "Failure '" #expr "' occurred", \ + ##__VA_ARGS__, NULL) \ : _mark_point(__FILE__, __LINE__) /* @@ -445,10 +448,10 @@ CK_DLL_EXP void CK_EXPORT _ck_assert_failed(const char *file, int line, * * @since 0.9.6 */ -#define ck_assert_msg(expr, ...) \ - (expr) \ - ? _mark_point(__FILE__, __LINE__) \ - : _ck_assert_failed(__FILE__, __LINE__, "Assertion '" #expr "' failed", \ +#define ck_assert_msg(expr, ...) \ + (expr) \ + ? _mark_point(__FILE__, __LINE__) \ + : _ck_assert_failed(__FILE__, __LINE__, "Assertion '" #expr "' failed", \ ##__VA_ARGS__, NULL) /** @@ -468,19 +471,20 @@ CK_DLL_EXP void CK_EXPORT _ck_assert_failed(const char *file, int line, * * @since 0.9.6 */ -#define ck_abort_msg(...) \ +#define ck_abort_msg(...) \ _ck_assert_failed(__FILE__, __LINE__, "Failed", ##__VA_ARGS__, NULL) /* Signed and unsigned integer comparison macros with improved output compared * to ck_assert(). */ /* OP may be any comparison operator. */ -#define _ck_assert_int(X, OP, Y) \ - do { \ - intmax_t _ck_x = (X); \ - intmax_t _ck_y = (Y); \ - ck_assert_msg(_ck_x OP _ck_y, \ - "Assertion '%s' failed: %s == %jd, %s == %jd", \ - #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ +#define _ck_assert_int(X, OP, Y) \ + do \ + { \ + intmax_t _ck_x = (X); \ + intmax_t _ck_y = (Y); \ + ck_assert_msg(_ck_x OP _ck_y, \ + "Assertion '%s' failed: %s == %jd, %s == %jd", \ + #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ } while (0) /** @@ -562,13 +566,14 @@ CK_DLL_EXP void CK_EXPORT _ck_assert_failed(const char *file, int line, */ #define ck_assert_int_ge(X, Y) _ck_assert_int(X, >=, Y) -#define _ck_assert_uint(X, OP, Y) \ - do { \ - uintmax_t _ck_x = (X); \ - uintmax_t _ck_y = (Y); \ - ck_assert_msg(_ck_x OP _ck_y, \ - "Assertion '%s' failed: %s == %ju, %s == %ju", \ - #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ +#define _ck_assert_uint(X, OP, Y) \ + do \ + { \ + uintmax_t _ck_x = (X); \ + uintmax_t _ck_y = (Y); \ + ck_assert_msg(_ck_x OP _ck_y, \ + "Assertion '%s' failed: %s == %ju, %s == %ju", \ + #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ } while (0) /** * Check two unsigned integers to determine if X==Y @@ -653,13 +658,14 @@ CK_DLL_EXP void CK_EXPORT _ck_assert_failed(const char *file, int line, /* OP might be any operator that can be used in '0 OP strcmp(X,Y)' comparison */ /* The x and y parameter swap in strcmp() is needed to handle >, >=, <, <= * operators */ -#define _ck_assert_str(X, OP, Y) \ - do { \ - const char *_ck_x = (X); \ - const char *_ck_y = (Y); \ - ck_assert_msg(0 OP strcmp(_ck_y, _ck_x), \ - "Assertion '%s' failed: %s == \"%s\", %s == \"%s\"", \ - #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ +#define _ck_assert_str(X, OP, Y) \ + do \ + { \ + const char *_ck_x = (X); \ + const char *_ck_y = (Y); \ + ck_assert_msg(0 OP strcmp(_ck_y, _ck_x), \ + "Assertion '%s' failed: %s == \"%s\", %s == \"%s\"", \ + #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ } while (0) /** * Check two strings to determine if 0==strcmp(X,Y) @@ -742,13 +748,14 @@ CK_DLL_EXP void CK_EXPORT _ck_assert_failed(const char *file, int line, /* Pointer comparison macros with improved output compared to ck_assert(). */ /* OP may only be == or != */ -#define _ck_assert_ptr(X, OP, Y) \ - do { \ - const void *_ck_x = (X); \ - const void *_ck_y = (Y); \ - ck_assert_msg(_ck_x OP _ck_y, \ - "Assertion '%s' failed: %s == %#x, %s == %#x", \ - #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ +#define _ck_assert_ptr(X, OP, Y) \ + do \ + { \ + const void *_ck_x = (X); \ + const void *_ck_y = (Y); \ + ck_assert_msg(_ck_x OP _ck_y, \ + "Assertion '%s' failed: %s == %#x, %s == %#x", \ + #X " " #OP " " #Y, #X, _ck_x, #Y, _ck_y); \ } while (0) /** @@ -796,7 +803,8 @@ CK_DLL_EXP void CK_EXPORT _mark_point(const char *file, int line); /** * Enum describing the possible results of a test */ -enum test_result { +enum test_result +{ CK_TEST_RESULT_INVALID, /**< Default value; should not encounter this */ CK_PASS, /**< Test passed */ CK_SKIP, @@ -808,7 +816,8 @@ enum test_result { /** * Enum specifying the verbosity of output a SRunner should produce */ -enum print_output { +enum print_output +{ CK_SILENT, /**< No output */ CK_MINIMAL, /**< Only summary output */ CK_NORMAL, /**< All failed tests */ @@ -837,7 +846,8 @@ typedef struct TestResult TestResult; /** * Enum representing the types of contexts for a test */ -enum ck_result_ctx { +enum ck_result_ctx +{ CK_CTX_INVALID, /**< Default value; should not encounter this */ CK_CTX_SETUP, /**< Setup before a test */ CK_CTX_TEST, /**< Body of test itself */ @@ -1190,7 +1200,8 @@ CK_DLL_EXP const char *CK_EXPORT srunner_tap_fname(SRunner *sr); /** * Enum describing the current fork usage. */ -enum fork_status { +enum fork_status +{ CK_FORK_GETENV, /**< look in the environment for CK_FORK */ CK_FORK, /**< call fork to run tests */ CK_NOFORK /**< don't call fork */ diff --git a/testing/backends/check/check_error.c b/testing/backends/check/check_error.c index 17510844cd..79cce6fc01 100644 --- a/testing/backends/check/check_error.c +++ b/testing/backends/check/check_error.c @@ -59,7 +59,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. jmp_buf error_jmp_buffer; /* FIXME: including a colon at the end is a bad way to indicate an error */ -void eprintf(const char *fmt, const char *file, int line, ...) { +void eprintf(const char *fmt, const char *file, int line, ...) +{ va_list args; fflush(stderr); @@ -77,7 +78,8 @@ void eprintf(const char *fmt, const char *file, int line, ...) { exit(2); } -void *emalloc(size_t n) { +void *emalloc(size_t n) +{ void *p; p = malloc(n); @@ -86,7 +88,8 @@ void *emalloc(size_t n) { return p; } -void *erealloc(void *ptr, size_t n) { +void *erealloc(void *ptr, size_t n) +{ void *p; p = realloc(ptr, n); diff --git a/testing/backends/check/check_impl.h b/testing/backends/check/check_impl.h index 1ff601b233..0b05a0fa17 100644 --- a/testing/backends/check/check_impl.h +++ b/testing/backends/check/check_impl.h @@ -30,11 +30,12 @@ #define NANOS_PER_SECONDS 1000000000 /** calculate the difference in useconds out of two "struct timespec"s */ -#define DIFF_IN_USEC(begin, end) \ - ((((end).tv_sec - (begin).tv_sec) * US_PER_SEC) + ((end).tv_nsec / 1000) - \ +#define DIFF_IN_USEC(begin, end) \ + ((((end).tv_sec - (begin).tv_sec) * US_PER_SEC) + ((end).tv_nsec / 1000) - \ ((begin).tv_nsec / 1000)) -typedef struct TF { +typedef struct TF +{ TFun fn; int loop_start; int loop_end; @@ -43,17 +44,20 @@ typedef struct TF { signed char allowed_exit_value; } TF; -struct Suite { +struct Suite +{ const char *name; List *tclst; /* List of test cases */ }; -typedef struct Fixture { +typedef struct Fixture +{ int ischecked; SFun fun; } Fixture; -struct TCase { +struct TCase +{ const char *name; struct timespec timeout; List *tflst; /* list of test functions */ @@ -63,13 +67,15 @@ struct TCase { List *ch_tflst; }; -typedef struct TestStats { +typedef struct TestStats +{ int n_checked; int n_failed; int n_errors; } TestStats; -struct TestResult { +struct TestResult +{ enum test_result rtype; /* Type of result */ enum ck_result_ctx ctx; /* When the result occurred */ char *file; /* File where the test occured */ @@ -85,7 +91,8 @@ TestResult *tr_create(void); void tr_reset(TestResult *tr); void tr_free(TestResult *tr); -enum cl_event { +enum cl_event +{ CLINITLOG_SR, /* Initialize log file */ CLENDLOG_SR, /* Tests are complete */ CLSTART_SR, /* Suite runner start */ @@ -99,14 +106,16 @@ enum cl_event { typedef void (*LFun)(SRunner *, FILE *, enum print_output, void *, enum cl_event); -typedef struct Log { +typedef struct Log +{ FILE *lfile; LFun lfun; int close; enum print_output mode; } Log; -struct SRunner { +struct SRunner +{ List *slst; /* List of Suite objects */ TestStats *stats; /* Run statistics */ List *resultlst; /* List of unit test results */ diff --git a/testing/backends/check/check_list.c b/testing/backends/check/check_list.c index fa929225b0..5a5f58e740 100644 --- a/testing/backends/check/check_list.c +++ b/testing/backends/check/check_list.c @@ -50,9 +50,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "check_list.h" #include "check_error.h" -enum { LINIT = 1, LGROW = 2 }; +enum +{ + LINIT = 1, + LGROW = 2 +}; -struct List { +struct List +{ unsigned int n_elts; unsigned int max_elts; int current; /* pointer to the current node */ @@ -60,14 +65,17 @@ struct List { void **data; }; -static void maybe_grow(List *lp) { - if (lp->n_elts >= lp->max_elts) { +static void maybe_grow(List *lp) +{ + if (lp->n_elts >= lp->max_elts) + { lp->max_elts *= LGROW; lp->data = (void **)erealloc(lp->data, lp->max_elts * sizeof(lp->data[0])); } } -List *check_list_create(void) { +List *check_list_create(void) +{ List *lp; lp = (List *)emalloc(sizeof(List)); @@ -78,7 +86,8 @@ List *check_list_create(void) { return lp; } -void check_list_add_front(List *lp, void *val) { +void check_list_add_front(List *lp, void *val) +{ if (lp == NULL) return; maybe_grow(lp); @@ -89,7 +98,8 @@ void check_list_add_front(List *lp, void *val) { lp->data[lp->current] = val; } -void check_list_add_end(List *lp, void *val) { +void check_list_add_end(List *lp, void *val) +{ if (lp == NULL) return; maybe_grow(lp); @@ -99,20 +109,23 @@ void check_list_add_end(List *lp, void *val) { lp->data[lp->current] = val; } -int check_list_at_end(List *lp) { +int check_list_at_end(List *lp) +{ if (lp->current == -1) return 1; else return (lp->current > lp->last); } -void check_list_front(List *lp) { +void check_list_front(List *lp) +{ if (lp->current == -1) return; lp->current = 0; } -void check_list_free(List *lp) { +void check_list_free(List *lp) +{ if (lp == NULL) return; @@ -120,7 +133,8 @@ void check_list_free(List *lp) { free(lp); } -void *check_list_val(List *lp) { +void *check_list_val(List *lp) +{ if (lp == NULL) return NULL; if (lp->current == -1 || lp->current > lp->last) @@ -129,7 +143,8 @@ void *check_list_val(List *lp) { return lp->data[lp->current]; } -void check_list_advance(List *lp) { +void check_list_advance(List *lp) +{ if (lp == NULL) return; if (check_list_at_end(lp)) @@ -137,7 +152,8 @@ void check_list_advance(List *lp) { lp->current++; } -void check_list_apply(List *lp, void (*fp)(void *)) { +void check_list_apply(List *lp, void (*fp)(void *)) +{ if (lp == NULL || fp == NULL) return; diff --git a/testing/backends/check/check_log.c b/testing/backends/check/check_log.c index f718e2fced..1d8979d945 100644 --- a/testing/backends/check/check_log.c +++ b/testing/backends/check/check_log.c @@ -68,7 +68,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt); -void srunner_set_log(SRunner *sr, const char *fname) { +void srunner_set_log(SRunner *sr, const char *fname) +{ if (sr->log_fname) return; sr->log_fname = fname; @@ -76,7 +77,8 @@ void srunner_set_log(SRunner *sr, const char *fname) { int srunner_has_log(SRunner *sr) { return srunner_log_fname(sr) != NULL; } -const char *srunner_log_fname(SRunner *sr) { +const char *srunner_log_fname(SRunner *sr) +{ /* check if log filename have been set explicitly */ if (sr->log_fname != NULL) return sr->log_fname; @@ -84,7 +86,8 @@ const char *srunner_log_fname(SRunner *sr) { return getenv("CK_LOG_FILE_NAME"); } -void srunner_set_xml(SRunner *sr, const char *fname) { +void srunner_set_xml(SRunner *sr, const char *fname) +{ if (sr->xml_fname) return; sr->xml_fname = fname; @@ -92,16 +95,19 @@ void srunner_set_xml(SRunner *sr, const char *fname) { int srunner_has_xml(SRunner *sr) { return srunner_xml_fname(sr) != NULL; } -const char *srunner_xml_fname(SRunner *sr) { +const char *srunner_xml_fname(SRunner *sr) +{ /* check if XML log filename have been set explicitly */ - if (sr->xml_fname != NULL) { + if (sr->xml_fname != NULL) + { return sr->xml_fname; } return getenv("CK_XML_LOG_FILE_NAME"); } -void srunner_set_tap(SRunner *sr, const char *fname) { +void srunner_set_tap(SRunner *sr, const char *fname) +{ if (sr->tap_fname) return; sr->tap_fname = fname; @@ -109,9 +115,11 @@ void srunner_set_tap(SRunner *sr, const char *fname) { int srunner_has_tap(SRunner *sr) { return srunner_tap_fname(sr) != NULL; } -const char *srunner_tap_fname(SRunner *sr) { +const char *srunner_tap_fname(SRunner *sr) +{ /* check if tap log filename have been set explicitly */ - if (sr->tap_fname != NULL) { + if (sr->tap_fname != NULL) + { return sr->tap_fname; } @@ -119,10 +127,12 @@ const char *srunner_tap_fname(SRunner *sr) { } void srunner_register_lfun(SRunner *sr, FILE *lfile, int close, LFun lfun, - enum print_output printmode) { + enum print_output printmode) +{ Log *l = (Log *)emalloc(sizeof(Log)); - if (printmode == CK_ENV) { + if (printmode == CK_ENV) + { printmode = get_env_printmode(); } @@ -138,29 +148,34 @@ void log_srunner_start(SRunner *sr) { srunner_send_evt(sr, NULL, CLSTART_SR); } void log_srunner_end(SRunner *sr) { srunner_send_evt(sr, NULL, CLEND_SR); } -void log_suite_start(SRunner *sr, Suite *s) { +void log_suite_start(SRunner *sr, Suite *s) +{ srunner_send_evt(sr, s, CLSTART_S); } void log_suite_end(SRunner *sr, Suite *s) { srunner_send_evt(sr, s, CLEND_S); } -void log_test_start(SRunner *sr, TCase *tc, TF *tfun) { +void log_test_start(SRunner *sr, TCase *tc, TF *tfun) +{ char buffer[100]; snprintf(buffer, 99, "%s:%s", tc->name, tfun->name); srunner_send_evt(sr, buffer, CLSTART_T); } -void log_test_end(SRunner *sr, TestResult *tr) { +void log_test_end(SRunner *sr, TestResult *tr) +{ srunner_send_evt(sr, tr, CLEND_T); } -static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) { +static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) +{ List *l; Log *lg; l = sr->loglst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { lg = (Log *)check_list_val(l); fflush(lg->lfile); lg->lfun(sr, lg->lfile, lg->mode, obj, evt); @@ -169,16 +184,19 @@ static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) { } void stdout_lfun(SRunner *sr, FILE *file, enum print_output printmode, - void *obj, enum cl_event evt) { + void *obj, enum cl_event evt) +{ Suite *s; - switch (evt) { + switch (evt) + { case CLINITLOG_SR: break; case CLENDLOG_SR: break; case CLSTART_SR: - if (printmode > CK_SILENT) { + if (printmode > CK_SILENT) + { fprintf(file, " ,---------------------------------------. \n" " | MDSplus unit testing... | \n" " '---------------------------------------' \n" @@ -187,7 +205,8 @@ void stdout_lfun(SRunner *sr, FILE *file, enum print_output printmode, break; case CLSTART_S: s = (Suite *)obj; - if (printmode > CK_SILENT) { + if (printmode > CK_SILENT) + { fprintf(file, " Running in suite: %s\n", s->name); fprintf(file, "\n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n" @@ -195,7 +214,8 @@ void stdout_lfun(SRunner *sr, FILE *file, enum print_output printmode, } break; case CLEND_SR: - if (printmode > CK_SILENT) { + if (printmode > CK_SILENT) + { /* we don't want a newline before printing here, newlines should come after printing a string, not before. it's better to add the newline above in CLSTART_S. @@ -210,7 +230,8 @@ void stdout_lfun(SRunner *sr, FILE *file, enum print_output printmode, case CLEND_S: break; case CLSTART_T: - if (printmode > CK_SILENT) { + if (printmode > CK_SILENT) + { TCase *t = (TCase *)obj; fprintf(file, " -- [%s] -- \n", t->name); } @@ -224,11 +245,13 @@ void stdout_lfun(SRunner *sr, FILE *file, enum print_output printmode, void lfile_lfun(SRunner *sr, FILE *file, enum print_output printmode CK_ATTRIBUTE_UNUSED, void *obj, - enum cl_event evt) { + enum cl_event evt) +{ TestResult *tr; Suite *s; - switch (evt) { + switch (evt) + { case CLINITLOG_SR: break; case CLENDLOG_SR: @@ -258,13 +281,15 @@ void lfile_lfun(SRunner *sr, FILE *file, void xml_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, enum print_output printmode CK_ATTRIBUTE_UNUSED, void *obj, - enum cl_event evt) { + enum cl_event evt) +{ TestResult *tr; Suite *s; static struct timespec ts_start = {0, 0}; static char t[sizeof "yyyy-mm-dd hh:mm:ss"] = {0}; - if (t[0] == 0) { + if (t[0] == 0) + { struct timeval inittv; // struct tm now; @@ -279,7 +304,8 @@ void xml_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, // } } - switch (evt) { + switch (evt) + { case CLINITLOG_SR: fprintf(file, "\n"); fprintf( @@ -289,7 +315,8 @@ void xml_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, fprintf(file, "\n"); fprintf(file, " %s\n", t); break; - case CLENDLOG_SR: { + case CLENDLOG_SR: + { struct timespec ts_end = {0, 0}; unsigned long duration; @@ -299,7 +326,8 @@ void xml_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, fprintf(file, " %lu.%06lu\n", duration / US_PER_SEC, duration % US_PER_SEC); fprintf(file, "\n"); - } break; + } + break; case CLSTART_SR: break; case CLSTART_S: @@ -327,12 +355,14 @@ void xml_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, void tap_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, enum print_output printmode CK_ATTRIBUTE_UNUSED, void *obj, - enum cl_event evt) { + enum cl_event evt) +{ TestResult *tr; static int num_tests_run = 0; - switch (evt) { + switch (evt) + { case CLINITLOG_SR: /* As this is a new log file, reset the number of tests executed */ num_tests_run = 0; @@ -356,7 +386,8 @@ void tap_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, /* Print the test result to the tap file */ num_tests_run += 1; tr = (TestResult *)obj; - switch (tr->rtype) { + switch (tr->rtype) + { case CK_PASS: fprintf(file, "ok %d - %s:%s:%d: %s\n", num_tests_run, tr->tcname, tr->file, tr->line, tr->msg); @@ -379,13 +410,15 @@ void tap_lfun(SRunner *sr CK_ATTRIBUTE_UNUSED, FILE *file, #if ENABLE_SUBUNIT void subunit_lfun(SRunner *sr, FILE *file, enum print_output printmode, - void *obj, enum cl_event evt) { + void *obj, enum cl_event evt) +{ TestResult *tr; char const *name; /* assert(printmode == CK_SUBUNIT); */ - switch (evt) { + switch (evt) + { case CLINITLOG_SR: break; case CLENDLOG_SR: @@ -395,7 +428,8 @@ void subunit_lfun(SRunner *sr, FILE *file, enum print_output printmode, case CLSTART_S: break; case CLEND_SR: - if (printmode > CK_SILENT) { + if (printmode > CK_SILENT) + { fprintf(file, "\n"); srunner_fprint(file, sr, printmode); } @@ -412,7 +446,8 @@ void subunit_lfun(SRunner *sr, FILE *file, enum print_output printmode, char *name = ck_strdup_printf("%s:%s", tr->tcname, tr->tname); char *msg = tr_short_str(tr); - switch (tr->rtype) { + switch (tr->rtype) + { case CK_PASS: subunit_test_pass(name); break; @@ -436,14 +471,19 @@ void subunit_lfun(SRunner *sr, FILE *file, enum print_output printmode, } #endif -static FILE *srunner_open_file(const char *filename) { +static FILE *srunner_open_file(const char *filename) +{ FILE *f = NULL; - if (strcmp(filename, STDOUT_OVERRIDE_LOG_FILE_NAME) == 0) { + if (strcmp(filename, STDOUT_OVERRIDE_LOG_FILE_NAME) == 0) + { f = stdout; - } else { + } + else + { f = fopen(filename, "w"); - if (f == NULL) { + if (f == NULL) + { eprintf("Error in call to fopen while opening file %s:", __FILE__, __LINE__ - 2, filename); } @@ -451,34 +491,41 @@ static FILE *srunner_open_file(const char *filename) { return f; } -FILE *srunner_open_lfile(SRunner *sr) { +FILE *srunner_open_lfile(SRunner *sr) +{ FILE *f = NULL; - if (srunner_has_log(sr)) { + if (srunner_has_log(sr)) + { f = srunner_open_file(srunner_log_fname(sr)); } return f; } -FILE *srunner_open_xmlfile(SRunner *sr) { +FILE *srunner_open_xmlfile(SRunner *sr) +{ FILE *f = NULL; - if (srunner_has_xml(sr)) { + if (srunner_has_xml(sr)) + { f = srunner_open_file(srunner_xml_fname(sr)); } return f; } -FILE *srunner_open_tapfile(SRunner *sr) { +FILE *srunner_open_tapfile(SRunner *sr) +{ FILE *f = NULL; - if (srunner_has_tap(sr)) { + if (srunner_has_tap(sr)) + { f = srunner_open_file(srunner_tap_fname(sr)); } return f; } -void srunner_init_logging(SRunner *sr, enum print_output print_mode) { +void srunner_init_logging(SRunner *sr, enum print_output print_mode) +{ FILE *f; sr->loglst = check_list_create(); @@ -491,31 +538,37 @@ void srunner_init_logging(SRunner *sr, enum print_output print_mode) { else srunner_register_lfun(sr, stdout, 0, subunit_lfun, print_mode); #endif f = srunner_open_lfile(sr); - if (f) { + if (f) + { srunner_register_lfun(sr, f, f != stdout, lfile_lfun, print_mode); } f = srunner_open_xmlfile(sr); - if (f) { + if (f) + { srunner_register_lfun(sr, f, f != stdout, xml_lfun, print_mode); } f = srunner_open_tapfile(sr); - if (f) { + if (f) + { srunner_register_lfun(sr, f, f != stdout, tap_lfun, print_mode); } srunner_send_evt(sr, NULL, CLINITLOG_SR); } -void srunner_end_logging(SRunner *sr) { +void srunner_end_logging(SRunner *sr) +{ List *l; int rval; srunner_send_evt(sr, NULL, CLENDLOG_SR); l = sr->loglst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { Log *lg = (Log *)check_list_val(l); - if (lg->close) { + if (lg->close) + { rval = fclose(lg->lfile); if (rval != 0) eprintf("Error in call to fclose while closing log file:", __FILE__, diff --git a/testing/backends/check/check_msg.c b/testing/backends/check/check_msg.c index efa918f997..c43e2f81f0 100644 --- a/testing/backends/check/check_msg.c +++ b/testing/backends/check/check_msg.c @@ -89,12 +89,15 @@ static void teardown_pipe(void); static TestResult *construct_test_result(RcvMsg *rmsg, int waserror); static void tr_set_loc_by_ctx(TestResult *tr, enum ck_result_ctx ctx, RcvMsg *rmsg); -static FILE *get_pipe(void) { - if (send_file2 != 0) { +static FILE *get_pipe(void) +{ + if (send_file2 != 0) + { return send_file2; } - if (send_file1 != 0) { + if (send_file1 != 0) + { return send_file1; } @@ -103,7 +106,8 @@ static FILE *get_pipe(void) { return NULL; } -void send_failure_info(const char *msg, int rtype) { +void send_failure_info(const char *msg, int rtype) +{ FailMsg fmsg; fmsg.msg = strdup(msg); @@ -112,14 +116,16 @@ void send_failure_info(const char *msg, int rtype) { free(fmsg.msg); } -void send_duration_info(int duration) { +void send_duration_info(int duration) +{ DurationMsg dmsg; dmsg.duration = duration; ppack(get_pipe(), CK_MSG_DURATION, (CheckMsg *)&dmsg); } -void send_loc_info(const char *file, int line) { +void send_loc_info(const char *file, int line) +{ LocMsg lmsg; lmsg.file = strdup(file); @@ -128,27 +134,31 @@ void send_loc_info(const char *file, int line) { free(lmsg.file); } -void send_ctx_info(enum ck_result_ctx ctx) { +void send_ctx_info(enum ck_result_ctx ctx) +{ CtxMsg cmsg; cmsg.ctx = ctx; ppack(get_pipe(), CK_MSG_CTX, (CheckMsg *)&cmsg); } -TestResult *receive_test_result(int waserror) { +TestResult *receive_test_result(int waserror) +{ FILE *fp; RcvMsg *rmsg; TestResult *result; fp = get_pipe(); - if (fp == NULL) { + if (fp == NULL) + { eprintf("Error in call to get_pipe", __FILE__, __LINE__ - 2); } rewind(fp); rmsg = punpack(fp); - if (rmsg == NULL) { + if (rmsg == NULL) + { eprintf("Error in call to punpack", __FILE__, __LINE__ - 4); } @@ -161,13 +171,17 @@ TestResult *receive_test_result(int waserror) { } static void tr_set_loc_by_ctx(TestResult *tr, enum ck_result_ctx ctx, - RcvMsg *rmsg) { - if (ctx == CK_CTX_TEST) { + RcvMsg *rmsg) +{ + if (ctx == CK_CTX_TEST) + { tr->file = rmsg->test_file; tr->line = rmsg->test_line; rmsg->test_file = NULL; rmsg->test_line = -1; - } else { + } + else + { tr->file = rmsg->fixture_file; tr->line = rmsg->fixture_line; rmsg->fixture_file = NULL; @@ -175,7 +189,8 @@ static void tr_set_loc_by_ctx(TestResult *tr, enum ck_result_ctx ctx, } } -static TestResult *construct_test_result(RcvMsg *rmsg, int waserror) { +static TestResult *construct_test_result(RcvMsg *rmsg, int waserror) +{ TestResult *tr; if (rmsg == NULL) @@ -183,23 +198,31 @@ static TestResult *construct_test_result(RcvMsg *rmsg, int waserror) { tr = tr_create(); - if (rmsg->msg != NULL || waserror) { - if (rmsg->failctx != CK_CTX_INVALID) { + if (rmsg->msg != NULL || waserror) + { + if (rmsg->failctx != CK_CTX_INVALID) + { tr->ctx = rmsg->failctx; tr->rtype = rmsg->rtype; - } else { + } + else + { tr->ctx = rmsg->lastctx; } tr->msg = rmsg->msg; rmsg->msg = NULL; tr_set_loc_by_ctx(tr, tr->ctx, rmsg); - } else if (rmsg->lastctx == CK_CTX_SETUP) { + } + else if (rmsg->lastctx == CK_CTX_SETUP) + { tr->ctx = CK_CTX_SETUP; tr->msg = NULL; tr->rtype = CK_PASS; tr_set_loc_by_ctx(tr, CK_CTX_SETUP, rmsg); - } else { + } + else + { tr->ctx = CK_CTX_TEST; tr->msg = NULL; tr->rtype = CK_PASS; @@ -223,7 +246,8 @@ void teardown_messaging(void) { teardown_pipe(); } * expecting the caller to both delete the file and * free the 'name' field after the file is closed. */ -FILE *open_tmp_file(char **name) { +FILE *open_tmp_file(char **name) +{ FILE *file = NULL; *name = NULL; @@ -239,7 +263,8 @@ FILE *open_tmp_file(char **name) { /* and finally, the "b" from "w+b" is ignored on OS X, not sure about WIN32 */ file = tmpfile(); - if (file == NULL) { + if (file == NULL) + { char *tmp = getenv("TEMP"); char *tmp_file = tempnam(tmp, "check_"); @@ -262,15 +287,18 @@ FILE *open_tmp_file(char **name) { #else int fd = -1; const char *tmp_dir = getenv("TEMP"); - if (!tmp_dir) { + if (!tmp_dir) + { tmp_dir = "."; } *name = ck_strdup_printf("%s/check_XXXXXX", tmp_dir); - if (-1 < (fd = mkstemp(*name))) { + if (-1 < (fd = mkstemp(*name))) + { file = fdopen(fd, "w+b"); - if (0 == unlink(*name) || NULL == file) { + if (0 == unlink(*name) || NULL == file) + { free(*name); *name = NULL; } @@ -279,36 +307,47 @@ FILE *open_tmp_file(char **name) { return file; } -static void setup_pipe(void) { - if (send_file1 == NULL) { +static void setup_pipe(void) +{ + if (send_file1 == NULL) + { send_file1 = open_tmp_file(&send_file1_name); return; } - if (send_file2 == NULL) { + if (send_file2 == NULL) + { send_file2 = open_tmp_file(&send_file2_name); return; } eprintf("Only one nesting of suite runs supported", __FILE__, __LINE__); } -static void teardown_pipe(void) { - if (send_file2 != 0) { +static void teardown_pipe(void) +{ + if (send_file2 != 0) + { fclose(send_file2); send_file2 = 0; - if (send_file2_name != NULL) { + if (send_file2_name != NULL) + { unlink(send_file2_name); free(send_file2_name); send_file2_name = NULL; } - } else if (send_file1 != 0) { + } + else if (send_file1 != 0) + { fclose(send_file1); send_file1 = 0; - if (send_file1_name != NULL) { + if (send_file1_name != NULL) + { unlink(send_file1_name); free(send_file1_name); send_file1_name = NULL; } - } else { + } + else + { eprintf("No messaging setup", __FILE__, __LINE__); } } diff --git a/testing/backends/check/check_pack.c b/testing/backends/check/check_pack.c index 64deb9c1d2..987282de2f 100644 --- a/testing/backends/check/check_pack.c +++ b/testing/backends/check/check_pack.c @@ -118,7 +118,8 @@ static pfun pftab[] = {(pfun)pack_ctx, (pfun)pack_fail, (pfun)pack_loc, static upfun upftab[] = {(upfun)upack_ctx, (upfun)upack_fail, (upfun)upack_loc, (upfun)upack_duration}; -int pack(enum ck_msg_type type, char **buf, CheckMsg *msg) { +int pack(enum ck_msg_type type, char **buf, CheckMsg *msg) +{ if (buf == NULL) return -1; if (msg == NULL) @@ -129,7 +130,8 @@ int pack(enum ck_msg_type type, char **buf, CheckMsg *msg) { return pftab[type](buf, msg); } -int upack(char *buf, CheckMsg *msg, enum ck_msg_type *type) { +int upack(char *buf, CheckMsg *msg, enum ck_msg_type *type) +{ char *obuf; if (buf == NULL) @@ -146,7 +148,8 @@ int upack(char *buf, CheckMsg *msg, enum ck_msg_type *type) { return buf - obuf; } -static void pack_int(char **buf, int val) { +static void pack_int(char **buf, int val) +{ unsigned char *ubuf = (unsigned char *)*buf; ck_uint32 uval = val; @@ -158,7 +161,8 @@ static void pack_int(char **buf, int val) { *buf += 4; } -static int upack_int(char **buf) { +static int upack_int(char **buf) +{ unsigned char *ubuf = (unsigned char *)*buf; ck_uint32 uval; @@ -170,7 +174,8 @@ static int upack_int(char **buf) { return (int)uval; } -static void pack_str(char **buf, const char *val) { +static void pack_str(char **buf, const char *val) +{ int strsz; if (val == NULL) @@ -180,24 +185,29 @@ static void pack_str(char **buf, const char *val) { pack_int(buf, strsz); - if (strsz > 0) { + if (strsz > 0) + { memcpy(*buf, val, strsz); *buf += strsz; } } -static char *upack_str(char **buf) { +static char *upack_str(char **buf) +{ char *val; int strsz; strsz = upack_int(buf); - if (strsz > 0) { + if (strsz > 0) + { val = (char *)emalloc(strsz + 1); memcpy(val, *buf, strsz); val[strsz] = 0; *buf += strsz; - } else { + } + else + { val = (char *)emalloc(1); *val = 0; } @@ -205,15 +215,18 @@ static char *upack_str(char **buf) { return val; } -static void pack_type(char **buf, enum ck_msg_type type) { +static void pack_type(char **buf, enum ck_msg_type type) +{ pack_int(buf, (int)type); } -static enum ck_msg_type upack_type(char **buf) { +static enum ck_msg_type upack_type(char **buf) +{ return (enum ck_msg_type)upack_int(buf); } -static int pack_ctx(char **buf, CtxMsg *cmsg) { +static int pack_ctx(char **buf, CtxMsg *cmsg) +{ char *ptr; int len; @@ -226,11 +239,13 @@ static int pack_ctx(char **buf, CtxMsg *cmsg) { return len; } -static void upack_ctx(char **buf, CtxMsg *cmsg) { +static void upack_ctx(char **buf, CtxMsg *cmsg) +{ cmsg->ctx = (enum ck_result_ctx)upack_int(buf); } -static int pack_duration(char **buf, DurationMsg *cmsg) { +static int pack_duration(char **buf, DurationMsg *cmsg) +{ char *ptr; int len; @@ -243,11 +258,13 @@ static int pack_duration(char **buf, DurationMsg *cmsg) { return len; } -static void upack_duration(char **buf, DurationMsg *cmsg) { +static void upack_duration(char **buf, DurationMsg *cmsg) +{ cmsg->duration = upack_int(buf); } -static int pack_loc(char **buf, LocMsg *lmsg) { +static int pack_loc(char **buf, LocMsg *lmsg) +{ char *ptr; int len; @@ -261,12 +278,14 @@ static int pack_loc(char **buf, LocMsg *lmsg) { return len; } -static void upack_loc(char **buf, LocMsg *lmsg) { +static void upack_loc(char **buf, LocMsg *lmsg) +{ lmsg->file = upack_str(buf); lmsg->line = upack_int(buf); } -static int pack_fail(char **buf, FailMsg *fmsg) { +static int pack_fail(char **buf, FailMsg *fmsg) +{ char *ptr; int len; @@ -280,24 +299,28 @@ static int pack_fail(char **buf, FailMsg *fmsg) { return len; } -static void upack_fail(char **buf, FailMsg *fmsg) { +static void upack_fail(char **buf, FailMsg *fmsg) +{ fmsg->msg = upack_str(buf); fmsg->rtype = upack_int(buf); } -static void check_type(int type, const char *file, int line) { +static void check_type(int type, const char *file, int line) +{ if (type < 0 || type >= CK_MSG_LAST) eprintf("Bad message type arg %d", file, line, type); } #ifdef HAVE_PTHREAD_H static pthread_mutex_t ck_mutex_lock = PTHREAD_MUTEX_INITIALIZER; -static void ppack_cleanup(void *mutex) { +static void ppack_cleanup(void *mutex) +{ pthread_mutex_unlock((pthread_mutex_t *)mutex); } #endif #pragma GCC diagnostic ignored "-Wclobbered" -void ppack(FILE *fdes, enum ck_msg_type type, CheckMsg *msg) { +void ppack(FILE *fdes, enum ck_msg_type type, CheckMsg *msg) +{ char *buf = NULL; int n; ssize_t r; @@ -319,19 +342,22 @@ void ppack(FILE *fdes, enum ck_msg_type type, CheckMsg *msg) { free(buf); } -static int read_buf(FILE *fdes, int size, char *buf) { +static int read_buf(FILE *fdes, int size, char *buf) +{ int n; n = fread(buf, 1, size, fdes); - if (ferror(fdes)) { + if (ferror(fdes)) + { eprintf("Error in call to fread:", __FILE__, __LINE__ - 4); } return n; } -static int get_result(char *buf, RcvMsg *rmsg) { +static int get_result(char *buf, RcvMsg *rmsg) +{ enum ck_msg_type type; CheckMsg msg; int n; @@ -340,49 +366,64 @@ static int get_result(char *buf, RcvMsg *rmsg) { if (n == -1) eprintf("Error in call to upack", __FILE__, __LINE__ - 2); - if (type == CK_MSG_CTX) { + if (type == CK_MSG_CTX) + { CtxMsg *cmsg = (CtxMsg *)&msg; rcvmsg_update_ctx(rmsg, cmsg->ctx); - } else if (type == CK_MSG_LOC) { + } + else if (type == CK_MSG_LOC) + { LocMsg *lmsg = (LocMsg *)&msg; - if (rmsg->failctx == CK_CTX_INVALID) { + if (rmsg->failctx == CK_CTX_INVALID) + { rcvmsg_update_loc(rmsg, lmsg->file, lmsg->line); } free(lmsg->file); - } else if (type == CK_MSG_FAIL) { + } + else if (type == CK_MSG_FAIL) + { FailMsg *fmsg = (FailMsg *)&msg; - if (rmsg->msg == NULL) { + if (rmsg->msg == NULL) + { rmsg->msg = strdup(fmsg->msg); rmsg->rtype = fmsg->rtype; rmsg->failctx = rmsg->lastctx; - } else { + } + else + { /* Skip subsequent failure messages, only happens for CK_NOFORK */ } free(fmsg->msg); - } else if (type == CK_MSG_DURATION) { + } + else if (type == CK_MSG_DURATION) + { DurationMsg *cmsg = (DurationMsg *)&msg; rmsg->duration = cmsg->duration; - } else + } + else check_type(type, __FILE__, __LINE__); return n; } -static void reset_rcv_test(RcvMsg *rmsg) { +static void reset_rcv_test(RcvMsg *rmsg) +{ rmsg->test_line = -1; rmsg->test_file = NULL; } -static void reset_rcv_fixture(RcvMsg *rmsg) { +static void reset_rcv_fixture(RcvMsg *rmsg) +{ rmsg->fixture_line = -1; rmsg->fixture_file = NULL; } -static RcvMsg *rcvmsg_create(void) { +static RcvMsg *rcvmsg_create(void) +{ RcvMsg *rmsg; rmsg = (RcvMsg *)emalloc(sizeof(RcvMsg)); @@ -395,34 +436,42 @@ static RcvMsg *rcvmsg_create(void) { return rmsg; } -void rcvmsg_free(RcvMsg *rmsg) { +void rcvmsg_free(RcvMsg *rmsg) +{ free(rmsg->fixture_file); free(rmsg->test_file); free(rmsg->msg); free(rmsg); } -static void rcvmsg_update_ctx(RcvMsg *rmsg, enum ck_result_ctx ctx) { - if (rmsg->lastctx != CK_CTX_INVALID) { +static void rcvmsg_update_ctx(RcvMsg *rmsg, enum ck_result_ctx ctx) +{ + if (rmsg->lastctx != CK_CTX_INVALID) + { free(rmsg->fixture_file); reset_rcv_fixture(rmsg); } rmsg->lastctx = ctx; } -static void rcvmsg_update_loc(RcvMsg *rmsg, const char *file, int line) { - if (rmsg->lastctx == CK_CTX_TEST) { +static void rcvmsg_update_loc(RcvMsg *rmsg, const char *file, int line) +{ + if (rmsg->lastctx == CK_CTX_TEST) + { free(rmsg->test_file); rmsg->test_line = line; rmsg->test_file = strdup(file); - } else { + } + else + { free(rmsg->fixture_file); rmsg->fixture_line = line; rmsg->fixture_file = strdup(file); } } -RcvMsg *punpack(FILE *fdes) { +RcvMsg *punpack(FILE *fdes) +{ int nread, nparse, n; char *buf; RcvMsg *rmsg; @@ -435,14 +484,16 @@ RcvMsg *punpack(FILE *fdes) { nread = read_buf(fdes, CK_MAX_MSG_SIZE, buf); nparse = nread; /* While not all parsed */ - while (nparse > 0) { + while (nparse > 0) + { /* Parse one message */ n = get_result(buf, rmsg); nparse -= n; /* Move remaining data in buffer to the beginning */ memmove(buf, buf + n, nparse); /* If EOF has not been seen */ - if (nread > 0) { + if (nread > 0) + { /* Read more data into empty space at end of the buffer */ nread = read_buf(fdes, n, buf + nparse); nparse += nread; @@ -450,7 +501,8 @@ RcvMsg *punpack(FILE *fdes) { } free(buf); - if (rmsg->lastctx == CK_CTX_INVALID) { + if (rmsg->lastctx == CK_CTX_INVALID) + { free(rmsg); rmsg = NULL; } diff --git a/testing/backends/check/check_pack.h b/testing/backends/check/check_pack.h index d6a0cda8da..0dfb4c05d8 100644 --- a/testing/backends/check/check_pack.h +++ b/testing/backends/check/check_pack.h @@ -21,7 +21,8 @@ #ifndef CHECK_PACK_H #define CHECK_PACK_H -enum ck_msg_type { +enum ck_msg_type +{ CK_MSG_CTX, CK_MSG_FAIL, CK_MSG_LOC, @@ -29,21 +30,25 @@ enum ck_msg_type { CK_MSG_LAST }; -typedef struct CtxMsg { +typedef struct CtxMsg +{ enum ck_result_ctx ctx; } CtxMsg; -typedef struct LocMsg { +typedef struct LocMsg +{ int line; char *file; } LocMsg; -typedef struct FailMsg { +typedef struct FailMsg +{ int rtype; char *msg; } FailMsg; -typedef struct DurationMsg { +typedef struct DurationMsg +{ int duration; } DurationMsg; @@ -54,7 +59,8 @@ typedef union { DurationMsg duration_msg; } CheckMsg; -typedef struct RcvMsg { +typedef struct RcvMsg +{ enum ck_result_ctx lastctx; enum ck_result_ctx failctx; char *fixture_file; diff --git a/testing/backends/check/check_print.c b/testing/backends/check/check_print.c index 77b7ff1dbe..86fa287d6b 100644 --- a/testing/backends/check/check_print.c +++ b/testing/backends/check/check_print.c @@ -59,12 +59,15 @@ static void srunner_fprint_summary(FILE *file, SRunner *sr, static void srunner_fprint_results(FILE *file, SRunner *sr, enum print_output print_mode); -void srunner_print(SRunner *sr, enum print_output print_mode) { +void srunner_print(SRunner *sr, enum print_output print_mode) +{ srunner_fprint(stdout, sr, print_mode); } -void srunner_fprint(FILE *file, SRunner *sr, enum print_output print_mode) { - if (print_mode == CK_ENV) { +void srunner_fprint(FILE *file, SRunner *sr, enum print_output print_mode) +{ + if (print_mode == CK_ENV) + { print_mode = get_env_printmode(); } @@ -73,13 +76,15 @@ void srunner_fprint(FILE *file, SRunner *sr, enum print_output print_mode) { } static void srunner_fprint_summary(FILE *file, SRunner *sr, - enum print_output print_mode) { + enum print_output print_mode) +{ #if ENABLE_SUBUNIT if (print_mode == CK_SUBUNIT) return; #endif - if (print_mode >= CK_MINIMAL) { + if (print_mode >= CK_MINIMAL) + { char *str; str = sr_stat_str(sr); @@ -90,7 +95,8 @@ static void srunner_fprint_summary(FILE *file, SRunner *sr, } static void srunner_fprint_results(FILE *file, SRunner *sr, - enum print_output print_mode) { + enum print_output print_mode) +{ List *resultlst; #if ENABLE_SUBUNIT @@ -101,7 +107,8 @@ static void srunner_fprint_results(FILE *file, SRunner *sr, resultlst = sr->resultlst; for (check_list_front(resultlst); !check_list_at_end(resultlst); - check_list_advance(resultlst)) { + check_list_advance(resultlst)) + { TestResult *tr = (TestResult *)check_list_val(resultlst); tr_fprint(file, tr, print_mode); @@ -109,10 +116,13 @@ static void srunner_fprint_results(FILE *file, SRunner *sr, return; } -void fprint_xml_esc(FILE *file, const char *str) { - for (; *str != '\0'; str++) { +void fprint_xml_esc(FILE *file, const char *str) +{ + for (; *str != '\0'; str++) + { - switch (*str) { + switch (*str) + { /* handle special characters that must be escaped */ case '"': @@ -139,13 +149,16 @@ void fprint_xml_esc(FILE *file, const char *str) { } } -void tr_fprint(FILE *file, TestResult *tr, enum print_output print_mode) { - if (print_mode == CK_ENV) { +void tr_fprint(FILE *file, TestResult *tr, enum print_output print_mode) +{ + if (print_mode == CK_ENV) + { print_mode = get_env_printmode(); } if ((print_mode >= CK_VERBOSE && tr->rtype == CK_PASS) || - (tr->rtype != CK_PASS && print_mode >= CK_NORMAL)) { + (tr->rtype != CK_PASS && print_mode >= CK_NORMAL)) + { char *trstr = tr_str(tr); fprintf(file, "%s\n", trstr); @@ -154,13 +167,15 @@ void tr_fprint(FILE *file, TestResult *tr, enum print_output print_mode) { } void tr_xmlprint(FILE *file, TestResult *tr, - enum print_output print_mode CK_ATTRIBUTE_UNUSED) { + enum print_output print_mode CK_ATTRIBUTE_UNUSED) +{ char result[10]; char *path_name = NULL; char *file_name = NULL; char *slash = NULL; - switch (tr->rtype) { + switch (tr->rtype) + { case CK_PASS: snprintf(result, sizeof(result), "%s", "success"); break; @@ -179,16 +194,21 @@ void tr_xmlprint(FILE *file, TestResult *tr, break; } - if (tr->file) { + if (tr->file) + { slash = strrchr(tr->file, '/'); - if (slash == NULL) { + if (slash == NULL) + { slash = strrchr(tr->file, '\\'); } - if (slash == NULL) { + if (slash == NULL) + { path_name = strdup("."); file_name = tr->file; - } else { + } + else + { path_name = strdup(tr->file); path_name[slash - tr->file] = 0; /* Terminate the temporary string. */ file_name = slash + 1; @@ -216,7 +236,8 @@ void tr_xmlprint(FILE *file, TestResult *tr, free(path_name); } -enum print_output get_env_printmode(void) { +enum print_output get_env_printmode(void) +{ char *env = getenv("CK_VERBOSITY"); if (env == NULL) diff --git a/testing/backends/check/check_run.c b/testing/backends/check/check_run.c index 5df8a23e35..bc3927d657 100644 --- a/testing/backends/check/check_run.c +++ b/testing/backends/check/check_run.c @@ -68,7 +68,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // waitpid #endif extern char *strsignal(int); -enum rinfo { +enum rinfo +{ CK_R_SIG, CK_R_PASS, CK_R_EXIT, @@ -76,7 +77,12 @@ enum rinfo { CK_R_FAIL_FIXTURE }; -enum tf_type { CK_FORK_TEST, CK_NOFORK_TEST, CK_NOFORK_FIXTURE }; +enum tf_type +{ + CK_FORK_TEST, + CK_NOFORK_TEST, + CK_NOFORK_FIXTURE +}; /* all functions are defined in the same order they are declared. functions that depend on forking are gathered all together. @@ -124,22 +130,28 @@ static pid_t group_pid; static struct sigaction sigint_old_action; static struct sigaction sigterm_old_action; -static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) { - switch (sig_nr) { +static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) +{ + switch (sig_nr) + { case SIGALRM: alarm_received = 1; killpg(group_pid, SIGKILL); break; case SIGTERM: - case SIGINT: { + case SIGINT: + { pid_t own_group_pid; int child_sig = SIGTERM; - if (sig_nr == SIGINT) { + if (sig_nr == SIGINT) + { printf("received sig interrupt\n"); child_sig = SIGKILL; sigaction(SIGINT, &sigint_old_action, NULL); - } else { + } + else + { sigaction(SIGTERM, &sigterm_old_action, NULL); } @@ -161,7 +173,8 @@ static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) { #define MSG_LEN 100 -static void srunner_run_init(SRunner *sr, enum print_output print_mode) { +static void srunner_run_init(SRunner *sr, enum print_output print_mode) +{ set_fork_status(srunner_fork_status(sr)); setup_messaging(); srunner_init_logging(sr, print_mode); @@ -169,7 +182,8 @@ static void srunner_run_init(SRunner *sr, enum print_output print_mode) { } static void srunner_run_end(SRunner *sr, - enum print_output CK_ATTRIBUTE_UNUSED print_mode) { + enum print_output CK_ATTRIBUTE_UNUSED print_mode) +{ log_srunner_end(sr); srunner_end_logging(sr); teardown_messaging(); @@ -178,7 +192,8 @@ static void srunner_run_end(SRunner *sr, static void srunner_iterate_suites(SRunner *sr, const char *sname, const char *tcname, - enum print_output CK_ATTRIBUTE_UNUSED print_mode) { + enum print_output CK_ATTRIBUTE_UNUSED print_mode) +{ List *slst; List *tcl; TCase *tc; @@ -186,7 +201,8 @@ srunner_iterate_suites(SRunner *sr, const char *sname, const char *tcname, slst = sr->slst; for (check_list_front(slst); !check_list_at_end(slst); - check_list_advance(slst)) { + check_list_advance(slst)) + { Suite *s = (Suite *)check_list_val(slst); if (((sname != NULL) && (strcmp(sname, s->name) != 0)) || @@ -198,10 +214,12 @@ srunner_iterate_suites(SRunner *sr, const char *sname, const char *tcname, tcl = s->tclst; for (check_list_front(tcl); !check_list_at_end(tcl); - check_list_advance(tcl)) { + check_list_advance(tcl)) + { tc = (TCase *)check_list_val(tcl); - if ((tcname != NULL) && (strcmp(tcname, tc->name) != 0)) { + if ((tcname != NULL) && (strcmp(tcname, tc->name) != 0)) + { continue; } @@ -212,7 +230,8 @@ srunner_iterate_suites(SRunner *sr, const char *sname, const char *tcname, } } -static void srunner_iterate_tcase_tfuns(SRunner *sr, TCase *tc) { +static void srunner_iterate_tcase_tfuns(SRunner *sr, TCase *tc) +{ List *tfl; TF *tfun; TestResult *tr = NULL; @@ -220,14 +239,17 @@ static void srunner_iterate_tcase_tfuns(SRunner *sr, TCase *tc) { tfl = tc->tflst; for (check_list_front(tfl); !check_list_at_end(tfl); - check_list_advance(tfl)) { + check_list_advance(tfl)) + { int i; tfun = (TF *)check_list_val(tfl); - for (i = tfun->loop_start; i < tfun->loop_end; i++) { + for (i = tfun->loop_start; i < tfun->loop_end; i++) + { log_test_start(sr, tc, tfun); - switch (srunner_fork_status(sr)) { + switch (srunner_fork_status(sr)) + { case CK_FORK: #if defined(HAVE_FORK) && HAVE_FORK == 1 tr = tcase_run_tfun_fork(sr, tc, tfun, i); @@ -243,7 +265,8 @@ static void srunner_iterate_tcase_tfuns(SRunner *sr, TCase *tc) { eprintf("Bad fork status in SRunner", __FILE__, __LINE__); } - if (NULL != tr) { + if (NULL != tr) + { srunner_add_failure(sr, tr); log_test_end(sr, tr); } @@ -251,7 +274,8 @@ static void srunner_iterate_tcase_tfuns(SRunner *sr, TCase *tc) { } } -static void srunner_add_failure(SRunner *sr, TestResult *tr) { +static void srunner_add_failure(SRunner *sr, TestResult *tr) +{ check_list_add_end(sr->resultlst, tr); sr->stats->n_checked++; /* count checks during setup, test, and teardown */ if (tr->rtype == CK_FAILURE) @@ -263,28 +287,34 @@ static void srunner_add_failure(SRunner *sr, TestResult *tr) { static TestResult *srunner_run_setup(List *fixture_list, enum fork_status fork_usage, const char *test_name, - const char *setup_name) { + const char *setup_name) +{ TestResult *tr = NULL; Fixture *setup_fixture; - if (fork_usage == CK_FORK) { + if (fork_usage == CK_FORK) + { send_ctx_info(CK_CTX_SETUP); } for (check_list_front(fixture_list); !check_list_at_end(fixture_list); - check_list_advance(fixture_list)) { + check_list_advance(fixture_list)) + { setup_fixture = (Fixture *)check_list_val(fixture_list); - if (fork_usage == CK_NOFORK) { + if (fork_usage == CK_NOFORK) + { send_ctx_info(CK_CTX_SETUP); - if (0 == setjmp(error_jmp_buffer)) { + if (0 == setjmp(error_jmp_buffer)) + { setup_fixture->fun(); } /* Stop the setup and return the failure in nofork mode. */ tr = receive_result_info_nofork(test_name, setup_name, 0, -1); - if (tr->rtype != CK_PASS) { + if (tr->rtype != CK_PASS) + { break; } @@ -292,7 +322,9 @@ static TestResult *srunner_run_setup(List *fixture_list, free(tr->msg); free(tr); tr = NULL; - } else { + } + else + { setup_fixture->fun(); } } @@ -300,7 +332,8 @@ static TestResult *srunner_run_setup(List *fixture_list, return tr; } -static int srunner_run_unchecked_setup(SRunner *sr, TCase *tc) { +static int srunner_run_unchecked_setup(SRunner *sr, TCase *tc) +{ TestResult *tr = NULL; int rval = 1; @@ -309,7 +342,8 @@ static int srunner_run_unchecked_setup(SRunner *sr, TCase *tc) { srunner_run_setup(tc->unch_sflst, CK_NOFORK, tc->name, "unchecked_setup"); set_fork_status(srunner_fork_status(sr)); - if (tr != NULL && tr->rtype != CK_PASS) { + if (tr != NULL && tr->rtype != CK_PASS) + { srunner_add_failure(sr, tr); rval = 0; } @@ -317,7 +351,8 @@ static int srunner_run_unchecked_setup(SRunner *sr, TCase *tc) { return rval; } -static TestResult *tcase_run_checked_setup(SRunner *sr, TCase *tc) { +static TestResult *tcase_run_checked_setup(SRunner *sr, TCase *tc) +{ TestResult *tr = srunner_run_setup(tc->ch_sflst, srunner_fork_status(sr), tc->name, "checked_setup"); @@ -325,51 +360,66 @@ static TestResult *tcase_run_checked_setup(SRunner *sr, TCase *tc) { } static void srunner_run_teardown(List *fixture_list, - enum fork_status fork_usage) { + enum fork_status fork_usage) +{ Fixture *fixture; for (check_list_front(fixture_list); !check_list_at_end(fixture_list); - check_list_advance(fixture_list)) { + check_list_advance(fixture_list)) + { fixture = (Fixture *)check_list_val(fixture_list); send_ctx_info(CK_CTX_TEARDOWN); - if (fork_usage == CK_NOFORK) { - if (0 == setjmp(error_jmp_buffer)) { + if (fork_usage == CK_NOFORK) + { + if (0 == setjmp(error_jmp_buffer)) + { fixture->fun(); - } else { + } + else + { /* Abort the remaining teardowns */ break; } - } else { + } + else + { fixture->fun(); } } } -static void srunner_run_unchecked_teardown(SRunner *sr, TCase *tc) { +static void srunner_run_unchecked_teardown(SRunner *sr, TCase *tc) +{ srunner_run_teardown(tc->unch_tflst, srunner_fork_status(sr)); } -static void tcase_run_checked_teardown(TCase *tc) { +static void tcase_run_checked_teardown(TCase *tc) +{ srunner_run_teardown(tc->ch_tflst, CK_NOFORK); } -static void srunner_run_tcase(SRunner *sr, TCase *tc) { - if (srunner_run_unchecked_setup(sr, tc)) { +static void srunner_run_tcase(SRunner *sr, TCase *tc) +{ + if (srunner_run_unchecked_setup(sr, tc)) + { srunner_iterate_tcase_tfuns(sr, tc); srunner_run_unchecked_teardown(sr, tc); } } static TestResult *tcase_run_tfun_nofork(SRunner *sr, TCase *tc, TF *tfun, - int i) { + int i) +{ TestResult *tr; struct timespec ts_start = {0, 0}, ts_end = {0, 0}; tr = tcase_run_checked_setup(sr, tc); - if (tr == NULL) { + if (tr == NULL) + { clock_gettime(check_get_clockid(), &ts_start); - if (0 == setjmp(error_jmp_buffer)) { + if (0 == setjmp(error_jmp_buffer)) + { tfun->fn(i); } clock_gettime(check_get_clockid(), &ts_end); @@ -383,13 +433,17 @@ static TestResult *tcase_run_tfun_nofork(SRunner *sr, TCase *tc, TF *tfun, static TestResult *receive_result_info_nofork(const char *tcname, const char *tname, int iter, - int duration) { + int duration) +{ TestResult *tr; tr = receive_test_result(0); - if (tr == NULL) { + if (tr == NULL) + { eprintf("Failed to receive test result", __FILE__, __LINE__); - } else { + } + else + { tr->tcname = tcname; tr->tname = tname; tr->iter = iter; @@ -400,11 +454,15 @@ static TestResult *receive_result_info_nofork(const char *tcname, return tr; } -static void set_nofork_info(TestResult *tr) { - if (tr->msg == NULL) { +static void set_nofork_info(TestResult *tr) +{ + if (tr->msg == NULL) + { tr->rtype = CK_PASS; tr->msg = pass_msg(); - } else { + } + else + { tr->rtype = CK_FAILURE; } } @@ -413,7 +471,8 @@ static char *pass_msg(void) { return strdup("Passed"); } #if defined(HAVE_FORK) && HAVE_FORK == 1 static TestResult *tcase_run_tfun_fork(SRunner *sr, TCase *tc, TF *tfun, - int i) { + int i) +{ pid_t pid_w; pid_t pid; int status = 0; @@ -426,7 +485,8 @@ static TestResult *tcase_run_tfun_fork(SRunner *sr, TCase *tc, TF *tfun, pid = fork(); if (pid == -1) eprintf("Error in call to fork:", __FILE__, __LINE__ - 2); - if (pid == 0) { + if (pid == 0) + { setpgid(0, 0); group_pid = getpgrp(); tr = tcase_run_checked_setup(sr, tc); @@ -437,29 +497,38 @@ static TestResult *tcase_run_tfun_fork(SRunner *sr, TCase *tc, TF *tfun, tcase_run_checked_teardown(tc); send_duration_info(DIFF_IN_USEC(ts_start, ts_end)); exit(EXIT_SUCCESS); - } else { + } + else + { group_pid = pid; } alarm_received = 0; if (timer_create(check_get_clockid(), - NULL /* fire SIGALRM if timer expires */, &timerid) == 0) { + NULL /* fire SIGALRM if timer expires */, &timerid) == 0) + { /* Set the timer to fire once */ timer_spec.it_value = tc->timeout; timer_spec.it_interval.tv_sec = 0; timer_spec.it_interval.tv_nsec = 0; - if (timer_settime(timerid, 0, &timer_spec, NULL) == 0) { - do { + if (timer_settime(timerid, 0, &timer_spec, NULL) == 0) + { + do + { pid_w = waitpid(pid, &status, 0); } while (pid_w == -1); - } else { + } + else + { eprintf("Error in call to timer_settime:", __FILE__, __LINE__); } /* If the timer has not fired, disable it */ timer_delete(timerid); - } else { + } + else + { eprintf("Error in call to timer_create:", __FILE__, __LINE__); } @@ -472,13 +541,17 @@ static TestResult *tcase_run_tfun_fork(SRunner *sr, TCase *tc, TF *tfun, static TestResult *receive_result_info_fork(const char *tcname, const char *tname, int iter, int status, int expected_signal, - signed char allowed_exit_value) { + signed char allowed_exit_value) +{ TestResult *tr; tr = receive_test_result(waserror(status, expected_signal)); - if (tr == NULL) { + if (tr == NULL) + { eprintf("Failed to receive test result", __FILE__, __LINE__); - } else { + } + else + { tr->tcname = tcname; tr->tname = tname; tr->iter = iter; @@ -489,96 +562,134 @@ static TestResult *receive_result_info_fork(const char *tcname, } static void set_fork_info(TestResult *tr, int status, int signal_expected, - signed char allowed_exit_value) { + signed char allowed_exit_value) +{ int was_sig = WIFSIGNALED(status); int was_exit = WIFEXITED(status); signed char exit_status = WEXITSTATUS(status); int signal_received = WTERMSIG(status); - if (was_sig) { - if (signal_expected == signal_received) { - if (alarm_received) { + if (was_sig) + { + if (signal_expected == signal_received) + { + if (alarm_received) + { /* Got alarm instead of signal */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_error_msg(signal_received, signal_expected); - } else { + } + else + { tr->rtype = CK_PASS; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = pass_msg(); } - } else if (signal_expected != 0) { + } + else if (signal_expected != 0) + { /* signal received, but not the expected one */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_error_msg(signal_received, signal_expected); - } else { + } + else + { /* signal received and none expected */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_msg(signal_received); } - } else if (signal_expected == 0) { - if (was_exit && exit_status == allowed_exit_value) { + } + else if (signal_expected == 0) + { + if (was_exit && exit_status == allowed_exit_value) + { tr->rtype = CK_PASS; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = pass_msg(); - } else if (was_exit && exit_status != allowed_exit_value) { - if (tr->msg == NULL) { /* early exit */ + } + else if (was_exit && exit_status != allowed_exit_value) + { + if (tr->msg == NULL) + { /* early exit */ tr->rtype = CK_ERROR; tr->msg = exit_msg(exit_status); - } else { + } + else + { tr->rtype = CK_FAILURE; } } - } else { /* a signal was expected and none raised */ - if (was_exit) { - if (tr->msg != NULL) { + } + else + { /* a signal was expected and none raised */ + if (was_exit) + { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = exit_msg(exit_status); - if (exit_status == allowed_exit_value) { + if (exit_status == allowed_exit_value) + { tr->rtype = CK_FAILURE; /* normal exit status */ - } else { + } + else + { tr->rtype = CK_FAILURE; /* early exit */ } } } } -static char *signal_msg(int signal) { +static char *signal_msg(int signal) +{ char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ - if (alarm_received) { + if (alarm_received) + { snprintf(msg, MSG_LEN, "Test timeout expired"); - } else { + } + else + { snprintf(msg, MSG_LEN, "Received signal %d (%s)", signal, strsignal(signal)); } return msg; } -static char *signal_error_msg(int signal_received, int signal_expected) { +static char *signal_error_msg(int signal_received, int signal_expected) +{ char *sig_r_str; char *sig_e_str; char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ sig_r_str = strdup(strsignal(signal_received)); sig_e_str = strdup(strsignal(signal_expected)); - if (alarm_received) { + if (alarm_received) + { snprintf(msg, MSG_LEN, "Test timeout expired, expected signal %d (%s)", signal_expected, sig_e_str); - } else { + } + else + { snprintf(msg, MSG_LEN, "Received signal %d (%s), expected %d (%s)", signal_received, sig_r_str, signal_expected, sig_e_str); } @@ -587,14 +698,16 @@ static char *signal_error_msg(int signal_received, int signal_expected) { return msg; } -static char *exit_msg(int exitval) { +static char *exit_msg(int exitval) +{ char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ snprintf(msg, MSG_LEN, "Early exit with return value %d", exitval); return msg; } -static int waserror(int status, int signal_expected) { +static int waserror(int status, int signal_expected) +{ int was_sig = WIFSIGNALED(status); int was_exit = WIFEXITED(status); int exit_status = WEXITSTATUS(status); @@ -605,8 +718,10 @@ static int waserror(int status, int signal_expected) { } #endif /* HAVE_FORK */ -enum fork_status srunner_fork_status(SRunner *sr) { - if (sr->fstat == CK_FORK_GETENV) { +enum fork_status srunner_fork_status(SRunner *sr) +{ + if (sr->fstat == CK_FORK_GETENV) + { char *env = getenv("CK_FORK"); if (env == NULL) @@ -617,7 +732,8 @@ enum fork_status srunner_fork_status(SRunner *sr) { #endif if (strcmp(env, "no") == 0) return CK_NOFORK; - else { + else + { #if defined(HAVE_FORK) && HAVE_FORK == 1 return CK_FORK; #else /* HAVE_FORK */ @@ -625,14 +741,17 @@ enum fork_status srunner_fork_status(SRunner *sr) { return CK_NOFORK; #endif /* HAVE_FORK */ } - } else + } + else return sr->fstat; } -void srunner_set_fork_status(SRunner *sr, enum fork_status fstat) { +void srunner_set_fork_status(SRunner *sr, enum fork_status fstat) +{ #if !defined(HAVE_FORK) || HAVE_FORK == 0 /* If fork() is unavailable, do not allow a fork mode to be set */ - if (fstat != CK_NOFORK) { + if (fstat != CK_NOFORK) + { /* Overriding, as Check is not compiled with fork support. */ fstat = CK_NOFORK; } @@ -640,14 +759,16 @@ void srunner_set_fork_status(SRunner *sr, enum fork_status fstat) { sr->fstat = fstat; } -void srunner_run_all(SRunner *sr, enum print_output print_mode) { +void srunner_run_all(SRunner *sr, enum print_output print_mode) +{ srunner_run(sr, NULL, /* All test suites. */ NULL, /* All test cases. */ print_mode); } void srunner_run(SRunner *sr, const char *sname, const char *tcname, - enum print_output print_mode) { + enum print_output print_mode) +{ #if defined(HAVE_SIGACTION) && defined(HAVE_FORK) static struct sigaction sigalarm_old_action; static struct sigaction sigalarm_new_action; @@ -664,7 +785,8 @@ void srunner_run(SRunner *sr, const char *sname, const char *tcname, if (sr == NULL) return; - if (print_mode >= CK_LAST) { + if (print_mode >= CK_LAST) + { eprintf("Bad print_mode argument to srunner_run_all: %d", __FILE__, __LINE__, print_mode); } @@ -691,12 +813,14 @@ void srunner_run(SRunner *sr, const char *sname, const char *tcname, #endif /* HAVE_SIGACTION && HAVE_FORK */ } -pid_t check_fork(void) { +pid_t check_fork(void) +{ #if defined(HAVE_FORK) && HAVE_FORK == 1 pid_t pid = fork(); /* Set the process to a process group to be able to kill it easily. */ - if (pid >= 0) { + if (pid >= 0) + { setpgid(pid, group_pid); } return pid; @@ -706,16 +830,20 @@ pid_t check_fork(void) { #endif /* HAVE_FORK */ } -void check_waitpid_and_exit(pid_t pid CK_ATTRIBUTE_UNUSED) { +void check_waitpid_and_exit(pid_t pid CK_ATTRIBUTE_UNUSED) +{ #if defined(HAVE_FORK) && HAVE_FORK == 1 pid_t pid_w; int status; - if (pid > 0) { - do { + if (pid > 0) + { + do + { pid_w = waitpid(pid, &status, 0); } while (pid_w == -1); - if (waserror(status, 0)) { + if (waserror(status, 0)) + { exit(EXIT_FAILURE); } } diff --git a/testing/backends/check/check_str.c b/testing/backends/check/check_str.c index 47d5022d4d..84cf775389 100644 --- a/testing/backends/check/check_str.c +++ b/testing/backends/check/check_str.c @@ -56,7 +56,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static const char *tr_type_str(TestResult *tr); static int percent_passed(TestStats *t); -char *tr_str(TestResult *tr) { +char *tr_str(TestResult *tr) +{ const char *exact_msg; char *rstr; @@ -69,7 +70,8 @@ char *tr_str(TestResult *tr) { return rstr; } -char *tr_short_str(TestResult *tr) { +char *tr_short_str(TestResult *tr) +{ const char *exact_msg; char *rstr; @@ -81,7 +83,8 @@ char *tr_short_str(TestResult *tr) { return rstr; } -char *sr_stat_str(SRunner *sr) { +char *sr_stat_str(SRunner *sr) +{ char *str; TestStats *ts; @@ -94,7 +97,8 @@ char *sr_stat_str(SRunner *sr) { return str; } -char *ck_strdup_printf(const char *fmt, ...) { +char *ck_strdup_printf(const char *fmt, ...) +{ /* Guess we need no more than 100 bytes. */ int n; size_t size = 100; @@ -103,7 +107,8 @@ char *ck_strdup_printf(const char *fmt, ...) { p = (char *)emalloc(size); - while (1) { + while (1) + { /* Try to print in the allocated space. */ va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); @@ -122,23 +127,27 @@ char *ck_strdup_printf(const char *fmt, ...) { } } -static const char *tr_type_str(TestResult *tr) { +static const char *tr_type_str(TestResult *tr) +{ const char *str = NULL; - if (tr->ctx == CK_CTX_TEST) { + if (tr->ctx == CK_CTX_TEST) + { if (tr->rtype == CK_PASS) str = "P"; else if (tr->rtype == CK_FAILURE) str = "F"; else if (tr->rtype == CK_ERROR) str = "E"; - } else + } + else str = "S"; return str; } -static int percent_passed(TestStats *t) { +static int percent_passed(TestStats *t) +{ if (t->n_failed == 0 && t->n_errors == 0) return 100; else if (t->n_checked == 0) diff --git a/testing/backends/check/lib/libcompat.c b/testing/backends/check/lib/libcompat.c index bf8c2bde1f..0db772fd8d 100644 --- a/testing/backends/check/lib/libcompat.c +++ b/testing/backends/check/lib/libcompat.c @@ -25,7 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "libcompat.h" /* silence warnings about an empty library */ -void ck_do_nothing(void) { +void ck_do_nothing(void) +{ assert(0); /* diff --git a/testing/backends/check/lib/libcompat.h b/testing/backends/check/lib/libcompat.h index 2d16dc5335..a7ae866d45 100644 --- a/testing/backends/check/lib/libcompat.h +++ b/testing/backends/check/lib/libcompat.h @@ -6,7 +6,7 @@ #endif #if defined(__GNUC__) && defined(__GNUC_MINOR__) -#define GCC_VERSION_AT_LEAST(major, minor) \ +#define GCC_VERSION_AT_LEAST(major, minor) \ ((__GNUC__ > (major)) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) #else #define GCC_VERSION_AT_LEAST(major, minor) 0 @@ -141,7 +141,8 @@ * specified in seconds and nanoseconds. If it is not defined in * time.g, then we need to define it here */ -struct timespec { +struct timespec +{ time_t tv_sec; long tv_nsec; }; @@ -152,7 +153,8 @@ struct timespec { * The following structure is defined in POSIX.1b for timer start values and * intervals. If it is not defined in time.h, then we need to define it here. */ -struct itimerspec { +struct itimerspec +{ struct timespec it_interval; struct timespec it_value; }; @@ -166,7 +168,9 @@ struct itimerspec { struct sigevent; #ifdef _WIN32 -struct __timer_t {}; +struct __timer_t +{ +}; typedef struct __timer_t timer_t; #endif diff --git a/testing/base_backend.c b/testing/base_backend.c index ef77a3a572..bf23f43d40 100644 --- a/testing/base_backend.c +++ b/testing/base_backend.c @@ -32,7 +32,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include void __assert_fail(const char *__assertion, const char *__file, - ASSERT_LINE_TYPE __line, const char *__function) { + ASSERT_LINE_TYPE __line, const char *__function) +{ printf(" .-----------------------------------. \n" " | Assertion failed during test | \n" " '-----------------------------------' \n" @@ -45,7 +46,8 @@ void __assert_fail(const char *__assertion, const char *__file, } void __test_abort(int code, const char *__msg, const char *__file, - unsigned int __line, const char *__function) { + unsigned int __line, const char *__function) +{ printf(" .-----------------------------------. \n" " | TEST ABORTED | \n" " '-----------------------------------' \n" diff --git a/testing/check_backend.c b/testing/check_backend.c index c873e4cb7e..021e6787ed 100644 --- a/testing/check_backend.c +++ b/testing/check_backend.c @@ -95,19 +95,23 @@ extern void *erealloc(void *, size_t n); static int out_fd = -1; static fpos_t out_pos; -static FILE *switchStdout(const char *newStream) { +static FILE *switchStdout(const char *newStream) +{ fflush(stdout); fgetpos(stdout, &out_pos); out_fd = dup(fileno(stdout)); - if (newStream) { + if (newStream) + { if (freopen(newStream, "w", stdout) == NULL) perror("Error redirecting stdout\n"); - } else + } + else fclose(stdout); return fdopen(out_fd, "w"); } -static void revertStdout() { +static void revertStdout() +{ if (out_fd < 0) return; fflush(stdout); @@ -124,20 +128,26 @@ static void revertStdout() { /// Signal handler for the proces created by test fork /// #ifdef HAVE_FORK -static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) { - switch (sig_nr) { +static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) +{ + switch (sig_nr) + { case SIGALRM: alarm_received = 1; killpg(group_pid, SIGKILL); break; case SIGTERM: - case SIGINT: { + case SIGINT: + { pid_t own_group_pid; int child_sig = SIGTERM; - if (sig_nr == SIGINT) { + if (sig_nr == SIGINT) + { child_sig = SIGKILL; sigaction(SIGINT, &sigint_old_action, NULL); - } else { + } + else + { sigaction(SIGTERM, &sigterm_old_action, NULL); } killpg(group_pid, child_sig); @@ -163,7 +173,8 @@ static void CK_ATTRIBUTE_UNUSED sig_handler(int sig_nr) { /// \brief __ck_assert_fail /// -void __test_assert_fail(const char *file, int line, const char *expr, ...) { +void __test_assert_fail(const char *file, int line, const char *expr, ...) +{ const char *msg; va_list ap; char buf[BUFSIZ]; @@ -172,20 +183,26 @@ void __test_assert_fail(const char *file, int line, const char *expr, ...) { send_loc_info(file, line); va_start(ap, expr); msg = (const char *)va_arg(ap, char *); - if (msg != NULL) { + if (msg != NULL) + { vsnprintf(buf, BUFSIZ, msg, ap); to_send = buf; - } else { + } + else + { to_send = expr; } va_end(ap); send_failure_info(to_send, CK_FAILURE); - if (cur_fork_status() == CK_FORK && group_pid) { + if (cur_fork_status() == CK_FORK && group_pid) + { #ifdef HAVE_FORK _exit(1); #endif /* HAVE_FORK */ - } else { + } + else + { __test_end(); _exit(1); } @@ -197,7 +214,8 @@ void __test_assert_fail(const char *file, int line, const char *expr, ...) { void __mark_point(const char *__assertion, const char *__file, ASSERT_LINE_TYPE __line, - const char *__function __attribute__((unused))) { + const char *__function __attribute__((unused))) +{ if (!suite) __test_init(__assertion, __file, __line); send_loc_info(__file, __line); @@ -209,7 +227,8 @@ void __mark_point(const char *__assertion, const char *__file, void __assert_fail(const char *__assertion, const char *__file, ASSERT_LINE_TYPE __line, - const char *__function __attribute__((unused))) { + const char *__function __attribute__((unused))) +{ if (!suite) __test_init(__assertion, __file, __line); __test_assert_fail(__file, __line, __assertion, NULL); @@ -219,7 +238,8 @@ void __assert_fail(const char *__assertion, const char *__file, abort(); } -static char *pass_msg(void) { +static char *pass_msg(void) +{ if (custom_pass_msg) return custom_pass_msg; else @@ -244,13 +264,17 @@ static int waserror(int status, int expected_signal); static TestResult *receive_result_info_fork(const char *tcname, const char *tname, int iter, int status, int expected_signal, - signed char allowed_exit_value) { + signed char allowed_exit_value) +{ TestResult *tr; tr = receive_test_result(waserror(status, expected_signal)); - if (tr == NULL) { + if (tr == NULL) + { eprintf("Failed to receive test result", __FILE__, __LINE__); - } else { + } + else + { tr->tcname = tcname; tr->tname = tname; tr->iter = iter; @@ -261,7 +285,8 @@ static TestResult *receive_result_info_fork(const char *tcname, } static void set_fork_info(TestResult *tr, int status, int signal_expected, - signed char allowed_exit_value) { + signed char allowed_exit_value) +{ // nonzero value if the child process terminated because it received a // signal that was not handled int was_sig = WIFSIGNALED(status); @@ -280,33 +305,46 @@ static void set_fork_info(TestResult *tr, int status, int signal_expected, // true. int signal_received = WTERMSIG(status); - if (was_sig) { - if (signal_expected == signal_received) { - if (alarm_received) { + if (was_sig) + { + if (signal_expected == signal_received) + { + if (alarm_received) + { /* Got alarm instead of signal */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_error_msg(signal_received, signal_expected); - } else { + } + else + { tr->rtype = CK_PASS; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = pass_msg(); } - } else if (signal_expected != 0) { + } + else if (signal_expected != 0) + { /* signal received, but not the expected one */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_error_msg(signal_received, signal_expected); - } else { + } + else + { /* signal received and none expected */ tr->rtype = CK_ERROR; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = signal_msg(signal_received); @@ -314,63 +352,85 @@ static void set_fork_info(TestResult *tr, int status, int signal_expected, } // no signal .. (child exited by itself) - else if (signal_expected == 0) { - if (was_exit && exit_status == allowed_exit_value) { + else if (signal_expected == 0) + { + if (was_exit && exit_status == allowed_exit_value) + { tr->rtype = CK_PASS; - if (tr->msg != NULL) { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = pass_msg(); - } else if (was_exit && exit_status != allowed_exit_value) { - if (tr->rtype == CK_TEST_RESULT_INVALID) { /* early exit */ + } + else if (was_exit && exit_status != allowed_exit_value) + { + if (tr->rtype == CK_TEST_RESULT_INVALID) + { /* early exit */ tr->rtype = CK_ERROR; tr->msg = exit_msg(exit_status); error_code = exit_status; - } else { + } + else + { // tr->rtype = CK_FAILURE; error_code = exit_status; } } } - else { /* a signal was expected and none raised */ - if (was_exit) { - if (tr->msg != NULL) { + else + { /* a signal was expected and none raised */ + if (was_exit) + { + if (tr->msg != NULL) + { free(tr->msg); } tr->msg = exit_msg(exit_status); - if (exit_status == allowed_exit_value) { + if (exit_status == allowed_exit_value) + { tr->rtype = CK_FAILURE; /* normal exit status */ - } else { + } + else + { tr->rtype = CK_FAILURE; /* early exit */ } } } } -static char *signal_msg(int signal) { +static char *signal_msg(int signal) +{ char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ - if (alarm_received) { + if (alarm_received) + { snprintf(msg, MSG_LEN, "Test timeout expired"); - } else { + } + else + { snprintf(msg, MSG_LEN, "Received signal %d (%s)", signal, strsignal(signal)); } return msg; } -static char *signal_error_msg(int signal_received, int signal_expected) { +static char *signal_error_msg(int signal_received, int signal_expected) +{ char *sig_r_str; char *sig_e_str; char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ sig_r_str = strdup(strsignal(signal_received)); sig_e_str = strdup(strsignal(signal_expected)); - if (alarm_received) { + if (alarm_received) + { snprintf(msg, MSG_LEN, "Test timeout expired, expected signal %d (%s)", signal_expected, sig_e_str); - } else { + } + else + { snprintf(msg, MSG_LEN, "Received signal %d (%s), expected %d (%s)", signal_received, sig_r_str, signal_expected, sig_e_str); } @@ -379,14 +439,16 @@ static char *signal_error_msg(int signal_received, int signal_expected) { return msg; } -static char *exit_msg(int exitval) { +static char *exit_msg(int exitval) +{ char *msg = (char *)emalloc(MSG_LEN); /* free'd by caller */ snprintf(msg, MSG_LEN, "Early exit with return value %d", exitval); return msg; } -static int waserror(int status, int signal_expected) { +static int waserror(int status, int signal_expected) +{ int was_sig = WIFSIGNALED(status); int was_exit = WIFEXITED(status); int exit_status = WEXITSTATUS(status); @@ -401,20 +463,25 @@ static int waserror(int status, int signal_expected) { // nofork //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static void set_nofork_info(TestResult *tr) { +static void set_nofork_info(TestResult *tr) +{ if (tr->msg == NULL && tr->rtype == CK_PASS) tr->msg = pass_msg(); } static TestResult *receive_result_info_nofork(const char *tcname, const char *tname, int iter, - int duration) { + int duration) +{ TestResult *tr; tr = receive_test_result(0); - if (tr == NULL) { + if (tr == NULL) + { eprintf("Failed to receive test result", __FILE__, __LINE__); - } else { + } + else + { tr->tcname = tcname; tr->tname = tname; tr->iter = iter; @@ -425,7 +492,8 @@ static TestResult *receive_result_info_nofork(const char *tcname, return tr; } -static void srunner_add_failure(SRunner *sr, TestResult *tr) { +static void srunner_add_failure(SRunner *sr, TestResult *tr) +{ check_list_add_end(sr->resultlst, tr); sr->stats->n_checked++; /* count checks during setup, test, and teardown */ if (tr->rtype == CK_FAILURE) @@ -435,19 +503,22 @@ static void srunner_add_failure(SRunner *sr, TestResult *tr) { } static void srunner_run_end(SRunner *sr, - enum print_output CK_ATTRIBUTE_UNUSED print_mode) { + enum print_output CK_ATTRIBUTE_UNUSED print_mode) +{ log_srunner_end(sr); srunner_end_logging(sr); teardown_messaging(); set_fork_status(CK_FORK); } -static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) { +static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) +{ List *l; Log *lg; l = sr->loglst; - for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) { + for (check_list_front(l); !check_list_at_end(l); check_list_advance(l)) + { lg = (Log *)check_list_val(l); fflush(lg->lfile); lg->lfun(sr, lg->lfile, lg->mode, obj, evt); @@ -467,19 +538,23 @@ static void srunner_send_evt(SRunner *sr, void *obj, enum cl_event evt) { static enum print_output print_mode = CK_NORMAL; -static int find_first(const char *str, const char *pat) { +static int find_first(const char *str, const char *pat) +{ return strstr(str, pat) == str; } -void __test_init(const char *test_name, const char *file, const int line) { +void __test_init(const char *test_name, const char *file, const int line) +{ - if (!suite) { + if (!suite) + { suite = suite_create(file); runner = srunner_create(suite); // print mode normal by default // char *env = getenv("TEST_MODE"); - if (env) { + if (env) + { if (strcmp(env, "silent") == 0) print_mode = CK_SILENT; if (strcmp(env, "minimal") == 0) @@ -504,7 +579,8 @@ void __test_init(const char *test_name, const char *file, const int line) { // the standard output format is taken from the frist item in // TEST_FORMAT string - if (format) { + if (format) + { if (find_first(format, "log") || find_first(format, "LOG")) srunner_register_lfun(runner, stdout, 0, stdout_lfun, print_mode); else if (find_first(format, "tap") || find_first(format, "TAP")) @@ -513,7 +589,9 @@ void __test_init(const char *test_name, const char *file, const int line) { else if (find_first(format, "xml") || find_first(format, "XML")) srunner_register_lfun(runner, switchStdout(out_file), 0, xml_lfun, print_mode); - } else { + } + else + { // default to plain log format // srunner_register_lfun(runner, stdout, 0, lfile_lfun, print_mode); } @@ -521,12 +599,14 @@ void __test_init(const char *test_name, const char *file, const int line) { // if any of TEST_TAPFILE or TEST_XMLFILE is given in env further // logger are instanced pointing to specified files. - if ((out_file = getenv("TEST_TAPFILE")) != NULL) { + if ((out_file = getenv("TEST_TAPFILE")) != NULL) + { FILE *f = fopen(out_file, "w"); if (f) srunner_register_lfun(runner, f, 0, tap_lfun, print_mode); } - if ((out_file = getenv("TEST_XMLFILE")) != NULL) { + if ((out_file = getenv("TEST_XMLFILE")) != NULL) + { FILE *f = fopen(out_file, "w"); if (f) srunner_register_lfun(runner, f, 0, xml_lfun, print_mode); @@ -552,10 +632,12 @@ void __test_init(const char *test_name, const char *file, const int line) { // SET tcase TIMEOUT // tcase_set_timeout(tcase, default_timeout); char *time_unit = getenv("TEST_TIMEUNIT"); - if (time_unit != NULL) { + if (time_unit != NULL) + { char *endptr = NULL; double tu = strtod(time_unit, &endptr); - if (tu >= 0 && endptr != time_unit && (*endptr) == '\0') { + if (tu >= 0 && endptr != time_unit && (*endptr) == '\0') + { tcase_set_timeout(tcase, default_timeout * tu); } } @@ -564,7 +646,8 @@ void __test_init(const char *test_name, const char *file, const int line) { suite_add_tcase(suite, tcase); #ifdef HAVE_FORK - if (cur_fork_status() == CK_FORK) { + if (cur_fork_status() == CK_FORK) + { // SIGALRM // memset(&sigalarm_new_action, 0, sizeof(sigalarm_new_action)); @@ -598,19 +681,24 @@ void __test_timeout(double seconds) { default_timeout = seconds; } // START TEST //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int __setup_parent() { +int __setup_parent() +{ // FORK // #ifdef HAVE_FORK - if (cur_fork_status() == CK_FORK) { + if (cur_fork_status() == CK_FORK) + { pid_t pid = fork(); if (pid == -1) // error forking // eprintf("Error forking to a new process:", __FILE__, __LINE__); - else if (pid == 0) { + else if (pid == 0) + { return 0; // continue on child // - } else { + } + else + { group_pid = pid; timer_t timerid; @@ -618,23 +706,27 @@ int __setup_parent() { int status = 0; alarm_received = 0; - if (timer_create(check_get_clockid(), NULL, &timerid) == 0) { + if (timer_create(check_get_clockid(), NULL, &timerid) == 0) + { /* Set the timer to fire once */ timer_spec.it_value = tcase->timeout; timer_spec.it_interval.tv_sec = 0; timer_spec.it_interval.tv_nsec = 0; - if (timer_settime(timerid, 0, &timer_spec, NULL) == 0) { + if (timer_settime(timerid, 0, &timer_spec, NULL) == 0) + { pid_t pid_w; do pid_w = waitpid(group_pid, &status, 0); while (pid_w == -1); - } else + } + else // settime failed // eprintf("Error in call to timer_settime:", __FILE__, __LINE__); /* If the timer has not fired, disable it */ timer_delete(timerid); - } else + } + else // create timer failed // eprintf("Error in call to timer_create:", __FILE__, __LINE__); @@ -651,15 +743,18 @@ int __setup_parent() { srunner_send_evt(runner, tr, CLEND_T); return 1; } - } else + } + else #endif // child here or no fork available return 0; } -int __setup_child() { +int __setup_child() +{ #ifdef HAVE_FORK - if (cur_fork_status() == CK_FORK) { + if (cur_fork_status() == CK_FORK) + { setpgid(0, 0); group_pid = getpgrp(); return 1; @@ -673,14 +768,18 @@ int __setup_child() { // END TEST ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void __test_end() { +void __test_end() +{ // if forked // #ifdef HAVE_FORK - if (cur_fork_status() == CK_FORK) { - if (group_pid) { + if (cur_fork_status() == CK_FORK) + { + if (group_pid) + { // child _exit(0); - } else + } + else // parent return; } @@ -696,15 +795,18 @@ void __test_end() { // EXIT FUNCTION ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void __test_exit() { +void __test_exit() +{ // if we are on child silently exit // #ifdef HAVE_FORK - if (cur_fork_status() == CK_FORK && group_pid) { + if (cur_fork_status() == CK_FORK && group_pid) + { _exit(0); } #endif int _nerr = 0; - if (runner && suite) { + if (runner && suite) + { log_suite_end(runner, suite); srunner_run_end(runner, CK_VERBOSE); _nerr = srunner_ntests_failed(runner); @@ -720,7 +822,8 @@ void __test_exit() { // Force exit with custo signal // void __test_abort(int code, const char *__msg, const char *__file, - unsigned int __line, const char *__function) { + unsigned int __line, const char *__function) +{ // TODO: fix this with proper enum related to test_driver error_code = code; if (tcase) @@ -728,15 +831,19 @@ void __test_abort(int code, const char *__msg, const char *__file, else __mark_point("test aborted", __file, __line, __function); - switch (code) { + switch (code) + { case 77: custom_pass_msg = strdup(__msg); send_failure_info(__msg, CK_SKIP); - if (cur_fork_status() == CK_FORK && group_pid) { + if (cur_fork_status() == CK_FORK && group_pid) + { #ifdef HAVE_FORK _exit(code); #endif /* HAVE_FORK */ - } else { + } + else + { TestResult *tr; tr = receive_result_info_nofork(tcase->name, "test_main", 0, 0); if (tr) @@ -756,10 +863,14 @@ void __test_abort(int code, const char *__msg, const char *__file, // FORK SET FUNCTION ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void __test_setfork(int value) { - if (value) { +void __test_setfork(int value) +{ + if (value) + { set_fork_status(CK_FORK); - } else { + } + else + { set_fork_status(CK_NOFORK); } } diff --git a/testing/selftest/error_test.c b/testing/selftest/error_test.c index 0329500e5a..ba46eacc93 100644 --- a/testing/selftest/error_test.c +++ b/testing/selftest/error_test.c @@ -25,6 +25,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing.h" int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ ABORT_TEST(" test abort by user "); } diff --git a/testing/selftest/example.c b/testing/selftest/example.c index e3d99e8c52..3767d8dc63 100644 --- a/testing/selftest/example.c +++ b/testing/selftest/example.c @@ -38,7 +38,8 @@ void external_test(); //////////////////////////////////////////////////////////////////////////////// int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(test 1); printf("test1\n"); @@ -54,7 +55,8 @@ int main(int argc __attribute__((unused)), END_TESTING; // test block explicit // - BEGIN_TESTING(example2) { + BEGIN_TESTING(example2) + { int a, *b; memcpy(b, &a, 10000000000); printf("I should be in segfault here...\n"); @@ -64,7 +66,8 @@ int main(int argc __attribute__((unused)), // start testing without fork // TEST_FORK(0); - BEGIN_TESTING(example3) { + BEGIN_TESTING(example3) + { int c = 1; TEST0(c == 0 && "false"); test_pass_function(); @@ -75,7 +78,8 @@ int main(int argc __attribute__((unused)), external_test(); TEST_FORK(1); - BEGIN_TESTING(timeout) { + BEGIN_TESTING(timeout) + { printf(" ... child 3 ... \n"); sleep(30); } @@ -106,7 +110,8 @@ void test_fail_function() { TEST1(0 && "no passing external function"); } /// inside another test as tests can not be nested. /// -void external_test() { +void external_test() +{ BEGIN_TESTING(external_test); printf(" ... child 4 ... \n"); int external_test = 0; diff --git a/testing/selftest/example2.c b/testing/selftest/example2.c index 0cda1604c6..f27d0ce993 100644 --- a/testing/selftest/example2.c +++ b/testing/selftest/example2.c @@ -28,8 +28,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { - BEGIN_TESTING(example2 fail 1) { + char *argv[] __attribute__((unused))) +{ + BEGIN_TESTING(example2 fail 1) + { // // generate a leak // // char * p = (char *)malloc(1234); // strcpy(p,"string lost\n"); diff --git a/testing/selftest/example3.cpp b/testing/selftest/example3.cpp index 6ae690892d..5844e5ab6b 100644 --- a/testing/selftest/example3.cpp +++ b/testing/selftest/example3.cpp @@ -27,7 +27,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing.h" -class MyTestPersonalClass { +class MyTestPersonalClass +{ int a, b; public: @@ -37,7 +38,8 @@ class MyTestPersonalClass { }; int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(test cpp); std::cout << "Hello Test!\n"; diff --git a/testing/selftest/example4.c b/testing/selftest/example4.c index 97445c6c24..32c5c2a983 100644 --- a/testing/selftest/example4.c +++ b/testing/selftest/example4.c @@ -27,9 +27,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ TEST_FORK(0); - BEGIN_TESTING(no fork success) { + BEGIN_TESTING(no fork success) + { printf("Hello successfull test\n"); int success = 1; TEST1(success == 1); @@ -37,7 +39,8 @@ int main(int argc __attribute__((unused)), END_TESTING; TEST_FORK(1); - BEGIN_TESTING(yes fork fail) { + BEGIN_TESTING(yes fork fail) + { printf("Hello successfull test\n"); int success = 0; TEST1(success == 1); @@ -45,7 +48,8 @@ int main(int argc __attribute__((unused)), END_TESTING; TEST_FORK(0); - BEGIN_TESTING(no fork success) { + BEGIN_TESTING(no fork success) + { printf("Hello successfull test\n"); int success = 1; TEST1(success == 1); diff --git a/testing/selftest/example_assert.c b/testing/selftest/example_assert.c index 7de2c51579..ff298f8b74 100644 --- a/testing/selftest/example_assert.c +++ b/testing/selftest/example_assert.c @@ -29,7 +29,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // extern void generate_false_assert(); int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(ok); int a = 1; TEST1(a == 1); diff --git a/testing/selftest/fork_fail.c b/testing/selftest/fork_fail.c index ef838ecc79..1e986a9986 100644 --- a/testing/selftest/fork_fail.c +++ b/testing/selftest/fork_fail.c @@ -25,7 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(fork fail); #ifdef _WIN32 SKIP_TEST("Skipping fork tests under wine"); diff --git a/testing/selftest/fork_success.c b/testing/selftest/fork_success.c index f86764da6b..f4f2fb6676 100644 --- a/testing/selftest/fork_success.c +++ b/testing/selftest/fork_success.c @@ -26,7 +26,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(fork success); #ifdef _WIN32 SKIP_TEST("Skipping fork tests under wine"); diff --git a/testing/selftest/leak_test.c b/testing/selftest/leak_test.c index ffafb6405b..42dd74215a 100644 --- a/testing/selftest/leak_test.c +++ b/testing/selftest/leak_test.c @@ -29,15 +29,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing.h" int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ if (!getenv("VALGRIND_TOOL") || strcmp("memcheck", getenv("VALGRIND_TOOL"))) SKIP_TEST("This test is supposed to run with valgrind memcheck"); BEGIN_TESTING(leak test); volatile int undef; - if (undef) { + if (undef) + { printf("."); - } else { + } + else + { printf(","); } TEST1(1); diff --git a/testing/selftest/mdstestdummy.h b/testing/selftest/mdstestdummy.h index 38605c7e4d..6a95256d4f 100644 --- a/testing/selftest/mdstestdummy.h +++ b/testing/selftest/mdstestdummy.h @@ -2,12 +2,13 @@ #define MDSTESTDUMMY_H #if defined __cplusplus -extern "C" { +extern "C" +{ #endif -void generate_false_assert(); + void generate_false_assert(); -void generate_true_assert(); + void generate_true_assert(); #if defined __cplusplus } diff --git a/testing/selftest/skip_test.c b/testing/selftest/skip_test.c index 8e6241bf4c..bc1d4bea59 100644 --- a/testing/selftest/skip_test.c +++ b/testing/selftest/skip_test.c @@ -26,7 +26,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing.h" int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ SKIP_TEST("test skip by user"); BEGIN_TESTING(skip test); END_TESTING; diff --git a/testing/selftest/test_options.c b/testing/selftest/test_options.c index f809025077..bf1edbdc6a 100644 --- a/testing/selftest/test_options.c +++ b/testing/selftest/test_options.c @@ -26,7 +26,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(1); TEST1(1); END_TESTING; diff --git a/testing/selftest/timeout_fail.c b/testing/selftest/timeout_fail.c index 61ae251e9c..6b28b633f8 100644 --- a/testing/selftest/timeout_fail.c +++ b/testing/selftest/timeout_fail.c @@ -37,7 +37,8 @@ int main() { SKIP_TEST("current test is not performed on windows"); } #endif int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ #if defined(__has_feature) #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) diff --git a/testing/selftest/timeout_success.c b/testing/selftest/timeout_success.c index 97d38f4061..2ab95aff4b 100644 --- a/testing/selftest/timeout_success.c +++ b/testing/selftest/timeout_success.c @@ -37,7 +37,8 @@ int main() { SKIP_TEST("current test is not performed on windows"); } #endif int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ #if defined(__has_feature) #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) diff --git a/testing/testing.h b/testing/testing.h index 33a09ad557..768808c977 100644 --- a/testing/testing.h +++ b/testing/testing.h @@ -36,22 +36,13 @@ // ASSERT //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /* -//# define assert(expr) \ -// ((expr) \ -// ? __ASSERT_VOID_CAST (0) \ -// : __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION)) +//# define assert(expr) ((expr) ? __ASSERT_VOID_CAST (0) : __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION)) -//#define assert(expr) \ -// ((expr) \ -// ? __mark_point (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) \ -// : __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION)) +//#define assert(expr) ((expr) ? __mark_point (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) : __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION)) -//#define assert_msg(expr, ...) \ -// (expr) ? \ -// _mark_point(__FILE__, __LINE__) : \ -// __assert_fail(expr, __FILE__, __LINE__, __ASSERT_FUNCTION) +//#define assert_msg(expr, ...) (expr) ? _mark_point(__FILE__, __LINE__) : __assert_fail(expr, __FILE__, __LINE__, __ASSERT_FUNCTION) */ #ifndef __ASSERT_FUNCTION @@ -64,34 +55,38 @@ #if defined __cplusplus // Assertion fail declaration as found in assert.h // -extern "C" { +extern "C" +{ #endif -EXPORT void __assert_fail(const char *__assertion, const char *__file, - ASSERT_LINE_TYPE __line, - const char *__function) __THROW - __attribute__((__noreturn__)); + EXPORT void __assert_fail(const char *__assertion, const char *__file, + ASSERT_LINE_TYPE __line, + const char *__function) __THROW + __attribute__((__noreturn__)); #ifdef _TESTING -EXPORT void __mark_point(const char *__assertion, const char *__file, - ASSERT_LINE_TYPE __line, const char *__function); - -EXPORT void __test_setfork(const int value); -EXPORT void __test_init(const char *test_name, const char *file, - const int line); -EXPORT void __test_end(); -EXPORT int __setup_parent(); -EXPORT int __setup_child(); -EXPORT void __test_assert_fail(const char *file, int line, const char *expr, - ...); -EXPORT void __test_exit() __attribute__((__noreturn__)); -EXPORT void __test_abort(int code, const char *__msg, const char *__file, - unsigned int __line, const char *__function); -EXPORT void __test_timeout(double seconds); + EXPORT void __mark_point(const char *__assertion, const char *__file, + ASSERT_LINE_TYPE __line, const char *__function); + + EXPORT void __test_setfork(const int value); + EXPORT void __test_init(const char *test_name, const char *file, + const int line); + EXPORT void __test_end(); + EXPORT int __setup_parent(); + EXPORT int __setup_child(); + EXPORT void __test_assert_fail(const char *file, int line, const char *expr, + ...); + EXPORT void __test_exit() __attribute__((__noreturn__)); + EXPORT void __test_abort(int code, const char *__msg, const char *__file, + unsigned int __line, const char *__function); + EXPORT void __test_timeout(double seconds); #else // not _TESTING ( normal build ) -void __test_setfork(const int value) { (void)value; } +void __test_setfork(const int value) +{ + (void)value; +} int __setup_parent() { return 0; } int __setup_child() { return 0; } void __test_exit() { exit(0); } @@ -102,7 +97,8 @@ void __test_init(const char *test_name __attribute__((unused)), void __test_end() { atexit(__test_exit); } void __test_abort(int code, const char *__msg, const char *__file, - unsigned int __line, const char *__function) { + unsigned int __line, const char *__function) +{ printf(" TEST: ABORT - " " file: %s , function: %s, line: %d " " message: (%s) \n", @@ -111,7 +107,8 @@ void __test_abort(int code, const char *__msg, const char *__file, _Exit(code); } -void __test_assert_fail(const char *file, int line, const char *expr, ...) { +void __test_assert_fail(const char *file, int line, const char *expr, ...) +{ printf(" TEST: FAIL" " file: %s , line: %d " " assertion: (%s) \n", @@ -121,7 +118,8 @@ void __test_assert_fail(const char *file, int line, const char *expr, ...) { } void __mark_point(const char *__assertion, const char *__file, - unsigned int __line, const char *__function) { + unsigned int __line, const char *__function) +{ printf(" TEST: OK" " file: %s , function: %s, line: %d " " assertion: (%s) \n", @@ -143,32 +141,33 @@ void __mark_point(const char *__assertion, const char *__file, #define TEST_FORK(value) __test_setfork(value); -#define TEST1(expr) \ - ((expr) \ - ? __mark_point(__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) \ - : __test_assert_fail(__FILE__, __LINE__, __STRING(expr), \ +#define TEST1(expr) \ + ((expr) \ + ? __mark_point(__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) \ + : __test_assert_fail(__FILE__, __LINE__, __STRING(expr), \ __ASSERT_FUNCTION)); -#define TEST0(expr) \ - (!(expr) \ - ? __mark_point(__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) \ - : __test_assert_fail(__FILE__, __LINE__, __STRING(expr), \ +#define TEST0(expr) \ + (!(expr) \ + ? __mark_point(__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION) \ + : __test_assert_fail(__FILE__, __LINE__, __STRING(expr), \ __ASSERT_FUNCTION)); #define TEST_ASSERT(expr) TEST1(expr) -#define BEGIN_TESTING(description) \ - __test_init(__STRING(description), __FILE__, __LINE__); \ - if (!__setup_parent()) { \ +#define BEGIN_TESTING(description) \ + __test_init(__STRING(description), __FILE__, __LINE__); \ + if (!__setup_parent()) \ + { \ __setup_child(); -#define END_TESTING \ - } \ +#define END_TESTING \ + } \ __test_end(); -#define SKIP_TEST(msg) \ +#define SKIP_TEST(msg) \ __test_abort(77, msg, __FILE__, __LINE__, __ASSERT_FUNCTION); -#define ABORT_TEST(msg) \ +#define ABORT_TEST(msg) \ __test_abort(99, msg, __FILE__, __LINE__, __ASSERT_FUNCTION); #define TEST_TIMEOUT(seconds) (__test_timeout(seconds)) @@ -177,27 +176,38 @@ void __mark_point(const char *__assertion, const char *__file, #if defined __GNUC__ && 800 <= __GNUC__ * 100 + __GNUC_MINOR__ _Pragma("GCC diagnostic ignored \"-Wcatch-value\"") #endif -#define TEST_STD_EXCEPTION(val, string) \ - try { \ - val; \ - } catch (std::exception & e) { \ - TEST0(strcmp(e.what(), string)); \ +#define TEST_STD_EXCEPTION(val, string) \ + try \ + { \ + val; \ + } \ + catch (std::exception & e) \ + { \ + TEST0(strcmp(e.what(), string)); \ } -#define TEST_MDS_EXCEPTION(val, string) \ - try { \ - val; \ - } catch (std::exception & e) { \ - TEST0(strcmp(e.what(), string)); \ +#define TEST_MDS_EXCEPTION(val, string) \ + try \ + { \ + val; \ + } \ + catch (std::exception & e) \ + { \ + TEST0(strcmp(e.what(), string)); \ } -#define TEST_EXCEPTION(val, ExceptionClass) \ - { \ - bool correct_exception_caught = false; \ - try { \ - val; \ - } catch (ExceptionClass & e) { \ - correct_exception_caught = true; \ - } catch (...) { \ - } \ - TEST1(correct_exception_caught); \ +#define TEST_EXCEPTION(val, ExceptionClass) \ + { \ + bool correct_exception_caught = false; \ + try \ + { \ + val; \ + } \ + catch (ExceptionClass & e) \ + { \ + correct_exception_caught = true; \ + } \ + catch (...) \ + { \ + } \ + TEST1(correct_exception_caught); \ } #endif diff --git a/traverser/CallbacksUil.c b/traverser/CallbacksUil.c index 7a4159fdb7..4f6d6695f9 100644 --- a/traverser/CallbacksUil.c +++ b/traverser/CallbacksUil.c @@ -122,16 +122,26 @@ static Atom XA_TARGETS = 0; static ListTreeItem *add_target; -struct node { +struct node +{ int nid; int usage; char *name; int populated; }; -typedef enum { on_off, rename_node, delete, new, tree, set_def } NodeTouchType; - -static char *get_node_name(int nid) { +typedef enum +{ + on_off, + rename_node, + delete, + new, + tree, + set_def +} NodeTouchType; + +static char *get_node_name(int nid) +{ char *name; // char *ans; // int def_nid; @@ -147,25 +157,29 @@ static char *get_node_name(int nid) { return name; } -static void set_name(ListTreeItem *item, char *name) { +static void set_name(ListTreeItem *item, char *name) +{ struct node *nd; nd = (struct node *)item->user_data; nd->name = name; } -static void set_nid(ListTreeItem *item, int nid) { +static void set_nid(ListTreeItem *item, int nid) +{ struct node *nd; nd = (struct node *)item->user_data; nd->nid = nid; } -static void set_usage(ListTreeItem *item, int usage) { +static void set_usage(ListTreeItem *item, int usage) +{ struct node *nd; nd = (struct node *)item->user_data; nd->usage = usage; } -static int get_nid(ListTreeItem *item) { +static int get_nid(ListTreeItem *item) +{ struct node *nd; nd = (struct node *)item->user_data; if (nd) @@ -174,25 +188,29 @@ static int get_nid(ListTreeItem *item) { return -1; } -static int get_usage(ListTreeItem *item) { +static int get_usage(ListTreeItem *item) +{ struct node *nd; nd = (struct node *)item->user_data; return nd->usage; } -static void set_populated(ListTreeItem *item, int populated) { +static void set_populated(ListTreeItem *item, int populated) +{ struct node *nd; nd = (struct node *)item->user_data; nd->populated = populated; } -static int is_populated(ListTreeItem *item) { +static int is_populated(ListTreeItem *item) +{ struct node *nd; nd = (struct node *)item->user_data; return nd->populated; } -static int parent_nid(int nid) { +static int parent_nid(int nid) +{ static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); static char *getparent = "GETNCI($, 'PARENT')"; @@ -203,33 +221,42 @@ static int parent_nid(int nid) { static Boolean convert_proc(Widget w, Atom *selection __attribute__((unused)), Atom *target, Atom *type_return, XtPointer *value_return, - unsigned long *length_return, int *format_return) { + unsigned long *length_return, int *format_return) +{ int status = 1; if (!XA_TARGETS) XA_TARGETS = XInternAtom(XtDisplay(w), "TARGETS", 0); - if (*target == XA_TARGETS) { + if (*target == XA_TARGETS) + { status = 1; *type_return = *target; *value_return = XtMalloc(sizeof(Atom)); ((Atom *)*value_return)[0] = XA_STRING; *length_return = 1; *format_return = 32; - } else if (*target == XA_STRING) { - if (num_selected > 0) { + } + else if (*target == XA_STRING) + { + if (num_selected > 0) + { int i; char *ans = 0; status = 1; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { static char *getnci = "GETNCI($, 'FULLPATH')"; static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); char *fullpath; c_nid = get_nid(selections[i]); fullpath = ReadString(getnci, &nid_dsc MDS_END_ARG); - if (i == 0) { + if (i == 0) + { ans = malloc(strlen(fullpath) + 1); strcpy(ans, fullpath); - } else { + } + else + { static char *cr = "\r"; char *tmp = malloc(strlen(ans) + strlen(fullpath) + 1 + @@ -246,15 +273,18 @@ static Boolean convert_proc(Widget w, Atom *selection __attribute__((unused)), *length_return = strlen(ans); *type_return = *target; *format_return = 8; - } else + } + else status = 0; - } else + } + else status = 0; return status; } static void loose_selection_proc(Widget w, - Atom *selection __attribute__((unused))) { + Atom *selection __attribute__((unused))) +{ int i; for (i = 0; i < num_selected; i++) selections[i]->highlighted = 0; @@ -262,16 +292,20 @@ static void loose_selection_proc(Widget w, ListTreeRefresh(w); } -void add_to_selected(ListTreeItem *item, Boolean first) { +void add_to_selected(ListTreeItem *item, Boolean first) +{ if (first) num_selected = 0; - if (num_selected < MAX_SELECTIONS) { + if (num_selected < MAX_SELECTIONS) + { selections[num_selected++] = item; - } else + } + else item->highlighted = 0; } -static void FixPixMap(Widget w, ListTreeItem *itm) { +static void FixPixMap(Widget w, ListTreeItem *itm) +{ static char *get_on = "GETNCI($, 'ON')"; int usage = get_usage(itm); int on; @@ -285,14 +319,16 @@ static void FixPixMap(Widget w, ListTreeItem *itm) { ListTreeSetItemPixmaps(w, itm, off_icons[usage], off_icons[usage]); } -static void FixPixMaps(Widget w, ListTreeItem *itm) { +static void FixPixMaps(Widget w, ListTreeItem *itm) +{ ListTreeItem *tmp; FixPixMap(w, itm); for (tmp = itm->firstchild; tmp; tmp = tmp->nextsibling) FixPixMaps(w, tmp); } -static ListTreeItem *add_item(Widget tree, ListTreeItem *parent, int nid) { +static ListTreeItem *add_item(Widget tree, ListTreeItem *parent, int nid) +{ static char *get_usage = "GETNCI($, 'USAGE')"; static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); @@ -315,7 +351,8 @@ static ListTreeItem *add_item(Widget tree, ListTreeItem *parent, int nid) { return item; } -void add_descendents(Widget tree, ListTreeItem *item, int nid) { +void add_descendents(Widget tree, ListTreeItem *item, int nid) +{ static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); static char *get_num_members = "GETNCI($, 'NUMBER_OF_MEMBERS')"; @@ -332,7 +369,8 @@ void add_descendents(Widget tree, ListTreeItem *item, int nid) { item->open = 1; num = ReadInt(get_num_members, &nid_dsc MDS_END_ARG); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { mem_nid = ReadInt((i == 0) ? get_mem_nid : get_bro_nid, &nid_dsc MDS_END_ARG); add_item(tree, item, mem_nid); @@ -341,7 +379,8 @@ void add_descendents(Widget tree, ListTreeItem *item, int nid) { c_nid = nid; num = ReadInt(get_num_children, &nid_dsc MDS_END_ARG); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { child_nid = ReadInt((i == 0) ? get_child_nid : get_bro_nid, &nid_dsc MDS_END_ARG); add_item(tree, item, child_nid); @@ -350,17 +389,22 @@ void add_descendents(Widget tree, ListTreeItem *item, int nid) { set_populated(item, 1); } -static ListTreeItem *insert_item(Widget tree, ListTreeItem *parent, int nid) { +static ListTreeItem *insert_item(Widget tree, ListTreeItem *parent, int nid) +{ ListTreeItem *itm; char *node_name = get_node_name(nid); itm = ListTreeFindChildName(tree, parent, node_name); - if (itm == NULL) { - if (!is_populated(parent)) { + if (itm == NULL) + { + if (!is_populated(parent)) + { ListTreeRefreshOff(tree); add_descendents(tree, parent, get_nid(parent)); ListTreeRefreshOn(tree); itm = ListTreeFindChildName(tree, parent, node_name); - } else { + } + else + { itm = add_item(tree, parent, nid); ListTreeOrderChildren(tree, parent); } @@ -371,30 +415,35 @@ static ListTreeItem *insert_item(Widget tree, ListTreeItem *parent, int nid) { int parent_nid = get_nid(parent); char *name = get_node_name(parent_nid); status = TreeGetDefaultNid(&def_nid); - if ((status & 1) && (parent_nid == def_nid)) { + if ((status & 1) && (parent_nid == def_nid)) + { char *tmp = malloc(strlen(name) + 3 + 3 + 1); strcpy(tmp, "<<<"); strcat(tmp, name); strcat(tmp, ">>>"); ListTreeRenameItem(tree, parent, tmp); free(tmp); - } else + } + else ListTreeRenameItem(tree, parent, name); } return itm; } void HighlightCallback(Widget w, XtPointer client __attribute__((unused)), - XtPointer call) { + XtPointer call) +{ ListTreeMultiReturnStruct *ret; ListTreeItem *item; int i; ret = (ListTreeMultiReturnStruct *)call; - for (i = 0; i < ret->count; i++) { + for (i = 0; i < ret->count; i++) + { item = ret->items[i]; add_to_selected(item, i == 0); - while (item->parent) { + while (item->parent) + { item = item->parent; } } @@ -418,7 +467,8 @@ XtPointer call __attribute__((unused)); } void ActivateCallback(Widget w, XtPointer client __attribute__((unused)), - XtPointer call) { + XtPointer call) +{ ListTreeActivateStruct *ret; // ListTreeMultiReturnStruct ret2; // ListTreeItem *item; @@ -428,11 +478,13 @@ void ActivateCallback(Widget w, XtPointer client __attribute__((unused)), ret = (ListTreeActivateStruct *)call; count = 0; - while (count < ret->count) { + while (count < ret->count) + { count++; } // node_ptr = (struct node *)(ret->path[count - 1]->user_data); - if (!is_populated(ret->path[count - 1])) { + if (!is_populated(ret->path[count - 1])) + { ListTreeRefreshOff(w); add_descendents(w, ret->path[count - 1], get_nid(ret->path[count - 1])); ListTreeRefreshOn(w); @@ -440,15 +492,19 @@ void ActivateCallback(Widget w, XtPointer client __attribute__((unused)), menu_item = 0; } -static ListTreeItem *Open(Widget tree, int nid) { +static ListTreeItem *Open(Widget tree, int nid) +{ ListTreeItem *parent_item, *item; int parent; - if (nid == 0) { + if (nid == 0) + { item = ListTreeFirstItem(tree); - if (item) { + if (item) + { if (!item->open) add_descendents(tree, item, nid); - } else + } + else item = add_item(tree, NULL, 0); /* add the top with no parent */ return item; } @@ -463,17 +519,20 @@ static ListTreeItem *Open(Widget tree, int nid) { return (item == NULL) ? parent_item : item; } -static void set_default(Widget w, ListTreeItem *item) { +static void set_default(Widget w, ListTreeItem *item) +{ int status; // int old_def; int nid = get_nid(item); Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); - if (default_item != NULL) { + if (default_item != NULL) + { char *name = get_node_name(get_nid(default_item)); ListTreeRenameItem(tree, default_item, name); } status = TreeSetDefaultNid(nid); - if (status & 1) { + if (status & 1) + { char *name = get_node_name(nid); char *new_name = malloc(strlen(name) + 3 + 3 + 1); strcpy(new_name, "<<<"); @@ -482,28 +541,34 @@ static void set_default(Widget w, ListTreeItem *item) { ListTreeRenameItem(tree, item, new_name); free(new_name); default_item = item; - } else + } + else XmdsComplain(w, "Error setting default Nid"); } extern int ClosingWindow; -static void Init(Widget tree) { +static void Init(Widget tree) +{ ListTreeItem *item; char *getdbi = "GETDBI('NUMBER_OPENED')"; int num = ReadInt(getdbi MDS_END_ARG); - if (num > 0) { + if (num > 0) + { int status; int nid; ListTreeRefreshOff(tree); item = add_item(tree, NULL, 0); /* add the top with no parent */ default_item = 0; status = TreeGetDefaultNid(&nid); - if (status & 1) { + if (status & 1) + { item = Open(tree, nid); set_default(tree, item); } ListTreeRefreshOn(tree); - } else { + } + else + { if (ClosingWindow) exit(0); } @@ -511,10 +576,12 @@ static void Init(Widget tree) { } static void CommandLineOpen(Display *display __attribute__((unused)), - Widget tree) { + Widget tree) +{ char chars[132] = {0}; // int status; - typedef struct { + typedef struct + { int shot; Boolean edit; Boolean read_only; @@ -536,18 +603,23 @@ static void CommandLineOpen(Display *display __attribute__((unused)), resources, XtNumber(resources), (Arg *)NULL, 0); { int status; - if (options.tree != NULL) { - if (options.edit) { + if (options.tree != NULL) + { + if (options.edit) + { status = TreeOpenEdit(options.tree, options.shot); - if (status == TreeFILE_NOT_FOUND || status == TreeFOPENW) { + if (status == TreeFILE_NOT_FOUND || status == TreeFOPENW) + { printf("Tree /%s/ shot /%d/ does not exist. Create?(Y/N) ", options.tree, options.shot); if ((scanf("%1s", chars) > 0) && - ((chars[0] == 'y') || (chars[0] == 'Y'))) { + ((chars[0] == 'y') || (chars[0] == 'Y'))) + { status = TreeOpenNew(options.tree, options.shot); } } - } else + } + else status = TreeOpen(options.tree, options.shot, options.read_only); if (status & 1) Init(tree); @@ -555,11 +627,13 @@ static void CommandLineOpen(Display *display __attribute__((unused)), } } -static ListTreeItem *FindItemByNid(ListTreeItem *parent, int nid) { +static ListTreeItem *FindItemByNid(ListTreeItem *parent, int nid) +{ ListTreeItem *itm; if (get_nid(parent) == nid) return parent; - for (itm = parent->firstchild; itm; itm = itm->nextsibling) { + for (itm = parent->firstchild; itm; itm = itm->nextsibling) + { ListTreeItem *ans; if ((ans = FindItemByNid(itm, nid)) != NULL) return ans; @@ -567,7 +641,8 @@ static ListTreeItem *FindItemByNid(ListTreeItem *parent, int nid) { return NULL; } -static ListTreeItem *FindParentItemByNid(Widget tree, int nid) { +static ListTreeItem *FindParentItemByNid(Widget tree, int nid) +{ static char *getnci = "GETNCI($, 'PARENT')"; static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); @@ -578,13 +653,15 @@ static ListTreeItem *FindParentItemByNid(Widget tree, int nid) { } static ListTreeItem *FindChildItemByNid(Widget tree __attribute__((unused)), - ListTreeItem *parent, int nid) { + ListTreeItem *parent, int nid) +{ ListTreeItem *itm; Boolean found = 0; if (nid == 0) return parent; - for (itm = parent->firstchild; itm && !found;) { + for (itm = parent->firstchild; itm && !found;) + { found = get_nid(itm) == nid; if (!found) itm = itm->nextsibling; @@ -596,60 +673,75 @@ static Widget toplevel; static Boolean notify_on = TRUE; -static void FixUpName(Widget tree, ListTreeItem *itm) { +static void FixUpName(Widget tree, ListTreeItem *itm) +{ int nid = get_nid(itm); char *name = get_node_name(nid); int def_nid = -1; TreeGetDefaultNid(&def_nid); - if (nid == def_nid) { + if (nid == def_nid) + { char *str = malloc(strlen(name) + 3 + 3 + 1); strcpy(str, "<<<"); strcat(str, name); strcat(str, ">>>"); ListTreeRenameItem(tree, itm, str); free(str); - } else + } + else ListTreeRenameItem(tree, itm, name); } -static void NodeTouched(int nid, NodeTouchType type) { - if (notify_on) { +static void NodeTouched(int nid, NodeTouchType type) +{ + if (notify_on) + { Widget treew = XtNameToWidget(BxFindTopShell(toplevel), "*.tree"); ListTreeItem *this_item; ListTreeRefreshOff(treew); - if (type == tree) { + if (type == tree) + { ListTreeItem *top = ListTreeFirstItem(treew); ListTreeRefreshOff(treew); if (top != NULL) ListTreeDelete(treew, top); Init(treew); - } else { + } + else + { this_item = FindParentItemByNid(treew, nid); - if (this_item != NULL) { - switch (type) { + if (this_item != NULL) + { + switch (type) + { case on_off: FixPixMaps(treew, this_item); break; case set_def: set_default(toplevel, FindChildItemByNid(treew, this_item, nid)); break; - case new: { + case new: + { // ListTreeItem *itm; insert_item(treew, this_item, nid); FixUpName(treew, this_item); break; } - case rename_node: { + case rename_node: + { ListTreeItem *itm; - if ((itm = FindItemByNid(ListTreeFirstItem(treew), nid)) != NULL) { + if ((itm = FindItemByNid(ListTreeFirstItem(treew), nid)) != NULL) + { ListTreeDelete(treew, itm); } itm = insert_item(treew, this_item, nid); FixUpName(treew, this_item); - } break; + } + break; case delete: if ((this_item = FindItemByNid(ListTreeFirstItem(treew), nid)) != - NULL) { + NULL) + { int pnid = parent_nid(nid); ListTreeItem *pitem = FindItemByNid(ListTreeFirstItem(treew), pnid); ListTreeDelete(treew, this_item); @@ -665,17 +757,20 @@ static void NodeTouched(int nid, NodeTouchType type) { } } -void MessageDismiss(Widget w) { +void MessageDismiss(Widget w) +{ Widget box_w = XtParent(w); XtUnmanageChild(box_w); } -void MessageClear(Widget w) { +void MessageClear(Widget w) +{ Widget text_w = XtNameToWidget(XtParent(w), "*message_text"); XmTextSetString(text_w, ""); } -static void TOutput(char *text) { +static void TOutput(char *text) +{ char *txt = malloc(strlen(text) + 2); Widget message_box; Widget message_text; @@ -690,16 +785,19 @@ static void TOutput(char *text) { free(txt); } -static void TCLOutput(char *text) { +static void TCLOutput(char *text) +{ Widget message_box = XtNameToWidget(toplevel, "*message_box"); if (!XtIsManaged(message_box)) XtManageChild(message_box); TOutput(text); } -static void InitializeCommandInterface(Widget w) { +static void InitializeCommandInterface(Widget w) +{ int status = mdsdcl_do_command("set command tcl"); - if (status & 1) { + if (status & 1) + { int (*set_callbacks)() = NULL; status = LibFindImageSymbol_C("tcl_commands", "TclSetCallbacks", &set_callbacks); @@ -712,7 +810,8 @@ static void InitializeCommandInterface(Widget w) { static Widget TREE; void AddListTree(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ Widget tree; // ListTreeItem *item; tree = XtCreateWidget("tree", listtreeWidgetClass, w, NULL, 0); @@ -747,7 +846,8 @@ void AddListTree(Widget w, XtPointer client_data __attribute__((unused)), extern void CloseWindow(); /* ARGSUSED */ void BxExitCB ARGLIST((w, client, call)) UARG(Widget, w) ARG(XtPointer, client) - GRAU(XtPointer, call) { + GRAU(XtPointer, call) +{ // int *exitValue = (int *)client; CloseWindow(w, client, call); } @@ -770,7 +870,8 @@ void BxExitCB ARGLIST((w, client, call)) UARG(Widget, w) ARG(XtPointer, client) /* ARGSUSED */ void BxManageCB ARGLIST((w, client, call)) ARG(Widget, w) ARG(XtPointer, client) - GRAU(XtPointer, call __attribute__((unused))) { + GRAU(XtPointer, call __attribute__((unused))) +{ WidgetList widgets; int i; @@ -781,18 +882,21 @@ void BxManageCB ARGLIST((w, client, call)) ARG(Widget, w) ARG(XtPointer, client) widgets = BxWidgetIdsFromNames(w, "BxManageCB", (String)client); i = 0; - while (widgets && widgets[i] != NULL) { + while (widgets && widgets[i] != NULL) + { XtManageChild(widgets[i]); i++; } XtFree((char *)widgets); } -static void makeNoEdit(Widget w) { +static void makeNoEdit(Widget w) +{ WidgetList children; Cardinal count = 0; Cardinal i; - if (strcmp(XtClass(w)->core_class.class_name, "XmScrollBar")) { + if (strcmp(XtClass(w)->core_class.class_name, "XmScrollBar")) + { XtVaGetValues(w, XmNchildren, &children, XmNnumChildren, &count, NULL); XtVaSetValues(w, XmNeditable, False, NULL); for (i = 0; i < count; i++) @@ -800,7 +904,8 @@ static void makeNoEdit(Widget w) { } } -static void display_data(Widget w, int nid, int count) { +static void display_data(Widget w, int nid, int count) +{ static int x, y; Arg args[] = {{XmdsNnid, 0}, {XmNx, 0}, @@ -812,11 +917,14 @@ static void display_data(Widget w, int nid, int count) { args[0].value = nid; args[1].value = x; args[2].value = y; - if (count == 0) { + if (count == 0) + { XtManageChild(w = XmdsCreateXdBoxDialog(BxFindTopShell(w), "Display Data", args, XtNumber(args) - 2)); XtVaGetValues(w, XmNx, &x, XmNy, &y, NULL); - } else { + } + else + { x += 20; y += 20; args[3].value = 0; @@ -827,24 +935,29 @@ static void display_data(Widget w, int nid, int count) { } void DisplayData(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); display_data(w, nid, i); } } void TurnOnOff(Widget w, XtPointer client_data, - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; int on = *(int *)client_data; Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); // XmAnyCallbackStruct *acs = (XmAnyCallbackStruct *) call_data; ListTreeRefreshOff(tree); - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); - switch (on) { + switch (on) + { case 0: TreeTurnOff(nid); break; @@ -857,7 +970,8 @@ void TurnOnOff(Widget w, XtPointer client_data, ListTreeRefreshOn(tree); } -static void modify_data(Widget w, int nid, int count) { +static void modify_data(Widget w, int nid, int count) +{ static int x, y; Arg args[] = {{XmdsNnid, 0}, {XmNx, 0}, @@ -870,11 +984,14 @@ static void modify_data(Widget w, int nid, int count) { args[0].value = nid; args[1].value = x; args[2].value = y; - if (count == 0) { + if (count == 0) + { XtManageChild(w = XmdsCreateXdBoxDialog(BxFindTopShell(w), "Modify Data", args, XtNumber(args))); XtVaGetValues(w, XmNx, &x, XmNy, &y, NULL); - } else { + } + else + { x += 20; y += 20; args[3].value = 0; @@ -884,9 +1001,11 @@ static void modify_data(Widget w, int nid, int count) { } void ModifyData(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); modify_data(w, nid, i); } @@ -896,7 +1015,8 @@ static int NUM_TO_DELETE = 0; static int *NIDS_TO_DELETE = 0; void DeleteNodeNow(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; int status; int def_nid; @@ -904,7 +1024,8 @@ void DeleteNodeNow(Widget w, XtPointer client_data __attribute__((unused)), Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *itm; loose_selection_proc(tree, NULL); - for (i = 0; i < NUM_TO_DELETE; i++) { + for (i = 0; i < NUM_TO_DELETE; i++) + { int nid = NIDS_TO_DELETE[i]; ListTreeItem *itm = FindItemByNid(ListTreeFirstItem(tree), nid); if (itm != NULL) @@ -916,19 +1037,23 @@ void DeleteNodeNow(Widget w, XtPointer client_data __attribute__((unused)), status = TreeGetDefaultNid(&def_nid); if ((status & 1) == 0) def_nid = 0; - for (i = 0; i < NUM_TO_DELETE; i++) { + for (i = 0; i < NUM_TO_DELETE; i++) + { if (parent_nids[i] != -1) if ((itm = FindItemByNid(ListTreeFirstItem(tree), parent_nids[i])) != - NULL) { + NULL) + { char *name = get_node_name(parent_nids[i]); - if (parent_nids[i] == def_nid) { + if (parent_nids[i] == def_nid) + { char *str = malloc(strlen(name) + 3 + 3 + 1); strcpy(str, "<<<"); strcat(str, name); strcat(str, ">>>"); ListTreeRenameItem(tree, itm, str); free(str); - } else + } + else ListTreeRenameItem(tree, itm, name); } } @@ -937,13 +1062,15 @@ void DeleteNodeNow(Widget w, XtPointer client_data __attribute__((unused)), NIDS_TO_DELETE = NULL; } -void DeleteNodeConditional() { +void DeleteNodeConditional() +{ int idx = 0; static int first_time = 1; Widget delete_ok_box = XtNameToWidget(toplevel, "*delete_ok_box"); Widget delete_ok_list = XtNameToWidget(delete_ok_box, "*delete_ok_list"); int nid; - if (first_time) { + if (first_time) + { XtManageChild(delete_ok_box); XtUnmanageChild(delete_ok_box); } @@ -951,7 +1078,8 @@ void DeleteNodeConditional() { if (NIDS_TO_DELETE != NULL) free(NIDS_TO_DELETE); NIDS_TO_DELETE = (int *)malloc(NUM_TO_DELETE * sizeof(int)); - for (nid = 0; TreeDeleteNodeGetNid(&nid) & 1;) { + for (nid = 0; TreeDeleteNodeGetNid(&nid) & 1;) + { XmString path_str; char *c_path = TreeGetPath(nid); NIDS_TO_DELETE[idx++] = nid; @@ -964,22 +1092,27 @@ void DeleteNodeConditional() { } void DeleteNode(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; NUM_TO_DELETE = 0; - if (num_selected > 0) { - for (i = 0; i < num_selected; i++) { + if (num_selected > 0) + { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); TreeDeleteNodeInitialize(nid, &NUM_TO_DELETE, i == 0); } DeleteNodeConditional(); - } else + } + else XmdsComplain( w, "Please choose one or more nodes\nbefore choosing delete node."); } void RenameNodeNow(Widget w, XtPointer client_data, - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int nid = (int)((char *)client_data - (char *)0); Widget tree = XtNameToWidget(BxFindTopShell(toplevel), "*.tree"); Widget tw = XtNameToWidget(w, "*.new_name"); @@ -988,9 +1121,11 @@ void RenameNodeNow(Widget w, XtPointer client_data, int status; parent = parent_nid(nid); status = TreeRenameNode(nid, new_name); - if (status & 1) { + if (status & 1) + { int new_parent = parent_nid(nid); - if (new_parent != parent) { + if (new_parent != parent) + { ListTreeItem *this_item = FindParentItemByNid(tree, nid); ListTreeDelete(tree, FindItemByNid(ListTreeFirstItem(tree), nid)); FixUpName(tree, FindItemByNid(ListTreeFirstItem(tree), parent)); @@ -998,15 +1133,19 @@ void RenameNodeNow(Widget w, XtPointer client_data, } FixUpName(tree, FindItemByNid(ListTreeFirstItem(tree), nid)); XtDestroyWidget(w); - } else + } + else XmdsComplain(w, "Error renaming node"); } void RenameNode(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - if (num_selected > 0) { - for (i = 0; i < num_selected; i++) { + if (num_selected > 0) + { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); char *c_path = TreeGetPath(nid); static XtCallbackRec ok_callback_list[] = { @@ -1042,13 +1181,15 @@ void RenameNode(Widget w, XtPointer client_data __attribute__((unused)), XtManageChild(widg); XtManageChild(qdlog); } - } else + } + else XmdsComplain( w, "Please choose one or more nodes\nbefore choosing rename node."); } static int DoMethodNoSignal(struct descriptor *niddsc, - struct descriptor *method, Widget parent) { + struct descriptor *method, Widget parent) +{ /* LibEstablish(LibSigToRet); */ EMPTYXD(xd); int status; @@ -1059,13 +1200,15 @@ static int DoMethodNoSignal(struct descriptor *niddsc, return status; } -static int setup_device(Widget parent, int nid) { +static int setup_device(Widget parent, int nid) +{ static DESCRIPTOR(const method, "DW_SETUP"); struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, 0}; volatile int status; niddsc.pointer = (char *)&nid; status = DoMethodNoSignal(&niddsc, (struct descriptor *)&method, parent); - if (status == TreeNOMETHOD) { + if (status == TreeNOMETHOD) + { static char *getnci = "GETNCI($, 'CONGLOMERATE_ELT')"; static int c_nid; static DESCRIPTOR_NID(nid_dsc, &c_nid); @@ -1076,7 +1219,8 @@ static int setup_device(Widget parent, int nid) { conglomerate_elt = ReadInt(getnci, &nid_dsc MDS_END_ARG); head_nid = nid + 1 - conglomerate_elt; c_nid = head_nid; - if (TdiModelOf(&nid_dsc, &model MDS_END_ARG) & 1) { + if (TdiModelOf(&nid_dsc, &model MDS_END_ARG) & 1) + { static struct descriptor filename = {0, DTYPE_T, CLASS_D, 0}; /* static DESCRIPTOR(const prefix, "DECW$SYSTEM_DEFAULTS:"); */ static DESCRIPTOR(const postfix, ".uid\0"); @@ -1088,7 +1232,8 @@ static int setup_device(Widget parent, int nid) { StrAppend(&model, (struct descriptor *)&zero); status = XmdsDeviceSetup(parent, &c_nid, &filename.pointer, 1, model.pointer, NULL, 0, 0); - switch (status) { + switch (status) + { case MrmSUCCESS: status = 1; break; @@ -1105,9 +1250,11 @@ static int setup_device(Widget parent, int nid) { } void SetupDevice(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); setup_device(w, nid); } @@ -1118,8 +1265,10 @@ void MenuUnmap(Widget w __attribute__((unused)), XtPointer call_data __attribute__((unused))) {} void MSetupDevice(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { - if (menu_item != NULL) { + XtPointer call_data __attribute__((unused))) +{ + if (menu_item != NULL) + { int nid = get_nid(menu_item); setup_device(w, nid); menu_item = NULL; @@ -1127,11 +1276,13 @@ void MSetupDevice(Widget w, XtPointer client_data __attribute__((unused)), } void MTurnOnOff(Widget w, XtPointer client_data, - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int on = *(int *)client_data; Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeRefreshOff(tree); - if (menu_item != NULL) { + if (menu_item != NULL) + { int nid = get_nid(menu_item); if (on) TreeTurnOn(nid); @@ -1144,8 +1295,10 @@ void MTurnOnOff(Widget w, XtPointer client_data, } void MDisplayData(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { - if (menu_item != NULL) { + XtPointer call_data __attribute__((unused))) +{ + if (menu_item != NULL) + { int nid = get_nid(menu_item); display_data(w, nid, 0); menu_item = NULL; @@ -1153,14 +1306,17 @@ void MDisplayData(Widget w, XtPointer client_data __attribute__((unused)), } void MModifyData(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { - if (menu_item != NULL) { + XtPointer call_data __attribute__((unused))) +{ + if (menu_item != NULL) + { int nid = get_nid(menu_item); modify_data(w, nid, 0); } } -static void display_nci(Widget bu, int nid, int count) { +static void display_nci(Widget bu, int nid, int count) +{ static int x, y; XmString label = GetNciString(nid); Widget w; @@ -1181,12 +1337,15 @@ static void display_nci(Widget bu, int nid, int count) { args[2].value = (long)XmStringCreateLtoR("Dismiss", XmSTRING_DEFAULT_CHARSET); args[3].value = x; args[4].value = y; - if (count == 0) { + if (count == 0) + { XtManageChild(w = XmCreateInformationDialog(BxFindTopShell(bu), "Display Nci", args, XtNumber(args) - 2)); XtVaGetValues(w, XmNx, &x, XmNy, &y, NULL); - } else { + } + else + { x += 20; y += 20; args[6].value = 0; @@ -1197,17 +1356,21 @@ static void display_nci(Widget bu, int nid, int count) { } void DisplayNci(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { int nid = get_nid(selections[i]); display_nci(w, nid, i); } } void MDisplayNci(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { - if (menu_item != NULL) { + XtPointer call_data __attribute__((unused))) +{ + if (menu_item != NULL) + { int nid = get_nid(menu_item); display_nci(w, nid, 0); menu_item = NULL; @@ -1215,14 +1378,18 @@ void MDisplayNci(Widget w, XtPointer client_data __attribute__((unused)), } void CloseTree(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *top = ListTreeFirstItem(tree); static char *getediting = "GETDBI('OPEN_FOR_EDIT') && GETDBI('MODIFIED')"; - if (ReadInt(getediting MDS_END_ARG)) { + if (ReadInt(getediting MDS_END_ARG)) + { Widget write_dlog = XtNameToWidget(BxFindTopShell(w), "*.writeDialog"); XtManageChild(write_dlog); - } else { + } + else + { int status = TreeClose(NULL, 0); ListTreeRefreshOff(tree); if ((status & 1) && (top != NULL)) @@ -1233,16 +1400,20 @@ void CloseTree(Widget w, XtPointer client_data __attribute__((unused)), } void WriteTree(Widget w, XtPointer client_data, - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int status; int write = *(int *)client_data; - if (write) { + if (write) + { status = TreeWriteTree(0, 0); if (status) status = TreeClose(NULL, 0); - } else + } + else status = TreeQuitTree(0, 0); - if (status & 1) { + if (status & 1) + { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *top = ListTreeFirstItem(tree); ListTreeRefreshOff(tree); @@ -1250,16 +1421,19 @@ void WriteTree(Widget w, XtPointer client_data, ListTreeDelete(tree, top); Init(tree); ListTreeRefreshOn(tree); - } else + } + else XmdsComplain(BxFindTopShell(w), "Error writing or quiting from tree"); } -struct tree_id { +struct tree_id +{ char *tree; int shot; }; -static void AskCreate(Widget w, char *tree, int shot) { +static void AskCreate(Widget w, char *tree, int shot) +{ Widget ask_dlog = XtNameToWidget(BxFindTopShell(w), "*.createDialog"); struct tree_id *treeid = (struct tree_id *)malloc(sizeof(*treeid)); treeid->shot = shot; @@ -1270,14 +1444,16 @@ static void AskCreate(Widget w, char *tree, int shot) { } void CreateTree(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int status = 1; struct tree_id *treeid; XtVaGetValues(w, XmNuserData, (char *)(&treeid), NULL); status = TreeOpenNew(treeid->tree, treeid->shot); free(treeid->tree); free(treeid); - if (status & 1) { + if (status & 1) + { Widget tree = TREE; ListTreeItem *top = ListTreeFirstItem(tree); ListTreeRefreshOff(tree); @@ -1288,18 +1464,23 @@ void CreateTree(Widget w, XtPointer client_data __attribute__((unused)), } } -void open_tree(Widget w, char *tree, int shot) { +void open_tree(Widget w, char *tree, int shot) +{ int status; Widget edit = XtNameToWidget(BxFindTopShell(w), "*.edit_toggle"); - if (XmToggleButtonGetState(edit)) { + if (XmToggleButtonGetState(edit)) + { status = TreeOpenEdit(tree, shot); if (status == TreeFILE_NOT_FOUND) AskCreate(w, tree, shot); - } else { + } + else + { Widget r_o = XtNameToWidget(BxFindTopShell(w), "*.r_o_toggle"); status = TreeOpen(tree, shot, XmToggleButtonGetState(r_o)); } - if (status & 1) { + if (status & 1) + { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *top = ListTreeFirstItem(tree); ListTreeRefreshOff(tree); @@ -1311,14 +1492,16 @@ void open_tree(Widget w, char *tree, int shot) { } void OpenTree(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ Widget parentw = XtParent(w); Widget treew = XtNameToWidget(parentw, "tree_name"); char *tree = XmTextGetString(treew); Widget shotw = XtNameToWidget(parentw, "shot_name"); char *shot_str = XmTextGetString(shotw); ; - if (tree && strlen(tree) && shot_str && strlen(shot_str)) { + if (tree && strlen(tree) && shot_str && strlen(shot_str)) + { int lshot; int status = sscanf(shot_str, "%d", &lshot); if (status) @@ -1328,28 +1511,34 @@ void OpenTree(Widget w, XtPointer client_data __attribute__((unused)), "shot specifed as /%s/\nmust be an integer\nPlease reeenter " "or choose \"Cancel\"", shot_str); - } else + } + else XmdsComplain(parentw, "Specify both a tree and a shot\nbefore choosing " "\"Ok\"\nUse \"Cancel\" to abort operation"); } void MDoAction(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ // XmAnyCallbackStruct *acs = (XmAnyCallbackStruct *) call_data; } void SetDefault(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ int i; - for (i = 0; i < num_selected; i++) { + for (i = 0; i < num_selected; i++) + { set_default(w, selections[i]); } } void MSetDefault(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { - if (menu_item != NULL) { + XtPointer call_data __attribute__((unused))) +{ + if (menu_item != NULL) + { set_default(w, menu_item); menu_item = NULL; } @@ -1357,7 +1546,8 @@ void MSetDefault(Widget w, XtPointer client_data __attribute__((unused)), void DoAction(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ // XmAnyCallbackStruct *acs = (XmAnyCallbackStruct *) call_data; } @@ -1365,25 +1555,29 @@ static unsigned int usage = 0; static char *device_type = 0; void AddNodeStart(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ if (num_selected != 1) XmdsComplain(w, "select exactly one node as parent before choosing add node"); - else { + else + { add_target = selections[0]; XtManageChild(XtNameToWidget(toplevel, "*addDialog")); } } void AddNodeDismiss(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ XtUnmanageChild(w); } extern int GetSupportedDevices(); Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, - ListTreeItem **itm) { + ListTreeItem **itm) +{ int parent_nid = get_nid(parent); char *parent_path; char *full_path; @@ -1395,7 +1589,8 @@ Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, c_nid = parent_nid; parent_path = ReadString(getnci, &nid_dsc MDS_END_ARG); full_path = realloc(parent_path, strlen(parent_path) + 1 + strlen(name) + 1); - if (usage == TreeUSAGE_SUBTREE) { + if (usage == TreeUSAGE_SUBTREE) + { XmdsComplain(BxFindTopShell(w), "Non Motif traverser does not\nyet support " "adding subtrees to the tree"); return 0; @@ -1406,23 +1601,29 @@ Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, else strcat(full_path, ":"); strcat(full_path, name); - if (usage == TreeUSAGE_DEVICE) { + if (usage == TreeUSAGE_DEVICE) + { status = 0; - if (device_type) { + if (device_type) + { notify_on = FALSE; status = TreeAddConglom(full_path, device_type, &new_nid); notify_on = TRUE; if (!(status & 1)) XmdsComplain(BxFindTopShell(w), "Error adding device"); - } else + } + else XmdsComplain(BxFindTopShell(w), "Select a device type before choosing add"); - } else { + } + else + { status = TreeAddNode(full_path, &new_nid, usage); if (!(status & 1)) XmdsComplain(BxFindTopShell(w), "Error adding node"); } - if (status & 1) { + if (status & 1) + { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); *itm = insert_item(tree, parent, new_nid); } @@ -1432,23 +1633,30 @@ Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, void add_tags(ListTreeItem *itm __attribute__((unused)), char *tags __attribute__((unused))) {} -Boolean AddNodeApply(Widget w) { +Boolean AddNodeApply(Widget w) +{ Boolean status = 0; - if (TreeEditing()) { - if (usage != 0) { + if (TreeEditing()) + { + if (usage != 0) + { Widget name_w = XtNameToWidget(XtParent(w), "*.nodeName"); char *name_c = XmTextGetString(name_w); - if (strlen(name_c) > 0) { + if (strlen(name_c) > 0) + { if ((index(name_c, '.') == name_c) || (index(name_c, ':') == name_c)) XmdsComplain(w, "Remove leading punctuation"); - else { + else + { if (strlen(name_c) > 12) XmdsComplain(w, "Node names must be no more than 12 characters long"); - else { + else + { ListTreeItem *ret_itm; status = add_node(w, add_target, name_c, usage, &ret_itm); - if (status) { + if (status) + { Widget tag_w = XtNameToWidget(XtParent(w), "*.nodeTags"); char *tags_c = XmTextGetString(tag_w); if (strlen(tags_c) > 0) @@ -1457,30 +1665,36 @@ Boolean AddNodeApply(Widget w) { status = TRUE; } } - } else + } + else XmdsComplain(w, "Specifiy a name before \"Ok\""); - } else + } + else XmdsComplain(w, "Please choose a usage before pressing \"Ok\""); - } else + } + else XmdsComplain(w, "Tree not open for edit"); return status; } void AddNode(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ if (AddNodeApply(w)) XtUnmanageChild(w); } void SetUsage(Widget w __attribute__((unused)), XtPointer client_data, - XtPointer call_data) { + XtPointer call_data) +{ XmToggleButtonCallbackStruct *cb = (XmToggleButtonCallbackStruct *)call_data; if (cb->set) usage = *(int *)client_data; } void SetDeviceType(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ char *sptr, *dptr; // XmToggleButtonCallbackStruct *cb = (XmToggleButtonCallbackStruct *) // call_data; @@ -1494,7 +1708,8 @@ void SetDeviceType(Widget w, XtPointer client_data __attribute__((unused)), void CommandEntered(Widget w __attribute__((unused)), XtPointer client_data __attribute__((unused)), - XtPointer call_data) { + XtPointer call_data) +{ XmCommandCallbackStruct *cb = (XmCommandCallbackStruct *)call_data; char *cmd; char *output = 0; @@ -1503,12 +1718,14 @@ void CommandEntered(Widget w __attribute__((unused)), cmd = XmStringUnparse(cb->value, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); mdsdcl_do_command_extra_args(cmd, 0, &error, &output, 0, 0); - if (output != NULL) { + if (output != NULL) + { if (strlen(output) > 1) TOutput(output); free(output); } - if (error != NULL) { + if (error != NULL) + { if (strlen(error) > 1) TOutput(error); free(error); @@ -1516,7 +1733,8 @@ void CommandEntered(Widget w __attribute__((unused)), } void CreateAddDevice(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ static Boolean devices_loaded = False; char **devnames; int num; @@ -1525,10 +1743,12 @@ void CreateAddDevice(Widget w, XtPointer client_data __attribute__((unused)), if (num_selected != 1) XmdsComplain(w, "select exactly one node as parent before choosing add node"); - else { + else + { add_target = selections[0]; top = XtNameToWidget(BxFindTopShell(w), "*.addDeviceDialog"); - if (!devices_loaded) { + if (!devices_loaded) + { static Arg args[] = {{XmNarmCallback, 0}}; int i; Widget rb; @@ -1537,7 +1757,8 @@ void CreateAddDevice(Widget w, XtPointer client_data __attribute__((unused)), args[0].value = (long)device_changed_list; rb = XtNameToWidget(top, "*.ad_radioBox1"); GetSupportedDevices(&devnames, &num); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { Widget w = XmCreateToggleButton(rb, devnames[i], args, 1); free(devnames[i]); @@ -1551,16 +1772,19 @@ void CreateAddDevice(Widget w, XtPointer client_data __attribute__((unused)), } void AddDevice(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ XtUnmanageChild(w); } void AddDeviceDismiss(Widget w, XtPointer client_data __attribute__((unused)), - XtPointer call_data __attribute__((unused))) { + XtPointer call_data __attribute__((unused))) +{ XtUnmanageChild(w); } -static Boolean TagsApply(Widget w, int nid) { +static Boolean TagsApply(Widget w, int nid) +{ int status; int retstatus = 1; Widget list_widget = XtNameToWidget(w, "*.tag_list"); @@ -1570,13 +1794,16 @@ static Boolean TagsApply(Widget w, int nid) { TreeRemoveNodesTags(nid); XtVaGetValues(list_widget, XmNitems, &item_list, XmNitemCount, &num_items, NULL); - for (i = 0; i < num_items; i++) { + for (i = 0; i < num_items; i++) + { char *tag_txt; tag_txt = XmStringUnparse(item_list[i], NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); - if (tag_txt) { + if (tag_txt) + { status = TreeAddTag(nid, tag_txt); - if (!(status & 1)) { + if (!(status & 1)) + { retstatus = status; XmdsComplain(toplevel, "Error Adding tag\n%s", tag_txt); } @@ -1586,7 +1813,8 @@ static Boolean TagsApply(Widget w, int nid) { return retstatus; } -static void TagsReset(Widget w, int nid) { +static void TagsReset(Widget w, int nid) +{ char *path; char *tag; // int status; @@ -1600,7 +1828,8 @@ static void TagsReset(Widget w, int nid) { XtVaSetValues(XtNameToWidget(w, "tag_node_label"), XmNlabelString, path_str, NULL); XmStringFree(path_str); - for (ctx = 0; (tag = TreeFindNodeTags(nid, &ctx)) != NULL;) { + for (ctx = 0; (tag = TreeFindNodeTags(nid, &ctx)) != NULL;) + { XmString tag_str = XmStringCreateLtoR(tag, XmSTRING_DEFAULT_CHARSET); XmListAddItemUnselected(list_widget, tag_str, 0); XmStringFree(tag_str); @@ -1614,13 +1843,15 @@ static void TagsReset(Widget w, int nid) { #define TAGS_CANCEL 3 #define TAGS_ADD 4 #define TAGS_REMOVE 5 -void tag_button_proc(Widget w, int *tag) { +void tag_button_proc(Widget w, int *tag) +{ Widget tag_widget = XtParent(w); XtPointer temp; int nid; XtVaGetValues(tag_widget, XmNuserData, (XtArgVal)&temp, NULL); nid = (intptr_t)temp; - switch (*tag) { + switch (*tag) + { case TAGS_OK: if (TagsApply(tag_widget, nid) & 1) XtUnmanageChild(tag_widget); @@ -1634,29 +1865,35 @@ void tag_button_proc(Widget w, int *tag) { case TAGS_CANCEL: XtUnmanageChild(tag_widget); break; - case TAGS_ADD: { + case TAGS_ADD: + { char *new_tag = (char *)XmTextFieldGetString( XtNameToWidget(tag_widget, "tag_current_text")); - if (strlen(new_tag)) { + if (strlen(new_tag)) + { XmString new_tag_str = XmStringCreateSimple(new_tag); Widget list_widget = XtNameToWidget(tag_widget, "*.tag_list"); XmListAddItemUnselected(list_widget, new_tag_str, 0); XmStringFree(new_tag_str); XtFree(new_tag); } - } break; - case TAGS_REMOVE: { + } + break; + case TAGS_REMOVE: + { int *pos_list; int pos_count; Widget list_widget = XtNameToWidget(tag_widget, "*.tag_list"); if (XmListGetSelectedPos(list_widget, &pos_list, &pos_count)) XmListDeletePos(list_widget, pos_list[0]); - } break; + } + break; } } void tag_selection_proc(Widget w, int *tag __attribute__((unused)), - XmListCallbackStruct *reason) { + XmListCallbackStruct *reason) +{ Widget tag_widget = XtParent(w); char *tag_txt; tag_txt = XmStringUnparse(reason->item, NULL, 0, XmCHARSET_TEXT, NULL, 0, @@ -1667,18 +1904,25 @@ void tag_selection_proc(Widget w, int *tag __attribute__((unused)), } void ModifyTags(Widget w, XtPointer client_data __attribute__((unused)), - XmListCallbackStruct *reason __attribute__((unused))) { + XmListCallbackStruct *reason __attribute__((unused))) +{ Widget tagsw = XtNameToWidget(BxFindTopShell(w), "*.tags_box"); - if (!XtIsManaged(tagsw)) { - if (num_selected == 1) { + if (!XtIsManaged(tagsw)) + { + if (num_selected == 1) + { int nid = get_nid(selections[0]); XtVaSetValues(tagsw, XmNuserData, (XtArgVal)nid, NULL); TagsReset(tagsw, nid); XtManageChild(tagsw); - } else { + } + else + { XmdsComplain(w, "Please select exactly one node before modifying tags"); } - } else { + } + else + { XmdsComplain(w, "Please modify only one node's tags at a time"); } } diff --git a/traverser/GetNciString.c b/traverser/GetNciString.c index 115252677d..5f69d84f4d 100644 --- a/traverser/GetNciString.c +++ b/traverser/GetNciString.c @@ -24,7 +24,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -XmString GetNciString(int nid __attribute__((unused))) { +XmString GetNciString(int nid __attribute__((unused))) +{ char *cstring = "GETNCI is not yet implemented"; XmString ans = XmStringCreateLtoR(cstring, XmSTRING_DEFAULT_CHARSET); return ans; diff --git a/traverser/GetSupportedDevices.c b/traverser/GetSupportedDevices.c index dbc65e370f..0b5ea7533a 100644 --- a/traverser/GetSupportedDevices.c +++ b/traverser/GetSupportedDevices.c @@ -31,19 +31,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -int GetSupportedDevices(char ***devnames, int *number) { +int GetSupportedDevices(char ***devnames, int *number) +{ EMPTYXD(dev_list); static DESCRIPTOR(expr, "_devs = MdsDevices()"); int status; *number = 0; *devnames = 0; status = TdiExecute((struct descriptor *)&expr, &dev_list MDS_END_ARG); - if (status & 1) { + if (status & 1) + { int i; struct descriptor_a *a_ptr = (struct descriptor_a *)dev_list.pointer; *number = a_ptr->arsize / a_ptr->length / 2; *devnames = (char **)malloc(*number * sizeof(char **)); - for (i = 0; i < *number; i++) { + for (i = 0; i < *number; i++) + { char *devname; (*devnames)[i] = devname = strndup((const char *)a_ptr->pointer + (i * 2 * a_ptr->length), diff --git a/traverser/ReadInt.c b/traverser/ReadInt.c index 3345cc2dde..4585a4ccc3 100644 --- a/traverser/ReadInt.c +++ b/traverser/ReadInt.c @@ -33,7 +33,8 @@ extern int TdiCompile(); extern int TdiEvaluate(); extern int TdiExecute(); -int ReadInt(char *expr, ...) { +int ReadInt(char *expr, ...) +{ INIT_STATUS; static struct descriptor expr_dsc = {0, DTYPE_T, CLASS_S, 0}; int ans; @@ -43,7 +44,8 @@ int ReadInt(char *expr, ...) { int numargs; struct descriptor *dsc_ptrs[3]; VA_LIST_MDS_END_ARG(dsc_ptrs, numargs, 0, 0, expr); - switch (numargs) { + switch (numargs) + { case 0: status = TdiExecute(&expr_dsc, &ans_xd MDS_END_ARG); break; @@ -57,47 +59,57 @@ int ReadInt(char *expr, ...) { default: return 0; } - if - STATUS_OK { - /* status = TdiEvaluate(&ans_xd, &ans_xd); */ - if - STATUS_OK { - struct descriptor *d_ptr; - for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; - d_ptr = (struct descriptor *)d_ptr->pointer) - ; - if (d_ptr->dtype == DTYPE_L) { - /* + if (STATUS_OK) + { + /* status = TdiEvaluate(&ans_xd, &ans_xd); */ + if (STATUS_OK) + { + struct descriptor *d_ptr; + for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; + d_ptr = (struct descriptor *)d_ptr->pointer) + ; + if (d_ptr->dtype == DTYPE_L) + { + /* ans = (int)malloc(sizeof(int)); */ - ans = *(int *)d_ptr->pointer; - } else if (d_ptr->dtype == DTYPE_NID) { - /* + ans = *(int *)d_ptr->pointer; + } + else if (d_ptr->dtype == DTYPE_NID) + { + /* ans = (int)malloc(sizeof(int)); */ - ans = *(int *)d_ptr->pointer; - } else if (d_ptr->dtype == DTYPE_WU) { - /* + ans = *(int *)d_ptr->pointer; + } + else if (d_ptr->dtype == DTYPE_WU) + { + /* ans = (int)malloc(sizeof(int)); */ - ans = *(unsigned short *)d_ptr->pointer; - } else if (d_ptr->dtype == DTYPE_W) { - /* + ans = *(unsigned short *)d_ptr->pointer; + } + else if (d_ptr->dtype == DTYPE_W) + { + /* ans = (int)malloc(sizeof(int)); */ - ans = *(short *)d_ptr->pointer; - } else if (d_ptr->dtype == DTYPE_BU) { - /* + ans = *(short *)d_ptr->pointer; + } + else if (d_ptr->dtype == DTYPE_BU) + { + /* ans = (int)malloc(sizeof(int)); */ - ans = *(char *)d_ptr->pointer; - } else - ans = 0; - } + ans = *(char *)d_ptr->pointer; + } else ans = 0; - MdsFree1Dx(&ans_xd, 0); } + else + ans = 0; + MdsFree1Dx(&ans_xd, 0); + } else ans = 0; return ans; diff --git a/traverser/ReadString.c b/traverser/ReadString.c index b7d0bf2501..0a3262268f 100644 --- a/traverser/ReadString.c +++ b/traverser/ReadString.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern int TdiData(); extern int TdiCompile(); extern int TdiExecute(); -char *ReadString(char *expr, ...) { +char *ReadString(char *expr, ...) +{ INIT_STATUS; static struct descriptor expr_dsc = {0, DTYPE_T, CLASS_S, 0}; char *ans; @@ -43,7 +44,8 @@ char *ReadString(char *expr, ...) { int numargs; struct descriptor *dsc_ptrs[3]; VA_LIST_MDS_END_ARG(dsc_ptrs, numargs, 0, 0, expr); - switch (numargs) { + switch (numargs) + { case 0: status = TdiExecute(&expr_dsc, &ans_xd MDS_END_ARG); break; @@ -57,26 +59,28 @@ char *ReadString(char *expr, ...) { default: return 0; } - if - STATUS_OK { - /* status = TdiData(&ans_xd, &ans_xd); */ - if - STATUS_OK { - struct descriptor *d_ptr; - for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; - d_ptr = (struct descriptor *)d_ptr->pointer) - ; - if (d_ptr->dtype == DTYPE_T) { - ans = (char *)malloc((d_ptr->length + 1) * sizeof(char)); - strncpy(ans, d_ptr->pointer, d_ptr->length); - ans[d_ptr->length] = 0; - } else - ans = 0; - } + if (STATUS_OK) + { + /* status = TdiData(&ans_xd, &ans_xd); */ + if (STATUS_OK) + { + struct descriptor *d_ptr; + for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; + d_ptr = (struct descriptor *)d_ptr->pointer) + ; + if (d_ptr->dtype == DTYPE_T) + { + ans = (char *)malloc((d_ptr->length + 1) * sizeof(char)); + strncpy(ans, d_ptr->pointer, d_ptr->length); + ans[d_ptr->length] = 0; + } else ans = 0; - MdsFree1Dx(&ans_xd, 0); } + else + ans = 0; + MdsFree1Dx(&ans_xd, 0); + } else ans = 0; return ans; diff --git a/traverser/bxutils-uil.c b/traverser/bxutils-uil.c index 94d466b4e1..a3611bd0da 100644 --- a/traverser/bxutils-uil.c +++ b/traverser/bxutils-uil.c @@ -156,7 +156,8 @@ static int StrCasecmp(char *, char *); * If you add to the array, ALWAYS keep NUM_COMMON_WCHARS as the last * entry in the enum. This will maintain correct memory usage, etc. */ -enum { +enum +{ WNull, WTab, WNewLine, @@ -248,19 +249,23 @@ static wchar_t *CStrCommonWideCharsGet(); * 1; s1 != s2 */ static int StrCasecmp ARGLIST((s1, s2)) ARG(register char *, s1) - GRA(register char *, s2) { + GRA(register char *, s2) +{ register int c1, c2; - while (*s1 && *s2) { + while (*s1 && *s2) + { c1 = isupper(*s1) ? tolower(*s1) : *s1; c2 = isupper(*s2) ? tolower(*s2) : *s2; - if (c1 != c2) { + if (c1 != c2) + { return (1); } s1++; s2++; } - if (*s1 || *s2) { + if (*s1 || *s2) + { return (1); } return (0); @@ -295,7 +300,8 @@ static int mblen ARGLIST((s, n)) ARG(char *, s) GRA(size_t, n) { return (1); } * Output: * int : the number of characters found */ -static int strlenWc ARGLIST((ptr)) GRA(wchar_t *, ptr) { +static int strlenWc ARGLIST((ptr)) GRA(wchar_t *, ptr) +{ register wchar_t *p = ptr; register int x = 0; @@ -320,11 +326,13 @@ static int strlenWc ARGLIST((ptr)) GRA(wchar_t *, ptr) { * bytesConv - size_t : number of bytes converted */ static size_t doMbstowcs ARGLIST((wcs, mbs, n)) ARG(wchar_t *, wcs) - ARG(char *, mbs) GRA(size_t, n) { + ARG(char *, mbs) GRA(size_t, n) +{ #ifndef SUPPORTS_WCHARS int i; - for (i = 0; i < n && mbs[i] != 0; ++i) { + for (i = 0; i < n && mbs[i] != 0; ++i) + { wcs[i] = mbs[i]; } wcs[i++] = 0; @@ -347,11 +355,13 @@ static size_t doMbstowcs ARGLIST((wcs, mbs, n)) ARG(wchar_t *, wcs) * bytesConv - size_t : number of bytes converted */ static size_t doWcstombs ARGLIST((mbs, wcs, n)) ARG(char *, mbs) - ARG(wchar_t *, wcs) GRA(size_t, n) { + ARG(wchar_t *, wcs) GRA(size_t, n) +{ #ifndef SUPPORTS_WCHARS int i; - for (i = 0; i < n && wcs[i] != 0; ++i) { + for (i = 0; i < n && wcs[i] != 0; ++i) + { mbs[i] = wcs[i]; } mbs[i] = 0; @@ -383,7 +393,8 @@ static size_t doWcstombs ARGLIST((mbs, wcs, n)) ARG(char *, mbs) * None */ static void copyWcsToMbs ARGLIST((mbs, wcs, len, process_it)) ARG(char *, mbs) - ARG(wchar_t *, wcs) ARG(int, len) GRA(Boolean, process_it) { + ARG(wchar_t *, wcs) ARG(int, len) GRA(Boolean, process_it) +{ static wchar_t *tbuf = NULL; static int tbufSize = 0; @@ -398,7 +409,8 @@ static void copyWcsToMbs ARGLIST((mbs, wcs, len, process_it)) ARG(char *, mbs) /* * Make sure there's room in the buffer */ - if (tbufSize < len) { + if (tbufSize < len) + { tbuf = (wchar_t *)XtRealloc((char *)tbuf, (len + 1) * sizeof(wchar_t)); tbufSize = len; } @@ -408,37 +420,55 @@ static void copyWcsToMbs ARGLIST((mbs, wcs, len, process_it)) ARG(char *, mbs) */ toP = tbuf; lenToConvert = 0; - while (fromP < x) { + while (fromP < x) + { /* * Check for quoted characters */ - if ((*fromP == commonWChars[WBackSlash]) && process_it) { - fromP++; /* Skip quote */ - if (fromP == x) { /* Hanging quote? */ + if ((*fromP == commonWChars[WBackSlash]) && process_it) + { + fromP++; /* Skip quote */ + if (fromP == x) + { /* Hanging quote? */ *toP++ = commonWChars[WBackSlash]; lenToConvert++; break; } tmp = *fromP++; - if (tmp == commonWChars[WideN]) { + if (tmp == commonWChars[WideN]) + { *toP++ = commonWChars[WNewLine]; - } else if (tmp == commonWChars[WideT]) { + } + else if (tmp == commonWChars[WideT]) + { *toP++ = commonWChars[WTab]; - } else if (tmp == commonWChars[WideR]) { + } + else if (tmp == commonWChars[WideR]) + { *toP++ = commonWChars[WCarriageReturn]; - } else if (tmp == commonWChars[WideF]) { + } + else if (tmp == commonWChars[WideF]) + { *toP++ = commonWChars[WFormFeed]; - } else if (tmp == commonWChars[WideV]) { + } + else if (tmp == commonWChars[WideV]) + { *toP++ = commonWChars[WVerticalTab]; - } else if (tmp == commonWChars[WBackSlash]) { + } + else if (tmp == commonWChars[WBackSlash]) + { *toP++ = commonWChars[WBackSlash]; - } else { + } + else + { /* * No special translation needed */ *toP++ = tmp; } - } else { + } + else + { *toP++ = *fromP++; } lenToConvert++; @@ -470,18 +500,22 @@ static void copyWcsToMbs ARGLIST((mbs, wcs, len, process_it)) ARG(char *, mbs) * the multibyte character. */ static int dombtowc ARGLIST((wide, multi, size)) ARG(wchar_t *, wide) - ARG(char *, multi) GRA(size_t, size) { + ARG(char *, multi) GRA(size_t, size) +{ int retVal = 0; #ifndef SUPPORTS_WCHARS - if ((multi == NULL) || (*multi == '\000')) { + if ((multi == NULL) || (*multi == '\000')) + { if (wide) wide[0] = '\0'; return (0); } - for (retVal = 0; retVal < size && multi[retVal] != '\000'; retVal++) { - if (wide != NULL) { + for (retVal = 0; retVal < size && multi[retVal] != '\000'; retVal++) + { + if (wide != NULL) + { wide[retVal] = multi[retVal]; } } @@ -503,22 +537,29 @@ static int dombtowc ARGLIST((wide, multi, size)) ARG(wchar_t *, wide) * ptr - wchar_t* : pointer to character, if found, points to end * of string otherwise ('\0'). */ -static wchar_t *getNextSeparator ARGLIST((str)) GRA(wchar_t *, str) { +static wchar_t *getNextSeparator ARGLIST((str)) GRA(wchar_t *, str) +{ wchar_t *ptr = str; wchar_t *commonWChars = CStrCommonWideCharsGet(); - while (*ptr) { + while (*ptr) + { /* * Check for separator */ if ((*ptr == commonWChars[WHash]) || (*ptr == commonWChars[WQuote]) || - (*ptr == commonWChars[WColon])) { + (*ptr == commonWChars[WColon])) + { return (ptr); - } else if (*ptr == commonWChars[WBackSlash]) { + } + else if (*ptr == commonWChars[WBackSlash]) + { ptr++; if (*ptr) ptr++; /* Skip quoted character */ - } else { + } + else + { ptr++; } } @@ -548,7 +589,8 @@ static wchar_t *getNextSeparator ARGLIST((str)) GRA(wchar_t *, str) { static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, pDir, pSep)) ARG(wchar_t **, str) ARG(wchar_t **, tagStart) ARG(size_t *, tagLen) ARG(wchar_t **, txtStart) - ARG(size_t *, txtLen) ARG(int *, pDir) GRA(Boolean *, pSep) { + ARG(size_t *, txtLen) ARG(int *, pDir) GRA(Boolean *, pSep) +{ wchar_t *start; wchar_t *text; int textL; @@ -582,7 +624,8 @@ static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, /* * Guard against nulls */ - if (!(start = *str)) { + if (!(start = *str)) + { start = emptyStrWcs; emptyStrWcs[0] = commonWChars[WNull]; } @@ -592,47 +635,65 @@ static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, * just have a regular old simple string. Do the same the thing for * the empty string. */ - if ((*start == '\0') || (start != getNextSeparator(start))) { + if ((*start == '\0') || (start != getNextSeparator(start))) + { text = start; - if (!(textL = strlenWc(start))) { + if (!(textL = strlenWc(start))) + { text = NULL; } start += textL; - } else { + } + else + { done = False; - while (!done) { - if (*start == commonWChars[WHash]) { - if (tagSeen) { + while (!done) + { + if (*start == commonWChars[WHash]) + { + if (tagSeen) + { done = True; break; - } else { + } + else + { tagSeen = True; tag = ++start; start = getNextSeparator(tag); - if ((tagL = start - tag) == 0) { + if ((tagL = start - tag) == 0) + { tag = NULL; /* Null tag specified */ } } - } else if (*start == commonWChars[WQuote]) { + } + else if (*start == commonWChars[WQuote]) + { text = ++start; start = getNextSeparator(start); while (!((*start == commonWChars[WQuote]) || - (*start == commonWChars[WNull]))) { + (*start == commonWChars[WNull]))) + { start = getNextSeparator(++start); } - if ((textL = start - text) == 0) { + if ((textL = start - text) == 0) + { text = NULL; /* Null text specified */ } /* * if a quote, skip over it */ - if (*start == commonWChars[WQuote]) { + if (*start == commonWChars[WQuote]) + { start++; } done = True; - } else if (*start == commonWChars[WColon]) { - if (modsSeen) { + } + else if (*start == commonWChars[WColon]) + { + if (modsSeen) + { done = True; break; } @@ -646,22 +707,29 @@ static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, start++; if ((*start == commonWChars[WideT]) || (*start == commonWChars[WideUT]) || - (*start == commonWChars[WideOne])) { + (*start == commonWChars[WideOne])) + { sep = True; start++; checkDir = True; - } else if ((*start == commonWChars[WideF]) || - (*start == commonWChars[WideUF]) || - (*start == commonWChars[WideZero])) { + } + else if ((*start == commonWChars[WideF]) || + (*start == commonWChars[WideUF]) || + (*start == commonWChars[WideZero])) + { sep = False; start++; checkDir = True; - } else if ((*start == commonWChars[WideR]) || - (*start == commonWChars[WideUR])) { + } + else if ((*start == commonWChars[WideR]) || + (*start == commonWChars[WideUR])) + { start++; dir = XmSTRING_DIRECTION_R_TO_L; - } else if ((*start == commonWChars[WideL]) || - (*start == commonWChars[WideUL])) { + } + else if ((*start == commonWChars[WideL]) || + (*start == commonWChars[WideUL])) + { start++; dir = XmSTRING_DIRECTION_L_TO_R; } @@ -669,18 +737,24 @@ static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, * Look for direction if necessary. This requires a bit of * look ahead. */ - if (checkDir && (*start == commonWChars[WColon])) { + if (checkDir && (*start == commonWChars[WColon])) + { if ((*(start + 1) == commonWChars[WideL]) || - (*(start + 1) == commonWChars[WideUL])) { + (*(start + 1) == commonWChars[WideUL])) + { dir = XmSTRING_DIRECTION_L_TO_R; start += 2; - } else if ((*(start + 1) == commonWChars[WideR]) || - (*(start + 1) == commonWChars[WideUR])) { + } + else if ((*(start + 1) == commonWChars[WideR]) || + (*(start + 1) == commonWChars[WideUR])) + { dir = XmSTRING_DIRECTION_R_TO_L; start += 2; } } - } else { + } + else + { /* * A bad string format! We'll just skip the character. */ @@ -720,7 +794,8 @@ static Boolean extractSegment ARGLIST((str, tagStart, tagLen, txtStart, txtLen, * Outputs: * xstr - XmString : the allocated return structure */ -static XmString StringToXmString ARGLIST((str)) GRA(char *, str) { +static XmString StringToXmString ARGLIST((str)) GRA(char *, str) +{ static char *tagBuf = NULL; static size_t tagBufLen = 0; static char *textBuf = NULL; @@ -762,12 +837,14 @@ static XmString StringToXmString ARGLIST((str)) GRA(char *, str) { */ more = True; ctx = wcStr; - while (more) { + while (more) + { more = extractSegment(&ctx, &tag, &tagLen, &text, &textLen, &dir, &sep); /* * Pick up a direction change */ - if (dir != curDir) { + if (dir != curDir) + { curDir = dir; s1 = XmStringDirectionCreate(curDir); s2 = xmStr; @@ -779,21 +856,28 @@ static XmString StringToXmString ARGLIST((str)) GRA(char *, str) { /* * Create the segment. Text and tag first. */ - if (textLen) { - if (textBufLen <= (textLen * sizeof(wchar_t))) { + if (textLen) + { + if (textBufLen <= (textLen * sizeof(wchar_t))) + { textBufLen = (textLen + 1) * sizeof(wchar_t); textBuf = (char *)XtRealloc(textBuf, textBufLen); } copyWcsToMbs(textBuf, text, textLen, True); - if (tagLen) { - if (tagBufLen <= (tagLen * sizeof(wchar_t))) { + if (tagLen) + { + if (tagBufLen <= (tagLen * sizeof(wchar_t))) + { tagBufLen = (tagLen + 1) * sizeof(wchar_t); tagBuf = (char *)XtRealloc(tagBuf, tagBufLen); } copyWcsToMbs(tagBuf, tag, tagLen, False); - } else { - if (!tagBuf) { + } + else + { + if (!tagBuf) + { tagBufLen = strlen(XmSTRING_DEFAULT_CHARSET) + 1; tagBuf = (char *)XtMalloc(tagBufLen); } @@ -810,7 +894,8 @@ static XmString StringToXmString ARGLIST((str)) GRA(char *, str) { /* * Add in the separators. */ - if (sep) { + if (sep) + { s1 = XmStringSeparatorCreate(); s2 = xmStr; xmStr = XmStringConcat(s2, s1); @@ -837,7 +922,8 @@ static XmString StringToXmString ARGLIST((str)) GRA(char *, str) { * nextCStr - char* : pointer to the next delimiter. Returns NULL if no * delimiter found. */ -static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) { +static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) +{ char *comma = str; Boolean inQuotes = False; int len; @@ -852,13 +938,16 @@ static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) { #else mblen(NULL, sizeof(wchar_t)); #endif - while (*comma) { - if ((len = mblen(comma, sizeof(wchar_t))) > 1) { + while (*comma) + { + if ((len = mblen(comma, sizeof(wchar_t))) > 1) + { comma += len; continue; } - if (*comma == '\\') { + if (*comma == '\\') + { comma++; /* Over quote */ comma += mblen(comma, sizeof(wchar_t)); continue; @@ -867,8 +956,10 @@ static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) { /* * See if we have a delimiter */ - if (!inQuotes) { - if ((*comma == ',') || (*comma == '\012')) { + if (!inQuotes) + { + if ((*comma == ',') || (*comma == '\012')) + { return (comma); } } @@ -876,7 +967,8 @@ static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) { /* * Deal with quotes */ - if (*comma == '\"') { + if (*comma == '\"') + { inQuotes = ~inQuotes; } @@ -897,7 +989,8 @@ static char *getNextCStrDelim ARGLIST((str)) GRA(char *, str) { * Output: * cnt - int : the number of XmStrings found */ -static int getCStrCount ARGLIST((str)) GRA(char *, str) { +static int getCStrCount ARGLIST((str)) GRA(char *, str) +{ int x = 1; char *newStr; @@ -906,7 +999,8 @@ static int getCStrCount ARGLIST((str)) GRA(char *, str) { if (!*str) return (0); - while ((newStr = getNextCStrDelim(str))) { + while ((newStr = getNextCStrDelim(str))) + { x++; str = ++newStr; } @@ -923,7 +1017,8 @@ static int getCStrCount ARGLIST((str)) GRA(char *, str) { * Output: * cwc - wchar_t * : this array should never be written to or FREEd. */ -static wchar_t *CStrCommonWideCharsGet() { +static wchar_t *CStrCommonWideCharsGet() +{ static wchar_t *CommonWideChars = NULL; /* * If you add to this array, don't forget to change the enum in @@ -931,10 +1026,11 @@ static wchar_t *CStrCommonWideCharsGet() { * array. */ static char *characters[] = {"\000", "\t", "\n", "\r", "\f", "\v", "\\", "\"", - "#", ":", "f", "l", "n", "r", "t", "v", - "F", "L", "R", "T", "0", "1"}; + "#", ":", "f", "l", "n", "r", "t", "v", + "F", "L", "R", "T", "0", "1"}; - if (CommonWideChars == NULL) { + if (CommonWideChars == NULL) + { int i; /* @@ -942,7 +1038,8 @@ static wchar_t *CStrCommonWideCharsGet() { */ CommonWideChars = (wchar_t *)XtMalloc(NUM_COMMON_WCHARS * sizeof(wchar_t)); - for (i = 0; i < NUM_COMMON_WCHARS; i++) { + for (i = 0; i < NUM_COMMON_WCHARS; i++) + { (void)dombtowc(&(CommonWideChars[i]), characters[i], 1); } } @@ -971,14 +1068,16 @@ static Boolean CvtStringToXmString ARGLIST((d, args, num_args, fromVal, toVal, UARG(XrmValue *, args __attribute__((unused))) ARG(Cardinal *, num_args __attribute__((unused))) ARG(XrmValue *, fromVal) ARG(XrmValue *, toVal) - GRAU(XtPointer, data __attribute__((unused))) { + GRAU(XtPointer, data __attribute__((unused))) +{ static XmString resStr; char *str; /* * This converter takes no parameters */ - if (*num_args != 0) { + if (*num_args != 0) + { XtAppWarningMsg(XtDisplayToApplicationContext(d), "cvtStringToXmString", "wrongParameters", "XtToolkitError", "String to XmString converter needs no extra arguments", @@ -989,9 +1088,12 @@ static Boolean CvtStringToXmString ARGLIST((d, args, num_args, fromVal, toVal, * See if this is a simple string */ str = (char *)fromVal->addr; - if (strncmp(str, "::", 2)) { + if (strncmp(str, "::", 2)) + { resStr = XmStringCreateLtoR(fromVal->addr, XmSTRING_DEFAULT_CHARSET); - } else { + } + else + { /* * Convert into internal format */ @@ -1001,15 +1103,20 @@ static Boolean CvtStringToXmString ARGLIST((d, args, num_args, fromVal, toVal, /* * Done, return result */ - if (toVal->addr == NULL) { + if (toVal->addr == NULL) + { toVal->addr = (XTPOINTER)&resStr; toVal->size = sizeof(XmString); - } else if (toVal->size < sizeof(XmString)) { + } + else if (toVal->size < sizeof(XmString)) + { toVal->size = sizeof(XmString); XtDisplayStringConversionWarning(d, fromVal->addr, "XmString"); XmStringFree(resStr); return (False); - } else { + } + else + { *(XmString *)toVal->addr = resStr; toVal->size = sizeof(XmString); } @@ -1020,7 +1127,8 @@ static void XmStringCvtDestroy ARGLIST((app, to, data, args, num_args)) UARG(XtAppContext, app __attribute__((unused))) ARG(XrmValue *, to) UARG(XtPointer, data __attribute__((unused))) UARG(XrmValue *, args __attribute__((unused))) - GRAU(Cardinal *, num_args __attribute__((unused))) { + GRAU(Cardinal *, num_args __attribute__((unused))) +{ XmStringFree(*(XmString *)(to->addr)); } @@ -1046,7 +1154,8 @@ static void XmStringCvtDestroy ARGLIST((app, to, data, args, num_args)) static Boolean CvtStringToXmStringTable ARGLIST((d, args, num_args, fromVal, toVal, data)) ARG(Display *, d) ARG(XrmValue *, args) ARG(Cardinal *, num_args) ARG(XrmValue *, fromVal) - ARG(XrmValue *, toVal) GRAU(XtPointer, data __attribute__((unused))) { + ARG(XrmValue *, toVal) GRAU(XtPointer, data __attribute__((unused))) +{ static XmString *CStrTable; XmString *tblPtr; char *str; @@ -1058,7 +1167,8 @@ static Boolean CvtStringToXmStringTable ARGLIST((d, args, num_args, fromVal, /* * This converter takes no parameters */ - if (*num_args != 0) { + if (*num_args != 0) + { XtAppWarningMsg( XtDisplayToApplicationContext(d), "cvtStringToXmStringTable", "wrongParameters", "XtToolkitError", @@ -1069,7 +1179,8 @@ static Boolean CvtStringToXmStringTable ARGLIST((d, args, num_args, fromVal, /* * Set str and make sure there's somethin' there */ - if (!(str = (char *)fromVal->addr)) { + if (!(str = (char *)fromVal->addr)) + { str = ""; } @@ -1090,14 +1201,17 @@ static Boolean CvtStringToXmStringTable ARGLIST((d, args, num_args, fromVal, * Create strings */ tblPtr = CStrTable; - if (*str) { - while (str) { + if (*str) + { + while (str) + { nextDelim = getNextCStrDelim(str); /* * Overwrite nextDelim */ - if (nextDelim) { + if (nextDelim) + { *nextDelim = '\0'; nextDelim++; } @@ -1134,20 +1248,26 @@ static Boolean CvtStringToXmStringTable ARGLIST((d, args, num_args, fromVal, /* * Done, return result */ - if (toVal->addr == NULL) { + if (toVal->addr == NULL) + { toVal->addr = (XTPOINTER)&CStrTable; toVal->size = sizeof(XmString); - } else if (toVal->size < sizeof(XmString *)) { + } + else if (toVal->size < sizeof(XmString *)) + { toVal->size = sizeof(XmString *); XtDisplayStringConversionWarning(d, fromVal->addr, "XmStringTable"); tblPtr = CStrTable; - while (*tblPtr) { + while (*tblPtr) + { XmStringFree(*tblPtr); } XtFree((char *)CStrTable); return (False); - } else { + } + else + { *(XmString **)toVal->addr = CStrTable; toVal->size = sizeof(XmString *); } @@ -1158,10 +1278,12 @@ static void XmStringTableCvtDestroy ARGLIST((app, to, data, args, num_args)) UARG(XtAppContext, app __attribute__((unused))) ARG(XrmValue *, to) UARG(XtPointer, data __attribute__((unused))) UARG(XrmValue *, args __attribute__((unused))) - GRAU(Cardinal *, num_args __attribute__((unused))) { + GRAU(Cardinal *, num_args __attribute__((unused))) +{ XmString *tblPtr = *(XmString **)(to->addr); - while (*tblPtr) { + while (*tblPtr) + { XmStringFree(*tblPtr); } XtFree((char *)(*(XmString **)(to->addr))); @@ -1184,7 +1306,8 @@ static void XmStringTableCvtDestroy ARGLIST((app, to, data, args, num_args)) * Output: * None */ -void RegisterBxConverters ARGLIST((appContext)) GRA(XtAppContext, appContext) { +void RegisterBxConverters ARGLIST((appContext)) GRA(XtAppContext, appContext) +{ XtAppSetTypeConverter(appContext, XmRString, XmRXmString, (XtTypeConverter)CvtStringToXmString, NULL, 0, XtCacheNone, XmStringCvtDestroy); @@ -1211,7 +1334,8 @@ void RegisterBxConverters ARGLIST((appContext)) GRA(XtAppContext, appContext) { #ifndef IGNORE_CONVERT XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) ARG(Widget, w) ARG(char *, from_string) ARG(char *, to_type) - ARG(int, to_size __attribute__((unused))) GRA(Boolean *, success) { + ARG(int, to_size __attribute__((unused))) GRA(Boolean *, success) +{ XrmValue fromVal, toVal; /* resource holders */ Boolean convResult; /* return value */ XtPointer val; /* Pointer size return value */ @@ -1250,7 +1374,8 @@ XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) * Now we have two conditions here. One the conversion was a success * and two the conversion failed. */ - if (!convResult) { + if (!convResult) + { /* * If this conversion failed that we can pretty much return right * here because there is nothing else we can do. @@ -1263,7 +1388,8 @@ XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) * well. Now we have to handle the special cases for type and * size constraints. */ - if (!strcmp(to_type, "String")) { + if (!strcmp(to_type, "String")) + { /* * Since strings are handled different in Xt we have to deal with * the conversion from a string to a string. When this happens the @@ -1272,11 +1398,17 @@ XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) * string conversion to happen so we do have to watch for it. */ val = (XTPOINTER)toVal.addr; - } else if (!strcmp(to_type, "Double")) { + } + else if (!strcmp(to_type, "Double")) + { val = (XTPOINTER)((double *)toVal.addr); - } else if (!strcmp(to_type, "Float")) { + } + else if (!strcmp(to_type, "Float")) + { val = (XTPOINTER)((float *)toVal.addr); - } else { + } + else + { /* * Here is the generic conversion return value handler. This * just does some size specific casting so that value that we @@ -1290,7 +1422,8 @@ XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) long l; XTPOINTER p; } uval; - switch (toVal.size) { + switch (toVal.size) + { case 1: uval.c = *(char *)toVal.addr; break; @@ -1340,7 +1473,8 @@ XtPointer CONVERT ARGLIST((w, from_string, to_type, to_size, success)) void MENU_POST ARGLIST((p, mw, ev, dispatch)) UARG(Widget, p __attribute__((unused))) ARG(XtPointer, mw) ARG(XEvent *, ev) - GRAU(Boolean *, dispatch __attribute__((unused))) { + GRAU(Boolean *, dispatch __attribute__((unused))) +{ Arg args[2]; int argcnt; Cardinal button; @@ -1381,7 +1515,8 @@ void MENU_POST ARGLIST((p, mw, ev, dispatch)) void SET_BACKGROUND_COLOR ARGLIST((w, args, argcnt, bg_color)) ARG(Widget, w __attribute__((unused))) ARG(ArgList, args) - ARG(Cardinal *, argcnt) GRA(Pixel, bg_color) { + ARG(Cardinal *, argcnt) GRA(Pixel, bg_color) +{ #if ((XmVERSION == 1) && (XmREVISION > 0)) int i; @@ -1395,16 +1530,24 @@ void SET_BACKGROUND_COLOR ARGLIST((w, args, argcnt, bg_color)) * bottom shadow colors. */ selectLoc = topShadowLoc = bottomShadowLoc = UNSET; - for (i = 0; i < *argcnt; i++) { + for (i = 0; i < *argcnt; i++) + { if ((strcmp(args[i].name, XmNtopShadowColor) == 0) || - (strcmp(args[i].name, XmNtopShadowPixmap) == 0)) { + (strcmp(args[i].name, XmNtopShadowPixmap) == 0)) + { topShadowLoc = i; - } else if ((strcmp(args[i].name, XmNbottomShadowColor) == 0) || - (strcmp(args[i].name, XmNbottomShadowPixmap) == 0)) { + } + else if ((strcmp(args[i].name, XmNbottomShadowColor) == 0) || + (strcmp(args[i].name, XmNbottomShadowPixmap) == 0)) + { bottomShadowLoc = i; - } else if (strcmp(args[i].name, XmNarmColor) == 0) { + } + else if (strcmp(args[i].name, XmNarmColor) == 0) + { selectLoc = i; - } else if (strcmp(args[i].name, XmNforeground) == 0) { + } + else if (strcmp(args[i].name, XmNforeground) == 0) + { fgLoc = i; } } @@ -1417,7 +1560,8 @@ void SET_BACKGROUND_COLOR ARGLIST((w, args, argcnt, bg_color)) * */ if ((bottomShadowLoc == UNSET) || (topShadowLoc == UNSET) || - (selectLoc == UNSET) || (fgLoc == UNSET)) { + (selectLoc == UNSET) || (fgLoc == UNSET)) + { Arg larg[1]; Colormap cmap; Pixel topShadow; @@ -1430,22 +1574,26 @@ void SET_BACKGROUND_COLOR ARGLIST((w, args, argcnt, bg_color)) XmGetColors(XtScreen(w), cmap, bg_color, &fgColor, &topShadow, &bottomShadow, &select); - if (topShadowLoc == UNSET) { + if (topShadowLoc == UNSET) + { XtSetArg(args[*argcnt], XmNtopShadowColor, topShadow); (*argcnt)++; } - if (bottomShadowLoc == UNSET) { + if (bottomShadowLoc == UNSET) + { XtSetArg(args[*argcnt], XmNbottomShadowColor, bottomShadow); (*argcnt)++; } - if (selectLoc == UNSET) { + if (selectLoc == UNSET) + { XtSetArg(args[*argcnt], XmNarmColor, select); (*argcnt)++; } - if (fgLoc == UNSET) { + if (fgLoc == UNSET) + { XtSetArg(args[*argcnt], XmNforeground, fgColor); (*argcnt)++; } @@ -1469,10 +1617,12 @@ void SET_BACKGROUND_COLOR ARGLIST((w, args, argcnt, bg_color)) #ifndef _BX_FIND_TOP_SHELL #define _BX_FIND_TOP_SHELL -Widget BxFindTopShell ARGLIST((start)) GRA(Widget, start) { +Widget BxFindTopShell ARGLIST((start)) GRA(Widget, start) +{ Widget p; - while ((p = XtParent(start))) { + while ((p = XtParent(start))) + { start = p; } return (start); @@ -1496,7 +1646,8 @@ Widget BxFindTopShell ARGLIST((start)) GRA(Widget, start) { #define _BX_WIDGETIDS_FROM_NAMES WidgetList BxWidgetIdsFromNames ARGLIST((ref, cbName, stringList)) - ARG(Widget, ref) ARG(char, *cbName) GRA(char, *stringList) { + ARG(Widget, ref) ARG(char, *cbName) GRA(char, *stringList) +{ WidgetList wgtIds = NULL; int wgtCount = 0; Widget inst; @@ -1515,24 +1666,31 @@ WidgetList BxWidgetIdsFromNames ARGLIST((ref, cbName, stringList)) else start = tmp; - while ((start && *start) && isspace(*start)) { + while ((start && *start) && isspace(*start)) + { start++; } ptr = strrchr(start, ']'); - if (ptr) { + if (ptr) + { *ptr = '\0'; } ptr = start + strlen(start) - 1; - while (ptr && *ptr) { - if (isspace(*ptr)) { + while (ptr && *ptr) + { + if (isspace(*ptr)) + { ptr--; - } else { + } + else + { ptr++; break; } } - if (ptr && *ptr) { + if (ptr && *ptr) + { *ptr = '\0'; } @@ -1542,20 +1700,27 @@ WidgetList BxWidgetIdsFromNames ARGLIST((ref, cbName, stringList)) * instance names. */ start = strtok(start, ","); - while (start) { - while ((start && *start) && isspace(*start)) { + while (start) + { + while ((start && *start) && isspace(*start)) + { start++; } ptr = start + strlen(start) - 1; - while (ptr && *ptr) { - if (isspace(*ptr)) { + while (ptr && *ptr) + { + if (isspace(*ptr)) + { ptr--; - } else { + } + else + { ptr++; break; } } - if (ptr && *ptr) { + if (ptr && *ptr) + { *ptr = '\0'; } @@ -1570,9 +1735,11 @@ WidgetList BxWidgetIdsFromNames ARGLIST((ref, cbName, stringList)) * or until the top of the hierarchy is reached. */ current = ref; - while (current != NULL) { + while (current != NULL) + { inst = XtNameToWidget(current, widget); - if (inst != NULL) { + if (inst != NULL) + { wgtCount++; wgtIds = (WidgetList)XtRealloc((char *)wgtIds, wgtCount * sizeof(Widget)); @@ -1582,7 +1749,8 @@ WidgetList BxWidgetIdsFromNames ARGLIST((ref, cbName, stringList)) current = XtParent(current); } - if (current == NULL) { + if (current == NULL) + { printf("Callback Error (%s):\n\t\ Cannot find widget %s\n", cbName, widget); @@ -1603,7 +1771,8 @@ Cannot find widget %s\n", } #endif /* _BX_WIDGETIDS_FROM_NAMES */ -XtPointer SINGLE ARGLIST((val)) GRA(float, val) { +XtPointer SINGLE ARGLIST((val)) GRA(float, val) +{ XtPointer pointer; pointer = (XtPointer)XtMalloc(sizeof(float)); @@ -1612,7 +1781,8 @@ XtPointer SINGLE ARGLIST((val)) GRA(float, val) { return (pointer); } -XtPointer DOUBLE ARGLIST((val)) GRA(double, val) { +XtPointer DOUBLE ARGLIST((val)) GRA(double, val) +{ XtPointer pointer; pointer = (XtPointer)XtMalloc(sizeof(double)); @@ -1646,7 +1816,8 @@ XtPointer call; { Widget *widAddr = (Widget *)client; - if (widAddr == NULL) { + if (widAddr == NULL) + { return; } *widAddr = w; diff --git a/traverser/main-uil.c b/traverser/main-uil.c index cdbe404948..14f3bdf9d0 100644 --- a/traverser/main-uil.c +++ b/traverser/main-uil.c @@ -161,7 +161,8 @@ Widget AddDialog; Widget AddDeviceDialog; Widget OpenDialog; int ClosingWindow = 0; -void CloseWindow(Widget w, caddr_t client_data, caddr_t call_data) { +void CloseWindow(Widget w, caddr_t client_data, caddr_t call_data) +{ ClosingWindow = 1; CloseTree(w, client_data, call_data); ClosingWindow = 0; @@ -170,7 +171,8 @@ void CloseWindow(Widget w, caddr_t client_data, caddr_t call_data) { /* * Main Program */ -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ Display *display; Arg args[256]; Cardinal ac; @@ -297,7 +299,8 @@ int main(int argc, char **argv) { options, XtNumber(options), &argc, argv); #endif #endif - if (display == NULL) { + if (display == NULL) + { XtWarning("cannot open display"); exit(1); } diff --git a/treeshr/Makefile.in b/treeshr/Makefile.in index c975b57e48..03b01b9f89 100644 --- a/treeshr/Makefile.in +++ b/treeshr/Makefile.in @@ -3,7 +3,7 @@ include @top_builddir@/Makefile.inc LIBPREFIX=Tree srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ @AX_RECONFIGURE_TARGET@ @@ -13,39 +13,8 @@ LIBS=-L@MAKESHLIBDIR@ @LIBS@ -lMdsShr @SRBLIB@ $(LIBSOCKET) $(THREAD) @MINGW_TRUE@ IMPLIB=@MAKELIBDIR@TreeShr.dll.a @MINGW_TRUE@ DEF=${srcdir}/TreeShr.def -SOURCES = \ -dummies.c \ -TreeAddNode.c \ -TreeAddTag.c \ -TreeCallHook.c \ -TreeCleanDatafile.c \ -TreeCreatePulseFile.c \ -TreeDeleteNode.c \ -TreeDeletePulseFile.c \ -TreeDoMethod.c \ -TreeFindNode.c \ -TreeFindTag.c \ -TreeFindTagWild.c \ -TreeGetDbi.c \ -TreeGetNci.c \ -TreeGetRecord.c \ -TreeGetSetShotId.c \ -TreeOpen.c \ -TreePerf.c \ -TreePutRecord.c \ -TreeRenameNode.c \ -TreeRemoveNodesTags.c\ -TreeSegments.c \ -TreeSerializeNci.c \ -TreeSetDbi.c \ -TreeSetDefault.c \ -TreeSetNci.c \ -TreeThreadStatic.c \ -TreeVerify.c \ -RemoteAccess.c \ -lex.yytreepath.c - -OBJECTS = $(SOURCES:.c=.o) +SOURCES = $(wildcard @srcdir@/*.c) +OBJECTS = $(SOURCES:@srcdir@/%.c=%.o) all : @MAKELIBDIR@ @MAKESHLIBDIR@ @MAKESHLIBDIR@@LIBPRE@TreeShr@SHARETYPE@ $(IMPLIB) @MAKELIBDIR@@LIBPRE@TreeShr.a @@ -66,7 +35,7 @@ install: $(libdir) @MINGW_TRUE@ MAKE_IMPLIB=-Wl,--out-implib,$(IMPLIB) -@MAKESHLIBDIR@@LIBPRE@TreeShr@SHARETYPE@ $(IMPLIB): $(OBJECTS) +@MAKESHLIBDIR@@LIBPRE@TreeShr@SHARETYPE@ $(IMPLIB): $(OBJECTS) $(LINK.c) $(OUTPUT_OPTION) @LINKSHARED@ $(OBJECTS) $(LIBS) $(MAKE_IMPLIB) @MAKELIBDIR@@LIBPRE@TreeShr.a : $(OBJECTS) diff --git a/treeshr/Notify.c b/treeshr/Notify.c.template similarity index 98% rename from treeshr/Notify.c rename to treeshr/Notify.c.template index 916a817832..5bf4dd951b 100644 --- a/treeshr/Notify.c +++ b/treeshr/Notify.c.template @@ -23,16 +23,19 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include +#include #include extern char *TreeGetPath(int); -int Notify(TreeshrHookType htype, char *tree, int shot, int nid) { +int Notify(TreeshrHookType htype, char *tree, int shot, int nid) +{ char *name; char def_name[50]; char *na = "N/A"; char *path = na; sprintf(def_name, "Hook number %d", htype); name = def_name; - switch (htype) { + switch (htype) + { case OpenTree: name = "OpenTree"; break; diff --git a/treeshr/RemoteAccess.c b/treeshr/RemoteAccess.c index 982f053439..017e4e2060 100644 --- a/treeshr/RemoteAccess.c +++ b/treeshr/RemoteAccess.c @@ -69,19 +69,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - do { \ +#define DBG(...) \ + do \ + { \ } while (0) #endif -static inline char *replaceBackslashes(char *filename) { +static inline char *replaceBackslashes(char *filename) +{ char *ptr; while ((ptr = strchr(filename, '\\')) != NULL) *ptr = '/'; return filename; } -typedef struct { +typedef struct +{ int conid; int connections; char *unique; @@ -90,7 +93,8 @@ typedef struct { #endif } host_t; -typedef struct host_list { +typedef struct host_list +{ struct host_list *next; host_t h; } host_list_t; @@ -99,8 +103,8 @@ static host_list_t *host_list = NULL; static int host_list_armed = FALSE; static pthread_mutex_t host_list_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t host_list_sig = PTHREAD_COND_INITIALIZER; -#define HOST_LIST_LOCK \ - pthread_mutex_lock(&host_list_lock); \ +#define HOST_LIST_LOCK \ + pthread_mutex_lock(&host_list_lock); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &host_list_lock); #define HOST_LIST_UNLOCK pthread_cleanup_pop(1); /** host_list_cleanup @@ -109,35 +113,45 @@ static pthread_cond_t host_list_sig = PTHREAD_COND_INITIALIZER; * Can be called by remote_access_disconnect() with conid>=0, * in which case it will only disconnect the desired connection. */ -static void host_list_cleanup(const int conid) { +static void host_list_cleanup(const int conid) +{ static int (*disconnectFromMds)(int) = NULL; - if - IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "DisconnectFromMds", - &disconnectFromMds)) - perror("Error loading MdsIpShr->DisconnectFromMds in host_list_cleanup"); + if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "DisconnectFromMds", + &disconnectFromMds))) + perror("Error loading MdsIpShr->DisconnectFromMds in host_list_cleanup"); host_list_t *host, *prev = NULL; - for (host = host_list; host;) { - if (conid >= 0 && host->h.conid != conid) { + for (host = host_list; host;) + { + if (conid >= 0 && host->h.conid != conid) + { prev = host; host = host->next; - } else { - if (host->h.connections <= 0) { + } + else + { + if (host->h.connections <= 0) + { DBG("Disconnecting %d: %d\n", host->h.conid, host->h.connections); if (disconnectFromMds && IS_NOT_OK(disconnectFromMds(host->h.conid))) fprintf(stderr, "Failed to disconnect Connection %d\n", host->h.conid); - if (prev) { + if (prev) + { prev->next = host->next; free(host->h.unique); free(host); host = prev->next; - } else { + } + else + { host_list = host->next; free(host->h.unique); free(host); host = host_list; } - } else { + } + else + { prev = host; host = host->next; } @@ -150,19 +164,24 @@ static void host_list_cleanup(const int conid) { * After the cleanup it will go into idle state. * Signalling host_cleaner_sig will wake it up or reset the timeout. */ -static void host_list_clean_main() { +static void host_list_clean_main() +{ HOST_LIST_LOCK; struct timespec tp; - do { // entering armed state + do + { // entering armed state host_list_armed = TRUE; clock_gettime(CLOCK_REALTIME, &tp); tp.tv_sec += 10; int err = pthread_cond_timedwait(&host_list_sig, &host_list_lock, &tp); if (!err) continue; // reset timeout - if (err == ETIMEDOUT) { + if (err == ETIMEDOUT) + { host_list_cleanup(-1); - } else { + } + else + { perror("PANIC in treeshr/RemoteAccess.c -> host_list_clean_main"); abort(); } // entering idle state @@ -175,7 +194,8 @@ static void host_list_clean_main() { * Creates the cleanup thread and detaches. * This method is only called once in host_list_schedule_cleanup() */ -static void host_list_init_cleanup() { +static void host_list_init_cleanup() +{ static pthread_t thread; int err = pthread_create(&thread, NULL, (void *)host_list_clean_main, NULL); if (!err) @@ -187,15 +207,17 @@ static void host_list_init_cleanup() { * If the cleanup cycle is not armed, it is not required to arm it. */ static int remote_access_connect(char *server, int inc_count, - void *dbid __attribute__((unused))) { + void *dbid __attribute__((unused))) +{ static int (*ReuseCheck)(char *, char *, int) = NULL; char unique[128] = "\0"; - if - IS_OK(LibFindImageSymbol_C("MdsIpShr", "ReuseCheck", &ReuseCheck)) { - if (ReuseCheck(server, unique, 128) < 0) - return -1; // TODO: check if this is required / desired - } - else { + if (IS_OK(LibFindImageSymbol_C("MdsIpShr", "ReuseCheck", &ReuseCheck))) + { + if (ReuseCheck(server, unique, 128) < 0) + return -1; // TODO: check if this is required / desired + } + else + { int i; for (i = 0; server[i] && i < 127; i++) unique[i] = tolower(server[i]); @@ -204,34 +226,41 @@ static int remote_access_connect(char *server, int inc_count, int conid; HOST_LIST_LOCK; host_list_t *host; - for (host = host_list; host; host = host->next) { - if (!strcmp(host->h.unique, unique)) { - if (inc_count) { + for (host = host_list; host; host = host->next) + { + if (!strcmp(host->h.unique, unique)) + { + if (inc_count) + { host->h.connections++; DBG("Connection %d> %d\n", host->h.conid, host->h.connections); - } else + } + else DBG("Connection %d= %d\n", host->h.conid, host->h.connections); break; } } static int (*ConnectToMds)(char *) = NULL; - if (!host) { - if - IS_OK(LibFindImageSymbol_C("MdsIpShr", "ConnectToMds", &ConnectToMds)) { - conid = ConnectToMds(unique); - if (conid > 0) { - DBG("New connection %d> %s\n", conid, unique); - host = malloc(sizeof(host_list_t)); - host->h.conid = conid; - host->h.connections = inc_count ? 1 : 0; - host->h.unique = strdup(unique); - host->next = host_list; - host_list = host; - } + if (!host) + { + if (IS_OK(LibFindImageSymbol_C("MdsIpShr", "ConnectToMds", &ConnectToMds))) + { + conid = ConnectToMds(unique); + if (conid > 0) + { + DBG("New connection %d> %s\n", conid, unique); + host = malloc(sizeof(host_list_t)); + host->h.conid = conid; + host->h.connections = inc_count ? 1 : 0; + host->h.unique = strdup(unique); + host->next = host_list; + host_list = host; } + } else conid = -1; - } else + } + else conid = host->h.conid; if (host_list_armed) pthread_cond_signal(&host_list_sig); @@ -245,27 +274,34 @@ static int remote_access_connect(char *server, int inc_count, * cleanup cycle. If the cleanup cycle is already armed, it is not required to * reset it. */ -static int remote_access_disconnect(int conid, int force) { +static int remote_access_disconnect(int conid, int force) +{ HOST_LIST_LOCK; host_list_t *host; for (host = host_list; host && host->h.conid != conid; host = host->next) ; - if (host) { - if (force) { + if (host) + { + if (force) + { fprintf(stderr, "Connection %d: forcefully disconnecting %d links\n", conid, host->h.connections); host->h.connections = 0; host_list_cleanup(conid); - } else { + } + else + { host->h.connections--; DBG("Connection %d< %d\n", conid, host->h.connections); - if (host->h.connections <= 0 && !host_list_armed) { + if (host->h.connections <= 0 && !host_list_armed) + { // arm host_list_cleaner RUN_FUNCTION_ONCE(host_list_init_cleanup); pthread_cond_signal(&host_list_sig); } } - } else + } + else DBG("Disconnected %d\n", conid); HOST_LIST_UNLOCK; return TreeSUCCESS; @@ -276,7 +312,8 @@ static int remote_access_disconnect(int conid, int force) { /////////////////////////////////////////////////////////////////// #define min(a, b) (((a) < (b)) ? (a) : (b)) -struct descrip { +struct descrip +{ char dtype; char ndims; int dims[MAX_DIMS]; @@ -284,17 +321,18 @@ struct descrip { void *ptr; }; -#define STR2DESCRIP(str) \ +#define STR2DESCRIP(str) \ (struct descrip) { DTYPE_T, 0, {0}, strlen(str), (char *)str } -static int MdsValue(int conid, char *exp, ...) { +static int MdsValue(int conid, char *exp, ...) +{ static int (*_mds_value)() = NULL; int status = LibFindImageSymbol_C("MdsIpShr", "_MdsValue", (void **)&_mds_value); - if - STATUS_NOT_OK { - fprintf(stderr, "Error loadig symbol MdsIpShr->_MdsValue: %d\n", status); - return status; - } + if (STATUS_NOT_OK) + { + fprintf(stderr, "Error loadig symbol MdsIpShr->_MdsValue: %d\n", status); + return status; + } int nargs; struct descrip *arglist[256]; VA_LIST_NULL(arglist, nargs, 1, -1, exp); @@ -303,128 +341,142 @@ static int MdsValue(int conid, char *exp, ...) { return _mds_value(conid, nargs, arglist, arglist[nargs]); } -static int MdsValueDsc(int conid, char *exp, ...) { +static int MdsValueDsc(int conid, char *exp, ...) +{ static int (*_mds_value_dsc)() = NULL; int status = LibFindImageSymbol_C("MdsIpShr", "MdsIpGetDescriptor", (void **)&_mds_value_dsc); - if - STATUS_NOT_OK { - fprintf(stderr, "Error loadig symbol MdsIpShr->MdsIpGetDescriptor: %d\n", - status); - return status; - } + if (STATUS_NOT_OK) + { + fprintf(stderr, "Error loadig symbol MdsIpShr->MdsIpGetDescriptor: %d\n", + status); + return status; + } int nargs; struct descrip *arglist[256]; VA_LIST_NULL(arglist, nargs, 0, -1, exp); return _mds_value_dsc(conid, exp, nargs, arglist, arglist[nargs]); } -inline static void MdsIpFree(void *ptr) { +inline static void MdsIpFree(void *ptr) +{ // used to free ans.ptr returned by MdsValue static void (*mdsIpFree)(void *) = NULL; - if - IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", &mdsIpFree)) return; + if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", &mdsIpFree))) + return; mdsIpFree(ptr); } -inline static void MdsIpFreeDsc(struct descriptor_xd *xd) { +inline static void MdsIpFreeDsc(struct descriptor_xd *xd) +{ // used to free ans.ptr returned by MdsValueDsc static void (*mdsIpFreeDsc)(struct descriptor_xd *) = NULL; - if - IS_NOT_OK( - LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", (void **)&mdsIpFreeDsc)) + if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", (void **)&mdsIpFreeDsc))) return; mdsIpFreeDsc(xd); } inline static int tree_open(PINO_DATABASE *dblist, int conid, - const char *treearg) { + const char *treearg) +{ int status; struct descrip ans = {0}; char exp[256]; sprintf(exp, "TreeShr->TreeOpen(ref($),val(%d),val(0))", dblist->shotid); struct descrip tree = STR2DESCRIP(treearg); status = MdsValue(conid, exp, &tree, &ans, NULL); - if (ans.ptr) { - if - STATUS_OK - status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : TreeFAILURE; + if (ans.ptr) + { + if (STATUS_OK) + status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : TreeFAILURE; MdsIpFree(ans.ptr); } return status; } int ConnectTreeRemote(PINO_DATABASE *dblist, char const *tree, - char *subtree_list, char *logname) { + char *subtree_list, char *logname) +{ int conid; logname[strlen(logname) - 2] = '\0'; int status = TreeSUCCESS; conid = remote_access_connect(logname, 1, (void *)dblist); - if (conid != -1) { + if (conid != -1) + { status = tree_open(dblist, conid, subtree_list ? subtree_list : tree); - if - STATUS_OK { - TREE_INFO *info; - /*********************************************** + if (STATUS_OK) + { + TREE_INFO *info; + /*********************************************** Get virtual memory for the tree information structure and zero the structure. ***********************************************/ - for (info = dblist->tree_info; info && strcmp(tree, info->treenam); - info = info->next_info) - ; - if (!info) { - info = malloc(sizeof(TREE_INFO) + sizeof(TREE_HEADER)); - if (info) { - memset(info, 0, sizeof(*info) + sizeof(TREE_HEADER)); - info->blockid = TreeBLOCKID; - info->flush = (dblist->shotid == -1); - info->header = (TREE_HEADER *)&info[1]; - info->treenam = strcpy(malloc(strlen(tree) + 1), tree); - TreeCallHookFun("TreeHook", "OpenTree", tree, dblist->shotid, NULL); - TreeCallHook(OpenTree, info, 0); - info->channel = conid; - dblist->tree_info = info; - dblist->remote = 1; - status = TreeSUCCESS; - } else - status = TreeFILE_NOT_FOUND; + for (info = dblist->tree_info; info && strcmp(tree, info->treenam); + info = info->next_info) + ; + if (!info) + { + info = malloc(sizeof(TREE_INFO) + sizeof(TREE_HEADER)); + if (info) + { + memset(info, 0, sizeof(*info) + sizeof(TREE_HEADER)); + info->blockid = TreeBLOCKID; + info->flush = (dblist->shotid == -1); + info->header = (TREE_HEADER *)&info[1]; + info->treenam = strcpy(malloc(strlen(tree) + 1), tree); + TreeCallHookFun("TreeHook", "OpenTree", tree, dblist->shotid, NULL); + TreeCallHook(OpenTree, info, 0); + info->channel = conid; + dblist->tree_info = info; + dblist->remote = 1; + status = TreeSUCCESS; } + else + status = TreeFILE_NOT_FOUND; } + } else remote_access_disconnect(conid, 0); - } else + } + else status = TreeCONNECTFAIL; return status; } int SetStackSizeRemote(PINO_DATABASE *dbid __attribute__((unused)), - int stack_size __attribute__((unused))) { + int stack_size __attribute__((unused))) +{ return 1; } int CloseTreeRemote(PINO_DATABASE *dblist, - int call_host __attribute__((unused))) { + int call_host __attribute__((unused))) +{ struct descrip ans = {0}; struct descrip tree = STR2DESCRIP(dblist->experiment); int status; char exp[80]; sprintf(exp, "TreeShr->TreeClose(ref($),val(%d))", dblist->shotid); status = MdsValue(dblist->tree_info->channel, exp, &tree, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } remote_access_disconnect(dblist->tree_info->channel, 0); - if (dblist->tree_info) { + if (dblist->tree_info) + { free(dblist->tree_info->treenam); free(dblist->tree_info); dblist->tree_info = NULL; } - if (dblist->experiment) { + if (dblist->experiment) + { free(dblist->experiment); dblist->experiment = NULL; } - if (dblist->main_treenam) { + if (dblist->main_treenam) + { free(dblist->main_treenam); dblist->main_treenam = NULL; } @@ -432,14 +484,16 @@ int CloseTreeRemote(PINO_DATABASE *dblist, return status; } -int CreatePulseFileRemote(PINO_DATABASE *dblist, int shot, int num, int *nids) { +int CreatePulseFileRemote(PINO_DATABASE *dblist, int shot, int num, int *nids) +{ char exp[80]; sprintf(exp, "TreeShr->TreeCreatePulseFile(val(%d),val(%d),ref($))", shot, num); struct descrip arr = {DTYPE_L, 1, {num}, sizeof(int), (void *)nids}; struct descrip ans = {0}; int status = MdsValue(dblist->tree_info->channel, exp, &arr, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } @@ -447,16 +501,16 @@ int CreatePulseFileRemote(PINO_DATABASE *dblist, int shot, int num, int *nids) { } int GetRecordRemote(PINO_DATABASE *dblist, int nid_in, - struct descriptor_xd *dsc) { + struct descriptor_xd *dsc) +{ int status; char exp[80]; sprintf(exp, "getnci(%d,'RECORD')", nid_in); #ifdef STRICT_MDSIPFREE EMPTYXD(ans); status = MdsValueDsc(dblist->tree_info->channel, exp, &ans, NULL); - if - STATUS_OK - MdsCopyDxXd(&ans, dsc); + if (STATUS_OK) + MdsCopyDxXd(&ans, dsc); MdsIpFreeDsc(&ans); #else status = MdsValueDsc(dblist->tree_info->channel, exp, dsc, NULL); @@ -466,11 +520,14 @@ int GetRecordRemote(PINO_DATABASE *dblist, int nid_in, return status; } -int LeadingBackslash(char const *path) { +int LeadingBackslash(char const *path) +{ size_t i; size_t len = strlen(path); - for (i = 0; i < len; i++) { - if ((path[i] != 32) && (path[i] != 9)) { + for (i = 0; i < len; i++) + { + if ((path[i] != 32) && (path[i] != 9)) + { if (path[i] == '\\') return 1; else @@ -480,7 +537,8 @@ int LeadingBackslash(char const *path) { return 0; } -int FindNodeRemote(PINO_DATABASE *dblist, char const *path, int *outnid) { +int FindNodeRemote(PINO_DATABASE *dblist, char const *path, int *outnid) +{ struct descrip ans = {0}; int status; INIT_AND_FREE_ON_EXIT(char *, exp); @@ -488,28 +546,31 @@ int FindNodeRemote(PINO_DATABASE *dblist, char const *path, int *outnid) { sprintf(exp, "getnci(%s%s,'nid_number')", path[0] == '-' ? "." : "", path); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); FREE_NOW(exp); - if - STATUS_OK { - if (ans.ptr) - *outnid = *(int *)ans.ptr; - else - status = TreeNNF; - } + if (STATUS_OK) + { + if (ans.ptr) + *outnid = *(int *)ans.ptr; + else + status = TreeNNF; + } if (ans.ptr) MdsIpFree(ans.ptr); return status; } -struct _FindNodeStruct { +struct _FindNodeStruct +{ int *nids; int num; void *ptr; }; int FindNodeEndRemote(PINO_DATABASE *dblist __attribute__((unused)), - void **ctx_inout) { + void **ctx_inout) +{ struct _FindNodeStruct *ctx = (struct _FindNodeStruct *)*ctx_inout; - if (ctx) { + if (ctx) + { MdsIpFree(ctx->ptr); free(ctx); *ctx_inout = 0; @@ -518,48 +579,57 @@ int FindNodeEndRemote(PINO_DATABASE *dblist __attribute__((unused)), } int FindNodeWildRemote(PINO_DATABASE *dblist, char const *patharg, int *nid_out, - void **ctx_inout, int usage_mask) { + void **ctx_inout, int usage_mask) +{ int status = TreeSUCCESS; struct _FindNodeStruct *ctx = (struct _FindNodeStruct *)*ctx_inout; - if (!ctx) { + if (!ctx) + { struct descrip ans = {0}; struct descrip path = STR2DESCRIP(patharg); char exp[80]; sprintf(exp, "TreeFindNodeWild($,%d)", usage_mask); status = MdsValue(dblist->tree_info->channel, exp, &path, &ans, NULL); - if - STATUS_OK { - if (ans.ptr) { - ctx = malloc(sizeof(struct _FindNodeStruct)); - ctx->nids = ctx->ptr = (int *)ans.ptr; - ctx->num = ans.dims[0]; - *ctx_inout = (void *)ctx; - } else - status = TreeNNF; + if (STATUS_OK) + { + if (ans.ptr) + { + ctx = malloc(sizeof(struct _FindNodeStruct)); + ctx->nids = ctx->ptr = (int *)ans.ptr; + ctx->num = ans.dims[0]; + *ctx_inout = (void *)ctx; } + else + status = TreeNNF; + } } - if - STATUS_OK { - if (ctx->num > 0) { - *nid_out = *ctx->nids; - ctx->num--; - ctx->nids++; - } else { - FindNodeEndRemote(dblist, ctx_inout); - status = TreeNMN; - } + if (STATUS_OK) + { + if (ctx->num > 0) + { + *nid_out = *ctx->nids; + ctx->num--; + ctx->nids++; } + else + { + FindNodeEndRemote(dblist, ctx_inout); + status = TreeNMN; + } + } return status; } char *FindNodeTagsRemote(PINO_DATABASE *dblist, int nid_in, - void **ctx_ptr __attribute__((unused))) { + void **ctx_ptr __attribute__((unused))) +{ struct descrip ans = {0}; char exp[80]; char *tag = 0; sprintf(exp, "TreeFindNodeTags(%d)", nid_in); MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { if ((ans.dtype == DTYPE_BU) && (strlen(ans.ptr) > 0)) tag = strdup(ans.ptr); MdsIpFree(ans.ptr); @@ -567,12 +637,14 @@ char *FindNodeTagsRemote(PINO_DATABASE *dblist, int nid_in, return tag; } -char *AbsPathRemote(PINO_DATABASE *dblist, char const *inpatharg) { +char *AbsPathRemote(PINO_DATABASE *dblist, char const *inpatharg) +{ char *retans = 0; struct descrip ans = {0}; struct descrip inpath = STR2DESCRIP(inpatharg); MdsValue(dblist->tree_info->channel, "TreeAbsPath($)", &inpath, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { if (ans.dtype == DTYPE_T && (strlen(ans.ptr) > 0)) retans = strcpy(malloc(strlen(ans.ptr) + 1), ans.ptr); MdsIpFree(ans.ptr); @@ -580,35 +652,39 @@ char *AbsPathRemote(PINO_DATABASE *dblist, char const *inpatharg) { return retans; } -int SetDefaultNidRemote(PINO_DATABASE *dblist, int nid) { +int SetDefaultNidRemote(PINO_DATABASE *dblist, int nid) +{ struct descrip ans = {0}; char exp[80]; int status; sprintf(exp, "TreeShr->TreeSetDefaultNid(val(%d))", nid); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int GetDefaultNidRemote(PINO_DATABASE *dblist, int *nid) { +int GetDefaultNidRemote(PINO_DATABASE *dblist, int *nid) +{ struct descrip ans = {0}; int status = MdsValue(dblist->tree_info->channel, "_=0;TreeShr->TreeGetDefaultNid(ref(_));_", &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { if (ans.dtype == DTYPE_L) *nid = *(int *)ans.ptr; - else if - STATUS_OK - status = 0; + else if (STATUS_OK) + status = 0; MdsIpFree(ans.ptr); } return status; } -typedef struct tag_search { +typedef struct tag_search +{ int next_tag; TREE_INFO *this_tree_info; struct descriptor_d search_tag; @@ -621,10 +697,12 @@ typedef struct tag_search { } TAG_SEARCH; char *FindTagWildRemote(PINO_DATABASE *dblist, const char *wildarg, int *nidout, - void **ctx_inout) { + void **ctx_inout) +{ TAG_SEARCH **ctx = (TAG_SEARCH **)ctx_inout; char exp[256]; - if (!*ctx) { + if (!*ctx) + { *ctx = malloc(sizeof(TAG_SEARCH)); (*ctx)->remote = 1; (*ctx)->conid = dblist->tree_info->channel; @@ -638,30 +716,35 @@ char *FindTagWildRemote(PINO_DATABASE *dblist, const char *wildarg, int *nidout, "xd(__c));execute('deallocate(\"__*\");`list(*,___,__a,__b,__c)')", (*ctx)->ctx); int status = MdsValueDsc(dblist->tree_info->channel, exp, &wild, &ans, NULL); - if - STATUS_OK { - struct descriptor **list = (struct descriptor **)ans.pointer->pointer; - status = *(int *)list[0]->pointer; - if (nidout) - *nidout = *(int *)list[1]->pointer; - (*ctx)->ctx = *(uint64_t *)list[2]->pointer; - if ((*ctx)->ctx) { - size_t len = list[3]->length < sizeof((*ctx)->answer) - ? list[3]->length - : sizeof((*ctx)->answer) - 1; - memcpy((*ctx)->answer, list[3]->pointer, len); - (*ctx)->answer[len] = '\0'; - } else - status = TreeFAILURE; + if (STATUS_OK) + { + struct descriptor **list = (struct descriptor **)ans.pointer->pointer; + status = *(int *)list[0]->pointer; + if (nidout) + *nidout = *(int *)list[1]->pointer; + (*ctx)->ctx = *(uint64_t *)list[2]->pointer; + if ((*ctx)->ctx) + { + size_t len = list[3]->length < sizeof((*ctx)->answer) + ? list[3]->length + : sizeof((*ctx)->answer) - 1; + memcpy((*ctx)->answer, list[3]->pointer, len); + (*ctx)->answer[len] = '\0'; } + else + status = TreeFAILURE; + } MdsIpFreeDsc(&ans); return STATUS_OK ? (*ctx)->answer : NULL; } -void FindTagEndRemote(void **ctx_inout) { +void FindTagEndRemote(void **ctx_inout) +{ TAG_SEARCH **ctx = (TAG_SEARCH **)ctx_inout; - if (*ctx) { - if ((*ctx)->ctx) { + if (*ctx) + { + if ((*ctx)->ctx) + { char exp[128]; sprintf(exp, "TreeShr->TreeFindTagEnd(val(0x%" PRIx64 "QU))", (*ctx)->ctx); @@ -675,13 +758,16 @@ void FindTagEndRemote(void **ctx_inout) { } } -int GetNciRemote(PINO_DATABASE *dblist, int nid_in, struct nci_itm *nci_itm) { +int GetNciRemote(PINO_DATABASE *dblist, int nid_in, struct nci_itm *nci_itm) +{ int status = TreeSUCCESS; NCI_ITM *itm; struct descrip ans; - for (itm = nci_itm; itm->code != NciEND_OF_LIST && status & 1; itm++) { + for (itm = nci_itm; itm->code != NciEND_OF_LIST && status & 1; itm++) + { char *getnci_str = NULL; - switch (itm->code) { + switch (itm->code) + { case NciDEPTH: getnci_str = "getnci(%d,'depth')"; break; @@ -794,92 +880,108 @@ int GetNciRemote(PINO_DATABASE *dblist, int nid_in, struct nci_itm *nci_itm) { status = TreeILLEGAL_ITEM; break; } - if - STATUS_OK { - char exp[1024]; - sprintf(exp, getnci_str, nid_in); - status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if - STATUS_OK { - if (ans.ptr && ans.length) { - int length = ans.length * (ans.ndims ? ans.dims[0] : 1); - if (itm->return_length_address) - *itm->return_length_address = length; - if ((ans.dtype == DTYPE_T) && (itm->pointer == 0)) { - itm->pointer = memcpy(malloc(length + 1), ans.ptr, length); - ((char *)itm->pointer)[length] = '\0'; - } else { - memcpy(itm->pointer, ans.ptr, min(itm->buffer_length, length)); - /* if (itm->buffer_length < length) status = + if (STATUS_OK) + { + char exp[1024]; + sprintf(exp, getnci_str, nid_in); + status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); + if (STATUS_OK) + { + if (ans.ptr && ans.length) + { + int length = ans.length * (ans.ndims ? ans.dims[0] : 1); + if (itm->return_length_address) + *itm->return_length_address = length; + if ((ans.dtype == DTYPE_T) && (itm->pointer == 0)) + { + itm->pointer = memcpy(malloc(length + 1), ans.ptr, length); + ((char *)itm->pointer)[length] = '\0'; + } + else + { + memcpy(itm->pointer, ans.ptr, min(itm->buffer_length, length)); + /* if (itm->buffer_length < length) status = * TreeBUFFEROVF; */ - } - free(ans.ptr); - } else - status = 0; } + free(ans.ptr); + } + else + status = 0; } + } } return status; } int PutRecordRemote(PINO_DATABASE *dblist, int nid_in, struct descriptor *dsc, - int utility_update) { + int utility_update) +{ int status; EMPTYXD(ans); char exp[80]; - if (dsc) { + if (dsc) + { sprintf(exp, "TreeShr->TreePutRecord(val(%d),xd($),val(%d))", nid_in, utility_update); status = MdsValueDsc(dblist->tree_info->channel, exp, dsc, &ans, NULL); - } else { + } + else + { sprintf(exp, "TreeShr->TreePutRecord(val(%d),val(0),val(%d))", nid_in, utility_update); status = MdsValueDsc(dblist->tree_info->channel, exp, &ans, NULL); } - if (ans.pointer) { + if (ans.pointer) + { if (ans.pointer->dtype == DTYPE_L) status = *(int *)ans.pointer->pointer; - else if - STATUS_OK - status = 0; + else if (STATUS_OK) + status = 0; MdsFree1Dx(&ans, NULL); } MdsIpFreeDsc(&ans); return status; } -int SetNciItmRemote(PINO_DATABASE *dblist, int nid, int code, int value) { +int SetNciItmRemote(PINO_DATABASE *dblist, int nid, int code, int value) +{ struct descrip ans = {0}; char exp[80]; int status; sprintf(exp, "TreeShr->TreeSetNciItm(val(%d),val(%d),val(%d))", nid, code, value); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int SetDbiItmRemote(PINO_DATABASE *dblist, int code, int value) { +int SetDbiItmRemote(PINO_DATABASE *dblist, int code, int value) +{ struct descrip ans = {0}; char exp[64]; sprintf(exp, "TreeShr->TreeSetDbiItm(val(%d),val(%d))", code, value); int status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int SetNciRemote(PINO_DATABASE *dblist, int nid, NCI_ITM *nci_itm) { +int SetNciRemote(PINO_DATABASE *dblist, int nid, NCI_ITM *nci_itm) +{ int status = 1; NCI_ITM *itm_ptr; for (itm_ptr = nci_itm; itm_ptr->code != NciEND_OF_LIST && status & 1; - itm_ptr++) { - switch (itm_ptr->code) { + itm_ptr++) + { + switch (itm_ptr->code) + { case NciSTATUS: case NciCLEAR_FLAGS: case NciSET_FLAGS: @@ -894,12 +996,15 @@ int SetNciRemote(PINO_DATABASE *dblist, int nid, NCI_ITM *nci_itm) { return status; } -int SetDbiRemote(PINO_DATABASE *dblist, DBI_ITM *dbi_itm) { +int SetDbiRemote(PINO_DATABASE *dblist, DBI_ITM *dbi_itm) +{ int status = 1; DBI_ITM *itm_ptr; for (itm_ptr = dbi_itm; itm_ptr->code != DbiEND_OF_LIST && status & 1; - itm_ptr++) { - switch (itm_ptr->code) { + itm_ptr++) + { + switch (itm_ptr->code) + { case DbiVERSIONS_IN_MODEL: case DbiVERSIONS_IN_PULSE: status = @@ -913,66 +1018,77 @@ int SetDbiRemote(PINO_DATABASE *dblist, DBI_ITM *dbi_itm) { return status; } -int TreeFlushOffRemote(PINO_DATABASE *dblist, int nid) { +int TreeFlushOffRemote(PINO_DATABASE *dblist, int nid) +{ struct descrip ans = {0}; char exp[64]; sprintf(exp, "TreeShr->TreeFlushOff(val(%d))", nid); int status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int TreeFlushResetRemote(PINO_DATABASE *dblist, int nid) { +int TreeFlushResetRemote(PINO_DATABASE *dblist, int nid) +{ struct descrip ans = {0}; char exp[64]; int status; sprintf(exp, "TreeShr->TreeFlushReset(val(%d))", nid); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int TreeTurnOnRemote(PINO_DATABASE *dblist, int nid) { +int TreeTurnOnRemote(PINO_DATABASE *dblist, int nid) +{ struct descrip ans = {0}; char exp[64]; int status; sprintf(exp, "TreeShr->TreeTurnOn(val(%d))", nid); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int TreeTurnOffRemote(PINO_DATABASE *dblist, int nid) { +int TreeTurnOffRemote(PINO_DATABASE *dblist, int nid) +{ struct descrip ans = {0}; char exp[64]; int status; sprintf(exp, "TreeShr->TreeTurnOff(val(%d))", nid); status = MdsValue(dblist->tree_info->channel, exp, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } return status; } -int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) { +int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) +{ int status = TreeFAILURE; int channel = remote_access_connect(path, 0, 0); - if (channel > 0) { + if (channel > 0) + { struct descrip ans = {0}; struct descrip tree = STR2DESCRIP(treearg); status = MdsValue(channel, "TreeShr->TreeGetCurrentShotId(ref($))", &tree, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { if (ans.dtype == DTYPE_L) *shot = *(int *)ans.ptr; else @@ -983,16 +1099,19 @@ int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) { return status; } -int TreeSetCurrentShotIdRemote(const char *treearg, char *path, int shot) { +int TreeSetCurrentShotIdRemote(const char *treearg, char *path, int shot) +{ int status = 0; int channel = remote_access_connect(path, 0, 0); - if (channel > 0) { + if (channel > 0) + { struct descrip ans = {0}; struct descrip tree = STR2DESCRIP(treearg); char exp[64]; sprintf(exp, "TreeShr->TreeSetCurrentShotId(ref($),val(%d))", shot); status = MdsValue(channel, exp, &tree, &ans, NULL); - if (ans.ptr) { + if (ans.ptr) + { status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } @@ -1014,44 +1133,52 @@ extern char *TreePath(char const *tree, char *tree_lower_out); extern void TreePerfWrite(int); extern void TreePerfRead(int); -typedef struct { +typedef struct +{ int conid; int fd; int enhanced; } fdinfo_t; -static struct fd_info_struct { +static struct fd_info_struct +{ int in_use; fdinfo_t i; } *FDS = 0; static int ALLOCATED_FDS = 0; -typedef struct iolock_s { +typedef struct iolock_s +{ int (*io_lock)(); fdinfo_t fd; off_t offset; size_t size; int *deleted; } iolock_t; -static void mds_io_unlock(void *in) { +static void mds_io_unlock(void *in) +{ iolock_t *l = (iolock_t *)in; l->io_lock(l->fd, l->offset, l->size, MDS_IO_LOCK_NONE, l->deleted); } -#define IO_RDLOCK_FILE(io_lock, fd, offset, size, deleted) \ - io_lock(fd, offset, size, MDS_IO_LOCK_RD, deleted); \ - iolock_t iolock = {io_lock, fd, offset, size, deleted}; \ +#define IO_RDLOCK_FILE(io_lock, fd, offset, size, deleted) \ + io_lock(fd, offset, size, MDS_IO_LOCK_RD, deleted); \ + iolock_t iolock = {io_lock, fd, offset, size, deleted}; \ pthread_cleanup_push(mds_io_unlock, &iolock); #define IO_UNLOCK_FILE() pthread_cleanup_pop(1); -char *ParseFile(char *filename, char **hostpart, char **filepart) { +char *ParseFile(char *filename, char **hostpart, char **filepart) +{ char *tmp = strcpy((char *)malloc(strlen(filename) + 1), filename); char *ptr = strstr(tmp, "::"); - if (ptr) { + if (ptr) + { *hostpart = tmp; *filepart = ptr + 2; *ptr = (char)0; - } else { + } + else + { *hostpart = 0; *filepart = tmp; } @@ -1059,12 +1186,13 @@ char *ParseFile(char *filename, char **hostpart, char **filepart) { } static pthread_mutex_t fds_lock = PTHREAD_MUTEX_INITIALIZER; -#define FDS_LOCK \ - pthread_mutex_lock(&fds_lock); \ +#define FDS_LOCK \ + pthread_mutex_lock(&fds_lock); \ pthread_cleanup_push((void *)pthread_mutex_unlock, &fds_lock); #define FDS_UNLOCK pthread_cleanup_pop(1); -int ADD_FD(int fd, int conid, int enhanced) { +int ADD_FD(int fd, int conid, int enhanced) +{ int idx; FDS_LOCK; for (idx = 0; idx < ALLOCATED_FDS && FDS[idx].in_use; idx++) @@ -1079,19 +1207,23 @@ int ADD_FD(int fd, int conid, int enhanced) { return idx + 1; } -inline static fdinfo_t RM_FD(int idx) { +inline static fdinfo_t RM_FD(int idx) +{ fdinfo_t fdinfo; FDS_LOCK; - if (idx > 0 && idx <= ALLOCATED_FDS && FDS[idx - 1].in_use) { + if (idx > 0 && idx <= ALLOCATED_FDS && FDS[idx - 1].in_use) + { fdinfo = FDS[idx - 1].i; FDS[idx - 1].in_use = B_FALSE; - } else + } + else fdinfo = (fdinfo_t){-1, -1, -1}; FDS_UNLOCK; return fdinfo; } -inline static fdinfo_t GET_FD(int idx) { +inline static fdinfo_t GET_FD(int idx) +{ fdinfo_t fdinfo; FDS_LOCK; if (idx > 0 && idx <= ALLOCATED_FDS && FDS[idx - 1].in_use) @@ -1102,7 +1234,8 @@ inline static fdinfo_t GET_FD(int idx) { return fdinfo; } -EXPORT int MDS_IO_ID(int idx) { +EXPORT int MDS_IO_ID(int idx) +{ int id; FDS_LOCK; id = (idx > 0 && idx <= ALLOCATED_FDS && FDS[idx - 1].in_use) @@ -1112,7 +1245,8 @@ EXPORT int MDS_IO_ID(int idx) { return id; } -EXPORT int MDS_IO_FD(int idx) { +EXPORT int MDS_IO_FD(int idx) +{ int fd; FDS_LOCK; fd = (idx > 0 && idx <= ALLOCATED_FDS && FDS[idx - 1].in_use) @@ -1126,71 +1260,79 @@ static int (*SendArg)() = NULL; static int (*GetAnswerInfoTS)() = NULL; static inline int mds_io_request(int conid, mds_io_mode idx, size_t size, mdsio_t *mdsio, char *din, int *bytes, - char **dout, void **m) { + char **dout, void **m) +{ int status; static pthread_mutex_t io_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&io_lock); pthread_cleanup_push((void *)pthread_mutex_unlock, &io_lock); char nargs = size / sizeof(int); status = SendArg(conid, (int)idx, 0, 0, 0, nargs, mdsio->dims, din); - if - STATUS_NOT_OK { - if (idx != MDS_IO_CLOSE_K) - fprintf(stderr, "Error in SendArg: mode = %d, status = %d\n", idx, - status); - remote_access_disconnect(conid, 1); - } - else { + if (STATUS_NOT_OK) + { + if (idx != MDS_IO_CLOSE_K) + fprintf(stderr, "Error in SendArg: mode = %d, status = %d\n", idx, + status); + remote_access_disconnect(conid, 1); + } + else + { int d[MAX_DIMS]; status = GetAnswerInfoTS(conid, (char *)d, (short *)d, (char *)d, d, bytes, (void **)dout, m); - if - STATUS_NOT_OK { - if (idx != MDS_IO_CLOSE_K) - fprintf(stderr, "Error in GetAnswerInfoTS: mode = %d, status = %d\n", - idx, status); - remote_access_disconnect(conid, 0); - } + if (STATUS_NOT_OK) + { + if (idx != MDS_IO_CLOSE_K) + fprintf(stderr, "Error in GetAnswerInfoTS: mode = %d, status = %d\n", + idx, status); + remote_access_disconnect(conid, 0); + } } pthread_cleanup_pop(1); return status; } EXPORT int MdsIoRequest(int conid, mds_io_mode idx, size_t size, mdsio_t *mdsio, - char *din, int *bytes, char **dout, void **m) { + char *din, int *bytes, char **dout, void **m) +{ int status = LibFindImageSymbol_C("MdsIpShr", "SendArg", &SendArg); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; status = LibFindImageSymbol_C("MdsIpShr", "GetAnswerInfoTS", &GetAnswerInfoTS); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; return mds_io_request(conid, idx, size, mdsio, din, bytes, dout, m); } inline static int io_open_request(int conid, int *enhanced, size_t size, - mdsio_t *mdsio, char *filename) { + mdsio_t *mdsio, char *filename) +{ int fd; INIT_AND_FREE_ON_EXIT(void *, msg); int len; char *dout; int status = MdsIoRequest(conid, MDS_IO_OPEN_K, size, mdsio, filename, &len, &dout, &msg); - if (STATUS_OK && sizeof(int) == len) { + if (STATUS_OK && sizeof(int) == len) + { fd = *(int *)dout; *enhanced = status == 3; - } else + } + else fd = -1; FREE_NOW(msg); return fd; } inline static int io_open_remote(char *host, char *filename, int options, - mode_t mode, int *conid, int *enhanced) { + mode_t mode, int *conid, int *enhanced) +{ int fd; mdsio_t mdsio = { .open = {.length = strlen(filename) + 1, .options = 0, .mode = mode}}; - if (O_CREAT == 0x0200) { /* BSD */ + if (O_CREAT == 0x0200) + { /* BSD */ if (options & O_CREAT) options = (options & ~O_CREAT) | 0100; if (options & O_TRUNC) @@ -1212,12 +1354,15 @@ inline static int io_open_remote(char *host, char *filename, int options, mdsio.open.options |= MDS_IO_O_RDWR; if (*conid == -1) *conid = remote_access_connect(host, 1, 0); - if (*conid != -1) { + if (*conid != -1) + { fd = io_open_request(*conid, enhanced, sizeof(mdsio.open), &mdsio, filename); if (fd < 0) remote_access_disconnect(*conid, B_FALSE); - } else { + } + else + { fd = -1; fprintf(stderr, "Error connecting to host /%s/ in io_open_remote\n", host); } @@ -1225,7 +1370,8 @@ inline static int io_open_remote(char *host, char *filename, int options, } #ifndef _WIN32 -inline static void set_mdsplus_file_protection(const char *filename) { +inline static void set_mdsplus_file_protection(const char *filename) +{ INIT_AND_FREE_ON_EXIT(char *, cmd); struct descriptor cmd_d = {0, DTYPE_T, CLASS_S, 0}; cmd = (char *)malloc(39 + strlen(filename)); @@ -1237,7 +1383,8 @@ inline static void set_mdsplus_file_protection(const char *filename) { } #endif -EXPORT int MDS_IO_OPEN(char *filename_in, int options, mode_t mode) { +EXPORT int MDS_IO_OPEN(char *filename_in, int options, mode_t mode) +{ int idx; INIT_AND_FREE_ON_EXIT(char *, filename); INIT_AND_FREE_ON_EXIT(char *, tmp); @@ -1247,7 +1394,8 @@ EXPORT int MDS_IO_OPEN(char *filename_in, int options, mode_t mode) { tmp = ParseFile(filename, &hostpart, &filepart); if (hostpart) fd = io_open_remote(hostpart, filepart, options, mode, &conid, &enhanced); - else { + else + { fd = open(filename, options | O_BINARY | O_RANDOM, mode); #ifndef _WIN32 if ((fd >= 0) && ((options & O_CREAT) != 0)) @@ -1260,7 +1408,8 @@ EXPORT int MDS_IO_OPEN(char *filename_in, int options, mode_t mode) { return idx; } -inline static int io_close_remote(int conid, int fd) { +inline static int io_close_remote(int conid, int fd) +{ int ret; INIT_AND_FREE_ON_EXIT(void *, msg); int len; @@ -1270,15 +1419,18 @@ inline static int io_close_remote(int conid, int fd) { NULL, &len, &dout, &msg); if (STATUS_OK) remote_access_disconnect(conid, 0); - if (STATUS_OK && sizeof(int) == len) { + if (STATUS_OK && sizeof(int) == len) + { ret = *(int *)dout; - } else + } + else ret = -1; FREE_NOW(msg); return ret; } -EXPORT int MDS_IO_CLOSE(int idx) { +EXPORT int MDS_IO_CLOSE(int idx) +{ fdinfo_t i = RM_FD(idx); if (i.fd < 0) return -1; @@ -1288,7 +1440,8 @@ EXPORT int MDS_IO_CLOSE(int idx) { } inline static off_t io_lseek_remote(int conid, int fd, off_t offset, - int whence) { + int whence) +{ off_t ret; INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = {.lseek = {.fd = fd, .offset = offset, .whence = whence}}; @@ -1298,11 +1451,13 @@ inline static off_t io_lseek_remote(int conid, int fd, off_t offset, int status = MdsIoRequest(conid, MDS_IO_LSEEK_K, sizeof(mdsio.lseek), &mdsio, NULL, &len, &dout, &msg); if (STATUS_OK) - if (len == sizeof(int32_t)) { + if (len == sizeof(int32_t)) + { ret = (off_t) * (int32_t *)dout; fprintf(stderr, "Server return 4 byte offset. Please update MDSplus on " "server if possible."); - } else if (len == sizeof(int64_t)) + } + else if (len == sizeof(int64_t)) ret = (off_t) * (int64_t *)dout; else ret = -1; @@ -1312,7 +1467,8 @@ inline static off_t io_lseek_remote(int conid, int fd, off_t offset, return ret; } -EXPORT off_t MDS_IO_LSEEK(int idx, off_t offset, int whence) { +EXPORT off_t MDS_IO_LSEEK(int idx, off_t offset, int whence) +{ fdinfo_t i = GET_FD(idx); if (i.fd < 0) return -1; @@ -1322,7 +1478,8 @@ EXPORT off_t MDS_IO_LSEEK(int idx, off_t offset, int whence) { } inline static ssize_t io_write_remote(int conid, int fd, void *buff, - size_t count) { + size_t count) +{ ssize_t ret; INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = {.write = {.fd = fd, .count = count}}; @@ -1330,22 +1487,23 @@ inline static ssize_t io_write_remote(int conid, int fd, void *buff, char *dout; int status = MdsIoRequest(conid, MDS_IO_WRITE_K, sizeof(mdsio.write), &mdsio, buff, &len, &dout, &msg); - if - STATUS_OK { - if (len == sizeof(int32_t)) - ret = (ssize_t) * (int32_t *)dout; - else if (len == sizeof(int64_t)) - ret = (ssize_t) * (int64_t *)dout; - else - ret = 0; - } + if (STATUS_OK) + { + if (len == sizeof(int32_t)) + ret = (ssize_t) * (int32_t *)dout; + else if (len == sizeof(int64_t)) + ret = (ssize_t) * (int64_t *)dout; + else + ret = 0; + } else ret = 0; FREE_NOW(msg); return ret; } -EXPORT ssize_t MDS_IO_WRITE(int idx, void *buff, size_t count) { +EXPORT ssize_t MDS_IO_WRITE(int idx, void *buff, size_t count) +{ fdinfo_t i = GET_FD(idx); if (i.fd < 0) return -1; @@ -1360,7 +1518,8 @@ EXPORT ssize_t MDS_IO_WRITE(int idx, void *buff, size_t count) { } inline static ssize_t io_read_remote(int conid, int fd, void *buff, - size_t count) { + size_t count) +{ ssize_t ret; INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = {.read = {.fd = fd, .count = count}}; @@ -1368,18 +1527,19 @@ inline static ssize_t io_read_remote(int conid, int fd, void *buff, char *dout; int status = MdsIoRequest(conid, MDS_IO_READ_K, sizeof(mdsio.read), &mdsio, NULL, &len, &dout, &msg); - if - STATUS_OK { - ret = (ssize_t)len; - memcpy(buff, dout, ret); - } + if (STATUS_OK) + { + ret = (ssize_t)len; + memcpy(buff, dout, ret); + } else ret = 0; FREE_NOW(msg); return ret; } -EXPORT ssize_t MDS_IO_READ(int idx, void *buff, size_t count) { +EXPORT ssize_t MDS_IO_READ(int idx, void *buff, size_t count) +{ fdinfo_t i = GET_FD(idx); if (i.fd < 0) return -1; @@ -1394,7 +1554,8 @@ EXPORT ssize_t MDS_IO_READ(int idx, void *buff, size_t count) { } inline static ssize_t io_read_x_remote(int conid, int fd, off_t offset, - void *buff, size_t count, int *deleted) { + void *buff, size_t count, int *deleted) +{ ssize_t ret; INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = {.read_x = {.fd = fd, .offset = offset, .count = count}}; @@ -1403,14 +1564,14 @@ inline static ssize_t io_read_x_remote(int conid, int fd, off_t offset, char *dout; int status = MdsIoRequest(conid, MDS_IO_READ_X_K, sizeof(mdsio.read_x), &mdsio, NULL, &len, &dout, &msg); - if - STATUS_OK { - if (deleted) - *deleted = status == 3; - ret = (ssize_t)len; - if (ret) - memcpy(buff, dout, ret); - } + if (STATUS_OK) + { + if (deleted) + *deleted = status == 3; + ret = (ssize_t)len; + if (ret) + memcpy(buff, dout, ret); + } else ret = -1; FREE_NOW(msg); @@ -1421,7 +1582,8 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, static int io_lock_remote(fdinfo_t fdinfo, off_t offset, size_t size, int mode_in, int *deleted); EXPORT ssize_t MDS_IO_READ_X(int idx, off_t offset, void *buff, size_t count, - int *deleted) { + int *deleted) +{ fdinfo_t i = GET_FD(idx); if (deleted) *deleted = 0; @@ -1429,7 +1591,8 @@ EXPORT ssize_t MDS_IO_READ_X(int idx, off_t offset, void *buff, size_t count, return -1; if (count == 0) return 0; - if (i.conid >= 0) { + if (i.conid >= 0) + { if (i.enhanced) return io_read_x_remote(i.conid, i.fd, offset, buff, count, deleted); ssize_t ans; @@ -1451,7 +1614,8 @@ EXPORT ssize_t MDS_IO_READ_X(int idx, off_t offset, void *buff, size_t count, } inline static int io_lock_remote(fdinfo_t fdinfo, off_t offset, size_t size, - int mode, int *deleted) { + int mode, int *deleted) +{ int ret; INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = { @@ -1461,18 +1625,21 @@ inline static int io_lock_remote(fdinfo_t fdinfo, off_t offset, size_t size, char *dout; int status = MdsIoRequest(fdinfo.conid, MDS_IO_LOCK_K, sizeof(mdsio.lock), &mdsio, NULL, &len, &dout, &msg); - if (STATUS_OK && len == sizeof(ret)) { + if (STATUS_OK && len == sizeof(ret)) + { if (deleted) *deleted = status == 3; ret = *(int *)dout; - } else + } + else ret = 0; FREE_NOW(msg); return ret; } static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, - int mode_in, int *deleted) { + int mode_in, int *deleted) +{ int fd = fdinfo.fd; int err; int mode = mode_in & MDS_IO_LOCK_MASK; @@ -1485,7 +1652,8 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, overlapped.OffsetHigh = (int)(offset >> 32); overlapped.hEvent = 0; HANDLE h = (HANDLE)_get_osfhandle(fd); - if (mode > 0) { + if (mode > 0) + { flags = ((mode == MDS_IO_LOCK_RD) && (nowait == 0)) ? 0 : LOCKFILE_EXCLUSIVE_LOCK; @@ -1493,7 +1661,9 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, flags |= LOCKFILE_FAIL_IMMEDIATELY; // UnlockFileEx(h, 0, (DWORD) size, 0, &overlapped); err = !LockFileEx(h, flags, 0, (DWORD)size, 0, &overlapped); - } else { + } + else + { err = !UnlockFileEx(h, 0, (DWORD)size, 0, &overlapped); } if (err) @@ -1511,20 +1681,25 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, flock.l_start = (mode == 0) ? 0 : ((offset >= 0) ? offset : 0); flock.l_len = (mode == 0) ? 0 : size; static int use_ofd_locks = 1; // atomic? - if (use_ofd_locks == 1) { + if (use_ofd_locks == 1) + { flock.l_pid = 0; err = fcntl(fd, nowait ? F_OFD_SETLK : F_OFD_SETLKW, &flock); - if (err != 0 && errno == EINVAL) { + if (err != 0 && errno == EINVAL) + { flock.l_pid = getpid(); err = fcntl(fd, nowait ? F_SETLK : F_SETLKW, &flock); - if (err == 0) { + if (err == 0) + { fprintf( stderr, "OS does not support OFD locks, file access is not threadsafe\n"); use_ofd_locks = 0; } } - } else { + } + else + { flock.l_pid = getpid(); err = fcntl(fd, nowait ? F_SETLK : F_SETLKW, &flock); } @@ -1536,7 +1711,8 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, } EXPORT int MDS_IO_LOCK(int idx, off_t offset, size_t size, int mode_in, - int *deleted) { + int *deleted) +{ fdinfo_t fdinfo = GET_FD(idx); if (deleted) *deleted = 0; @@ -1547,11 +1723,13 @@ EXPORT int MDS_IO_LOCK(int idx, off_t offset, size_t size, int mode_in, return io_lock_local(fdinfo, offset, size, mode_in, deleted); } -inline static int io_exists_remote(char *host, char *filename) { +inline static int io_exists_remote(char *host, char *filename) +{ int ret; INIT_AND_FREE_ON_EXIT(void *, msg); int conid = remote_access_connect(host, 1, 0); - if (conid != -1) { + if (conid != -1) + { mdsio_t mdsio = {.exists = {.length = strlen(filename) + 1}}; int len; char *dout; @@ -1561,13 +1739,15 @@ inline static int io_exists_remote(char *host, char *filename) { ret = *(int *)dout; else ret = 0; - } else + } + else ret = 0; FREE_NOW(msg); return ret; } -EXPORT int MDS_IO_EXISTS(char *filename_in) { +EXPORT int MDS_IO_EXISTS(char *filename_in) +{ int status; INIT_AND_FREE_ON_EXIT(char *, filename); INIT_AND_FREE_ON_EXIT(char *, tmp); @@ -1584,11 +1764,13 @@ EXPORT int MDS_IO_EXISTS(char *filename_in) { return status; } -inline static int io_remove_remote(char *host, char *filename) { +inline static int io_remove_remote(char *host, char *filename) +{ int ret; INIT_AND_FREE_ON_EXIT(void *, msg); int conid = remote_access_connect(host, 1, 0); - if (conid != -1) { + if (conid != -1) + { mdsio_t mdsio = {.remove = {.length = strlen(filename) + 1}}; int len; char *dout; @@ -1598,13 +1780,15 @@ inline static int io_remove_remote(char *host, char *filename) { ret = *(int *)dout; else ret = -1; - } else + } + else ret = -1; FREE_NOW(msg); return ret; } -EXPORT int MDS_IO_REMOVE(char *filename_in) { +EXPORT int MDS_IO_REMOVE(char *filename_in) +{ int status; INIT_AND_FREE_ON_EXIT(char *, filename); INIT_AND_FREE_ON_EXIT(char *, tmp); @@ -1618,11 +1802,13 @@ EXPORT int MDS_IO_REMOVE(char *filename_in) { } inline static int io_rename_remote(char *host, char *filename_old, - char *filename_new) { + char *filename_new) +{ int ret; int conid; conid = remote_access_connect(host, 1, 0); - if (conid != -1) { + if (conid != -1) + { INIT_AND_FREE_ON_EXIT(char *, names); INIT_AND_FREE_ON_EXIT(void *, msg); mdsio_t mdsio = {.rename = {.length = strlen(filename_old) + 1 + @@ -1639,12 +1825,14 @@ inline static int io_rename_remote(char *host, char *filename_old, ret = -1; FREE_NOW(msg); FREE_NOW(names); - } else + } + else ret = -1; return ret; } -EXPORT int MDS_IO_RENAME(char *filename_old, char *filename_new) { +EXPORT int MDS_IO_RENAME(char *filename_old, char *filename_new) +{ int status; INIT_AND_FREE_ON_EXIT(char *, tmp_new); INIT_AND_FREE_ON_EXIT(char *, tmp_old); @@ -1653,12 +1841,14 @@ EXPORT int MDS_IO_RENAME(char *filename_old, char *filename_new) { tmp_new = ParseFile(filename_new, &hostpart_new, &filepart_new); filename_old = replaceBackslashes(filename_old); filename_new = replaceBackslashes(filename_new); - if (hostpart_old) { + if (hostpart_old) + { if (hostpart_new && (strcmp(hostpart_old, hostpart_new) == 0)) status = io_rename_remote(hostpart_old, filepart_old, filepart_new); else status = -1; - } else + } + else status = rename(filename_old, filename_new); FREE_NOW(tmp_old); FREE_NOW(tmp_new); @@ -1670,12 +1860,14 @@ EXPORT int MDS_IO_RENAME(char *filename_old, char *filename_new) { /////////////////////////////////////////////////////////////////// inline static char *generate_fullpath(char *filepath, char const *treename, - int shot, tree_type_t type) { + int shot, tree_type_t type) +{ const char treeext[] = TREE_TREEFILE_EXT; const char nciext[] = TREE_NCIFILE_EXT; const char dataext[] = TREE_DATAFILE_EXT; char *ext; - switch (type) { + switch (type) + { case TREE_TREEFILE_TYPE: ext = (char *)treeext; break; @@ -1700,7 +1892,8 @@ inline static char *generate_fullpath(char *filepath, char const *treename, int last = strlen(resnam) - 1; if (resnam[last] == '+') resnam[last] = '\0'; - else { + else + { if (strcmp(resnam + last, TREE_PATH_DELIM)) strcat(resnam, TREE_PATH_DELIM); strcat(resnam, name); @@ -1711,34 +1904,44 @@ inline static char *generate_fullpath(char *filepath, char const *treename, inline static int io_open_one_request(int conid, size_t size, mdsio_t *mdsio, char *data, char *host, int *enhanced, - char **fullpath, int *fd_out) { + char **fullpath, int *fd_out) +{ int status; INIT_AND_FREE_ON_EXIT(void *, msg); int len; int *dout; status = MdsIoRequest(conid, MDS_IO_OPEN_ONE_K, size, mdsio, data, &len, (char **)&dout, &msg); - if (STATUS_OK && len >= 8) { + if (STATUS_OK && len >= 8) + { *enhanced = status == 3; status = *(dout++); *fd_out = *(dout++); - if (len > 8) { + if (len > 8) + { *fullpath = malloc(len - 8 + strlen(host) + 3); sprintf(*fullpath, "%s::%s", host, (char *)dout); - } else + } + else *fullpath = NULL; - } else { + } + else + { *fd_out = -1; } FREE_NOW(msg); return status; } -static void getOptionsMode(int new, int edit, int *options, int *mode) { - if (new) { +static void getOptionsMode(int new, int edit, int *options, int *mode) +{ + if (new) + { *options = O_RDWR | O_CREAT | O_TRUNC; *mode = 0664; - } else { + } + else + { *options = edit ? O_RDWR : O_RDONLY; *mode = 0; } @@ -1748,37 +1951,46 @@ inline static int io_open_one_remote(char *host, char *filepath, char const *treename, int shot, tree_type_t type, int new, int edit, char **fullpath, int *conid, int *fd, - int *enhanced) { + int *enhanced) +{ int status; static int (*GetConnectionVersion)(int) = NULL; status = LibFindImageSymbol_C("MdsIpShr", "GetConnectionVersion", &GetConnectionVersion); - do { + do + { *conid = remote_access_connect(host, 1, NULL); - if (*conid != -1) { - if (GetConnectionVersion(*conid) < MDSIP_VERSION_OPEN_ONE) { - if (*filepath && !strstr(filepath, "::")) { + if (*conid != -1) + { + if (GetConnectionVersion(*conid) < MDSIP_VERSION_OPEN_ONE) + { + if (*filepath && !strstr(filepath, "::")) + { INIT_AS_AND_FREE_ON_EXIT( char *, tmp, generate_fullpath(filepath, treename, shot, type)); int options, mode; getOptionsMode(new, edit, &options, &mode); *fd = io_open_remote(host, tmp, options, mode, conid, enhanced); status = *fd == -1 ? TreeFAILURE : TreeSUCCESS; - if ((*fd >= 0) && edit && (type == TREE_TREEFILE_TYPE)) { - if - IS_NOT_OK(io_lock_remote((fdinfo_t){*conid, *fd, *enhanced}, 1, 1, - MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, - 0)) { - status = TreeEDITTING; - *fd = -2; - } + if ((*fd >= 0) && edit && (type == TREE_TREEFILE_TYPE)) + { + if (IS_NOT_OK(io_lock_remote((fdinfo_t){*conid, *fd, *enhanced}, 1, 1, + MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, + 0))) + { + status = TreeEDITTING; + *fd = -2; + } } - if (*fd >= 0) { + if (*fd >= 0) + { *fullpath = malloc(strlen(host) + 3 + strlen(tmp)); sprintf(*fullpath, "%s::%s", host, tmp); } FREE_NOW(tmp); - } else { + } + else + { status = TreeUNSUPTHICKOP; remote_access_disconnect(*conid, B_FALSE); } @@ -1799,7 +2011,9 @@ inline static int io_open_one_remote(char *host, char *filepath, FREE_NOW(data); if (*fd < 0) remote_access_disconnect(*conid, B_FALSE); - } else { + } + else + { fprintf(stderr, "Error connecting to host /%s/ in io_open_one_remote\n", host); *fd = -1; @@ -1812,7 +2026,8 @@ extern char *MaskReplace(char *, char *, int); #include EXPORT int MDS_IO_OPEN_ONE(char *filepath_in, char const *treename_in, int shot, tree_type_t type, int new, int edit, char **filespec, - int *speclen, int *idx) { + int *speclen, int *idx) +{ int status; INIT_AND_FREE_ON_EXIT(char *, fullpath); status = TreeSUCCESS; @@ -1823,23 +2038,29 @@ EXPORT int MDS_IO_OPEN_ONE(char *filepath_in, char const *treename_in, int shot, char *hostpart, *filepart; size_t i; char *filepath = NULL; - if (filepath_in && *filepath_in /*not empty*/) { + if (filepath_in && *filepath_in /*not empty*/) + { for (i = 0; i < 12 && treename_in[i]; ++i) treename[i] = tolower(treename_in[i]); treename[i] = '\0'; filepath = strdup(filepath_in); - } else { + } + else + { char *tmp = TreePath(treename_in, treename); - if (tmp) { + if (tmp) + { replaceBackslashes(tmp); filepath = MaskReplace(tmp, treename, shot); free(tmp); } } - if (filepath) { + if (filepath) + { size_t pathlen = strlen(filepath); char *part = filepath; - for (i = 0; i <= pathlen; i++) { + for (i = 0; i <= pathlen; i++) + { if (filepath[i] != ';' && filepath[i] != '\0') continue; while (*part == ' ') @@ -1849,47 +2070,58 @@ EXPORT int MDS_IO_OPEN_ONE(char *filepath_in, char const *treename_in, int shot, filepath[i] = 0; char *tmp = ParseFile(part, &hostpart, &filepart); free(fullpath); - if (hostpart) { + if (hostpart) + { fullpath = NULL; status = io_open_one_remote(hostpart, filepart, treename, shot, type, new, edit, &fullpath, &conid, &fd, &enhanced); - if (fd < 0) { + if (fd < 0) + { if (status != TreeUNSUPTHICKOP) status = TreeSUCCESS; conid = -1; enhanced = 0; } - } else { + } + else + { fullpath = generate_fullpath(filepart, treename, shot, type); int options, mode; getOptionsMode(new, edit, &options, &mode); fd = open(fullpath, options | O_BINARY | O_RANDOM, mode); - if (type == TREE_DIRECTORY) { - if (fd != -1) { + if (type == TREE_DIRECTORY) + { + if (fd != -1) + { close(fd); fd = -3; } - } else { + } + else + { #ifndef _WIN32 if ((fd != -1) && new) set_mdsplus_file_protection(fullpath); #endif - if ((fd != -1) && edit && (type == TREE_TREEFILE_TYPE)) { - if - IS_NOT_OK(io_lock_local((fdinfo_t){conid, fd, enhanced}, 1, 1, - MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, 0)) { - status = TreeEDITTING; - fd = -2; - } + if ((fd != -1) && edit && (type == TREE_TREEFILE_TYPE)) + { + if (IS_NOT_OK(io_lock_local((fdinfo_t){conid, fd, enhanced}, 1, 1, + MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, 0))) + { + status = TreeEDITTING; + fd = -2; + } } } } free(tmp); - if (fd != -1) { + if (fd != -1) + { if (speclen) *speclen = strlen(part); - if (filespec && fullpath) { + if (filespec && fullpath) + { *filespec = fullpath; fullpath = NULL; } diff --git a/treeshr/TreeAddNode.c b/treeshr/TreeAddNode.c index 9c977d9f1a..a171d3fc75 100644 --- a/treeshr/TreeAddNode.c +++ b/treeshr/TreeAddNode.c @@ -55,17 +55,20 @@ STATIC_ROUTINE int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, NODE **trn_node_ptrptr); STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info); -int TreeAddNode(char const *name, int *nid_out, char usage) { +int TreeAddNode(char const *name, int *nid_out, char usage) +{ return _TreeAddNode(*TreeCtx(), name, nid_out, usage); } -int TreeAddConglom(char const *path, char const *congtype, int *nid) { +int TreeAddConglom(char const *path, char const *congtype, int *nid) +{ return _TreeAddConglom(*TreeCtx(), path, congtype, nid); } int TreeEndConglomerate() { return _TreeEndConglomerate(*TreeCtx()); } -int TreeQuitTree(char const *exp_ptr, int shotid) { +int TreeQuitTree(char const *exp_ptr, int shotid) +{ return _TreeQuitTree(TreeCtx(), exp_ptr, shotid); } @@ -73,17 +76,20 @@ int TreeSetNoSubtree(int nid) { return _TreeSetNoSubtree(*TreeCtx(), nid); } int TreeSetSubtree(int nid) { return _TreeSetSubtree(*TreeCtx(), nid); } -int TreeStartConglomerate(int size) { +int TreeStartConglomerate(int size) +{ return _TreeStartConglomerate(*TreeCtx(), size); } -int TreeWriteTree(char const *exp_ptr, int shotid) { +int TreeWriteTree(char const *exp_ptr, int shotid) +{ return _TreeWriteTree(TreeCtx(), exp_ptr, shotid); } int64_t TreeGetDatafileSize() { return _TreeGetDatafileSize(*TreeCtx()); } -int _TreeAddNode(void *dbid, char const *name, int *nid_out, char usage) { +int _TreeAddNode(void *dbid, char const *name, int *nid_out, char usage) +{ INIT_STATUS_AS TreeSUCCESS; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NODE *parent; @@ -112,130 +118,144 @@ int _TreeAddNode(void *dbid, char const *name, int *nid_out, char usage) { if not it is an error. ******************************************************/ status = TreeFindParent(dblist, upcase_name, &parent, &node_name, &is_child); - if - STATUS_OK { - /**************************************************** + if (STATUS_OK) + { + /**************************************************** make sure that the node is not already there *****************************************************/ - status = _TreeFindNode(dbid, upcase_name, &nid); - if - STATUS_OK + status = _TreeFindNode(dbid, upcase_name, &nid); + if (STATUS_OK) status = TreeALREADY_THERE; - else if (status == TreeNNF) { - /*********************************************** + else if (status == TreeNNF) + { + /*********************************************** If a conglomerate is being built make sure that it has not grown to big and increment the conglomerate node number. ************************************************/ - status = TreeSUCCESS; - conglom_size = &dblist->tree_info->edit->conglomerate_size; - conglom_index = &dblist->tree_info->edit->conglomerate_index; - if (*conglom_size) { - (*conglom_index)++; - if (*conglom_index > *conglom_size) - status = _TreeEndConglomerate((void *)dblist); - } - /************************************************ + status = TreeSUCCESS; + conglom_size = &dblist->tree_info->edit->conglomerate_size; + conglom_index = &dblist->tree_info->edit->conglomerate_index; + if (*conglom_size) + { + (*conglom_index)++; + if (*conglom_index > *conglom_size) + status = _TreeEndConglomerate((void *)dblist); + } + /************************************************ If OK so far so grab a new node, Fill in the name and insert it into the list of brothers. *************************************************/ - if (STATUS_OK) { - status = TreeNewNode(dblist, &new_ptr, &parent); - if - STATUS_OK { - size_t i; - short idx = *conglom_index; + if (STATUS_OK) + { + status = TreeNewNode(dblist, &new_ptr, &parent); + if (STATUS_OK) + { + size_t i; + short idx = *conglom_index; #pragma GCC diagnostic push #if defined __GNUC__ && 800 <= __GNUC__ * 100 + __GNUC_MINOR__ - _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"") + _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"") #endif - strncpy(new_ptr->name, node_name, sizeof(new_ptr->name)); + strncpy(new_ptr->name, node_name, sizeof(new_ptr->name)); #pragma GCC diagnostic pop - for (i = strlen(node_name); i < sizeof(new_ptr->name); i++) - new_ptr->name[i] = ' '; - new_ptr->child = 0; - loadint16(&new_ptr->conglomerate_elt, &idx); - if ((is_child && (usage == TreeUSAGE_ANY)) || - usage == TreeUSAGE_STRUCTURE || usage == TreeUSAGE_SUBTREE) { - status = TreeInsertChild( - parent, new_ptr, dblist->tree_info->header->sort_children); - new_ptr->usage = usage == TreeUSAGE_SUBTREE - ? TreeUSAGE_SUBTREE - : TreeUSAGE_STRUCTURE; - } else { - status = TreeInsertMember( - parent, new_ptr, dblist->tree_info->header->sort_members); - new_ptr->usage = (unsigned char)(((usage < TreeUSAGE_MAXIMUM) && - (usage >= 0)) - ? usage - : TreeUSAGE_ANY); - } - *nid_out = node_to_nid(dblist, new_ptr, 0); - } - if - STATUS_OK { - NCI new_nci; - NCI scratch_nci; - NID nid; - int parent_nid; - int ncilocked = 0; - memset(&new_nci, 0, sizeof(NCI)); - parent_nid = node_to_nid(dblist, parent, 0); - node_to_nid(dblist, new_ptr, &nid); - status = tree_get_and_lock_nci(dblist->tree_info, nid.node, - &scratch_nci, &ncilocked); - if - STATUS_OK { - if (_TreeIsOn(dblist, *(int *)&parent_nid) & 1) - new_nci.flags &= (unsigned)~NciM_PARENT_STATE; - else - new_nci.flags |= NciM_PARENT_STATE; - new_nci.flags |= NciM_COMPRESS_ON_PUT; - status = tree_put_nci(dblist->tree_info, nid.node, &new_nci, - &ncilocked); - } - } - } else - status = TreeINVPATH; + for (i = strlen(node_name); i < sizeof(new_ptr->name); i++) + new_ptr->name[i] = ' '; + new_ptr->child = 0; + loadint16(&new_ptr->conglomerate_elt, &idx); + if ((is_child && (usage == TreeUSAGE_ANY)) || + usage == TreeUSAGE_STRUCTURE || usage == TreeUSAGE_SUBTREE) + { + status = TreeInsertChild( + parent, new_ptr, dblist->tree_info->header->sort_children); + new_ptr->usage = usage == TreeUSAGE_SUBTREE + ? TreeUSAGE_SUBTREE + : TreeUSAGE_STRUCTURE; + } + else + { + status = TreeInsertMember( + parent, new_ptr, dblist->tree_info->header->sort_members); + new_ptr->usage = (unsigned char)(((usage < TreeUSAGE_MAXIMUM) && + (usage >= 0)) + ? usage + : TreeUSAGE_ANY); + } + *nid_out = node_to_nid(dblist, new_ptr, 0); + } + if (STATUS_OK) + { + NCI new_nci; + NCI scratch_nci; + NID nid; + int parent_nid; + int ncilocked = 0; + memset(&new_nci, 0, sizeof(NCI)); + parent_nid = node_to_nid(dblist, parent, 0); + node_to_nid(dblist, new_ptr, &nid); + status = tree_get_and_lock_nci(dblist->tree_info, nid.node, + &scratch_nci, &ncilocked); + if (STATUS_OK) + { + if (_TreeIsOn(dblist, *(int *)&parent_nid) & 1) + new_nci.flags &= (unsigned)~NciM_PARENT_STATE; + else + new_nci.flags |= NciM_PARENT_STATE; + new_nci.flags |= NciM_COMPRESS_ON_PUT; + status = tree_put_nci(dblist->tree_info, nid.node, &new_nci, + &ncilocked); + } + } } - free(node_name); + else + status = TreeINVPATH; } - if - STATUS_OK - dblist->modified = 1; + free(node_name); + } + if (STATUS_OK) + dblist->modified = 1; FREE_NOW(upcase_name); return status; } -int TreeInsertChild(NODE *parent_ptr, NODE *child_ptr, int sort) { +int TreeInsertChild(NODE *parent_ptr, NODE *child_ptr, int sort) +{ INIT_STATUS_AS TreeSUCCESS; NODE *pre_ptr; NODE *tmp_ptr; child_ptr->parent = node_offset(parent_ptr, child_ptr); /* fill in the parent pointer */ child_ptr->brother = 0; /* Assume it will be only child */ - if (parent_ptr->child == 0) { /* If first child */ + if (parent_ptr->child == 0) + { /* If first child */ parent_ptr->child = node_offset(child_ptr, parent_ptr); - } else { /* else */ + } + else + { /* else */ - if (sort) { + if (sort) + { for (pre_ptr = 0, tmp_ptr = child_of(0, parent_ptr); /* for all children < this one */ tmp_ptr && (strncmp((const char *)tmp_ptr->name, (const char *)child_ptr->name, 12) < 0); pre_ptr = tmp_ptr, tmp_ptr = brother_of(0, tmp_ptr)) ; - if (pre_ptr == 0) { /* if this will be first child */ + if (pre_ptr == 0) + { /* if this will be first child */ child_ptr->brother = node_offset(child_of(0, parent_ptr), child_ptr); /* make bro old first child */ parent_ptr->child = node_offset(child_ptr, parent_ptr); /* make it first child */ - } else { /* else */ + } + else + { /* else */ if (pre_ptr->brother == 0) /* if it will be last child */ child_ptr->brother = 0; /* it has no brother */ - else { /* else */ + else + { /* else */ child_ptr->brother = node_offset(brother_of(0, pre_ptr), @@ -244,7 +264,9 @@ int TreeInsertChild(NODE *parent_ptr, NODE *child_ptr, int sort) { pre_ptr->brother = node_offset( child_ptr, pre_ptr); /* the previous's bro is this one */ } - } else { + } + else + { for (tmp_ptr = child_of(0, parent_ptr); tmp_ptr->brother; /* Find last child */ tmp_ptr = brother_of(0, tmp_ptr)) @@ -256,7 +278,8 @@ int TreeInsertChild(NODE *parent_ptr, NODE *child_ptr, int sort) { return status; /* return the status */ } -int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) { +int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) +{ NODE *tmp_ptr; NODE *pre_ptr; /*------------------------------------------------------------------------------ @@ -265,26 +288,34 @@ int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) { member_ptr->parent = node_offset(parent_ptr, member_ptr); /* fill in the parent pointer */ member_ptr->brother = 0; /* Assume it will be only member */ - if (parent_ptr->member == 0) { /* If first member */ + if (parent_ptr->member == 0) + { /* If first member */ parent_ptr->member = node_offset(member_ptr, parent_ptr); /* hook it up */ - } else { /* else */ - if (sort) { + } + else + { /* else */ + if (sort) + { for (pre_ptr = 0, tmp_ptr = member_of(parent_ptr); /* for all members < this one */ tmp_ptr && (strncmp((const char *)tmp_ptr->name, (const char *)member_ptr->name, 12) < 0); pre_ptr = tmp_ptr, tmp_ptr = brother_of(0, tmp_ptr)) ; - if (pre_ptr == 0) { /* if this will be first child */ + if (pre_ptr == 0) + { /* if this will be first child */ member_ptr->brother = node_offset(member_of(parent_ptr), member_ptr); /* make bro old first child */ parent_ptr->member = node_offset(member_ptr, parent_ptr); /* make it first child */ - } else { /* else */ + } + else + { /* else */ if (pre_ptr->brother == 0) /* if it will be last child */ member_ptr->brother = 0; /* it has no brother */ - else { /* else */ + else + { /* else */ member_ptr->brother = node_offset(brother_of(0, pre_ptr), member_ptr); /* its bro is the previous's bro */ @@ -292,7 +323,9 @@ int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) { pre_ptr->brother = node_offset( member_ptr, pre_ptr); /* the previous's bro is this one */ } - } else { + } + else + { for (tmp_ptr = member_of(parent_ptr); /* Find last member */ tmp_ptr->brother; tmp_ptr = brother_of(0, tmp_ptr)) ; @@ -304,7 +337,8 @@ int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) { } STATIC_ROUTINE int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, - NODE **trn_node_ptrptr) { + NODE **trn_node_ptrptr) +{ INIT_STATUS_AS TreeSUCCESS; NODE *node_ptr; TREE_INFO *info_ptr = db_ptr->tree_info; @@ -315,38 +349,41 @@ STATIC_ROUTINE int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, *********************************/ if (header_ptr->free == -1) status = TreeExpandNodes(db_ptr, 1, &trn_node_ptrptr); - if - STATUS_OK { + if (STATUS_OK) + { - /************************************** + /************************************** Use the first node on the free list. **************************************/ - node_ptr = (NODE *)((char *)info_ptr->node + header_ptr->free); + node_ptr = (NODE *)((char *)info_ptr->node + header_ptr->free); - /************************************* + /************************************* Remove it from the free list *************************************/ - if (node_ptr->parent) { - header_ptr->free += swapint32(&node_ptr->parent); - (parent_of(0, node_ptr))->child = 0; - } else - header_ptr->free = -1; + if (node_ptr->parent) + { + header_ptr->free += swapint32(&node_ptr->parent); + (parent_of(0, node_ptr))->child = 0; + } + else + header_ptr->free = -1; - /*********************************** + /*********************************** Return the node ************************************/ - memset(node_ptr, 0, sizeof(*node_ptr)); + memset(node_ptr, 0, sizeof(*node_ptr)); - *node_ptrptr = node_ptr; - } + *node_ptrptr = node_ptr; + } return status; } #define EXTEND_NODES 512 -int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { +int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) +{ int status; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static NODE *empty_node_array = NULL; @@ -369,7 +406,8 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { STATIC_CONSTANT size_t empty_node_size = sizeof(NODE) * EXTEND_NODES; STATIC_CONSTANT size_t empty_nci_size = sizeof(NCI) * EXTEND_NODES; - if (!empty_node_array) { + if (!empty_node_array) + { /* int uic_code = JPI$_UIC; lib$getjpi(&uic_code, 0, 0, &empty_nci.nci$l_owner_identifier, 0, 0); @@ -378,16 +416,19 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { empty_node.child = -(int)sizeof(NODE); ; empty_node_array = (NODE *)malloc(empty_node_size); - if (empty_node_array == NULL) { + if (empty_node_array == NULL) + { status = MDSplusERROR; goto end; } empty_nci_array = (NCI *)malloc(empty_nci_size); - if (empty_nci_array == NULL) { + if (empty_nci_array == NULL) + { status = MDSplusERROR; goto end; } - for (i = 0; i < EXTEND_NODES; i++) { + for (i = 0; i < EXTEND_NODES; i++) + { empty_node_array[i] = empty_node; empty_nci_array[i] = empty_nci; } @@ -411,9 +452,11 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { ncis = ncis > 0 ? ncis : 0; ncis = ncis + EXTEND_NODES * 10; vm_bytes = nodes * (int)sizeof(NODE) + ncis * (int)sizeof(NCI); - if (vm_bytes > edit_ptr->node_vm_size) { + if (vm_bytes > edit_ptr->node_vm_size) + { ptr = (NODE *)malloc((size_t)vm_bytes); - if (ptr != NULL) { + if (ptr != NULL) + { int old_node_bytes = header_ptr->nodes * (int)sizeof(NODE); int old_nci_bytes = (header_ptr->nodes - edit_ptr->first_in_mem) * (int)sizeof(NCI); @@ -456,11 +499,13 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { info_ptr->root = info_ptr->node + saved_node_numbers[i++]; db_ptr->default_node = info_ptr->node + saved_node_numbers[i++]; free(saved_node_numbers); - } else + } + else goto end; } memcpy(info_ptr->node + header_ptr->nodes, empty_node_array, empty_node_size); - if (ncis) { + if (ncis) + { int nci_offset = header_ptr->nodes - edit_ptr->first_in_mem; if (nci_offset < 0) nci_offset = 0; @@ -477,11 +522,14 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) { old last node in the free list point to the first free node in the freelist. *******************************************/ - if (header_ptr->free == -1) { + if (header_ptr->free == -1) + { header_ptr->free = header_ptr->nodes * (int)sizeof(NODE); node_ptr = (NODE *)((char *)info_ptr->node + header_ptr->free); node_ptr->child = 0; - } else { + } + else + { int tmp; for (node_ptr = (NODE *)((char *)info_ptr->node + header_ptr->free); node_ptr->parent; node_ptr = parent_of(0, node_ptr)) @@ -497,11 +545,13 @@ end:; return status; } -typedef struct { +typedef struct +{ void *xd; char *rtn, *model, *image; } get_add_rtn_t; -static void get_add_rtn_c(void *in) { +static void get_add_rtn_c(void *in) +{ get_add_rtn_t *c = (get_add_rtn_t *)in; free_xd(c->xd); free(c->rtn); @@ -512,23 +562,25 @@ static void get_add_rtn_c(void *in) { #pragma GCC diagnostic ignored "-Wclobbered" // fc21 claims that '__cancel_routine' is clobbered // pthread_cleanup_push(get_add_rtn_c,(void*)&c); -static inline int get_add_rtn(char const *congtype, int (**add)()) { +static inline int get_add_rtn(char const *congtype, int (**add)()) +{ static int (*TdiExecute)() = NULL; int status = LibFindImageSymbol_C("TdiShr", "TdiExecute", &TdiExecute); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; // find image name by MdsDevices() array char exp[] = "MdsDevices()"; struct descriptor expdsc = {strlen(exp), DTYPE_T, CLASS_S, (char *)exp}; EMPTYXD(xd); status = TdiExecute(&expdsc, &xd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; get_add_rtn_t c = {&xd, NULL, NULL, NULL}; uint32_t j, i = (uint32_t)strlen(congtype); c.rtn = malloc(i + 6); c.model = malloc(i + 1); - for (i = 0; congtype[i] && congtype[i] != ' '; i++) { + for (i = 0; congtype[i] && congtype[i] != ' '; i++) + { c.rtn[i] = congtype[i]; c.model[i] = toupper(congtype[i]); } @@ -537,34 +589,38 @@ static inline int get_add_rtn(char const *congtype, int (**add)()) { strcpy(&c.rtn[i], "__add"); c.model[i] = '\0'; char *tmp; - for (i = 0; i < list->arsize; i += 2 * list->length) { + for (i = 0; i < list->arsize; i += 2 * list->length) + { tmp = &list->pointer[i]; for (j = 0; j < list->length && c.model[j] == toupper(tmp[j]); j++) ; if (j == list->length || (c.model[j] == '\0' && tmp[j] == ' ')) break; } - if (i < list->arsize) { + if (i < list->arsize) + { c.image = malloc(list->length + 1); tmp = &list->pointer[i + list->length]; for (i = 0; i < list->length && tmp[i] != ' '; i++) c.image[i] = tmp[i]; c.image[i] = '\0'; status = LibFindImageSymbol_C(c.image, c.rtn, add); - } else + } + else status = LibKEYNOTFOU; pthread_cleanup_pop(1); return status; } #pragma GCC diagnostic pop int _TreeAddConglom(void *dbid, char const *path, char const *congtype, - int *nid) { + int *nid) +{ if (!IS_OPEN_FOR_EDIT(((PINO_DATABASE *)dbid))) return TreeNOEDIT; static int (*_TdiExecute)() = NULL; int status = LibFindImageSymbol_C("TdiShr", "_TdiExecute", &_TdiExecute); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; struct descriptor pathdsc = {strlen(path), DTYPE_T, CLASS_S, (char *)path}; struct descriptor typedsc = {strlen(congtype), DTYPE_T, CLASS_S, (char *)congtype}; @@ -576,13 +632,12 @@ int _TreeAddConglom(void *dbid, char const *path, char const *congtype, struct descriptor expdsc = {strlen(exp), DTYPE_T, CLASS_S, (char *)exp}; status = _TdiExecute(&dbid, &expdsc, &pathdsc, &typedsc, &statdsc MDS_END_ARG); - if - STATUS_OK { - status = addstatus; - if - STATUS_OK + if (STATUS_OK) + { + status = addstatus; + if (STATUS_OK) status = _TreeFindNode(dbid, path, nid); - } + } FREE_NOW(exp); } if (status != TdiUNKNOWN_VAR) @@ -590,12 +645,12 @@ int _TreeAddConglom(void *dbid, char const *path, char const *congtype, /*try shared device*/ { int (*add)() = NULL; status = get_add_rtn(congtype, &add); - if - STATUS_OK { - CTX_PUSH(&dbid); - status = add(&pathdsc, &typedsc, nid); - CTX_POP(&dbid); - } + if (STATUS_OK) + { + CTX_PUSH(&dbid); + status = add(&pathdsc, &typedsc, nid); + CTX_POP(&dbid); + } } if (status != LibKEYNOTFOU) goto end; @@ -604,26 +659,26 @@ int _TreeAddConglom(void *dbid, char const *path, char const *congtype, struct descriptor expdsc = {strlen(exp), DTYPE_T, CLASS_S, (char *)exp}; INIT_AND_FREEXD_ON_EXIT(xd); status = _TdiExecute(&dbid, &expdsc, &pathdsc, &typedsc, &xd MDS_END_ARG); - if - STATUS_OK { - int *arr = (int *)xd.pointer->pointer; - status = arr[0]; - if - STATUS_OK + if (STATUS_OK) + { + int *arr = (int *)xd.pointer->pointer; + status = arr[0]; + if (STATUS_OK) *nid = arr[1]; - } + } FREEXD_NOW(xd); } end:; return status; } -#define set_parent(nod_ptr, new_par_ptr) \ +#define set_parent(nod_ptr, new_par_ptr) \ (nod_ptr)->parent = (int)((char *)new_par_ptr - (char *)nod_ptr) -#define set_child(nod_ptr, new_child_ptr) \ +#define set_child(nod_ptr, new_child_ptr) \ (nod_ptr)->child = (int)((char *)new_child_ptr - (char *)nod_ptr) -int _TreeStartConglomerate(void *dbid, int size) { +int _TreeStartConglomerate(void *dbid, int size) +{ if (size > 0x7fff) return TreeBUFFEROVF; INIT_STATUS_AS TreeSUCCESS; @@ -656,17 +711,21 @@ int _TreeStartConglomerate(void *dbid, int size) { is found looking for it. If nessesary expand the node pool and continue looking. ******************************************************/ - for (i = 0; STATUS_OK && i < size - 1;) { + for (i = 0; STATUS_OK && i < size - 1;) + { if (i == 0) starting_node_ptr = this_node_ptr; - if (this_node_ptr->parent) { + if (this_node_ptr->parent) + { next_node_ptr = parent_of(0, this_node_ptr); if (next_node_ptr - this_node_ptr != 1) i = 0; else i++; this_node_ptr = next_node_ptr; - } else { + } + else + { NODE **fixups[3]; fixups[0] = &this_node_ptr; fixups[1] = &starting_node_ptr; @@ -680,33 +739,37 @@ int _TreeStartConglomerate(void *dbid, int size) { pointer points to this block of nodes. If nessesary move the pointers around to make it so. ****************************************************/ - if - STATUS_OK { - if (starting_node_ptr && starting_node_ptr->child != 0) { - if (parent_of(0, this_node_ptr)) { - set_parent(child_of(0, starting_node_ptr), - parent_of(0, this_node_ptr)); - set_child(parent_of(0, this_node_ptr), - child_of(0, starting_node_ptr)); - } else - (child_of(0, starting_node_ptr))->parent = 0; - set_parent(this_node_ptr, - (NODE *)((char *)info_ptr->node + header_ptr->free)); - set_child((NODE *)((char *)info_ptr->node + header_ptr->free), - this_node_ptr); - header_ptr->free = - (int)((char *)starting_node_ptr - (char *)info_ptr->node); - starting_node_ptr->child = 0; + if (STATUS_OK) + { + if (starting_node_ptr && starting_node_ptr->child != 0) + { + if (parent_of(0, this_node_ptr)) + { + set_parent(child_of(0, starting_node_ptr), + parent_of(0, this_node_ptr)); + set_child(parent_of(0, this_node_ptr), + child_of(0, starting_node_ptr)); } - info_ptr->edit->conglomerate_index = 0; - info_ptr->edit->conglomerate_size = (short)size; - info_ptr->edit->conglomerate_setup = dblist->setup_info; - dblist->setup_info = 0; + else + (child_of(0, starting_node_ptr))->parent = 0; + set_parent(this_node_ptr, + (NODE *)((char *)info_ptr->node + header_ptr->free)); + set_child((NODE *)((char *)info_ptr->node + header_ptr->free), + this_node_ptr); + header_ptr->free = + (int)((char *)starting_node_ptr - (char *)info_ptr->node); + starting_node_ptr->child = 0; } + info_ptr->edit->conglomerate_index = 0; + info_ptr->edit->conglomerate_size = (short)size; + info_ptr->edit->conglomerate_setup = dblist->setup_info; + dblist->setup_info = 0; + } return status; } -int _TreeEndConglomerate(void *dbid) { +int _TreeEndConglomerate(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; short conglom_size, conglom_index; /***************************************************** @@ -730,7 +793,8 @@ int _TreeEndConglomerate(void *dbid) { STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr); #ifdef WORDS_BIGENDIAN -STATIC_ROUTINE TREE_HEADER *HeaderOut(TREE_HEADER *hdr) { +STATIC_ROUTINE TREE_HEADER *HeaderOut(TREE_HEADER *hdr) +{ TREE_HEADER *ans = (TREE_HEADER *)malloc(sizeof(TREE_HEADER)); ((char *)ans)[1] = (char)((hdr->sort_children ? 1 : 0) | (hdr->sort_members ? 2 : 0)); @@ -748,20 +812,22 @@ STATIC_ROUTINE void FreeHeaderOut(TREE_HEADER *hdr) { free(hdr); } #define FreeHeaderOut(in) #endif -int64_t _TreeGetDatafileSize(void *dbid) { +int64_t _TreeGetDatafileSize(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; TREE_INFO *info = dblist->tree_info; if (!info) return -1; - if ((!info->data_file) || info->data_file->get == 0) { - if - IS_NOT_OK(TreeOpenDatafileR(info)) - return -1; + if ((!info->data_file) || info->data_file->get == 0) + { + if (IS_NOT_OK(TreeOpenDatafileR(info))) + return -1; } return MDS_IO_LSEEK(info->data_file->get, 0, SEEK_END); } -int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) { +int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) +{ INIT_STATUS_AS TreeNOT_OPEN; PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; size_t header_pages; @@ -771,8 +837,10 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) { size_t external_pages; PINO_DATABASE *db; PINO_DATABASE *prev_db; - if (dblist) { - if (exp_ptr) { + if (dblist) + { + if (exp_ptr) + { char uptree[13]; size_t i; int shot; @@ -783,9 +851,12 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) { shot = (shotid == 0) ? TreeGetCurrentShotId(uptree) : shotid; status = TreeNOT_OPEN; for (prev_db = 0, db = (*dblist); db ? db->open : 0; - prev_db = db, db = db->next) { - if ((shot == db->shotid) && (strcmp(uptree, db->main_treenam) == 0)) { - if (prev_db) { + prev_db = db, db = db->next) + { + if ((shot == db->shotid) && (strcmp(uptree, db->main_treenam) == 0)) + { + if (prev_db) + { prev_db->next = db->next; db->next = (*dblist); *dblist = db; @@ -794,11 +865,12 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) { break; } } - } else + } + else status = IS_OPEN_FOR_EDIT(*dblist) ? TreeSUCCESS : TreeNOT_OPEN; - if - STATUS_OK { - /************************************** + if (STATUS_OK) + { + /************************************** Compute number of pages to allocate for each part of the tree file. Create a file of the correct size then @@ -806,87 +878,94 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) { Close the file. Write out the characteristics file. **************************************/ - char *nfilenam = NULL; - FREE_ON_EXIT(nfilenam); - int ntreefd; - TREE_INFO *info_ptr = (*dblist)->tree_info; - nfilenam = - strcpy(malloc(strlen(info_ptr->filespec) + 2), info_ptr->filespec); - _TreeDeleteNodesWrite(*dbid); - trim_excess_nodes(info_ptr); - header_pages = (sizeof(TREE_HEADER) + 511u) / 512u; - node_pages = - ((size_t)info_ptr->header->nodes * sizeof(NODE) + 511u) / 512u; - tags_pages = ((size_t)info_ptr->header->tags * 4u + 511u) / 512u; - tag_info_pages = - ((size_t)info_ptr->header->tags * sizeof(TAG_INFO) + 511u) / 512u; - external_pages = - ((size_t)info_ptr->header->externals * 4u + 511u) / 512u; - strcat(nfilenam, "#"); - ntreefd = MDS_IO_OPEN(nfilenam, O_WRONLY | O_CREAT | O_TRUNC, 0664); - if (ntreefd != -1) { - status = MDSplusERROR; - ssize_t num; - TREE_HEADER *header = HeaderOut(info_ptr->header); - num = MDS_IO_WRITE(ntreefd, header, 512 * header_pages); - FreeHeaderOut(header); - status = TreeWRITETREEERR; - if (num != (ssize_t)(header_pages * 512)) { - goto error_exit; - } - num = MDS_IO_WRITE(ntreefd, info_ptr->node, 512 * node_pages); - if (num != (ssize_t)(node_pages * 512)) - goto error_exit; - num = MDS_IO_WRITE(ntreefd, info_ptr->tags, 512 * tags_pages); - if (num != (ssize_t)(tags_pages * 512)) - goto error_exit; - num = MDS_IO_WRITE(ntreefd, info_ptr->tag_info, 512 * tag_info_pages); - if (num != (ssize_t)(tag_info_pages * 512)) - goto error_exit; - num = MDS_IO_WRITE(ntreefd, info_ptr->external, 512 * external_pages); - if (num != (ssize_t)(external_pages * 512)) - goto error_exit; - status = TreeWriteNci(info_ptr); - if - STATUS_NOT_OK + char *nfilenam = NULL; + FREE_ON_EXIT(nfilenam); + int ntreefd; + TREE_INFO *info_ptr = (*dblist)->tree_info; + nfilenam = + strcpy(malloc(strlen(info_ptr->filespec) + 2), info_ptr->filespec); + _TreeDeleteNodesWrite(*dbid); + trim_excess_nodes(info_ptr); + header_pages = (sizeof(TREE_HEADER) + 511u) / 512u; + node_pages = + ((size_t)info_ptr->header->nodes * sizeof(NODE) + 511u) / 512u; + tags_pages = ((size_t)info_ptr->header->tags * 4u + 511u) / 512u; + tag_info_pages = + ((size_t)info_ptr->header->tags * sizeof(TAG_INFO) + 511u) / 512u; + external_pages = + ((size_t)info_ptr->header->externals * 4u + 511u) / 512u; + strcat(nfilenam, "#"); + ntreefd = MDS_IO_OPEN(nfilenam, O_WRONLY | O_CREAT | O_TRUNC, 0664); + if (ntreefd != -1) + { + status = MDSplusERROR; + ssize_t num; + TREE_HEADER *header = HeaderOut(info_ptr->header); + num = MDS_IO_WRITE(ntreefd, header, 512 * header_pages); + FreeHeaderOut(header); + status = TreeWRITETREEERR; + if (num != (ssize_t)(header_pages * 512)) + { + goto error_exit; + } + num = MDS_IO_WRITE(ntreefd, info_ptr->node, 512 * node_pages); + if (num != (ssize_t)(node_pages * 512)) + goto error_exit; + num = MDS_IO_WRITE(ntreefd, info_ptr->tags, 512 * tags_pages); + if (num != (ssize_t)(tags_pages * 512)) + goto error_exit; + num = MDS_IO_WRITE(ntreefd, info_ptr->tag_info, 512 * tag_info_pages); + if (num != (ssize_t)(tag_info_pages * 512)) + goto error_exit; + num = MDS_IO_WRITE(ntreefd, info_ptr->external, 512 * external_pages); + if (num != (ssize_t)(external_pages * 512)) + goto error_exit; + status = TreeWriteNci(info_ptr); + if (STATUS_NOT_OK) + goto error_exit; + status = TreeSUCCESS; + if (info_ptr->channel > -1) + status = MDS_IO_CLOSE(info_ptr->channel); + info_ptr->channel = -2; + MDS_IO_REMOVE(info_ptr->filespec); + if (MDS_IO_CLOSE(ntreefd) == -1) + { + status = TreeCLOSEERR; goto error_exit; - status = TreeSUCCESS; - if (info_ptr->channel > -1) - status = MDS_IO_CLOSE(info_ptr->channel); - info_ptr->channel = -2; - MDS_IO_REMOVE(info_ptr->filespec); - if (MDS_IO_CLOSE(ntreefd) == -1) { - status = TreeCLOSEERR; - goto error_exit; - } - if (MDS_IO_RENAME(nfilenam, info_ptr->filespec) == -1) { - status = TreeMOVEERROR; - goto error_exit; - } - info_ptr->channel = MDS_IO_OPEN(info_ptr->filespec, O_RDWR, 0); - if (info_ptr->channel == -1) { - status = TreeOPENEDITERR; - goto error_exit; - } - MDS_IO_LOCK(info_ptr->channel, 1, 1, - MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, 0); - status = TreeSUCCESS; - (*dblist)->modified = 0; - TreeCallHookFun("TreeHook", "WriteTree", info_ptr->treenam, - (*dblist)->shotid, NULL); - TreeCallHook(WriteTree, info_ptr, 0); - } else { - (*dblist)->modified = 0; - status = TreeFCREATE; } - error_exit:; - FREE_NOW(nfilenam); + if (MDS_IO_RENAME(nfilenam, info_ptr->filespec) == -1) + { + status = TreeMOVEERROR; + goto error_exit; + } + info_ptr->channel = MDS_IO_OPEN(info_ptr->filespec, O_RDWR, 0); + if (info_ptr->channel == -1) + { + status = TreeOPENEDITERR; + goto error_exit; + } + MDS_IO_LOCK(info_ptr->channel, 1, 1, + MDS_IO_LOCK_RD | MDS_IO_LOCK_NOWAIT, 0); + status = TreeSUCCESS; + (*dblist)->modified = 0; + TreeCallHookFun("TreeHook", "WriteTree", info_ptr->treenam, + (*dblist)->shotid, NULL); + TreeCallHook(WriteTree, info_ptr, 0); } + else + { + (*dblist)->modified = 0; + status = TreeFCREATE; + } + error_exit:; + FREE_NOW(nfilenam); + } } return status; } -STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) { +STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) +{ int *nodecount_ptr = (int *)&info_ptr->header->nodes; int *free_ptr = (int *)&info_ptr->header->free; NODE *node_ptr; @@ -904,22 +983,31 @@ STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) { (((size_t)(node_ptr - nodes_ptr + 1) * sizeof(NODE) + 511) / 512); nodes = max(info_ptr->edit->first_in_mem, (int)((node_pages * 512) / sizeof(NODE))); - if (nodes < *nodecount_ptr) { + if (nodes < *nodecount_ptr) + { for (node_ptr = &nodes_ptr[nodes]; - (*free_ptr != -1) && (node_ptr <= last_node_ptr); node_ptr++) { - if (node_ptr == (NODE *)((char *)nodes_ptr + *free_ptr)) { - if (node_ptr->parent) { + (*free_ptr != -1) && (node_ptr <= last_node_ptr); node_ptr++) + { + if (node_ptr == (NODE *)((char *)nodes_ptr + *free_ptr)) + { + if (node_ptr->parent) + { *free_ptr += swapint32(&node_ptr->parent); (parent_of(0, node_ptr))->child = 0; - } else + } + else *free_ptr = -1; - } else { + } + else + { NODE *p = parent_of(0, node_ptr); NODE *c = child_of(0, node_ptr); - if (p) { + if (p) + { p->child = node_offset(c, p); } - if (c) { + if (c) + { c->parent = node_offset(p, c); } } @@ -928,9 +1016,11 @@ STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) { } } -STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info) { +STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info) +{ INIT_STATUS_AS TreeSUCCESS; - if (info->header->nodes > info->edit->first_in_mem) { + if (info->header->nodes > info->edit->first_in_mem) + { int numnodes = info->header->nodes - info->edit->first_in_mem; int i; NCI nci; @@ -938,7 +1028,8 @@ STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info) { int nbytes = (int)sizeof(nci_bytes); int offset; for (i = 0, offset = info->edit->first_in_mem * nbytes; - i < numnodes && STATUS_OK; i++, offset += nbytes) { + i < numnodes && STATUS_OK; i++, offset += nbytes) + { MDS_IO_LSEEK(info->nci_file->put, offset, SEEK_SET); memcpy(&nci, &info->edit->nci[i], sizeof(nci)); TreeSerializeNciOut(&nci, nci_bytes); @@ -946,15 +1037,15 @@ STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info) { nbytes) ? TreeSUCCESS : TreeNCIWRITE; - if - STATUS_OK - info->edit->first_in_mem++; + if (STATUS_OK) + info->edit->first_in_mem++; } } return status; } -int _TreeSetSubtree(void *dbid, int nid) { +int _TreeSetSubtree(void *dbid, int nid) +{ INIT_STATUS_AS TreeSUCCESS; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; @@ -990,9 +1081,12 @@ int _TreeSetSubtree(void *dbid, int nid) { ***************************************************/ node_idx = (int)(node_ptr - dblist->tree_info->node); - for (i = 0; i < dblist->tree_info->header->externals; i++) { - if (swapint32(&dblist->tree_info->external[i]) == node_idx) { - if (node_ptr->usage != TreeUSAGE_SUBTREE) { + for (i = 0; i < dblist->tree_info->header->externals; i++) + { + if (swapint32(&dblist->tree_info->external[i]) == node_idx) + { + if (node_ptr->usage != TreeUSAGE_SUBTREE) + { node_ptr->usage = TreeUSAGE_SUBTREE; dblist->modified = 1; } @@ -1010,11 +1104,14 @@ int _TreeSetSubtree(void *dbid, int nid) { pages_needed = (numext * 4 + 511) / 512; pages_allocated = max((numext * 4 + 507) / 512, dblist->tree_info->edit->external_pages); - if (pages_needed > pages_allocated) { + if (pages_needed > pages_allocated) + { new_external_ptr = malloc((size_t)pages_needed * 512u); status = new_external_ptr == 0 ? TreeMEMERR : TreeSUCCESS; - if - STATUS_NOT_OK { return status; } + if (STATUS_NOT_OK) + { + return status; + } memcpy(new_external_ptr, dblist->tree_info->external, (size_t)((numext - 1) * 4)); if (dblist->tree_info->edit->external_pages > 0) @@ -1040,7 +1137,8 @@ int _TreeSetSubtree(void *dbid, int nid) { return TreeSUCCESS; } -int _TreeSetNoSubtree(void *dbid, int nid) { +int _TreeSetNoSubtree(void *dbid, int nid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; NODE *node_ptr; @@ -1084,13 +1182,16 @@ int _TreeSetNoSubtree(void *dbid, int nid) { return TreeSUCCESS; } -int _TreeQuitTree(void **dbid, char const *exp_ptr, int shotid) { +int _TreeQuitTree(void **dbid, char const *exp_ptr, int shotid) +{ INIT_STATUS_AS TreeNOT_OPEN; PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; PINO_DATABASE *db; PINO_DATABASE *prev_db; - if (*dblist) { - if (exp_ptr) { + if (*dblist) + { + if (exp_ptr) + { char uptree[13]; size_t i; int shot; @@ -1101,9 +1202,12 @@ int _TreeQuitTree(void **dbid, char const *exp_ptr, int shotid) { shot = (shotid == 0) ? TreeGetCurrentShotId(uptree) : shotid; status = TreeNOT_OPEN; for (prev_db = 0, db = (*dblist); db ? db->open : 0; - prev_db = db, db = db->next) { - if ((shot == db->shotid) && (strcmp(uptree, db->main_treenam) == 0)) { - if (prev_db) { + prev_db = db, db = db->next) + { + if ((shot == db->shotid) && (strcmp(uptree, db->main_treenam) == 0)) + { + if (prev_db) + { prev_db->next = db->next; db->next = (*dblist); *dblist = db; @@ -1112,9 +1216,11 @@ int _TreeQuitTree(void **dbid, char const *exp_ptr, int shotid) { break; } } - } else + } + else status = (*dblist)->open_for_edit ? TreeSUCCESS : TreeNOT_OPEN; - if (STATUS_OK && ((*dblist)->open)) { + if (STATUS_OK && ((*dblist)->open)) + { _TreeDeleteNodesDiscard(*dbid); (*dblist)->modified = 0; status = _TreeClose(dbid, 0, 0); diff --git a/treeshr/TreeAddTag.c b/treeshr/TreeAddTag.c index fe6fe1c18c..04e6660097 100644 --- a/treeshr/TreeAddTag.c +++ b/treeshr/TreeAddTag.c @@ -69,11 +69,13 @@ extern void **TreeCtx(); #endif #define max(a, b) ((a) >= (b) ? (a) : (b)) -int TreeAddTag(int nid, char const *tagnam) { +int TreeAddTag(int nid, char const *tagnam) +{ return _TreeAddTag(*TreeCtx(), nid, tagnam); } -int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { +int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid_in; int status; @@ -116,7 +118,8 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { if ((tag[0] < 'A') || (tag[0] > 'Z')) return TreeINVTAG; - for (i = 1; i < len; i++) { + for (i = 1; i < len; i++) + { if (((tag[i] < 'A') || (tag[i] > 'Z')) && ((tag[i] < '0') || (tag[i] > '9')) && (tag[i] != '_')) return TreeINVTAG; @@ -131,22 +134,26 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { tags = dblist->tree_info->header->tags; old_tags_ptr = dblist->tree_info->tags; - if (tags > 0) { + if (tags > 0) + { newtag_idx = 0; - for (tidx = 0; tidx < tags; tidx++) { + for (tidx = 0; tidx < tags; tidx++) + { int idx = swapint32((old_tags_ptr + tidx)); char *defined_tag = (char *)(dblist->tree_info->tag_info + idx)->name; int cmp = strncmp(tag, defined_tag, sizeof(TAG_NAME)); if (cmp == 0) return TreeDUPTAG; - else if (cmp < 0) { + else if (cmp < 0) + { newtag_idx = tidx; break; } } if (newtag_idx == 0) newtag_idx = tidx; - } else + } + else newtag_idx = 0; /******************************************************* @@ -158,7 +165,8 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { pages_needed = ((tags + 1) * 4 + 511) / 512; pages_allocated = max((tags * 4 + 511) / 512, dblist->tree_info->edit->tags_pages); - if (pages_needed > pages_allocated) { + if (pages_needed > pages_allocated) + { /******************************************************** If we need to allocate more pages for tag indices we @@ -172,7 +180,8 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { ********************************************************/ new_tags_ptr = calloc(512, (size_t)pages_needed); - if (!(new_tags_ptr)) { + if (!(new_tags_ptr)) + { return TreeMEMERR; } memcpy(new_tags_ptr, old_tags_ptr, (size_t)newtag_idx * sizeof(int)); @@ -183,7 +192,9 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { free(old_tags_ptr); dblist->tree_info->tags = new_tags_ptr; dblist->tree_info->edit->tags_pages = pages_needed; - } else { + } + else + { /******************************************************** If we don't need to allocate more pages for tag indices we @@ -218,7 +229,8 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { pages_needed = ((tags + 1) * (int)sizeof(TAG_INFO) + 511) / 512; pages_allocated = max((tags * (int)sizeof(TAG_INFO) + 511) / 512, dblist->tree_info->edit->tag_info_pages); - if (pages_needed > pages_allocated) { + if (pages_needed > pages_allocated) + { /******************************************************* If we need to get more memory we should get more than @@ -241,7 +253,9 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) { free(dblist->tree_info->tag_info); dblist->tree_info->tag_info = new_tag_info_ptr; dblist->tree_info->edit->tag_info_pages = pages_needed; - } else { + } + else + { /*************************************************** If we don't have to expand, just add the new tag diff --git a/treeshr/TreeCallHook.c b/treeshr/TreeCallHook.c index a24da99e7a..16b1cbc406 100644 --- a/treeshr/TreeCallHook.c +++ b/treeshr/TreeCallHook.c @@ -35,18 +35,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include static int (*Notify)(TreeshrHookType, char *, int, int) = NULL; -static void load_Notify() { +static void load_Notify() +{ LibFindImageSymbol_C("TreeShrHooks", "Notify", &Notify); } -int TreeCallHook(TreeshrHookType htype, TREE_INFO *info, int nid) { +int TreeCallHook(TreeshrHookType htype, TREE_INFO *info, int nid) +{ RUN_FUNCTION_ONCE(load_Notify); if (Notify) return (*Notify)(htype, info->treenam, info->shot, nid); return 1; } -static char *_strcasestr(char *s1_in, char *s2_in) { +static char *_strcasestr(char *s1_in, char *s2_in) +{ /* This is needed because strcasestr() is no available on all platforms */ char *s1 = strdup(s1_in); char *s2 = strdup(s2_in); @@ -63,7 +66,8 @@ static char *_strcasestr(char *s1_in, char *s2_in) { return s; } -static int isEnabled(char *hookName) { +static int isEnabled(char *hookName) +{ char *enabledHooks = getenv("TreeHooks"); if (enabledHooks == NULL) return 0; @@ -76,16 +80,20 @@ static int isEnabled(char *hookName) { return 1; char *p = enabledHooks; - while (p) { + while (p) + { p = _strcasestr(p, hookName); - if (p) { - if (p == enabledHooks || p[-1] == ',') { + if (p) + { + if (p == enabledHooks || p[-1] == ',') + { size_t len = strlen(hookName); if (p[len] == ',' || p[len] == '\0') return 1; else p = p + len; - } else + } + else return 0; } } @@ -93,7 +101,8 @@ static int isEnabled(char *hookName) { return 0; } -void TreeCallHookFun(char *hookType, char *hookName, ...) { +void TreeCallHookFun(char *hookType, char *hookName, ...) +{ static int (*TdiExecute)() = NULL; int status; status = LibFindImageSymbol_C("TdiShr", "TdiExecute", &TdiExecute); @@ -109,7 +118,8 @@ void TreeCallHookFun(char *hookType, char *hookName, ...) { EMPTYXD(defaultAns); struct descriptor_xd *ans = &defaultAns; struct descriptor *dict = NULL; - if (strcmp(hookType, "TreeHook") == 0) { + if (strcmp(hookType, "TreeHook") == 0) + { va_list ap; va_start(ap, hookName); char *tree = va_arg(ap, char *); @@ -121,12 +131,14 @@ void TreeCallHookFun(char *hookType, char *hookName, ...) { ans = this_ans ? this_ans : &defaultAns; struct descriptor *hook_dscs[] = { (struct descriptor *)&hooktype_key_d, (struct descriptor *)&hooktype_d, - (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, - (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d}; + (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, + (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d}; DESCRIPTOR_APD(hook_d, DTYPE_DICTIONARY, &hook_dscs, 6); dict = (struct descriptor *)&hook_d; (*TdiExecute)(&expression_d, dict, ans MDS_END_ARG); - } else if (strcmp(hookType, "TreeNidHook") == 0) { + } + else if (strcmp(hookType, "TreeNidHook") == 0) + { va_list ap; va_start(ap, hookName); char *tree = va_arg(ap, char *); @@ -140,13 +152,15 @@ void TreeCallHookFun(char *hookType, char *hookName, ...) { ans = this_ans ? this_ans : &defaultAns; struct descriptor *hook_dscs[] = { (struct descriptor *)&hooktype_key_d, (struct descriptor *)&hooktype_d, - (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, - (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d, - (struct descriptor *)&nid_key_d, (struct descriptor *)&nid_d}; + (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, + (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d, + (struct descriptor *)&nid_key_d, (struct descriptor *)&nid_d}; DESCRIPTOR_APD(hook_d, DTYPE_DICTIONARY, &hook_dscs, 8); dict = (struct descriptor *)&hook_d; (*TdiExecute)(&expression_d, dict, ans MDS_END_ARG); - } else if (strcmp(hookType, "TreeNidDataHook") == 0) { + } + else if (strcmp(hookType, "TreeNidDataHook") == 0) + { va_list ap; va_start(ap, hookName); char *tree = va_arg(ap, char *); @@ -161,14 +175,16 @@ void TreeCallHookFun(char *hookType, char *hookName, ...) { ans = this_ans ? this_ans : &defaultAns; struct descriptor *hook_dscs[] = { (struct descriptor *)&hooktype_key_d, (struct descriptor *)&hooktype_d, - (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, - (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d, - (struct descriptor *)&nid_key_d, (struct descriptor *)&nid_d, - (struct descriptor *)&data_key_d, data_d}; + (struct descriptor *)&tree_key_d, (struct descriptor *)&tree_d, + (struct descriptor *)&shot_key_d, (struct descriptor *)&shot_d, + (struct descriptor *)&nid_key_d, (struct descriptor *)&nid_d, + (struct descriptor *)&data_key_d, data_d}; DESCRIPTOR_APD(hook_d, DTYPE_DICTIONARY, &hook_dscs, 10); dict = (struct descriptor *)&hook_d; (*TdiExecute)(&expression_d, dict, ans MDS_END_ARG); - } else { + } + else + { return; } MdsFree1Dx(&defaultAns, 0); diff --git a/treeshr/TreeCleanDatafile.c b/treeshr/TreeCleanDatafile.c index faa05bb132..29a834bd62 100644 --- a/treeshr/TreeCleanDatafile.c +++ b/treeshr/TreeCleanDatafile.c @@ -33,167 +33,179 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern void **TreeCtx(); -typedef struct move_s { +typedef struct move_s +{ char *from_c; char *to_c; char *from_d; char *to_d; } move_t; -static void freemove(void *move_p) { +static void freemove(void *move_p) +{ free(((move_t *)move_p)->from_c); free(((move_t *)move_p)->to_c); free(((move_t *)move_p)->from_d); free(((move_t *)move_p)->to_d); } -static void treeclose(void *dbid_p) { +static void treeclose(void *dbid_p) +{ _TreeClose(dbid_p, 0, 0); free(*(void **)dbid_p); } -STATIC_ROUTINE int RewriteDatafile(char const *tree, int shot, int compress) { +STATIC_ROUTINE int RewriteDatafile(char const *tree, int shot, int compress) +{ int status, stat1; void *dbid1 = 0, *dbid2 = 0; char *tree_list = strcpy(malloc(strlen(tree) + 4), tree); strcat(tree_list, ",\"\""); status = _TreeOpen(&dbid1, tree_list, shot, 1); free(tree_list); - if - STATUS_OK { - move_t move = {0}; - pthread_cleanup_push(freemove, &move); - pthread_cleanup_push(treeclose, &dbid1); - int stv; - PINO_DATABASE *dblist1 = (PINO_DATABASE *)dbid1; - TREE_INFO *info1 = dblist1->tree_info; - status = TreeOpenNciW(dblist1->tree_info, 0); - if - STATUS_OK { - status = TreeOpenDatafileW(dblist1->tree_info, &stv, 0); - if - STATUS_OK { - status = _TreeOpenEdit(&dbid2, tree, shot); - if - STATUS_OK { - pthread_cleanup_push(treeclose, &dbid2); - PINO_DATABASE *dblist2 = (PINO_DATABASE *)dbid2; - TREE_INFO *info2 = dblist2->tree_info; - status = TreeOpenNciW(dblist2->tree_info, 1); - if - STATUS_OK { - dblist2->tree_info->edit->first_in_mem = - dblist2->tree_info->header->nodes; - status = TreeOpenDatafileW(dblist2->tree_info, &stv, 1); - if - STATUS_OK { - int i; - for (i = 0; i < info1->header->nodes; i++) { - EMPTYXD(xd); - EMPTYXD(mtxd); - int first = 1; - struct nci_list { - NCI nci; - struct nci_list *next; - } *list = memset(malloc(sizeof(struct nci_list)), 0, - sizeof(struct nci_list)); - { - int locked = 0; - tree_get_nci(info1, i, &list->nci, 0, &locked); - } - while (list->nci.flags & NciM_VERSIONS) { - struct nci_list *old_list = list; - list = malloc(sizeof(struct nci_list)); - list->next = old_list; - TreeGetVersionNci(info1, &old_list->nci, - &list->nci); - } - while (list) { - int64_t now = -1; - unsigned int oldlength; - struct nci_list *old_list = list; - TreeSetViewDate(&list->nci.time_inserted); - if (first) { - oldlength = list->nci.length; - list->nci.length = 0; - { - int locked = 0; - tree_put_nci(info2, i, &list->nci, &locked); - } - list->nci.length = oldlength; - first = 0; - } - if (list->nci.flags2 & NciM_EXTENDED_NCI) { - TreeCopyExtended(dbid1, dbid2, i, &list->nci, - compress); - } else { - stat1 = _TreeGetRecord(dbid1, i, &xd); - TreeSetViewDate(&now); - if - IS_OK(stat1) { - TreeSetTemplateNci(&list->nci); - stat1 = _TreePutRecord( - dbid2, i, (struct descriptor *)&xd, - compress ? 2 : 1); - } - else if (stat1 == TreeBADRECORD || - stat1 == TreeINVDFFCLASS) { - fprintf(stderr, - "TreeBADRECORD, Clearing nid %d\n", - i); - stat1 = _TreePutRecord( - dbid2, i, (struct descriptor *)&mtxd, - compress ? 2 : 1); - } - MdsFree1Dx(&xd, NULL); - } - list = list->next; - free(old_list); - } - } - move.from_c = - strcpy(malloc(strlen(info1->filespec) + 13), - info1->filespec); - strcpy(move.from_c + strlen(info1->filespec) - 4, - "characteristics#"); - move.to_c = - strcpy(malloc(strlen(info1->filespec) + 12), - info1->filespec); - strcpy(move.to_c + strlen(info1->filespec) - 4, - "characteristics"); - move.from_d = - strcpy(malloc(strlen(info1->filespec) + 6), - info1->filespec); - strcpy(move.from_d + strlen(info1->filespec) - 4, - "datafile#"); - move.to_d = - strcpy(malloc(strlen(info1->filespec) + 5), - info1->filespec); - strcpy(move.to_d + strlen(info1->filespec) - 4, - "datafile"); - } + if (STATUS_OK) + { + move_t move = {0}; + pthread_cleanup_push(freemove, &move); + pthread_cleanup_push(treeclose, &dbid1); + int stv; + PINO_DATABASE *dblist1 = (PINO_DATABASE *)dbid1; + TREE_INFO *info1 = dblist1->tree_info; + status = TreeOpenNciW(dblist1->tree_info, 0); + if (STATUS_OK) + { + status = TreeOpenDatafileW(dblist1->tree_info, &stv, 0); + if (STATUS_OK) + { + status = _TreeOpenEdit(&dbid2, tree, shot); + if (STATUS_OK) + { + pthread_cleanup_push(treeclose, &dbid2); + PINO_DATABASE *dblist2 = (PINO_DATABASE *)dbid2; + TREE_INFO *info2 = dblist2->tree_info; + status = TreeOpenNciW(dblist2->tree_info, 1); + if (STATUS_OK) + { + dblist2->tree_info->edit->first_in_mem = + dblist2->tree_info->header->nodes; + status = TreeOpenDatafileW(dblist2->tree_info, &stv, 1); + if (STATUS_OK) + { + int i; + for (i = 0; i < info1->header->nodes; i++) + { + EMPTYXD(xd); + EMPTYXD(mtxd); + int first = 1; + struct nci_list + { + NCI nci; + struct nci_list *next; + } *list = memset(malloc(sizeof(struct nci_list)), 0, + sizeof(struct nci_list)); + { + int locked = 0; + tree_get_nci(info1, i, &list->nci, 0, &locked); + } + while (list->nci.flags & NciM_VERSIONS) + { + struct nci_list *old_list = list; + list = malloc(sizeof(struct nci_list)); + list->next = old_list; + TreeGetVersionNci(info1, &old_list->nci, + &list->nci); + } + while (list) + { + int64_t now = -1; + unsigned int oldlength; + struct nci_list *old_list = list; + TreeSetViewDate(&list->nci.time_inserted); + if (first) + { + oldlength = list->nci.length; + list->nci.length = 0; + { + int locked = 0; + tree_put_nci(info2, i, &list->nci, &locked); + } + list->nci.length = oldlength; + first = 0; + } + if (list->nci.flags2 & NciM_EXTENDED_NCI) + { + TreeCopyExtended(dbid1, dbid2, i, &list->nci, + compress); + } + else + { + stat1 = _TreeGetRecord(dbid1, i, &xd); + TreeSetViewDate(&now); + if (IS_OK(stat1)) + { + TreeSetTemplateNci(&list->nci); + stat1 = _TreePutRecord( + dbid2, i, (struct descriptor *)&xd, + compress ? 2 : 1); } - pthread_cleanup_pop(1); // treeclose(&dbid2) + else if (stat1 == TreeBADRECORD || + stat1 == TreeINVDFFCLASS) + { + fprintf(stderr, + "TreeBADRECORD, Clearing nid %d\n", + i); + stat1 = _TreePutRecord( + dbid2, i, (struct descriptor *)&mtxd, + compress ? 2 : 1); + } + MdsFree1Dx(&xd, NULL); + } + list = list->next; + free(old_list); } + } + move.from_c = + strcpy(malloc(strlen(info1->filespec) + 13), + info1->filespec); + strcpy(move.from_c + strlen(info1->filespec) - 4, + "characteristics#"); + move.to_c = + strcpy(malloc(strlen(info1->filespec) + 12), + info1->filespec); + strcpy(move.to_c + strlen(info1->filespec) - 4, + "characteristics"); + move.from_d = + strcpy(malloc(strlen(info1->filespec) + 6), + info1->filespec); + strcpy(move.from_d + strlen(info1->filespec) - 4, + "datafile#"); + move.to_d = + strcpy(malloc(strlen(info1->filespec) + 5), + info1->filespec); + strcpy(move.to_d + strlen(info1->filespec) - 4, + "datafile"); } + } + pthread_cleanup_pop(1); // treeclose(&dbid2) } - pthread_cleanup_pop(1); // treeclose(&dbid1) - if - STATUS_OK { - status = MDS_IO_REMOVE(move.to_c) == 0 ? TreeSUCCESS : TreeDELFAIL; - if - STATUS_OK - status = MDS_IO_REMOVE(move.to_d) == 0 ? TreeSUCCESS : TreeDELFAIL; - if - STATUS_OK - status = ((MDS_IO_RENAME(move.from_c, move.to_c) == 0) && - (MDS_IO_RENAME(move.from_d, move.to_d) == 0)) - ? TreeSUCCESS - : TreeRENFAIL; - } - pthread_cleanup_pop(1); // freemove(&move) + } + } + pthread_cleanup_pop(1); // treeclose(&dbid1) + if (STATUS_OK) + { + status = MDS_IO_REMOVE(move.to_c) == 0 ? TreeSUCCESS : TreeDELFAIL; + if (STATUS_OK) + status = MDS_IO_REMOVE(move.to_d) == 0 ? TreeSUCCESS : TreeDELFAIL; + if (STATUS_OK) + status = ((MDS_IO_RENAME(move.from_c, move.to_c) == 0) && + (MDS_IO_RENAME(move.from_d, move.to_d) == 0)) + ? TreeSUCCESS + : TreeRENFAIL; } + pthread_cleanup_pop(1); // freemove(&move) + } return status; } -int _TreeCleanDatafile(void **dbid, char const *tree, int shot) { +int _TreeCleanDatafile(void **dbid, char const *tree, int shot) +{ int status = TreeSUCCESS; if (dbid) status = _TreeClose(dbid, tree, shot); @@ -202,7 +214,8 @@ int _TreeCleanDatafile(void **dbid, char const *tree, int shot) { return RewriteDatafile(tree, shot, 0); } -int _TreeCompressDatafile(void **dbid, char const *tree, int shot) { +int _TreeCompressDatafile(void **dbid, char const *tree, int shot) +{ int status = TreeSUCCESS; if (dbid) status = _TreeClose(dbid, tree, shot); @@ -211,10 +224,12 @@ int _TreeCompressDatafile(void **dbid, char const *tree, int shot) { return RewriteDatafile(tree, shot, 1); } -int TreeCleanDatafile(char const *tree, int shot) { +int TreeCleanDatafile(char const *tree, int shot) +{ return _TreeCleanDatafile(TreeCtx(), tree, shot); } -int TreeCompressDatafile(char const *tree, int shot) { +int TreeCompressDatafile(char const *tree, int shot) +{ return _TreeCompressDatafile(TreeCtx(), tree, shot); } diff --git a/treeshr/TreeCreatePulseFile.c b/treeshr/TreeCreatePulseFile.c index 89c4a8d024..2c54acabd9 100644 --- a/treeshr/TreeCreatePulseFile.c +++ b/treeshr/TreeCreatePulseFile.c @@ -66,21 +66,24 @@ int TreeCreatePulseFile(int shotid,int numnids, int *nids) #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - {} +#define DBG(...) \ + { \ + } #endif STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it); extern void **TreeCtx(); -int TreeCreatePulseFile(int shotid, int numnids_in, int *nids_in) { +int TreeCreatePulseFile(int shotid, int numnids_in, int *nids_in) +{ return _TreeCreatePulseFile(*TreeCtx(), shotid, numnids_in, nids_in); } static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, char *treepath); -int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { +int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; /* Make sure tree is open */ int status = _TreeIsOpen(dblist); @@ -98,14 +101,17 @@ int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { char *treepath; if (info && info->filespec && info->speclen > 2 && info->filespec[info->speclen - 1] == ':' && - info->filespec[info->speclen - 2] == ':') { + info->filespec[info->speclen - 2] == ':') + { treepath = memcpy(malloc(info->speclen + 1), info->filespec, info->speclen); treepath[info->speclen] = '\0'; - } else + } + else treepath = NULL; int nids[256], i, j, num; - if (numnids_in == 0) { + if (numnids_in == 0) + { void *ctx = 0; #ifdef OLD_VIA_USAGE nids[0] = 0; @@ -121,9 +127,12 @@ int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { ; TreeFindTagEnd(&ctx); #endif - } else { + } + else + { num = 0; - for (i = 0; i < numnids_in; i++) { + for (i = 0; i < numnids_in; i++) + { for (j = 0; j < num; j++) if (nids[j] == nids_in[i]) break; @@ -131,10 +140,12 @@ int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { nids[num++] = nids_in[i]; } } - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { int sts, skip = 0; char name[13]; - if (nids[i]) { // for subtree nodes, i.e. nid!=0 + if (nids[i]) + { // for subtree nodes, i.e. nid!=0 int flags; NCI_ITM itmlst[] = {{sizeof(name) - 1, NciNODE_NAME, 0, 0}, {4, NciGET_FLAGS, &flags, 0}, @@ -147,13 +158,16 @@ int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { for (j = 0; j < 12 && name[j] != ' '; j++) ; name[j] = '\0'; - } else { + } + else + { strcpy(name, dblist->experiment); sts = 1; } if (IS_OK(sts) && !(skip)) sts = TreeCreateTreeFilesOne(name, shot, source_shot, treepath); - if (IS_NOT_OK(sts) && i == 0) { + if (IS_NOT_OK(sts) && i == 0) + { status = sts; break; } @@ -163,7 +177,8 @@ int _TreeCreatePulseFile(void *dbid, int shotid, int numnids_in, int *nids_in) { } static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, - char *treepath) { + char *treepath) +{ if (!source_shot || (source_shot < -1)) return TreeINVSHOT; if (!shot || (shot < -1)) @@ -172,41 +187,46 @@ static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, int src[3], dst[3]; INIT_AND_FREE_ON_EXIT(char *, tmp); status = TreeSUCCESS; - for (i = 0; i < 3; i++) { - if - STATUS_OK { - status = - MDS_IO_OPEN_ONE(treepath, tree, source_shot, i + TREE_TREEFILE_TYPE, - 0, 0, &tmp, NULL, &src[i]); - if (tmp) { - if - STATUS_OK DBG("%s ->\n", tmp); - free(tmp); - tmp = NULL; - } + for (i = 0; i < 3; i++) + { + if (STATUS_OK) + { + status = + MDS_IO_OPEN_ONE(treepath, tree, source_shot, i + TREE_TREEFILE_TYPE, + 0, 0, &tmp, NULL, &src[i]); + if (tmp) + { + if (STATUS_OK) + DBG("%s ->\n", tmp); + free(tmp); + tmp = NULL; } + } else src[i] = -1; } - for (i = 0; i < 3; i++) { - if - STATUS_OK { - status = MDS_IO_OPEN_ONE(treepath, tree, shot, i + TREE_TREEFILE_TYPE, - 1, 0, &tmp, NULL, &dst[i]); - if (tmp) { - if - STATUS_OK DBG("%s <-\n", tmp); - free(tmp); - tmp = NULL; - } + for (i = 0; i < 3; i++) + { + if (STATUS_OK) + { + status = MDS_IO_OPEN_ONE(treepath, tree, shot, i + TREE_TREEFILE_TYPE, + 1, 0, &tmp, NULL, &dst[i]); + if (tmp) + { + if (STATUS_OK) + DBG("%s <-\n", tmp); + free(tmp); + tmp = NULL; } + } else dst[i] = -1; } FREE_NOW(tmp); - for (i = 0; i < 3; i++) { - if - STATUS_OK status = _CopyFile(src[i], dst[i], i > 0); + for (i = 0; i < 3; i++) + { + if (STATUS_OK) + status = _CopyFile(src[i], dst[i], i > 0); if (src[i] >= 0) MDS_IO_CLOSE(src[i]); if (dst[i] >= 0) @@ -215,7 +235,8 @@ static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, return status; } -int TreeCreateTreeFiles(char const *tree, int shot, int source_shot) { +int TreeCreateTreeFiles(char const *tree, int shot, int source_shot) +{ return TreeCreateTreeFilesOne(tree, shot, source_shot, NULL); } @@ -223,22 +244,28 @@ int TreeCreateTreeFiles(char const *tree, int shot, int source_shot) { #define MIN(a, b) ((a) < (b)) ? (a) : (b) #define MAX(a, b) ((a) > (b)) ? (a) : (b) -STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it) { +STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it) +{ INIT_STATUS_ERROR; - if (src_fd != -1) { + if (src_fd != -1) + { ssize_t src_len = MDS_IO_LSEEK(src_fd, 0, SEEK_END); - if ((dst_fd != -1) && (src_len != -1)) { + if ((dst_fd != -1) && (src_len != -1)) + { MDS_IO_LSEEK(src_fd, 0, SEEK_SET); if (lock_it) MDS_IO_LOCK(src_fd, 0, (size_t)src_len, MDS_IO_LOCK_RD, 0); - if (src_len > 0) { + if (src_len > 0) + { size_t chunk_size = (size_t)(MIN(MAX_CHUNK, src_len)); void *buff = malloc(chunk_size); size_t bytes_to_go = (size_t)src_len; - while (bytes_to_go > 0) { + while (bytes_to_go > 0) + { size_t io_size = MIN(bytes_to_go, chunk_size); ssize_t bytes_read = MDS_IO_READ(src_fd, buff, io_size); - if (bytes_read == (ssize_t)io_size) { + if (bytes_read == (ssize_t)io_size) + { ssize_t bytes_written = MDS_IO_WRITE(dst_fd, buff, io_size); if (bytes_written != (ssize_t)io_size) break; @@ -248,13 +275,16 @@ STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it) { free(buff); if (bytes_to_go == 0) status = TreeSUCCESS; - } else + } + else status = TreeSUCCESS; if (lock_it) MDS_IO_LOCK(src_fd, 0, (size_t)src_len, MDS_IO_LOCK_NONE, 0); - } else + } + else status = TreeFCREATE; - } else + } + else status = TreeFOPENR; return status; } diff --git a/treeshr/TreeDeleteNode.c b/treeshr/TreeDeleteNode.c index 7471b29296..8462b370a4 100644 --- a/treeshr/TreeDeleteNode.c +++ b/treeshr/TreeDeleteNode.c @@ -62,33 +62,40 @@ extern void **TreeCtx(); STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count); -int TreeDeleteNodeGetNid(int *nid) { +int TreeDeleteNodeGetNid(int *nid) +{ return _TreeDeleteNodeGetNid(*TreeCtx(), nid); } -int TreeDeleteNodeInitialize(int nid, int *count, int reset) { +int TreeDeleteNodeInitialize(int nid, int *count, int reset) +{ return (_TreeDeleteNodeInitialize(*TreeCtx(), nid, count, reset)); } void TreeDeleteNodeExecute() { _TreeDeleteNodeExecute(*TreeCtx()); } -int _TreeDeleteNodeInitialize(void *dbid, int nidin, int *count, int reset) { +int _TreeDeleteNodeInitialize(void *dbid, int nidin, int *count, int reset) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nidin; int vm_needed; if (!IS_OPEN_FOR_EDIT(dblist)) return TreeNOEDIT; vm_needed = dblist->tree_info->header->nodes / 8 + 4; - if (vm_needed != dblist->delete_list_vm) { + if (vm_needed != dblist->delete_list_vm) + { unsigned char *old_list = dblist->delete_list; dblist->delete_list = malloc((size_t)vm_needed); if (!dblist->delete_list) return TreeMEMERR; - if (reset) { + if (reset) + { memset(dblist->delete_list, 0, (size_t)vm_needed); if (count) *count = 0; - } else { + } + else + { if (old_list) memcpy(dblist->delete_list, old_list, (size_t)((dblist->delete_list_vm < vm_needed) @@ -101,7 +108,9 @@ int _TreeDeleteNodeInitialize(void *dbid, int nidin, int *count, int reset) { if (dblist->delete_list_vm) free(old_list); dblist->delete_list_vm = vm_needed; - } else if (reset) { + } + else if (reset) + { memset(dblist->delete_list, 0, (size_t)dblist->delete_list_vm); if (count) *count = 0; @@ -111,18 +120,22 @@ int _TreeDeleteNodeInitialize(void *dbid, int nidin, int *count, int reset) { return TreeSUCCESS; } -static inline int getbit(PINO_DATABASE *dblist, int bitnum) { +static inline int getbit(PINO_DATABASE *dblist, int bitnum) +{ return dblist->delete_list[bitnum / 8] & (1 << (bitnum % 8)); } -static inline void setbit(PINO_DATABASE *dblist, int bitnum) { +static inline void setbit(PINO_DATABASE *dblist, int bitnum) +{ dblist->delete_list[bitnum / 8] = (unsigned char)(dblist->delete_list[bitnum / 8] | (1 << bitnum % 8)); } -STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count) { +STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count) +{ int bitnum = nid->node; - if (!getbit(dblist, bitnum)) { + if (!getbit(dblist, bitnum)) + { NODE *node; NODE *descendent; node = nid_to_node(dblist, nid); @@ -130,18 +143,21 @@ STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count) { (*count)++; setbit(dblist, bitnum); for (descendent = member_of(node); descendent; - descendent = brother_of(0, descendent)) { + descendent = brother_of(0, descendent)) + { NID nid; node_to_nid(dblist, descendent, (&nid)); check_nid(dblist, &nid, count); } for (descendent = child_of(0, node); descendent; - descendent = brother_of(0, descendent)) { + descendent = brother_of(0, descendent)) + { NID nid; node_to_nid(dblist, descendent, (&nid)); check_nid(dblist, &nid, count); } - if (swapint16(&node->conglomerate_elt)) { + if (swapint16(&node->conglomerate_elt)) + { NID elt_nid; NODE *elt_node; unsigned short elt_num = 1; @@ -187,7 +203,8 @@ void TreeDeleteNodeExecute( ) ------------------------------------------------------------------------------*/ -extern void _TreeDeleteNodeExecute(void *dbid) { +extern void _TreeDeleteNodeExecute(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; if (!IS_OPEN_FOR_EDIT(dblist)) return; @@ -203,59 +220,79 @@ extern void _TreeDeleteNodeExecute(void *dbid) { nid.tree = 0; nid.node = 0; - while (_TreeDeleteNodeGetNid(dbid, (int *)&nid) & 1) { + while (_TreeDeleteNodeGetNid(dbid, (int *)&nid) & 1) + { int found = 0; _TreeRemoveNodesTags(dbid, *(int *)&nid); _TreeSetNoSubtree(dbid, *(int *)&nid); node = nid_to_node(dblist, &nid); parent = parent_of(0, node); - if (child_of(0, parent) == node) { + if (child_of(0, parent) == node) + { found = 1; - if (node->brother) { + if (node->brother) + { parent->child = node_offset(brother_of(0, node), parent); - } else + } + else parent->child = 0; - } else if (parent->child) { + } + else if (parent->child) + { NODE *bro; for (bro = child_of(0, parent); bro->brother && (brother_of(0, bro) != node); bro = brother_of(0, bro)) ; - if (brother_of(0, bro) == node) { + if (brother_of(0, bro) == node) + { found = 1; - if (node->brother) { + if (node->brother) + { bro->brother = node_offset(brother_of(0, node), bro); - } else + } + else bro->brother = 0; } } - if (!found) { - if (member_of(parent) == node) { - if (node->brother) { + if (!found) + { + if (member_of(parent) == node) + { + if (node->brother) + { parent->member = node_offset(brother_of(0, node), parent); - } else + } + else parent->member = 0; - } else if (parent->member) { + } + else if (parent->member) + { NODE *bro; for (bro = member_of(parent); bro->brother && (brother_of(0, bro) != node); bro = brother_of(0, bro)) ; - if (brother_of(0, bro) == node) { + if (brother_of(0, bro) == node) + { found = 1; - if (node->brother) { + if (node->brother) + { bro->brother = node_offset(brother_of(0, node), bro); - } else + } + else bro->brother = 0; } } } - if ((int)nid.node < edit->first_in_mem) { + if ((int)nid.node < edit->first_in_mem) + { DELETED_NID *dnid = malloc(sizeof(DELETED_NID)); dnid->next = edit->deleted_nid_list; dnid->nid = nid; edit->deleted_nid_list = dnid; - } else + } + else memset(edit->nci + nid.node - edit->first_in_mem, 0, sizeof(struct nci)); memcpy(node->name, "deleted node", sizeof(node->name)); loadint16(&node->conglomerate_elt, &zero); @@ -267,7 +304,8 @@ extern void _TreeDeleteNodeExecute(void *dbid) { _TreeDeleteNodeInitialize(dbid, 0, 0, 1); } -void _TreeDeleteNodesWrite(void *dbid) { +void _TreeDeleteNodesWrite(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID nid; NODE *node; @@ -281,47 +319,55 @@ void _TreeDeleteNodesWrite(void *dbid) { NCI old_nci; int nidx; for (dnid = edit->deleted_nid_list, edit->deleted_nid_list = 0; dnid; - dnid = next) { + dnid = next) + { next = dnid->next; nid = dnid->nid; free(dnid); node = nid_to_node(dblist, &nid); - if (prevnode) { + if (prevnode) + { int tmp; prevnode->parent = node_offset(node, prevnode); tmp = -swapint32(&prevnode->parent); node->child = swapint32(&tmp); - } else { + } + else + { int tmp; tmp = node_offset(node, dblist->tree_info->node); dblist->tree_info->header->free = swapint32(&tmp); node->child = 0; } prevnode = node; - if (firstempty) { + if (firstempty) + { int tmp; node->parent = node_offset(firstempty, node); tmp = -swapint32(&node->parent); firstempty->child = swapint32(&tmp); - } else + } + else node->parent = 0; nidx = nid.node; int ncilocked = 0; - if - IS_OK(tree_get_and_lock_nci(dblist->tree_info, nidx, &old_nci, - &ncilocked)) { - NCI empty_nci = {0}; - tree_put_nci(dblist->tree_info, nidx, &empty_nci, &ncilocked); - } + if (IS_OK(tree_get_and_lock_nci(dblist->tree_info, nidx, &old_nci, + &ncilocked))) + { + NCI empty_nci = {0}; + tree_put_nci(dblist->tree_info, nidx, &empty_nci, &ncilocked); + } } } -void _TreeDeleteNodesDiscard(void *dbid) { +void _TreeDeleteNodesDiscard(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; TREE_EDIT *edit = dblist->tree_info->edit; DELETED_NID *dnid, *next; for (dnid = edit->deleted_nid_list, edit->deleted_nid_list = 0; dnid; - dnid = next) { + dnid = next) + { next = dnid->next; free(dnid); } @@ -357,7 +403,8 @@ int TreeDeleteNodeGetNid(NID *nid) ------------------------------------------------------------------------------*/ -int _TreeDeleteNodeGetNid(void *dbid, int *innid) { +int _TreeDeleteNodeGetNid(void *dbid, int *innid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)innid; int i; diff --git a/treeshr/TreeDeletePulseFile.c b/treeshr/TreeDeletePulseFile.c index b472de65d8..25bdd24376 100644 --- a/treeshr/TreeDeletePulseFile.c +++ b/treeshr/TreeDeletePulseFile.c @@ -68,49 +68,55 @@ int TreeDeletePulseFile(int shotid,int numnids, int *nids) #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - {} +#define DBG(...) \ + { \ + } #endif extern void **TreeCtx(); -int TreeDeletePulseFile(int shotid, int allfiles) { +int TreeDeletePulseFile(int shotid, int allfiles) +{ return _TreeDeletePulseFile(*TreeCtx(), shotid, allfiles); } -static inline int TreeDeleteTreeFilesOne(char *tree, int shot, char *treepath) { +static inline int TreeDeleteTreeFilesOne(char *tree, int shot, char *treepath) +{ int status, i; int src[3]; char *tmp[3] = {0}; status = TreeSUCCESS; - for (i = 0; i < 3; i++) { - if - STATUS_OK { - status = MDS_IO_OPEN_ONE(treepath, tree, shot, i + TREE_TREEFILE_TYPE, - 0, 0, &tmp[i], NULL, &src[i]); - if (STATUS_OK && tmp[i]) - DBG("%s -x\n", tmp[i]); - } + for (i = 0; i < 3; i++) + { + if (STATUS_OK) + { + status = MDS_IO_OPEN_ONE(treepath, tree, shot, i + TREE_TREEFILE_TYPE, + 0, 0, &tmp[i], NULL, &src[i]); + if (STATUS_OK && tmp[i]) + DBG("%s -x\n", tmp[i]); + } else src[i] = -1; } int retstatus = 0; - for (i = 0; i < 3; i++) { + for (i = 0; i < 3; i++) + { if (src[i] >= 0) MDS_IO_CLOSE(src[i]); - if - STATUS_OK retstatus = MDS_IO_REMOVE(tmp[i]); + if (STATUS_OK) + retstatus = MDS_IO_REMOVE(tmp[i]); free(tmp[i]); } return retstatus ? TreeFAILURE : status; } static inline int _TreeDeletePulseFiles(PINO_DATABASE *dblist, int shotid, - char *treepath) { + char *treepath) +{ void *dbid_tmp = NULL; int status = _TreeOpen(&dbid_tmp, dblist->experiment, shotid, 0); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; void *ctx = 0; // push cleanup of ctx and dbid_tmp status = TreeSUCCESS; @@ -119,10 +125,12 @@ static inline int _TreeDeletePulseFiles(PINO_DATABASE *dblist, int shotid, int nids[256], j, num; for (num = 0; num < 256 && _TreeFindTagWild(dbid_tmp, "TOP", &nids[num], &ctx); - num++) { + num++) + { int sts; char name[13]; - if (nids[num]) { // for subtree nodes, i.e. nid!=0 + if (nids[num]) + { // for subtree nodes, i.e. nid!=0 NCI_ITM itmlst[] = {{sizeof(name) - 1, NciNODE_NAME, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; itmlst[0].pointer = name; @@ -131,18 +139,19 @@ static inline int _TreeDeletePulseFiles(PINO_DATABASE *dblist, int shotid, for (j = 0; j < 12 && name[j] != ' '; j++) ; name[j] = '\0'; - } else { + } + else + { strcpy(name, dblist->experiment); sts = 1; } - if - IS_OK(sts) - sts = TreeDeleteTreeFilesOne(name, shot, treepath); - if - IS_NOT_OK(sts) { - status = sts; - break; - } + if (IS_OK(sts)) + sts = TreeDeleteTreeFilesOne(name, shot, treepath); + if (IS_NOT_OK(sts)) + { + status = sts; + break; + } } // pop cleanup of ctx and dbid_tmp { @@ -154,7 +163,8 @@ static inline int _TreeDeletePulseFiles(PINO_DATABASE *dblist, int shotid, } int _TreeDeletePulseFile(void *dbid, int shotid, - int allfiles __attribute__((unused))) { + int allfiles __attribute__((unused))) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; /* Make sure tree is open */ int status = _TreeIsOpen(dblist); @@ -166,7 +176,8 @@ int _TreeDeletePulseFile(void *dbid, int shotid, TREE_INFO *info = dblist->tree_info; if (info && info->filespec && info->speclen > 2 && info->filespec[info->speclen - 1] == ':' && - info->filespec[info->speclen - 2] == ':') { + info->filespec[info->speclen - 2] == ':') + { treepath = memcpy(malloc(info->speclen + 1), info->filespec, info->speclen); treepath[info->speclen] = '\0'; } diff --git a/treeshr/TreeDoMethod.c b/treeshr/TreeDoMethod.c index 80c6a5ab4c..d1b2b7cd95 100644 --- a/treeshr/TreeDoMethod.c +++ b/treeshr/TreeDoMethod.c @@ -69,12 +69,14 @@ extern void **TreeCtx(); static int (*_TdiIntrinsic)() = NULL; -inline static int strdcmp(const struct descriptor *strd, const char *cmp) { +inline static int strdcmp(const struct descriptor *strd, const char *cmp) +{ return strd && strd->length == strlen(cmp) && strncmp(strd->pointer, cmp, strlen(cmp)) == 0; } -static inline int _LibCallg(void **ctx, void **arglist, void *addr) { +static inline int _LibCallg(void **ctx, void **arglist, void *addr) +{ int status; CTX_PUSH(ctx); status = (int)(intptr_t)LibCallg(arglist, addr); @@ -83,12 +85,14 @@ static inline int _LibCallg(void **ctx, void **arglist, void *addr) { } int TreeDoMethodA(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, int nargs_in, - mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr) { + mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr) +{ return _TreeDoMethodA(*TreeCtx(), nid_dsc, method_ptr, nargs_in, arglist_in, out_ptr); } int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, - int nargs_in, mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr) { + int nargs_in, mdsdsc_t **arglist_in, mdsdsc_xd_t *out_ptr) +{ if (nargs_in > 250) return TdiEXTRA_ARG; INIT_STATUS; @@ -106,8 +110,8 @@ int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, return TreeNOMETHOD; head_nid = 0; status = _TreeGetNci(dbid, *(int *)nid_dsc->pointer, itmlst); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; if (!conglomerate_elt && (data_type != DTYPE_CONGLOM)) return TreeNOMETHOD; struct descriptor_conglom *conglom_ptr; @@ -117,10 +121,11 @@ int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, FREED_ON_EXIT(&method); status = _TreeGetRecord( dbid, head_nid ? head_nid : *((int *)nid_dsc->pointer), &xd); - if - STATUS_NOT_OK goto end; + if (STATUS_NOT_OK) + goto end; conglom_ptr = (struct descriptor_conglom *)xd.pointer; - if (conglom_ptr->dtype != DTYPE_CONGLOM) { + if (conglom_ptr->dtype != DTYPE_CONGLOM) + { status = TreeNOT_CONGLOM; goto end; } @@ -135,48 +140,51 @@ int _TreeDoMethodA(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, for (i = 0; i < nargs_in; i++) arglist[i + 3] = arglist_in[i]; /**** Try python class ***/ - if (strdcmp(conglom_ptr->image, "__python__")) { + if (strdcmp(conglom_ptr->image, "__python__")) + { status = LibFindImageSymbol_C("TdiShr", "_TdiIntrinsic", &_TdiIntrinsic); - if - STATUS_OK { - if (nargs == 4 && strdcmp(method_ptr, "DW_SETUP")) - nargs--; - char exp[1024]; - DESCRIPTOR(exp_dsc, exp); - strcpy(exp, "PyDoMethod("); - for (i = 1; i < nargs - 1; i++) - strcat(exp, "$,"); - strcat(exp, "$)"); - exp_dsc.length = strlen(exp); - arglist[0] = &exp_dsc; - status = _TdiIntrinsic(&dbid, OPC_EXECUTE, nargs, arglist, out_ptr); - } + if (STATUS_OK) + { + if (nargs == 4 && strdcmp(method_ptr, "DW_SETUP")) + nargs--; + char exp[1024]; + DESCRIPTOR(exp_dsc, exp); + strcpy(exp, "PyDoMethod("); + for (i = 1; i < nargs - 1; i++) + strcat(exp, "$,"); + strcat(exp, "$)"); + exp_dsc.length = strlen(exp); + arglist[0] = &exp_dsc; + status = _TdiIntrinsic(&dbid, OPC_EXECUTE, nargs, arglist, out_ptr); + } goto end; } const DESCRIPTOR(underunder, "__"); StrConcat((struct descriptor *)&method, conglom_ptr->model, (struct descriptor *)&underunder, method_ptr MDS_END_ARG); /**** Try lib call ***/ - if (conglom_ptr->image) { + if (conglom_ptr->image) + { for (i = 0; i < method.length; i++) method.pointer[i] = (char)tolower(method.pointer[i]); - if (conglom_ptr->image && conglom_ptr->image->dtype != DTYPE_T) { + if (conglom_ptr->image && conglom_ptr->image->dtype != DTYPE_T) + { status = TdiINVDTYDSC; goto end; } void (*addr)(); status = LibFindImageSymbol(conglom_ptr->image, &method, &addr); - if - STATUS_OK { - arglist[nargs] = out_ptr; - status = (int)(intptr_t)_LibCallg(&dbid, arglist, addr); - goto end; - } + if (STATUS_OK) + { + arglist[nargs] = out_ptr; + status = (int)(intptr_t)_LibCallg(&dbid, arglist, addr); + goto end; + } } /**** Try tdi fun ***/ status = LibFindImageSymbol_C("TdiShr", "_TdiIntrinsic", &_TdiIntrinsic); - if - STATUS_NOT_OK goto end; + if (STATUS_NOT_OK) + goto end; void *funarglist[] = {(void *)&fun}; fun.ndesc = nargs > 254 ? 255 : (unsigned char)(nargs + 1); // add NULL fun.arguments[0] = NULL; @@ -190,7 +198,8 @@ end:; return status; } -int _TreeDoMethod(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...) { +int _TreeDoMethod(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...) +{ int nargs; void *arglist[255]; arglist[0] = NULL; @@ -198,7 +207,8 @@ int _TreeDoMethod(void *dbid, mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...) { return _TreeDoMethodA(dbid, nid_dsc, method_ptr, nargs, (mdsdsc_t **)arglist, (mdsdsc_xd_t *)arglist[nargs]); } -int TreeDoMethod(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...) { +int TreeDoMethod(mdsdsc_t *nid_dsc, mdsdsc_t *method_ptr, ...) +{ int nargs; void *arglist[255]; arglist[0] = NULL; diff --git a/treeshr/TreeFindNode.c b/treeshr/TreeFindNode.c index 92a7dab820..68dea5fe94 100644 --- a/treeshr/TreeFindNode.c +++ b/treeshr/TreeFindNode.c @@ -88,9 +88,11 @@ extern char *_TreeGetPath(void *dbid, int nid_in); /* trim trailing space form str into buf */ -static size_t trim_cpy(char *buf, char *str, size_t len) { +static size_t trim_cpy(char *buf, char *str, size_t len) +{ size_t i; - for (i = 0; i < len; i++) { + for (i = 0; i < len; i++) + { if (str[i] == ' ') break; else @@ -99,44 +101,52 @@ static size_t trim_cpy(char *buf, char *str, size_t len) { buf[i] = '\0'; return i; } -static inline int is_wild2(const char *const str) { +static inline int is_wild2(const char *const str) +{ const char *p = str; while (*p != '\0' && *p != '*' && *p != '%') p++; return *p; } -static inline int is_wild3(const char *const str) { +static inline int is_wild3(const char *const str) +{ const char *p = str; while (*p != '\0' && *p != '*' && *p != '?' && *p != '%') p++; return *p; } -EXPORT int TreeFindNode(char const *path, int *outnid) { +EXPORT int TreeFindNode(char const *path, int *outnid) +{ return _TreeFindNode(*TreeCtx(), path, outnid); } -EXPORT int TreeFindNodeRelative(char const *path, int start, int *outnid) { +EXPORT int TreeFindNodeRelative(char const *path, int start, int *outnid) +{ return _TreeFindNodeRelative(*TreeCtx(), path, start, outnid); } EXPORT int TreeFindNodeWild(char const *path, int *nid_out, void **ctx_inout, - int usage_mask) { + int usage_mask) +{ return _TreeFindNodeWild(*TreeCtx(), path, nid_out, ctx_inout, usage_mask); } EXPORT int TreeFindNodeWildRelative(char const *path, int start, int *nid_out, - void **ctx_inout, int usage_mask) { + void **ctx_inout, int usage_mask) +{ return _TreeFindNodeWildRelative(*TreeCtx(), path, start, nid_out, ctx_inout, usage_mask); } -EXPORT int TreeFindNodeEnd(void **ctx_in) { +EXPORT int TreeFindNodeEnd(void **ctx_in) +{ return _TreeFindNodeEnd(*TreeCtx(), ctx_in); } EXPORT int _TreeFindNodeWild(void *dbid, char const *path, int *nid_out, - void **ctx_inout, int usage_mask) { + void **ctx_inout, int usage_mask) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int startnid = node_to_nid(dblist, dblist->default_node, NULL); int status = _TreeFindNodeWildRelative(dbid, path, startnid, nid_out, @@ -147,7 +157,8 @@ EXPORT int _TreeFindNodeWild(void *dbid, char const *path, int *nid_out, EXPORT int _TreeFindNodeWildRelative(void *dbid, char const *path, int startnid, int *nid_out, void **ctx_inout, - int usage_mask) { + int usage_mask) +{ int status = TreeSUCCESS; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int wild = 0; @@ -158,13 +169,13 @@ EXPORT int _TreeFindNodeWildRelative(void *dbid, char const *path, int startnid, return TreeNOT_OPEN; if (dblist->remote) return FindNodeWildRemote(dbid, path, nid_out, ctx_inout, usage_mask); - if (*ctx_inout == NULL) { + if (*ctx_inout == NULL) + { not_first_time = 0; ctx = (SEARCH_CTX *)calloc(1, sizeof(SEARCH_CTX)); status = WildParse(path, ctx, &wild); - if - STATUS_NOT_OK - return (status); + if (STATUS_NOT_OK) + return (status); *ctx_inout = ctx; NODELIST *tail = NULL; ctx->default_node = dblist->default_node; @@ -174,27 +185,34 @@ EXPORT int _TreeFindNodeWildRelative(void *dbid, char const *path, int startnid, ctx->answers = Search(dblist, ctx, ctx->terms, startn, &tail); ctx->answers = Filter(ctx->answers, usage_mask); - if (ctx->answers && (ctx->answers->node == ctx->default_node) && wild) { + if (ctx->answers && (ctx->answers->node == ctx->default_node) && wild) + { NODELIST *tmp = ctx->answers; ctx->answers = ctx->answers->next; free(tmp); } - } else { + } + else + { ctx = *ctx_inout; } - if (ctx->answers) { + if (ctx->answers) + { NODELIST *tmp; tmp = ctx->answers->next; *nid_out = node_to_nid(dblist, ctx->answers->node, (NID *)nid_out); free(ctx->answers); ctx->answers = tmp; - } else { + } + else + { status = (not_first_time) ? TreeNMN : TreeNNF; } return status; } -EXPORT int _TreeFindNode(void *dbid, char const *path, int *outnid) { +EXPORT int _TreeFindNode(void *dbid, char const *path, int *outnid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int startnid = node_to_nid(dblist, dblist->default_node, NULL); int status = _TreeFindNodeRelative(dblist, path, startnid, outnid); @@ -202,7 +220,8 @@ EXPORT int _TreeFindNode(void *dbid, char const *path, int *outnid) { } EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, int startnid, - int *outnid) { + int *outnid) +{ int status = TreeSUCCESS; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int wild = 0; @@ -210,22 +229,24 @@ EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, int startnid, NODELIST *answer = NULL; NODELIST *tail = NULL; - if (!IS_OPEN(dblist)) { + if (!IS_OPEN(dblist)) + { return TreeNOT_OPEN; } if (dblist->remote) return FindNodeRemote(dblist, path, outnid); - if (path && (path[0] == '\n')) { + if (path && (path[0] == '\n')) + { status = TreeNNF; goto done; } status = WildParse(path, &ctx, &wild); - if - STATUS_NOT_OK - goto done; - if (wild) { + if (STATUS_NOT_OK) + goto done; + if (wild) + { status = TreeNOWILD; goto done; } @@ -235,10 +256,13 @@ EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, int startnid, answer = Search(dblist, &ctx, ctx.terms, startn, &tail); - if (answer) { + if (answer) + { *outnid = node_to_nid(dblist, answer->node, (NID *)outnid); FreeNodeList(answer); - } else { + } + else + { status = TreeNNF; } done: @@ -246,9 +270,12 @@ EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, int startnid, return (status & 1) ? TreeSUCCESS : status; } -EXPORT int _TreeFindNodeEnd(void *dbid __attribute__((unused)), void **ctx) { - if (ctx) { - if (*ctx) { +EXPORT int _TreeFindNodeEnd(void *dbid __attribute__((unused)), void **ctx) +{ + if (ctx) + { + if (*ctx) + { FreeSearchCtx(*ctx); free(*ctx); *ctx = NULL; @@ -257,23 +284,29 @@ EXPORT int _TreeFindNodeEnd(void *dbid __attribute__((unused)), void **ctx) { return TreeSUCCESS; } -static void FreeSearchCtx(SEARCH_CTX *ctx) { +static void FreeSearchCtx(SEARCH_CTX *ctx) +{ free(ctx->wildcard); FreeSearchTerms(ctx->terms); } static NODELIST *Search(PINO_DATABASE *dblist, SEARCH_CTX *ctx, - SEARCH_TERM *term, NODE *start, NODELIST **tail) { + SEARCH_TERM *term, NODE *start, NODELIST **tail) +{ NODELIST *nodes = term ? Find(dblist, term, start, tail) : NULL; - if (nodes) { + if (nodes) + { NODELIST *more_nodes = NULL; NODELIST *more_tail = NULL; - if (term->next) { + if (term->next) + { NODELIST *these_nodes = NULL; NODELIST *n; - for (n = nodes; n; n = n->next) { + for (n = nodes; n; n = n->next) + { NODELIST *these_tail = NULL; these_nodes = Search(dblist, ctx, term->next, n->node, &these_tail); - if (these_nodes) { + if (these_nodes) + { more_nodes = ConcatenateNodeLists(more_nodes, &more_tail, these_nodes, these_tail); } @@ -281,80 +314,101 @@ static NODELIST *Search(PINO_DATABASE *dblist, SEARCH_CTX *ctx, FreeNodeList(nodes); *tail = more_tail; return (more_nodes); - } else { + } + else + { return nodes; } - } else { + } + else + { return NULL; } } static NODELIST *Find(PINO_DATABASE *dblist, SEARCH_TERM *term, NODE *start, - NODELIST **tail) { + NODELIST **tail) +{ NODELIST *answer = NULL; if (((term->search_type == CHILD) || (term->search_type == MEMBER)) && - (!is_wild3(term->term))) { + (!is_wild3(term->term))) + { term->search_type = CHILD_OR_MEMBER; } char trimmed[sizeof(NODE_NAME) + 1]; - switch (term->search_type) { - case (CHILD): { + switch (term->search_type) + { + case (CHILD): + { NODE *n = child_of(dblist, start); - for (; n; n = brother_of(dblist, n)) { + for (; n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); if (match(term->term, trimmed)) answer = AddNodeList(answer, tail, n); } break; } - case (MEMBER): { + case (MEMBER): + { NODE *n; - for (n = member_of(start); n; n = brother_of(dblist, n)) { + for (n = member_of(start); n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); if (match(term->term, trimmed)) answer = AddNodeList(answer, tail, n); } break; } - case (CHILD_OR_MEMBER): { + case (CHILD_OR_MEMBER): + { NODE *n; - for (n = member_of(start); n; n = brother_of(dblist, n)) { + for (n = member_of(start); n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); if (match(term->term, trimmed)) answer = AddNodeList(answer, tail, n); } n = child_of(dblist, start); - for (; n; n = brother_of(dblist, n)) { + for (; n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); if (match(term->term, trimmed)) answer = AddNodeList(answer, tail, n); } break; } - case (CHILD_SEARCH): { + case (CHILD_SEARCH): + { answer = FindChildren(dblist, term, start, tail); break; } - case (MEMBER_SEARCH): { + case (MEMBER_SEARCH): + { answer = FindMembers(dblist, term, start, tail); break; } - case (CHILD_OR_MEMBER_SEARCH): { + case (CHILD_OR_MEMBER_SEARCH): + { answer = FindMembersOrChildren(dblist, term, start, tail); break; } case (TAG): - case (TAG_TREE): { + case (TAG_TREE): + { answer = FindTagWild(dblist, term, tail); break; } - case (PARENT): { + case (PARENT): + { answer = AddNodeList(answer, tail, parent_of(dblist, start)); break; } - case (ANCESTOR): { + case (ANCESTOR): + { NODE *parent = parent_of(dblist, start); - if (parent) { + if (parent) + { trim_cpy(trimmed, parent->name, sizeof(NODE_NAME)); char *search_term = (strlen(term->term)) ? term->term : "*"; if (match(search_term, trimmed)) @@ -362,9 +416,11 @@ static NODELIST *Find(PINO_DATABASE *dblist, SEARCH_TERM *term, NODE *start, } break; } - case (ANCESTOR_SEARCH): { + case (ANCESTOR_SEARCH): + { NODE *parent = parent_of(dblist, start); - while (parent) { + while (parent) + { trim_cpy(trimmed, parent->name, sizeof(NODE_NAME)); char *search_term = (strlen(term->term)) ? term->term : "*"; if (match(search_term, trimmed)) @@ -374,7 +430,8 @@ static NODELIST *Find(PINO_DATABASE *dblist, SEARCH_TERM *term, NODE *start, break; } - default: { + default: + { printf("Search for type %d not implemented\n", term->search_type); return NULL; break; @@ -384,7 +441,8 @@ static NODELIST *Find(PINO_DATABASE *dblist, SEARCH_TERM *term, NODE *start, } static NODELIST *FindTags(PINO_DATABASE *dblist, TREE_INFO *info, int treenum, - char *tagname, NODELIST **tail) { + char *tagname, NODELIST **tail) +{ NODELIST *answer = NULL; TAG_INFO *tptr = info->tag_info; int i; @@ -393,17 +451,22 @@ static NODELIST *FindTags(PINO_DATABASE *dblist, TREE_INFO *info, int treenum, *tail = NULL; NODE *n; nid.tree = treenum; - if (match(tagname, "TOP")) { + if (match(tagname, "TOP")) + { nid.node = 0; n = nid_to_node(dblist, &nid); if (n->usage == TreeUSAGE_SUBTREE_REF) n = child_of(dblist, n); answer = AddNodeList(answer, tail, n); - } else { + } + else + { char trimmed[sizeof(TAG_NAME) + 1]; - for (i = 0; i < info->header->tags; i++) { + for (i = 0; i < info->header->tags; i++) + { trim_cpy(trimmed, tptr[i].name, sizeof(TAG_NAME)); - if (match(tagname, trimmed)) { + if (match(tagname, trimmed)) + { nid.node = tptr[i].node_idx; n = nid_to_node(dblist, &nid); if (n->usage == TreeUSAGE_SUBTREE_REF) @@ -417,7 +480,8 @@ static NODELIST *FindTags(PINO_DATABASE *dblist, TREE_INFO *info, int treenum, return (answer); } -static TREE_INFO *GetDefaultTreeInfo(PINO_DATABASE *dblist, int *treenum) { +static TREE_INFO *GetDefaultTreeInfo(PINO_DATABASE *dblist, int *treenum) +{ TREE_INFO *info; int i = 0; NID nid; @@ -429,12 +493,14 @@ static TREE_INFO *GetDefaultTreeInfo(PINO_DATABASE *dblist, int *treenum) { } static NODELIST *FindTagWild(PINO_DATABASE *dblist, SEARCH_TERM *term, - NODELIST **tail) { + NODELIST **tail) +{ NODELIST *answer = NULL; TREE_INFO *tinfo; int treenum; char *tag_term = strdup(term->term); - if (term->search_type == TAG_TREE) { + if (term->search_type == TAG_TREE) + { int tree_wild; char *treename = tag_term; char *tagname = strstr(tag_term, "::") + 2; @@ -443,8 +509,10 @@ static NODELIST *FindTagWild(PINO_DATABASE *dblist, SEARCH_TERM *term, if (treename[0] == '\\') treename++; for (treenum = 0, tinfo = dblist->tree_info; tinfo; - tinfo = tinfo->next_info, treenum++) { - if (match(treename, tinfo->treenam)) { + tinfo = tinfo->next_info, treenum++) + { + if (match(treename, tinfo->treenam)) + { NODELIST *tag_tail = NULL; answer = ConcatenateNodeLists( answer, tail, FindTags(dblist, tinfo, treenum, tagname, &tag_tail), @@ -453,7 +521,9 @@ static NODELIST *FindTagWild(PINO_DATABASE *dblist, SEARCH_TERM *term, break; } } - } else { + } + else + { TREE_INFO *default_tinfo = GetDefaultTreeInfo(dblist, &treenum); char *tagname = tag_term; int tag_wild; @@ -461,10 +531,13 @@ static NODELIST *FindTagWild(PINO_DATABASE *dblist, SEARCH_TERM *term, tagname++; tag_wild = is_wild2(tagname); answer = FindTags(dblist, default_tinfo, treenum, tagname, tail); - if ((!answer) || tag_wild) { + if ((!answer) || tag_wild) + { for (treenum = 0, tinfo = dblist->tree_info; tinfo; - tinfo = tinfo->next_info) { - if (tinfo != default_tinfo) { + tinfo = tinfo->next_info) + { + if (tinfo != default_tinfo) + { NODELIST *tag_tail = NULL; answer = ConcatenateNodeLists( answer, tail, @@ -481,7 +554,8 @@ static NODELIST *FindTagWild(PINO_DATABASE *dblist, SEARCH_TERM *term, } static NODELIST *FindMembers(PINO_DATABASE *dblist, SEARCH_TERM *term, - NODE *start, NODELIST **tail) { + NODE *start, NODELIST **tail) +{ NODELIST *answer = NULL; NODELIST *queue = NULL; NODELIST *que_tail = NULL; @@ -490,13 +564,16 @@ static NODELIST *FindMembers(PINO_DATABASE *dblist, SEARCH_TERM *term, queue = AddNodeList(queue, &que_tail, start); NODE *n; NODELIST *this; - while (queue) { + while (queue) + { this = queue; queue = queue->next; if (!queue) que_tail = NULL; - if ((n = member_of(this->node))) { - for (; n; n = brother_of(dblist, n)) { + if ((n = member_of(this->node))) + { + for (; n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); char *search_term = (strlen(term->term)) ? term->term : "*"; queue = AddNodeList(queue, &que_tail, n); @@ -510,7 +587,8 @@ static NODELIST *FindMembers(PINO_DATABASE *dblist, SEARCH_TERM *term, } static NODELIST *FindChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, - NODE *start, NODELIST **tail) { + NODE *start, NODELIST **tail) +{ NODELIST *answer = NULL; NODELIST *queue = NULL; NODELIST *que_tail = NULL; @@ -519,13 +597,16 @@ static NODELIST *FindChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, queue = AddNodeList(queue, &que_tail, start); NODE *n; NODELIST *this; - while (queue) { + while (queue) + { this = queue; queue = queue->next; if (!queue) que_tail = NULL; - if ((n = child_of(dblist, this->node))) { - for (; n; n = brother_of(dblist, n)) { + if ((n = child_of(dblist, this->node))) + { + for (; n; n = brother_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); char *search_term = (strlen(term->term)) ? term->term : "*"; queue = AddNodeList(queue, &que_tail, n); @@ -539,7 +620,8 @@ static NODELIST *FindChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, } static NODELIST *FindMembersOrChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, - NODE *start, NODELIST **tail) { + NODE *start, NODELIST **tail) +{ NODELIST *answer = NULL; NODELIST *queue = NULL; NODELIST *que_tail = NULL; @@ -549,13 +631,16 @@ static NODELIST *FindMembersOrChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, answer = AddNodeList(answer, tail, start); NODE *n; NODELIST *this; - while (queue) { + while (queue) + { this = queue; queue = queue->next; if (!queue) que_tail = NULL; - if ((n = descendant_of(dblist, this->node))) { - for (; n; n = sibling_of(dblist, n)) { + if ((n = descendant_of(dblist, this->node))) + { + for (; n; n = sibling_of(dblist, n)) + { trim_cpy(trimmed, n->name, sizeof(NODE_NAME)); char *search_term = (strlen(term->term)) ? term->term : "*"; queue = AddNodeList(queue, &que_tail, n); @@ -568,29 +653,36 @@ static NODELIST *FindMembersOrChildren(PINO_DATABASE *dblist, SEARCH_TERM *term, return answer; } -static NODELIST *AddNodeList(NODELIST *head, NODELIST **tail, NODE *node) { +static NODELIST *AddNodeList(NODELIST *head, NODELIST **tail, NODE *node) +{ NODELIST *this_one = malloc(sizeof(NODELIST)); this_one->node = node; this_one->next = NULL; - if (*tail) { + if (*tail) + { (*tail)->next = this_one; - } else { + } + else + { head = this_one; } *tail = this_one; return (head); } -static void FreeNodeList(NODELIST *list) { +static void FreeNodeList(NODELIST *list) +{ NODELIST *ptr; - for (ptr = list; ptr;) { + for (ptr = list; ptr;) + { NODELIST *nxt = ptr->next; free(ptr); ptr = nxt; } } -static int match(char *first, char *second) { +static int match(char *first, char *second) +{ // If we reach at the end of both strings, we are done if (*first == '\0' && *second == '\0') return 1; @@ -615,46 +707,61 @@ static int match(char *first, char *second) { } static NODELIST *ConcatenateNodeLists(NODELIST *start_list, NODELIST **tail, - NODELIST *end_list, NODELIST *end_tail) { + NODELIST *end_list, NODELIST *end_tail) +{ NODELIST *answer; - if (end_list) { - if (start_list) { + if (end_list) + { + if (start_list) + { (*tail)->next = end_list; answer = start_list; - } else { + } + else + { answer = end_list; } *tail = end_tail; - } else { + } + else + { answer = start_list; } return answer; } -static NODELIST *Filter(NODELIST *list, int usage_mask) { +static NODELIST *Filter(NODELIST *list, int usage_mask) +{ NODELIST *ptr; NODELIST *previous = list; NODELIST *answer = list; /* printf("In Filter() list %s and mask %d \n", *list, usage_mask); */ - for (ptr = list; ptr;) { + for (ptr = list; ptr;) + { if (!((1 << ((ptr->node->usage == TreeUSAGE_SUBTREE_TOP) ? TreeUSAGE_SUBTREE : ptr->node->usage)) & - usage_mask)) { + usage_mask)) + { NODELIST *tmp = ptr; - if (ptr == answer) { + if (ptr == answer) + { answer = ptr->next; previous = answer; ptr = ptr->next; - } else { + } + else + { previous->next = ptr->next; ptr = ptr->next; } free(tmp); - } else { + } + else + { previous = ptr; ptr = ptr->next; } @@ -662,40 +769,52 @@ static NODELIST *Filter(NODELIST *list, int usage_mask) { return answer; } extern int TreeFindParent(PINO_DATABASE *dblist, char *name, NODE **node, - char **new_name, int *child) { + char **new_name, int *child) +{ NODE *start = dblist->default_node; int status = TreeSUCCESS; *node = NULL; char *parent_name = strdup(name); char *last_dot = strrchr(parent_name, '.'); char *last_colon = strrchr(parent_name, ':'); - if ((last_dot == NULL) && (last_colon == NULL)) { + if ((last_dot == NULL) && (last_colon == NULL)) + { *node = start; *new_name = strdup(name); *child = 0; - } else { + } + else + { NID nid; *child = 0; - if (last_dot > last_colon) { + if (last_dot > last_colon) + { *child = 1; *new_name = strdup(last_dot + 1); *last_dot = '\0'; - } else { + } + else + { *child = 0; *new_name = strdup(last_colon + 1); *last_colon = '\0'; } - if (strlen(parent_name) == 0) { + if (strlen(parent_name) == 0) + { status = TreeSUCCESS; *node = dblist->default_node; - } else { + } + else + { status = _TreeFindNode(dblist, parent_name, (int *)&nid); - if (status & 1) { + if (status & 1) + { *node = nid_to_node(dblist, &nid); } } } - if (!*node) { + if (!*node) + { status = TreeNNF; } free(parent_name); diff --git a/treeshr/TreeFindTag.c b/treeshr/TreeFindTag.c index 44e65a4a80..17a6dbd837 100644 --- a/treeshr/TreeFindTag.c +++ b/treeshr/TreeFindTag.c @@ -37,11 +37,13 @@ extern void **TreeCtx(); static int BsearchCompare(const void *this_one, const void *compare_one); -char *TreeFindNodeTags(int nid_in, void **ctx_ptr) { +char *TreeFindNodeTags(int nid_in, void **ctx_ptr) +{ return _TreeFindNodeTags(*TreeCtx(), nid_in, ctx_ptr); } -int TreeFindTag(const char *tagnam, const char *treename, int *tagidx) { +int TreeFindTag(const char *tagnam, const char *treename, int *tagidx) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)*TreeCtx(); NODE *nodeptr; return _TreeFindTag(*TreeCtx(), dblist->default_node, (short)strlen(treename), @@ -49,7 +51,8 @@ int TreeFindTag(const char *tagnam, const char *treename, int *tagidx) { tagidx); } -int TreeFindNodeTagsDsc(int nid_in, void **ctx_ptr, struct descriptor *tag) { +int TreeFindNodeTagsDsc(int nid_in, void **ctx_ptr, struct descriptor *tag) +{ char *tagname = TreeFindNodeTags(nid_in, ctx_ptr); if (!tagname) return TreeTNF; @@ -59,7 +62,8 @@ int TreeFindNodeTagsDsc(int nid_in, void **ctx_ptr, struct descriptor *tag) { return TreeSUCCESS; } -char *_TreeFindNodeTags(void *dbid, int nid_in, void **ctx_ptr) { +char *_TreeFindNodeTags(void *dbid, int nid_in, void **ctx_ptr) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nid_in; TREE_INFO *info_ptr; @@ -85,7 +89,8 @@ char *_TreeFindNodeTags(void *dbid, int nid_in, void **ctx_ptr) { **********************************************************/ nid_to_tree(dblist, nid, info_ptr); - if (info_ptr) { + if (info_ptr) + { /********************************************************* If the context argument is zero then begin at the nodes @@ -95,13 +100,17 @@ char *_TreeFindNodeTags(void *dbid, int nid_in, void **ctx_ptr) { is the tag index of the next tag to be returned to the called. **********************************************************/ - if (*ctx == 0) { + if (*ctx == 0) + { node_ptr = nid_to_node(dblist, nid); loadint32(ctx, &node_ptr->tag_link); - } else if (*ctx == -1) { + } + else if (*ctx == -1) + { *ctx = 0; } - if ((*ctx > 0) && (*ctx <= info_ptr->header->tags)) { + if ((*ctx > 0) && (*ctx <= info_ptr->header->tags)) + { unsigned int i; char *name = (char *)(info_ptr->tag_info + *ctx - 1)->name; for (i = 0; i < sizeof(TAG_NAME) && name[i] != ' '; i++) @@ -112,21 +121,25 @@ char *_TreeFindNodeTags(void *dbid, int nid_in, void **ctx_ptr) { if (*ctx == 0) *ctx = -1; return answer; - } else + } + else *ctx = 0; - } else + } + else *ctx = 0; return NULL; } -struct tag_search { +struct tag_search +{ TAG_NAME tag; TREE_INFO *info; }; int _TreeFindTag(PINO_DATABASE *db, NODE *default_node, short treelen, const char *tree, short taglen, const char *tagnam, - NODE **nodeptr, int *tagidx) { + NODE **nodeptr, int *tagidx) +{ int len = min(taglen, (short)sizeof(TAG_NAME)); int i; int *idx; @@ -144,15 +157,18 @@ int _TreeFindTag(PINO_DATABASE *db, NODE *default_node, short treelen, *********************************************/ for (tsearch.info = db->tree_info; tsearch.info; - tsearch.info = tsearch.info->next_info) { - if (tree) { + tsearch.info = tsearch.info->next_info) + { + if (tree) + { size_t len = strlen(tsearch.info->treenam); if ((len == (size_t)treelen) && strncmp(tsearch.info->treenam, tree, len) == 0) break; - } else if ((default_node >= tsearch.info->node) && - (default_node < - tsearch.info->node + tsearch.info->header->nodes)) + } + else if ((default_node >= tsearch.info->node) && + (default_node < + tsearch.info->node + tsearch.info->header->nodes)) break; } if (tsearch.info == NULL) @@ -165,11 +181,14 @@ int _TreeFindTag(PINO_DATABASE *db, NODE *default_node, short treelen, Otherwise we must look up the tagname in the tagname table of the tree. ***********************************************/ - if (taglen == 3 && strncmp(tagnam, "TOP", 3) == 0) { + if (taglen == 3 && strncmp(tagnam, "TOP", 3) == 0) + { *nodeptr = tsearch.info->root; *tagidx = 0; return TreeSUCCESS; - } else { + } + else + { /****************************************************** To look up the tag in the tag table we will use a binary search. If there are no tags defined, just return @@ -179,48 +198,57 @@ int _TreeFindTag(PINO_DATABASE *db, NODE *default_node, short treelen, we will just use the C binary search routine to find the tag in the table. ********************************************************/ - switch (tsearch.info->header->tags) { + switch (tsearch.info->header->tags) + { case 0: status = TreeTNF; break; case 1: - if (BsearchCompare((void *)&tsearch, (void *)tsearch.info->tags) == 0) { + if (BsearchCompare((void *)&tsearch, (void *)tsearch.info->tags) == 0) + { *nodeptr = tsearch.info->node + swapint32(&tsearch.info->tag_info->node_idx); *tagidx = 1; return TreeSUCCESS; - } else + } + else status = TreeTNF; break; default: if ((idx = bsearch((const void *)&tsearch, (const void *)tsearch.info->tags, (size_t)tsearch.info->header->tags, sizeof(int), - BsearchCompare)) != 0) { + BsearchCompare)) != 0) + { *nodeptr = tsearch.info->node + swapint32(&(tsearch.info->tag_info + swapint32(idx))->node_idx); *tagidx = swapint32(idx) + 1; return TreeSUCCESS; - } else + } + else status = TreeTNF; break; } - if (status == TreeTNF && tree == 0) { + if (status == TreeTNF && tree == 0) + { char *tag; void *ctx = 0; int nid; NODE *node; NID *nidptr = (NID *)&nid; unsigned int i; - for (i = 0; i < sizeof(tsearch.tag); i++) { - if (tsearch.tag[i] == ' ') { + for (i = 0; i < sizeof(tsearch.tag); i++) + { + if (tsearch.tag[i] == ' ') + { tsearch.tag[i] = '\0'; break; } } tag = _TreeFindTagWild(db, tsearch.tag, &nid, &ctx); - if (tag) { + if (tag) + { status = TreeSUCCESS; node = nid_to_node(db, nidptr); *nodeptr = node; @@ -231,7 +259,8 @@ int _TreeFindTag(PINO_DATABASE *db, NODE *default_node, short treelen, return status; } -static int BsearchCompare(const void *this_one, const void *compare_one) { +static int BsearchCompare(const void *this_one, const void *compare_one) +{ struct tag_search *tsearch = (struct tag_search *)this_one; char *tag = (tsearch->info->tag_info + swapint32(compare_one))->name; diff --git a/treeshr/TreeFindTagWild.c b/treeshr/TreeFindTagWild.c index 30655d745d..4a02575b98 100644 --- a/treeshr/TreeFindTagWild.c +++ b/treeshr/TreeFindTagWild.c @@ -68,7 +68,8 @@ extern int FindTagEndRemote(); extern void **TreeCtx(); -typedef struct tag_search { +typedef struct tag_search +{ int next_tag; TREE_INFO *this_tree_info; mdsdsc_d_t search_tag; @@ -84,12 +85,14 @@ static int nextTagTree(PINO_DATABASE *dblist, TAG_SEARCH *ctx); char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout); -char *TreeFindTagWild(char *wild, int *nidout, void **ctx_inout) { +char *TreeFindTagWild(char *wild, int *nidout, void **ctx_inout) +{ return _TreeFindTagWild(*TreeCtx(), wild, nidout, ctx_inout); } int _TreeFindTagWildDsc(void *dbid, char *wild, int *nidout, void **ctx_inout, - mdsdsc_xd_t *name) { + mdsdsc_xd_t *name) +{ char *ans_c = _TreeFindTagWild(dbid, wild, nidout, ctx_inout); if (!ans_c) return TreeFAILURE; @@ -98,49 +101,62 @@ int _TreeFindTagWildDsc(void *dbid, char *wild, int *nidout, void **ctx_inout, return TreeSUCCESS; } int TreeFindTagWildDsc(char *wild, int *nidout, void **ctx_inout, - mdsdsc_xd_t *name) { + mdsdsc_xd_t *name) +{ return _TreeFindTagWildDsc(*TreeCtx(), wild, nidout, ctx_inout, name); } -static int findtag(PINO_DATABASE *dblist, TAG_SEARCH **ctx) { +static int findtag(PINO_DATABASE *dblist, TAG_SEARCH **ctx) +{ int found, done, status; mdsdsc_s_t s_tag_dsc = {sizeof(TAG_NAME), DTYPE_T, CLASS_S, 0}; mdsdsc_d_t tag_dsc = {0, DTYPE_T, CLASS_D, 0}; FREED_ON_EXIT(&tag_dsc); - for (found = 0, done = 0, status = 1; STATUS_OK && !found && !done;) { + for (found = 0, done = 0, status = 1; STATUS_OK && !found && !done;) + { /************************************* if out of tags in this tree then see if there is another one **************************************/ - if ((*ctx)->next_tag >= (*ctx)->this_tree_info->header->tags) { + if ((*ctx)->next_tag >= (*ctx)->this_tree_info->header->tags) + { status = nextTagTree(dblist, *ctx); - if - STATUS_OK(*ctx)->next_tag = -1; - else { + if (STATUS_OK) + (*ctx)->next_tag = -1; + else + { done = 1; break; } - } else { + } + else + { /********************************************** else if this is the first time for this tree try to return the \TOP tag. otherwise - move on to next tag for next time through the loop. ***********************************************/ - if ((*ctx)->next_tag == -1) { - if ((*ctx)->top_match) { + if ((*ctx)->next_tag == -1) + { + if ((*ctx)->top_match) + { done = 1; found = 1; - } else + } + else ((*ctx)->next_tag)++; - } else { + } + else + { /**************************************** Else loop looking for a tag that matches *****************************************/ for (; !done && - ((*ctx)->next_tag < (*ctx)->this_tree_info->header->tags);) { + ((*ctx)->next_tag < (*ctx)->this_tree_info->header->tags);) + { unsigned short len; s_tag_dsc.pointer = (char *)(*ctx) @@ -149,12 +165,12 @@ static int findtag(PINO_DATABASE *dblist, TAG_SEARCH **ctx) { &(*ctx)->this_tree_info->tags[(*ctx)->next_tag])] .name; StrTrim((mdsdsc_t *)&tag_dsc, (mdsdsc_t *)&s_tag_dsc, &len); - if - IS_OK(StrMatchWild((mdsdsc_t *)&tag_dsc, - (mdsdsc_t *)&((*ctx)->search_tag))) { - done = 1; - found = 1; - } + if (IS_OK(StrMatchWild((mdsdsc_t *)&tag_dsc, + (mdsdsc_t *)&((*ctx)->search_tag)))) + { + done = 1; + found = 1; + } else ((*ctx)->next_tag)++; } @@ -165,7 +181,8 @@ static int findtag(PINO_DATABASE *dblist, TAG_SEARCH **ctx) { return found; } -char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { +char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; /*************************** check that there is a tree @@ -183,13 +200,15 @@ char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { it in with a parse of the tagname. ***********************************/ int status; - if (*ctx == (TAG_SEARCH *)0) { + if (*ctx == (TAG_SEARCH *)0) + { *ctx = newTagSearch(wild); if (*ctx == (TAG_SEARCH *)0) return NULL; else status = nextTagTree(dblist, *ctx); - } else + } + else status = TreeSUCCESS; /************************************* @@ -198,10 +217,12 @@ char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { /******************************************** If done and found then fill in the answer *********************************************/ - if (STATUS_OK && findtag(dblist, ctx)) { + if (STATUS_OK && findtag(dblist, ctx)) + { NODE *nptr = (*ctx)->this_tree_info->node; char tagname[sizeof(TAG_NAME) + 1]; - if ((*ctx)->next_tag != -1) { + if ((*ctx)->next_tag != -1) + { mdsdsc_s_t s_tag_name = {sizeof(TAG_NAME), DTYPE_T, CLASS_S, 0}; mdsdsc_s_t tag_name = {sizeof(TAG_NAME), DTYPE_T, CLASS_S, tagname}; unsigned short len; @@ -219,7 +240,8 @@ char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { ->tag_info[swapint32( &(*ctx)->this_tree_info->tags[(*ctx)->next_tag])] .node_idx); - } else + } + else strcpy(tagname, "TOP"); strcpy((*ctx)->answer, "\\"); strcat((*ctx)->answer, (*ctx)->this_tree_info->treenam); @@ -228,7 +250,9 @@ char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { if (nid_ptr) node_to_nid(dblist, nptr, nid_ptr); ((*ctx)->next_tag)++; - } else { + } + else + { TreeFindTagEnd(ctx_inout); status = TreeNMT; } @@ -238,13 +262,15 @@ char *_TreeFindTagWild(void *dbid, char *wild, int *nidout, void **ctx_inout) { /**************************************** Routine to free the tag search context *****************************************/ -void TreeFindTagEnd(void **ctx_inout) { +void TreeFindTagEnd(void **ctx_inout) +{ if (!*ctx_inout) return; TAG_SEARCH **ctx = (TAG_SEARCH **)ctx_inout; if ((*ctx)->remote) FindTagEndRemote(ctx_inout); - else { + else + { StrFree1Dx(&((*ctx)->search_tag)); StrFree1Dx(&((*ctx)->search_tree)); free(*ctx); @@ -255,7 +281,8 @@ void TreeFindTagEnd(void **ctx_inout) { /***************************************************** Routine to return a new tag search data structure. ******************************************************/ -static inline TAG_SEARCH *newTagSearch(char *tagnam_ptr) { +static inline TAG_SEARCH *newTagSearch(char *tagnam_ptr) +{ const DESCRIPTOR(top, "TOP"); length_t tree_len; TAG_SEARCH *ctx = (TAG_SEARCH *)malloc(sizeof(TAG_SEARCH)); @@ -268,18 +295,21 @@ static inline TAG_SEARCH *newTagSearch(char *tagnam_ptr) { ctx->remote = 0; ctx->answer[0] = '\0'; DESCRIPTOR_FROM_CSTRING(tag_dsc, tagnam_ptr); - if (*(char *)tag_dsc.pointer == '\\') { + if (*(char *)tag_dsc.pointer == '\\') + { tag_dsc.length--; tag_dsc.pointer++; } char *cptr = strstr(tagnam_ptr, "::"); const length_t one = 1; - if (cptr) { + if (cptr) + { tree_len = (length_t)(cptr - tagnam_ptr); StrCopyR((mdsdsc_t *)&ctx->search_tree, &tree_len, tag_dsc.pointer); tag_dsc.length = (length_t)(tag_dsc.length - tree_len - 2); tag_dsc.pointer += (tree_len + 2); - } else + } + else StrCopyR((mdsdsc_t *)&ctx->search_tree, &one, "*"); if (tag_dsc.length) StrCopyDx((mdsdsc_t *)&ctx->search_tag, &tag_dsc); @@ -296,17 +326,18 @@ static inline TAG_SEARCH *newTagSearch(char *tagnam_ptr) { Routine to return the next subtree in this tree which matches the wildcard tree spec. *********************************************/ -static int nextTagTree(PINO_DATABASE *dblist, TAG_SEARCH *ctx) { +static int nextTagTree(PINO_DATABASE *dblist, TAG_SEARCH *ctx) +{ if (!ctx->this_tree_info) ctx->this_tree_info = dblist->tree_info; else ctx->this_tree_info = ctx->this_tree_info->next_info; for (; ctx->this_tree_info; - ctx->this_tree_info = ctx->this_tree_info->next_info) { + ctx->this_tree_info = ctx->this_tree_info->next_info) + { DESCRIPTOR_FROM_CSTRING(treenam, ctx->this_tree_info->treenam); - if - IS_OK(StrMatchWild(&treenam, (mdsdsc_t *)&ctx->search_tree)) - return TreeSUCCESS; + if (IS_OK(StrMatchWild(&treenam, (mdsdsc_t *)&ctx->search_tree))) + return TreeSUCCESS; } return TreeNMT; } diff --git a/treeshr/TreeGetDbi.c b/treeshr/TreeGetDbi.c index e70552b352..d8a9d18b26 100644 --- a/treeshr/TreeGetDbi.c +++ b/treeshr/TreeGetDbi.c @@ -31,33 +31,40 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern void **TreeCtx(); static inline int minInt(int a, int b) { return a < b ? a : b; } -int TreeGetDbi(struct dbi_itm *itmlst) { +int TreeGetDbi(struct dbi_itm *itmlst) +{ return _TreeGetDbi(*TreeCtx(), itmlst); } -#define set_retlen(length) \ - if ((unsigned int)lst->buffer_length < length) { \ - status = TreeBUFFEROVF; \ - break; \ - } else \ +#define set_retlen(length) \ + if ((unsigned int)lst->buffer_length < length) \ + { \ + status = TreeBUFFEROVF; \ + break; \ + } \ + else \ retlen = length -#define CheckOpen(db) \ - if (!db || !db->open) { \ - status = TreeNOT_OPEN; \ - break; \ +#define CheckOpen(db) \ + if (!db || !db->open) \ + { \ + status = TreeNOT_OPEN; \ + break; \ } -#define set_ret_char(val) \ - memset(lst->pointer, 0, (size_t)lst->buffer_length); \ +#define set_ret_char(val) \ + memset(lst->pointer, 0, (size_t)lst->buffer_length); \ *((char *)lst->pointer) = val -int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst) { +int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst) +{ PINO_DATABASE *db = (PINO_DATABASE *)dbid; struct dbi_itm *lst = itmlst; int status = TreeSUCCESS; - while ((lst->code != 0) && (status & 1)) { + while ((lst->code != 0) && (status & 1)) + { char *string = NULL; unsigned short retlen = 0; - switch (lst->code) { + switch (lst->code) + { case DbiNAME: CheckOpen(db); @@ -176,15 +183,19 @@ int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst) { default: status = TreeILLEGAL_ITEM; } - if (string) { - if (lst->buffer_length && lst->pointer) { + if (string) + { + if (lst->buffer_length && lst->pointer) + { retlen = (unsigned short)minInt((int)strlen(string), lst->buffer_length); memcpy((char *)lst->pointer, string, (size_t)retlen); if (retlen < lst->buffer_length) ((char *)lst->pointer)[retlen] = '\0'; free(string); - } else { + } + else + { lst->pointer = (unsigned char *)string; retlen = (unsigned short)strlen(string); } diff --git a/treeshr/TreeGetNci.c b/treeshr/TreeGetNci.c index d5cab3fa6b..b205024d5f 100644 --- a/treeshr/TreeGetNci.c +++ b/treeshr/TreeGetNci.c @@ -45,33 +45,37 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static inline int minInt(int a, int b) { return a < b ? a : b; } -#define read_nci \ - if (nci_version != version) { \ - nid_to_tree_nidx(dblist, (&nid), info, node_number); \ - TreeCallHookFun("TreeNidHook", "GetNci", info->treenam, info->shot, nid, \ - NULL); \ - status = TreeCallHook(GetNci, info, nid_in); \ - if (status && STATUS_NOT_OK) \ - break; \ - { \ - int locked = 0; \ - status = tree_get_nci(info, node_number, &nci, version, &locked); \ - } \ - if \ - STATUS_OK nci_version = version; \ - if \ - STATUS_NOT_OK break; \ +#define read_nci \ + if (nci_version != version) \ + { \ + nid_to_tree_nidx(dblist, (&nid), info, node_number); \ + TreeCallHookFun("TreeNidHook", "GetNci", info->treenam, info->shot, nid, \ + NULL); \ + status = TreeCallHook(GetNci, info, nid_in); \ + if (status && STATUS_NOT_OK) \ + break; \ + { \ + int locked = 0; \ + status = tree_get_nci(info, node_number, &nci, version, &locked); \ + } \ + if (STATUS_OK) \ + nci_version = version; \ + if (STATUS_NOT_OK) \ + break; \ } -#define break_on_no_node \ - if (!node_exists) { \ - status = TreeNNF; \ - break; \ +#define break_on_no_node \ + if (!node_exists) \ + { \ + status = TreeNNF; \ + break; \ } -#define set_retlen(length) \ - if (itm->buffer_length < (int)(length)) { \ - status = TreeBUFFEROVF; \ - break; \ - } else \ +#define set_retlen(length) \ + if (itm->buffer_length < (int)(length)) \ + { \ + status = TreeBUFFEROVF; \ + break; \ + } \ + else \ retlen = (length) #define NODE_NOT_FOUND_NAME " " @@ -81,7 +85,8 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs); extern void **TreeCtx(); -static char *Treename(PINO_DATABASE *dblist, int nid_in) { +static char *Treename(PINO_DATABASE *dblist, int nid_in) +{ TREE_INFO *info; NID nid = *(NID *)&nid_in; unsigned int treenum; @@ -90,26 +95,36 @@ static char *Treename(PINO_DATABASE *dblist, int nid_in) { ; return info ? info->treenam : ""; } -static char *AbsPath(void *dbid, char const *inpath, int nid_in) { +static char *AbsPath(void *dbid, char const *inpath, int nid_in) +{ char *answer = NULL, *pathptr = NULL; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; _TreeSetDefaultNid(dbid, nid_in); size_t len = strlen(inpath); - if (len) { + if (len) + { int nid; - if (_TreeFindNode(dbid, inpath, &nid) & 1) { + if (_TreeFindNode(dbid, inpath, &nid) & 1) + { pathptr = _TreeGetPath(dbid, nid); len = strlen(pathptr); - } else + } + else pathptr = strdup(inpath); - } else { + } + else + { pathptr = _TreeGetPath(dbid, nid_in); len = strlen(pathptr); } - if (pathptr[0] == '\\') { - if (strstr(pathptr, "::")) { + if (pathptr[0] == '\\') + { + if (strstr(pathptr, "::")) + { answer = strdup(pathptr); - } else { + } + else + { char *treename = Treename(dblist, nid_in); answer = (char *)malloc(strlen(treename) + strlen(pathptr) + 2 + 1); strcpy(answer, "\\"); @@ -117,24 +132,31 @@ static char *AbsPath(void *dbid, char const *inpath, int nid_in) { strcat(answer, "::"); strcat(answer, pathptr + 1); } - } else if ((strstr(pathptr, "-") == pathptr) || - (strstr(pathptr, ".-") == pathptr)) { + } + else if ((strstr(pathptr, "-") == pathptr) || + (strstr(pathptr, ".-") == pathptr)) + { int nid; NODE node; NODE *nodeptr = &node; NID *nidptr = (NID *)&nid; NID *nidinptr = (NID *)&nid_in; - if (nid_in) { + if (nid_in) + { nodeptr = nid_to_node(dblist, nidinptr); node_to_nid(dblist, parent_of(dblist, nodeptr), nidptr); answer = AbsPath(dbid, &pathptr[2], nid); - } else + } + else answer = NULL; - } else { + } + else + { char *tmp = _TreeGetPath(dbid, nid_in); answer = strcpy(malloc(strlen(tmp) + strlen(pathptr) + 2), tmp); free(tmp); - switch (pathptr[0]) { + switch (pathptr[0]) + { case '.': case ':': strcat(answer, pathptr); @@ -148,7 +170,8 @@ static char *AbsPath(void *dbid, char const *inpath, int nid_in) { free(pathptr); return answer; } -char *_TreeAbsPath(void *dbid, char const *inpath) { +char *_TreeAbsPath(void *dbid, char const *inpath) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int nid; char *answer; @@ -161,10 +184,12 @@ char *_TreeAbsPath(void *dbid, char const *inpath) { _TreeSetDefaultNid(dbid, nid); return answer; } -char *TreeAbsPath(char const *inpath) { +char *TreeAbsPath(char const *inpath) +{ return _TreeAbsPath(*TreeCtx(), inpath); } -int _TreeAbsPathDsc(void *dbid, char const *inpath, mdsdsc_t *out_ptr) { +int _TreeAbsPathDsc(void *dbid, char const *inpath, mdsdsc_t *out_ptr) +{ char *ans_c = _TreeAbsPath(dbid, inpath); if (!ans_c) return TreeFAILURE; @@ -173,11 +198,13 @@ int _TreeAbsPathDsc(void *dbid, char const *inpath, mdsdsc_t *out_ptr) { free(ans_c); return TreeSUCCESS; } -int TreeAbsPathDsc(char const *inpath, mdsdsc_t *out_ptr) { +int TreeAbsPathDsc(char const *inpath, mdsdsc_t *out_ptr) +{ return _TreeAbsPathDsc(*TreeCtx(), inpath, out_ptr); } -int _TreeGetNci(void *dbid, int nid_in, struct nci_itm *nci_itm) { +int _TreeGetNci(void *dbid, int nid_in, struct nci_itm *nci_itm) +{ int status; CTX_PUSH(&dbid); status = TreeGetNci(nid_in, nci_itm); @@ -185,7 +212,8 @@ int _TreeGetNci(void *dbid, int nid_in, struct nci_itm *nci_itm) { return status; } -int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { +int TreeGetNci(int nid_in, struct nci_itm *nci_itm) +{ void *dbid = *TreeCtx(); INIT_STATUS_AS TreeSUCCESS; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; @@ -213,11 +241,13 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { return GetNciRemote(dbid, nid_in, nci_itm); saved_node = nid_to_node(dblist, &nid); node_exists = saved_node && (saved_node->name[0] < 'a'); - for (itm = nci_itm; itm->code != NciEND_OF_LIST && STATUS_OK; itm++) { + for (itm = nci_itm; itm->code != NciEND_OF_LIST && STATUS_OK; itm++) + { char *string = NULL; int retlen = 0; node = saved_node; - switch (itm->code) { + switch (itm->code) + { case NciVERSION: break_on_no_node; set_retlen(0); @@ -326,37 +356,45 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { case NciPARENT: break_on_no_node; set_retlen(sizeof(NID)); - if (parent_of(dblist, node)) { + if (parent_of(dblist, node)) + { node_to_nid(dblist, parent_of(dblist, node), &out_nid); *(NID *)itm->pointer = out_nid; - } else + } + else retlen = 0; break; case NciBROTHER: break_on_no_node; set_retlen(sizeof(NID)); - if (brother_of(dblist, node)) { + if (brother_of(dblist, node)) + { node_to_nid(dblist, brother_of(dblist, node), (&out_nid)); *(NID *)itm->pointer = out_nid; - } else + } + else retlen = 0; break; case NciMEMBER: break_on_no_node; set_retlen(sizeof(NID)); - if (member_of(node)) { + if (member_of(node)) + { node_to_nid(dblist, member_of(node), (&out_nid)); *(NID *)itm->pointer = out_nid; - } else + } + else retlen = 0; break; case NciCHILD: break_on_no_node; set_retlen(sizeof(NID)); - if (child_of(dblist, node)) { + if (child_of(dblist, node)) + { node_to_nid(dblist, child_of(dblist, node), (&out_nid)); *(NID *)itm->pointer = out_nid; - } else + } + else retlen = 0; break; case NciPARENT_RELATIONSHIP: @@ -367,19 +405,22 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { break; case NciCONGLOMERATE_NIDS: break_on_no_node; - if (node->conglomerate_elt) { + if (node->conglomerate_elt) + { out_nid = nid; out_nid.node -= (swapint16(&node->conglomerate_elt) - 1); cng_node = node - swapint16(&node->conglomerate_elt) + 1; int len = itm->buffer_length >> 2; // /4; for (i = 0; i < len && i < swapint16(&cng_node->conglomerate_elt); - i++) { + i++) + { *((NID *)(itm->pointer) + i) = out_nid; cng_node++; out_nid.node++; } set_retlen(sizeof(NID) * i); - } else + } + else retlen = 0; break; case NciNUMBER_OF_CHILDREN: @@ -411,7 +452,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { ; *(int *)(itm->pointer) = count; break; - case NciCHILDREN_NIDS: { + case NciCHILDREN_NIDS: + { break_on_no_node; out_nids = (NID *)itm->pointer; end_nids = (NID *)(((char *)itm->pointer) + itm->buffer_length); @@ -421,7 +463,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { out_nids++) node_to_nid(dblist, node, out_nids); retlen = (int)((char *)out_nids - (char *)itm->pointer); - } break; + } + break; case NciMEMBER_NIDS: break_on_no_node; out_nids = (NID *)itm->pointer; @@ -441,11 +484,13 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { : node->usage); break; case NciNODE_NAME: - if (node_exists) { + if (node_exists) + { string = strncpy(malloc(sizeof(NODE_NAME) + 1), node->name, sizeof(NODE_NAME)); string[sizeof(NODE_NAME)] = '\0'; - } else + } + else string = strdup(NODE_NOT_FOUND_NAME); break; case NciPATH: @@ -456,20 +501,23 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { break; case NciORIGINAL_PART_NAME: break_on_no_node; - if (node->conglomerate_elt) { + if (node->conglomerate_elt) + { struct descriptor_d string_d = {0, DTYPE_T, CLASS_D, 0}; DESCRIPTOR_NID(nid_dsc, 0); DESCRIPTOR(part_name, "PART_NAME"); nid_dsc.pointer = (char *)&nid; status = _TreeDoMethod(dbid, &nid_dsc, (struct descriptor *)&part_name, &string_d MDS_END_ARG); - if (status == TreeNOMETHOD) { + if (status == TreeNOMETHOD) + { DESCRIPTOR(part_name, "ORIGINAL_PART_NAME"); status = _TreeDoMethod(dbid, &nid_dsc, (struct descriptor *)&part_name, &string_d MDS_END_ARG); } - if (STATUS_OK && string_d.pointer) { + if (STATUS_OK && string_d.pointer) + { string = strncpy(malloc(string_d.length + 1), string_d.pointer, string_d.length); string[string_d.length] = 0; @@ -478,13 +526,15 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { } break; case NciFULLPATH: - if (node_exists) { + if (node_exists) + { char *part = malloc(0x1000); char *temp; string = malloc(0x1000); string[0] = 0; part[0] = 0; - for (; parent_of(dblist, node); node = parent_of(dblist, node)) { + for (; parent_of(dblist, node); node = parent_of(dblist, node)) + { unsigned int i; part[0] = TreeIsChild(dblist, node) ? '.' : ':'; for (i = 0; i < sizeof(NODE_NAME) && node->name[i] != ' '; i++) @@ -504,17 +554,22 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { strcat(string, "::TOP"); strcat(string, part); free(part); - } else + } + else string = strdup(NODE_NOT_FOUND_PATH); break; case NciMINPATH: - if (node_exists) { - if (nid.tree == 0 && nid.node == 0) { + if (node_exists) + { + if (nid.tree == 0 && nid.node == 0) + { string = malloc(7 + strlen(dblist->tree_info->treenam)); string[0] = '\\'; strcpy(&string[1], dblist->tree_info->treenam); strcat(string, "::TOP"); - } else { + } + else + { char *part = malloc(0x1000); char *temp; NODE *default_node = dblist->default_node; @@ -534,7 +589,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { found_it: for (ancestor = node; parent_of(dblist, ancestor) && (default_node != ancestor); - ancestor = parent_of(dblist, ancestor)) { + ancestor = parent_of(dblist, ancestor)) + { unsigned int i; part[0] = TreeIsChild(dblist, ancestor) ? '.' : ':'; for (i = 0; i < sizeof(NODE_NAME) && ancestor->name[i] != ' '; i++) @@ -546,7 +602,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { part = string; string = temp; } - if (hyphens) { + if (hyphens) + { temp = part; part = string; string = temp; @@ -555,14 +612,16 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { strcat(string, ".-"); strcat(string, part); } - if (strlen(string) && string[0] == ':') { + if (strlen(string) && string[0] == ':') + { temp = part; part = string; string = temp; strcpy(string, &part[1]); } path_string = getPath(dblist, node, 1); - if (strlen(path_string) <= strlen(string)) { + if (strlen(path_string) <= strlen(string)) + { temp = path_string; path_string = string; string = temp; @@ -570,24 +629,29 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { free(path_string); free(part); } - } else + } + else string = strdup(NODE_NOT_FOUND_PATH); break; - case NciPARENT_TREE: { + case NciPARENT_TREE: + { break_on_no_node; set_retlen(sizeof(NID)); for (node = parent_of(dblist, node); node && node->usage != TreeUSAGE_SUBTREE; node = parent_of(dblist, node)) ; - if (node) { + if (node) + { node_to_nid(dblist, node, (&out_nid)); *(NID *)itm->pointer = out_nid; - } else + } + else *(int *)itm->pointer = 0; break; } - case NciDTYPE_STR: { + case NciDTYPE_STR: + { char *lstr; break_on_no_node; read_nci; @@ -596,7 +660,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { break; } - case NciCLASS_STR: { + case NciCLASS_STR: + { char *lstr; break_on_no_node; read_nci; @@ -605,7 +670,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { break; } - case NciUSAGE_STR: { + case NciUSAGE_STR: + { char *lstr; break_on_no_node; lstr = MdsUsageString(node->usage); @@ -616,12 +682,16 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { default: status = TreeILLEGAL_ITEM; } - if (string) { - if (itm->buffer_length && itm->pointer) { + if (string) + { + if (itm->buffer_length && itm->pointer) + { retlen = minInt(strlen(string), itm->buffer_length); memcpy(itm->pointer, string, retlen); free(string); - } else { + } + else + { retlen = (int)strlen(string); // trunc to actual length to reduce memory leak if caller forgot to free itm->pointer = (unsigned char *)realloc(string, strlen(string) + 1); @@ -633,7 +703,8 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) { return status; } -static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { +static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) +{ char *string = malloc(0x1000); char *part = malloc(0x1000); char *temp; @@ -642,7 +713,8 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { int tagged; string[0] = '\0'; part[0] = '\0'; - if (remove_tree_refs) { + if (remove_tree_refs) + { NODE *default_node = dblist->default_node; for (default_node_info = dblist->tree_info; default_node_info; default_node_info = default_node_info->next_info) @@ -652,7 +724,8 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { break; } for (tagged = 0; parent_of(dblist, node) && !tagged; - node = parent_of(dblist, node)) { + node = parent_of(dblist, node)) + { char *tag; void *ctx = NULL; NID nid; @@ -661,10 +734,12 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { for (info = dblist->tree_info, i = 0; info && i < nid.tree; i++, info = info->next_info) ; - if ((tag = _TreeFindNodeTags((void *)dblist, *(int *)&nid, &ctx)) != NULL) { + if ((tag = _TreeFindNodeTags((void *)dblist, *(int *)&nid, &ctx)) != NULL) + { string[0] = '\\'; string[1] = '\0'; - if (default_node_info != info) { + if (default_node_info != info) + { strcat(string, info->treenam); strcat(string, "::"); } @@ -672,17 +747,22 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { strcat(string, part); free(tag); tagged = 1; - } else if (node == info->root) { + } + else if (node == info->root) + { string[0] = '\\'; string[1] = '\0'; - if (default_node_info != info) { + if (default_node_info != info) + { strcat(string, info->treenam); strcat(string, "::"); } strcat(string, "TOP"); strcat(string, part); tagged = 1; - } else { + } + else + { unsigned int i; temp = part; part = string; @@ -695,10 +775,12 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { strcat(part, string); } } - if (!strlen(string) || !tagged) { + if (!strlen(string) || !tagged) + { string[0] = '\\'; string[1] = '\0'; - if (default_node_info != info) { + if (default_node_info != info) + { strcat(string, info->treenam); strcat(string, "::"); } @@ -712,7 +794,8 @@ static char *getPath(PINO_DATABASE *dblist, NODE *node, int remove_tree_refs) { return NULL; } -int TreeIsChild(PINO_DATABASE *dblist, NODE *node) { +int TreeIsChild(PINO_DATABASE *dblist, NODE *node) +{ NODE *n = 0; if (parent_of(dblist, node)) for (n = child_of(dblist, parent_of(dblist, node)); n && n != node; @@ -721,7 +804,8 @@ int TreeIsChild(PINO_DATABASE *dblist, NODE *node) { return n == node; } -char *_TreeGetPath(void *dbid, int nid_in) { +char *_TreeGetPath(void *dbid, int nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NCI_ITM itm_lst[] = {{0, NciPATH, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; if (!(IS_OPEN(dblist))) @@ -730,7 +814,8 @@ char *_TreeGetPath(void *dbid, int nid_in) { return (char *)itm_lst[0].pointer; } char *TreeGetPath(int nid_in) { return _TreeGetPath(*TreeCtx(), nid_in); } -int _TreeGetPathDsc(void *dbid, int nid_in, mdsdsc_xd_t *out_ptr) { +int _TreeGetPathDsc(void *dbid, int nid_in, mdsdsc_xd_t *out_ptr) +{ char *ans_c = _TreeGetPath(dbid, nid_in); if (!ans_c) return TreeFAILURE; @@ -739,32 +824,38 @@ int _TreeGetPathDsc(void *dbid, int nid_in, mdsdsc_xd_t *out_ptr) { free(ans_c); return TreeSUCCESS; } -int TreeGetPathDsc(int nid_in, mdsdsc_xd_t *out_ptr) { +int TreeGetPathDsc(int nid_in, mdsdsc_xd_t *out_ptr) +{ return _TreeGetPathDsc(*TreeCtx(), nid_in, out_ptr); } -char *_TreeGetMinimumPath(void *dbid, int *def_nid_in, int nid_in) { +char *_TreeGetMinimumPath(void *dbid, int *def_nid_in, int nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *def_nid = (NID *)def_nid_in; int status; NCI_ITM itm_lst[] = {{0, NciMINPATH, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; if (!(IS_OPEN(dblist))) return NULL; - if (def_nid) { + if (def_nid) + { int old_def; _TreeGetDefaultNid(dbid, &old_def); _TreeSetDefaultNid(dbid, *def_nid_in); status = _TreeGetNci(dbid, nid_in, itm_lst); _TreeSetDefaultNid(dbid, old_def); - } else + } + else status = _TreeGetNci(dbid, nid_in, itm_lst); return STATUS_OK ? (char *)itm_lst[0].pointer : NULL; } -char *TreeGetMinimumPath(int *def_nid_in, int nid_in) { +char *TreeGetMinimumPath(int *def_nid_in, int nid_in) +{ return _TreeGetMinimumPath(*TreeCtx(), def_nid_in, nid_in); } int _TreeGetMinimumPathDsc(void *dbid, int *def_nid_in, int nid_in, - mdsdsc_xd_t *out_ptr) { + mdsdsc_xd_t *out_ptr) +{ char *ans_c = _TreeGetMinimumPath(dbid, def_nid_in, nid_in); if (!ans_c) return TreeFAILURE; @@ -773,11 +864,13 @@ int _TreeGetMinimumPathDsc(void *dbid, int *def_nid_in, int nid_in, free(ans_c); return TreeSUCCESS; } -int TreeGetMinimumPathDsc(int *def_nid_in, int nid_in, mdsdsc_xd_t *out_ptr) { +int TreeGetMinimumPathDsc(int *def_nid_in, int nid_in, mdsdsc_xd_t *out_ptr) +{ return _TreeGetMinimumPathDsc(*TreeCtx(), def_nid_in, nid_in, out_ptr); } -int _TreeIsOn(void *dbid, int nid) { +int _TreeIsOn(void *dbid, int nid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int nci_flags; int retlen; @@ -788,24 +881,25 @@ int _TreeIsOn(void *dbid, int nid) { nci_list[0].pointer = (unsigned char *)&nci_flags; nci_list[0].return_length_address = &retlen; status = _TreeGetNci(dbid, nid, nci_list); - if - STATUS_OK { - if (nci_flags & NciM_STATE) - if (nci_flags & NciM_PARENT_STATE) - status = TreeBOTH_OFF; - else - status = TreeOFF; - else if (nci_flags & NciM_PARENT_STATE) - status = TreePARENT_OFF; + if (STATUS_OK) + { + if (nci_flags & NciM_STATE) + if (nci_flags & NciM_PARENT_STATE) + status = TreeBOTH_OFF; else - status = TreeON; - } + status = TreeOFF; + else if (nci_flags & NciM_PARENT_STATE) + status = TreePARENT_OFF; + else + status = TreeON; + } return status; } int TreeIsOn(int nid) { return _TreeIsOn(*TreeCtx(), nid); } int tree_get_nci(TREE_INFO *info, int node_num, NCI *nci, unsigned int version, - int *locked) { + int *locked) +{ int status = TreeSUCCESS; /****************************************** If the tree is not open for edit then @@ -814,53 +908,63 @@ int tree_get_nci(TREE_INFO *info, int node_num, NCI *nci, unsigned int version, if OK so far then fill in the gab and read the record ******************************************/ - if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) { + if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) + { int deleted = TRUE; char nci_bytes[42]; unsigned int n_version = 0; int64_t viewDate; RETURN_IF_NOT_OK(TreeOpenNciR(info)); - while - STATUS_OK { - RETURN_IF_NOT_OK(tree_lock_nci(info, 1, node_num, &deleted, locked)); - if (!deleted) - break; - status = TreeReopenNci(info); - } - if - STATUS_OK { - MDS_IO_LSEEK(info->nci_file->get, node_num * sizeof(nci_bytes), - SEEK_SET); - if (MDS_IO_READ(info->nci_file->get, nci_bytes, sizeof(nci_bytes)) == - sizeof(nci_bytes)) { - TreeSerializeNciIn(nci_bytes, nci); - status = TreeSUCCESS; - TreeGetViewDate(&viewDate); - if (viewDate > 0) { - while (STATUS_OK && nci->time_inserted > viewDate) { - if (nci->flags & NciM_VERSIONS) - status = TreeGetVersionNci(info, nci, nci); - else - status = 0; - } - if - STATUS_NOT_OK { - memset(nci, 0, sizeof(NCI)); - status = TreeSUCCESS; - } - } - while (STATUS_OK && version > n_version) { - if (nci->flags & NciM_VERSIONS) { + while (STATUS_OK) + { + RETURN_IF_NOT_OK(tree_lock_nci(info, 1, node_num, &deleted, locked)); + if (!deleted) + break; + status = TreeReopenNci(info); + } + if (STATUS_OK) + { + MDS_IO_LSEEK(info->nci_file->get, node_num * sizeof(nci_bytes), + SEEK_SET); + if (MDS_IO_READ(info->nci_file->get, nci_bytes, sizeof(nci_bytes)) == + sizeof(nci_bytes)) + { + TreeSerializeNciIn(nci_bytes, nci); + status = TreeSUCCESS; + TreeGetViewDate(&viewDate); + if (viewDate > 0) + { + while (STATUS_OK && nci->time_inserted > viewDate) + { + if (nci->flags & NciM_VERSIONS) status = TreeGetVersionNci(info, nci, nci); - n_version++; - } else - status = TreeNOVERSION; + else + status = 0; } - } else - status = TreeNCIREAD; + if (STATUS_NOT_OK) + { + memset(nci, 0, sizeof(NCI)); + status = TreeSUCCESS; + } + } + while (STATUS_OK && version > n_version) + { + if (nci->flags & NciM_VERSIONS) + { + status = TreeGetVersionNci(info, nci, nci); + n_version++; + } + else + status = TreeNOVERSION; + } } + else + status = TreeNCIREAD; + } tree_unlock_nci(info, 1, node_num, locked); - } else { + } + else + { /******************************************** Otherwise the tree is open for edit so the attributes are just a memory reference @@ -875,7 +979,8 @@ int tree_get_nci(TREE_INFO *info, int node_num, NCI *nci, unsigned int version, return status; } -int TreeOpenNciR(TREE_INFO *info) { +int TreeOpenNciR(TREE_INFO *info) +{ INIT_STATUS_AS TreeSUCCESS; WRLOCKINFO(info); if (!info->nci_file) @@ -884,34 +989,38 @@ int TreeOpenNciR(TREE_INFO *info) { return status; } static char *tree_to_characteristic( - const char *tree) { // replace .tree with .characteristics or - // .characteristics# if tmpfile + const char *tree) +{ // replace .tree with .characteristics or + // .characteristics# if tmpfile const size_t baselen = strlen(tree) - sizeof("tree") + 1; const size_t namelen = baselen + sizeof("characteristics"); char *const filename = memcpy(malloc(namelen), tree, baselen); memcpy(filename + baselen, "characteristics", namelen - baselen); return filename; } -int _TreeOpenNciR(TREE_INFO *info) { +int _TreeOpenNciR(TREE_INFO *info) +{ /**************************************************** Allocate an nci_file structure (if there is any problem ... Free the mem allocated and return *****************************************************/ INIT_STATUS_AS TreeFAILURE; - if (!info->nci_file) { + if (!info->nci_file) + { info->nci_file = calloc(1, sizeof(NCI_FILE)); - if (info->nci_file) { + if (info->nci_file) + { char *filename = tree_to_characteristic(info->filespec); info->nci_file->get = MDS_IO_OPEN(filename, O_RDONLY | O_BINARY | O_RANDOM, 0); free(filename); status = (info->nci_file->get == -1) ? TreeFOPENR : TreeSUCCESS; - if - STATUS_NOT_OK { - free(info->nci_file); - info->nci_file = NULL; - } + if (STATUS_NOT_OK) + { + free(info->nci_file); + info->nci_file = NULL; + } } } return status; @@ -919,7 +1028,8 @@ int _TreeOpenNciR(TREE_INFO *info) { void TreeFree(void *ptr) { free(ptr); } -int64_t RfaToSeek(unsigned char *rfa) { +int64_t RfaToSeek(unsigned char *rfa) +{ int64_t ans = (((int64_t)rfa[0] << 9) | ((int64_t)rfa[1] << 17) | ((int64_t)rfa[2] << 25) | ((int64_t)rfa[4]) | (((int64_t)rfa[5] & 1) << 8)) - @@ -928,7 +1038,8 @@ int64_t RfaToSeek(unsigned char *rfa) { return ans; } -void SeekToRfa(int64_t seek, unsigned char *rfa) { +void SeekToRfa(int64_t seek, unsigned char *rfa) +{ int64_t tmp = seek + 512; rfa[0] = (unsigned char)((tmp >> 9) & 0xff); rfa[1] = (unsigned char)((tmp >> 17) & 0xff); diff --git a/treeshr/TreeGetRecord.c b/treeshr/TreeGetRecord.c index f95d65659a..8ce447f20d 100644 --- a/treeshr/TreeGetRecord.c +++ b/treeshr/TreeGetRecord.c @@ -47,7 +47,8 @@ extern void **TreeCtx(); #define min(a, b) (((a) < (b)) ? (a) : (b)) int TreeGetRecord(int nid_in, struct descriptor_xd *dsc); -int _TreeGetRecord(void *dbid, int nid_in, struct descriptor_xd *dsc) { +int _TreeGetRecord(void *dbid, int nid_in, struct descriptor_xd *dsc) +{ int status; CTX_PUSH(&dbid); status = TreeGetRecord(nid_in, dsc); @@ -55,7 +56,8 @@ int _TreeGetRecord(void *dbid, int nid_in, struct descriptor_xd *dsc) { return status; } -int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) { +int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) +{ void *dbid = *TreeCtx(); PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nid_in; @@ -72,131 +74,151 @@ int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) { if (dblist->remote) return GetRecordRemote(dblist, nid_in, dsc); nid_to_tree_nidx(dblist, nid, info, nidx); - if (info) { + if (info) + { TreeCallHookFun("TreeNidHook", "GetNci", info->treenam, info->shot, nid, NULL); status = TreeCallHook(GetNci, info, nid_in); if (status && STATUS_NOT_OK) return 0; status = TreeOpenDatafileR(info); - if - STATUS_OK { - int locked = 0; - status = tree_get_nci(info, nidx, &nci, 0, &locked); - if - STATUS_OK { - if (nci.length) { - TreeCallHookFun("TreeNidHook", "GetData", info->treenam, - info->shot, nid, NULL); - status = TreeCallHook(GetData, info, nid_in); - if (status && STATUS_NOT_OK) - return 0; - switch (nci.class) { - case CLASS_APD: - case CLASS_CA: - case CLASS_R: - case CLASS_A: - if (nci.flags2 & NciM_DATA_IN_ATT_BLOCK) { - status = TreeINVDFFCLASS; - break; + if (STATUS_OK) + { + int locked = 0; + status = tree_get_nci(info, nidx, &nci, 0, &locked); + if (STATUS_OK) + { + if (nci.length) + { + TreeCallHookFun("TreeNidHook", "GetData", info->treenam, + info->shot, nid, NULL); + status = TreeCallHook(GetData, info, nid_in); + if (status && STATUS_NOT_OK) + return 0; + switch (nci.class) + { + case CLASS_APD: + case CLASS_CA: + case CLASS_R: + case CLASS_A: + if (nci.flags2 & NciM_DATA_IN_ATT_BLOCK) + { + status = TreeINVDFFCLASS; + break; + } + MDS_ATTR_FALLTHROUGH + case CLASS_S: + case CLASS_XS: + if (STATUS_OK) + { + if (nci.flags2 & NciM_EXTENDED_NCI) + { + EXTENDED_ATTRIBUTES attributes; + status = TreeGetExtendedAttributes( + info, RfaToSeek(nci.DATA_INFO.DATA_LOCATION.rfa), + &attributes); + if (STATUS_OK && + attributes + .facility_offset[STANDARD_RECORD_FACILITY] != + -1) + { + status = tree_get_dsc( + info, nid->tree, + attributes + .facility_offset[STANDARD_RECORD_FACILITY], + attributes + .facility_length[STANDARD_RECORD_FACILITY], + dsc); + } + else if (STATUS_OK && + attributes.facility_offset + [SEGMENTED_RECORD_FACILITY] != -1) + { + status = _TreeGetSegmentedRecord(dbid, nid_in, dsc); } - MDS_ATTR_FALLTHROUGH - case CLASS_S: - case CLASS_XS: - if - STATUS_OK { - if (nci.flags2 & NciM_EXTENDED_NCI) { - EXTENDED_ATTRIBUTES attributes; - status = TreeGetExtendedAttributes( - info, RfaToSeek(nci.DATA_INFO.DATA_LOCATION.rfa), - &attributes); - if (STATUS_OK && - attributes - .facility_offset[STANDARD_RECORD_FACILITY] != - -1) { - status = tree_get_dsc( - info, nid->tree, - attributes - .facility_offset[STANDARD_RECORD_FACILITY], - attributes - .facility_length[STANDARD_RECORD_FACILITY], - dsc); - } else if (STATUS_OK && - attributes.facility_offset - [SEGMENTED_RECORD_FACILITY] != -1) { - status = _TreeGetSegmentedRecord(dbid, nid_in, dsc); - } else - status = TreeBADRECORD; - } else { - if (nci.flags2 & NciM_DATA_IN_ATT_BLOCK) { - dtype_t dsc_dtype = DTYPE_DSC; - length_t dlen = nci.length - 8; - l_length_t ddlen = dlen + sizeof(struct descriptor); - status = MdsGet1Dx(&ddlen, &dsc_dtype, dsc, 0); - dptr = dsc->pointer; - dptr->length = dlen; - dptr->dtype = nci.dtype; - dptr->class = CLASS_S; - dptr->pointer = - (char *)dptr + sizeof(struct descriptor); - memcpy(dptr->pointer, nci.DATA_INFO.DATA_IN_RECORD.data, - dptr->length); - if (dptr->dtype != DTYPE_T) { - switch (dptr->length) { - case 2: - *(int16_t *)dptr->pointer = - swapint16(dptr->pointer); - break; - case 4: - *(int32_t *)dptr->pointer = - swapint32(dptr->pointer); - break; - case 8: - *(int64_t *)dptr->pointer = - swapint64(dptr->pointer); - break; - } - } - } else { - int length = nci.DATA_INFO.DATA_LOCATION.record_length; - if (length > 0) { - char *data = malloc(length); - status = TreeGetDatafile( - info, nci.DATA_INFO.DATA_LOCATION.rfa, &length, - data, &retsize, &nodenum, nci.flags2); - if - STATUS_NOT_OK - status = TreeBADRECORD; - else if (!(nci.flags2 & NciM_NON_VMS) && - ((retsize != length) || (nodenum != nidx))) - status = TreeBADRECORD; - else status = (MdsSerializeDscIn(data, dsc) & 1) - ? TreeSUCCESS - : TreeBADRECORD; - free(data); - } else - status = TreeBADRECORD; - } + else + status = TreeBADRECORD; + } + else + { + if (nci.flags2 & NciM_DATA_IN_ATT_BLOCK) + { + dtype_t dsc_dtype = DTYPE_DSC; + length_t dlen = nci.length - 8; + l_length_t ddlen = dlen + sizeof(struct descriptor); + status = MdsGet1Dx(&ddlen, &dsc_dtype, dsc, 0); + dptr = dsc->pointer; + dptr->length = dlen; + dptr->dtype = nci.dtype; + dptr->class = CLASS_S; + dptr->pointer = + (char *)dptr + sizeof(struct descriptor); + memcpy(dptr->pointer, nci.DATA_INFO.DATA_IN_RECORD.data, + dptr->length); + if (dptr->dtype != DTYPE_T) + { + switch (dptr->length) + { + case 2: + *(int16_t *)dptr->pointer = + swapint16(dptr->pointer); + break; + case 4: + *(int32_t *)dptr->pointer = + swapint32(dptr->pointer); + break; + case 8: + *(int64_t *)dptr->pointer = + swapint64(dptr->pointer); + break; } } - break; - default: - status = TreeINVDFFCLASS; - break; + } + else + { + int length = nci.DATA_INFO.DATA_LOCATION.record_length; + if (length > 0) + { + char *data = malloc(length); + status = TreeGetDatafile( + info, nci.DATA_INFO.DATA_LOCATION.rfa, &length, + data, &retsize, &nodenum, nci.flags2); + if (STATUS_NOT_OK) + status = TreeBADRECORD; + else if (!(nci.flags2 & NciM_NON_VMS) && + ((retsize != length) || (nodenum != nidx))) + status = TreeBADRECORD; + else + status = (MdsSerializeDscIn(data, dsc) & 1) + ? TreeSUCCESS + : TreeBADRECORD; + free(data); + } + else + status = TreeBADRECORD; + } } - } else - status = TreeNODATA; + } + break; + default: + status = TreeINVDFFCLASS; + break; } + } + else + status = TreeNODATA; } - } else + } + } + else status = TreeINVTREE; - if - STATUS_OK - status = TreeMakeNidsLocal((struct descriptor *)dsc, nid_in); + if (STATUS_OK) + status = TreeMakeNidsLocal((struct descriptor *)dsc, nid_in); return status; } -int TreeOpenDatafileR(TREE_INFO *info) { +int TreeOpenDatafileR(TREE_INFO *info) +{ int status = 1; WRLOCKINFO(info); if (!info->data_file) @@ -205,19 +227,23 @@ int TreeOpenDatafileR(TREE_INFO *info) { return status; } static inline char * -tree_to_datafile(const char *tree) { // replace .tree with .characteristics +tree_to_datafile(const char *tree) +{ // replace .tree with .characteristics const size_t baselen = strlen(tree) - sizeof("tree") + 1; const size_t namelen0 = baselen + sizeof("datafile"); char *const filename = memcpy(malloc(namelen0), tree, baselen); memcpy(filename + baselen, "datafile", namelen0 - baselen); return filename; } -int _TreeOpenDatafileR(TREE_INFO *info) { +int _TreeOpenDatafileR(TREE_INFO *info) +{ INIT_STATUS_AS TreeFAILURE; if (!info->data_file) info->data_file = TreeGetVmDatafile(info); - if (info->data_file) { - if (!info->data_file->get) { + if (info->data_file) + { + if (!info->data_file->get) + { char *filename = tree_to_datafile(info->filespec); const int lun = MDS_IO_OPEN(filename, O_RDONLY, 0); free(filename); @@ -231,13 +257,15 @@ int _TreeOpenDatafileR(TREE_INFO *info) { typedef RECORD(1) record_one; typedef ARRAY(struct descriptor *) array_dsc; -int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) { +int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) +{ int status = 1; unsigned char tree = ((NID *)&nid)->tree; if (dsc_ptr == NULL) status = 1; else - switch (dsc_ptr->class) { + switch (dsc_ptr->class) + { case CLASS_D: case CLASS_S: @@ -247,11 +275,13 @@ int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) { status = 1; else if (dsc_ptr->dtype == DTYPE_DSC) status = TreeMakeNidsLocal((struct descriptor *)dsc_ptr->pointer, nid); - else if (dsc_ptr->dtype == DTYPE_NID) { + else if (dsc_ptr->dtype == DTYPE_NID) + { NID *nid_ptr = (NID *)dsc_ptr->pointer; if ((nid_ptr->node == 0) && (nid_ptr->tree == 0)) status = 1; - else { + else + { nid_ptr->node = *(int *)nid_ptr & 0xffffff; nid_ptr->tree = tree; } @@ -265,25 +295,29 @@ int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) { status = TreeUNSUPARRDTYPE; break; - case CLASS_R: { + case CLASS_R: + { record_one *rptr = (record_one *)dsc_ptr; int i; for (i = 0, status = 1; STATUS_OK && (i < rptr->ndesc); i++) status = TreeMakeNidsLocal(rptr->dscptrs[i], nid); - } break; + } + break; case CLASS_CA: status = 1; break; - case CLASS_APD: { + case CLASS_APD: + { array_dsc *aptr = (array_dsc *)dsc_ptr; int n_elts = aptr->arsize / aptr->length; int i; for (status = 1, i = 0; STATUS_OK && (i < n_elts); i++) status = TreeMakeNidsLocal((struct descriptor *)*(aptr->pointer + i), nid); - } break; + } + break; default: status = LibINVSTRDES; @@ -292,7 +326,8 @@ int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) { return status; } -DATA_FILE *TreeGetVmDatafile() { +DATA_FILE *TreeGetVmDatafile() +{ DATA_FILE *datafile_ptr; static const struct descriptor_xd empty_xd = {0, 0, CLASS_XD, 0, 0}; int length = align(sizeof(DATA_FILE), sizeof(void *)) + @@ -301,7 +336,8 @@ DATA_FILE *TreeGetVmDatafile() { align(sizeof(NCI), sizeof(void *)) + align(sizeof(struct descriptor_xd), sizeof(void *)); datafile_ptr = malloc(length * 2); - if (datafile_ptr != NULL) { + if (datafile_ptr != NULL) + { char *ptr = (char *)datafile_ptr; memset(datafile_ptr, 0, length); datafile_ptr->record_header = @@ -319,7 +355,8 @@ DATA_FILE *TreeGetVmDatafile() { EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, int *buffer_size, char *record, int *retsize, - int *nodenum, unsigned char flags) { + int *nodenum, unsigned char flags) +{ int status = 1; int buffer_space = *buffer_size; int first = 1; @@ -327,13 +364,16 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, char *bptr = (char *)record; *retsize = 0; memcpy(rfa, rfa_in, sizeof(rfa)); - if (!(flags & NciM_DATA_CONTIGUOUS)) { + if (!(flags & NciM_DATA_CONTIGUOUS)) + { while ((rfa[0] || rfa[1] || rfa[2] || rfa[3] || rfa[4] || rfa[5]) && - buffer_space && STATUS_OK) { + buffer_space && STATUS_OK) + { RECORD_HEADER hdr; int64_t rfa_l = RfaToSeek(rfa); int deleted = 1; - while (STATUS_OK && deleted) { + while (STATUS_OK && deleted) + { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)&hdr, 12, &deleted) == 12) ? TreeSUCCESS @@ -341,41 +381,47 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, if (STATUS_OK && deleted) status = TreeReopenDatafile(info); } - if - STATUS_OK { - unsigned int partlen = - min(swapint16(&hdr.rlength) - 10, buffer_space); - int nidx = swapint32(&hdr.node_number); - if (first) - *nodenum = nidx; - else if (*nodenum != nidx) { - status = 0; - break; - } - deleted = 1; - while (STATUS_OK && deleted) { - status = ((unsigned int)MDS_IO_READ_X(info->data_file->get, - rfa_l + 12, (void *)bptr, - partlen, &deleted) == partlen) - ? TreeSUCCESS - : TreeDFREAD; - if (STATUS_OK && deleted) - status = TreeReopenDatafile(info); - } - if - STATUS_OK { - bptr += partlen; - buffer_space -= partlen; - *retsize = *retsize + partlen; - memcpy(rfa, &hdr.rfa, sizeof(rfa)); - } + if (STATUS_OK) + { + unsigned int partlen = + min(swapint16(&hdr.rlength) - 10, buffer_space); + int nidx = swapint32(&hdr.node_number); + if (first) + *nodenum = nidx; + else if (*nodenum != nidx) + { + status = 0; + break; + } + deleted = 1; + while (STATUS_OK && deleted) + { + status = ((unsigned int)MDS_IO_READ_X(info->data_file->get, + rfa_l + 12, (void *)bptr, + partlen, &deleted) == partlen) + ? TreeSUCCESS + : TreeDFREAD; + if (STATUS_OK && deleted) + status = TreeReopenDatafile(info); + } + if (STATUS_OK) + { + bptr += partlen; + buffer_space -= partlen; + *retsize = *retsize + partlen; + memcpy(rfa, &hdr.rfa, sizeof(rfa)); } + } } - } else { - if (flags & NciM_NON_VMS) { + } + else + { + if (flags & NciM_NON_VMS) + { int64_t rfa_l = RfaToSeek(rfa); int deleted = 1; - while (STATUS_OK && deleted) { + while (STATUS_OK && deleted) + { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)record, *buffer_size, &deleted) == *buffer_size) ? TreeSUCCESS @@ -384,7 +430,9 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, status = TreeReopenDatafile(info); } *retsize = *buffer_size; - } else { + } + else + { int blen = *buffer_size + (*buffer_size + DATAF_C_MAX_RECORD_SIZE + 1) / (DATAF_C_MAX_RECORD_SIZE + 2) * sizeof(RECORD_HEADER); @@ -399,7 +447,8 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, blen - (partlen ? partlen : (DATAF_C_MAX_RECORD_SIZE + 2 + sizeof(RECORD_HEADER))); - while (STATUS_OK && deleted) { + while (STATUS_OK && deleted) + { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)buffer, blen, &deleted) == blen) ? TreeSUCCESS @@ -410,7 +459,8 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, loadint32(nodenum, &((RECORD_HEADER *)buffer)->node_number); for (bptr_in = buffer, bptr = record + *buffer_size, bytes_remaining = *buffer_size; - bytes_remaining;) { + bytes_remaining;) + { int bytes_this_time = min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_remaining); bptr_in += sizeof(RECORD_HEADER); memcpy(bptr - bytes_this_time, bptr_in, bytes_this_time); @@ -426,11 +476,13 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, } static pthread_mutex_t viewdate_lock = PTHREAD_MUTEX_INITIALIZER; -int TreeSetViewDate(int64_t *date) { +int TreeSetViewDate(int64_t *date) +{ TREETHREADSTATIC_INIT; if (TREE_PRIVATECTX) TREE_VIEWDATE = *date; - else { + else + { pthread_mutex_lock(&viewdate_lock); ViewDate = *date; pthread_mutex_unlock(&viewdate_lock); @@ -438,11 +490,13 @@ int TreeSetViewDate(int64_t *date) { return TreeSUCCESS; } -int TreeGetViewDate(int64_t *date) { +int TreeGetViewDate(int64_t *date) +{ TREETHREADSTATIC_INIT; if (TREE_PRIVATECTX) *date = TREE_VIEWDATE; - else { + else + { pthread_mutex_lock(&viewdate_lock); *date = ViewDate; pthread_mutex_unlock(&viewdate_lock); @@ -450,29 +504,33 @@ int TreeGetViewDate(int64_t *date) { return TreeSUCCESS; } -int TreeGetVersionNci(TREE_INFO *info, NCI *nci, NCI *v_nci) { +int TreeGetVersionNci(TREE_INFO *info, NCI *nci, NCI *v_nci) +{ char nci_bytes[42]; int status = TreeOpenDatafileR(info); - if - STATUS_OK { - int deleted = 1; - int64_t rfa_l = RfaToSeek(nci->DATA_INFO.DATA_LOCATION.rfa); - rfa_l += ((nci->DATA_INFO.DATA_LOCATION.record_length == - (DATAF_C_MAX_RECORD_SIZE + 2)) - ? (DATAF_C_MAX_RECORD_SIZE + 2) - : (nci->DATA_INFO.DATA_LOCATION.record_length % - (DATAF_C_MAX_RECORD_SIZE + 2))); - rfa_l += sizeof(RECORD_HEADER); - while (STATUS_OK && deleted) { - status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)nci_bytes, - 42, &deleted) == 42) - ? TreeSUCCESS - : TreeDFREAD; - if (STATUS_OK && deleted) - status = TreeReopenDatafile(info); - } - if - STATUS_OK { TreeSerializeNciIn(nci_bytes, v_nci); } + if (STATUS_OK) + { + int deleted = 1; + int64_t rfa_l = RfaToSeek(nci->DATA_INFO.DATA_LOCATION.rfa); + rfa_l += ((nci->DATA_INFO.DATA_LOCATION.record_length == + (DATAF_C_MAX_RECORD_SIZE + 2)) + ? (DATAF_C_MAX_RECORD_SIZE + 2) + : (nci->DATA_INFO.DATA_LOCATION.record_length % + (DATAF_C_MAX_RECORD_SIZE + 2))); + rfa_l += sizeof(RECORD_HEADER); + while (STATUS_OK && deleted) + { + status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)nci_bytes, + 42, &deleted) == 42) + ? TreeSUCCESS + : TreeDFREAD; + if (STATUS_OK && deleted) + status = TreeReopenDatafile(info); } + if (STATUS_OK) + { + TreeSerializeNciIn(nci_bytes, v_nci); + } + } return status; } diff --git a/treeshr/TreeGetSetShotId.c b/treeshr/TreeGetSetShotId.c index 5ce0adc193..a0c3c0d6ec 100644 --- a/treeshr/TreeGetSetShotId.c +++ b/treeshr/TreeGetSetShotId.c @@ -65,22 +65,26 @@ extern char *MaskReplace(); extern char *TreePath(); -static char *GetFileName(char *experiment, char **ctx) { +static char *GetFileName(char *experiment, char **ctx) +{ char *ans = 0; static char pathname[1024]; static char *path; char *semi = 0; char *part; - if (*ctx == NULL) { + if (*ctx == NULL) + { if (path != NULL) free(path); path = TreePath(experiment, NULL); part = path; - } else if (*ctx == pathname) + } + else if (*ctx == pathname) return NULL; else part = *ctx; - if (part != NULL) { + if (part != NULL) + { char *delim = TREE_PATH_DELIM; char *tmp; if ((semi = strchr(part, ';')) != 0) @@ -93,13 +97,16 @@ static char *GetFileName(char *experiment, char **ctx) { tmp = MaskReplace(pathname, experiment, 0); strcpy(pathname, tmp); free(tmp); - if (pathname[strlen(pathname) - 1] == '+') { + if (pathname[strlen(pathname) - 1] == '+') + { size_t i; for (i = strlen(pathname); (i > 0) && (pathname[i - 1] != delim[0]); i--) ; if (i > 0) pathname[i] = 0; - } else { + } + else + { if (pathname[strlen(pathname) - 1] != delim[0]) strcat(pathname, TREE_PATH_DELIM); } @@ -109,7 +116,8 @@ static char *GetFileName(char *experiment, char **ctx) { return ans; } -static int CreateShotIdFile(char *experiment) { +static int CreateShotIdFile(char *experiment) +{ int fd = -1; char *ctx = 0; char *filename; @@ -118,7 +126,8 @@ static int CreateShotIdFile(char *experiment) { return fd; } -static int OpenShotIdFile(char *experiment, int mode) { +static int OpenShotIdFile(char *experiment, int mode) +{ int fd = -1; char *ctx = 0; char *filename; @@ -133,23 +142,29 @@ static int OpenShotIdFile(char *experiment, int mode) { return fd; } -int TreeGetCurrentShotId(char const *experiment) { +int TreeGetCurrentShotId(char const *experiment) +{ int shot = 0; int status = TreeFAILURE; char exp[16] = {0}; char *path = TreePath(experiment, exp); size_t slen; if (path && ((slen = strlen(path)) > 2) && (path[slen - 1] == ':') && - (path[slen - 2] == ':')) { + (path[slen - 2] == ':')) + { path[slen - 2] = 0; status = TreeGetCurrentShotIdRemote(exp, path, &shot); - } else { + } + else + { int fd = OpenShotIdFile(exp, O_RDONLY); - if (fd != -1) { + if (fd != -1) + { status = MDS_IO_READ(fd, &shot, sizeof(shot)) == sizeof(shot); MDS_IO_CLOSE(fd); #ifdef WORDS_BIGENDIAN - if (status & 1) { + if (status & 1) + { int lshot = shot; int i; char *optr = (char *)&shot; @@ -165,18 +180,23 @@ int TreeGetCurrentShotId(char const *experiment) { return STATUS_OK ? shot : 0; } -int TreeSetCurrentShotId(char const *experiment, int shot) { +int TreeSetCurrentShotId(char const *experiment, int shot) +{ int status = TreeFAILURE; char exp[16] = {0}; char *path = TreePath(experiment, exp); size_t slen; if (path && ((slen = strlen(path)) > 2) && (path[slen - 1] == ':') && - (path[slen - 2] == ':')) { + (path[slen - 2] == ':')) + { path[slen - 2] = 0; status = TreeSetCurrentShotIdRemote(exp, path, shot); - } else { + } + else + { int fd = OpenShotIdFile(exp, O_WRONLY); - if (fd != -1) { + if (fd != -1) + { int lshot = shot; #ifdef WORDS_BIGENDIAN int i; diff --git a/treeshr/TreeOpen.c b/treeshr/TreeOpen.c index b59fad981e..4c57bcd5f4 100644 --- a/treeshr/TreeOpen.c +++ b/treeshr/TreeOpen.c @@ -43,7 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef _WIN32 #include #include -inline static char *strndup(const char *src, size_t n) { +inline static char *strndup(const char *src, size_t n) +{ size_t len = strnlen(src, n); char *dst = memcpy(malloc(len + 1), src, len); dst[len] = '\0'; @@ -70,8 +71,8 @@ inline static char *strndup(const char *src, size_t n) { #ifdef DEBUG #define DBG(...) fprintf(stderr, __VA_ARGS__) #else -#define DBG(...) \ - { /**/ \ +#define DBG(...) \ + { /**/ \ } #endif @@ -91,7 +92,8 @@ static void SubtreeNodeConnect(PINO_DATABASE *dblist, NODE *parent, extern void **TreeCtx(); -int TreeClose(char const *tree, int shot) { +int TreeClose(char const *tree, int shot) +{ return _TreeClose(TreeCtx(), tree, shot); } @@ -101,7 +103,8 @@ int TreeGetStackSize() { return _TreeGetStackSize(*TreeCtx()); } int TreeIsOpen() { return _TreeIsOpen(*TreeCtx()); } -int TreeOpen(char const *tree, int shot, int read_only) { +int TreeOpen(char const *tree, int shot, int read_only) +{ return _TreeOpen(TreeCtx(), tree, shot, read_only); } @@ -111,15 +114,18 @@ void TreeRestoreContext(void *ctx) { _TreeRestoreContext(TreeCtx(), ctx); } void *TreeSaveContext() { return _TreeSaveContext(*TreeCtx()); } -int TreeOpenEdit(char const *tree, int shot) { +int TreeOpenEdit(char const *tree, int shot) +{ return _TreeOpenEdit(TreeCtx(), tree, shot); } -int TreeOpenNew(char const *tree, int shot) { +int TreeOpenNew(char const *tree, int shot) +{ return _TreeOpenNew(TreeCtx(), tree, shot); } -EXPORT char *TreePath(char const *tree, char *tree_lower_out) { +EXPORT char *TreePath(char const *tree, char *tree_lower_out) +{ size_t i; char pathname[32]; char *path; @@ -134,12 +140,14 @@ EXPORT char *TreePath(char const *tree, char *tree_lower_out) { path = TranslateLogical(pathname); if (path == NULL) path = TranslateLogical(TREE_DEFAULT_PATH); - if (path) { + if (path) + { // remove trailing spaces for (i = strlen(path); i > 0 && (path[i - 1] == ' ' || path[i - 1] == 9); i--) path[i - 1] = '\0'; - if (!*path) { + if (!*path) + { // ignore empty path free(path); path = NULL; @@ -148,23 +156,27 @@ EXPORT char *TreePath(char const *tree, char *tree_lower_out) { return path; } -static char *ReplaceAliasTrees(char *tree_in) { +static char *ReplaceAliasTrees(char *tree_in) +{ size_t buflen = strlen(tree_in) + 1; char *ans = calloc(1, buflen); char *tree = strtok(tree_in, ","); size_t i; - while (tree) { + while (tree) + { char *treepath = TreePath(tree, 0); if (treepath && (strlen(treepath) > 5) && (strncmp(treepath, "ALIAS", 5) == 0)) tree = &treepath[5]; - if ((buflen - strlen(ans)) < (strlen(tree) + 1)) { + if ((buflen - strlen(ans)) < (strlen(tree) + 1)) + { buflen += (strlen(tree) + 1); ans = realloc(ans, buflen); } if (strlen(ans) == 0) strcpy(ans, tree); - else { + else + { strcat(ans, ","); strcat(ans, tree); } @@ -177,8 +189,10 @@ static char *ReplaceAliasTrees(char *tree_in) { return ans; } -static void free_top_db(PINO_DATABASE **dblist) { - if ((*dblist)->next) { +static void free_top_db(PINO_DATABASE **dblist) +{ + if ((*dblist)->next) + { PINO_DATABASE *db = *dblist; *dblist = (*dblist)->next; db->next = NULL; @@ -187,7 +201,8 @@ static void free_top_db(PINO_DATABASE **dblist) { } EXPORT int _TreeOpen(void **dbid, char const *tree_in, int shot_in, - int read_only_flag) { + int read_only_flag) +{ int status; int shot; char *tree = strdup(tree_in); @@ -196,7 +211,8 @@ EXPORT int _TreeOpen(void **dbid, char const *tree_in, int shot_in, RemoveBlanksAndUpcase(tree, tree_in); tree = ReplaceAliasTrees(tree); - if ((comma_ptr = strchr(tree, ',')) != 0) { + if ((comma_ptr = strchr(tree, ',')) != 0) + { subtree_list = strdup(tree); *comma_ptr = '\0'; } @@ -211,29 +227,37 @@ EXPORT int _TreeOpen(void **dbid, char const *tree_in, int shot_in, status = TreeINVSHOT; else if (shot == 0) status = TreeNOCURRENT; - else { + else + { char *path = TreePath(tree, 0); - if (path) { + if (path) + { PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; int db_slot_status = CreateDbSlot(dblist, tree, shot, 0); - if (db_slot_status == TreeSUCCESS || db_slot_status == TreeALREADY_OPEN) { + if (db_slot_status == TreeSUCCESS || db_slot_status == TreeALREADY_OPEN) + { status = ConnectTree(*dblist, tree, 0, subtree_list); if (status == TreeUNSUPTHICKOP) if (strlen(path) > 2 && path[strlen(path) - 2] == ':' && path[strlen(path) - 1] == ':') status = ConnectTreeRemote(*dblist, tree, subtree_list, path); - if (status == TreeSUCCESS || status == TreeNOTALLSUBS) { + if (status == TreeSUCCESS || status == TreeNOTALLSUBS) + { if (db_slot_status == TreeSUCCESS) (*dblist)->default_node = (*dblist)->tree_info->root; (*dblist)->open = 1; (*dblist)->open_readonly = read_only_flag != 0; - } else + } + else free_top_db(dblist); - } else { + } + else + { status = db_slot_status; } free(path); - } else + } + else status = TreeNOPATH; } free(subtree_list); @@ -241,8 +265,10 @@ EXPORT int _TreeOpen(void **dbid, char const *tree_in, int shot_in, return status; } -static void RemoveBlanksAndUpcase(char *out, char const *in) { - while (*in) { +static void RemoveBlanksAndUpcase(char *out, char const *in) +{ + while (*in) + { char c = *in++; if (!isspace(c)) *out++ = (char)toupper(c); @@ -250,7 +276,8 @@ static void RemoveBlanksAndUpcase(char *out, char const *in) { *out = 0; } -int _TreeClose(void **dbid, char const *tree, int shot) { +int _TreeClose(void **dbid, char const *tree, int shot) +{ PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; int status; PINO_DATABASE *db; @@ -258,8 +285,10 @@ int _TreeClose(void **dbid, char const *tree, int shot) { status = TreeNOT_OPEN; // printf("TREE CLOSE\n"); - if (dblist && *dblist) { - if (tree) { + if (dblist && *dblist) + { + if (tree) + { size_t i; char uptree[sizeof(TREE_NAME) + 1] = {0}; size_t len = strlen(tree); @@ -269,9 +298,12 @@ int _TreeClose(void **dbid, char const *tree, int shot) { if (!shot) shot = TreeGetCurrentShotId(tree); for (prev_db = 0, db = *dblist; db ? db->open : 0; - prev_db = db, db = db->next) { - if ((shot == db->shotid) && (strcmp(db->main_treenam, uptree) == 0)) { - if (prev_db) { + prev_db = db, db = db->next) + { + if ((shot == db->shotid) && (strcmp(db->main_treenam, uptree) == 0)) + { + if (prev_db) + { prev_db->next = db->next; db->next = *dblist; *dblist = db; @@ -280,39 +312,46 @@ int _TreeClose(void **dbid, char const *tree, int shot) { break; } } - } else + } + else status = TreeSUCCESS; - if - STATUS_OK { - if ((*dblist)->modified) { - status = TreeWRITEFIRST; - } else if ((*dblist)->open) { - status = CloseTopTree(*dblist, 1); - if - STATUS_OK + if (STATUS_OK) + { + if ((*dblist)->modified) + { + status = TreeWRITEFIRST; + } + else if ((*dblist)->open) + { + status = CloseTopTree(*dblist, 1); + if (STATUS_OK) free_top_db(dblist); - } else - status = TreeNOT_OPEN; } + else + status = TreeNOT_OPEN; + } } return status; } -static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { +static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) +{ int status = TreeSUCCESS; if (!dblist) return status; - if (dblist->dispatch_table) { + if (dblist->dispatch_table) + { static int (*ServerFreeDispatchTable)() = NULL; status = LibFindImageSymbol_C("MdsServerShr", "ServerFreeDispatchTable", &ServerFreeDispatchTable); - if - STATUS_OK { - status = ServerFreeDispatchTable(dblist->dispatch_table); - dblist->dispatch_table = NULL; - } + if (STATUS_OK) + { + status = ServerFreeDispatchTable(dblist->dispatch_table); + dblist->dispatch_table = NULL; + } } - if (dblist->remote) { + if (dblist->remote) + { status = CloseTreeRemote(dblist, call_hook); if (status == TreeNOT_OPEN) /**** Remote server might have already closed the tree ****/ @@ -320,7 +359,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { return status; } TREE_INFO *previous_info, *local_info = dblist->tree_info; - if (local_info) { + if (local_info) + { /************************************************ We check the BLOCKID just to make sure that what we were passed in indeed was a tree info block. @@ -330,7 +370,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { may not show up immediately. *************************************************/ - if (local_info->blockid == TreeBLOCKID) { + if (local_info->blockid == TreeBLOCKID) + { /****************************************************** If the edit pointer field of this tree is non-zero, @@ -341,7 +382,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { virtual memory allocated, this memory must be freed. *****************************************************/ - if (local_info->edit) { + if (local_info->edit) + { if (local_info->edit->header_pages) free(local_info->header); if (local_info->edit->node_vm_size) @@ -353,7 +395,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { if (local_info->edit->external_pages) free(local_info->external); DELETED_NID *next, *dnid; - for (dnid = local_info->edit->deleted_nid_list; dnid; dnid = next) { + for (dnid = local_info->edit->deleted_nid_list; dnid; dnid = next) + { next = dnid->next; free(dnid); } @@ -370,13 +413,16 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { Finally the tree information block memory can be released. *********************************************************/ - while (local_info) { - if (local_info->blockid == TreeBLOCKID) { + while (local_info) + { + if (local_info->blockid == TreeBLOCKID) + { if (local_info->rundown_id) MDSEventCan(local_info->rundown_id); if (local_info->channel) MDS_IO_CLOSE(local_info->channel); - if (local_info->section_addr[0]) { + if (local_info->section_addr[0]) + { #ifndef _WIN32 if (local_info->mapped) munmap(local_info->section_addr[0], @@ -385,7 +431,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { free(local_info->vm_addr); } TreeWait(local_info); - if (local_info->data_file) { + if (local_info->data_file) + { MdsFree1Dx(local_info->data_file->data, NULL); if (local_info->data_file->get) MDS_IO_CLOSE(local_info->data_file->get); @@ -394,7 +441,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { free(local_info->data_file); local_info->data_file = NULL; } - if (local_info->nci_file) { + if (local_info->nci_file) + { if (local_info->nci_file->get) MDS_IO_CLOSE(local_info->nci_file->get); if (local_info->nci_file->put) @@ -402,7 +450,8 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { free(local_info->nci_file); local_info->nci_file = NULL; } - if (call_hook) { + if (call_hook) + { TreeCallHookFun("TreeHook", "CloseTree", local_info->treenam, local_info->shot, NULL); TreeCallHook(CloseTree, local_info, 0); @@ -417,36 +466,40 @@ static int CloseTopTree(PINO_DATABASE *dblist, int call_hook) { } } dblist->tree_info = NULL; - } else + } + else status = TreeINVTREE; } - if - STATUS_OK { - dblist->open = 0; - dblist->open_for_edit = 0; - dblist->modified = 0; - dblist->remote = 0; - free(dblist->experiment); - dblist->experiment = NULL; - free(dblist->main_treenam); - dblist->main_treenam = NULL; - } + if (STATUS_OK) + { + dblist->open = 0; + dblist->open_for_edit = 0; + dblist->modified = 0; + dblist->remote = 0; + free(dblist->experiment); + dblist->experiment = NULL; + free(dblist->main_treenam); + dblist->main_treenam = NULL; + } return status; } -int _TreeIsOpen(void *dbid) { +int _TreeIsOpen(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; return IS_OPEN_FOR_EDIT(dblist) ? TreeOPEN_EDIT : (IS_OPEN(dblist) ? TreeOPEN : TreeNOT_OPEN); } -int _TreeEditing(void *dbid) { +int _TreeEditing(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; return IS_OPEN_FOR_EDIT(dblist) ? TreeSUCCESS : TreeNOEDIT; } static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, - char *subtree_list) { + char *subtree_list) +{ /*********************************************** If the parent's usage is not subtree then just return success. @@ -458,7 +511,8 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, this tree is not in it then just return success notinlist. ************************************************/ - if (subtree_list) { + if (subtree_list) + { char *found; char *tmp_list = malloc(strlen(subtree_list) + 3); char *tmp_tree = malloc(strlen(tree) + 3); @@ -489,9 +543,11 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, for (info = dblist->tree_info; info && strcmp(tree, info->treenam); info = info->next_info) ; - if (!info) { + if (!info) + { info = calloc(1, sizeof(TREE_INFO)); - if (info) { + if (info) + { /*********************************************** Next we map the file and if successful copy @@ -505,15 +561,16 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, info->shot = dblist->shotid; status = MapTree(info, dblist->tree_info, 0); if (STATUS_NOT_OK && (status == TreeFILE_NOT_FOUND || - treeshr_errno == TreeFILE_NOT_FOUND)) { + treeshr_errno == TreeFILE_NOT_FOUND)) + { TreeCallHookFun("TreeHook", "RetrieveTree", info->treenam, info->shot, NULL); status = TreeCallHook(RetrieveTree, info, 0); - if - STATUS_OK - status = MapTree(info, dblist->tree_info, 0); + if (STATUS_OK) + status = MapTree(info, dblist->tree_info, 0); } - if (status == TreeSUCCESS) { + if (status == TreeSUCCESS) + { TreeCallHookFun("TreeHook", "OpenTree", tree, info->shot, NULL); TreeCallHook(OpenTree, info, 0); @@ -526,10 +583,13 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, **********************************************/ info->root = info->node; - if (parent == 0 || !dblist->tree_info) { + if (parent == 0 || !dblist->tree_info) + { dblist->tree_info = info; dblist->remote = 0; - } else { + } + else + { for (iptr = dblist->tree_info; iptr->next_info; iptr = iptr->next_info) ; @@ -545,15 +605,18 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, the subtree(s). *************************************************/ } - if (STATUS_NOT_OK && info) { + if (STATUS_NOT_OK && info) + { free(info->treenam); free(info); info = 0; } } } - if (info) { - for (i = 0; i < info->header->externals; i++) { + if (info) + { + for (i = 0; i < info->header->externals; i++) + { NODE *external_node = info->node + swapint32(&info->external[i]); char *subtree = strncpy(calloc(1, sizeof(NODE_NAME) + 1), external_node->name, sizeof(NODE_NAME)); @@ -563,27 +626,30 @@ static int ConnectTree(PINO_DATABASE *dblist, char *tree, NODE *parent, *blank = '\0'; ext_status = ConnectTree(dblist, subtree, external_node, subtree_list); free(subtree); - if - IS_NOT_OK(ext_status) { - status = TreeNOTALLSUBS; - if (treeshr_errno == TreeCANCEL) - break; - } + if (IS_NOT_OK(ext_status)) + { + status = TreeNOTALLSUBS; + if (treeshr_errno == TreeCANCEL) + break; + } } } return status; } -#define move_to_top(prev_db, db) \ - if (prev_db) { \ - prev_db->next = db->next; \ - db->next = *dblist; \ - *dblist = db; \ +#define move_to_top(prev_db, db) \ + if (prev_db) \ + { \ + prev_db->next = db->next; \ + db->next = *dblist; \ + *dblist = db; \ } -EXPORT int _TreeNewDbid(void **dblist) { +EXPORT int _TreeNewDbid(void **dblist) +{ PINO_DATABASE *db = (PINO_DATABASE *)calloc(1, sizeof(PINO_DATABASE)); - if (db) { + if (db) + { DBG("Created DB %" PRIxPTR "\n", (uintptr_t)db); db->timecontext.start.dtype = DTYPE_DSC; db->timecontext.start.class = CLASS_XD; @@ -600,7 +666,8 @@ EXPORT int _TreeNewDbid(void **dblist) { } static int CreateDbSlot(PINO_DATABASE **dblist, char *tree, int shot, - int editting) { + int editting) +{ int status; PINO_DATABASE *db; PINO_DATABASE *prev_db; @@ -608,33 +675,54 @@ static int CreateDbSlot(PINO_DATABASE **dblist, char *tree, int shot, PINO_DATABASE *useable_db = 0; int count; int stack_size = DEFAULT_STACK_LIMIT; - enum options { MOVE_TO_TOP, CLOSE, ERROR_DIRTY, OPEN_NEW }; + enum options + { + MOVE_TO_TOP, + CLOSE, + ERROR_DIRTY, + OPEN_NEW + }; enum options option = OPEN_NEW; if (*dblist) stack_size = (*dblist)->stack_size; for (prev_db = 0, db = *dblist; db ? db->open : 0; - prev_db = db, db = db->next) { - if (db->shotid == shot) { - if (strcmp(db->main_treenam, tree) == 0) { - if (editting) { - if (db->open_for_edit) { + prev_db = db, db = db->next) + { + if (db->shotid == shot) + { + if (strcmp(db->main_treenam, tree) == 0) + { + if (editting) + { + if (db->open_for_edit) + { option = MOVE_TO_TOP; break; - } else { + } + else + { option = CLOSE; break; } - } else { - if (db->open_for_edit) { - if (db->modified) { + } + else + { + if (db->open_for_edit) + { + if (db->modified) + { option = ERROR_DIRTY; break; - } else { + } + else + { option = CLOSE; break; } - } else { + } + else + { option = MOVE_TO_TOP; break; } @@ -642,7 +730,8 @@ static int CreateDbSlot(PINO_DATABASE **dblist, char *tree, int shot, } } } - switch (option) { + switch (option) + { case MOVE_TO_TOP: move_to_top(prev_db, db); status = TreeALREADY_OPEN; @@ -659,30 +748,41 @@ static int CreateDbSlot(PINO_DATABASE **dblist, char *tree, int shot, break; default: for (count = 0, prev_db = 0, db = *dblist; db; - count++, prev_db = db, db = db->next) { - if (!db->open) { + count++, prev_db = db, db = db->next) + { + if (!db->open) + { move_to_top(prev_db, db); status = TreeSUCCESS; break; - } else if (!(db->open_for_edit && db->modified)) { + } + else if (!(db->open_for_edit && db->modified)) + { saved_prev_db = prev_db, useable_db = db; } } - if (!db) { - if (count >= stack_size) { - if (useable_db) { + if (!db) + { + if (count >= stack_size) + { + if (useable_db) + { move_to_top(saved_prev_db, useable_db); CloseTopTree(*dblist, 1); status = TreeSUCCESS; - } else { + } + else + { status = TreeMAXOPENEDIT; treeshr_errno = TreeMAXOPENEDIT; } - } else + } + else status = _TreeNewDbid((void **)dblist); } } - if (status == TreeSUCCESS) { + if (status == TreeSUCCESS) + { (*dblist)->shotid = shot; (*dblist)->setup_info = (shot == -1); free((*dblist)->experiment); @@ -694,16 +794,19 @@ static int CreateDbSlot(PINO_DATABASE **dblist, char *tree, int shot, return status; } -int _TreeGetStackSize(void *dbid) { +int _TreeGetStackSize(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; return dblist->stack_size; } -int _TreeSetStackSize(void **dbid, int size) { +int _TreeSetStackSize(void **dbid, int size) +{ PINO_DATABASE *dblist = *(PINO_DATABASE **)dbid; int new_size = size > 0 ? size : 1; int old_size = dblist->stack_size; - for (; dblist; dblist = dblist->next) { + for (; dblist; dblist = dblist->next) + { dblist->stack_size = new_size; if (dblist && dblist->remote) SetStackSizeRemote(dblist, new_size); @@ -722,7 +825,8 @@ static char *GetFname(char *tree, int shot) struct descriptor_d fname = {0, DTYPE_T, CLASS_D, 0}; char expression[128]; struct descriptor expression_d = {0, DTYPE_T, CLASS_S, 0}; - if (ans) { + if (ans) + { free(ans); ans = 0; } @@ -732,31 +836,33 @@ static char *GetFname(char *tree, int shot) static int (*TdiExecute)() = NULL; // LibFindImageSymbol_C is a NOP if TdiExecute is already set status = LibFindImageSymbol_C("TdiShr", "TdiExecute", &TdiExecute); - if - STATUS_OK - status = (*TdiExecute)(&expression_d, &fname MDS_END_ARG); - if - STATUS_OK { - ans = strncpy(malloc((size_t)fname.length + 2), fname.pointer, - fname.length); - ans[fname.length] = '+'; - ans[fname.length + 1] = 0; - } - else { + if (STATUS_OK) + status = (*TdiExecute)(&expression_d, &fname MDS_END_ARG); + if (STATUS_OK) + { + ans = strncpy(malloc((size_t)fname.length + 2), fname.pointer, + fname.length); + ans[fname.length] = '+'; + ans[fname.length + 1] = 0; + } + else + { ans = strdup("ErRoR"); } StrFree1Dx(&fname); return (ans); } -static void str_shift(char *in, int num) { +static void str_shift(char *in, int num) +{ char *p1 = in, *p2 = in + num; while (*p2 != 0) *p1++ = *p2++; *p1 = 0; } -EXPORT char *MaskReplace(char *path_in, char *tree, int shot) { +EXPORT char *MaskReplace(char *path_in, char *tree, int shot) +{ char *path = strdup(path_in); char ShotMask[13]; char *tilde; @@ -767,9 +873,11 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) { sprintf(ShotMask, "%012u", shot); else memset(ShotMask, 'X', 12); - for (tilde = strchr(path, '~'); tilde != 0; tilde = strchr(path, '~')) { + for (tilde = strchr(path, '~'); tilde != 0; tilde = strchr(path, '~')) + { char *tmp, *tmp2; - switch (tilde[1]) { + switch (tilde[1]) + { case 'a': tilde[0] = ShotMask[11]; str_shift(&tilde[1], 1); @@ -814,13 +922,16 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) { fname = GetFname(tree, shot); const size_t fname_len = strlen(fname); if ((strlen(tilde + 2) > 1) || - ((strlen(tilde + 2) == 1) && (tilde[2] != '\\'))) { + ((strlen(tilde + 2) == 1) && (tilde[2] != '\\'))) + { tmp = strcpy(malloc(strlen(tilde + 2) + 1), tilde + 2); tmp2 = strcpy(malloc(strlen(path) + 1 + fname_len), path); strcpy(tmp2 + (tilde - path) + fname_len, tmp); free(tmp); memcpy(tmp2 + (tilde - path), fname, fname_len); - } else { + } + else + { tmp2 = strcpy(malloc(strlen(path) + 1 + fname_len), path); memcpy(tmp2 + (tilde - path), fname, fname_len + 1); } @@ -843,7 +954,8 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) { break; } } - if (replace_tilde) { + if (replace_tilde) + { for (i = 0; i < strlen(path); i++) if (path[i] == (char)1) path[i] = '~'; @@ -852,17 +964,20 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) { } #ifdef HAVE_SYS_RESOURCE_H -static void init_rlimit_once() { +static void init_rlimit_once() +{ struct rlimit rlp; getrlimit(RLIMIT_NOFILE, &rlp); - if (rlp.rlim_cur < rlp.rlim_max) { + if (rlp.rlim_cur < rlp.rlim_max) + { rlp.rlim_cur = rlp.rlim_max; setrlimit(RLIMIT_NOFILE, &rlp); } } #endif int OpenOne(TREE_INFO *info, TREE_INFO *root, tree_type_t type, int new, - int edit_flag, char **filespec, int *fd_out) { + int edit_flag, char **filespec, int *fd_out) +{ /* * search for tree files unless filespec is preset with thick client def, i.e. * ends with "::" @@ -875,38 +990,41 @@ int OpenOne(TREE_INFO *info, TREE_INFO *root, tree_type_t type, int new, fd = -1; if (root && root->filespec && root->speclen > 2 && root->filespec[root->speclen - 1] == ':' && - root->filespec[root->speclen - 2] == ':') { + root->filespec[root->speclen - 2] == ':') + { treepath = strndup(root->filespec, root->speclen); } status = MDS_IO_OPEN_ONE(treepath, info->treenam, info->shot, type, new, edit_flag, filespec, &info->speclen, &fd); FREE_NOW(treepath); - if - STATUS_OK { - if (new &&fd == -1) - status = TreeFCREATE; - else { + if (STATUS_OK) + { + if (new &&fd == -1) + status = TreeFCREATE; + else + { #ifndef _WIN32 - info->mapped = (MDS_IO_ID(fd) == -1); + info->mapped = (MDS_IO_ID(fd) == -1); #ifdef __APPLE__ - /* from python-mmap Issue #11277: fsync(2) is not enough on OS X - a + /* from python-mmap Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug */ - if (info->mapped && fd != -1) - (void)fcntl(fd, F_FULLFSYNC); + if (info->mapped && fd != -1) + (void)fcntl(fd, F_FULLFSYNC); #endif #endif - if (fd == -1) - status = edit_flag ? TreeFOPENW : TreeFOPENR; - } + if (fd == -1) + status = edit_flag ? TreeFOPENW : TreeFOPENR; } + } *fd_out = fd; if (fd >= 0 && type == TREE_TREEFILE_TYPE) info->channel = fd; return status; } -static int MapTree(TREE_INFO *info, TREE_INFO *root, int edit_flag) { +static int MapTree(TREE_INFO *info, TREE_INFO *root, int edit_flag) +{ /****************************************** First we need to open the tree file. If successful, we create and map a global @@ -915,31 +1033,35 @@ static int MapTree(TREE_INFO *info, TREE_INFO *root, int edit_flag) { int status, fd, nomap = 0; status = OpenOne(info, root, TREE_TREEFILE_TYPE, 0, edit_flag, &info->filespec, &fd); - if - STATUS_OK { - info->alq = (int)(MDS_IO_LSEEK(fd, 0, SEEK_END) / 512); - if (info->alq < 1) { - if (info->filespec) - fprintf(stderr, "Corrupted/truncated tree file: %s\n", - info->filespec); - else - fprintf(stderr, - "Corrupted/truncated tree file: \n"); - MDS_IO_CLOSE(fd); - status = TreeFILE_NOT_FOUND; - } else { - MDS_IO_LSEEK(fd, 0, SEEK_SET); - status = TreeSUCCESS; - nomap = !info->mapped; - } + if (STATUS_OK) + { + info->alq = (int)(MDS_IO_LSEEK(fd, 0, SEEK_END) / 512); + if (info->alq < 1) + { + if (info->filespec) + fprintf(stderr, "Corrupted/truncated tree file: %s\n", + info->filespec); + else + fprintf(stderr, + "Corrupted/truncated tree file: \n"); + MDS_IO_CLOSE(fd); + status = TreeFILE_NOT_FOUND; + } + else + { + MDS_IO_LSEEK(fd, 0, SEEK_SET); + status = TreeSUCCESS; + nomap = !info->mapped; } + } if (status == TreeSUCCESS) status = MapFile(fd, info, nomap); return status; } #ifdef WORDS_BIGENDIAN -static void SwapBytesInt(char *in) { +static void SwapBytesInt(char *in) +{ char tmp = in[0]; in[0] = in[3]; in[3] = tmp; @@ -948,7 +1070,8 @@ static void SwapBytesInt(char *in) { in[2] = tmp; } -void FixupHeader(TREE_HEADER *hdr) { +void FixupHeader(TREE_HEADER *hdr) +{ char flags = ((char *)hdr)[1]; hdr->sort_children = (flags & 1) != 0; hdr->sort_members = (flags & 2) != 0; @@ -963,7 +1086,8 @@ void FixupHeader(TREE_HEADER *hdr) { #define FixupHeader(arg) #endif -static int MapFile(int fd, TREE_INFO *info, int nomap) { +static int MapFile(int fd, TREE_INFO *info, int nomap) +{ int status; /******************************************** @@ -972,15 +1096,18 @@ static int MapFile(int fd, TREE_INFO *info, int nomap) { ********************************************/ status = GetVmForTree(info, nomap); - if (status == TreeSUCCESS) { - if (nomap) { + if (status == TreeSUCCESS) + { + if (nomap) + { status = (MDS_IO_READ(fd, (void *)info->section_addr[0], (size_t)info->alq * 512) == (512 * info->alq)) ? TreeSUCCESS : TreeTREEFILEREADERR; } #ifndef _WIN32 - else { + else + { #ifndef MAP_FILE #define MAP_FILE 0 #endif @@ -989,11 +1116,11 @@ static int MapFile(int fd, TREE_INFO *info, int nomap) { MAP_FILE | MAP_PRIVATE, MDS_IO_FD(info->channel), 0); status = info->section_addr[0] != (void *)-1 ? TreeSUCCESS : TreeTREEFILEREADERR; - if - STATUS_NOT_OK { - perror("Error mapping file"); - info->mapped = 0; - } + if (STATUS_NOT_OK) + { + perror("Error mapping file"); + info->mapped = 0; + } } #endif /*********************************************** @@ -1005,49 +1132,53 @@ static int MapFile(int fd, TREE_INFO *info, int nomap) { the tree header. ************************************************/ - if - STATUS_OK { - info->blockid = TreeBLOCKID; - info->header = (TREE_HEADER *)info->section_addr[0]; - FixupHeader(info->header); - info->node = (NODE *)(info->section_addr[0] + - (((int)sizeof(TREE_HEADER) + 511) / 512) * 512); - info->tags = - (int *)(((char *)info->node) + - ((info->header->nodes * (int)sizeof(NODE) + 511) / 512) * - 512); - info->tag_info = - (TAG_INFO *)(((char *)info->tags) + - ((info->header->tags * 4 + 511) / 512) * 512); - info->external = - (int *)(((char *)info->tag_info) + - ((info->header->tags * (int)sizeof(TAG_INFO) + 511) / 512) * - 512); - TreeEstablishRundownEvent(info); - status = TreeSUCCESS; - } + if (STATUS_OK) + { + info->blockid = TreeBLOCKID; + info->header = (TREE_HEADER *)info->section_addr[0]; + FixupHeader(info->header); + info->node = (NODE *)(info->section_addr[0] + + (((int)sizeof(TREE_HEADER) + 511) / 512) * 512); + info->tags = + (int *)(((char *)info->node) + + ((info->header->nodes * (int)sizeof(NODE) + 511) / 512) * + 512); + info->tag_info = + (TAG_INFO *)(((char *)info->tags) + + ((info->header->tags * 4 + 511) / 512) * 512); + info->external = + (int *)(((char *)info->tag_info) + + ((info->header->tags * (int)sizeof(TAG_INFO) + 511) / 512) * + 512); + TreeEstablishRundownEvent(info); + status = TreeSUCCESS; + } else free(info->vm_addr); } return status; } -static int GetVmForTree(TREE_INFO *info, int nomap) { +static int GetVmForTree(TREE_INFO *info, int nomap) +{ int status = TreeSUCCESS; info->vm_pages = info->alq; - if (nomap) { + if (nomap) + { info->vm_addr = calloc(512, (size_t)info->vm_pages); if (info->vm_addr) info->section_addr[0] = info->vm_addr; else status = TreeMEMERR; - } else + } + else info->vm_addr = 0; return status; } static void SubtreeNodeConnect(PINO_DATABASE *dblist, NODE *parent, - NODE *subtreetop) { + NODE *subtreetop) +{ NID child_nid, parent_nid, brother_nid = {0, 0}; NODE *brother = brother_of(dblist, parent); parent->usage = TreeUSAGE_SUBTREE_REF; @@ -1063,7 +1194,8 @@ static void SubtreeNodeConnect(PINO_DATABASE *dblist, NODE *parent, return; } -struct context { +struct context +{ char *expt; int shot; int edit; @@ -1071,10 +1203,12 @@ struct context { int defnid; }; -void *_TreeSaveContext(void *dbid) { +void *_TreeSaveContext(void *dbid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; struct context *ctx = NULL; - if (IS_OPEN(dblist)) { + if (IS_OPEN(dblist)) + { ctx = malloc(sizeof(struct context)); ctx->expt = strcpy(malloc(strlen(dblist->experiment) + 1), dblist->experiment); @@ -1086,8 +1220,10 @@ void *_TreeSaveContext(void *dbid) { return (void *)ctx; } -void _TreeRestoreContext(void **dbid, void *ctxin) { - if (ctxin) { +void _TreeRestoreContext(void **dbid, void *ctxin) +{ + if (ctxin) + { struct context *ctx = (struct context *)ctxin; if (ctx->edit) _TreeOpenEdit(dbid, ctx->expt, ctx->shot); @@ -1099,10 +1235,12 @@ void _TreeRestoreContext(void **dbid, void *ctxin) { } } -int TreeReopenDatafile(struct tree_info *info) { +int TreeReopenDatafile(struct tree_info *info) +{ int status = 1, reopen_get, reopen_put, stv; WRLOCKINFO(info); - if (info->data_file) { + if (info->data_file) + { reopen_get = info->data_file->get > 0; reopen_put = info->data_file->put > 0; if (reopen_get) @@ -1120,10 +1258,12 @@ int TreeReopenDatafile(struct tree_info *info) { return status; } -int TreeReopenNci(struct tree_info *info) { +int TreeReopenNci(struct tree_info *info) +{ int status = 1, reopen_get, reopen_put; WRLOCKINFO(info); - if (info->nci_file) { + if (info->nci_file) + { reopen_get = info->nci_file->get > 0; reopen_put = info->nci_file->put > 0; if (reopen_get) @@ -1141,7 +1281,8 @@ int TreeReopenNci(struct tree_info *info) { return status; } -int _TreeOpenEdit(void **dbid, char const *tree_in, int shot_in) { +int _TreeOpenEdit(void **dbid, char const *tree_in, int shot_in) +{ TREE_INFO *info; size_t const treesize = strlen(tree_in) + 1; char *tree = (char *)alloca(treesize); @@ -1154,64 +1295,70 @@ int _TreeOpenEdit(void **dbid, char const *tree_in, int shot_in) { status = TreeINVSHOT; else if (shot == 0) status = TreeNOCURRENT; - else { + else + { PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; status = CreateDbSlot(dblist, tree, shot, 1); - if (status == TreeSUCCESS) { + if (status == TreeSUCCESS) + { info = (TREE_INFO *)calloc(1, sizeof(TREE_INFO)); - if (info) { + if (info) + { info->flush = ((*dblist)->shotid == -1); info->treenam = strdup(tree); info->shot = (*dblist)->shotid; status = MapTree(info, (*dblist)->tree_info, 1); if (STATUS_NOT_OK && (status == TreeFILE_NOT_FOUND || - treeshr_errno == TreeFILE_NOT_FOUND)) { + treeshr_errno == TreeFILE_NOT_FOUND)) + { TreeCallHookFun("TreeHook", "RetrieveTree", tree, info->shot, NULL); status = MapTree(info, (*dblist)->tree_info, 1); if (STATUS_NOT_OK && (status == TreeFILE_NOT_FOUND || - treeshr_errno == TreeFILE_NOT_FOUND)) { + treeshr_errno == TreeFILE_NOT_FOUND)) + { status = TreeCallHook(RetrieveTree, info, 0); - if - STATUS_OK - status = MapTree(info, (*dblist)->tree_info, 1); + if (STATUS_OK) + status = MapTree(info, (*dblist)->tree_info, 1); } } - if - STATUS_OK { - TreeCallHookFun("TreeHook", "OpenTreeEdit", tree, info->shot, NULL); - TreeCallHook(OpenTreeEdit, info, 0); - info->edit = (TREE_EDIT *)calloc(1, sizeof(TREE_EDIT)); - if (info->edit) { - info->root = info->node; - status = TreeOpenNciW(info, 0); - if - STATUS_OK { - (*dblist)->tree_info = info; - (*dblist)->open = 1; - (*dblist)->open_for_edit = 1; - (*dblist)->open_readonly = 0; - (*dblist)->default_node = info->root; - } - else - free(info->edit); + if (STATUS_OK) + { + TreeCallHookFun("TreeHook", "OpenTreeEdit", tree, info->shot, NULL); + TreeCallHook(OpenTreeEdit, info, 0); + info->edit = (TREE_EDIT *)calloc(1, sizeof(TREE_EDIT)); + if (info->edit) + { + info->root = info->node; + status = TreeOpenNciW(info, 0); + if (STATUS_OK) + { + (*dblist)->tree_info = info; + (*dblist)->open = 1; + (*dblist)->open_for_edit = 1; + (*dblist)->open_readonly = 0; + (*dblist)->default_node = info->root; } + else + free(info->edit); } - if - STATUS_NOT_OK { - free(info->treenam); - free(info); - } - } else + } + if (STATUS_NOT_OK) + { + free(info->treenam); + free(info); + } + } + else status = TreeMEMERR; - if - STATUS_NOT_OK - free_top_db(dblist); + if (STATUS_NOT_OK) + free_top_db(dblist); } } return status; } -int _TreeOpenNew(void **dbid, char const *tree_in, int shot_in) { +int _TreeOpenNew(void **dbid, char const *tree_in, int shot_in) +{ TREE_INFO *info; char *tree = strdup(tree_in); int shot; @@ -1223,24 +1370,29 @@ int _TreeOpenNew(void **dbid, char const *tree_in, int shot_in) { status = TreeINVSHOT; else if (shot == 0) status = TreeNOCURRENT; - else { + else + { PINO_DATABASE **dblist = (PINO_DATABASE **)dbid; status = CreateDbSlot(dblist, tree, shot, 1); - if (status == TreeSUCCESS) { + if (status == TreeSUCCESS) + { info = (TREE_INFO *)calloc(1, sizeof(TREE_INFO)); - if (info) { + if (info) + { int fd; info->flush = ((*dblist)->shotid == -1); info->treenam = strdup(tree); info->shot = (*dblist)->shotid; status = OpenOne(info, (*dblist)->tree_info, TREE_TREEFILE_TYPE, 1, 0, &info->filespec, &fd); - if (fd > -1) { + if (fd > -1) + { MDS_IO_CLOSE(fd); info->channel = -2; status = OpenOne(info, (*dblist)->tree_info, TREE_NCIFILE_TYPE, 1, 0, NULL, &fd); - if (fd > -1) { + if (fd > -1) + { MDS_IO_CLOSE(fd); status = OpenOne(info, (*dblist)->tree_info, TREE_DATAFILE_TYPE, 1, 0, NULL, &fd); @@ -1248,69 +1400,72 @@ int _TreeOpenNew(void **dbid, char const *tree_in, int shot_in) { MDS_IO_CLOSE(fd); } } - if - STATUS_OK { - TreeCallHookFun("TreeHook", "OpenTreeEdit", info->treenam, - info->shot, NULL); - TreeCallHook(OpenTreeEdit, info, 0); - info->edit = (TREE_EDIT *)calloc(1, sizeof(TREE_EDIT)); - if (info->edit) { - info->blockid = TreeBLOCKID; - info->header = calloc(1, 512); - info->header->free = -1; - info->edit->header_pages = 1; - (*dblist)->tree_info = info; - (*dblist)->open = 1; - (*dblist)->open_for_edit = 1; - (*dblist)->open_readonly = 0; - info->root = info->node; - (*dblist)->default_node = info->root; - TreeOpenNciW(info, 0); - info->edit->first_in_mem = 0; - status = TreeExpandNodes(*dblist, 0, 0); - // strncpy(info->node->name, "TOP ", - // sizeof(info->node->name)); - strcpy(info->node->name, "TOP"); - memset(info->node->name + 3, ' ', sizeof(info->node->name) - 3); - info->node->parent = 0; - info->node->child = 0; - info->node->member = 0; - info->node->usage = TreeUSAGE_SUBTREE; - (info->node + 1)->child = 0; - bitassign(1, info->edit->nci->flags, NciM_INCLUDE_IN_PULSE); - info->tags = calloc(1, 512); - info->edit->tags_pages = 1; - info->tag_info = calloc(sizeof(TAG_INFO), 512); - info->edit->tag_info_pages = sizeof(TAG_INFO); - info->external = calloc(1, 512); - info->edit->external_pages = 1; - info->edit->first_in_mem = 0; - info->header->version = 1; - info->header->sort_children = 1; - info->header->sort_members = 1; - info->header->free = sizeof(NODE); - } + if (STATUS_OK) + { + TreeCallHookFun("TreeHook", "OpenTreeEdit", info->treenam, + info->shot, NULL); + TreeCallHook(OpenTreeEdit, info, 0); + info->edit = (TREE_EDIT *)calloc(1, sizeof(TREE_EDIT)); + if (info->edit) + { + info->blockid = TreeBLOCKID; + info->header = calloc(1, 512); + info->header->free = -1; + info->edit->header_pages = 1; + (*dblist)->tree_info = info; + (*dblist)->open = 1; + (*dblist)->open_for_edit = 1; + (*dblist)->open_readonly = 0; + info->root = info->node; + (*dblist)->default_node = info->root; + TreeOpenNciW(info, 0); + info->edit->first_in_mem = 0; + status = TreeExpandNodes(*dblist, 0, 0); + // strncpy(info->node->name, "TOP ", + // sizeof(info->node->name)); + strcpy(info->node->name, "TOP"); + memset(info->node->name + 3, ' ', sizeof(info->node->name) - 3); + info->node->parent = 0; + info->node->child = 0; + info->node->member = 0; + info->node->usage = TreeUSAGE_SUBTREE; + (info->node + 1)->child = 0; + bitassign(1, info->edit->nci->flags, NciM_INCLUDE_IN_PULSE); + info->tags = calloc(1, 512); + info->edit->tags_pages = 1; + info->tag_info = calloc(sizeof(TAG_INFO), 512); + info->edit->tag_info_pages = sizeof(TAG_INFO); + info->external = calloc(1, 512); + info->edit->external_pages = 1; + info->edit->first_in_mem = 0; + info->header->version = 1; + info->header->sort_children = 1; + info->header->sort_members = 1; + info->header->free = sizeof(NODE); } - else { + } + else + { free(info->treenam); free(info); } free(tree); - } else + } + else status = TreeMEMERR; - if - STATUS_NOT_OK - free_top_db(dblist); + if (STATUS_NOT_OK) + free_top_db(dblist); } } - if - STATUS_OK - _TreeWriteTree(dbid, 0, 0); + if (STATUS_OK) + _TreeWriteTree(dbid, 0, 0); return status; } -void TreeFreeDbid(void *dbid) { - if (dbid) { +void TreeFreeDbid(void *dbid) +{ + if (dbid) + { DBG("Destroyed DB %" PRIxPTR "\n", (uintptr_t)dbid); PINO_DATABASE *db = (PINO_DATABASE *)dbid; TreeFreeDbid(db->next); @@ -1324,38 +1479,46 @@ void TreeFreeDbid(void *dbid) { } EXPORT int _TreeFileName(void *dbid, char *tree, int shot, - struct descriptor_xd *out_ptr) { + struct descriptor_xd *out_ptr) +{ int status; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; - if (tree) { + if (tree) + { int fd; TREE_INFO info; info.treenam = tree; info.shot = shot; status = OpenOne(&info, dblist ? dblist->tree_info : NULL, TREE_TREEFILE_TYPE, 0, 0, &info.filespec, &fd); - if - STATUS_OK { - MDS_IO_CLOSE(fd); - if (info.filespec) { - struct descriptor dsc = {(unsigned short)strlen(info.filespec), - DTYPE_T, CLASS_S, info.filespec}; - status = MdsCopyDxXd(&dsc, out_ptr); - free(info.filespec); - } + if (STATUS_OK) + { + MDS_IO_CLOSE(fd); + if (info.filespec) + { + struct descriptor dsc = {(unsigned short)strlen(info.filespec), + DTYPE_T, CLASS_S, info.filespec}; + status = MdsCopyDxXd(&dsc, out_ptr); + free(info.filespec); } - } else { - if (IS_OPEN(dblist)) { + } + } + else + { + if (IS_OPEN(dblist)) + { TREE_INFO *info = dblist->tree_info; struct descriptor dsc = {(uint16_t)strlen(info->filespec), DTYPE_T, CLASS_S, info->filespec}; status = MdsCopyDxXd(&dsc, out_ptr); - } else + } + else status = TreeNOT_OPEN; } return status; } -EXPORT int TreeFileName(char *tree, int shot, struct descriptor_xd *out_ptr) { +EXPORT int TreeFileName(char *tree, int shot, struct descriptor_xd *out_ptr) +{ return _TreeFileName(*TreeCtx(), tree, shot, out_ptr); } diff --git a/treeshr/TreePerf.c b/treeshr/TreePerf.c index 528dacde17..7c8ad82fd2 100644 --- a/treeshr/TreePerf.c +++ b/treeshr/TreePerf.c @@ -39,31 +39,38 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -EXPORT int TreeGetPerf(TREE_IO_PERF *perf) { +EXPORT int TreeGetPerf(TREE_IO_PERF *perf) +{ static int initialized = 0; static TREE_IO_PERF *p = 0; static sem_t *semaphore = 0; - if (!initialized) { + if (!initialized) + { initialized = 1; char *filename = getenv("mds_perf_filename"); - if (filename != 0) { + if (filename != 0) + { int pf = open(filename, O_RDONLY); - if (pf != -1) { + if (pf != -1) + { p = mmap(0, sizeof(TREE_IO_PERF), PROT_READ, MAP_SHARED, pf, 0); if (p == 0) perror("Error mapping performance file"); else semaphore = sem_open("mds_perf_lock", O_CREAT, 0664, 1); - } else + } + else perror("Error opening performance file"); } } - if (p != 0 && semaphore != 0) { + if (p != 0 && semaphore != 0) + { sem_wait(semaphore); *perf = *p; sem_post(semaphore); return TreeSUCCESS; - } else + } + else return TreeFAILURE; } @@ -71,36 +78,45 @@ static TREE_IO_PERF *PERF = 0; static int INITIALIZED = 0; static sem_t *SEMAPHORE = 0; -static void Initialize() { +static void Initialize() +{ INITIALIZED = 1; char *filename = getenv("mds_perf_filename"); - if (filename != 0) { + if (filename != 0) + { mode_t um = umask(0); int pf = open(filename, O_RDWR); - if (pf == -1) { + if (pf == -1) + { pf = open(filename, O_RDWR | O_CREAT, 0664); - if (pf != -1) { + if (pf != -1) + { static TREE_IO_PERF init; write(pf, &init, sizeof(init)); } } - if (pf != -1) { + if (pf != -1) + { PERF = mmap(0, sizeof(TREE_IO_PERF), PROT_WRITE, MAP_SHARED, pf, 0); if (PERF == 0) perror("Error mapping performance file"); - else { + else + { SEMAPHORE = sem_open("mds_perf_lock", O_CREAT, 0664, 1); } - } else + } + else perror("Error opening performance file"); umask(um); } } -EXPORT int TreePerfZero() { +EXPORT int TreePerfZero() +{ if (!INITIALIZED) Initialize(); - if (PERF != 0 && SEMAPHORE != 0) { + if (PERF != 0 && SEMAPHORE != 0) + { sem_wait(SEMAPHORE); memset(PERF, 0, sizeof(*PERF)); sem_post(SEMAPHORE); @@ -109,27 +125,40 @@ EXPORT int TreePerfZero() { return TreeFAILURE; } -EXPORT int TreePerfWrite(int bytes) { +EXPORT int TreePerfWrite(int bytes) +{ if (!INITIALIZED) Initialize(); - if (PERF != 0 && SEMAPHORE != 0) { + if (PERF != 0 && SEMAPHORE != 0) + { sem_wait(SEMAPHORE); - if (bytes < 10) { + if (bytes < 10) + { PERF->num_writes_10_0_to_10_1++; PERF->write_bytes_10_0_to_10_1 += bytes; - } else if (bytes < 100) { + } + else if (bytes < 100) + { PERF->num_writes_10_1_to_10_2++; PERF->write_bytes_10_1_to_10_2 += bytes; - } else if (bytes < 1000) { + } + else if (bytes < 1000) + { PERF->num_writes_10_2_to_10_3++; PERF->write_bytes_10_2_to_10_3 += bytes; - } else if (bytes < 100000) { + } + else if (bytes < 100000) + { PERF->num_writes_10_3_to_10_5++; PERF->write_bytes_10_3_to_10_5 += bytes; - } else if (bytes < 10000000) { + } + else if (bytes < 10000000) + { PERF->num_writes_10_5_to_10_7++; PERF->write_bytes_10_5_to_10_7 += bytes; - } else { + } + else + { PERF->num_writes_10_7_to_inf++; PERF->write_bytes_10_7_to_inf += bytes; } @@ -139,27 +168,40 @@ EXPORT int TreePerfWrite(int bytes) { return TreeFAILURE; } -EXPORT int TreePerfRead(int bytes) { +EXPORT int TreePerfRead(int bytes) +{ if (!INITIALIZED) Initialize(); - if (PERF != 0 && SEMAPHORE != 0) { + if (PERF != 0 && SEMAPHORE != 0) + { sem_wait(SEMAPHORE); - if (bytes < 10) { + if (bytes < 10) + { PERF->num_reads_10_0_to_10_1++; PERF->read_bytes_10_0_to_10_1 += bytes; - } else if (bytes < 100) { + } + else if (bytes < 100) + { PERF->num_reads_10_1_to_10_2++; PERF->read_bytes_10_1_to_10_2 += bytes; - } else if (bytes < 1000) { + } + else if (bytes < 1000) + { PERF->num_reads_10_2_to_10_3++; PERF->read_bytes_10_2_to_10_3 += bytes; - } else if (bytes < 100000) { + } + else if (bytes < 100000) + { PERF->num_reads_10_3_to_10_5++; PERF->read_bytes_10_3_to_10_5 += bytes; - } else if (bytes < 10000000) { + } + else if (bytes < 10000000) + { PERF->num_reads_10_5_to_10_7++; PERF->read_bytes_10_5_to_10_7 += bytes; - } else { + } + else + { PERF->num_reads_10_7_to_inf++; PERF->read_bytes_10_7_to_inf += bytes; } @@ -171,11 +213,13 @@ EXPORT int TreePerfRead(int bytes) { #else EXPORT int TreeGetPerf() { return TreeFAILURE; } -EXPORT int TreePerfRead(int bytes __attribute__((unused))) { +EXPORT int TreePerfRead(int bytes __attribute__((unused))) +{ return TreeFAILURE; } -EXPORT int TreePerfWrite(int bytes __attribute__((unused))) { +EXPORT int TreePerfWrite(int bytes __attribute__((unused))) +{ return TreeFAILURE; } diff --git a/treeshr/TreePutRecord.c b/treeshr/TreePutRecord.c index 50eaf3bd99..6229b597ec 100644 --- a/treeshr/TreePutRecord.c +++ b/treeshr/TreePutRecord.c @@ -96,19 +96,22 @@ extern int PutRecordRemote(); extern void **TreeCtx(); -int64_t TreeTimeInserted() { +int64_t TreeTimeInserted() +{ int64_t ans; LibTimeToVMSTime(0, &ans); return ans; } int TreePutRecord(int nid, struct descriptor *descriptor_ptr, - int utility_update) { + int utility_update) +{ return _TreePutRecord(*TreeCtx(), nid, descriptor_ptr, utility_update); } int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, - int utility_update) { + int utility_update) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; int status; @@ -134,7 +137,8 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, return PutRecordRemote(dblist, nid, descriptor_ptr, utility_update); shot_open = (dblist->shotid != -1); nid_to_tree_nidx(dblist, nid_ptr, info_ptr, nidx); - if (info_ptr) { + if (info_ptr) + { int stv; NCI local_nci, old_nci; int64_t saved_viewdate; @@ -155,149 +159,173 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, open_status = TreeOpenDatafileW(info_ptr, &stv, 0); else open_status = 1; - if (local_nci.flags2 & NciM_EXTENDED_NCI) { + if (local_nci.flags2 & NciM_EXTENDED_NCI) + { int ext_status; extended_offset = RfaToSeek(local_nci.DATA_INFO.DATA_LOCATION.rfa); ext_status = TreeGetExtendedAttributes(info_ptr, extended_offset, &attributes); - if (!(ext_status & 1)) { + if (!(ext_status & 1)) + { local_nci.flags2 &= ~NciM_EXTENDED_NCI; - } else { + } + else + { extended = 1; } } - if - STATUS_OK { - if (utility_update) { + if (STATUS_OK) + { + if (utility_update) + { + TREETHREADSTATIC_INIT; + local_nci.flags = TREE_TEMPNCI.flags; + bitassign(0, local_nci.flags, NciM_VERSIONS); + local_nci.owner_identifier = TREE_TEMPNCI.owner_identifier; + local_nci.time_inserted = TREE_TEMPNCI.time_inserted; + } + else + { + bitassign(dblist->setup_info, local_nci.flags, + NciM_SETUP_INFORMATION); + local_nci.owner_identifier = saved_uic; + /* VMS time = unixtime * 10,000,000 + 0x7c95674beb4000q */ + local_nci.time_inserted = TreeTimeInserted(); + } + if (!(open_status & 1)) + { + local_nci.DATA_INFO.ERROR_INFO.stv = stv; + bitassign_c(1, local_nci.flags2, NciM_ERROR_ON_PUT); + local_nci.DATA_INFO.ERROR_INFO.error_status = open_status; + local_nci.length = 0; + tree_put_nci(info_ptr, nidx, &local_nci, &locked_nci); + return open_status; + } + else + { + NCI *nci = info_ptr->data_file->asy_nci->nci; + *nci = local_nci; + if (nci->length != 0 && + ((shot_open && info_ptr->header->versions_in_pulse) || + (!shot_open && info_ptr->header->versions_in_model))) + bitassign(1, nci->flags, NciM_VERSIONS); + if (!utility_update) + { + old_record_length = + (nci->flags2 & NciM_DATA_IN_ATT_BLOCK || + (nci->flags & NciM_VERSIONS)) + ? 0 + : nci->DATA_INFO.DATA_LOCATION.record_length; + if ((nci->flags & NciM_WRITE_ONCE) && nci->length) + status = TreeNOOVERWRITE; + if ((status & 1) && + (shot_open && (nci->flags & NciM_NO_WRITE_SHOT))) + status = TreeNOWRITESHOT; + if ((status & 1) && + (!shot_open && (nci->flags & NciM_NO_WRITE_MODEL))) + status = TreeNOWRITEMODEL; + } + if (status & 1) + { + unsigned char tree = (unsigned char)nid_ptr->tree; + int compressible; + int data_in_altbuf; TREETHREADSTATIC_INIT; - local_nci.flags = TREE_TEMPNCI.flags; - bitassign(0, local_nci.flags, NciM_VERSIONS); - local_nci.owner_identifier = TREE_TEMPNCI.owner_identifier; - local_nci.time_inserted = TREE_TEMPNCI.time_inserted; - } else { - bitassign(dblist->setup_info, local_nci.flags, - NciM_SETUP_INFORMATION); - local_nci.owner_identifier = saved_uic; - /* VMS time = unixtime * 10,000,000 + 0x7c95674beb4000q */ - local_nci.time_inserted = TreeTimeInserted(); + void *dbid_tree[2] = {(void *)dbid, (void *)&tree}; + TREE_NIDREF = TREE_PATHREF = FALSE; + status = MdsSerializeDscOutZ( + descriptor_ptr, info_ptr->data_file->data, tree_fixup_nid, + dbid_tree, FixupPath, 0, + (compress_utility || (nci->flags & NciM_COMPRESS_ON_PUT)) && + !(nci->flags & NciM_DO_NOT_COMPRESS), + &compressible, &nci->length, + &nci->DATA_INFO.DATA_LOCATION.record_length, &nci->dtype, + &nci->class, + (nci->flags & NciM_VERSIONS || extended) + ? 0 + : sizeof(nci->DATA_INFO.DATA_IN_RECORD.data), + nci->DATA_INFO.DATA_IN_RECORD.data, &data_in_altbuf); + bitassign(TREE_PATHREF, nci->flags, NciM_PATH_REFERENCE); + bitassign(TREE_NIDREF, nci->flags, NciM_NID_REFERENCE); + bitassign(compressible, nci->flags, NciM_COMPRESSIBLE); + bitassign_c(data_in_altbuf, nci->flags2, NciM_DATA_IN_ATT_BLOCK); } - if (!(open_status & 1)) { - local_nci.DATA_INFO.ERROR_INFO.stv = stv; - bitassign_c(1, local_nci.flags2, NciM_ERROR_ON_PUT); - local_nci.DATA_INFO.ERROR_INFO.error_status = open_status; - local_nci.length = 0; - tree_put_nci(info_ptr, nidx, &local_nci, &locked_nci); - return open_status; - } else { - NCI *nci = info_ptr->data_file->asy_nci->nci; - *nci = local_nci; - if (nci->length != 0 && - ((shot_open && info_ptr->header->versions_in_pulse) || - (!shot_open && info_ptr->header->versions_in_model))) - bitassign(1, nci->flags, NciM_VERSIONS); - if (!utility_update) { - old_record_length = - (nci->flags2 & NciM_DATA_IN_ATT_BLOCK || - (nci->flags & NciM_VERSIONS)) - ? 0 - : nci->DATA_INFO.DATA_LOCATION.record_length; - if ((nci->flags & NciM_WRITE_ONCE) && nci->length) - status = TreeNOOVERWRITE; - if ((status & 1) && - (shot_open && (nci->flags & NciM_NO_WRITE_SHOT))) - status = TreeNOWRITESHOT; - if ((status & 1) && - (!shot_open && (nci->flags & NciM_NO_WRITE_MODEL))) - status = TreeNOWRITEMODEL; + if ((status & 1) && nci->length && (!utility_update)) + status = check_usage(dblist, nid_ptr, nci); + if (status & 1) + { + if (nci->flags2 & NciM_DATA_IN_ATT_BLOCK && + !(nci->flags & NciM_VERSIONS) && !extended) + { + bitassign_c(0, nci->flags2, NciM_ERROR_ON_PUT); + status = tree_put_nci(info_ptr, nidx, nci, &locked_nci); } - if (status & 1) { - unsigned char tree = (unsigned char)nid_ptr->tree; - int compressible; - int data_in_altbuf; - TREETHREADSTATIC_INIT; - void *dbid_tree[2] = {(void *)dbid, (void *)&tree}; - TREE_NIDREF = TREE_PATHREF = FALSE; - status = MdsSerializeDscOutZ( - descriptor_ptr, info_ptr->data_file->data, tree_fixup_nid, - dbid_tree, FixupPath, 0, - (compress_utility || (nci->flags & NciM_COMPRESS_ON_PUT)) && - !(nci->flags & NciM_DO_NOT_COMPRESS), - &compressible, &nci->length, - &nci->DATA_INFO.DATA_LOCATION.record_length, &nci->dtype, - &nci->class, - (nci->flags & NciM_VERSIONS || extended) - ? 0 - : sizeof(nci->DATA_INFO.DATA_IN_RECORD.data), - nci->DATA_INFO.DATA_IN_RECORD.data, &data_in_altbuf); - bitassign(TREE_PATHREF, nci->flags, NciM_PATH_REFERENCE); - bitassign(TREE_NIDREF, nci->flags, NciM_NID_REFERENCE); - bitassign(compressible, nci->flags, NciM_COMPRESSIBLE); - bitassign_c(data_in_altbuf, nci->flags2, NciM_DATA_IN_ATT_BLOCK); - } - if ((status & 1) && nci->length && (!utility_update)) - status = check_usage(dblist, nid_ptr, nci); - if (status & 1) { - if (nci->flags2 & NciM_DATA_IN_ATT_BLOCK && - !(nci->flags & NciM_VERSIONS) && !extended) { - bitassign_c(0, nci->flags2, NciM_ERROR_ON_PUT); - status = tree_put_nci(info_ptr, nidx, nci, &locked_nci); - } else { - if (extended) { - status = tree_put_dsc( - dblist, info_ptr, nid, descriptor_ptr, - &attributes.facility_offset[STANDARD_RECORD_FACILITY], - &attributes.facility_length[STANDARD_RECORD_FACILITY], - (compress_utility || (nci->flags & NciM_COMPRESS_ON_PUT)) && - !(nci->flags & NciM_DO_NOT_COMPRESS)); - if (status & 1) { - attributes.facility_offset[SEGMENTED_RECORD_FACILITY] = -1; - attributes.facility_length[SEGMENTED_RECORD_FACILITY] = 0; - status = TreePutExtendedAttributes(info_ptr, &attributes, - &extended_offset); - } - if (status & 1) { - bitassign(0, nci->flags, NciM_SEGMENTED); - tree_put_nci(info_ptr, nidx, nci, &locked_nci); - } else - tree_unlock_nci(info_ptr, 0, nidx, &locked_nci); - } else if ((nci->DATA_INFO.DATA_LOCATION.record_length != - old_record_length) || - (nci->DATA_INFO.DATA_LOCATION.record_length >= - DATAF_C_MAX_RECORD_SIZE) || - utility_update || (nci->flags & NciM_VERSIONS) || - (nci->flags2 & NciM_ERROR_ON_PUT)) - status = - put_datafile(info_ptr, nidx, nci, info_ptr->data_file->data, - &old_nci, &locked_nci); + else + { + if (extended) + { + status = tree_put_dsc( + dblist, info_ptr, nid, descriptor_ptr, + &attributes.facility_offset[STANDARD_RECORD_FACILITY], + &attributes.facility_length[STANDARD_RECORD_FACILITY], + (compress_utility || (nci->flags & NciM_COMPRESS_ON_PUT)) && + !(nci->flags & NciM_DO_NOT_COMPRESS)); + if (status & 1) + { + attributes.facility_offset[SEGMENTED_RECORD_FACILITY] = -1; + attributes.facility_length[SEGMENTED_RECORD_FACILITY] = 0; + status = TreePutExtendedAttributes(info_ptr, &attributes, + &extended_offset); + } + if (status & 1) + { + bitassign(0, nci->flags, NciM_SEGMENTED); + tree_put_nci(info_ptr, nidx, nci, &locked_nci); + } else - status = - update_datafile(info_ptr, nidx, nci, - info_ptr->data_file->data, &locked_nci); + tree_unlock_nci(info_ptr, 0, nidx, &locked_nci); } - } else - tree_unlock_nci(info_ptr, 0, nidx, &locked_nci); + else if ((nci->DATA_INFO.DATA_LOCATION.record_length != + old_record_length) || + (nci->DATA_INFO.DATA_LOCATION.record_length >= + DATAF_C_MAX_RECORD_SIZE) || + utility_update || (nci->flags & NciM_VERSIONS) || + (nci->flags2 & NciM_ERROR_ON_PUT)) + status = + put_datafile(info_ptr, nidx, nci, info_ptr->data_file->data, + &old_nci, &locked_nci); + else + status = + update_datafile(info_ptr, nidx, nci, + info_ptr->data_file->data, &locked_nci); + } } + else + tree_unlock_nci(info_ptr, 0, nidx, &locked_nci); } + } else tree_unlock_nci(info_ptr, 0, nidx, &locked_nci); - } else + } + else status = TreeINVTREE; return status; } -static int check_usage(PINO_DATABASE *dblist, NID *nid_ptr, NCI *nci) { +static int check_usage(PINO_DATABASE *dblist, NID *nid_ptr, NCI *nci) +{ -#define is_expression \ - ((nci->dtype == DTYPE_FUNCTION) || (nci->dtype == DTYPE_NID) || \ - (nci->dtype == DTYPE_PATH) || (nci->dtype == DTYPE_IDENT) || \ +#define is_expression \ + ((nci->dtype == DTYPE_FUNCTION) || (nci->dtype == DTYPE_NID) || \ + (nci->dtype == DTYPE_PATH) || (nci->dtype == DTYPE_IDENT) || \ (nci->dtype == DTYPE_CALL)) #define check(boolean) (boolean) ? TreeSUCCESS : TreeINVDTPUSG; -#define is_numeric \ - (((nci->dtype >= DTYPE_BU) && (nci->dtype <= DTYPE_DC)) || \ - ((nci->dtype >= DTYPE_OU) && (nci->dtype <= DTYPE_HC)) || \ - ((nci->dtype >= DTYPE_FS) && (nci->dtype <= DTYPE_FTC)) || \ +#define is_numeric \ + (((nci->dtype >= DTYPE_BU) && (nci->dtype <= DTYPE_DC)) || \ + ((nci->dtype >= DTYPE_OU) && (nci->dtype <= DTYPE_HC)) || \ + ((nci->dtype >= DTYPE_FS) && (nci->dtype <= DTYPE_FTC)) || \ (nci->dtype == DTYPE_DSC)) NODE *node_ptr; @@ -305,7 +333,8 @@ static int check_usage(PINO_DATABASE *dblist, NID *nid_ptr, NCI *nci) { node_ptr = nid_to_node(dblist, nid_ptr); if (!node_ptr) return TreeNNF; - switch (node_ptr->usage) { + switch (node_ptr->usage) + { case TreeUSAGE_STRUCTURE: case TreeUSAGE_SUBTREE: status = TreeINVDTPUSG; @@ -363,12 +392,15 @@ static int check_usage(PINO_DATABASE *dblist, NID *nid_ptr, NCI *nci) { return status; } -int tree_fixup_nid(NID *nid, void **dbid_tree, struct descriptor *path) { +int tree_fixup_nid(NID *nid, void **dbid_tree, struct descriptor *path) +{ unsigned char *tree = (unsigned char *)dbid_tree[1]; TREETHREADSTATIC_INIT; - if (nid->tree != *tree) { + if (nid->tree != *tree) + { char *path_c = _TreeGetPath(dbid_tree[0], *(int *)nid); - if (path_c) { + if (path_c) + { struct descriptor path_d = {0, DTYPE_T, CLASS_S, 0}; path_d.length = (unsigned short)strlen(path_c); path_d.pointer = path_c; @@ -377,21 +409,25 @@ int tree_fixup_nid(NID *nid, void **dbid_tree, struct descriptor *path) { } TREE_PATHREF = TRUE; return TRUE; - } else { + } + else + { TREE_NIDREF = TRUE; return FALSE; } } -static int FixupPath() { +static int FixupPath() +{ TREETHREADSTATIC_INIT; TREE_PATHREF = 1; return 0; } static inline char * tree_to_datafile(const char *tree, - const int tmpfile) { // replace .tree with .characteristics or - // .characteristics# if tmpfile + const int tmpfile) +{ // replace .tree with .characteristics or + // .characteristics# if tmpfile const size_t baselen = strlen(tree) - sizeof("tree") + 1; const size_t namelen = baselen + (tmpfile ? sizeof("datafile#") - 1 : sizeof("datafile") - 1); @@ -400,63 +436,67 @@ tree_to_datafile(const char *tree, filename[namelen] = '\0'; return filename; } -int TreeOpenDatafileW(TREE_INFO *info, int *stv_ptr, int tmpfile) { +int TreeOpenDatafileW(TREE_INFO *info, int *stv_ptr, int tmpfile) +{ WRLOCKINFO(info); int status = _TreeOpenDatafileW(info, stv_ptr, tmpfile); UNLOCKINFO(info); return status; } -int _TreeOpenDatafileW(TREE_INFO *info, int *stv_ptr, int tmpfile) { +int _TreeOpenDatafileW(TREE_INFO *info, int *stv_ptr, int tmpfile) +{ int status = TreeSUCCESS; if (info->header->readonly) return TreeREADONLY_TREE; DATA_FILE *df_ptr = info->data_file; *stv_ptr = 0; - if (df_ptr == 0) { + if (df_ptr == 0) + { df_ptr = TreeGetVmDatafile(); status = (df_ptr == NULL) ? TreeFAILURE : TreeSUCCESS; } - if - STATUS_OK { - int old_get = df_ptr->get; - char *filename = tree_to_datafile(info->filespec, tmpfile); - df_ptr->get = MDS_IO_OPEN( - filename, tmpfile ? O_RDWR | O_CREAT | O_TRUNC | O_EXCL : O_RDONLY, - 0664); - status = (df_ptr->get == -1) ? TreeFAILURE : TreeSUCCESS; - if (df_ptr->get == -1) - df_ptr->get = old_get; - else if (df_ptr->get > 0) - MDS_IO_CLOSE(old_get); - if - STATUS_OK { - df_ptr->put = MDS_IO_OPEN(filename, O_RDWR, 0); - status = (df_ptr->put == -1) ? TreeFAILURE : TreeSUCCESS; - if (df_ptr->put == -1) - df_ptr->put = 0; - if - STATUS_OK - df_ptr->open_for_write = 1; - } - free(filename); + if (STATUS_OK) + { + int old_get = df_ptr->get; + char *filename = tree_to_datafile(info->filespec, tmpfile); + df_ptr->get = MDS_IO_OPEN( + filename, tmpfile ? O_RDWR | O_CREAT | O_TRUNC | O_EXCL : O_RDONLY, + 0664); + status = (df_ptr->get == -1) ? TreeFAILURE : TreeSUCCESS; + if (df_ptr->get == -1) + df_ptr->get = old_get; + else if (df_ptr->get > 0) + MDS_IO_CLOSE(old_get); + if (STATUS_OK) + { + df_ptr->put = MDS_IO_OPEN(filename, O_RDWR, 0); + status = (df_ptr->put == -1) ? TreeFAILURE : TreeSUCCESS; + if (df_ptr->put == -1) + df_ptr->put = 0; + if (STATUS_OK) + df_ptr->open_for_write = 1; } - else { + free(filename); + } + else + { free(df_ptr); df_ptr = NULL; } info->data_file = df_ptr; - if - STATUS_OK { - TreeCallHookFun("TreeHook", "OpenDataFileWrite", info->treenam, - info->shot, NULL); - TreeCallHook(OpenDataFileWrite, info, 0); - } + if (STATUS_OK) + { + TreeCallHookFun("TreeHook", "OpenDataFileWrite", info->treenam, + info->shot, NULL); + TreeCallHook(OpenDataFileWrite, info, 0); + } return status; } static int put_datafile(TREE_INFO *info, int nodenum, NCI *nci_ptr, struct descriptor_xd *data_dsc_ptr, NCI *old_nci_ptr, - int *ncilocked) { + int *ncilocked) +{ int status = TreeSUCCESS; unsigned int bytes_to_put = data_dsc_ptr->l_length > 0 @@ -470,127 +510,144 @@ static int put_datafile(TREE_INFO *info, int nodenum, NCI *nci_ptr, char *bptr; int64_t eof; unsigned char rfa[6]; - if (blen > 0) { + if (blen > 0) + { bitassign_c(1, nci_ptr->flags2, NciM_DATA_CONTIGUOUS); if (nonvms_compatible == -1) nonvms_compatible = getenv("NONVMS_COMPATIBLE") != NULL; - if (nonvms_compatible) { + if (nonvms_compatible) + { bitassign_c(1, nci_ptr->flags2, NciM_NON_VMS); buffer = (char *)data_dsc_ptr->pointer->pointer; bptr = buffer + nci_ptr->DATA_INFO.DATA_LOCATION.record_length; status = TreeLockDatafile(info, 0, 0); eof = MDS_IO_LSEEK(info->data_file->put, 0, SEEK_END); - } else { + } + else + { buffer = (char *)malloc(blen); bptr = buffer; loadint32(&info->data_file->record_header->node_number, &nodenum); bitassign_c(0, nci_ptr->flags2, NciM_NON_VMS); memset(&info->data_file->record_header->rfa, 0, sizeof(RFA)); status = TreeLockDatafile(info, 0, 0); - if - STATUS_OK { - eof = MDS_IO_LSEEK(info->data_file->put, 0, SEEK_END); - while (bytes_to_put) { - const int bytes_this_time = - min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_to_put); - bytes_to_put -= bytes_this_time; - uint16_t rlength = bytes_this_time + 10; - loadint16(&info->data_file->record_header->rlength, &rlength); - memcpy(bptr, (void *)info->data_file->record_header, - sizeof(RECORD_HEADER)); - bptr += sizeof(RECORD_HEADER); - memcpy(bptr, - (void *)(((char *)data_dsc_ptr->pointer->pointer) + - bytes_to_put), - bytes_this_time); - bptr += bytes_this_time; - SeekToRfa(eof, rfa); - memcpy(&info->data_file->record_header->rfa, rfa, - sizeof(info->data_file->record_header->rfa)); - if (bytes_to_put) - eof += sizeof(RECORD_HEADER) + bytes_this_time; - } + if (STATUS_OK) + { + eof = MDS_IO_LSEEK(info->data_file->put, 0, SEEK_END); + while (bytes_to_put) + { + const int bytes_this_time = + min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_to_put); + bytes_to_put -= bytes_this_time; + uint16_t rlength = bytes_this_time + 10; + loadint16(&info->data_file->record_header->rlength, &rlength); + memcpy(bptr, (void *)info->data_file->record_header, + sizeof(RECORD_HEADER)); + bptr += sizeof(RECORD_HEADER); + memcpy(bptr, + (void *)(((char *)data_dsc_ptr->pointer->pointer) + + bytes_to_put), + bytes_this_time); + bptr += bytes_this_time; + SeekToRfa(eof, rfa); + memcpy(&info->data_file->record_header->rfa, rfa, + sizeof(info->data_file->record_header->rfa)); + if (bytes_to_put) + eof += sizeof(RECORD_HEADER) + bytes_this_time; } + } } - } else { + } + else + { if (nci_ptr->flags & NciM_VERSIONS) status = TreeLockDatafile(info, 0, 0); bptr = buffer; eof = -1; } - if - STATUS_OK { - if (bptr == buffer || MDS_IO_WRITE(info->data_file->put, (void *)buffer, - bptr - buffer) == (bptr - buffer)) { - bitassign_c(0, nci_ptr->flags2, NciM_ERROR_ON_PUT); - if (bptr > buffer) { - SeekToRfa(eof, rfa); - memcpy(nci_ptr->DATA_INFO.DATA_LOCATION.rfa, rfa, - sizeof(nci_ptr->DATA_INFO.DATA_LOCATION.rfa)); - } - if (nci_ptr->flags & NciM_VERSIONS) { - char nci_bytes[42]; - int64_t seek_end; - TreeSerializeNciOut(old_nci_ptr, nci_bytes); - seek_end = MDS_IO_LSEEK(info->data_file->put, 0, SEEK_END); - if (seek_end != -1 && - MDS_IO_WRITE(info->data_file->put, nci_bytes, - sizeof(nci_bytes)) != sizeof(nci_bytes)) { - fprintf(stderr, "ERROR: put_datafile writing old nci incomplete\n"); - status = TreeFAILURE; - } + if (STATUS_OK) + { + if (bptr == buffer || MDS_IO_WRITE(info->data_file->put, (void *)buffer, + bptr - buffer) == (bptr - buffer)) + { + bitassign_c(0, nci_ptr->flags2, NciM_ERROR_ON_PUT); + if (bptr > buffer) + { + SeekToRfa(eof, rfa); + memcpy(nci_ptr->DATA_INFO.DATA_LOCATION.rfa, rfa, + sizeof(nci_ptr->DATA_INFO.DATA_LOCATION.rfa)); + } + if (nci_ptr->flags & NciM_VERSIONS) + { + char nci_bytes[42]; + int64_t seek_end; + TreeSerializeNciOut(old_nci_ptr, nci_bytes); + seek_end = MDS_IO_LSEEK(info->data_file->put, 0, SEEK_END); + if (seek_end != -1 && + MDS_IO_WRITE(info->data_file->put, nci_bytes, + sizeof(nci_bytes)) != sizeof(nci_bytes)) + { + fprintf(stderr, "ERROR: put_datafile writing old nci incomplete\n"); + status = TreeFAILURE; } - } else { - bitassign_c(1, nci_ptr->flags2, NciM_ERROR_ON_PUT); - nci_ptr->DATA_INFO.ERROR_INFO.error_status = TreeFAILURE; - nci_ptr->length = 0; } - TreeUnLockDatafile(info, 0, 0); - if - STATUS_OK // unless put_datafile writing old nci incomplete - status = tree_put_nci(info, nodenum, nci_ptr, ncilocked); } + else + { + bitassign_c(1, nci_ptr->flags2, NciM_ERROR_ON_PUT); + nci_ptr->DATA_INFO.ERROR_INFO.error_status = TreeFAILURE; + nci_ptr->length = 0; + } + TreeUnLockDatafile(info, 0, 0); + if (STATUS_OK) + // unless put_datafile writing old nci incomplete + status = tree_put_nci(info, nodenum, nci_ptr, ncilocked); + } if (buffer && (!nonvms_compatible)) free(buffer); return status; } static int update_datafile(TREE_INFO *info, int nodenum, NCI *nci_ptr, - struct descriptor_xd *data_dsc_ptr, int *ncilocked) { + struct descriptor_xd *data_dsc_ptr, int *ncilocked) +{ int status = TreeSUCCESS; unsigned int bytes_to_put = nci_ptr->DATA_INFO.DATA_LOCATION.record_length; loadint32(&info->data_file->record_header->node_number, &nodenum); memset(&info->data_file->record_header->rfa, 0, sizeof(RFA)); - while (bytes_to_put && STATUS_OK) { + while (bytes_to_put && STATUS_OK) + { const int bytes_this_time = min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_to_put); const int64_t rfa_l = RfaToSeek(nci_ptr->DATA_INFO.DATA_LOCATION.rfa); uint16_t rlength = bytes_this_time + 10; loadint16(&info->data_file->record_header->rlength, &rlength); status = TreeLockDatafile(info, 0, rfa_l); - if - STATUS_OK { - MDS_IO_LSEEK(info->data_file->put, rfa_l, SEEK_SET); - if (MDS_IO_WRITE(info->data_file->put, - (void *)info->data_file->record_header, - sizeof(RECORD_HEADER)) == sizeof(RECORD_HEADER)) { - bytes_to_put -= bytes_this_time; - status = - (MDS_IO_WRITE(info->data_file->put, - (void *)(((char *)data_dsc_ptr->pointer->pointer) + - bytes_to_put), - bytes_this_time) == bytes_this_time) - ? TreeSUCCESS - : TreeFAILURE; - } else - status = TreeFAILURE; - TreeUnLockDatafile(info, 0, rfa_l); + if (STATUS_OK) + { + MDS_IO_LSEEK(info->data_file->put, rfa_l, SEEK_SET); + if (MDS_IO_WRITE(info->data_file->put, + (void *)info->data_file->record_header, + sizeof(RECORD_HEADER)) == sizeof(RECORD_HEADER)) + { + bytes_to_put -= bytes_this_time; + status = + (MDS_IO_WRITE(info->data_file->put, + (void *)(((char *)data_dsc_ptr->pointer->pointer) + + bytes_to_put), + bytes_this_time) == bytes_this_time) + ? TreeSUCCESS + : TreeFAILURE; } + else + status = TreeFAILURE; + TreeUnLockDatafile(info, 0, rfa_l); + } } bitassign(0, nci_ptr->flags, NciM_SEGMENTED); - if - STATUS_OK - bitassign_c(0, nci_ptr->flags2, NciM_ERROR_ON_PUT); - else { + if (STATUS_OK) + bitassign_c(0, nci_ptr->flags2, NciM_ERROR_ON_PUT); + else + { bitassign_c(1, nci_ptr->flags2, NciM_ERROR_ON_PUT); nci_ptr->DATA_INFO.ERROR_INFO.error_status = status; nci_ptr->length = 0; @@ -604,17 +661,21 @@ static int update_datafile(TREE_INFO *info, int nodenum, NCI *nci_ptr, NIDs converted to PATHs for TREE$COPY_TO_RECORD. Eliminates DSC descriptors. Need DSC for classes A and APD? -----------------------------------------------------------------*/ -int TreeSetTemplateNci(NCI *nci) { +int TreeSetTemplateNci(NCI *nci) +{ TREETHREADSTATIC_INIT; TREE_TEMPNCI = *nci; return TreeSUCCESS; } -int TreeLockDatafile(TREE_INFO *info, int readonly, int64_t offset) { +int TreeLockDatafile(TREE_INFO *info, int readonly, int64_t offset) +{ INIT_STATUS; int deleted = 1; - if (!info->header->readonly) { - while (deleted && status & 1) { + if (!info->header->readonly) + { + while (deleted && status & 1) + { status = MDS_IO_LOCK(readonly ? info->data_file->get : info->data_file->put, offset, offset >= 0 ? 12 : (DATAF_C_MAX_RECORD_SIZE * 3), @@ -626,7 +687,8 @@ int TreeLockDatafile(TREE_INFO *info, int readonly, int64_t offset) { return status; } -int TreeUnLockDatafile(TREE_INFO *info, int readonly, int64_t offset) { +int TreeUnLockDatafile(TREE_INFO *info, int readonly, int64_t offset) +{ INIT_STATUS; if (!info->header->readonly) status = MDS_IO_LOCK( diff --git a/treeshr/TreeRemoveNodesTags.c b/treeshr/TreeRemoveNodesTags.c index 155a07ae3e..a82db5534b 100644 --- a/treeshr/TreeRemoveNodesTags.c +++ b/treeshr/TreeRemoveNodesTags.c @@ -63,11 +63,13 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx); int TreeRemoveTag(char const *name) { return _TreeRemoveTag(*TreeCtx(), name); } -int TreeRemoveNodesTags(int nid) { +int TreeRemoveNodesTags(int nid) +{ return _TreeRemoveNodesTags(*TreeCtx(), nid); } -int _TreeRemoveNodesTags(void *dbid, int nid) { +int _TreeRemoveNodesTags(void *dbid, int nid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NODE *node; NID *nid_ptr = (NID *)&nid; @@ -82,7 +84,8 @@ int _TreeRemoveNodesTags(void *dbid, int nid) { ***********************************/ node = nid_to_node(dblist, nid_ptr); - for (tagidx = swapint32(&node->tag_link); tagidx != 0; tagidx = next_tag) { + for (tagidx = swapint32(&node->tag_link); tagidx != 0; tagidx = next_tag) + { next_tag = swapint32(&dblist->tree_info->tag_info[tagidx - 1].tag_link); _RemoveTagIdx(dblist, tagidx); } @@ -93,7 +96,8 @@ int _TreeRemoveNodesTags(void *dbid, int nid) { * Routine to remove a tag from the tree given its name */ -int _TreeRemoveTag(void *dbid, char const *name) { +int _TreeRemoveTag(void *dbid, char const *name) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int idx; int status; @@ -115,7 +119,8 @@ int _TreeRemoveTag(void *dbid, char const *name) { /* * Routine to remove a tag from the tree given its tag index */ -static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) { +static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) +{ TAG_INFO *info_ptr, *remove_info_ptr; NODE *node_ptr; int *tags_ptr, *this_tags_ptr = 0; @@ -133,7 +138,8 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) { node_ptr = dblist->tree_info->node + swapint32(&remove_info_ptr->node_idx); if (swapint32(&node_ptr->tag_link) == tagidx) node_ptr->tag_link = remove_info_ptr->tag_link; - else { + else + { int tag_link; for (tag_link = swapint32(&node_ptr->tag_link), info_ptr = dblist->tree_info->tag_info + tag_link - 1; @@ -157,14 +163,16 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) { for (info_ptr = dblist->tree_info->tag_info; info_ptr < dblist->tree_info->tag_info + dblist->tree_info->header->tags; info_ptr++) - if (swapint32(&info_ptr->tag_link) >= tagidx) { + if (swapint32(&info_ptr->tag_link) >= tagidx) + { int tmp = swapint32(&info_ptr->tag_link) - 1; info_ptr->tag_link = swapint32(&tmp); } for (node_ptr = dblist->tree_info->node; node_ptr < dblist->tree_info->node + dblist->tree_info->header->nodes; node_ptr++) - if (swapint32(&node_ptr->tag_link) >= tagidx) { + if (swapint32(&node_ptr->tag_link) >= tagidx) + { int tmp = swapint32(&node_ptr->tag_link) - 1; node_ptr->tag_link = swapint32(&tmp); } @@ -176,11 +184,13 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) { for (tags_ptr = dblist->tree_info->tags; tags_ptr < dblist->tree_info->tags + dblist->tree_info->header->tags; - tags_ptr++) { + tags_ptr++) + { int tags = swapint32(tags_ptr); if (tags == (tagidx - 1)) this_tags_ptr = tags_ptr; - if (tags >= tagidx) { + if (tags >= tagidx) + { tags--; *tags_ptr = swapint32(&tags); } @@ -192,7 +202,8 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) { by the removed tag and then decrement the total tag count. ********************************************/ - if (this_tags_ptr) { + if (this_tags_ptr) + { int i, range = dblist->tree_info->header->tags - (this_tags_ptr - dblist->tree_info->tags); for (i = 0; i < range; i++) diff --git a/treeshr/TreeRenameNode.c b/treeshr/TreeRenameNode.c index c695d7adac..c929c7bac4 100644 --- a/treeshr/TreeRenameNode.c +++ b/treeshr/TreeRenameNode.c @@ -70,11 +70,13 @@ extern int tree_set_parent_state(PINO_DATABASE *db, NODE *node, unsigned int state); extern void **TreeCtx(); -int TreeRenameNode(int nid, char const *newname) { +int TreeRenameNode(int nid, char const *newname) +{ return _TreeRenameNode(*TreeCtx(), nid, newname); } -int _TreeRenameNode(void *dbid, int nid, char const *newname) { +int _TreeRenameNode(void *dbid, int nid, char const *newname) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; NODE *pptr, *nptr, *newnode, *oldnode_ptr; @@ -86,14 +88,16 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { /***************************************************** Make sure that the tree is open and OK and editable *****************************************************/ - if (!(IS_OPEN_FOR_EDIT(dblist))) { + if (!(IS_OPEN_FOR_EDIT(dblist))) + { return TreeNOEDIT; } upcase_name = strdup(newname); /************************** Convert to upper case. ***************************/ - for (i = 0; i < (int)strlen(newname); i++) { + for (i = 0; i < (int)strlen(newname); i++) + { upcase_name[i] = (char)toupper(newname[i]); } upcase_name[i] = 0; @@ -101,7 +105,8 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { make sure that the new node is not already there ***************************************************/ status = _TreeFindNode(dbid, upcase_name, &i); - if (status & 1) { + if (status & 1) + { status = TreeALREADY_THERE; goto cleanup; } @@ -119,8 +124,10 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { off into space.) ************************************************/ oldnode_ptr = nid_to_node(dblist, (nid_ptr)); - for (nptr = newnode; nptr; nptr = parent_of(dblist, nptr)) { - if (nptr == oldnode_ptr) { + for (nptr = newnode; nptr; nptr = parent_of(dblist, nptr)) + { + if (nptr == oldnode_ptr) + { status = TreeINVPATH; goto cleanup; } @@ -130,8 +137,10 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { Make sure that a node with a non-STRUCTURE usage is not being renamed into a son. ************************************************/ - if (is_child) { - if (oldnode_ptr->usage != TreeUSAGE_STRUCTURE) { + if (is_child) + { + if (oldnode_ptr->usage != TreeUSAGE_STRUCTURE) + { status = TreeINVPATH; goto cleanup; } @@ -141,37 +150,56 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { OK so far so disconnect the old node *************************************************/ pptr = parent_of(dblist, oldnode_ptr); - if (child_of(dblist, pptr) == oldnode_ptr) { - if (oldnode_ptr->brother) { + if (child_of(dblist, pptr) == oldnode_ptr) + { + if (oldnode_ptr->brother) + { pptr->child = node_offset(brother_of(dblist, oldnode_ptr), pptr); - } else + } + else pptr->child = 0; - } else { + } + else + { for (nptr = child_of(dblist, pptr); nptr && (brother_of(dblist, nptr) != oldnode_ptr); nptr = brother_of(dblist, nptr)) ; - if (nptr) { - if (oldnode_ptr->brother) { + if (nptr) + { + if (oldnode_ptr->brother) + { nptr->brother = node_offset(brother_of(dblist, oldnode_ptr), nptr); - } else + } + else nptr->brother = 0; - } else if (member_of(pptr) == oldnode_ptr) { - if (oldnode_ptr->brother) { + } + else if (member_of(pptr) == oldnode_ptr) + { + if (oldnode_ptr->brother) + { pptr->member = node_offset(brother_of(dblist, oldnode_ptr), pptr); - } else + } + else pptr->member = 0; - } else { + } + else + { for (nptr = member_of(pptr); nptr && (brother_of(dblist, nptr) != oldnode_ptr); nptr = brother_of(dblist, nptr)) ; - if (nptr) { - if (oldnode_ptr->brother) { + if (nptr) + { + if (oldnode_ptr->brother) + { nptr->brother = node_offset(brother_of(dblist, oldnode_ptr), nptr); - } else + } + else nptr->brother = 0; - } else { + } + else + { status = TreeINVTREE; goto cleanup; } @@ -207,7 +235,8 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) { } static int FixParentState(PINO_DATABASE *dblist, NODE *parent_ptr, - NODE *child_ptr) { + NODE *child_ptr) +{ int status = 1; NID parent_nid; NID child_nid; @@ -229,7 +258,8 @@ static int FixParentState(PINO_DATABASE *dblist, NODE *parent_ptr, ****************************************************/ parent_state = _TreeIsOn(dblist, *(int *)&parent_nid) & 1; status = _TreeGetNci(dblist, *(int *)&child_nid, child_itm_list); - if (status & 1) { + if (status & 1) + { child_parent_state = ((child_flags & NciM_PARENT_STATE) == 0); if (child_parent_state != parent_state) status = tree_set_parent_state(dblist, child_ptr, !parent_state); diff --git a/treeshr/TreeSegments.c b/treeshr/TreeSegments.c index afa7cd63ea..e0a51a8dbf 100644 --- a/treeshr/TreeSegments.c +++ b/treeshr/TreeSegments.c @@ -98,14 +98,15 @@ found. They are set to -1 to indicate that there is no data for xxxx stored. ********************************************************/ #ifdef WORDS_BIGENDIAN -#define _WORDS_BIGENDIAN // can be activated to test WORDS_BIGENDIAN branch on - // little endian machines +#define _WORDS_BIGENDIAN // can be activated to test WORDS_BIGENDIAN branch on little endian machines #define ALLOCATE_BUFFER(SIZE, BUFFER) char *BUFFER = malloc(SIZE) inline static void endianTransfer(const char *buffer_in, const size_t size, - const int length, char *buffer_out) { + const int length, char *buffer_out) +{ char *bptr = (char *)buffer_out; int i; - switch (length) { + switch (length) + { case 2: for (i = 0; i < (int)size / length; i++) putint16(&bptr, &((int16_t *)buffer_in)[i]); @@ -120,36 +121,39 @@ inline static void endianTransfer(const char *buffer_in, const size_t size, break; } } -#define CHECK_ENDIAN(BUFFER, SIZE, LENGTH, DTYPE) \ - do { \ - if (LENGTH > 1 && DTYPE != DTYPE_T && DTYPE != DTYPE_IDENT && \ - DTYPE != DTYPE_PATH) \ - endianTransfer((char *)BUFFER, SIZE, LENGTH, (char *)BUFFER); \ +#define CHECK_ENDIAN(BUFFER, SIZE, LENGTH, DTYPE) \ + do \ + { \ + if (LENGTH > 1 && DTYPE != DTYPE_T && DTYPE != DTYPE_IDENT && \ + DTYPE != DTYPE_PATH) \ + endianTransfer((char *)BUFFER, SIZE, LENGTH, (char *)BUFFER); \ } while (0) -#define CHECK_ENDIAN_TRANSFER(BUFFER_IN, SIZE, LENGTH, DTYPE, BUFFER_OUT) \ - do { \ - if (LENGTH > 1 && DTYPE != DTYPE_T && DTYPE != DTYPE_IDENT && \ - DTYPE != DTYPE_PATH) \ - endianTransfer((char *)BUFFER_IN, SIZE, LENGTH, BUFFER_OUT); \ - else \ - memcpy(BUFFER_OUT, BUFFER_IN, SIZE); \ +#define CHECK_ENDIAN_TRANSFER(BUFFER_IN, SIZE, LENGTH, DTYPE, BUFFER_OUT) \ + do \ + { \ + if (LENGTH > 1 && DTYPE != DTYPE_T && DTYPE != DTYPE_IDENT && \ + DTYPE != DTYPE_PATH) \ + endianTransfer((char *)BUFFER_IN, SIZE, LENGTH, BUFFER_OUT); \ + else \ + memcpy(BUFFER_OUT, BUFFER_IN, SIZE); \ } while (0) #define FREE_BUFFER(BUFFER) free(BUFFER) #else #define ALLOCATE_BUFFER(SIZE, BUFFER) char *BUFFER -#define CHECK_ENDIAN(BUFFER, SIZE, LENGTH, DTYPE) \ - { /**/ \ +#define CHECK_ENDIAN(BUFFER, SIZE, LENGTH, DTYPE) \ + { /**/ \ } -#define CHECK_ENDIAN_TRANSFER(BUFFER_IN, SIZE, LENGTH, DTYPE, BUFFER_OUT) \ +#define CHECK_ENDIAN_TRANSFER(BUFFER_IN, SIZE, LENGTH, DTYPE, BUFFER_OUT) \ BUFFER_OUT = (char *)BUFFER_IN -#define FREE_BUFFER(BUFFER) \ - { /**/ \ +#define FREE_BUFFER(BUFFER) \ + { /**/ \ } #endif #define swap_inplace(dir, type, buf, param) dir##type(&buf, &(param)) typedef ARRAY_COEFF(char, 8) A_COEFF_TYPE; -typedef struct vars { +typedef struct vars +{ PINO_DATABASE *dblist; NID *nid_ptr; TREE_INFO *tinfo; @@ -176,20 +180,20 @@ typedef struct vars { size_t xnci_len; int64_t xnci_header_offset; } vars_t; -#define INIT_VARS \ - vars_t _vars = {0}; \ - vars_t *vars = &_vars; \ - _vars.dblist = (PINO_DATABASE *)dbid; \ - _vars.nid_ptr = (NID *)&nid; \ - _vars.xnci = xnci; \ - _vars.xnci_len = xnci ? strlen(xnci) : 0; \ - _vars.nci_locked = 0; \ - if (_vars.xnci && \ - (_vars.xnci_len < 1 || _vars.xnci_len > NAMED_ATTRIBUTE_NAME_SIZE)) \ - return TreeFAILURE; \ +#define INIT_VARS \ + vars_t _vars = {0}; \ + vars_t *vars = &_vars; \ + _vars.dblist = (PINO_DATABASE *)dbid; \ + _vars.nid_ptr = (NID *)&nid; \ + _vars.xnci = xnci; \ + _vars.xnci_len = xnci ? strlen(xnci) : 0; \ + _vars.nci_locked = 0; \ + if (_vars.xnci && \ + (_vars.xnci_len < 1 || _vars.xnci_len > NAMED_ATTRIBUTE_NAME_SIZE)) \ + return TreeFAILURE; \ int status; -#define INIT_WRITE_VARS \ - INIT_VARS _vars.idx = idx; \ +#define INIT_WRITE_VARS \ + INIT_VARS _vars.idx = idx; \ _vars.rows_filled = rows_filled; ////////////////////////////////////////////////////////////////////// @@ -197,12 +201,14 @@ typedef struct vars { ////////////////////////////////////////////////////////////////////// static int read_property(TREE_INFO *tinfo, const int64_t offset, char *buffer, - const int length) { + const int length) +{ if (!tinfo->data_file) return MDSplusFATAL; int status; int deleted = B_TRUE; - while (deleted) { + while (deleted) + { if (MDS_IO_READ_X(tinfo->data_file->get, offset, buffer, length, &deleted) != length) return TreeFAILURE; @@ -213,32 +219,39 @@ static int read_property(TREE_INFO *tinfo, const int64_t offset, char *buffer, } inline static int read_property_safe(TREE_INFO *tinfo, const int64_t offset, - char *buffer, const int length) { + char *buffer, const int length) +{ if (offset > -1) return read_property(tinfo, offset, buffer, length); return TreeFAILURE; } -typedef struct { +typedef struct +{ TREE_INFO *tinfo; int64_t offset; } write_cleanup_t; -static void unlock_datafile(void *c) { +static void unlock_datafile(void *c) +{ const write_cleanup_t *s = (write_cleanup_t *)c; if (s->offset != -1) TreeUnLockDatafile(s->tinfo, 0, s->offset); } static int write_property(TREE_INFO *tinfo, int64_t *offset, const char *buffer, - const int length) { + const int length) +{ if (!tinfo->data_file) return MDSplusFATAL; int status; write_cleanup_t c = {tinfo, -1}; pthread_cleanup_push(unlock_datafile, &c); - if (*offset == -1) { + if (*offset == -1) + { TreeLockDatafile(tinfo, 0, c.offset = 0); *offset = MDS_IO_LSEEK(tinfo->data_file->put, 0, SEEK_END); - } else { + } + else + { TreeLockDatafile(tinfo, 0, c.offset = *offset); MDS_IO_LSEEK(tinfo->data_file->put, *offset, SEEK_SET); } @@ -250,31 +263,33 @@ static int write_property(TREE_INFO *tinfo, int64_t *offset, const char *buffer, return status; } -#define swap_ext_attr(dir, buf, ext_attr) \ - { \ - char *ptr = buf; \ - int i; \ - swap_inplace(dir, int64, ptr, ext_attr->next_ea_offset); \ - for (i = 0; i < FACILITIES_PER_EA; i++) \ - swap_inplace(dir, int64, ptr, ext_attr->facility_offset[i]); \ - for (i = 0; i < FACILITIES_PER_EA; i++) \ - swap_inplace(dir, int32, ptr, ext_attr->facility_length[i]); \ +#define swap_ext_attr(dir, buf, ext_attr) \ + { \ + char *ptr = buf; \ + int i; \ + swap_inplace(dir, int64, ptr, ext_attr->next_ea_offset); \ + for (i = 0; i < FACILITIES_PER_EA; i++) \ + swap_inplace(dir, int64, ptr, ext_attr->facility_offset[i]); \ + for (i = 0; i < FACILITIES_PER_EA; i++) \ + swap_inplace(dir, int32, ptr, ext_attr->facility_length[i]); \ } #define EXTENDED_ATTRIBUTES_SIZE 8 + FACILITIES_PER_EA *(8 + 4) int TreePutExtendedAttributes(TREE_INFO *tinfo, EXTENDED_ATTRIBUTES *ext_attr, - int64_t *offset) { + int64_t *offset) +{ // private but used in TreeGet/PutRecord char buffer[EXTENDED_ATTRIBUTES_SIZE]; swap_ext_attr(put, buffer, ext_attr); return write_property(tinfo, offset, buffer, sizeof(buffer)); } int TreeGetExtendedAttributes(TREE_INFO *tinfo, const int64_t offset, - EXTENDED_ATTRIBUTES *ext_attr) { + EXTENDED_ATTRIBUTES *ext_attr) +{ // private but used in TreeGet/PutRecord char buffer[EXTENDED_ATTRIBUTES_SIZE]; const int status = read_property_safe(tinfo, offset, buffer, sizeof(buffer)); - if - STATUS_OK swap_ext_attr(get, buffer, ext_attr); + if (STATUS_OK) + swap_ext_attr(get, buffer, ext_attr); return status; } @@ -282,45 +297,53 @@ int TreeGetExtendedAttributes(TREE_INFO *tinfo, const int64_t offset, * current contents of the attr index. If not, make an empty index and flag that * a new index needs to be written. */ -inline static int load_extended_nci(vars_t *vars) { +inline static int load_extended_nci(vars_t *vars) +{ if (!(vars->local_nci.flags2 & NciM_EXTENDED_NCI)) return TreeFAILURE; return TreeGetExtendedAttributes( vars->tinfo, RfaToSeek(vars->local_nci.DATA_INFO.DATA_LOCATION.rfa), &vars->attr); } -inline static void begin_extended_nci(vars_t *vars) { - if - IS_OK(load_extended_nci(vars)) { - vars->attr_offset = - RfaToSeek(vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); - if (vars->attr.facility_offset[STANDARD_RECORD_FACILITY] != -1) { - vars->attr.facility_offset[STANDARD_RECORD_FACILITY] = -1; - vars->attr.facility_length[STANDARD_RECORD_FACILITY] = 0; - vars->attr_update = 1; - } +inline static void begin_extended_nci(vars_t *vars) +{ + if (IS_OK(load_extended_nci(vars))) + { + vars->attr_offset = + RfaToSeek(vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); + if (vars->attr.facility_offset[STANDARD_RECORD_FACILITY] != -1) + { + vars->attr.facility_offset[STANDARD_RECORD_FACILITY] = -1; + vars->attr.facility_length[STANDARD_RECORD_FACILITY] = 0; + vars->attr_update = 1; } - else { + } + else + { memset(&vars->attr, -1, sizeof(vars->attr)); vars->attr_update = 1; vars->attr_offset = -1; } } -inline static int check_segment_remote(vars_t *vars) { - if (vars->dblist->remote) { +inline static int check_segment_remote(vars_t *vars) +{ + if (vars->dblist->remote) + { printf("Segmented records are not supported using thick client mode\n"); return TreeFAILURE; } return TreeSUCCESS; } -inline static int load_info_ptr(vars_t *vars) { +inline static int load_info_ptr(vars_t *vars) +{ vars->nidx = nid_to_tree_idx(vars->dblist, vars->nid_ptr, &vars->tinfo); if (!vars->tinfo) return TreeNNF; // TODO verify errorcode return TreeSUCCESS; } -inline static int load_node_ptr(vars_t *vars) { +inline static int load_node_ptr(vars_t *vars) +{ vars->node_ptr = nid_to_node(vars->dblist, vars->nid_ptr); if (!vars->node_ptr) return TreeNNF; @@ -328,7 +351,8 @@ inline static int load_node_ptr(vars_t *vars) { return TreeSUCCESS; } -inline static int open_datafile_read(vars_t *vars) { +inline static int open_datafile_read(vars_t *vars) +{ if (!(IS_OPEN(vars->dblist))) return TreeNOT_OPEN; int status; @@ -343,7 +367,8 @@ inline static int open_datafile_read(vars_t *vars) { return TreeSUCCESS; } -static int open_datafile_write0(vars_t *vars) { +static int open_datafile_write0(vars_t *vars) +{ if (vars->dblist->open_readonly) return TreeREADONLY; int status; @@ -358,14 +383,18 @@ static int open_datafile_write0(vars_t *vars) { TreeGetViewDate(&vars->saved_viewdate); RETURN_IF_NOT_OK(tree_get_and_lock_nci(vars->tinfo, vars->nidx, &vars->local_nci, &vars->nci_locked)); - if (vars->dblist->shotid == -1) { + if (vars->dblist->shotid == -1) + { if (vars->local_nci.flags & NciM_NO_WRITE_MODEL) return TreeNOWRITEMODEL; - } else { + } + else + { if (vars->local_nci.flags & NciM_NO_WRITE_SHOT) return TreeNOWRITESHOT; } - if (vars->local_nci.flags & NciM_WRITE_ONCE) { + if (vars->local_nci.flags & NciM_WRITE_ONCE) + { if (vars->local_nci.length) return TreeNOOVERWRITE; vars->local_nci.flags &= ~NciM_WRITE_ONCE; @@ -373,47 +402,53 @@ static int open_datafile_write0(vars_t *vars) { return TreeSUCCESS; } -inline static int open_datafile_write1(vars_t *vars) { +inline static int open_datafile_write1(vars_t *vars) +{ if (vars->tinfo->data_file ? (!vars->tinfo->data_file->open_for_write) : 1) return TreeOpenDatafileW(vars->tinfo, &vars->stv, 0); return TreeSUCCESS; } -inline static void set_compress(vars_t *vars) { +inline static void set_compress(vars_t *vars) +{ vars->compress = (vars->local_nci.flags & NciM_COMPRESS_ON_PUT) && (vars->local_nci.flags & NciM_COMPRESS_SEGMENTS) && !(vars->local_nci.flags & NciM_DO_NOT_COMPRESS); } -#define NAMED_ATTRIBUTES_INDEX_SIZE \ +#define NAMED_ATTRIBUTES_INDEX_SIZE \ 8 + NAMED_ATTRIBUTES_PER_INDEX *(NAMED_ATTRIBUTE_NAME_SIZE + 8 + 4) -#define swap_named_attr(dir, buf, index) \ - { \ - char *ptr = buf; \ - int i; \ - swap_inplace(dir, int64, ptr, index->previous_offset); \ - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { \ - dir##chars(&ptr, index->attribute[i].name, NAMED_ATTRIBUTE_NAME_SIZE); \ - swap_inplace(dir, int64, ptr, index->attribute[i].offset); \ - swap_inplace(dir, int32, ptr, index->attribute[i].length); \ - } \ +#define swap_named_attr(dir, buf, index) \ + { \ + char *ptr = buf; \ + int i; \ + swap_inplace(dir, int64, ptr, index->previous_offset); \ + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) \ + { \ + dir##chars(&ptr, index->attribute[i].name, NAMED_ATTRIBUTE_NAME_SIZE); \ + swap_inplace(dir, int64, ptr, index->attribute[i].offset); \ + swap_inplace(dir, int32, ptr, index->attribute[i].length); \ + } \ } static int get_named_attributes_index(TREE_INFO *tinfo, const int64_t offset, - NAMED_ATTRIBUTES_INDEX *index) { + NAMED_ATTRIBUTES_INDEX *index) +{ char buffer[NAMED_ATTRIBUTES_INDEX_SIZE]; const int status = read_property_safe(tinfo, offset, buffer, sizeof(buffer)); - if - STATUS_OK swap_named_attr(get, buffer, index); + if (STATUS_OK) + swap_named_attr(get, buffer, index); return status; } static int put_named_attributes_index(TREE_INFO *tinfo, const NAMED_ATTRIBUTES_INDEX *index, - int64_t *offset) { + int64_t *offset) +{ char buffer[NAMED_ATTRIBUTES_INDEX_SIZE]; swap_named_attr(put, buffer, index); return write_property(tinfo, offset, buffer, sizeof(buffer)); } -static int get_top_index(vars_t *vars, NAMED_ATTRIBUTES_INDEX *index) { +static int get_top_index(vars_t *vars, NAMED_ATTRIBUTES_INDEX *index) +{ if (vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY] == -1) return TreeFAILURE; return get_named_attributes_index( @@ -421,19 +456,23 @@ static int get_top_index(vars_t *vars, NAMED_ATTRIBUTES_INDEX *index) { index); } -static inline int get_xnci_names(vars_t *vars, mdsdsc_xd_t *value) { +static inline int get_xnci_names(vars_t *vars, mdsdsc_xd_t *value) +{ NAMED_ATTRIBUTES_INDEX index; - if - IS_NOT_OK(get_top_index(vars, &index)) return TreeFAILURE; - struct _namelist { + if (IS_NOT_OK(get_top_index(vars, &index))) + return TreeFAILURE; + struct _namelist + { char name[NAMED_ATTRIBUTE_NAME_SIZE + 1]; struct _namelist *next; } *namelist = 0; size_t longestattname = 0; int numnames = 0; size_t i; - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { - if (index.attribute[i].name[0] != 0 && index.attribute[i].length != -1) { + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) + { + if (index.attribute[i].name[0] != 0 && index.attribute[i].length != -1) + { size_t len = strlen(index.attribute[i].name); struct _namelist *p = malloc(sizeof(struct _namelist)); memcpy(p->name, index.attribute[i].name, sizeof(p->name)); @@ -450,7 +489,8 @@ static inline int get_xnci_names(vars_t *vars, mdsdsc_xd_t *value) { (unsigned int)(longestattname * numnames)); struct _namelist *p, *pnext; char *np; - for (p = namelist, np = names; p; p = pnext, np += longestattname) { + for (p = namelist, np = names; p; p = pnext, np += longestattname) + { size_t i; pnext = p->next; memcpy(np, p->name, longestattname); @@ -463,15 +503,19 @@ static inline int get_xnci_names(vars_t *vars, mdsdsc_xd_t *value) { free(names); return TreeSUCCESS; } -static int get_xnci(vars_t *vars, mdsdsc_xd_t *value, int is_offset) { +static int get_xnci(vars_t *vars, mdsdsc_xd_t *value, int is_offset) +{ NAMED_ATTRIBUTES_INDEX index; - if - IS_NOT_OK(get_top_index(vars, &index)) return TreeFAILURE; + if (IS_NOT_OK(get_top_index(vars, &index))) + return TreeFAILURE; size_t i, j; int found_index = -1; - while (found_index == -1) { - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { - for (j = 0; j < vars->xnci_len; j++) { + while (found_index == -1) + { + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) + { + for (j = 0; j < vars->xnci_len; j++) + { if (tolower(vars->xnci[j]) != tolower(index.attribute[i].name[j])) break; } @@ -480,23 +524,29 @@ static int get_xnci(vars_t *vars, mdsdsc_xd_t *value, int is_offset) { } if (i < NAMED_ATTRIBUTES_PER_INDEX) found_index = i; - else if (index.previous_offset != -1) { - if - IS_NOT_OK(get_named_attributes_index(vars->tinfo, index.previous_offset, - &index)) - break; - } else + else if (index.previous_offset != -1) + { + if (IS_NOT_OK(get_named_attributes_index(vars->tinfo, index.previous_offset, + &index))) + break; + } + else break; } if (found_index == -1) return TreeFAILURE; - if (is_offset) { - if (index.attribute[found_index].length == -1) { + if (is_offset) + { + if (index.attribute[found_index].length == -1) + { vars->xnci_header_offset = index.attribute[found_index].offset; return TreeSUCCESS; - } else + } + else return TreeNOSEGMENTS; - } else { + } + else + { if (index.attribute[found_index].length == -1) return TreeBADRECORD; else @@ -505,15 +555,20 @@ static int get_xnci(vars_t *vars, mdsdsc_xd_t *value, int is_offset) { index.attribute[found_index].length, value); } } -static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { +static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) +{ int status = TreeSUCCESS; int value_length = 0; int64_t value_offset = -1; - if (is_offset) { + if (is_offset) + { value_offset = vars->xnci_header_offset; value_length = -1; - } else { - if (value) { // NULL means delete + } + else + { + if (value) + { // NULL means delete RETURN_IF_NOT_OK(tree_put_dsc( vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, (mdsdsc_t *)value, &value_offset, &value_length, vars->compress)); @@ -523,12 +578,15 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { * make an empty index and flag that a new index needs to be written. * Otherwise get the current contents of the attr */ - if (vars->attr_offset == -1) { + if (vars->attr_offset == -1) + { if (value_length == 0) return status; // has not xnci; nothing to delete if (((vars->local_nci.flags2 & NciM_EXTENDED_NCI) == 0) && - vars->local_nci.length > 0) { - if (vars->local_nci.flags2 & NciM_DATA_IN_ATT_BLOCK) { + vars->local_nci.length > 0) + { + if (vars->local_nci.flags2 & NciM_DATA_IN_ATT_BLOCK) + { EMPTYXD(dsc); mdsdsc_t *dptr; dtype_t dsc_dtype = DTYPE_DSC; @@ -542,8 +600,10 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { dptr->pointer = (char *)dptr + sizeof(mdsdsc_t); memcpy(dptr->pointer, vars->local_nci.DATA_INFO.DATA_IN_RECORD.data, dptr->length); - if (dptr->dtype != DTYPE_T) { - switch (dptr->length) { + if (dptr->dtype != DTYPE_T) + { + switch (dptr->length) + { case 2: *(int16_t *)dptr->pointer = swapint16(dptr->pointer); break; @@ -561,11 +621,14 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { &vars->attr.facility_length[STANDARD_RECORD_FACILITY], vars->compress); vars->local_nci.flags2 &= ~NciM_DATA_IN_ATT_BLOCK; - } else { + } + else + { int retsize; int nodenum; int length = vars->local_nci.DATA_INFO.DATA_LOCATION.record_length; - if (length > 0) { + if (length > 0) + { char *data = NULL; INIT_AND_FREEXD_ON_EXIT(xd); FREE_ON_EXIT(data); @@ -573,27 +636,30 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { status = TreeGetDatafile( vars->tinfo, vars->local_nci.DATA_INFO.DATA_LOCATION.rfa, &length, data, &retsize, &nodenum, vars->local_nci.flags2); - if - STATUS_NOT_OK - status = TreeBADRECORD; + if (STATUS_NOT_OK) + status = TreeBADRECORD; else if (!(vars->local_nci.flags2 & NciM_NON_VMS) && - ((retsize != length) || (nodenum != vars->nidx))) status = - TreeBADRECORD; - else if IS_OK(MdsSerializeDscIn(data, &xd)) status = TreeSUCCESS; - else status = TreeBADRECORD; + ((retsize != length) || (nodenum != vars->nidx))) + status = + TreeBADRECORD; + else if (IS_OK(MdsSerializeDscIn(data, &xd))) + status = TreeSUCCESS; + else + status = TreeBADRECORD; FREE_NOW(data); - if - STATUS_OK { - status = tree_put_dsc( - vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, - (mdsdsc_t *)&xd, - &vars->attr.facility_offset[STANDARD_RECORD_FACILITY], - &vars->attr.facility_length[STANDARD_RECORD_FACILITY], - vars->compress); - } + if (STATUS_OK) + { + status = tree_put_dsc( + vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, + (mdsdsc_t *)&xd, + &vars->attr.facility_offset[STANDARD_RECORD_FACILITY], + &vars->attr.facility_length[STANDARD_RECORD_FACILITY], + vars->compress); + } FREE_NOW(xd); } - if (length <= 0 || STATUS_NOT_OK) { + if (length <= 0 || STATUS_NOT_OK) + { vars->attr.facility_offset[STANDARD_RECORD_FACILITY] = 0; vars->attr.facility_length[STANDARD_RECORD_FACILITY] = 0; vars->local_nci.length = 0; @@ -601,80 +667,93 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { } } } - } else + } + else vars->attr_offset = RfaToSeek(vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); /* See if the node currently has an named attr header record. * If not, make an empty named attr header and flag that a new one needs to be * written. */ NAMED_ATTRIBUTES_INDEX top_index, index; - if - IS_OK(get_top_index(vars, &top_index)) { - vars->index_offset = - vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; - /*** See if the node currently has a value for this attribute. ***/ - int found_index = -1; - index = top_index; - while (vars->index_offset != -1) { - int i; - size_t j; - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { - for (j = 0; j < vars->xnci_len; j++) - if (tolower(vars->xnci[j]) != tolower(index.attribute[i].name[j])) - break; - if (j == vars->xnci_len && index.attribute[i].name[j] == 0) + if (IS_OK(get_top_index(vars, &top_index))) + { + vars->index_offset = + vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; + /*** See if the node currently has a value for this attribute. ***/ + int found_index = -1; + index = top_index; + while (vars->index_offset != -1) + { + int i; + size_t j; + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) + { + for (j = 0; j < vars->xnci_len; j++) + if (tolower(vars->xnci[j]) != tolower(index.attribute[i].name[j])) break; - } - if (i < NAMED_ATTRIBUTES_PER_INDEX) { - found_index = i; + if (j == vars->xnci_len && index.attribute[i].name[j] == 0) break; - } else if (index.previous_offset != -1) { - int64_t new_offset = index.previous_offset; - if - IS_NOT_OK(get_named_attributes_index(vars->tinfo, - index.previous_offset, &index)) + } + if (i < NAMED_ATTRIBUTES_PER_INDEX) + { + found_index = i; + break; + } + else if (index.previous_offset != -1) + { + int64_t new_offset = index.previous_offset; + if (IS_NOT_OK(get_named_attributes_index(vars->tinfo, + index.previous_offset, &index))) break; - vars->index_offset = new_offset; - } else + vars->index_offset = new_offset; + } + else + break; + } + /*** If name exists just replace the value else find an empty slot ***/ + if (found_index != -1) + { + index.attribute[found_index].offset = value_offset; + index.attribute[found_index].length = value_length; + status = put_named_attributes_index(vars->tinfo, &index, + &vars->index_offset); + } + else + { + if (value_length == 0) + return status; // nothing to delete + int i; + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) + { + if (top_index.attribute[i].name[0] == 0) break; } - /*** If name exists just replace the value else find an empty slot ***/ - if (found_index != -1) { - index.attribute[found_index].offset = value_offset; - index.attribute[found_index].length = value_length; - status = put_named_attributes_index(vars->tinfo, &index, - &vars->index_offset); - } else { - if (value_length == 0) - return status; // nothing to delete - int i; - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { - if (top_index.attribute[i].name[0] == 0) - break; - } - if (i < NAMED_ATTRIBUTES_PER_INDEX) { - vars->index_offset = - vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; - } else { - memset(&top_index, 0, sizeof(index)); - top_index.previous_offset = - vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; - vars->index_offset = -1; - vars->attr_update = 1; - i = 0; - } - strcpy(top_index.attribute[i].name, vars->xnci); - top_index.attribute[i].offset = value_offset; - top_index.attribute[i].length = value_length; - status = put_named_attributes_index(vars->tinfo, &top_index, - &vars->index_offset); - if - STATUS_OK + if (i < NAMED_ATTRIBUTES_PER_INDEX) + { + vars->index_offset = + vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; + } + else + { + memset(&top_index, 0, sizeof(index)); + top_index.previous_offset = + vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY]; + vars->index_offset = -1; + vars->attr_update = 1; + i = 0; + } + strcpy(top_index.attribute[i].name, vars->xnci); + top_index.attribute[i].offset = value_offset; + top_index.attribute[i].length = value_length; + status = put_named_attributes_index(vars->tinfo, &top_index, + &vars->index_offset); + if (STATUS_OK) vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY] = vars->index_offset; - } } - else { + } + else + { memset(&top_index, 0, sizeof(top_index)); vars->attr.facility_offset[NAMED_ATTRIBUTES_FACILITY] = vars->index_offset = -1; @@ -690,40 +769,47 @@ static int set_xnci(vars_t *vars, mdsdsc_t *value, int is_offset) { return status; } -static void unlock_nci(void *vars_in) { +static void unlock_nci(void *vars_in) +{ vars_t *vars = (vars_t *)vars_in; tree_unlock_nci(vars->tinfo, 0, vars->nidx, &vars->nci_locked); } #define CLEANUP_NCI_PUSH pthread_cleanup_push(unlock_nci, (void *)vars) #define CLEANUP_NCI_POP pthread_cleanup_pop(vars->nci_locked) -int _TreeGetXNci(void *dbid, int nid, const char *xnci, mdsdsc_xd_t *value) { +int _TreeGetXNci(void *dbid, int nid, const char *xnci, mdsdsc_xd_t *value) +{ if (!xnci) return TreeFAILURE; INIT_VARS; RETURN_IF_NOT_OK(open_datafile_read(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) return TreeFAILURE; + if (IS_NOT_OK(load_extended_nci(vars))) + return TreeFAILURE; const char *attnames = XNCI_ATTRIBUTE_NAMES; size_t i, len = strlen(xnci); int getnames; - if (len == strlen(attnames)) { - for (i = 0; i < len; i++) { + if (len == strlen(attnames)) + { + for (i = 0; i < len; i++) + { if (tolower(xnci[i]) != attnames[i]) break; } getnames = (i == len); - } else + } + else getnames = FALSE; if (getnames) return get_xnci_names(vars, value); else return get_xnci(vars, value, FALSE); } -int TreeGetXNci(int nid, const char *xnci, mdsdsc_xd_t *value) { +int TreeGetXNci(int nid, const char *xnci, mdsdsc_xd_t *value) +{ return _TreeGetXNci(*TreeCtx(), nid, xnci, value); } -int _TreeSetXNci(void *dbid, int nid, const char *xnci, mdsdsc_t *value) { +int _TreeSetXNci(void *dbid, int nid, const char *xnci, mdsdsc_t *value) +{ if (!xnci) return TreeFAILURE; INIT_VARS; @@ -734,24 +820,26 @@ int _TreeSetXNci(void *dbid, int nid, const char *xnci, mdsdsc_t *value) { begin_extended_nci(vars); vars->index_offset = -1; status = set_xnci(vars, value, FALSE); - if (STATUS_OK && vars->attr_update) { + if (STATUS_OK && vars->attr_update) + { status = TreePutExtendedAttributes(vars->tinfo, &vars->attr, &vars->attr_offset); - if - STATUS_OK { - SeekToRfa(vars->attr_offset, - vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); - vars->local_nci.flags2 |= NciM_EXTENDED_NCI; - status = tree_put_nci(vars->tinfo, vars->nidx, &vars->local_nci, - &vars->nci_locked); - vars->nci_locked = FALSE; - } + if (STATUS_OK) + { + SeekToRfa(vars->attr_offset, + vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); + vars->local_nci.flags2 |= NciM_EXTENDED_NCI; + status = tree_put_nci(vars->tinfo, vars->nidx, &vars->local_nci, + &vars->nci_locked); + vars->nci_locked = FALSE; + } } end:; CLEANUP_NCI_POP; return status; } -int TreeSetXNci(int nid, const char *xnci, mdsdsc_t *value) { +int TreeSetXNci(int nid, const char *xnci, mdsdsc_t *value) +{ return _TreeSetXNci(*TreeCtx(), nid, xnci, value); } @@ -759,114 +847,126 @@ int TreeSetXNci(int nid, const char *xnci, mdsdsc_t *value) { //////////////////////////// SEGMENTS ////////////////////////////// //////////////////////////////////////////////////////////////////// -#define swap_header(dir, buf, hdr) \ - { \ - char *ptr = buf; \ - int i; \ - swap_inplace(dir, int8, ptr, hdr->dtype); \ - swap_inplace(dir, int8, ptr, hdr->dimct); \ - for (i = 0; i < MAX_DIMS; i++) \ - swap_inplace(dir, int32, ptr, hdr->dims[i]); \ - swap_inplace(dir, int16, ptr, hdr->length); \ - swap_inplace(dir, int32, ptr, hdr->idx); \ - swap_inplace(dir, int32, ptr, hdr->next_row); \ - swap_inplace(dir, int64, ptr, hdr->index_offset); \ - swap_inplace(dir, int64, ptr, hdr->data_offset); \ - swap_inplace(dir, int64, ptr, hdr->dim_offset); \ +#define swap_header(dir, buf, hdr) \ + { \ + char *ptr = buf; \ + int i; \ + swap_inplace(dir, int8, ptr, hdr->dtype); \ + swap_inplace(dir, int8, ptr, hdr->dimct); \ + for (i = 0; i < MAX_DIMS; i++) \ + swap_inplace(dir, int32, ptr, hdr->dims[i]); \ + swap_inplace(dir, int16, ptr, hdr->length); \ + swap_inplace(dir, int32, ptr, hdr->idx); \ + swap_inplace(dir, int32, ptr, hdr->next_row); \ + swap_inplace(dir, int64, ptr, hdr->index_offset); \ + swap_inplace(dir, int64, ptr, hdr->data_offset); \ + swap_inplace(dir, int64, ptr, hdr->dim_offset); \ } #define SEGMENT_HEADER_SIZE 1 + 1 + MAX_DIMS * 4 + 2 + 4 + 4 + 8 + 8 + 8 static int get_segment_header(TREE_INFO *tinfo, const int64_t offset, - SEGMENT_HEADER *hdr) { + SEGMENT_HEADER *hdr) +{ char buffer[SEGMENT_HEADER_SIZE]; const int status = read_property_safe(tinfo, offset, buffer, sizeof(buffer)); - if - STATUS_OK swap_header(get, buffer, hdr); + if (STATUS_OK) + swap_header(get, buffer, hdr); return status; } static int put_segment_header(TREE_INFO *tinfo, const SEGMENT_HEADER *hdr, - int64_t *offset) { + int64_t *offset) +{ // getenv("NEXT_ROW_FIX") has been removed in favour of TreeSetRowsFilled char buffer[SEGMENT_HEADER_SIZE]; swap_header(put, buffer, hdr); return write_property(tinfo, offset, buffer, sizeof(buffer)); } -static int load_segment_header(vars_t *vars) { - if (vars->xnci) { +static int load_segment_header(vars_t *vars) +{ + if (vars->xnci) + { int status = get_xnci(vars, NULL, TRUE); - if - STATUS_OK - status = - get_segment_header(vars->tinfo, vars->xnci_header_offset, &vars->shead); - if - STATUS_NOT_OK - vars->xnci_header_offset = -1; + if (STATUS_OK) + status = + get_segment_header(vars->tinfo, vars->xnci_header_offset, &vars->shead); + if (STATUS_NOT_OK) + vars->xnci_header_offset = -1; return status; - } else { + } + else + { const int status = get_segment_header( vars->tinfo, vars->attr.facility_offset[SEGMENTED_RECORD_FACILITY], &vars->shead); - if - STATUS_NOT_OK - vars->attr.facility_offset[SEGMENTED_RECORD_FACILITY] = -1; + if (STATUS_NOT_OK) + vars->attr.facility_offset[SEGMENTED_RECORD_FACILITY] = -1; return status; } } -static int save_segment_header(vars_t *vars) { - if (vars->xnci) { +static int save_segment_header(vars_t *vars) +{ + if (vars->xnci) + { const int status = put_segment_header(vars->tinfo, &vars->shead, &vars->xnci_header_offset); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; return set_xnci(vars, NULL, TRUE); - } else { + } + else + { return put_segment_header( vars->tinfo, &vars->shead, &vars->attr.facility_offset[SEGMENTED_RECORD_FACILITY]); } } -#define SEGMENT_INDEX_SIZE \ +#define SEGMENT_INDEX_SIZE \ 8 + 4 + SEGMENTS_PER_INDEX *(8 + 8 + 8 + 4 + 8 + 4 + 8 + 4 + 8 + 4) -#define swap_sindex(dir, buf, sindex) \ - { \ - char *ptr = buf; \ - int i; \ - swap_inplace(dir, int64, ptr, sindex->previous_offset); \ - swap_inplace(dir, int32, ptr, sindex->first_idx); \ - for (i = 0; i < SEGMENTS_PER_INDEX; i++) { \ - swap_inplace(dir, int64, ptr, sindex->segment[i].start); \ - swap_inplace(dir, int64, ptr, sindex->segment[i].end); \ - swap_inplace(dir, int64, ptr, sindex->segment[i].start_offset); \ - swap_inplace(dir, int32, ptr, sindex->segment[i].start_length); \ - swap_inplace(dir, int64, ptr, sindex->segment[i].end_offset); \ - swap_inplace(dir, int32, ptr, sindex->segment[i].end_length); \ - swap_inplace(dir, int64, ptr, sindex->segment[i].dimension_offset); \ - swap_inplace(dir, int32, ptr, sindex->segment[i].dimension_length); \ - swap_inplace(dir, int64, ptr, sindex->segment[i].data_offset); \ - swap_inplace(dir, int32, ptr, sindex->segment[i].rows); \ - } \ +#define swap_sindex(dir, buf, sindex) \ + { \ + char *ptr = buf; \ + int i; \ + swap_inplace(dir, int64, ptr, sindex->previous_offset); \ + swap_inplace(dir, int32, ptr, sindex->first_idx); \ + for (i = 0; i < SEGMENTS_PER_INDEX; i++) \ + { \ + swap_inplace(dir, int64, ptr, sindex->segment[i].start); \ + swap_inplace(dir, int64, ptr, sindex->segment[i].end); \ + swap_inplace(dir, int64, ptr, sindex->segment[i].start_offset); \ + swap_inplace(dir, int32, ptr, sindex->segment[i].start_length); \ + swap_inplace(dir, int64, ptr, sindex->segment[i].end_offset); \ + swap_inplace(dir, int32, ptr, sindex->segment[i].end_length); \ + swap_inplace(dir, int64, ptr, sindex->segment[i].dimension_offset); \ + swap_inplace(dir, int32, ptr, sindex->segment[i].dimension_length); \ + swap_inplace(dir, int64, ptr, sindex->segment[i].data_offset); \ + swap_inplace(dir, int32, ptr, sindex->segment[i].rows); \ + } \ } static int put_segment_index(TREE_INFO *tinfo, const SEGMENT_INDEX *sindex, - int64_t *offset) { + int64_t *offset) +{ char buffer[SEGMENT_INDEX_SIZE]; swap_sindex(put, buffer, sindex); return write_property(tinfo, offset, buffer, sizeof(buffer)); } static int get_segment_index(TREE_INFO *tinfo, const int64_t offset, - SEGMENT_INDEX *sindex) { + SEGMENT_INDEX *sindex) +{ char buffer[SEGMENT_INDEX_SIZE]; const int status = read_property_safe(tinfo, offset, buffer, sizeof(buffer)); - if - STATUS_OK swap_sindex(get, buffer, sindex); + if (STATUS_OK) + swap_sindex(get, buffer, sindex); return status; } -inline static int begin_finish(vars_t *vars) { +inline static int begin_finish(vars_t *vars) +{ int status; RETURN_IF_NOT_OK( put_segment_index(vars->tinfo, &vars->sindex, &vars->shead.index_offset)); RETURN_IF_NOT_OK(save_segment_header(vars)); - if (vars->attr_update) { + if (vars->attr_update) + { RETURN_IF_NOT_OK(TreePutExtendedAttributes(vars->tinfo, &vars->attr, &vars->attr_offset)); SeekToRfa(vars->attr_offset, vars->local_nci.DATA_INFO.DATA_LOCATION.rfa); @@ -888,7 +988,8 @@ static int saved_uic = 0; static void init_saved_uic() { saved_uic = (getgid() << 16) | getuid(); } #endif inline static void begin_local_nci(vars_t *vars, - const mdsdsc_a_t *initialValue) { + const mdsdsc_a_t *initialValue) +{ vars->local_nci.flags2 &= ~NciM_DATA_IN_ATT_BLOCK; vars->local_nci.dtype = initialValue->dtype; vars->local_nci.class = CLASS_R; @@ -905,22 +1006,26 @@ inline static void begin_local_nci(vars_t *vars, * If not, make an empty segment header and flag that a new one needs to be * written. */ -inline static int begin_segment_header(vars_t *vars, mdsdsc_a_t *initialValue) { - if - IS_OK(load_segment_header(vars)) { - if (initialValue->dtype != vars->shead.dtype) - return TreeFAILURE; // inconsistent dtype - if (initialValue->class == CLASS_A) { - if (initialValue->dimct != vars->shead.dimct) - return TreeFAILURE; // inconsistent dims - if (initialValue->dimct > 1) { - if (memcmp(vars->shead.dims, ((A_COEFF_TYPE *)initialValue)->m, - (initialValue->dimct - 1) * sizeof(int))) - return TreeFAILURE; - } +inline static int begin_segment_header(vars_t *vars, mdsdsc_a_t *initialValue) +{ + if (IS_OK(load_segment_header(vars))) + { + if (initialValue->dtype != vars->shead.dtype) + return TreeFAILURE; // inconsistent dtype + if (initialValue->class == CLASS_A) + { + if (initialValue->dimct != vars->shead.dimct) + return TreeFAILURE; // inconsistent dims + if (initialValue->dimct > 1) + { + if (memcmp(vars->shead.dims, ((A_COEFF_TYPE *)initialValue)->m, + (initialValue->dimct - 1) * sizeof(int))) + return TreeFAILURE; } } - else { + } + else + { memset(&vars->shead, 0, sizeof(vars->shead)); vars->shead.index_offset = -1; vars->shead.idx = -1; @@ -933,32 +1038,35 @@ inline static int begin_segment_header(vars_t *vars, mdsdsc_a_t *initialValue) { * If not, make an empty segment index and flag that a new one needs to be * written. */ -inline static int load_segment_index(vars_t *vars) { +inline static int load_segment_index(vars_t *vars) +{ if (vars->shead.index_offset == -1) return TreeFAILURE; return get_segment_index(vars->tinfo, vars->shead.index_offset, &vars->sindex); } -inline static void begin_segment_index(vars_t *vars) { - if - IS_NOT_OK(load_segment_index(vars)) { - vars->shead.index_offset = -1; - memset(&vars->sindex, -1, sizeof(vars->sindex)); - vars->sindex.first_idx = 0; - } +inline static void begin_segment_index(vars_t *vars) +{ + if (IS_NOT_OK(load_segment_index(vars))) + { + vars->shead.index_offset = -1; + memset(&vars->sindex, -1, sizeof(vars->sindex)); + vars->sindex.first_idx = 0; + } } -static int check_sinfo(vars_t *vars) { +static int check_sinfo(vars_t *vars) +{ if (vars->idx < 0 || vars->idx > vars->shead.idx) return TreeFAILURE; for (vars->index_offset = vars->shead.index_offset; vars->idx < vars->sindex.first_idx && - vars->sindex.previous_offset > 0;) { + vars->sindex.previous_offset > 0;) + { vars->index_offset = vars->sindex.previous_offset; - if - IS_NOT_OK(get_segment_index(vars->tinfo, vars->sindex.previous_offset, - &vars->sindex)) - return TreeFAILURE; + if (IS_NOT_OK(get_segment_index(vars->tinfo, vars->sindex.previous_offset, + &vars->sindex))) + return TreeFAILURE; } if (vars->idx < vars->sindex.first_idx) return TreeFAILURE; @@ -970,17 +1078,21 @@ static int read_segment(void *dbid, TREE_INFO *tinfo, int nid, mdsdsc_xd_t *segment, mdsdsc_xd_t *dim); static int begin_sinfo(vars_t *vars, mdsdsc_a_t *initialValue, int checkcompress(vars_t *vars, mdsdsc_xd_t *, - mdsdsc_xd_t *, mdsdsc_a_t *)) { + mdsdsc_xd_t *, mdsdsc_a_t *)) +{ int status = TreeSUCCESS; vars->add_length = 0; - if (vars->idx == -1) { + if (vars->idx == -1) + { vars->shead.idx++; vars->idx = vars->shead.idx; vars->add_length = (initialValue->class == CLASS_A) ? initialValue->arsize : 0; - } else if (vars->idx < -1 || vars->idx > vars->shead.idx) + } + else if (vars->idx < -1 || vars->idx > vars->shead.idx) return TreeBUFFEROVF; - else { + else + { /* TODO: Add support for updating an existing segment. * vars->add_length=new_length-old_length. */ /* Potentially use same storage area if old array is same size. */ @@ -995,14 +1107,17 @@ static int begin_sinfo(vars_t *vars, mdsdsc_a_t *initialValue, vars->shead.length = (initialValue->class == CLASS_A) ? initialValue->length : 0; int previous_length = -1; - if (vars->shead.idx > 0 && vars->shead.length != 0) { + if (vars->shead.idx > 0 && vars->shead.length != 0) + { int d; previous_length = vars->shead.length; for (d = 0; d < vars->shead.dimct; d++) previous_length *= vars->shead.dims[d]; - } else + } + else previous_length = -1; - if (initialValue->class == CLASS_A) { + if (initialValue->class == CLASS_A) + { if (initialValue->dimct == 1) vars->shead.dims[0] = initialValue->arsize / initialValue->length; else @@ -1013,34 +1128,36 @@ static int begin_sinfo(vars_t *vars, mdsdsc_a_t *initialValue, /* If not the first segment, see if we can reuse the previous segment storage * space and compress the previous segment. */ if (((vars->shead.idx % SEGMENTS_PER_INDEX) > 0) && - (previous_length == (int64_t)vars->add_length) && vars->compress) { + (previous_length == (int64_t)vars->add_length) && vars->compress) + { EMPTYXD(xd_data); EMPTYXD(xd_dim); vars->sinfo = &vars->sindex.segment[(vars->idx % SEGMENTS_PER_INDEX) - 1]; status = read_segment(vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, &vars->shead, vars->sinfo, vars->idx - 1, &xd_data, &xd_dim); - if - STATUS_OK - status = checkcompress(vars, &xd_data, &xd_dim, initialValue); + if (STATUS_OK) + status = checkcompress(vars, &xd_data, &xd_dim, initialValue); MdsFree1Dx(&xd_data, 0); MdsFree1Dx(&xd_dim, 0); } - if - STATUS_OK { - if (vars->idx >= vars->sindex.first_idx + SEGMENTS_PER_INDEX) { - memset(&vars->sindex, -1, sizeof(vars->sindex)); - vars->sindex.previous_offset = vars->shead.index_offset; - vars->shead.index_offset = -1; - vars->sindex.first_idx = vars->idx; - } - vars->sinfo = &vars->sindex.segment[vars->idx % SEGMENTS_PER_INDEX]; + if (STATUS_OK) + { + if (vars->idx >= vars->sindex.first_idx + SEGMENTS_PER_INDEX) + { + memset(&vars->sindex, -1, sizeof(vars->sindex)); + vars->sindex.previous_offset = vars->shead.index_offset; + vars->shead.index_offset = -1; + vars->sindex.first_idx = vars->idx; } + vars->sinfo = &vars->sindex.segment[vars->idx % SEGMENTS_PER_INDEX]; + } return status; } inline static int put_initialvalue(TREE_INFO *tinfo, int *dims, - mdsdsc_a_t *array, int64_t *offset) { + mdsdsc_a_t *array, int64_t *offset) +{ int status; int length = array->length; int i; @@ -1054,9 +1171,11 @@ inline static int put_initialvalue(TREE_INFO *tinfo, int *dims, return status; } -inline static int putdata_initialvalue(vars_t *vars, mdsdsc_a_t *initialValue) { +inline static int putdata_initialvalue(vars_t *vars, mdsdsc_a_t *initialValue) +{ int status; - if (initialValue->dtype == DTYPE_OPAQUE) { + if (initialValue->dtype == DTYPE_OPAQUE) + { int length; status = tree_put_dsc(vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, (mdsdsc_t *)initialValue, &vars->sinfo->data_offset, @@ -1064,10 +1183,12 @@ inline static int putdata_initialvalue(vars_t *vars, mdsdsc_a_t *initialValue) { vars->shead.data_offset = vars->sinfo->data_offset; vars->add_length = length; vars->sinfo->rows = length | 0x80000000; - } else + } + else status = put_initialvalue(vars->tinfo, vars->shead.dims, initialValue, &vars->shead.data_offset); - if (initialValue->dtype != DTYPE_OPAQUE) { + if (initialValue->dtype != DTYPE_OPAQUE) + { vars->sinfo->data_offset = vars->shead.data_offset; vars->sinfo->rows = vars->shead.dims[vars->shead.dimct - 1]; } @@ -1076,19 +1197,22 @@ inline static int putdata_initialvalue(vars_t *vars, mdsdsc_a_t *initialValue) { inline static int put_limit_by_dsc(vars_t *vars, mdsdsc_t *limit_in, int64_t *limit_out, int64_t *offset, - int *length) { + int *length) +{ mdsdsc_t *dsc; for (dsc = limit_in; dsc && dsc->pointer && dsc->dtype == DTYPE_DSC; dsc = (mdsdsc_t *)dsc->pointer) ; if (dsc && dsc->pointer && - (dsc->dtype == DTYPE_Q || dsc->dtype == DTYPE_QU)) { + (dsc->dtype == DTYPE_Q || dsc->dtype == DTYPE_QU)) + { *limit_out = *(int64_t *)dsc->pointer; *offset = -1; *length = 0; return TreeSUCCESS; } - if (limit_in) { + if (limit_in) + { *limit_out = -1; return tree_put_dsc(vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, limit_in, offset, length, vars->compress); @@ -1097,7 +1221,8 @@ inline static int put_limit_by_dsc(vars_t *vars, mdsdsc_t *limit_in, } inline static int putdim_dim(vars_t *vars, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dimension) { + mdsdsc_t *dimension) +{ int status = TreeSUCCESS; RETURN_IF_NOT_OK(put_limit_by_dsc(vars, start, &vars->sinfo->start, &vars->sinfo->start_offset, @@ -1112,7 +1237,8 @@ inline static int putdim_dim(vars_t *vars, mdsdsc_t *start, mdsdsc_t *end, return status; } -inline static int putdim_ts(vars_t *vars, int64_t *timestamps) { +inline static int putdim_ts(vars_t *vars, int64_t *timestamps) +{ int status; INIT_AND_FREE_ON_EXIT(char *, fbuffer); const int rows = vars->shead.dims[vars->shead.dimct - 1]; @@ -1120,26 +1246,29 @@ inline static int putdim_ts(vars_t *vars, int64_t *timestamps) { char *buffer; if (!timestamps) fbuffer = buffer = calloc(bufsize, 1); - else if (vars->rows_filled < rows) { + else if (vars->rows_filled < rows) + { int off; fbuffer = buffer = malloc(bufsize); memcpy(buffer, timestamps, off = sizeof(int64_t) * vars->rows_filled); memset(buffer + off, 0, bufsize - off); - } else { + } + else + { fbuffer = NULL; // nothing to free buffer = (char *)timestamps; } status = write_property(vars->tinfo, &vars->shead.dim_offset, buffer, bufsize); FREE_NOW(fbuffer); - if - STATUS_OK { - vars->sinfo->start = vars->rows_filled > 0 ? timestamps[0] : 0; - vars->sinfo->end = - vars->rows_filled > 0 ? timestamps[vars->rows_filled - 1] : 0; - vars->sinfo->dimension_offset = vars->shead.dim_offset; - vars->sinfo->dimension_length = 0; - } + if (STATUS_OK) + { + vars->sinfo->start = vars->rows_filled > 0 ? timestamps[0] : 0; + vars->sinfo->end = + vars->rows_filled > 0 ? timestamps[vars->rows_filled - 1] : 0; + vars->sinfo->dimension_offset = vars->shead.dim_offset; + vars->sinfo->dimension_length = 0; + } return status; } @@ -1147,7 +1276,8 @@ inline static int check_compress_dim(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, mdsdsc_xd_t *xd_dim_ptr __attribute__((unused)), mdsdsc_a_t *initialValue - __attribute__((unused))) { + __attribute__((unused))) +{ int length = 0; vars->shead.data_offset = vars->sinfo->data_offset; int status = tree_put_dsc(vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, @@ -1160,7 +1290,8 @@ inline static int check_compress_dim(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, inline static int check_compress_ts(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, mdsdsc_xd_t *xd_dim_ptr, - mdsdsc_a_t *initialValue) { + mdsdsc_a_t *initialValue) +{ int length; A_COEFF_TYPE *data_a = (A_COEFF_TYPE *)xd_data_ptr->pointer; A_COEFF_TYPE *dim_a = (A_COEFF_TYPE *)xd_dim_ptr->pointer; @@ -1171,7 +1302,8 @@ inline static int check_compress_ts(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, data_a->arsize >= initialValue->arsize && dim_a && dim_a->class == CLASS_A && dim_a->pointer && dim_a->arsize >= (rows * sizeof(int64_t)) && dim_a->dimct == 1 && - dim_a->length == sizeof(int64_t) && dim_a->dtype == DTYPE_Q) { + dim_a->length == sizeof(int64_t) && dim_a->dtype == DTYPE_Q) + { vars->shead.data_offset = vars->sinfo->data_offset; vars->shead.dim_offset = vars->sinfo->dimension_offset; int status = tree_put_dsc(vars->dblist, vars->tinfo, *(int *)vars->nid_ptr, @@ -1187,7 +1319,9 @@ inline static int check_compress_ts(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, /*** flag compressed segment by setting high bit in the rows field. ***/ vars->sinfo->rows = length | 0x80000000; return STATUS_OK ? statdim : status; - } else { + } + else + { if (!data_a) printf("data_a null\n"); else if (data_a->class != CLASS_A) @@ -1216,7 +1350,8 @@ inline static int check_compress_ts(vars_t *vars, mdsdsc_xd_t *xd_data_ptr, } } -inline static int check_input(mdsdsc_a_t **data_p) { +inline static int check_input(mdsdsc_a_t **data_p) +{ while (*data_p && (*data_p)->dtype == DTYPE_DSC) *data_p = (mdsdsc_a_t *)(*data_p)->pointer; if (*data_p == NULL || @@ -1227,40 +1362,46 @@ inline static int check_input(mdsdsc_a_t **data_p) { return TreeSUCCESS; } -inline static int open_header_read(vars_t *vars) { +inline static int open_header_read(vars_t *vars) +{ int status; RETURN_IF_NOT_OK(open_datafile_read(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) return TreeNOSEGMENTS; - if - IS_NOT_OK(load_segment_header(vars)) return TreeNOSEGMENTS; + if (IS_NOT_OK(load_extended_nci(vars))) + return TreeNOSEGMENTS; + if (IS_NOT_OK(load_segment_header(vars))) + return TreeNOSEGMENTS; return TreeSUCCESS; } -inline static int open_index_read(vars_t *vars) { +inline static int open_index_read(vars_t *vars) +{ int status; RETURN_IF_NOT_OK(open_header_read(vars)); return load_segment_index(vars); } static int get_compressed_segment_rows(TREE_INFO *tinfo, const int64_t offset, - int *rows) { + int *rows) +{ int status; char buffer[60]; RETURN_IF_NOT_OK(read_property_safe(tinfo, offset, buffer, sizeof(buffer))); if ((class_t)buffer[3] != CLASS_CA && (class_t)buffer[3] != CLASS_A) return TreeFAILURE; char dimct = buffer[11]; - if (dimct == 1) { + if (dimct == 1) + { *rows = swapint32(&buffer[12]) / swapint16(buffer); // arsize / length - } else + } + else loadint32(rows, &buffer[16 + dimct * 4]); // last dim return TreeSUCCESS; } int _TreeXNciMakeSegment(void *dbid, int nid, const char *xnci, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, - mdsdsc_a_t *initValIn, int idx, int rows_filled) { + mdsdsc_a_t *initValIn, int idx, int rows_filled) +{ INIT_WRITE_VARS; CLEANUP_NCI_PUSH; mdsdsc_a_t *initialValue = initValIn; @@ -1279,8 +1420,7 @@ int _TreeXNciMakeSegment(void *dbid, int nid, const char *xnci, mdsdsc_t *start, vars->tinfo->shot, *vars->nid_ptr, NULL); SIGNAL(1) signal = { - 0, DTYPE_SIGNAL, CLASS_R, 0, 3, __fill_value__(mdsdsc_t *) initValIn, - NULL, {dimension}}; + 0, DTYPE_SIGNAL, CLASS_R, 0, 3, __fill_value__(mdsdsc_t *) initValIn, NULL, {dimension}}; TreeCallHookFun("TreeNidDataHook", "MakeSegmentFull", vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, &signal, NULL); status = begin_finish(vars); @@ -1291,7 +1431,8 @@ end:; int _TreeXNciMakeTimestampedSegment(void *dbid, int nid, const char *xnci, int64_t *timestamps, mdsdsc_a_t *initValIn, - int idx, int rows_filled) { + int idx, int rows_filled) +{ INIT_WRITE_VARS; CLEANUP_NCI_PUSH; mdsdsc_a_t *initialValue = initValIn; @@ -1311,10 +1452,7 @@ int _TreeXNciMakeTimestampedSegment(void *dbid, int nid, const char *xnci, DESCRIPTOR_A(dimension, sizeof(int64_t), DTYPE_Q, timestamps, rows_filled * sizeof(int64_t)); SIGNAL(1) - signal = {0, DTYPE_SIGNAL, - CLASS_R, 0, - 3, __fill_value__(mdsdsc_t *) initValIn, - NULL, {(mdsdsc_t *)&dimension}}; + signal = {0, DTYPE_SIGNAL, CLASS_R, 0, 3, __fill_value__(mdsdsc_t *) initValIn, NULL, {(mdsdsc_t *)&dimension}}; TreeCallHookFun("TreeNidDataHook", "MakeTimestampedSegmentFull", vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, &signal, NULL); @@ -1325,39 +1463,41 @@ end:; } int _TreeXNciSetRowsFilled(void *dbid, int nid, const char *xnci, - int rows_filled) { + int rows_filled) +{ const int idx = -1; INIT_WRITE_VARS; CLEANUP_NCI_PUSH; GOTO_IF_NOT_OK(end, open_datafile_write0(vars)); GOTO_IF_NOT_OK(end, open_datafile_write1(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) { - status = TreeNOSEGMENTS; - goto end; - } - if - IS_NOT_OK(load_segment_header(vars)) { - status = TreeNOSEGMENTS; - goto end; - } - if - IS_NOT_OK(load_segment_index(vars)) { - status = TreeFAILURE; - goto end; - } - if (rows_filled < 0) { + if (IS_NOT_OK(load_extended_nci(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } + if (IS_NOT_OK(load_segment_header(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } + if (IS_NOT_OK(load_segment_index(vars))) + { + status = TreeFAILURE; + goto end; + } + if (rows_filled < 0) + { vars->sinfo = &vars->sindex.segment[vars->shead.idx % SEGMENTS_PER_INDEX]; if (vars->sinfo->rows < 0) // compressed status = get_compressed_segment_rows( vars->tinfo, vars->sinfo->data_offset, &vars->shead.next_row); else vars->shead.next_row = vars->sinfo->rows & 0x7fffffff; - } else + } + else vars->shead.next_row = rows_filled; - if - STATUS_OK - status = save_segment_header(vars); + if (STATUS_OK) + status = save_segment_header(vars); end:; CLEANUP_NCI_POP; return status; @@ -1365,28 +1505,29 @@ end:; int _TreeXNciUpdateSegment(void *dbid, int nid, const char *xnci, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, - int idx) { + int idx) +{ INIT_VARS; vars->idx = idx; CLEANUP_NCI_PUSH; GOTO_IF_NOT_OK(end, open_datafile_write0(vars)); GOTO_IF_NOT_OK(end, open_datafile_write1(vars)); set_compress(vars); - if - IS_NOT_OK(load_extended_nci(vars)) { - status = TreeNOSEGMENTS; - goto end; - } - if - IS_NOT_OK(load_segment_header(vars)) { - status = TreeNOSEGMENTS; - goto end; - } - if - IS_NOT_OK(load_segment_index(vars)) { - status = TreeFAILURE; - goto end; - } + if (IS_NOT_OK(load_extended_nci(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } + if (IS_NOT_OK(load_segment_header(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } + if (IS_NOT_OK(load_segment_index(vars))) + { + status = TreeFAILURE; + goto end; + } GOTO_IF_NOT_OK(end, check_sinfo(vars)); GOTO_IF_NOT_OK(end, putdim_dim(vars, start, end, dimension)); TreeCallHookFun("TreeNidHook", "UpdateSegment", vars->tinfo->treenam, @@ -1398,7 +1539,8 @@ end:; } int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, - const int startIdx, mdsdsc_a_t *data) { + const int startIdx, mdsdsc_a_t *data) +{ A_COEFF_TYPE *a_coeff = (A_COEFF_TYPE *)data; INIT_VARS; CLEANUP_NCI_PUSH; @@ -1406,7 +1548,8 @@ int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, { while (data && data->dtype == DTYPE_DSC) data = (mdsdsc_a_t *)data->pointer; - if (data->class == CLASS_S) { + if (data->class == CLASS_S) + { data_a.pointer = data->pointer; data_a.length = data->length; data_a.class = CLASS_A; @@ -1416,36 +1559,39 @@ int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, data = (mdsdsc_a_t *)&data_a; } if (data == NULL || data->class != CLASS_A || data->dimct < 1 || - data->dimct > 8) { + data->dimct > 8) + { status = TreeINVDTPUSG; goto end; } } GOTO_IF_NOT_OK(end, open_datafile_write0(vars)); GOTO_IF_NOT_OK(end, open_datafile_write1(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) { - status = TreeNOSEGMENTS; - goto end; - } - if - IS_NOT_OK(load_segment_header(vars)) { - status = TreeNOSEGMENTS; - goto end; - } + if (IS_NOT_OK(load_extended_nci(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } + if (IS_NOT_OK(load_segment_header(vars))) + { + status = TreeNOSEGMENTS; + goto end; + } /*CHECK_DATA_DIMCT*/ { if (data->dtype != vars->shead.dtype || (data->dimct != vars->shead.dimct && data->dimct != vars->shead.dimct - 1) || (data->dimct > 1 && memcmp(vars->shead.dims, a_coeff->m, - (data->dimct - 1) * sizeof(int)))) { + (data->dimct - 1) * sizeof(int)))) + { status = TreeFAILURE; goto end; } } /*CHECK_STARTIDX*/ const int start_idx = (startIdx == -1) ? vars->shead.next_row : startIdx; - if (start_idx < 0 || start_idx >= vars->shead.dims[vars->shead.dimct - 1]) { + if (start_idx < 0 || start_idx >= vars->shead.dims[vars->shead.dimct - 1]) + { status = TreeBUFFEROVF; goto end; } @@ -1470,7 +1616,8 @@ int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, : rows_to_insert; uint32_t bytes_to_insert = rows_to_insert * bytes_per_row; if (bytes_to_insert < - data->arsize) { // segment does not fit array size (shape?) + data->arsize) + { // segment does not fit array size (shape?) status = TreeBUFFEROVF; goto end; } @@ -1484,21 +1631,22 @@ int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, } if (start_idx == vars->shead.next_row) vars->shead.next_row += bytes_to_insert / bytes_per_row; - if - STATUS_OK { - status = save_segment_header(vars); - TreeCallHookFun("TreeNidHook", "PutSegment", vars->tinfo->treenam, - vars->tinfo->shot, *vars->nid_ptr, NULL); - TreeCallHookFun("TreeNidDataHook", "PutSegmentFull", vars->tinfo->treenam, - vars->tinfo->shot, *vars->nid_ptr, data, NULL); - } + if (STATUS_OK) + { + status = save_segment_header(vars); + TreeCallHookFun("TreeNidHook", "PutSegment", vars->tinfo->treenam, + vars->tinfo->shot, *vars->nid_ptr, NULL); + TreeCallHookFun("TreeNidDataHook", "PutSegmentFull", vars->tinfo->treenam, + vars->tinfo->shot, *vars->nid_ptr, data, NULL); + } end:; CLEANUP_NCI_POP; return status; } int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, - int64_t *timestamp, mdsdsc_a_t *data_in) { + int64_t *timestamp, mdsdsc_a_t *data_in) +{ INIT_VARS; CLEANUP_NCI_PUSH; mdsdsc_a_t *data = data_in; @@ -1506,7 +1654,8 @@ int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, while (data && data->dtype == DTYPE_DSC) data = (mdsdsc_a_t *)data->pointer; DESCRIPTOR_A(data_a, 0, 0, 0, 0); - if (data && data->class == CLASS_S) { + if (data && data->class == CLASS_S) + { data_a.pointer = data->pointer; data_a.length = data->length; data_a.class = CLASS_A; @@ -1517,22 +1666,24 @@ int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, } A_COEFF_TYPE *a_coeff = (A_COEFF_TYPE *)data; if (data == NULL || data->class != CLASS_A || data->dimct < 1 || - data->dimct > 8) { + data->dimct > 8) + { status = TreeINVDTYPE; goto end; } GOTO_IF_NOT_OK(end, open_datafile_write1(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) { - status = TreeNOSEGMENTS; - goto end; - }; - if - IS_NOT_OK(load_segment_header(vars)) { - status = TreeNOSEGMENTS; - goto end; - }; - if (data->dtype != vars->shead.dtype) { + if (IS_NOT_OK(load_extended_nci(vars))) + { + status = TreeNOSEGMENTS; + goto end; + }; + if (IS_NOT_OK(load_segment_header(vars))) + { + status = TreeNOSEGMENTS; + goto end; + }; + if (data->dtype != vars->shead.dtype) + { status = TreeINVDTYPE; goto end; } @@ -1541,7 +1692,8 @@ int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, (data->dimct != vars->shead.dimct && data->dimct != vars->shead.dimct - 1) || (data->dimct > 1 && memcmp(vars->shead.dims, a_coeff->m, - (data->dimct - 1) * sizeof(int)))) { + (data->dimct - 1) * sizeof(int)))) + { status = TreeFAILURE; goto end; } @@ -1569,7 +1721,8 @@ int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, int64_t offset = vars->shead.data_offset + start_idx * bytes_per_row; uint32_t bytes_to_insert = rows_to_insert * bytes_per_row; if (bytes_to_insert < - data->arsize) { // segment does not fit array size (shape?) + data->arsize) + { // segment does not fit array size (shape?) status = TreeBUFFEROVF; goto end; } @@ -1579,34 +1732,31 @@ int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, status = write_property(vars->tinfo, &offset, buffer, bytes_to_insert); FREE_BUFFER(buffer); } - if - STATUS_OK { - int64_t offset = vars->shead.dim_offset + start_idx * sizeof(int64_t); - uint32_t bytes_to_insert = rows_to_insert * sizeof(int64_t); - ALLOCATE_BUFFER(bytes_to_insert, buffer); - CHECK_ENDIAN_TRANSFER(timestamp, rows_to_insert, sizeof(int64_t), 0, - buffer); - status = write_property(vars->tinfo, &offset, buffer, bytes_to_insert); - FREE_BUFFER(buffer); - } - if - STATUS_OK { - vars->shead.next_row = start_idx + rows_to_insert; - status = save_segment_header(vars); - TreeCallHookFun("TreeNidHook", "PutTimestampedSegment", - vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, - NULL); - DESCRIPTOR_A(dimension, sizeof(int64_t), DTYPE_Q, timestamp, - rows_to_insert * sizeof(int64_t)); - SIGNAL(1) - signal = {0, DTYPE_SIGNAL, - CLASS_R, 0, - 3, __fill_value__(mdsdsc_t *) data_in, - NULL, {(mdsdsc_t *)&dimension}}; - TreeCallHookFun("TreeNidDataHook", "PutTimestampedSegmentFull", - vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, - &signal, NULL); - } + if (STATUS_OK) + { + int64_t offset = vars->shead.dim_offset + start_idx * sizeof(int64_t); + uint32_t bytes_to_insert = rows_to_insert * sizeof(int64_t); + ALLOCATE_BUFFER(bytes_to_insert, buffer); + CHECK_ENDIAN_TRANSFER(timestamp, rows_to_insert, sizeof(int64_t), 0, + buffer); + status = write_property(vars->tinfo, &offset, buffer, bytes_to_insert); + FREE_BUFFER(buffer); + } + if (STATUS_OK) + { + vars->shead.next_row = start_idx + rows_to_insert; + status = save_segment_header(vars); + TreeCallHookFun("TreeNidHook", "PutTimestampedSegment", + vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, + NULL); + DESCRIPTOR_A(dimension, sizeof(int64_t), DTYPE_Q, timestamp, + rows_to_insert * sizeof(int64_t)); + SIGNAL(1) + signal = {0, DTYPE_SIGNAL, CLASS_R, 0, 3, __fill_value__(mdsdsc_t *) data_in, NULL, {(mdsdsc_t *)&dimension}}; + TreeCallHookFun("TreeNidDataHook", "PutTimestampedSegmentFull", + vars->tinfo->treenam, vars->tinfo->shot, *vars->nid_ptr, + &signal, NULL); + } end:; CLEANUP_NCI_POP; return status; @@ -1617,10 +1767,12 @@ end:; inline static void getlimit_array(vars_t *vars, int64_t *limitval, const int64_t sinfo_limit, const int64_t sinfo_limit_offset, - const int sinfo_limit_length) { + const int sinfo_limit_length) +{ if (sinfo_limit != -1) *limitval = sinfo_limit; - else if (sinfo_limit_offset > 0 && sinfo_limit_length > 0) { + else if (sinfo_limit_offset > 0 && sinfo_limit_length > 0) + { EMPTYXD(xd); if (tree_get_dsc(vars->tinfo, *(int *)vars->nid_ptr, sinfo_limit_offset, sinfo_limit_length, &xd) & @@ -1630,7 +1782,8 @@ inline static void getlimit_array(vars_t *vars, int64_t *limitval, else *limitval = 0; MdsFree1Dx(&xd, 0); - } else + } + else *limitval = 0; } @@ -1638,8 +1791,10 @@ inline static void getlimit_xd(vars_t *vars, int64_t *limitval, const int64_t sinfo_limit, const int64_t sinfo_limit_offset, const int sinfo_limit_length, - mdsdsc_xd_t *limit_xd, mdsdsc_t *limitdsc) { - if (sinfo_limit != -1) { + mdsdsc_xd_t *limit_xd, mdsdsc_t *limitdsc) +{ + if (sinfo_limit != -1) + { *limitval = sinfo_limit; MdsCopyDxXd(limitdsc, limit_xd); } @@ -1649,10 +1804,12 @@ inline static void getlimit_xd(vars_t *vars, int64_t *limitval, } inline static int get_filled_rows_ts(SEGMENT_HEADER *shead, SEGMENT_INFO *sinfo, - const int idx, const int64_t *buffer) { + const int idx, const int64_t *buffer) +{ if (shead->idx == idx) return shead->next_row < 0 ? sinfo->rows : shead->next_row; - else { + else + { /* Removes trailing null timestamps from dimension and data * if at least more than one zero timestamps * or last timestamp does not continue monotonic increase of time vector @@ -1670,19 +1827,24 @@ inline static int get_segment_times_loop(vars_t *vars, int64_t *startval, int64_t *endval, mdsdsc_xd_t *start_xd, mdsdsc_t *startdsc, mdsdsc_xd_t *end_xd, - mdsdsc_t *enddsc) { + mdsdsc_t *enddsc) +{ int status = TreeSUCCESS; int index_idx = vars->idx % SEGMENTS_PER_INDEX; vars->sinfo = &vars->sindex.segment[index_idx]; if (vars->sinfo->dimension_offset != -1 && - vars->sinfo->dimension_length == 0) { + vars->sinfo->dimension_length == 0) + { /* It's a timestamped segment */ if (vars->sinfo->rows < 0 || - !(vars->sinfo->start == 0 && vars->sinfo->end == 0)) { + !(vars->sinfo->start == 0 && vars->sinfo->end == 0)) + { /* Valid start and end in segment tinfo */ *startval = vars->sinfo->start; *endval = vars->sinfo->end; - } else { + } + else + { /* Current segment so use timestamps in segment */ int length = sizeof(int64_t) * vars->sinfo->rows; char *buffer = NULL; @@ -1690,32 +1852,38 @@ inline static int get_segment_times_loop(vars_t *vars, int64_t *startval, buffer = malloc(length); status = read_property(vars->tinfo, vars->sinfo->dimension_offset, buffer, length); - if - STATUS_OK { - loadint64(startval, buffer); - int filled_rows = get_filled_rows_ts(&vars->shead, vars->sinfo, - vars->idx, (int64_t *)buffer); - if (filled_rows > 0) - loadint64(endval, buffer + (filled_rows - 1) * sizeof(int64_t)); - else - *endval = 0; - } - else { + if (STATUS_OK) + { + loadint64(startval, buffer); + int filled_rows = get_filled_rows_ts(&vars->shead, vars->sinfo, + vars->idx, (int64_t *)buffer); + if (filled_rows > 0) + loadint64(endval, buffer + (filled_rows - 1) * sizeof(int64_t)); + else + *endval = 0; + } + else + { *startval = 0; *endval = 0; } FREE_NOW(buffer); } - if (start_xd) { + if (start_xd) + { MdsCopyDxXd(startdsc, start_xd); MdsCopyDxXd(enddsc, end_xd); } - } else if (start_xd) { + } + else if (start_xd) + { getlimit_xd(vars, startval, vars->sinfo->start, vars->sinfo->start_offset, vars->sinfo->start_length, start_xd, startdsc); getlimit_xd(vars, endval, vars->sinfo->end, vars->sinfo->end_offset, vars->sinfo->end_length, end_xd, enddsc); - } else { + } + else + { getlimit_array(vars, startval, vars->sinfo->start, vars->sinfo->start_offset, vars->sinfo->start_length); getlimit_array(vars, endval, vars->sinfo->end, vars->sinfo->end_offset, @@ -1729,7 +1897,8 @@ inline static int get_segment_times_loop(vars_t *vars, int64_t *startval, int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, const char *xnci, int *nsegs, mdsdsc_xd_t *start_list, - mdsdsc_xd_t *end_list) { + mdsdsc_xd_t *end_list) +{ INIT_VARS; RETURN_IF_NOT_OK(open_index_read(vars)); int numsegs = vars->shead.idx + 1; @@ -1748,7 +1917,8 @@ int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, const char *xnci, int64_t endval; mdsdsc_t startdsc = {sizeof(int64_t), DTYPE_Q, CLASS_S, (char *)&startval}; mdsdsc_t enddsc = {sizeof(int64_t), DTYPE_Q, CLASS_S, (char *)&endval}; - for (vars->idx = numsegs; STATUS_OK && vars->idx-- > 0;) { + for (vars->idx = numsegs; STATUS_OK && vars->idx-- > 0;) + { start_xds[vars->idx] = memcpy(malloc(sizeof(mdsdsc_xd_t)), &xd, sizeof(mdsdsc_xd_t)); end_xds[vars->idx] = @@ -1760,7 +1930,8 @@ int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, const char *xnci, } MdsCopyDxXd((mdsdsc_t *)&start_apd, start_list); MdsCopyDxXd((mdsdsc_t *)&end_apd, end_list); - for (vars->idx = 0; vars->idx < numsegs; vars->idx++) { + for (vars->idx = 0; vars->idx < numsegs; vars->idx++) + { MdsFree1Dx(start_xds[vars->idx], 0); free(start_xds[vars->idx]); MdsFree1Dx(end_xds[vars->idx], 0); @@ -1772,7 +1943,8 @@ int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, const char *xnci, } int _TreeXNciGetSegmentTimes(void *dbid, int nid, const char *xnci, int *nsegs, - int64_t **times) { + int64_t **times) +{ *times = NULL; INIT_VARS; RETURN_IF_NOT_OK(open_index_read(vars)); @@ -1787,14 +1959,15 @@ int _TreeXNciGetSegmentTimes(void *dbid, int nid, const char *xnci, int *nsegs, return status; } -int _TreeXNciGetNumSegments(void *dbid, int nid, const char *xnci, int *num) { +int _TreeXNciGetNumSegments(void *dbid, int nid, const char *xnci, int *num) +{ *num = 0; INIT_VARS; RETURN_IF_NOT_OK(open_datafile_read(vars)); - if - IS_NOT_OK(load_extended_nci(vars)) return TreeSUCCESS; // ans 0 segments - if - IS_NOT_OK(load_segment_header(vars)) return TreeSUCCESS; // ans 0 segments + if (IS_NOT_OK(load_extended_nci(vars))) + return TreeSUCCESS; // ans 0 segments + if (IS_NOT_OK(load_segment_header(vars))) + return TreeSUCCESS; // ans 0 segments *num = _vars.shead.idx + 1; return TreeSUCCESS; } @@ -1802,7 +1975,8 @@ int _TreeXNciGetNumSegments(void *dbid, int nid, const char *xnci, int *num) { static int (*_TdiExecute)() = NULL; static int (*_TdiCompile)() = NULL; /* checks last segment and trims it down to last written row if necessary */ -static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) { +static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) +{ int status = TreeSUCCESS; mdsdsc_t *tmp = dim->pointer; while (tmp && tmp->class == CLASS_R && tmp->dtype != DTYPE_WINDOW && @@ -1815,10 +1989,12 @@ static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) { (begin = (mdsdsc_s_t *)((mds_function_t *)tmp)->arguments[0])->class == CLASS_S && (end = (mdsdsc_s_t *)((mds_function_t *)tmp)->arguments[1])->class == - CLASS_S) { + CLASS_S) + { int64_t begin_i; double begin_d; - switch (begin->dtype) { + switch (begin->dtype) + { case DTYPE_B: case DTYPE_BU: begin_d = begin_i = *(int8_t *)begin->pointer; @@ -1844,7 +2020,8 @@ static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) { default: goto fallback; } - switch (end->dtype) { + switch (end->dtype) + { case DTYPE_B: case DTYPE_BU: *(int8_t *)end->pointer = (int8_t)(begin_i + filled_rows - 1); @@ -1872,7 +2049,8 @@ static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) { } return status; } - if (tmp->class == CLASS_A) { + if (tmp->class == CLASS_A) + { if (((mdsdsc_a_t *)tmp)->aflags.coeff) ((array_coeff *)tmp)->m[0] = filled_rows; else @@ -1881,33 +2059,36 @@ static int trim_last_segment(void *dbid, mdsdsc_xd_t *dim, int filled_rows) { } fallback:; status = LibFindImageSymbol_C("TdiShr", "_TdiCompile", &_TdiCompile); - if - STATUS_OK { - STATIC_CONSTANT DESCRIPTOR( - expression, "execute('$1[$2 : $2+$3-1]',$1,lbound($1,-1),$2)"); - DESCRIPTOR_LONG(row_d, &filled_rows); - status = _TdiCompile(&dbid, &expression, dim, &row_d, dim MDS_END_ARG); - } + if (STATUS_OK) + { + STATIC_CONSTANT DESCRIPTOR( + expression, "execute('$1[$2 : $2+$3-1]',$1,lbound($1,-1),$2)"); + DESCRIPTOR_LONG(row_d, &filled_rows); + status = _TdiCompile(&dbid, &expression, dim, &row_d, dim MDS_END_ARG); + } return status; } /* read segmet data and dim, perform trim operation iff dbid is provided */ static int read_segment(void *dbid, TREE_INFO *tinfo, int nid, SEGMENT_HEADER *shead, SEGMENT_INFO *sinfo, int idx, - mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) { + mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) +{ if (sinfo->data_offset == -1) return TreeFAILURE; // copy_segment_index expects TreeFAILURE; int status = TreeSUCCESS; int filled_rows; int compressed_segment = sinfo->rows < 0; int rows; - if (compressed_segment) { - if - IS_NOT_OK(get_compressed_segment_rows(tinfo, sinfo->data_offset, &rows)) - rows = 1; - } else + if (compressed_segment) + { + if (IS_NOT_OK(get_compressed_segment_rows(tinfo, sinfo->data_offset, &rows))) + rows = 1; + } + else rows = sinfo->rows; - if (sinfo->dimension_offset != -1 && sinfo->dimension_length == 0) { + if (sinfo->dimension_offset != -1 && sinfo->dimension_length == 0) + { // this is a timestamped segment node, i.e. dim is array of int64_t DESCRIPTOR_A(ans, 8, DTYPE_Q, 0, 0); ans.arsize = rows * sizeof(int64_t); @@ -1915,41 +2096,53 @@ static int read_segment(void *dbid, TREE_INFO *tinfo, int nid, status = read_property(tinfo, sinfo->dimension_offset, ans.pointer, (ssize_t)ans.arsize); CHECK_ENDIAN(ans.pointer, ans.arsize, sizeof(int64_t), 0); - if (dbid) { + if (dbid) + { if (idx == shead->idx) filled_rows = shead->next_row; else filled_rows = get_filled_rows_ts(shead, sinfo, idx, (int64_t *)ans.pointer); - } else + } + else filled_rows = rows; - if (dim) { + if (dim) + { ans.arsize = filled_rows * sizeof(int64_t); if (ans.arsize == 0) ans.pointer = NULL; MdsCopyDxXd((mdsdsc_t *)&ans, dim); } free(ans_ptr); - } else if (sinfo->dimension_length != -1) { + } + else if (sinfo->dimension_length != -1) + { filled_rows = (idx == shead->idx) ? shead->next_row : rows; - if (dim) { + if (dim) + { status = tree_get_dsc(tinfo, nid, sinfo->dimension_offset, sinfo->dimension_length, dim); if (STATUS_OK && dbid && dim->pointer && idx == shead->idx && shead->next_row != rows) status = trim_last_segment(dbid, dim, filled_rows); } - } else { // no dim is stored, set filled_rows to next_row or full + } + else + { // no dim is stored, set filled_rows to next_row or full filled_rows = (idx == shead->idx) ? shead->next_row : rows; if (!segment) segment = dim; // if segment is not requested, read it as dim } - if (STATUS_OK && segment) { - if (compressed_segment) { + if (STATUS_OK && segment) + { + if (compressed_segment) + { int data_length = sinfo->rows & 0x7fffffff; status = tree_get_dsc(tinfo, nid, sinfo->data_offset, data_length, segment); - } else { + } + else + { DESCRIPTOR_A_COEFF(ans, shead->length, shead->dtype, NULL, 8, 0); ans.dimct = shead->dimct; memcpy(ans.m, shead->dims, sizeof(shead->dims)); @@ -1961,18 +2154,19 @@ static int read_segment(void *dbid, TREE_INFO *tinfo, int nid, void *ans_ptr = ans.pointer = ans.a0 = malloc(ans.arsize); status = read_property(tinfo, sinfo->data_offset, ans.pointer, (ssize_t)ans.arsize); - if - STATUS_OK { - CHECK_ENDIAN(ans.pointer, ans.arsize, ans.length, ans.dtype); - if (ans.arsize == 0) - ans.pointer = NULL; - MdsCopyDxXd((mdsdsc_t *)&ans, segment); - } + if (STATUS_OK) + { + CHECK_ENDIAN(ans.pointer, ans.arsize, ans.length, ans.dtype); + if (ans.arsize == 0) + ans.pointer = NULL; + MdsCopyDxXd((mdsdsc_t *)&ans, segment); + } free(ans_ptr); } } if (STATUS_OK && dim && dim != segment && - (sinfo->dimension_offset == -1 && sinfo->dimension_length == -1)) { + (sinfo->dimension_offset == -1 && sinfo->dimension_length == -1)) + { // dim is requested, but no dim is stored. segment was also requested, so we // make a copy of segment. MdsCopyDxXd((mdsdsc_t *)segment, dim); @@ -1981,48 +2175,60 @@ static int read_segment(void *dbid, TREE_INFO *tinfo, int nid, } static int get_segment_limits(vars_t *vars, mdsdsc_xd_t *retStart, - mdsdsc_xd_t *retEnd) { + mdsdsc_xd_t *retEnd) +{ int status = TreeSUCCESS; int64_t timestamp = 0; mdsdsc_t q_d = {8, DTYPE_Q, CLASS_S, (char *)×tamp}; if (vars->sinfo->dimension_offset != -1 && - vars->sinfo->dimension_length == 0) { + vars->sinfo->dimension_length == 0) + { /*** timestamped segments ****/ if (vars->sinfo->rows < 0 || - !(vars->sinfo->start == 0 && vars->sinfo->end == 0)) { - if (retStart) { + !(vars->sinfo->start == 0 && vars->sinfo->end == 0)) + { + if (retStart) + { timestamp = vars->sinfo->start; MdsCopyDxXd(&q_d, retStart); } - if (retEnd) { + if (retEnd) + { timestamp = vars->sinfo->end; MdsCopyDxXd(&q_d, retEnd); } - } else { + } + else + { char *buffer = NULL; FREE_ON_EXIT(buffer); const int length = sizeof(int64_t) * vars->sinfo->rows; buffer = malloc(length); status = read_property(vars->tinfo, vars->sinfo->dimension_offset, buffer, length); - if - STATUS_OK { - if (retStart) { - loadint64(×tamp, buffer); - MdsCopyDxXd(&q_d, retStart); - } - if (retEnd) { - const int filled_rows = get_filled_rows_ts( - &vars->shead, vars->sinfo, vars->idx, (int64_t *)buffer); - if (filled_rows > 0) { - loadint64(×tamp, - buffer + (filled_rows - 1) * sizeof(int64_t)); - MdsCopyDxXd(&q_d, retEnd); - } else - MdsFree1Dx(retEnd, 0); + if (STATUS_OK) + { + if (retStart) + { + loadint64(×tamp, buffer); + MdsCopyDxXd(&q_d, retStart); + } + if (retEnd) + { + const int filled_rows = get_filled_rows_ts( + &vars->shead, vars->sinfo, vars->idx, (int64_t *)buffer); + if (filled_rows > 0) + { + loadint64(×tamp, + buffer + (filled_rows - 1) * sizeof(int64_t)); + MdsCopyDxXd(&q_d, retEnd); } + else + MdsFree1Dx(retEnd, 0); } - else { + } + else + { if (retStart) MdsFree1Dx(retStart, 0); if (retEnd) @@ -2030,23 +2236,31 @@ static int get_segment_limits(vars_t *vars, mdsdsc_xd_t *retStart, } FREE_NOW(buffer); } - } else { - if (retStart) { - if (vars->sinfo->start != -1) { + } + else + { + if (retStart) + { + if (vars->sinfo->start != -1) + { timestamp = vars->sinfo->start; MdsCopyDxXd(&q_d, retStart); - } else if (vars->sinfo->start_length > 0 && vars->sinfo->start_offset > 0) + } + else if (vars->sinfo->start_length > 0 && vars->sinfo->start_offset > 0) status = tree_get_dsc(vars->tinfo, *(int *)vars->nid_ptr, vars->sinfo->start_offset, vars->sinfo->start_length, retStart); else status = MdsFree1Dx(retStart, 0); } - if (retEnd) { - if (vars->sinfo->end != -1) { + if (retEnd) + { + if (vars->sinfo->end != -1) + { timestamp = vars->sinfo->end; MdsCopyDxXd(&q_d, retEnd); - } else if (vars->sinfo->end_length > 0 && vars->sinfo->end_offset > 0) + } + else if (vars->sinfo->end_length > 0 && vars->sinfo->end_offset > 0) status = tree_get_dsc(vars->tinfo, *(int *)vars->nid_ptr, vars->sinfo->end_offset, vars->sinfo->end_length, retEnd); @@ -2059,7 +2273,8 @@ static int get_segment_limits(vars_t *vars, mdsdsc_xd_t *retStart, extern int tree_fixup_nid(); int tree_put_dsc(PINO_DATABASE *dbid, TREE_INFO *tinfo, int nid_in, - mdsdsc_t *dsc, int64_t *offset, int *length, int compress) { + mdsdsc_t *dsc, int64_t *offset, int *length, int compress) +{ EMPTYXD(xd); int compressible; l_length_t ddlen, reclen; @@ -2073,7 +2288,8 @@ int tree_put_dsc(PINO_DATABASE *dbid, TREE_INFO *tinfo, int nid_in, compress, &compressible, &ddlen, &reclen, &dtype, &class, 0, 0, &data_in_altbuf); if (STATUS_OK && xd.pointer && xd.pointer->class == CLASS_A && - xd.pointer->pointer) { + xd.pointer->pointer) + { mdsdsc_a_t *ap = (mdsdsc_a_t *)xd.pointer; *offset = -1; status = write_property(tinfo, offset, ap->pointer, ap->arsize); @@ -2084,12 +2300,12 @@ int tree_put_dsc(PINO_DATABASE *dbid, TREE_INFO *tinfo, int nid_in, } int tree_get_dsc(TREE_INFO *tinfo, const int nid, int64_t offset, int length, - mdsdsc_xd_t *dsc) { + mdsdsc_xd_t *dsc) +{ char *buffer = malloc(length); int status = read_property_safe(tinfo, offset, buffer, length); - if - STATUS_OK - status = MdsSerializeDscIn(buffer, dsc); + if (STATUS_OK) + status = MdsSerializeDscIn(buffer, dsc); if (dsc->pointer) status = TreeMakeNidsLocal(dsc->pointer, nid); free(buffer); @@ -2098,18 +2314,18 @@ int tree_get_dsc(TREE_INFO *tinfo, const int nid, int64_t offset, int length, static int data_copy(TREE_INFO *tinfo_in, TREE_INFO *tinfo_out, int64_t offset_in, int length_in, - int64_t *offset_out) { // used in copy_segment only + int64_t *offset_out) +{ // used in copy_segment only *offset_out = -1; - if (offset_in != -1 && length_in >= 0) { + if (offset_in != -1 && length_in >= 0) + { char *data = malloc(length_in); int status = read_property(tinfo_in, offset_in, data, length_in); - if - STATUS_OK - status = write_property(tinfo_out, offset_out, data, length_in); + if (STATUS_OK) + status = write_property(tinfo_out, offset_out, data, length_in); free(data); - if - STATUS_NOT_OK - *offset_out = -1; + if (STATUS_NOT_OK) + *offset_out = -1; return status; } return TreeSUCCESS; @@ -2118,46 +2334,52 @@ static int data_copy(TREE_INFO *tinfo_in, TREE_INFO *tinfo_out, static inline int copy_segment(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, int nid, SEGMENT_HEADER *header, SEGMENT_INFO *sinfo, int idx, - int compress) { // used in copy_segment_index only + int compress) +{ // used in copy_segment_index only int status = TreeSUCCESS; - if (compress) { + if (compress) + { int length; EMPTYXD(xd); status = read_segment(NULL, tinfo_in, nid, header, sinfo, idx, &xd, NULL); - if - STATUS_OK { - status = tree_put_dsc(dbid_out, tinfo_out, nid, xd.pointer, - &sinfo->data_offset, &length, compress); - if - STATUS_OK { - if (sinfo->dimension_offset != -1 || - sinfo->dimension_length != -1) { - // dim is present - status = read_segment(NULL, tinfo_in, nid, header, sinfo, idx, - NULL, &xd); - if - STATUS_OK - status = tree_put_dsc(dbid_out, tinfo_out, nid, xd.pointer, - &sinfo->dimension_offset, - &sinfo->dimension_length, compress); - } - if (idx == header->idx) // finalize last segment - header->dims[header->dimct - 1] = header->next_row; - sinfo->rows = length | 0x80000000; - } - MdsFree1Dx(&xd, NULL); + if (STATUS_OK) + { + status = tree_put_dsc(dbid_out, tinfo_out, nid, xd.pointer, + &sinfo->data_offset, &length, compress); + if (STATUS_OK) + { + if (sinfo->dimension_offset != -1 || + sinfo->dimension_length != -1) + { + // dim is present + status = read_segment(NULL, tinfo_in, nid, header, sinfo, idx, + NULL, &xd); + if (STATUS_OK) + status = tree_put_dsc(dbid_out, tinfo_out, nid, xd.pointer, + &sinfo->dimension_offset, + &sinfo->dimension_length, compress); + } + if (idx == header->idx) // finalize last segment + header->dims[header->dimct - 1] = header->next_row; + sinfo->rows = length | 0x80000000; } - } else { + MdsFree1Dx(&xd, NULL); + } + } + else + { int length; - if (sinfo->data_offset != -1 && sinfo->rows < 0) { + if (sinfo->data_offset != -1 && sinfo->rows < 0) + { length = sinfo->rows & 0x7fffffff; status = data_copy(tinfo_in, tinfo_out, sinfo->data_offset, length, &sinfo->data_offset); - if - STATUS_OK - status = data_copy(tinfo_in, tinfo_out, sinfo->dimension_offset, - sinfo->dimension_length, &sinfo->dimension_offset); - } else { + if (STATUS_OK) + status = data_copy(tinfo_in, tinfo_out, sinfo->dimension_offset, + sinfo->dimension_length, &sinfo->dimension_offset); + } + else + { int rowlen = header->length, i; for (i = 0; i < header->dimct - 1; i++) rowlen = rowlen * header->dims[i]; @@ -2167,15 +2389,16 @@ copy_segment(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, length = sinfo->dimension_length; status = data_copy(tinfo_in, tinfo_out, sinfo->dimension_offset, length, &sinfo->dimension_offset); - if - STATUS_OK { - length = rowlen * sinfo->rows; - status = data_copy(tinfo_in, tinfo_out, sinfo->data_offset, length, - &sinfo->data_offset); - } + if (STATUS_OK) + { + length = rowlen * sinfo->rows; + status = data_copy(tinfo_in, tinfo_out, sinfo->data_offset, length, + &sinfo->data_offset); + } } } - if (STATUS_OK && (sinfo->start_offset > 0)) { + if (STATUS_OK && (sinfo->start_offset > 0)) + { status = data_copy(tinfo_in, tinfo_out, sinfo->start_offset, sinfo->start_length, &sinfo->start_offset); if (STATUS_OK && sinfo->end_offset > 0) @@ -2188,7 +2411,8 @@ copy_segment(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, static inline int copy_segment_index(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, int nid, SEGMENT_HEADER *shead, - int compress) { // used in copy_segmented_records only + int compress) +{ // used in copy_segmented_records only int status; INIT_AND_FREE_ON_EXIT(int64_t *, offsets); status = TreeSUCCESS; @@ -2196,18 +2420,21 @@ copy_segment_index(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, int i, ioff, noff = ((shead->idx - 1) / SEGMENTS_PER_INDEX) + 1; // First read all offsets as they have to be read last-one-first. offsets = malloc(noff * sizeof(int64_t)); - for (ioff = noff; ioff-- > 0 && STATUS_OK;) { + for (ioff = noff; ioff-- > 0 && STATUS_OK;) + { offsets[ioff] = offset; status = read_property(tinfo_in, offset, (char *)&offset, sizeof(offset)); offset = swapint64(&offset); - if (offsets[ioff] == offset) { + if (offsets[ioff] == offset) + { fprintf(stderr, "segment data malformed: offset[i]==offset[i+1]\n"); status = MDSplusFATAL; break; } } shead->index_offset = -1; - for (ioff = 0; ioff < noff && STATUS_OK; ioff++) { + for (ioff = 0; ioff < noff && STATUS_OK; ioff++) + { SEGMENT_INDEX sindex; status = get_segment_index(tinfo_in, offsets[ioff], &sindex); for (i = 0; (i < SEGMENTS_PER_INDEX) && STATUS_OK; i++) @@ -2224,7 +2451,8 @@ copy_segment_index(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, static int copy_segmented_records(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, int nid, - int64_t *offset, int *length, int compress) { + int64_t *offset, int *length, int compress) +{ SEGMENT_HEADER header; int status; RETURN_IF_NOT_OK(get_segment_header(tinfo_in, *offset, &header)); @@ -2237,47 +2465,53 @@ static int copy_segmented_records(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, static int copy_named_attributes(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, int nid, int64_t *offset, - int *length, int compress) { + int *length, int compress) +{ EMPTYXD(xd); NAMED_ATTRIBUTES_INDEX index; int status = get_named_attributes_index(tinfo_in, *offset, &index); - if - STATUS_OK { - int i; - *length = 0; - if (index.previous_offset != - -1) // TODO: avoid recursion due to stacklimit => can be inline - copy_named_attributes(tinfo_in, dbid_out, tinfo_out, nid, - &index.previous_offset, 0, compress); - for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) { - if (index.attribute[i].name[0] != '\0' && - index.attribute[i].offset != -1) { - if (index.attribute[i].length == -1) { - status = copy_segmented_records(tinfo_in, dbid_out, tinfo_out, nid, - &index.attribute[i].offset, length, - compress); - } else { - status = tree_get_dsc(tinfo_in, nid, index.attribute[i].offset, - index.attribute[i].length, &xd); - if - STATUS_OK { - status = tree_put_dsc(dbid_out, tinfo_out, nid, (mdsdsc_t *)&xd, - &index.attribute[i].offset, - &index.attribute[i].length, compress); - if - STATUS_NOT_OK { - memset(index.attribute[i].name, 0, - sizeof(index.attribute[i].name)); - index.attribute[i].offset = -1; - } - MdsFree1Dx(&xd, 0); - } + if (STATUS_OK) + { + int i; + *length = 0; + if (index.previous_offset != + -1) // TODO: avoid recursion due to stacklimit => can be inline + copy_named_attributes(tinfo_in, dbid_out, tinfo_out, nid, + &index.previous_offset, 0, compress); + for (i = 0; i < NAMED_ATTRIBUTES_PER_INDEX; i++) + { + if (index.attribute[i].name[0] != '\0' && + index.attribute[i].offset != -1) + { + if (index.attribute[i].length == -1) + { + status = copy_segmented_records(tinfo_in, dbid_out, tinfo_out, nid, + &index.attribute[i].offset, length, + compress); + } + else + { + status = tree_get_dsc(tinfo_in, nid, index.attribute[i].offset, + index.attribute[i].length, &xd); + if (STATUS_OK) + { + status = tree_put_dsc(dbid_out, tinfo_out, nid, (mdsdsc_t *)&xd, + &index.attribute[i].offset, + &index.attribute[i].length, compress); + if (STATUS_NOT_OK) + { + memset(index.attribute[i].name, 0, + sizeof(index.attribute[i].name)); + index.attribute[i].offset = -1; + } + MdsFree1Dx(&xd, 0); } } } - *offset = -1; - status = put_named_attributes_index(tinfo_out, &index, offset); } + *offset = -1; + status = put_named_attributes_index(tinfo_out, &index, offset); + } else *offset = -1; return status; @@ -2287,25 +2521,26 @@ inline static int copy_standard_record(TREE_INFO *tinfo_in, PINO_DATABASE *dbid_out, TREE_INFO *tinfo_out, int nid, int64_t *offset, int *length, - int compress) { + int compress) +{ int status; INIT_AND_FREEXD_ON_EXIT(xd); status = tree_get_dsc(tinfo_in, nid, *offset, *length, &xd); - if - STATUS_OK - status = tree_put_dsc(dbid_out, tinfo_out, nid, (mdsdsc_t *)&xd, offset, - length, compress); + if (STATUS_OK) + status = tree_put_dsc(dbid_out, tinfo_out, nid, (mdsdsc_t *)&xd, offset, + length, compress); FREEXD_NOW(xd); - if - STATUS_NOT_OK { - *offset = -1; - *length = 0; - } + if (STATUS_NOT_OK) + { + *offset = -1; + *length = 0; + } return status; } int TreeCopyExtended(PINO_DATABASE *dbid_in, PINO_DATABASE *dbid_out, int nid, - NCI *nci, int compress) { + NCI *nci, int compress) +{ EXTENDED_ATTRIBUTES attr; TREE_INFO *tinfo_in = dbid_in->tree_info, *tinfo_out = dbid_out->tree_info; int64_t now = -1, offset = -1; @@ -2335,7 +2570,8 @@ int TreeCopyExtended(PINO_DATABASE *dbid_in, PINO_DATABASE *dbid_out, int nid, } inline static int get_opaque_list(void *dbid, int nid, const char *xnci, - mdsdsc_xd_t *out) { + mdsdsc_xd_t *out) +{ { unsigned char data_type; NCI_ITM itmlst[] = {{1, NciDTYPE, &data_type, 0}, @@ -2353,30 +2589,33 @@ inline static int get_opaque_list(void *dbid, int nid, const char *xnci, status = get_segment_index(vars->tinfo, vars->shead.index_offset, &vars->sindex); int idx; - for (idx = numsegs; STATUS_OK && idx-- > 0;) { + for (idx = numsegs; STATUS_OK && idx-- > 0;) + { while (STATUS_OK && idx < vars->sindex.first_idx && vars->sindex.previous_offset > 0) status = get_segment_index(vars->tinfo, vars->sindex.previous_offset, &vars->sindex); - if - STATUS_NOT_OK break; + if (STATUS_NOT_OK) + break; vars->sinfo = &vars->sindex.segment[idx % SEGMENTS_PER_INDEX]; EMPTYXD(segment); status = read_segment(NULL, vars->tinfo, *(int *)vars->nid_ptr, &vars->shead, vars->sinfo, idx, &segment, NULL); - if - STATUS_OK { - dptr[idx] = malloc(sizeof(mdsdsc_xd_t)); - memcpy(dptr[idx], &segment, sizeof(mdsdsc_xd_t)); - segment.pointer = NULL; - } + if (STATUS_OK) + { + dptr[idx] = malloc(sizeof(mdsdsc_xd_t)); + memcpy(dptr[idx], &segment, sizeof(mdsdsc_xd_t)); + segment.pointer = NULL; + } else MdsFree1Dx(&segment, 0); } - if - STATUS_OK status = MdsCopyDxXd((mdsdsc_t *)&apd, out); - for (idx = 0; idx < numsegs; idx++) { - if (dptr[idx]) { + if (STATUS_OK) + status = MdsCopyDxXd((mdsdsc_t *)&apd, out); + for (idx = 0; idx < numsegs; idx++) + { + if (dptr[idx]) + { MdsFree1Dx((mdsdsc_xd_t *)dptr[idx], 0); free(dptr[idx]); } @@ -2387,71 +2626,82 @@ inline static int get_opaque_list(void *dbid, int nid, const char *xnci, int _TreeXNciGetSegmentedRecord( void *dbid, int nid, const char *xnci, - mdsdsc_xd_t *data) { // TODO: _XTreeXnciGetTimedRecord + mdsdsc_xd_t *data) +{ // TODO: _XTreeXnciGetTimedRecord int status = get_opaque_list(dbid, nid, xnci, data); if (status) return status; // 0: data is not Opaque static int (*_XTreeGetTimedRecord)() = NULL; status = LibFindImageSymbol_C("XTreeShr", "_XTreeGetTimedRecord", &_XTreeGetTimedRecord); - if - STATUS_NOT_OK { - fprintf(stderr, - "Error activating XTreeShr library. Cannot access segmented " - "records.\n"); - return status; - } + if (STATUS_NOT_OK) + { + fprintf(stderr, + "Error activating XTreeShr library. Cannot access segmented " + "records.\n"); + return status; + } timecontext_t *tc = &((PINO_DATABASE *)dbid)->timecontext; return (*_XTreeGetTimedRecord)(dbid, nid, tc->start.pointer, tc->end.pointer, tc->delta.pointer, data); } int _TreeXNciPutRow(void *dbid, int nid, const char *xnci, int bufsize, - int64_t *timestamp, mdsdsc_a_t *data) { + int64_t *timestamp, mdsdsc_a_t *data) +{ DESCRIPTOR_A_COEFF(initValue, data->length, data->dtype, 0, 8, 0); INIT_STATUS_AS _TreeXNciPutTimestampedSegment(dbid, nid, xnci, timestamp, data); - if (status == TreeNOSEGMENTS || status == TreeBUFFEROVF) { + if (status == TreeNOSEGMENTS || status == TreeBUFFEROVF) + { status = TreeSUCCESS; while (data && data->dtype == DTYPE_DSC) data = (mdsdsc_a_t *)data->pointer; - if (data) { - if (data->class == CLASS_A) { + if (data) + { + if (data->class == CLASS_A) + { int i; initValue.arsize = data->arsize * bufsize; initValue.pointer = initValue.a0 = malloc(initValue.arsize); memset(initValue.pointer, 0, initValue.arsize); initValue.dimct = data->dimct + 1; - if (data->dimct == 1) { + if (data->dimct == 1) + { initValue.arsize = data->arsize * bufsize; initValue.m[0] = data->arsize / data->length; initValue.m[1] = bufsize; - } else { + } + else + { A_COEFF_TYPE *data_c = (A_COEFF_TYPE *)data; for (i = 0; i < data->dimct; i++) initValue.m[i] = data_c->m[i]; initValue.m[data->dimct] = bufsize; } - } else if (data->class == CLASS_S || data->class == CLASS_D) { + } + else if (data->class == CLASS_S || data->class == CLASS_D) + { initValue.arsize = data->length * bufsize; initValue.pointer = initValue.a0 = malloc(initValue.arsize); memset(initValue.pointer, 0, initValue.arsize); initValue.dimct = 1; initValue.m[0] = bufsize; - } else + } + else status = TreeFAILURE; - } else + } + else status = TreeFAILURE; - if - STATUS_OK { - status = _TreeXNciBeginTimestampedSegment(dbid, nid, xnci, - (mdsdsc_a_t *)&initValue, -1); - free(initValue.pointer); - if - STATUS_OK + if (STATUS_OK) + { + status = _TreeXNciBeginTimestampedSegment(dbid, nid, xnci, + (mdsdsc_a_t *)&initValue, -1); + free(initValue.pointer); + if (STATUS_OK) status = _TreeXNciPutTimestampedSegment(dbid, nid, xnci, timestamp, data); - } + } } return status; } @@ -2463,7 +2713,8 @@ int _TreeXNciPutRow(void *dbid, int nid, const char *xnci, int bufsize, * If -1 is specified return the last segment started for the segment. * - no clean up required. - */ -inline static int get_segment(vars_t *vars) { +inline static int get_segment(vars_t *vars) +{ int status; RETURN_IF_NOT_OK(open_index_read(vars)); if (vars->idx == -1) @@ -2479,7 +2730,8 @@ inline static int get_segment(vars_t *vars) { } int _TreeXNciGetSegmentLimits(void *dbid, int nid, const char *xnci, int idx, - mdsdsc_xd_t *retStart, mdsdsc_xd_t *retEnd) { + mdsdsc_xd_t *retStart, mdsdsc_xd_t *retEnd) +{ INIT_VARS; vars->idx = idx; RETURN_IF_NOT_OK(get_segment(vars)); @@ -2487,7 +2739,8 @@ int _TreeXNciGetSegmentLimits(void *dbid, int nid, const char *xnci, int idx, } int _TreeXNciGetSegment(void *dbid, int nid, const char *xnci, int idx, - mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) { + mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) +{ INIT_VARS; vars->idx = idx; RETURN_IF_NOT_OK(get_segment(vars)); @@ -2497,7 +2750,8 @@ int _TreeXNciGetSegment(void *dbid, int nid, const char *xnci, int idx, int _TreeXNciGetSegmentInfo(void *dbid, int nid, const char *xnci, int idx, char *dtype, char *dimct, int *dims, - int *next_row) { + int *next_row) +{ INIT_VARS; vars->idx = idx; RETURN_IF_NOT_OK(get_segment(vars)); @@ -2509,7 +2763,8 @@ int _TreeXNciGetSegmentInfo(void *dbid, int nid, const char *xnci, int idx, *dimct = vars->shead.dimct; if (dims) memcpy(dims, vars->shead.dims, sizeof(vars->shead.dims)); - if (next_row) { + if (next_row) + { if (vars->idx == vars->shead.idx) *next_row = vars->shead.next_row; else if (vars->sinfo->rows < 1) @@ -2522,42 +2777,49 @@ int _TreeXNciGetSegmentInfo(void *dbid, int nid, const char *xnci, int idx, } inline static int is_segment_in_range(vars_t *vars, mdsdsc_t *start, - mdsdsc_t *end) { + mdsdsc_t *end) +{ if (!(start && start->pointer) && !(end && end->pointer)) return B_TRUE; - if - IS_NOT_OK(LibFindImageSymbol_C("TdiShr", "_TdiExecute", &_TdiExecute)) - return B_FALSE; + if (IS_NOT_OK(LibFindImageSymbol_C("TdiShr", "_TdiExecute", &_TdiExecute))) + return B_FALSE; int ans; EMPTYXD(segstart); EMPTYXD(segend); ans = B_FALSE; DESCRIPTOR_LONG(ans_d, &ans); - if - IS_OK(get_segment_limits(vars, &segstart, &segend)) { - if ((start && start->pointer) && (end && end->pointer)) { - STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $) && ($ >= $)"); + if (IS_OK(get_segment_limits(vars, &segstart, &segend))) + { + if ((start && start->pointer) && (end && end->pointer)) + { + STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $) && ($ >= $)"); + ans &= IS_OK(_TdiExecute(&vars->dblist, &expression, start, &segend, + end, &segstart, &ans_d MDS_END_ARG)); + } + else + { + if (start && start->pointer) + { + STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $)"); ans &= IS_OK(_TdiExecute(&vars->dblist, &expression, start, &segend, - end, &segstart, &ans_d MDS_END_ARG)); - } else { - if (start && start->pointer) { - STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $)"); - ans &= IS_OK(_TdiExecute(&vars->dblist, &expression, start, &segend, - &ans_d MDS_END_ARG)); - } else { - STATIC_CONSTANT DESCRIPTOR(expression, "($ >= $)"); - ans &= (_TdiExecute(&vars->dblist, &expression, end, &segstart, - &ans_d MDS_END_ARG)); - } + &ans_d MDS_END_ARG)); + } + else + { + STATIC_CONSTANT DESCRIPTOR(expression, "($ >= $)"); + ans &= (_TdiExecute(&vars->dblist, &expression, end, &segstart, + &ans_d MDS_END_ARG)); } } + } MdsFree1Dx(&segstart, 0); MdsFree1Dx(&segend, 0); return ans; } int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, mdsdsc_t *start, - mdsdsc_t *end, mdsdsc_xd_t *out) { + mdsdsc_t *end, mdsdsc_xd_t *out) +{ /* Get all the segments in an apd which contain data between the start and end * times specified */ INIT_VARS; @@ -2570,43 +2832,49 @@ int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, mdsdsc_t *start, memset(dptr, 0, sizeof(mdsdsc_t *) * numsegs * 2); status = get_segment_index(vars->tinfo, vars->shead.index_offset, &vars->sindex); - for (vars->idx = numsegs; STATUS_OK && vars->idx-- > 0;) { + for (vars->idx = numsegs; STATUS_OK && vars->idx-- > 0;) + { while (STATUS_OK && vars->idx < vars->sindex.first_idx && vars->sindex.previous_offset > 0) status = get_segment_index(vars->tinfo, vars->sindex.previous_offset, &vars->sindex); - if - STATUS_NOT_OK break; + if (STATUS_NOT_OK) + break; vars->sinfo = &vars->sindex.segment[vars->idx % SEGMENTS_PER_INDEX]; - if (is_segment_in_range(vars, start, end)) { + if (is_segment_in_range(vars, start, end)) + { apd_off = vars->idx; EMPTYXD(segment); EMPTYXD(dim); segfound = B_TRUE; status = read_segment(dbid, vars->tinfo, nid, &vars->shead, vars->sinfo, vars->idx, &segment, &dim); - if - STATUS_OK { - apd.pointer[vars->idx * 2] = malloc(sizeof(mdsdsc_xd_t)); - memcpy(apd.pointer[vars->idx * 2], &segment, sizeof(mdsdsc_xd_t)); - apd.pointer[vars->idx * 2 + 1] = malloc(sizeof(mdsdsc_xd_t)); - memcpy(apd.pointer[vars->idx * 2 + 1], &dim, sizeof(mdsdsc_xd_t)); - } - else { + if (STATUS_OK) + { + apd.pointer[vars->idx * 2] = malloc(sizeof(mdsdsc_xd_t)); + memcpy(apd.pointer[vars->idx * 2], &segment, sizeof(mdsdsc_xd_t)); + apd.pointer[vars->idx * 2 + 1] = malloc(sizeof(mdsdsc_xd_t)); + memcpy(apd.pointer[vars->idx * 2 + 1], &dim, sizeof(mdsdsc_xd_t)); + } + else + { MdsFree1Dx(&segment, 0); MdsFree1Dx(&dim, 0); } - } else if (segfound) + } + else if (segfound) break; } - if - STATUS_OK { - apd.arsize = (numsegs - apd_off) * 2 * sizeof(mdsdsc_t *); - apd.pointer = &apd.pointer[apd_off * 2]; - status = MdsCopyDxXd((mdsdsc_t *)&apd, out); - } - for (vars->idx = apd_off << 1; vars->idx < numsegs << 1; vars->idx++) { - if (dptr[vars->idx] != NULL) { + if (STATUS_OK) + { + apd.arsize = (numsegs - apd_off) * 2 * sizeof(mdsdsc_t *); + apd.pointer = &apd.pointer[apd_off * 2]; + status = MdsCopyDxXd((mdsdsc_t *)&apd, out); + } + for (vars->idx = apd_off << 1; vars->idx < numsegs << 1; vars->idx++) + { + if (dptr[vars->idx] != NULL) + { MdsFree1Dx((mdsdsc_xd_t *)dptr[vars->idx], 0); free(dptr[vars->idx]); } @@ -2617,13 +2885,15 @@ int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, mdsdsc_t *start, int _TreeXNciSetSegmentScale(void *dbid, int nid, const char *xnci __attribute__((unused)), - mdsdsc_t *value) { + mdsdsc_t *value) +{ // TODO: support individual scaling return _TreeSetXNci(dbid, nid, XNCI_SEGMENT_SCALE_NAME, value); } int _TreeXNciGetSegmentScale(void *dbid, int nid, const char *xnci __attribute__((unused)), - mdsdsc_xd_t *value) { + mdsdsc_xd_t *value) +{ // TODO: support individual scaling return _TreeGetXNci(dbid, nid, XNCI_SEGMENT_SCALE_NAME, value); } @@ -2635,36 +2905,43 @@ int _TreeXNciGetSegmentScale(void *dbid, int nid, */ int _TreeMakeSegment(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx, - int rows_filled) { + int rows_filled) +{ return _TreeXNciMakeSegment(dbid, nid, NULL, start, end, dimension, initialValue, idx, rows_filled); } int TreeMakeSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx, - int rows_filled) { + int rows_filled) +{ return _TreeMakeSegment(*TreeCtx(), nid, start, end, dimension, initialValue, idx, rows_filled); } int _TreeXNciBeginSegment(void *dbid, int nid, const char *xnci, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, - mdsdsc_a_t *initialValue, int idx) { + mdsdsc_a_t *initialValue, int idx) +{ return _TreeXNciMakeSegment(dbid, nid, xnci, start, end, dimension, initialValue, idx, 0); } int _TreeBeginSegment(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx) { + mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx) +{ return _TreeXNciBeginSegment(dbid, nid, NULL, start, end, dimension, initialValue, idx); } int TreeBeginSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx) { + mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx) +{ return _TreeBeginSegment(*TreeCtx(), nid, start, end, dimension, initialValue, idx); } -int _TreePutSegment(void *dbid, int nid, const int startIdx, mdsdsc_a_t *data) { +int _TreePutSegment(void *dbid, int nid, const int startIdx, mdsdsc_a_t *data) +{ return _TreeXNciPutSegment(dbid, nid, NULL, startIdx, data); } -int TreePutSegment(const int nid, const int startIdx, mdsdsc_a_t *data) { +int TreePutSegment(const int nid, const int startIdx, mdsdsc_a_t *data) +{ return _TreePutSegment(*TreeCtx(), nid, startIdx, data); } @@ -2676,40 +2953,49 @@ int TreePutSegment(const int nid, const int startIdx, mdsdsc_a_t *data) { */ int _TreeMakeTimestampedSegment(void *dbid, int nid, int64_t *timestamps, mdsdsc_a_t *initialValue, int idx, - int rows_filled) { + int rows_filled) +{ return _TreeXNciMakeTimestampedSegment(dbid, nid, NULL, timestamps, initialValue, idx, rows_filled); } int TreeMakeTimestampedSegment(int nid, int64_t *timestamps, mdsdsc_a_t *initialValue, int idx, - int rows_filled) { + int rows_filled) +{ return _TreeMakeTimestampedSegment(*TreeCtx(), nid, timestamps, initialValue, idx, rows_filled); } int _TreeXNciBeginTimestampedSegment(void *dbid, int nid, const char *xnci, - mdsdsc_a_t *initialValue, int idx) { + mdsdsc_a_t *initialValue, int idx) +{ return _TreeXNciMakeTimestampedSegment(dbid, nid, xnci, NULL, initialValue, idx, 0); } int _TreeBeginTimestampedSegment(void *dbid, int nid, mdsdsc_a_t *initialValue, - int idx) { + int idx) +{ return _TreeXNciBeginTimestampedSegment(dbid, nid, NULL, initialValue, idx); } -int TreeBeginTimestampedSegment(int nid, mdsdsc_a_t *initialValue, int idx) { +int TreeBeginTimestampedSegment(int nid, mdsdsc_a_t *initialValue, int idx) +{ return _TreeBeginTimestampedSegment(*TreeCtx(), nid, initialValue, idx); } int _TreePutTimestampedSegment(void *dbid, int nid, int64_t *timestamp, - mdsdsc_a_t *data) { + mdsdsc_a_t *data) +{ return _TreeXNciPutTimestampedSegment(dbid, nid, NULL, timestamp, data); } -int TreePutTimestampedSegment(int nid, int64_t *timestamp, mdsdsc_a_t *data) { +int TreePutTimestampedSegment(int nid, int64_t *timestamp, mdsdsc_a_t *data) +{ return _TreePutTimestampedSegment(*TreeCtx(), nid, timestamp, data); } int _TreePutRow(void *dbid, int nid, int bufsize, int64_t *timestamp, - mdsdsc_a_t *data) { + mdsdsc_a_t *data) +{ return _TreeXNciPutRow(dbid, nid, NULL, bufsize, timestamp, data); } -int TreePutRow(int nid, int bufsize, int64_t *timestamp, mdsdsc_a_t *data) { +int TreePutRow(int nid, int bufsize, int64_t *timestamp, mdsdsc_a_t *data) +{ return _TreePutRow(*TreeCtx(), nid, bufsize, timestamp, data); } @@ -2717,10 +3003,12 @@ int TreePutRow(int nid, int bufsize, int64_t *timestamp, mdsdsc_a_t *data) { * node e.g. after it has been written to using beginSegment instead of * makeSegment */ -int _TreeSetRowsFilled(void *dbid, int nid, int rows_filled) { +int _TreeSetRowsFilled(void *dbid, int nid, int rows_filled) +{ return _TreeXNciSetRowsFilled(dbid, nid, NULL, rows_filled); } -int TreeSetRowsFilled(int nid, int rows_filled) { +int TreeSetRowsFilled(int nid, int rows_filled) +{ return _TreeSetRowsFilled(*TreeCtx(), nid, rows_filled); } @@ -2728,54 +3016,66 @@ int TreeSetRowsFilled(int nid, int rows_filled) { * without touchng the data part */ int _TreeUpdateSegment(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dimension, int idx) { + mdsdsc_t *dimension, int idx) +{ return _TreeXNciUpdateSegment(dbid, nid, NULL, start, end, dimension, idx); } int TreeUpdateSegment(int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dimension, int idx) { + mdsdsc_t *dimension, int idx) +{ return _TreeUpdateSegment(*TreeCtx(), nid, start, end, dimension, idx); } /* TreeGetNumSegments returns the number of segments stored in the node */ -int _TreeGetNumSegments(void *dbid, int nid, int *num) { +int _TreeGetNumSegments(void *dbid, int nid, int *num) +{ return _TreeXNciGetNumSegments(dbid, nid, NULL, num); } -int TreeGetNumSegments(int nid, int *num) { +int TreeGetNumSegments(int nid, int *num) +{ return _TreeGetNumSegments(*TreeCtx(), nid, num); } int _TreeGetSegmentLimits(void *dbid, int nid, int idx, mdsdsc_xd_t *retStart, - mdsdsc_xd_t *retEnd) { + mdsdsc_xd_t *retEnd) +{ return _TreeXNciGetSegmentLimits(dbid, nid, NULL, idx, retStart, retEnd); } int TreeGetSegmentLimits(int nid, int idx, mdsdsc_xd_t *retStart, - mdsdsc_xd_t *retEnd) { + mdsdsc_xd_t *retEnd) +{ return _TreeGetSegmentLimits(*TreeCtx(), nid, idx, retStart, retEnd); } int _TreeGetSegmentInfo(void *dbid, int nid, int idx, char *dtype, char *dimct, - int *dims, int *next_row) { + int *dims, int *next_row) +{ return _TreeXNciGetSegmentInfo(dbid, nid, NULL, idx, dtype, dimct, dims, next_row); } int TreeGetSegmentInfo(int nid, int idx, char *dtype, char *dimct, int *dims, - int *next_row) { + int *next_row) +{ return _TreeGetSegmentInfo(*TreeCtx(), nid, idx, dtype, dimct, dims, next_row); } -int _TreeGetSegmentScale(void *dbid, int nid, mdsdsc_xd_t *value) { +int _TreeGetSegmentScale(void *dbid, int nid, mdsdsc_xd_t *value) +{ return _TreeXNciGetSegmentScale(dbid, nid, NULL, value); } -int TreeGetSegmentScale(int nid, mdsdsc_xd_t *value) { +int TreeGetSegmentScale(int nid, mdsdsc_xd_t *value) +{ return _TreeGetSegmentScale(*TreeCtx(), nid, value); } -int _TreeSetSegmentScale(void *dbid, int nid, mdsdsc_t *value) { +int _TreeSetSegmentScale(void *dbid, int nid, mdsdsc_t *value) +{ return _TreeXNciSetSegmentScale(dbid, nid, NULL, value); } -int TreeSetSegmentScale(int nid, mdsdsc_t *value) { +int TreeSetSegmentScale(int nid, mdsdsc_t *value) +{ return _TreeSetSegmentScale(*TreeCtx(), nid, value); } @@ -2784,40 +3084,50 @@ int TreeSetSegmentScale(int nid, mdsdsc_t *value) { * performance */ int _TreeGetSegment(void *dbid, int nid, int idx, mdsdsc_xd_t *segment, - mdsdsc_xd_t *dim) { + mdsdsc_xd_t *dim) +{ return _TreeXNciGetSegment(dbid, nid, NULL, idx, segment, dim); } -int TreeGetSegment(int nid, int idx, mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) { +int TreeGetSegment(int nid, int idx, mdsdsc_xd_t *segment, mdsdsc_xd_t *dim) +{ return _TreeGetSegment(*TreeCtx(), nid, idx, segment, dim); } int _TreeGetSegments(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_xd_t *out) { + mdsdsc_xd_t *out) +{ return _TreeXNciGetSegments(dbid, nid, NULL, start, end, out); } -int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_xd_t *out) { +int TreeGetSegments(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_xd_t *out) +{ return _TreeGetSegments(*TreeCtx(), nid, start, end, out); } int _TreeGetSegmentTimesXd(void *dbid, int nid, int *nsegs, - mdsdsc_xd_t *start_list, mdsdsc_xd_t *end_list) { + mdsdsc_xd_t *start_list, mdsdsc_xd_t *end_list) +{ return _TreeXNciGetSegmentTimesXd(dbid, nid, NULL, nsegs, start_list, end_list); } int TreeGetSegmentTimesXd(int nid, int *nsegs, mdsdsc_xd_t *start_list, - mdsdsc_xd_t *end_list) { + mdsdsc_xd_t *end_list) +{ return _TreeGetSegmentTimesXd(*TreeCtx(), nid, nsegs, start_list, end_list); } -int _TreeGetSegmentTimes(void *dbid, int nid, int *nsegs, int64_t **times) { +int _TreeGetSegmentTimes(void *dbid, int nid, int *nsegs, int64_t **times) +{ return _TreeXNciGetSegmentTimes(dbid, nid, NULL, nsegs, times); } -int TreeGetSegmentTimes(int nid, int *nsegs, int64_t **times) { +int TreeGetSegmentTimes(int nid, int *nsegs, int64_t **times) +{ return _TreeGetSegmentTimes(*TreeCtx(), nid, nsegs, times); } -int _TreeGetSegmentedRecord(void *dbid, int nid, mdsdsc_xd_t *data) { +int _TreeGetSegmentedRecord(void *dbid, int nid, mdsdsc_xd_t *data) +{ return _TreeXNciGetSegmentedRecord(dbid, nid, NULL, data); } -int TreeGetSegmentedRecord(int nid, mdsdsc_xd_t *data) { +int TreeGetSegmentedRecord(int nid, mdsdsc_xd_t *data) +{ return _TreeGetSegmentedRecord(*TreeCtx(), nid, data); } @@ -2825,25 +3135,27 @@ int TreeGetSegmentedRecord(int nid, mdsdsc_xd_t *data) { TimeContext sticks with current db (tree) *****************************************/ int _TreeSetTimeContext(void *dbid, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *delta) { + mdsdsc_t *delta) +{ timecontext_t *tc = &((PINO_DATABASE *)dbid)->timecontext; int status = MdsCopyDxXd(start, &tc->start); - if - STATUS_OK { - status = MdsCopyDxXd(end, &tc->end); - if - STATUS_OK + if (STATUS_OK) + { + status = MdsCopyDxXd(end, &tc->end); + if (STATUS_OK) status = MdsCopyDxXd(delta, &tc->delta); - } + } return status; } -int TreeSetTimeContext(mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *delta) { +int TreeSetTimeContext(mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *delta) +{ return _TreeSetTimeContext(*TreeCtx(), start, end, delta); } int _TreeGetTimeContext(void *dbid, mdsdsc_xd_t *start, mdsdsc_xd_t *end, - mdsdsc_xd_t *delta) { + mdsdsc_xd_t *delta) +{ timecontext_t *tc = &((PINO_DATABASE *)dbid)->timecontext; int status; if (start) @@ -2855,14 +3167,17 @@ int _TreeGetTimeContext(void *dbid, mdsdsc_xd_t *start, mdsdsc_xd_t *end, return TreeSUCCESS; } int TreeGetTimeContext(mdsdsc_xd_t *start, mdsdsc_xd_t *end, - mdsdsc_xd_t *delta) { + mdsdsc_xd_t *delta) +{ return _TreeGetTimeContext(*TreeCtx(), start, end, delta); } ////////////RESAMPLED STUFF -inline static float toFloat(char dtype, void *ptr, int idx) { - switch (dtype) { +inline static float toFloat(char dtype, void *ptr, int idx) +{ + switch (dtype) + { case DTYPE_B: case DTYPE_BU: return ((int8_t *)ptr)[idx]; @@ -2891,12 +3206,15 @@ inline static float toFloat(char dtype, void *ptr, int idx) { } inline static void resampleRow(char dtype, int rowSize, int resFact, void *ptr, - float *resampled, int rowIdx) { + float *resampled, int rowIdx) +{ int currResIdx, currRowIdx; float avgVal; - for (currRowIdx = 0; currRowIdx < rowSize; currRowIdx++) { + for (currRowIdx = 0; currRowIdx < rowSize; currRowIdx++) + { avgVal = 0; - for (currResIdx = 0; currResIdx < resFact; currResIdx++) { + for (currResIdx = 0; currResIdx < resFact; currResIdx++) + { avgVal += toFloat(dtype, ptr, (rowIdx * resFact + currResIdx) * rowSize + currRowIdx); } @@ -2904,13 +3222,16 @@ inline static void resampleRow(char dtype, int rowSize, int resFact, void *ptr, } } inline static void resampleRowMinMax(char dtype, int rowSize, int resFact, - void *ptr, float *resampled, int rowIdx) { + void *ptr, float *resampled, int rowIdx) +{ int currResIdx, currRowIdx; float minVal, maxVal, currVal; - for (currRowIdx = 0; currRowIdx < rowSize; currRowIdx++) { + for (currRowIdx = 0; currRowIdx < rowSize; currRowIdx++) + { minVal = maxVal = toFloat(dtype, ptr, rowIdx * resFact * rowSize + currRowIdx); - for (currResIdx = 1; currResIdx < resFact; currResIdx++) { + for (currResIdx = 1; currResIdx < resFact; currResIdx++) + { currVal = toFloat(dtype, ptr, (rowIdx * resFact + currResIdx) * rowSize + currRowIdx); if (currVal < minVal) @@ -2926,7 +3247,8 @@ inline static void resampleRowMinMax(char dtype, int rowSize, int resFact, inline static void resampleArrayDsc(mdsdsc_a_t *inArray, void *outArray, int resFactor, int *retRowSize, int *retNRows, int *retNResRows, - int isMinMax) { + int isMinMax) +{ int dims[MAX_DIMS]; int nRows, nResRows, rowSize; int nDims = inArray->dimct; @@ -2934,17 +3256,21 @@ inline static void resampleArrayDsc(mdsdsc_a_t *inArray, void *outArray, ARRAY_COEFF(char *, 8) * resArray; resArray = outArray; - if (nDims > 1) { + if (nDims > 1) + { memcpy(dims, ((A_COEFF_TYPE *)inArray)->m, nDims * sizeof(int)); nRows = dims[nDims - 1]; rowSize = 1; - for (idx = 0; idx < nDims - 1; idx++) { + for (idx = 0; idx < nDims - 1; idx++) + { rowSize *= dims[idx]; } resArray->dimct = inArray->dimct; memcpy(resArray->m, ((A_COEFF_TYPE *)inArray)->m, inArray->dimct * sizeof(int)); - } else { + } + else + { nRows = inArray->arsize / inArray->length; rowSize = 1; resArray->dimct = 1; @@ -2964,7 +3290,8 @@ inline static void resampleArrayDsc(mdsdsc_a_t *inArray, void *outArray, int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int id, int rows_filled, - int resampledNid, int resFactor) { + int resampledNid, int resFactor) +{ // Resampled array always converted to float, Assumed 1D array int idx, status; int nRows, nResRows, rowSize, nSegs; @@ -2979,13 +3306,15 @@ int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, resampleArrayDsc(initialValue, &resD, resFactor, &rowSize, &nRows, &nResRows, 0); - if (nResRows < 1) { + if (nResRows < 1) + { return _TreeMakeSegment(dbid, nid, start, end, dimension, initialValue, id, rows_filled); } resSamples = (float *)malloc(nResRows * rowSize * sizeof(float)); resD.pointer = (char *)resSamples; - for (idx = 0; idx < nResRows; idx++) { + for (idx = 0; idx < nResRows; idx++) + { resampleRow(initialValue->dtype, rowSize, resFactor, initialValue->pointer, resSamples, idx); } @@ -2994,14 +3323,16 @@ int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, status = _TdiCompile(&dbid, &expression, start, end, &resFactorD, end, start, &nRowsD, &resFactorD, end, start, &nRowsD, &dimXd MDS_END_ARG); - if (!STATUS_OK) { + if (!STATUS_OK) + { free(resSamples); return status; } status = _TreeMakeSegment(dbid, resampledNid, start, end, dimXd.pointer, (struct descriptor_a *)&resD, -1, rows_filled / resFactor); - if (!STATUS_OK) { + if (!STATUS_OK) + { free(resSamples); MdsFree1Dx(&dimXd, NULL); return status; @@ -3010,16 +3341,20 @@ int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, MdsFree1Dx(&dimXd, NULL); status = _TreeGetNumSegments(dbid, nid, &nSegs); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } - if (nSegs == 1) { + if (nSegs == 1) + { status = _TreeSetXNci(dbid, nid, "ResampleFactor", &resFactorD); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } status = _TreeSetXNci(dbid, nid, "ResampleNid", &resNidD); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } } @@ -3030,7 +3365,8 @@ int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, int TreeMakeSegmentResampled(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int idx, int rows_filled, int resNid, - int resFactor) { + int resFactor) +{ return _TreeMakeSegmentResampled(*TreeCtx(), nid, start, end, dimension, initialValue, idx, rows_filled, resNid, resFactor); @@ -3039,7 +3375,8 @@ int TreeMakeSegmentResampled(int nid, mdsdsc_t *start, mdsdsc_t *end, int _TreeBeginSegmentResampled(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int id, - int resampledNid, int resFactor) { + int resampledNid, int resFactor) +{ return _TreeMakeSegmentResampled(dbid, nid, start, end, dimension, initialValue, id, 0, resampledNid, resFactor); @@ -3047,26 +3384,30 @@ int _TreeBeginSegmentResampled(void *dbid, int nid, mdsdsc_t *start, int TreeBeginSegmentResampled(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, - int idx, int resNid, int resFactor) { + int idx, int resNid, int resFactor) +{ return _TreeBeginSegmentResampled(*TreeCtx(), nid, start, end, dimension, initialValue, idx, resNid, resFactor); } int _TreePutSegmentResampled(void *dbid, int nid, int startIdx, mdsdsc_a_t *data, int resampledNid, - int resFactor) { + int resFactor) +{ int idx, status; int nRows, nResRows, rowSize; float *resSamples; // Resampled version always float DESCRIPTOR_A_COEFF(resD, sizeof(float), DTYPE_FS, NULL, 8, 0); resampleArrayDsc(data, &resD, resFactor, &rowSize, &nRows, &nResRows, 0); - if (nResRows < 1) { + if (nResRows < 1) + { return _TreePutSegment(dbid, nid, startIdx, data); } resSamples = (float *)malloc(nResRows * rowSize * sizeof(float)); resD.pointer = (char *)resSamples; - for (idx = 0; idx < nResRows; idx++) { + for (idx = 0; idx < nResRows; idx++) + { resampleRow(data->dtype, rowSize, resFactor, data->pointer, resSamples, idx); } @@ -3079,7 +3420,8 @@ int _TreePutSegmentResampled(void *dbid, int nid, int startIdx, } int TreePutSegmentResampled(const int nid, const int startIdx, mdsdsc_a_t *data, - int resNid, int resFactor) { + int resNid, int resFactor) +{ return _TreePutSegmentResampled(*TreeCtx(), nid, startIdx, data, resNid, resFactor); } @@ -3087,7 +3429,8 @@ int TreePutSegmentResampled(const int nid, const int startIdx, mdsdsc_a_t *data, int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, int id, int rows_filled, int resampledNid, - int resFactor) { + int resFactor) +{ // Resampled array always converted to float, Assumed 1D array int idx, status; int nRows, nResRows, rowSize, nSegs; @@ -3103,13 +3446,15 @@ int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, resampleArrayDsc(initialValue, &resD, resFactor, &rowSize, &nRows, &nResRows, 1); - if (nResRows < 1) { + if (nResRows < 1) + { return _TreeMakeSegment(dbid, nid, start, end, dimension, initialValue, id, rows_filled); } resSamples = (float *)malloc(nResRows * rowSize * sizeof(float)); resD.pointer = (char *)resSamples; - for (idx = 0; idx < nResRows / 2; idx++) { + for (idx = 0; idx < nResRows / 2; idx++) + { resampleRowMinMax(initialValue->dtype, rowSize, resFactor, initialValue->pointer, resSamples, idx); } @@ -3118,14 +3463,16 @@ int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, status = _TdiCompile(&dbid, &expression, start, end, &resFactorD, end, start, &nRowsD, &resFactorD, end, start, &nRowsD, &dimXd MDS_END_ARG); - if (!STATUS_OK) { + if (!STATUS_OK) + { free(resSamples); return status; } status = _TreeMakeSegment(dbid, resampledNid, start, end, dimXd.pointer, (struct descriptor_a *)&resD, -1, 2 * rows_filled / resFactor); - if (!STATUS_OK) { + if (!STATUS_OK) + { free(resSamples); MdsFree1Dx(&dimXd, NULL); return status; @@ -3134,20 +3481,25 @@ int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, MdsFree1Dx(&dimXd, NULL); status = _TreeGetNumSegments(dbid, nid, &nSegs); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } - if (nSegs == 1) { + if (nSegs == 1) + { status = _TreeSetXNci(dbid, nid, "ResampleMode", &minMaxD); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } status = _TreeSetXNci(dbid, nid, "ResampleFactor", &resFactorD); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } status = _TreeSetXNci(dbid, nid, "ResampleNid", &resNidD); - if (!STATUS_OK) { + if (!STATUS_OK) + { return status; } } @@ -3158,7 +3510,8 @@ int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, int TreeMakeSegmentMinMax(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, - int idx, int rows_filled, int resNid, int resFactor) { + int idx, int rows_filled, int resNid, int resFactor) +{ return _TreeMakeSegmentMinMax(*TreeCtx(), nid, start, end, dimension, initialValue, idx, rows_filled, resNid, resFactor); @@ -3166,32 +3519,37 @@ int TreeMakeSegmentMinMax(int nid, mdsdsc_t *start, mdsdsc_t *end, int _TreeBeginSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, - int id, int resampledNid, int resFactor) { + int id, int resampledNid, int resFactor) +{ return _TreeMakeSegmentMinMax(dbid, nid, start, end, dimension, initialValue, id, 0, resampledNid, resFactor); } int TreeBeginSegmentMinMax(int nid, mdsdsc_t *start, mdsdsc_t *end, mdsdsc_t *dimension, mdsdsc_a_t *initialValue, - int idx, int resNid, int resFactor) { + int idx, int resNid, int resFactor) +{ return _TreeBeginSegmentMinMax(*TreeCtx(), nid, start, end, dimension, initialValue, idx, resNid, resFactor); } int _TreePutSegmentMinMax(void *dbid, int nid, int startIdx, mdsdsc_a_t *data, - int resampledNid, int resFactor) { + int resampledNid, int resFactor) +{ int idx, status; int nRows, nResRows, rowSize; float *resSamples; // Resampled version always float DESCRIPTOR_A_COEFF(resD, sizeof(float), DTYPE_FS, NULL, 8, 0); resampleArrayDsc(data, &resD, resFactor, &rowSize, &nRows, &nResRows, 1); - if (nResRows < 1) { + if (nResRows < 1) + { return _TreePutSegment(dbid, nid, startIdx, data); } resSamples = (float *)malloc(nResRows * rowSize * sizeof(float)); resD.pointer = (char *)resSamples; - for (idx = 0; idx < nResRows / 2; idx++) { + for (idx = 0; idx < nResRows / 2; idx++) + { resampleRowMinMax(data->dtype, rowSize, resFactor, data->pointer, resSamples, idx); } @@ -3204,7 +3562,8 @@ int _TreePutSegmentMinMax(void *dbid, int nid, int startIdx, mdsdsc_a_t *data, } int TreePutSegmentMinMax(const int nid, const int startIdx, mdsdsc_a_t *data, - int resNid, int resFactor) { + int resNid, int resFactor) +{ return _TreePutSegmentMinMax(*TreeCtx(), nid, startIdx, data, resNid, resFactor); } diff --git a/treeshr/TreeSerializeNci.c b/treeshr/TreeSerializeNci.c index 602e617f37..fa4af32b8d 100644 --- a/treeshr/TreeSerializeNci.c +++ b/treeshr/TreeSerializeNci.c @@ -27,7 +27,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -void TreeSerializeNciOut(const NCI *in, char *out) { +void TreeSerializeNciOut(const NCI *in, char *out) +{ char *ptr = out; memset(out, 0, 42); putint32(&ptr, &in->flags); @@ -40,13 +41,18 @@ void TreeSerializeNciOut(const NCI *in, char *out) { putint32(&ptr, &in->length); putint8(&ptr, &in->spare2); putint32(&ptr, &in->status); - if (in->flags2 & NciM_DATA_IN_ATT_BLOCK) { + if (in->flags2 & NciM_DATA_IN_ATT_BLOCK) + { putint8(&ptr, &in->DATA_INFO.DATA_IN_RECORD.element_length); putchars(&ptr, &in->DATA_INFO.DATA_IN_RECORD.data, 11); - } else if (in->flags2 & NciM_ERROR_ON_PUT) { + } + else if (in->flags2 & NciM_ERROR_ON_PUT) + { putint32(&ptr, &in->DATA_INFO.ERROR_INFO.error_status); putint32(&ptr, &in->DATA_INFO.ERROR_INFO.stv); - } else { + } + else + { putint8(&ptr, &in->DATA_INFO.DATA_LOCATION.file_level); putint8(&ptr, &in->DATA_INFO.DATA_LOCATION.file_version); putchars(&ptr, &in->DATA_INFO.DATA_LOCATION.rfa, 6); @@ -54,7 +60,8 @@ void TreeSerializeNciOut(const NCI *in, char *out) { } } -void TreeSerializeNciIn(const char *in, NCI *out) { +void TreeSerializeNciIn(const char *in, NCI *out) +{ char *ptr = (char *)in; getint32(&ptr, &out->flags); getint8(&ptr, &out->flags2); @@ -66,13 +73,18 @@ void TreeSerializeNciIn(const char *in, NCI *out) { getint32(&ptr, &out->length); getint8(&ptr, &out->spare2); getint32(&ptr, &out->status); - if (out->flags2 & NciM_DATA_IN_ATT_BLOCK) { + if (out->flags2 & NciM_DATA_IN_ATT_BLOCK) + { getint8(&ptr, &out->DATA_INFO.DATA_IN_RECORD.element_length); getchars(&ptr, &out->DATA_INFO.DATA_IN_RECORD.data, 11); - } else if (out->flags2 & NciM_ERROR_ON_PUT) { + } + else if (out->flags2 & NciM_ERROR_ON_PUT) + { getint32(&ptr, &out->DATA_INFO.ERROR_INFO.error_status); getint32(&ptr, &out->DATA_INFO.ERROR_INFO.stv); - } else { + } + else + { getint8(&ptr, &out->DATA_INFO.DATA_LOCATION.file_level); getint8(&ptr, &out->DATA_INFO.DATA_LOCATION.file_version); getchars(&ptr, &out->DATA_INFO.DATA_LOCATION.rfa, 6); diff --git a/treeshr/TreeSetDbi.c b/treeshr/TreeSetDbi.c index 6989b26a0c..2f334b9b06 100644 --- a/treeshr/TreeSetDbi.c +++ b/treeshr/TreeSetDbi.c @@ -68,15 +68,17 @@ extern void **TreeCtx(); extern int SetDbiRemote(); -int TreeSetDbi(DBI_ITM *dbi_itm_ptr) { +int TreeSetDbi(DBI_ITM *dbi_itm_ptr) +{ return _TreeSetDbi(*TreeCtx(), dbi_itm_ptr); } -#define NEED_EDIT \ - if (!(IS_OPEN_FOR_EDIT(dblist))) \ +#define NEED_EDIT \ + if (!(IS_OPEN_FOR_EDIT(dblist))) \ return TreeNOEDIT; -int _TreeSetDbi(void *dbid, DBI_ITM *dbi_itm_ptr) { +int _TreeSetDbi(void *dbid, DBI_ITM *dbi_itm_ptr) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; int status = TreeSUCCESS; DBI_ITM *itm_ptr; @@ -88,8 +90,10 @@ int _TreeSetDbi(void *dbid, DBI_ITM *dbi_itm_ptr) { if (dblist->remote) return SetDbiRemote(dbid, dbi_itm_ptr); for (itm_ptr = dbi_itm_ptr; itm_ptr->code != NciEND_OF_LIST && status & 1; - itm_ptr++) { - switch (itm_ptr->code) { + itm_ptr++) + { + switch (itm_ptr->code) + { case DbiVERSIONS_IN_MODEL: NEED_EDIT dblist->tree_info->header->versions_in_model = @@ -115,7 +119,8 @@ int _TreeSetDbi(void *dbid, DBI_ITM *dbi_itm_ptr) { return status; } -int TreeSetDbiItm(int code, int value) { +int TreeSetDbiItm(int code, int value) +{ DBI_ITM itm[] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; itm[0].buffer_length = (short)sizeof(int); itm[0].code = (short)code; diff --git a/treeshr/TreeSetDefault.c b/treeshr/TreeSetDefault.c index 44d5117cd7..9475f780cb 100644 --- a/treeshr/TreeSetDefault.c +++ b/treeshr/TreeSetDefault.c @@ -27,19 +27,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern void **TreeCtx(); -int TreeSetDefault(char *path, int *nid) { +int TreeSetDefault(char *path, int *nid) +{ return _TreeSetDefault(*TreeCtx(), path, nid); } -int TreeSetDefaultNid(int nid_in) { +int TreeSetDefaultNid(int nid_in) +{ return _TreeSetDefaultNid(*TreeCtx(), nid_in); } -int TreeGetDefaultNid(int *nid_in) { +int TreeGetDefaultNid(int *nid_in) +{ return _TreeGetDefaultNid(*TreeCtx(), nid_in); } -int _TreeSetDefault(void *dbid, char *path, int *nid) { +int _TreeSetDefault(void *dbid, char *path, int *nid) +{ int status; status = _TreeFindNode(dbid, path, nid); if (status & 1) @@ -47,24 +51,30 @@ int _TreeSetDefault(void *dbid, char *path, int *nid) { return status; } -int _TreeSetDefaultNid(void *dbid, int nid_in) { +int _TreeSetDefaultNid(void *dbid, int nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nid_in; - if (IS_OPEN(dblist)) { + if (IS_OPEN(dblist)) + { NODE *node_ptr; if (dblist->remote) return SetDefaultNidRemote(dblist, nid_in); node_ptr = nid_to_node(dblist, nid); - if (node_ptr) { + if (node_ptr) + { dblist->default_node = node_ptr; return TreeSUCCESS; - } else + } + else return TreeNNF; - } else + } + else return TreeNOT_OPEN; } -int _TreeGetDefaultNid(void *dbid, int *nid_in) { +int _TreeGetDefaultNid(void *dbid, int *nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)nid_in; if (!(IS_OPEN(dblist))) diff --git a/treeshr/TreeSetNci.c b/treeshr/TreeSetNci.c index c51cddc135..13d49c8fcd 100644 --- a/treeshr/TreeSetNci.c +++ b/treeshr/TreeSetNci.c @@ -38,7 +38,8 @@ extern int TreeFlushResetRemote(); extern int TreeTurnOnRemote(); extern int TreeTurnOffRemote(); -int TreeSetNci(int nid, NCI_ITM *nci_itm_ptr) { +int TreeSetNci(int nid, NCI_ITM *nci_itm_ptr) +{ return _TreeSetNci(*TreeCtx(), nid, nci_itm_ptr); } @@ -50,12 +51,14 @@ int TreeTurnOn(int nid) { return _TreeTurnOn(*TreeCtx(), nid); } int TreeTurnOff(int nid) { return _TreeTurnOff(*TreeCtx(), nid); } -int TreeSetUsage(int nid_in, unsigned char usage) { +int TreeSetUsage(int nid_in, unsigned char usage) +{ return _TreeSetUsage(*TreeCtx(), nid_in, usage); } static int set_node_parent_state(PINO_DATABASE *db, NODE *node, NCI *nci, - unsigned int state) { + unsigned int state) +{ TREE_INFO *info; int node_num; int status; @@ -69,20 +72,22 @@ static int set_node_parent_state(PINO_DATABASE *db, NODE *node, NCI *nci, node_num = (int)(node - info->node); int locked = 0; status = tree_get_and_lock_nci(info, node_num, nci, &locked); - if - STATUS_OK { - bitassign(state, nci->flags, NciM_PARENT_STATE); - status = tree_put_nci(info, node_num, nci, &locked); - } + if (STATUS_OK) + { + bitassign(state, nci->flags, NciM_PARENT_STATE); + status = tree_put_nci(info, node_num, nci, &locked); + } return status; } -int tree_set_parent_state(PINO_DATABASE *db, NODE *node, unsigned int state) { +int tree_set_parent_state(PINO_DATABASE *db, NODE *node, unsigned int state) +{ int status; NCI nci; NODE *lnode; status = TreeSUCCESS; - for (lnode = node; lnode && STATUS_OK; lnode = brother_of(db, lnode)) { + for (lnode = node; lnode && STATUS_OK; lnode = brother_of(db, lnode)) + { status = set_node_parent_state(db, lnode, &nci, state); if (STATUS_OK && (!(nci.flags & NciM_STATE)) && (lnode->child)) status = tree_set_parent_state(db, child_of(db, lnode), state); @@ -93,23 +98,28 @@ int tree_set_parent_state(PINO_DATABASE *db, NODE *node, unsigned int state) { } int tree_lock_nci(TREE_INFO *info, int readonly, int nodenum, int *deleted, - int *locked) { + int *locked) +{ int status = TreeSUCCESS; int deleted_loc, *deleted_ptr = deleted ? deleted : &deleted_loc; - if (!info->header->readonly) { - if (*locked == 0) { // acquire lock + if (!info->header->readonly) + { + if (*locked == 0) + { // acquire lock status = MDS_IO_LOCK( readonly ? info->nci_file->get : info->nci_file->put, nodenum * 42, 42, readonly ? MDS_IO_LOCK_RD : MDS_IO_LOCK_WRT, deleted_ptr); - if - STATUS_OK { - if (!*deleted_ptr) - *locked = 3; // lock acquired and increment - else if (!deleted) - *locked = 2; // lock not acquired but caller did not provide - // deleted; increment w/o lock - } - } else { // increment and simulate + if (STATUS_OK) + { + if (!*deleted_ptr) + *locked = 3; // lock acquired and increment + else if (!deleted) + *locked = 2; // lock not acquired but caller did not provide + // deleted; increment w/o lock + } + } + else + { // increment and simulate if (deleted) *deleted = FALSE; *locked += 2; @@ -117,15 +127,18 @@ int tree_lock_nci(TREE_INFO *info, int readonly, int nodenum, int *deleted, } return status; } -void tree_unlock_nci(TREE_INFO *info, int readonly, int nodenum, int *locked) { - if (!info->header->readonly) { +void tree_unlock_nci(TREE_INFO *info, int readonly, int nodenum, int *locked) +{ + if (!info->header->readonly) + { #ifdef DEBUG if (*locked < 2) fprintf(stderr, "ERROR: tree_unlock_nci and *locked invalid: %d\n", *locked); #endif - *locked -= 2; // decrement - if (*locked == 1) { // last lock and lock acquired -> release lock + *locked -= 2; // decrement + if (*locked == 1) + { // last lock and lock acquired -> release lock MDS_IO_LOCK(readonly ? info->nci_file->get : info->nci_file->put, nodenum * 42, 42, MDS_IO_LOCK_NONE, 0); *locked = 0; @@ -157,7 +170,8 @@ void tree_unlock_nci(TREE_INFO *info, int readonly, int nodenum, int *locked) { +-----------------------------------------------------------------------------*/ -int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) { +int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid_in; int status; @@ -183,8 +197,10 @@ int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) { RETURN_IF_NOT_OK( tree_get_and_lock_nci(tree_info, node_number, &nci, &locked)); for (itm_ptr = nci_itm_ptr; itm_ptr->code != NciEND_OF_LIST && STATUS_OK; - itm_ptr++) { - switch (itm_ptr->code) { + itm_ptr++) + { + switch (itm_ptr->code) + { case NciSET_FLAGS: nci.flags |= *(unsigned int *)itm_ptr->pointer; putnci = 1; @@ -197,7 +213,8 @@ int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) { putnci = 1; nci.status = *(unsigned int *)itm_ptr->pointer; break; - case NciUSAGE: { + case NciUSAGE: + { NODE *node_ptr; /************************************************** @@ -209,7 +226,8 @@ int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) { status = TreeNOEDIT; node_ptr = nid_to_node(dblist, nid_ptr); - if (node_ptr->usage != *(unsigned char *)itm_ptr->pointer) { + if (node_ptr->usage != *(unsigned char *)itm_ptr->pointer) + { node_ptr->usage = *(unsigned char *)itm_ptr->pointer; dblist->modified = 1; } @@ -228,7 +246,8 @@ int _TreeSetNci(void *dbid, int nid_in, NCI_ITM *nci_itm_ptr) { return status; } -EXPORT int TreeSetNciItm(int nid, int code, int value) { +EXPORT int TreeSetNciItm(int nid, int code, int value) +{ NCI_ITM itm[] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; itm[0].buffer_length = (short)sizeof(int); itm[0].code = (short)code; @@ -236,7 +255,8 @@ EXPORT int TreeSetNciItm(int nid, int code, int value) { return TreeSetNci(nid, itm); } -int _TreeFlushOff(void *dbid, int nid) { +int _TreeFlushOff(void *dbid, int nid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; TREE_INFO *tree_info; @@ -251,7 +271,8 @@ int _TreeFlushOff(void *dbid, int nid) { return TreeSUCCESS; } -int _TreeFlushReset(void *dbid, int nid) { +int _TreeFlushReset(void *dbid, int nid) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid_ptr = (NID *)&nid; TREE_INFO *tree_info; @@ -262,7 +283,8 @@ int _TreeFlushReset(void *dbid, int nid) { nid_to_tree(dblist, nid_ptr, tree_info); if (!tree_info) return TreeNNF; - if ((tree_info->flush == 0) && (dblist->shotid == -1)) { + if ((tree_info->flush == 0) && (dblist->shotid == -1)) + { tree_info->flush = 1; TreeWait(tree_info); } @@ -293,7 +315,8 @@ node locking the record so that it can be updated. +-----------------------------------------------------------------------------*/ int tree_get_and_lock_nci(TREE_INFO *info, int node_num, NCI *nci, - int *locked) { + int *locked) +{ if (info->header->readonly) return TreeREADONLY_TREE; @@ -307,33 +330,37 @@ int tree_get_and_lock_nci(TREE_INFO *info, int node_num, NCI *nci, if OK so far then fill in the gab and read the record ******************************************/ - if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) { + if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) + { int deleted = TRUE; char nci_bytes[42]; if ((info->nci_file == 0) || (info->nci_file->put == 0)) RETURN_IF_NOT_OK(TreeOpenNciW(info, 0)); - while - STATUS_OK { - RETURN_IF_NOT_OK(tree_lock_nci(info, 0, node_num, &deleted, locked)); - if (!deleted) - break; - status = TreeReopenNci(info); - } - if - STATUS_OK { - MDS_IO_LSEEK(info->nci_file->put, node_num * sizeof(nci_bytes), - SEEK_SET); - if (MDS_IO_READ(info->nci_file->put, nci_bytes, sizeof(nci_bytes)) == - sizeof(nci_bytes)) { - TreeSerializeNciIn(nci_bytes, nci); - status = TreeSUCCESS; - } else - status = TreeNCIREAD; + while (STATUS_OK) + { + RETURN_IF_NOT_OK(tree_lock_nci(info, 0, node_num, &deleted, locked)); + if (!deleted) + break; + status = TreeReopenNci(info); + } + if (STATUS_OK) + { + MDS_IO_LSEEK(info->nci_file->put, node_num * sizeof(nci_bytes), + SEEK_SET); + if (MDS_IO_READ(info->nci_file->put, nci_bytes, sizeof(nci_bytes)) == + sizeof(nci_bytes)) + { + TreeSerializeNciIn(nci_bytes, nci); + status = TreeSUCCESS; } - if - STATUS_NOT_OK - tree_unlock_nci(info, 0, node_num, locked); - } else { + else + status = TreeNCIREAD; + } + if (STATUS_NOT_OK) + tree_unlock_nci(info, 0, node_num, locked); + } + else + { /******************************************** Otherwise the tree is open for edit so the characteristics are just a memory reference @@ -370,8 +397,9 @@ int tree_get_and_lock_nci(TREE_INFO *info, int node_num, NCI *nci, +-----------------------------------------------------------------------------*/ static char *tree_to_characteristic( const char *tree, - const int tmpfile) { // replace .tree with .characteristics or - // .characteristics# if tmpfile + const int tmpfile) +{ // replace .tree with .characteristics or + // .characteristics# if tmpfile const size_t baselen = strlen(tree) - sizeof("tree") + 1; const size_t namelen = baselen + (tmpfile ? sizeof("characteristics#") - 1 : sizeof("characteristics") - 1); @@ -380,13 +408,15 @@ static char *tree_to_characteristic( filename[namelen] = '\0'; return filename; } -int TreeOpenNciW(TREE_INFO *info, int tmpfile) { +int TreeOpenNciW(TREE_INFO *info, int tmpfile) +{ WRLOCKINFO(info); int status = _TreeOpenNciW(info, tmpfile); UNLOCKINFO(info); return status; } -int _TreeOpenNciW(TREE_INFO *info, int tmpfile) { +int _TreeOpenNciW(TREE_INFO *info, int tmpfile) +{ int status; /**************************************************** @@ -394,31 +424,34 @@ int _TreeOpenNciW(TREE_INFO *info, int tmpfile) { Allocate one *****************************************************/ - if (!info->nci_file) { + if (!info->nci_file) + { status = ((info->nci_file = (struct nci_file *)malloc(sizeof(NCI_FILE))) != NULL) ? TreeSUCCESS : TreeFAILURE; - if - STATUS_OK { - char *filename = tree_to_characteristic(info->filespec, tmpfile); - memset(info->nci_file, 0, sizeof(NCI_FILE)); - info->nci_file->get = MDS_IO_OPEN( - filename, tmpfile ? O_RDWR | O_CREAT | O_TRUNC | O_EXCL : O_RDONLY, - 0664); - status = (info->nci_file->get == -1) ? TreeFAILURE : TreeSUCCESS; - if (info->nci_file->get == -1) - info->nci_file->get = 0; - if - STATUS_OK { - info->nci_file->put = MDS_IO_OPEN(filename, O_RDWR, 0); - status = (info->nci_file->put == -1) ? TreeFAILURE : TreeSUCCESS; - if (info->nci_file->put == -1) - info->nci_file->put = 0; - } - free(filename); + if (STATUS_OK) + { + char *filename = tree_to_characteristic(info->filespec, tmpfile); + memset(info->nci_file, 0, sizeof(NCI_FILE)); + info->nci_file->get = MDS_IO_OPEN( + filename, tmpfile ? O_RDWR | O_CREAT | O_TRUNC | O_EXCL : O_RDONLY, + 0664); + status = (info->nci_file->get == -1) ? TreeFAILURE : TreeSUCCESS; + if (info->nci_file->get == -1) + info->nci_file->get = 0; + if (STATUS_OK) + { + info->nci_file->put = MDS_IO_OPEN(filename, O_RDWR, 0); + status = (info->nci_file->put == -1) ? TreeFAILURE : TreeSUCCESS; + if (info->nci_file->put == -1) + info->nci_file->put = 0; } - } else { + free(filename); + } + } + else + { /******************************************* Else the file was open for read access so open it for write access. @@ -434,16 +467,16 @@ int _TreeOpenNciW(TREE_INFO *info, int tmpfile) { info->nci_file->put = 0; free(filename); } - if - STATUS_OK { - if (info->edit) { - info->edit->first_in_mem = - (int)MDS_IO_LSEEK(info->nci_file->put, 0, SEEK_END) / 42; - } + if (STATUS_OK) + { + if (info->edit) + { + info->edit->first_in_mem = + (int)MDS_IO_LSEEK(info->nci_file->put, 0, SEEK_END) / 42; } - if - STATUS_OK - TreeCallHook(OpenNCIFileWrite, info, 0); + } + if (STATUS_OK) + TreeCallHook(OpenNCIFileWrite, info, 0); return status; } @@ -471,13 +504,15 @@ int _TreeOpenNciW(TREE_INFO *info, int tmpfile) { +-----------------------------------------------------------------------------*/ -int tree_put_nci(TREE_INFO *info, int node_num, NCI *nci, int *locked) { +int tree_put_nci(TREE_INFO *info, int node_num, NCI *nci, int *locked) +{ int status = TreeSUCCESS; /*************************************** If the tree is not open for edit ****************************************/ - if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) { + if ((info->edit == 0) || (node_num < info->edit->first_in_mem)) + { /********************** Update the NCI record @@ -500,7 +535,8 @@ int tree_put_nci(TREE_INFO *info, int node_num, NCI *nci, int *locked) { memory reference away. *****************************/ - else { + else + { memcpy(info->edit->nci + (node_num - info->edit->first_in_mem), nci, sizeof(*nci)); if (!*locked) @@ -532,7 +568,8 @@ int tree_put_nci(TREE_INFO *info, int node_num, NCI *nci, int *locked) { +-----------------------------------------------------------------------------*/ -int _TreeTurnOn(void *dbid, int nid_in) { +int _TreeTurnOn(void *dbid, int nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nid_in; int status; @@ -549,18 +586,23 @@ int _TreeTurnOn(void *dbid, int nid_in) { return TreeNNF; int locked = 0; RETURN_IF_NOT_OK(tree_get_and_lock_nci(info, node_num, &nci, &locked)); - if (nci.flags & NciM_STATE) { + if (nci.flags & NciM_STATE) + { bitassign(0, nci.flags, NciM_STATE); RETURN_IF_NOT_OK(tree_put_nci(info, node_num, &nci, &locked)); - if (!(nci.flags & NciM_PARENT_STATE)) { + if (!(nci.flags & NciM_PARENT_STATE)) + { node = nid_to_node(dblist, nid); if (node->child) status = tree_set_parent_state(dblist, child_of(dblist, node), 0); if (node->member) status = tree_set_parent_state(dblist, member_of(node), 0); - } else + } + else status = TreePARENT_OFF; - } else { + } + else + { tree_unlock_nci(info, 0, node_num, &locked); status = TreeALREADY_ON; } @@ -590,7 +632,8 @@ int _TreeTurnOn(void *dbid, int nid_in) { +-----------------------------------------------------------------------------*/ -int _TreeTurnOff(void *dbid, int nid_in) { +int _TreeTurnOff(void *dbid, int nid_in) +{ PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; NID *nid = (NID *)&nid_in; int status; @@ -607,24 +650,29 @@ int _TreeTurnOff(void *dbid, int nid_in) { return TreeNNF; int locked = 0; RETURN_IF_NOT_OK(tree_get_and_lock_nci(info, node_num, &nci, &locked)); - if (!(nci.flags & NciM_STATE)) { + if (!(nci.flags & NciM_STATE)) + { bitassign(1, nci.flags, NciM_STATE); RETURN_IF_NOT_OK(tree_put_nci(info, node_num, &nci, &locked)); - if (!(nci.flags & NciM_PARENT_STATE)) { + if (!(nci.flags & NciM_PARENT_STATE)) + { node = nid_to_node(dblist, nid); if (node->child) status = tree_set_parent_state(dblist, child_of(dblist, node), 1); if (node->member) status = tree_set_parent_state(dblist, member_of(node), 1); } - } else { + } + else + { tree_unlock_nci(info, 0, node_num, &locked); status = TreeALREADY_OFF; } return status; } -int _TreeSetUsage(void *dbid, int nid_in, unsigned char usage) { +int _TreeSetUsage(void *dbid, int nid_in, unsigned char usage) +{ NCI_ITM itm[] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; itm[0].buffer_length = (short)sizeof(usage); itm[0].code = (short)NciUSAGE; diff --git a/treeshr/TreeThreadStatic.c b/treeshr/TreeThreadStatic.c index e1056145d5..85fd5245a7 100644 --- a/treeshr/TreeThreadStatic.c +++ b/treeshr/TreeThreadStatic.c @@ -40,18 +40,25 @@ extern int _TreeNewDbid(void **dblist); static pthread_rwlock_t treectx_lock = PTHREAD_RWLOCK_INITIALIZER; static void *DBID = NULL, *G_DBID = NULL; -static void buffer_free(TREETHREADSTATIC_ARG) { - if (TREE_DBID) { +static void buffer_free(TREETHREADSTATIC_ARG) +{ + if (TREE_DBID) + { PINO_DATABASE *g_dbid, *p_dbid; pthread_rwlock_rdlock(&treectx_lock); for (g_dbid = G_DBID; g_dbid && g_dbid != TREE_DBID; g_dbid = g_dbid->next) ; - if (g_dbid) { + if (g_dbid) + { pthread_rwlock_unlock(&treectx_lock); perror("privateCtx share globalCtx on Threadexit! -> memory leak"); - } else { - for (p_dbid = TREE_DBID; p_dbid->next; p_dbid = p_dbid->next) { - if (p_dbid->next == G_DBID) { + } + else + { + for (p_dbid = TREE_DBID; p_dbid->next; p_dbid = p_dbid->next) + { + if (p_dbid->next == G_DBID) + { // clip private context if extension of global p_dbid->next = NULL; break; @@ -63,7 +70,8 @@ static void buffer_free(TREETHREADSTATIC_ARG) { } free(TREETHREADSTATIC_VAR); } -static inline TREETHREADSTATIC_TYPE *buffer_alloc() { +static inline TREETHREADSTATIC_TYPE *buffer_alloc() +{ TREETHREADSTATIC_ARG = (TREETHREADSTATIC_TYPE *)calloc(1, sizeof(TREETHREADSTATIC_TYPE)); return TREETHREADSTATIC_VAR; @@ -72,16 +80,21 @@ static inline TREETHREADSTATIC_TYPE *buffer_alloc() { IMPLEMENT_GETTHREADSTATIC(TREETHREADSTATIC_TYPE, TreeGetThreadStatic, THREADSTATIC_TREESHR, buffer_alloc, buffer_free) -EXPORT void **TreeCtx() { +EXPORT void **TreeCtx() +{ TREETHREADSTATIC_INIT; void **ctx; - if (TREE_PRIVATECTX) { + if (TREE_PRIVATECTX) + { if (!TREE_DBID) _TreeNewDbid(&TREE_DBID); ctx = &TREE_DBID; - } else { + } + else + { pthread_rwlock_wrlock(&treectx_lock); - if (!DBID) { + if (!DBID) + { if (!G_DBID) _TreeNewDbid(&G_DBID); DBID = G_DBID; @@ -96,13 +109,17 @@ EXPORT void *TreeDbid() { return *TreeCtx(); } EXPORT void *_TreeDbid(void **dbid) { return *dbid; } -EXPORT void *TreeSwitchDbid(void *dbid) { +EXPORT void *TreeSwitchDbid(void *dbid) +{ TREETHREADSTATIC_INIT; void *old_dbid; - if (TREE_PRIVATECTX) { + if (TREE_PRIVATECTX) + { old_dbid = TREE_DBID; TREE_DBID = dbid; - } else { + } + else + { pthread_rwlock_wrlock(&treectx_lock); old_dbid = DBID; DBID = dbid; @@ -111,24 +128,28 @@ EXPORT void *TreeSwitchDbid(void *dbid) { return old_dbid; } -EXPORT int TreeUsePrivateCtx(int onoff) { +EXPORT int TreeUsePrivateCtx(int onoff) +{ TREETHREADSTATIC_INIT; int old = TREE_PRIVATECTX; TREE_PRIVATECTX = onoff != 0; return old; } -EXPORT int TreeUsingPrivateCtx() { +EXPORT int TreeUsingPrivateCtx() +{ TREETHREADSTATIC_INIT; return TREE_PRIVATECTX; } -typedef struct { +typedef struct +{ void *dbid; void **ctx; int priv; } push_ctx_t; -EXPORT void *TreeCtxPush(void **ctx) { +EXPORT void *TreeCtxPush(void **ctx) +{ /* switch to private context and use dbid * SHOULD be used with pthread_cleanup or similar constucts * DONT USE this from tdi; will cause memory violation @@ -143,7 +164,8 @@ EXPORT void *TreeCtxPush(void **ctx) { return ps; } -EXPORT void TreeCtxPop(void *ps) { +EXPORT void TreeCtxPop(void *ps) +{ /* done using dbid in private context, restore state */ TREETHREADSTATIC_INIT; @@ -153,11 +175,13 @@ EXPORT void TreeCtxPop(void *ps) { free(ps); } -typedef struct { +typedef struct +{ void *dbid; int priv; } push_dbid_t; -EXPORT void *TreeDbidPush(void *dbid) { +EXPORT void *TreeDbidPush(void *dbid) +{ /* switch to private context and use dbid * DONT USE with pthread_cleanup * Useful when called from tdi @@ -171,7 +195,8 @@ EXPORT void *TreeDbidPush(void *dbid) { return ps; } -EXPORT void *TreeDbidPop(void *ps) { +EXPORT void *TreeDbidPop(void *ps) +{ /* done using dbid in private context, restore state */ TREETHREADSTATIC_INIT; diff --git a/treeshr/TreeVerify.c b/treeshr/TreeVerify.c index 76dd610913..8c700415a1 100644 --- a/treeshr/TreeVerify.c +++ b/treeshr/TreeVerify.c @@ -67,21 +67,25 @@ extern void **TreeCtx(); int TreeVerify() { return _TreeVerify(*TreeCtx()); } -int _TreeVerify(void *dbid) { +int _TreeVerify(void *dbid) +{ int status; PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; - if (dblist && dblist->tree_info) { + if (dblist && dblist->tree_info) + { NODE *firstempty = (dblist->tree_info->header->free == -1) ? (NODE *)0 : (NODE *)((char *)dblist->tree_info->node + dblist->tree_info->header->free); nodecount = 0; maxnodes = dblist->tree_info->header->nodes; - if (countnodes(dblist, dblist->tree_info->node)) { + if (countnodes(dblist, dblist->tree_info->node)) + { int allocated = nodecount; printf("Node summary:\n"); printf(" Allocated = %d/%d\n", nodecount, maxnodes); - if (countfree(dblist, firstempty)) { + if (countfree(dblist, firstempty)) + { int free = nodecount - allocated; int other = maxnodes - nodecount; printf(" Free = %d/%d\n", free, maxnodes); @@ -89,36 +93,44 @@ int _TreeVerify(void *dbid) { } } status = TreeSUCCESS; - } else + } + else status = TreeNOT_OPEN; return status; } -static int countnodes(PINO_DATABASE *dblist, NODE *node) { - if (node) { +static int countnodes(PINO_DATABASE *dblist, NODE *node) +{ + if (node) + { nodecount++; - if (nodecount > maxnodes) { + if (nodecount > maxnodes) + { printf("Too many nodes found - exceeds total nodes %d\n", maxnodes); return 0; } - switch (node->usage) { + switch (node->usage) + { case TreeUSAGE_SUBTREE_REF: break; case TreeUSAGE_SUBTREE_TOP: break; default: - if (member_of(node)) { + if (member_of(node)) + { if (parent_of(dblist, member_of(node)) != node) printf("Bad node linkage\n"); countnodes(dblist, member_of(node)); } - if (child_of(dblist, node)) { + if (child_of(dblist, node)) + { if (parent_of(dblist, child_of(dblist, node)) != node) printf("Bad node linkage\n"); countnodes(dblist, child_of(dblist, node)); } } - if (brother_of(dblist, node)) { + if (brother_of(dblist, node)) + { if (parent_of(dblist, brother_of(dblist, node)) != parent_of(dblist, node)) printf("Bad node linkage\n"); @@ -128,11 +140,14 @@ static int countnodes(PINO_DATABASE *dblist, NODE *node) { return 1; } -static int countfree(PINO_DATABASE *dblist, NODE *node) { +static int countfree(PINO_DATABASE *dblist, NODE *node) +{ NODE *lnode; - for (lnode = node; lnode; lnode = parent_of(dblist, lnode)) { + for (lnode = node; lnode; lnode = parent_of(dblist, lnode)) + { nodecount++; - if (nodecount > maxnodes) { + if (nodecount > maxnodes) + { printf("Too many nodes found - exceeds total nodes %d\n", maxnodes); return 0; } diff --git a/treeshr/dummies.c b/treeshr/dummies.c index 927a09f6b9..744b082254 100644 --- a/treeshr/dummies.c +++ b/treeshr/dummies.c @@ -27,18 +27,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define Dummy(name, status) \ - int name() { \ - int stat = status; \ - if (!(stat & 1)) \ - printf("%s not currently implemented\n", #name); \ - return stat; \ +#define Dummy(name, status) \ + int name() \ + { \ + int stat = status; \ + if (!(stat & 1)) \ + printf("%s not currently implemented\n", #name); \ + return stat; \ } -#define DummyArgs(name, ret, args, status) \ - ret name args { \ - printf("%s not currently implemented\n", #name); \ - return status; \ +#define DummyArgs(name, ret, args, status) \ + ret name args \ + { \ + printf("%s not currently implemented\n", #name); \ + return status; \ } Dummy(TreeEstablishRundownEvent, TreeSUCCESS) Dummy(TreeWait, TreeSUCCESS) diff --git a/treeshr/lex.yytreepath.c b/treeshr/lex.yytreepath.c deleted file mode 100644 index 6e998b3763..0000000000 --- a/treeshr/lex.yytreepath.c +++ /dev/null @@ -1,2104 +0,0 @@ - -#line 3 "lex.yytreepath.c" - -#define YY_INT_ALIGNED short int - -/* A lexical scanner generated by flex */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 -#define YY_FLEX_SUBMINOR_VERSION 35 -#if YY_FLEX_SUBMINOR_VERSION > 0 -#define FLEX_BETA -#endif - -/* First, we deal with platform-specific or compiler-specific issues. */ - -/* begin standard C headers. */ -#include -#include -#include -#include - -/* end standard C headers. */ - -/* flex integer type definitions */ - -#ifndef FLEXINT_H -#define FLEXINT_H - -/* C99 systems have . Non-C99 systems may or may not. */ - -#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - -/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, - * if you want the limit (max/min) macros for int types. - */ -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS 1 -#endif - -#include -typedef int8_t flex_int8_t; -typedef uint8_t flex_uint8_t; -typedef int16_t flex_int16_t; -typedef uint16_t flex_uint16_t; -typedef int32_t flex_int32_t; -typedef uint32_t flex_uint32_t; -typedef uint64_t flex_uint64_t; -#else -typedef signed char flex_int8_t; -typedef short int flex_int16_t; -typedef int flex_int32_t; -typedef unsigned char flex_uint8_t; -typedef unsigned short int flex_uint16_t; -typedef unsigned int flex_uint32_t; -#endif /* ! C99 */ - -/* Limits of integral types. */ -#ifndef INT8_MIN -#define INT8_MIN (-128) -#endif -#ifndef INT16_MIN -#define INT16_MIN (-32767 - 1) -#endif -#ifndef INT32_MIN -#define INT32_MIN (-2147483647 - 1) -#endif -#ifndef INT8_MAX -#define INT8_MAX (127) -#endif -#ifndef INT16_MAX -#define INT16_MAX (32767) -#endif -#ifndef INT32_MAX -#define INT32_MAX (2147483647) -#endif -#ifndef UINT8_MAX -#define UINT8_MAX (255U) -#endif -#ifndef UINT16_MAX -#define UINT16_MAX (65535U) -#endif -#ifndef UINT32_MAX -#define UINT32_MAX (4294967295U) -#endif - -#endif /* ! FLEXINT_H */ - -#ifdef __cplusplus - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -/* C99 requires __STDC__ to be defined as 1. */ -#if defined(__STDC__) - -#define YY_USE_CONST - -#endif /* defined (__STDC__) */ -#endif /* ! __cplusplus */ - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int)(unsigned char)c) - -/* An opaque pointer. */ -#ifndef YY_TYPEDEF_YY_SCANNER_T -#define YY_TYPEDEF_YY_SCANNER_T -typedef void *yyscan_t; -#endif - -/* For convenience, these vars (plus the bison vars far below) - are macros in the reentrant scanner. */ -#define yyin yyg->yyin_r -#define yyout yyg->yyout_r -#define yyextra yyg->yyextra_r -#define yyleng yyg->yyleng_r -#define yytext yyg->yytext_r -#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) -#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) -#define yy_flex_debug yyg->yy_flex_debug_r - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yyg->yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yyg->yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yytreepathrestart(yyin, yyscanner) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#ifndef YY_BUF_SIZE -#define YY_BUF_SIZE 16384 -#endif - -/* The state buf must be large enough to hold one state per character in the - * main buffer. - */ -#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) - -#ifndef YY_TYPEDEF_YY_BUFFER_STATE -#define YY_TYPEDEF_YY_BUFFER_STATE -typedef struct yy_buffer_state *YY_BUFFER_STATE; -#endif - -#ifndef YY_TYPEDEF_YY_SIZE_T -#define YY_TYPEDEF_YY_SIZE_T -typedef size_t yy_size_t; -#endif - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -#define YY_LESS_LINENO(n) - -/* Return all but the first "n" matched characters back to the input stream. */ -#define yyless(n) \ - do { \ - /* Undo effects of setting up yytext. */ \ - int yyless_macro_arg = (n); \ - YY_LESS_LINENO(yyless_macro_arg); \ - *yy_cp = yyg->yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } while (0) - -#define unput(c) yyunput(c, yyg->yytext_ptr, yyscanner) - -#ifndef YY_STRUCT_YY_BUFFER_STATE -#define YY_STRUCT_YY_BUFFER_STATE -struct yy_buffer_state { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - yy_size_t yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - int yy_bs_lineno; /**< The line count. */ - int yy_bs_column; /**< The column count. */ - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; - -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yytreepathrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 -}; -#endif /* !YY_STRUCT_YY_BUFFER_STATE */ - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - * - * Returns the top of the stack, or NULL. - */ -#define YY_CURRENT_BUFFER \ - (yyg->yy_buffer_stack ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] : NULL) - -/* Same as previous macro, but useful when we know that the buffer stack is not - * NULL or when we need an lvalue. For internal use only. - */ -#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] - -void yytreepathrestart(FILE *input_file, yyscan_t yyscanner); -void yytreepath_switch_to_buffer(YY_BUFFER_STATE new_buffer, - yyscan_t yyscanner); -YY_BUFFER_STATE yytreepath_create_buffer(FILE *file, int size, - yyscan_t yyscanner); -void yytreepath_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner); -void yytreepath_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner); -void yytreepathpush_buffer_state(YY_BUFFER_STATE new_buffer, - yyscan_t yyscanner); -void yytreepathpop_buffer_state(yyscan_t yyscanner); - -static void yytreepathensure_buffer_stack(yyscan_t yyscanner); -static void yytreepath_load_buffer_state(yyscan_t yyscanner); -static void yytreepath_init_buffer(YY_BUFFER_STATE b, FILE *file, - yyscan_t yyscanner); - -#define YY_FLUSH_BUFFER yytreepath_flush_buffer(YY_CURRENT_BUFFER, yyscanner) - -YY_BUFFER_STATE yytreepath_scan_buffer(char *base, yy_size_t size, - yyscan_t yyscanner); -YY_BUFFER_STATE yytreepath_scan_string(yyconst char *yy_str, - yyscan_t yyscanner); -YY_BUFFER_STATE yytreepath_scan_bytes(yyconst char *bytes, yy_size_t len, - yyscan_t yyscanner); - -void *yytreepathalloc(yy_size_t, yyscan_t yyscanner); -void *yytreepathrealloc(void *, yy_size_t, yyscan_t yyscanner); -void yytreepathfree(void *, yyscan_t yyscanner); - -#define yy_new_buffer yytreepath_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if (!YY_CURRENT_BUFFER) { \ - yytreepathensure_buffer_stack(yyscanner); \ - YY_CURRENT_BUFFER_LVALUE = \ - yytreepath_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \ - } \ - YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if (!YY_CURRENT_BUFFER) { \ - yytreepathensure_buffer_stack(yyscanner); \ - YY_CURRENT_BUFFER_LVALUE = \ - yytreepath_create_buffer(yyin, YY_BUF_SIZE, yyscanner); \ - } \ - YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) - -/* Begin user sect3 */ - -#define yytreepathwrap(n) 1 -#define YY_SKIP_YYWRAP - -typedef unsigned char YY_CHAR; - -typedef int yy_state_type; - -#define yytext_ptr yytext_r - -static yy_state_type yy_get_previous_state(yyscan_t yyscanner); -static yy_state_type yy_try_NUL_trans(yy_state_type current_state, - yyscan_t yyscanner); -static int yy_get_next_buffer(yyscan_t yyscanner); -static void yy_fatal_error(yyconst char msg[], yyscan_t yyscanner); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yyg->yytext_ptr = yy_bp; \ - yyleng = (yy_size_t)(yy_cp - yy_bp); \ - yyg->yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yyg->yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 14 -#define YY_END_OF_BUFFER 15 -/* This struct is not used in this scanner, - but its presence is necessary. */ -struct yy_trans_info { - flex_int32_t yy_verify; - flex_int32_t yy_nxt; -}; -static yyconst flex_int16_t yy_accept[136] = { - 0, 6, 6, 15, 13, 12, 9, 9, 7, 6, 13, 8, 13, 13, 9, 9, 10, 7, 0, 8, 9, - 0, 0, 8, 0, 11, 0, 2, 9, 6, 10, 3, 4, 8, 5, 11, 6, 2, 0, 9, 10, 8, - 5, 11, 2, 0, 9, 10, 8, 5, 11, 2, 1, 9, 10, 8, 5, 11, 2, 1, 9, 10, 8, - 5, 11, 2, 1, 9, 10, 8, 5, 11, 2, 1, 9, 10, 8, 5, 11, 2, 1, 9, 10, 8, - 5, 11, 2, 1, 9, 10, 8, 5, 11, 2, 1, 9, 10, 8, 5, 11, 2, - - 1, 10, 8, 5, 11, 2, 1, 5, 2, 1, 5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 0}; - -static yyconst flex_int32_t yy_ec[256] = { - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4, 1, 1, 5, 6, 1, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 7, 1, 1, 1, 1, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 8, 1, 9, 3, 1, 3, 3, 3, - 3, - - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, - 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1}; - -static yyconst flex_int32_t yy_meta[11] = {0, 1, 1, 2, 2, 1, 1, 3, 1, 4, 5}; - -static yyconst flex_int16_t yy_base[240] = { - 0, 0, 154, 161, 163, 163, 0, 156, 163, 8, 15, 150, 148, 0, 0, - 153, 0, 163, 150, 146, 0, 147, 143, 0, 143, 0, 141, 143, 0, 0, - 0, 163, 163, 0, 0, 0, 163, 142, 141, 0, 0, 0, 0, 0, 140, - 0, 0, 0, 0, 0, 0, 139, 0, 0, 0, 0, 0, 0, 138, 0, - 0, 0, 0, 0, 0, 137, 0, 0, 0, 0, 0, 0, 136, 0, 0, - 0, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 134, 0, 0, 0, - 0, 0, 0, 133, 0, 163, 0, 0, 0, 0, 132, - - 0, 163, 163, 0, 163, 131, 0, 0, 0, 0, 163, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 163, - 0, 0, 0, 163, 163, 135, 24, 27, 134, 133, 132, 131, 130, 31, 129, - 128, 127, 126, 125, 33, 124, 123, 122, 121, 120, 35, 119, 118, 117, 116, - 115, 114, 37, 113, 112, 111, 110, 109, 108, 39, 107, 106, 105, 104, 103, - 102, 41, 101, 100, 99, 98, 97, 96, 43, 95, 94, 93, 92, 91, 90, - 45, 89, 88, 87, 86, 85, 84, 47, 83, 82, - - 81, 80, 79, 78, 49, 77, 76, 75, 74, 73, 51, 72, 71, 53, 70, - 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, - 29, 28, 25, 22, 21, 19, 18, 14, 13}; - -static yyconst flex_int16_t yy_def[240] = { - 0, 135, 1, 135, 135, 135, 136, 136, 135, 135, 135, 137, 138, 139, 140, - 140, 141, 135, 135, 137, 136, 135, 135, 142, 135, 143, 135, 144, 145, 145, - 146, 135, 135, 147, 148, 149, 135, 150, 135, 151, 152, 153, 154, 155, 156, - 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, - 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, - 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, - 202, 203, 204, 205, 206, 135, 207, 208, 209, 210, 211, - - 212, 135, 135, 213, 135, 214, 215, 216, 217, 218, 135, 219, 220, 221, 222, - 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 135, - 237, 238, 239, 135, 0, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, - 135, 135, 135, 135, 135, 135, 135, 135, 135}; - -static yyconst flex_int16_t yy_nxt[174] = { - 0, 4, 5, 6, 7, 8, 9, 10, 4, 11, 12, 16, 16, 17, 18, - 134, 133, 19, 20, 20, 132, 131, 21, 130, 129, 22, 23, 128, 23, 25, - 127, 126, 25, 37, 37, 44, 44, 51, 51, 58, 58, 65, 65, 72, 72, - 79, 79, 86, 86, 93, 93, 100, 100, 106, 106, 109, 109, 125, 124, 123, - 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 108, 107, - 105, 104, 103, 102, 101, 99, 98, 97, 96, 95, 94, 92, 91, 90, 89, - 88, 87, 85, 84, 83, 82, 81, 80, 78, 77, 76, - - 75, 74, 73, 71, 70, 69, 68, 67, 66, 64, 63, 62, 61, 60, 59, - 57, 56, 55, 54, 53, 52, 50, 49, 48, 47, 46, 43, 42, 41, 40, - 39, 35, 33, 30, 28, 27, 14, 38, 38, 38, 38, 38, 38, 38, 38, - 38, 38, 45, 38, 38, 36, 34, 26, 32, 24, 31, 29, 26, 24, 15, - 135, 13, 3, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135}; - -static yyconst flex_int16_t yy_chk[174] = { - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, - 239, 238, 9, 10, 10, 237, 236, 10, 235, 234, 10, 137, 233, 137, 138, - 232, 231, 138, 144, 144, 150, 150, 156, 156, 163, 163, 170, 170, 177, 177, - 184, 184, 191, 191, 198, 198, 205, 205, 211, 211, 214, 214, 230, 229, 228, - 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 213, 212, - 210, 209, 208, 207, 206, 204, 203, 202, 201, 200, 199, 197, 196, 195, 194, - 193, 192, 190, 189, 188, 187, 186, 185, 183, 182, 181, - - 180, 179, 178, 176, 175, 174, 173, 172, 171, 169, 168, 167, 166, 165, 164, - 162, 161, 160, 159, 158, 157, 155, 154, 153, 152, 151, 149, 148, 147, 146, - 145, 143, 142, 141, 140, 139, 136, 106, 100, 93, 86, 79, 72, 65, 58, - 51, 44, 38, 37, 27, 26, 24, 22, 21, 19, 18, 15, 12, 11, 7, - 3, 2, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135}; - -/* The intent behind this definition is that it'll catch - * any uses of REJECT which flex missed. - */ -#define REJECT reject_used_but_not_detected -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -#line 1 "TreeFindNodeWild.l" -#line 2 "TreeFindNodeWild.l" -#include "treeshrp.h" -#include -#include -#include -#include - -STATIC_ROUTINE void addSearchTerm(yyscan_t scanner, int type, char *str); - -STATIC_ROUTINE void upcaseAndTrim(char *str) { - char *p = str; - for (p = str; *p; p++) { - *p = (isspace(*p) ? '\0' : toupper(*p)); - } -} - -STATIC_ROUTINE int isPunctuation(char c) { - return ((c == '.') || (c == ':') || (c == '-') || (c == '~') | (c == '^')); -} - -#define YY_NO_INPUT 1 -#line 555 "lex.yytreepath.c" - -#define INITIAL 0 - -#ifndef YY_NO_UNISTD_H -/* Special case for "unistd.h", since it is non-ANSI. We include it way - * down here because we want the user's section 1 to have been scanned first. - * The user has a chance to override it with an option. - */ -#include -#endif - -#define YY_EXTRA_TYPE SEARCH_CTX * - -/* Holds the entire state of the reentrant scanner. */ -struct yyguts_t { - - /* User-defined. Not touched by flex. */ - YY_EXTRA_TYPE yyextra_r; - - /* The rest are the same as the globals declared in the non-reentrant scanner. - */ - FILE *yyin_r, *yyout_r; - size_t yy_buffer_stack_top; /**< index of top of stack. */ - size_t yy_buffer_stack_max; /**< capacity of stack. */ - YY_BUFFER_STATE *yy_buffer_stack; /**< Stack as an array. */ - char yy_hold_char; - yy_size_t yy_n_chars; - yy_size_t yyleng_r; - char *yy_c_buf_p; - int yy_init; - int yy_start; - int yy_did_buffer_switch_on_eof; - int yy_start_stack_ptr; - int yy_start_stack_depth; - int *yy_start_stack; - yy_state_type yy_last_accepting_state; - char *yy_last_accepting_cpos; - - int yylineno_r; - int yy_flex_debug_r; - - char *yytext_r; - int yy_more_flag; - int yy_more_len; - -}; /* end struct yyguts_t */ - -static int yy_init_globals(yyscan_t yyscanner); - -int yytreepathlex_init(yyscan_t *scanner); - -int yytreepathlex_init_extra(YY_EXTRA_TYPE user_defined, yyscan_t *scanner); - -/* Accessor methods to globals. - These are made visible to non-reentrant scanners for convenience. */ - -int yytreepathlex_destroy(yyscan_t yyscanner); - -int yytreepathget_debug(yyscan_t yyscanner); - -void yytreepathset_debug(int debug_flag, yyscan_t yyscanner); - -YY_EXTRA_TYPE yytreepathget_extra(yyscan_t yyscanner); - -void yytreepathset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner); - -FILE *yytreepathget_in(yyscan_t yyscanner); - -void yytreepathset_in(FILE *in_str, yyscan_t yyscanner); - -FILE *yytreepathget_out(yyscan_t yyscanner); - -void yytreepathset_out(FILE *out_str, yyscan_t yyscanner); - -yy_size_t yytreepathget_leng(yyscan_t yyscanner); - -char *yytreepathget_text(yyscan_t yyscanner); - -int yytreepathget_lineno(yyscan_t yyscanner); - -void yytreepathset_lineno(int line_number, yyscan_t yyscanner); - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yytreepathwrap(yyscan_t yyscanner); -#else -extern int yytreepathwrap(yyscan_t yyscanner); -#endif -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy(char *, yyconst char *, int, yyscan_t yyscanner); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen(yyconst char *, yyscan_t yyscanner); -#endif - -#ifndef YY_NO_INPUT - -#ifdef __cplusplus -static int yyinput(yyscan_t yyscanner); -#else -static int input(yyscan_t yyscanner); -#endif - -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO fwrite(yytext, yyleng, 1, yyout) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf, result, max_size) \ - if (YY_CURRENT_BUFFER_LVALUE->yy_is_interactive) { \ - int c = '*'; \ - yy_size_t n; \ - for (n = 0; n < max_size && (c = getc(yyin)) != EOF && c != '\n'; ++n) \ - buf[n] = (char)c; \ - if (c == '\n') \ - buf[n++] = (char)c; \ - if (c == EOF && ferror(yyin)) \ - YY_FATAL_ERROR("input in flex scanner failed"); \ - result = n; \ - } else { \ - errno = 0; \ - while ((result = fread(buf, 1, max_size, yyin)) == 0 && ferror(yyin)) { \ - if (errno != EINTR) { \ - YY_FATAL_ERROR("input in flex scanner failed"); \ - break; \ - } \ - errno = 0; \ - clearerr(yyin); \ - } \ - } - -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error(msg, yyscanner) -#endif - -/* end tables serialization structures and prototypes */ - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL_IS_OURS 1 - -extern int yytreepathlex(yyscan_t yyscanner); - -#define YY_DECL int yytreepathlex(yyscan_t yyscanner) -#endif /* !YY_DECL */ - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - if (yyleng > 0) \ - YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (yytext[yyleng - 1] == '\n'); \ - YY_USER_ACTION - -/** The main scanner function which does all the work. - */ -YY_DECL { - register yy_state_type yy_current_state; - register char *yy_cp, *yy_bp; - register int yy_act; - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - -#line 46 "TreeFindNodeWild.l" - -#line 777 "lex.yytreepath.c" - - if (!yyg->yy_init) { - yyg->yy_init = 1; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if (!yyg->yy_start) - yyg->yy_start = 1; /* first start state */ - - if (!yyin) - yyin = stdin; - - if (!yyout) - yyout = stdout; - - if (!YY_CURRENT_BUFFER) { - yytreepathensure_buffer_stack(yyscanner); - YY_CURRENT_BUFFER_LVALUE = - yytreepath_create_buffer(yyin, YY_BUF_SIZE, yyscanner); - } - - yytreepath_load_buffer_state(yyscanner); - } - - while (1) /* loops until end-of-file is reached */ - { - yy_cp = yyg->yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yyg->yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yyg->yy_start; - yy_current_state += YY_AT_BOL(); - yy_match: - do { - register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - if (yy_accept[yy_current_state]) { - yyg->yy_last_accepting_state = yy_current_state; - yyg->yy_last_accepting_cpos = yy_cp; - } - while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { - yy_current_state = (int)yy_def[yy_current_state]; - if (yy_current_state >= 136) - yy_c = yy_meta[(unsigned int)yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; - ++yy_cp; - } while (yy_base[yy_current_state] != 163); - - yy_find_action: - yy_act = yy_accept[yy_current_state]; - if (yy_act == 0) { /* have to back up */ - yy_cp = yyg->yy_last_accepting_cpos; - yy_current_state = yyg->yy_last_accepting_state; - yy_act = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - do_action: /* This label is used only to access EOF actions. */ - - switch (yy_act) { /* beginning of action switch */ - case 0: /* must back up */ - /* undo the effects of YY_DO_BEFORE_ACTION */ - *yy_cp = yyg->yy_hold_char; - yy_cp = yyg->yy_last_accepting_cpos; - yy_current_state = yyg->yy_last_accepting_state; - goto yy_find_action; - - case 1: - YY_RULE_SETUP -#line 47 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, TAG_TREE, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 2: - YY_RULE_SETUP -#line 50 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, TAG, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 3: - YY_RULE_SETUP -#line 53 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, CHILD_SEARCH, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 4: - YY_RULE_SETUP -#line 56 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, MEMBER_SEARCH, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 5: - YY_RULE_SETUP -#line 59 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, ANCESTOR_SEARCH, - yytreepathget_text(yyscanner)); - } - YY_BREAK - case 6: - YY_RULE_SETUP -#line 62 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, CHILD_OR_MEMBER_SEARCH, - yytreepathget_text(yyscanner)); - } - YY_BREAK - case 7: - YY_RULE_SETUP -#line 65 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, PARENT, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 8: - YY_RULE_SETUP -#line 68 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, ANCESTOR, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 9: - YY_RULE_SETUP -#line 71 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, MEMBER, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 10: - YY_RULE_SETUP -#line 74 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, CHILD, yytreepathget_text(yyscanner)); - } - YY_BREAK - case 11: - YY_RULE_SETUP -#line 77 "TreeFindNodeWild.l" - { - addSearchTerm(yyscanner, CHILD_OR_MEMBER, - yytreepathget_text(yyscanner)); - } - YY_BREAK - case 12: - /* rule 12 can match eol */ - YY_RULE_SETUP -#line 80 "TreeFindNodeWild.l" - { - return (0); - } - YY_BREAK - case YY_STATE_EOF(INITIAL): -#line 83 "TreeFindNodeWild.l" - { - return (0); - } - YY_BREAK - case 13: - YY_RULE_SETUP -#line 86 "TreeFindNodeWild.l" - { - return (-1); - } - YY_BREAK - case 14: - YY_RULE_SETUP -#line 89 "TreeFindNodeWild.l" - ECHO; - YY_BREAK -#line 964 "lex.yytreepath.c" - - case YY_END_OF_BUFFER: { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int)(yy_cp - yyg->yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yyg->yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW) { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yytreepathlex(). If so, then we have to assure - * consistency between YY_CURRENT_BUFFER and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; - YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; - YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if (yyg->yy_c_buf_p <= - &YY_CURRENT_BUFFER_LVALUE - ->yy_ch_buf[yyg->yy_n_chars]) { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(yyscanner); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans(yy_current_state, yyscanner); - - yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; - - if (yy_next_state) { - /* Consume the NUL. */ - yy_cp = ++yyg->yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else { - yy_cp = yyg->yy_c_buf_p; - goto yy_find_action; - } - } - - else - switch (yy_get_next_buffer(yyscanner)) { - case EOB_ACT_END_OF_FILE: { - yyg->yy_did_buffer_switch_on_eof = 0; - - if (yytreepathwrap(yyscanner)) { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else { - if (!yyg->yy_did_buffer_switch_on_eof) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(yyscanner); - - yy_cp = yyg->yy_c_buf_p; - yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yyg->yy_c_buf_p = - &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; - - yy_current_state = yy_get_previous_state(yyscanner); - - yy_cp = yyg->yy_c_buf_p; - yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR("fatal flex scanner internal error--no action found"); - } /* end of action switch */ - } /* end of scanning one token */ -} /* end of yytreepathlex */ - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ -static int yy_get_next_buffer(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; - register char *source = yyg->yytext_ptr; - register int number_to_move, i; - int ret_val; - - if (yyg->yy_c_buf_p > - &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1]) - YY_FATAL_ERROR("fatal flex scanner internal error--end of buffer missed"); - - if (YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == - 0) { /* Don't try to fill the buffer, so this is an EOF. */ - if (yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1) { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int)(yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; - - for (i = 0; i < number_to_move; ++i) - *(dest++) = *(source++); - - if (YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; - - else { - yy_size_t num_to_read = - YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; - - while (num_to_read <= 0) { /* Not enough room in the buffer - grow it. */ - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = YY_CURRENT_BUFFER; - - int yy_c_buf_p_offset = (int)(yyg->yy_c_buf_p - b->yy_ch_buf); - - if (b->yy_is_our_buffer) { - yy_size_t new_size = b->yy_buf_size * 2; - - if (new_size <= 0) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yytreepathrealloc((void *)b->yy_ch_buf, b->yy_buf_size + 2, - yyscanner); - } else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if (!b->yy_ch_buf) - YY_FATAL_ERROR("fatal error - scanner input buffer overflow"); - - yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; - } - - if (num_to_read > YY_READ_BUF_SIZE) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT((&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), - yyg->yy_n_chars, num_to_read); - - YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; - } - - if (yyg->yy_n_chars == 0) { - if (number_to_move == YY_MORE_ADJ) { - ret_val = EOB_ACT_END_OF_FILE; - yytreepathrestart(yyin, yyscanner); - } - - else { - ret_val = EOB_ACT_LAST_MATCH; - YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - if ((yy_size_t)(yyg->yy_n_chars + number_to_move) > - YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { - /* Extend the array by 50%, plus the number we really need. */ - yy_size_t new_size = - yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *)yytreepathrealloc( - (void *)YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, new_size, yyscanner); - if (!YY_CURRENT_BUFFER_LVALUE->yy_ch_buf) - YY_FATAL_ERROR("out of dynamic memory in yy_get_next_buffer()"); - } - - yyg->yy_n_chars += number_to_move; - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = - YY_END_OF_BUFFER_CHAR; - - yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; - - return ret_val; -} - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state(yyscan_t yyscanner) { - register yy_state_type yy_current_state; - register char *yy_cp; - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - yy_current_state = yyg->yy_start; - yy_current_state += YY_AT_BOL(); - - for (yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; - ++yy_cp) { - register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - if (yy_accept[yy_current_state]) { - yyg->yy_last_accepting_state = yy_current_state; - yyg->yy_last_accepting_cpos = yy_cp; - } - while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { - yy_current_state = (int)yy_def[yy_current_state]; - if (yy_current_state >= 136) - yy_c = yy_meta[(unsigned int)yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; - } - - return yy_current_state; -} - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ -static yy_state_type yy_try_NUL_trans(yy_state_type yy_current_state, - yyscan_t yyscanner) { - register int yy_is_jam; - struct yyguts_t *yyg = (struct yyguts_t *) - yyscanner; /* This var may be unused depending upon options. */ - register char *yy_cp = yyg->yy_c_buf_p; - - register YY_CHAR yy_c = 1; - if (yy_accept[yy_current_state]) { - yyg->yy_last_accepting_state = yy_current_state; - yyg->yy_last_accepting_cpos = yy_cp; - } - while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { - yy_current_state = (int)yy_def[yy_current_state]; - if (yy_current_state >= 136) - yy_c = yy_meta[(unsigned int)yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; - yy_is_jam = (yy_current_state == 135); - - return yy_is_jam ? 0 : yy_current_state; -} - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput(yyscan_t yyscanner) -#else -static int input(yyscan_t yyscanner) -#endif - -{ - int c; - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - *yyg->yy_c_buf_p = yyg->yy_hold_char; - - if (*yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR) { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if (yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]) - /* This was really a NUL. */ - *yyg->yy_c_buf_p = '\0'; - - else { /* need more input */ - yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; - ++yyg->yy_c_buf_p; - - switch (yy_get_next_buffer(yyscanner)) { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yytreepathrestart(yyin, yyscanner); - - /*FALLTHROUGH*/ - - case EOB_ACT_END_OF_FILE: { - if (yytreepathwrap(yyscanner)) - return 0; - - if (!yyg->yy_did_buffer_switch_on_eof) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(yyscanner); -#else - return input(yyscanner); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yyg->yy_c_buf_p = yyg->yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *)yyg->yy_c_buf_p; /* cast for 8-bit char's */ - *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ - yyg->yy_hold_char = *++yyg->yy_c_buf_p; - - YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n'); - - return c; -} -#endif /* ifndef YY_NO_INPUT */ - -/** Immediately switch to a different input stream. - * @param input_file A readable stream. - * @param yyscanner The scanner object. - * @note This function does not reset the start condition to @c INITIAL . - */ -void yytreepathrestart(FILE *input_file, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - if (!YY_CURRENT_BUFFER) { - yytreepathensure_buffer_stack(yyscanner); - YY_CURRENT_BUFFER_LVALUE = - yytreepath_create_buffer(yyin, YY_BUF_SIZE, yyscanner); - } - - yytreepath_init_buffer(YY_CURRENT_BUFFER, input_file, yyscanner); - yytreepath_load_buffer_state(yyscanner); -} - -/** Switch to a different input buffer. - * @param new_buffer The new input buffer. - * @param yyscanner The scanner object. - */ -void yytreepath_switch_to_buffer(YY_BUFFER_STATE new_buffer, - yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - /* TODO. We should be able to replace this entire function body - * with - * yytreepathpop_buffer_state(); - * yytreepathpush_buffer_state(new_buffer); - */ - yytreepathensure_buffer_stack(yyscanner); - if (YY_CURRENT_BUFFER == new_buffer) - return; - - if (YY_CURRENT_BUFFER) { - /* Flush out information for old buffer. */ - *yyg->yy_c_buf_p = yyg->yy_hold_char; - YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; - YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; - } - - YY_CURRENT_BUFFER_LVALUE = new_buffer; - yytreepath_load_buffer_state(yyscanner); - - /* We don't actually know whether we did this switch during - * EOF (yytreepathwrap()) processing, but the only time this flag - * is looked at is after yytreepathwrap() is called, so it's safe - * to go ahead and always set it. - */ - yyg->yy_did_buffer_switch_on_eof = 1; -} - -static void yytreepath_load_buffer_state(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; - yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; - yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; - yyg->yy_hold_char = *yyg->yy_c_buf_p; -} - -/** Allocate and initialize an input buffer state. - * @param file A readable stream. - * @param size The character buffer size in bytes. When in doubt, use @c - * YY_BUF_SIZE. - * @param yyscanner The scanner object. - * @return the allocated buffer state. - */ -YY_BUFFER_STATE yytreepath_create_buffer(FILE *file, int size, - yyscan_t yyscanner) { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE)yytreepathalloc(sizeof(struct yy_buffer_state), - yyscanner); - if (!b) - YY_FATAL_ERROR("out of dynamic memory in yytreepath_create_buffer()"); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *)yytreepathalloc(b->yy_buf_size + 2, yyscanner); - if (!b->yy_ch_buf) - YY_FATAL_ERROR("out of dynamic memory in yytreepath_create_buffer()"); - - b->yy_is_our_buffer = 1; - - yytreepath_init_buffer(b, file, yyscanner); - - return b; -} - -/** Destroy the buffer. - * @param b a buffer created with yytreepath_create_buffer() - * @param yyscanner The scanner object. - */ -void yytreepath_delete_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - if (!b) - return; - - if (b == YY_CURRENT_BUFFER) /* Not sure if we should pop here. */ - YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE)0; - - if (b->yy_is_our_buffer) - yytreepathfree((void *)b->yy_ch_buf, yyscanner); - - yytreepathfree((void *)b, yyscanner); -} - -#ifndef __cplusplus -extern int isatty(int); -#endif /* __cplusplus */ - -/* Initializes or reinitializes a buffer. - * This function is sometimes called more than once on the same buffer, - * such as during a yytreepathrestart() or at EOF. - */ -static void yytreepath_init_buffer(YY_BUFFER_STATE b, FILE *file, - yyscan_t yyscanner) - -{ - int oerrno = errno; - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - yytreepath_flush_buffer(b, yyscanner); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - - /* If b is the current buffer, then yytreepath_init_buffer was _probably_ - * called from yytreepathrestart() or through yy_get_next_buffer. - * In that case, we don't want to reset the lineno or column. - */ - if (b != YY_CURRENT_BUFFER) { - b->yy_bs_lineno = 1; - b->yy_bs_column = 0; - } - - b->yy_is_interactive = file ? (isatty(fileno(file)) > 0) : 0; - - errno = oerrno; -} - -/** Discard all buffered characters. On the next scan, YY_INPUT will be called. - * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. - * @param yyscanner The scanner object. - */ -void yytreepath_flush_buffer(YY_BUFFER_STATE b, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - if (!b) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if (b == YY_CURRENT_BUFFER) - yytreepath_load_buffer_state(yyscanner); -} - -/** Pushes the new state onto the stack. The new state becomes - * the current state. This function will allocate the stack - * if necessary. - * @param new_buffer The new state. - * @param yyscanner The scanner object. - */ -void yytreepathpush_buffer_state(YY_BUFFER_STATE new_buffer, - yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - if (new_buffer == NULL) - return; - - yytreepathensure_buffer_stack(yyscanner); - - /* This block is copied from yytreepath_switch_to_buffer. */ - if (YY_CURRENT_BUFFER) { - /* Flush out information for old buffer. */ - *yyg->yy_c_buf_p = yyg->yy_hold_char; - YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; - YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; - } - - /* Only push if top exists. Otherwise, replace top. */ - if (YY_CURRENT_BUFFER) - yyg->yy_buffer_stack_top++; - YY_CURRENT_BUFFER_LVALUE = new_buffer; - - /* copied from yytreepath_switch_to_buffer. */ - yytreepath_load_buffer_state(yyscanner); - yyg->yy_did_buffer_switch_on_eof = 1; -} - -/** Removes and deletes the top of the stack, if present. - * The next element becomes the new top. - * @param yyscanner The scanner object. - */ -void yytreepathpop_buffer_state(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - if (!YY_CURRENT_BUFFER) - return; - - yytreepath_delete_buffer(YY_CURRENT_BUFFER, yyscanner); - YY_CURRENT_BUFFER_LVALUE = NULL; - if (yyg->yy_buffer_stack_top > 0) - --yyg->yy_buffer_stack_top; - - if (YY_CURRENT_BUFFER) { - yytreepath_load_buffer_state(yyscanner); - yyg->yy_did_buffer_switch_on_eof = 1; - } -} - -/* Allocates the stack if it does not exist. - * Guarantees space for at least one push. - */ -static void yytreepathensure_buffer_stack(yyscan_t yyscanner) { - yy_size_t num_to_alloc; - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - if (!yyg->yy_buffer_stack) { - - /* First allocation is just for 2 elements, since we don't know if this - * scanner will even need a stack. We use 2 instead of 1 to avoid an - * immediate realloc on the next call. - */ - num_to_alloc = 1; - yyg->yy_buffer_stack = (struct yy_buffer_state **)yytreepathalloc( - num_to_alloc * sizeof(struct yy_buffer_state *), yyscanner); - if (!yyg->yy_buffer_stack) - YY_FATAL_ERROR( - "out of dynamic memory in yytreepathensure_buffer_stack()"); - - memset(yyg->yy_buffer_stack, 0, - num_to_alloc * sizeof(struct yy_buffer_state *)); - - yyg->yy_buffer_stack_max = num_to_alloc; - yyg->yy_buffer_stack_top = 0; - return; - } - - if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1) { - - /* Increase the buffer to prepare for a possible push. */ - int grow_size = 8 /* arbitrary grow size */; - - num_to_alloc = yyg->yy_buffer_stack_max + grow_size; - yyg->yy_buffer_stack = (struct yy_buffer_state **)yytreepathrealloc( - yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state *), - yyscanner); - if (!yyg->yy_buffer_stack) - YY_FATAL_ERROR( - "out of dynamic memory in yytreepathensure_buffer_stack()"); - - /* zero only the new slots.*/ - memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, - grow_size * sizeof(struct yy_buffer_state *)); - yyg->yy_buffer_stack_max = num_to_alloc; - } -} - -/** Setup the input buffer state to scan directly from a user-specified - * character buffer. - * @param base the character buffer - * @param size the size in bytes of the character buffer - * @param yyscanner The scanner object. - * @return the newly allocated buffer state object. - */ -YY_BUFFER_STATE yytreepath_scan_buffer(char *base, yy_size_t size, - yyscan_t yyscanner) { - YY_BUFFER_STATE b; - - if (size < 2 || base[size - 2] != YY_END_OF_BUFFER_CHAR || - base[size - 1] != YY_END_OF_BUFFER_CHAR) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE)yytreepathalloc(sizeof(struct yy_buffer_state), - yyscanner); - if (!b) - YY_FATAL_ERROR("out of dynamic memory in yytreepath_scan_buffer()"); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yytreepath_switch_to_buffer(b, yyscanner); - - return b; -} - -/** Setup the input buffer state to scan a string. The next call to - * yytreepathlex() will scan from a @e copy of @a str. - * @param yystr a NUL-terminated string to scan - * @param yyscanner The scanner object. - * @return the newly allocated buffer state object. - * @note If you want to scan bytes that may contain NUL values, then use - * yytreepath_scan_bytes() instead. - */ -YY_BUFFER_STATE yytreepath_scan_string(yyconst char *yystr, - yyscan_t yyscanner) { - - return yytreepath_scan_bytes(yystr, strlen(yystr), yyscanner); -} - -/** Setup the input buffer state to scan the given bytes. The next call to - * yytreepathlex() will scan from a @e copy of @a bytes. - * @param bytes the byte buffer to scan - * @param len the number of bytes in the buffer pointed to by @a bytes. - * @param yyscanner The scanner object. - * @return the newly allocated buffer state object. - */ -YY_BUFFER_STATE yytreepath_scan_bytes(yyconst char *yybytes, - yy_size_t _yybytes_len, - yyscan_t yyscanner) { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n, i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = _yybytes_len + 2; - buf = (char *)yytreepathalloc(n, yyscanner); - if (!buf) - YY_FATAL_ERROR("out of dynamic memory in yytreepath_scan_bytes()"); - - for (i = 0; i < _yybytes_len; ++i) - buf[i] = yybytes[i]; - - buf[_yybytes_len] = buf[_yybytes_len + 1] = YY_END_OF_BUFFER_CHAR; - - b = yytreepath_scan_buffer(buf, n, yyscanner); - if (!b) - YY_FATAL_ERROR("bad buffer in yytreepath_scan_bytes()"); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; -} - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -static void yy_fatal_error(yyconst char *msg, yyscan_t yyscanner) { - (void)fprintf(stderr, "%s\n", msg); - exit(YY_EXIT_FAILURE); -} - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do { \ - /* Undo effects of setting up yytext. */ \ - int yyless_macro_arg = (n); \ - YY_LESS_LINENO(yyless_macro_arg); \ - yytext[yyleng] = yyg->yy_hold_char; \ - yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ - yyg->yy_hold_char = *yyg->yy_c_buf_p; \ - *yyg->yy_c_buf_p = '\0'; \ - yyleng = yyless_macro_arg; \ - } while (0) - -/* Accessor methods (get/set functions) to struct members. */ - -/** Get the user-defined data for this scanner. - * @param yyscanner The scanner object. - */ -YY_EXTRA_TYPE yytreepathget_extra(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yyextra; -} - -/** Get the current line number. - * @param yyscanner The scanner object. - */ -int yytreepathget_lineno(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - if (!YY_CURRENT_BUFFER) - return 0; - - return yylineno; -} - -/** Get the current column number. - * @param yyscanner The scanner object. - */ -int yytreepathget_column(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - if (!YY_CURRENT_BUFFER) - return 0; - - return yycolumn; -} - -/** Get the input stream. - * @param yyscanner The scanner object. - */ -FILE *yytreepathget_in(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yyin; -} - -/** Get the output stream. - * @param yyscanner The scanner object. - */ -FILE *yytreepathget_out(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yyout; -} - -/** Get the length of the current token. - * @param yyscanner The scanner object. - */ -yy_size_t yytreepathget_leng(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yyleng; -} - -/** Get the current token. - * @param yyscanner The scanner object. - */ - -char *yytreepathget_text(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yytext; -} - -/** Set the user-defined data. This data is never touched by the scanner. - * @param user_defined The data to be associated with this scanner. - * @param yyscanner The scanner object. - */ -void yytreepathset_extra(YY_EXTRA_TYPE user_defined, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - yyextra = user_defined; -} - -/** Set the current line number. - * @param line_number - * @param yyscanner The scanner object. - */ -void yytreepathset_lineno(int line_number, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - /* lineno is only valid if an input buffer exists. */ - if (!YY_CURRENT_BUFFER) - yy_fatal_error("yytreepathset_lineno called with no buffer", yyscanner); - - yylineno = line_number; -} - -/** Set the current column. - * @param line_number - * @param yyscanner The scanner object. - */ -void yytreepathset_column(int column_no, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - /* column is only valid if an input buffer exists. */ - if (!YY_CURRENT_BUFFER) - yy_fatal_error("yytreepathset_column called with no buffer", yyscanner); - - yycolumn = column_no; -} - -/** Set the input stream. This does not discard the current - * input buffer. - * @param in_str A readable stream. - * @param yyscanner The scanner object. - * @see yytreepath_switch_to_buffer - */ -void yytreepathset_in(FILE *in_str, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - yyin = in_str; -} - -void yytreepathset_out(FILE *out_str, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - yyout = out_str; -} - -int yytreepathget_debug(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - return yy_flex_debug; -} - -void yytreepathset_debug(int bdebug, yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - yy_flex_debug = bdebug; -} - -/* Accessor methods for yylval and yylloc */ - -/* User-visible API */ - -/* yytreepathlex_init is special because it creates the scanner itself, so it is - * the ONLY reentrant function that doesn't take the scanner as the last - * argument. That's why we explicitly handle the declaration, instead of using - * our macros. - */ - -int yytreepathlex_init(yyscan_t *ptr_yy_globals) - -{ - if (ptr_yy_globals == NULL) { - errno = EINVAL; - return 1; - } - - *ptr_yy_globals = (yyscan_t)yytreepathalloc(sizeof(struct yyguts_t), NULL); - - if (*ptr_yy_globals == NULL) { - errno = ENOMEM; - return 1; - } - - /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for - * releases. */ - memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t)); - - return yy_init_globals(*ptr_yy_globals); -} - -/* yytreepathlex_init_extra has the same functionality as yytreepathlex_init, - * but follows the convention of taking the scanner as the last argument. Note - * however, that this is a *pointer* to a scanner, as it will be allocated by - * this call (and is the reason, too, why this function also must handle its own - * declaration). The user defined value in the first argument will be available - * to yytreepathalloc in the yyextra field. - */ - -int yytreepathlex_init_extra(YY_EXTRA_TYPE yy_user_defined, - yyscan_t *ptr_yy_globals) - -{ - struct yyguts_t dummy_yyguts; - - yytreepathset_extra(yy_user_defined, &dummy_yyguts); - - if (ptr_yy_globals == NULL) { - errno = EINVAL; - return 1; - } - - *ptr_yy_globals = - (yyscan_t)yytreepathalloc(sizeof(struct yyguts_t), &dummy_yyguts); - - if (*ptr_yy_globals == NULL) { - errno = ENOMEM; - return 1; - } - - /* By setting to 0xAA, we expose bugs in - yy_init_globals. Leave at 0x00 for releases. */ - memset(*ptr_yy_globals, 0x00, sizeof(struct yyguts_t)); - - yytreepathset_extra(yy_user_defined, *ptr_yy_globals); - - return yy_init_globals(*ptr_yy_globals); -} - -static int yy_init_globals(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - /* Initialization is the same as for the non-reentrant scanner. - * This function is called from yytreepathlex_destroy(), so don't allocate - * here. - */ - - yyg->yy_buffer_stack = 0; - yyg->yy_buffer_stack_top = 0; - yyg->yy_buffer_stack_max = 0; - yyg->yy_c_buf_p = (char *)0; - yyg->yy_init = 0; - yyg->yy_start = 0; - - yyg->yy_start_stack_ptr = 0; - yyg->yy_start_stack_depth = 0; - yyg->yy_start_stack = NULL; - -/* Defined in main.c */ -#ifdef YY_STDINIT - yyin = stdin; - yyout = stdout; -#else - yyin = (FILE *)0; - yyout = (FILE *)0; -#endif - - /* For future reference: Set errno on error, since we are called by - * yytreepathlex_init() - */ - return 0; -} - -/* yytreepathlex_destroy is for both reentrant and non-reentrant scanners. */ -int yytreepathlex_destroy(yyscan_t yyscanner) { - struct yyguts_t *yyg = (struct yyguts_t *)yyscanner; - - /* Pop the buffer stack, destroying each element. */ - while (YY_CURRENT_BUFFER) { - yytreepath_delete_buffer(YY_CURRENT_BUFFER, yyscanner); - YY_CURRENT_BUFFER_LVALUE = NULL; - yytreepathpop_buffer_state(yyscanner); - } - - /* Destroy the stack itself. */ - yytreepathfree(yyg->yy_buffer_stack, yyscanner); - yyg->yy_buffer_stack = NULL; - - /* Destroy the start condition stack. */ - yytreepathfree(yyg->yy_start_stack, yyscanner); - yyg->yy_start_stack = NULL; - - /* Reset the globals. This is important in a non-reentrant scanner so the next - * time yytreepathlex() is called, initialization will occur. */ - yy_init_globals(yyscanner); - - /* Destroy the main struct (reentrant only). */ - yytreepathfree(yyscanner, yyscanner); - yyscanner = NULL; - return 0; -} - -/* - * Internal utility routines. - */ - -#ifndef yytext_ptr -static void yy_flex_strncpy(char *s1, yyconst char *s2, int n, - yyscan_t yyscanner) { - register int i; - for (i = 0; i < n; ++i) - s1[i] = s2[i]; -} -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen(yyconst char *s, yyscan_t yyscanner) { - register int n; - for (n = 0; s[n]; ++n) - ; - - return n; -} -#endif - -void *yytreepathalloc(yy_size_t size, yyscan_t yyscanner) { - return (void *)malloc(size); -} - -void *yytreepathrealloc(void *ptr, yy_size_t size, yyscan_t yyscanner) { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *)realloc((char *)ptr, size); -} - -void yytreepathfree(void *ptr, yyscan_t yyscanner) { - free((char *)ptr); /* see yytreepathrealloc() for (char *) cast */ -} - -#define YYTABLES_NAME "yytables" - -#line 89 "TreeFindNodeWild.l" - -/* -STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) -{ - const char * names[] = { - "TAG_TREE", - "TAG", - "CHILD", - "MEMBER", - "CHILD_OR_MEMBER", - "ANCESTOR", - "ANCESTOR_SEARCH", - "CHILD_SEARCH", - "MEMBER_SEARCH", - "CHILD_OR_MEMBER_SEARCH", - "PARENT", - "EOL" - }; - return names[typ-TAG_TREE]; -} - -STATIC_ROUTINE void PrintCtx(SEARCH_CTX *ctx) -{ - SEARCH_TERM *ptr; - printf ("Print Context for %s\n", ctx->wildcard); - for ( ptr=ctx->terms; - ptr; - ptr=ptr->next) { - printf("\t%s -%s-\n", SearchTypeName(ptr->search_type), ptr->term); - } -} -*/ - -STATIC_ROUTINE SEARCH_TERM *SquishSearches(SEARCH_TERM *terms) { - SEARCH_TERM *ptr = terms; - SEARCH_TERM *tmp; - for (; ptr && ptr->next; ptr = ptr->next) { - if (((ptr->search_type == CHILD_SEARCH) && - (ptr->next->search_type == CHILD)) || - ((ptr->search_type == MEMBER_SEARCH) && - (ptr->next->search_type == MEMBER)) || - ((ptr->search_type == CHILD_OR_MEMBER_SEARCH) && - (ptr->next->search_type == CHILD_OR_MEMBER))) { - char *str = - calloc(strlen(ptr->term) + strlen(ptr->next->term) + 1, sizeof(char)); - strcpy(str, ptr->term); - strcat(str, ptr->next->term); - free(ptr->term); - free(ptr->next->term); - ptr->term = str; - tmp = ptr->next; - ptr->next = tmp->next; - free(tmp); - } - } - return terms; -} - -EXPORT void FreeSearchTerms(SEARCH_TERM *terms) { - SEARCH_TERM *ptr = terms; - SEARCH_TERM *next; - while (ptr) { - next = ptr->next; - free(ptr->term); - free(ptr); - ptr = next; - } -} - -static char *strtrim(char *str) { - char *q; - for (q = str + strlen(str) - 1; (q > str) && isspace(*q); q--) - *q = '\0'; - return str; -} - -EXPORT int WildParse(char const *path, SEARCH_CTX *ctx, int *wild) { - int status = 1; - - // static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; - if (path && strlen(path)) { - char *wild_path = strdup(path); - char *p; - yyscan_t scanner; - wild_path = strtrim(wild_path); - while ((p = strstr(wild_path, "***"))) { - *p++ = '~'; - *p++ = '~'; - *p++ = '~'; - } - - yytreepathlex_init_extra(ctx, &scanner); - ctx->wildcard = strdup(wild_path); - - yytreepath_scan_string(wild_path, scanner); - - while ((status = yytreepathlex(scanner)) > 0) - ; - if (status == 0) { - /* now merge in trailing search clauses */ - ctx->terms = SquishSearches(ctx->terms); - /* check if any terms are wild */ - *wild = strchr(wild_path, '*') || strchr(wild_path, '%') || - strstr(wild_path, "~~~") || strstr(wild_path, "...") || - strstr(wild_path, ":::") || strstr(wild_path, "^^^"); - } - yytreepathlex_destroy(scanner); - free(wild_path); - } - - return (status == 0) ? TreeSUCCESS : TreeINVPATH; -} - -STATIC_ROUTINE void addSearchTerm(yyscan_t scanner, int type, char *str) { - - SEARCH_TERM *ptr, *p; - // printf("addSearchTerm\n"); - - ptr = malloc(sizeof(SEARCH_TERM)); - ptr->search_type = type; - ptr->term = NULL; - ptr->next = NULL; - if (str) { - char *cptr = str; - while (*cptr) { - if (isPunctuation(*cptr)) { - cptr++; - } else { - break; - } - } - ptr->term = strdup(cptr); - } - upcaseAndTrim(ptr->term); - - if (yytreepathget_extra(scanner)->terms == NULL) - yytreepathget_extra(scanner)->terms = ptr; - else { - for (p = yytreepathget_extra(scanner)->terms; p->next; p = p->next) - ; - p->next = ptr; - } -} diff --git a/treeshr/testing/TreeDeleteNodeTest.c b/treeshr/testing/TreeDeleteNodeTest.c index 4bee914389..da0febcc22 100644 --- a/treeshr/testing/TreeDeleteNodeTest.c +++ b/treeshr/testing/TreeDeleteNodeTest.c @@ -43,7 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // tree->write(); // -int dbiTest(void *ctx, short int code) { +int dbiTest(void *ctx, short int code) +{ int supports; int len; struct dbi_itm dbiList[] = {{sizeof(int), code, &supports, &len}, @@ -64,7 +65,8 @@ int dbiTest(void *ctx, short int code) { /// /// int main(int argc __attribute__((unused)), - char *argv[] __attribute__((unused))) { + char *argv[] __attribute__((unused))) +{ BEGIN_TESTING(Tree Delete Node); void *ctx = NULL; @@ -98,10 +100,13 @@ int main(int argc __attribute__((unused)), // close tree // int is_modified = dbiTest(ctx, DbiMODIFIED); - if (is_modified) { + if (is_modified) + { status = _TreeQuitTree(&ctx, tree_name, shot); TEST1(status & 1); - } else { + } + else + { status = _TreeClose(&ctx, tree_name, shot); TEST1(status & 1); } diff --git a/treeshr/testing/TreeSegmentTest.c b/treeshr/testing/TreeSegmentTest.c index 28b4f89082..111f61b2e7 100644 --- a/treeshr/testing/TreeSegmentTest.c +++ b/treeshr/testing/TreeSegmentTest.c @@ -41,18 +41,20 @@ static int go = 0; static char const tree[] = "tree_test"; static int const shot = 1; static int result = 0; -#define TEST_STATUS(m) \ - ({ \ - int r = (m); \ - if ((r & 1) == 0) { \ - fprintf(stdout, "%d: %d - %s\n", num, r, #m); \ - pthread_mutex_lock(&mutex); \ - result = 1; \ - pthread_mutex_unlock(&mutex); \ - } \ +#define TEST_STATUS(m) \ + ({ \ + int r = (m); \ + if ((r & 1) == 0) \ + { \ + fprintf(stdout, "%d: %d - %s\n", num, r, #m); \ + pthread_mutex_lock(&mutex); \ + result = 1; \ + pthread_mutex_unlock(&mutex); \ + } \ }) -void *job(void *args) { +void *job(void *args) +{ int i, j, num = (int)(intptr_t)args; void *DBID = NULL; int nid; @@ -74,7 +76,8 @@ void *job(void *args) { pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); fprintf(stderr, "%d: nid = %d\n", num, nid); - for (i = 0; i < NUM_SEGS; i++) { + for (i = 0; i < NUM_SEGS; i++) + { for (j = 0; j < SEG_SZE; j++) dim[j] = i * SEG_SZE + j; start = dim[0]; @@ -89,7 +92,8 @@ void *job(void *args) { return NULL; } -int main(int const argc, char const *const argv[]) { +int main(int const argc, char const *const argv[]) +{ int a = 0; if (argc > ++a) NUM_THREADS = atoi(argv[a]); @@ -104,7 +108,8 @@ int main(int const argc, char const *const argv[]) { int nid; char name[13]; int i, j; - for (i = 0; i < NUM_THREADS; i++) { + for (i = 0; i < NUM_THREADS; i++) + { sprintf(name, NODEFMTSTR, i); TEST_STATUS(_TreeAddNode(DBID, name, &nid, 6)); } @@ -121,33 +126,40 @@ int main(int const argc, char const *const argv[]) { pthread_join(threads[i], NULL); TEST_STATUS(_TreeOpen(&DBID, tree, shot, 1)); mdsdsc_xd_t xd = {0, DTYPE_DSC, CLASS_XD, NULL, 0}; - for (num = 0; num < NUM_THREADS; num++) { + for (num = 0; num < NUM_THREADS; num++) + { sprintf(name, NODEFMTSTR, num); TEST_STATUS(_TreeFindNode(DBID, name, &nid)); TEST_STATUS(_TreeGetRecord(DBID, nid, &xd)); if (xd.l_length == 0 || xd.pointer == NULL || - xd.pointer->class != CLASS_R) { + xd.pointer->class != CLASS_R) + { fprintf(stderr, "%d: invalid record", num); result = 1; continue; } mdsdsc_r_t const *r = (mdsdsc_r_t const *)xd.pointer; - if (r->dscptrs[0]->class != CLASS_A || r->dscptrs[0]->dtype != DTYPE_W) { + if (r->dscptrs[0]->class != CLASS_A || r->dscptrs[0]->dtype != DTYPE_W) + { fprintf(stderr, "%d: invalid data type", num); result = 1; continue; } int16_t const *data = (int16_t const *)r->dscptrs[0]->pointer; int arr_length = ((mdsdsc_a_t *)r->dscptrs[0])->arsize / 2; - if (arr_length != SEG_SZE * NUM_SEGS) { + if (arr_length != SEG_SZE * NUM_SEGS) + { fprintf(stderr, "%d: invalid data length %d of %d", num, arr_length, SEG_SZE * NUM_SEGS); result = 1; continue; } - for (j = 0; j < NUM_SEGS; j++) { - for (i = 0; i < SEG_SZE; i++) { - if (data[i + j * SEG_SZE] != (int16_t)i) { + for (j = 0; j < NUM_SEGS; j++) + { + for (i = 0; i < SEG_SZE; i++) + { + if (data[i + j * SEG_SZE] != (int16_t)i) + { fprintf(stderr, "%d: invalid data[i] is %d, but %d expected", num, data[i + j * SEG_SZE], i); result = 1; diff --git a/treeshr/treeshr_xnci.h b/treeshr/treeshr_xnci.h index 6b0c02e18b..e1ca933157 100644 --- a/treeshr/treeshr_xnci.h +++ b/treeshr/treeshr_xnci.h @@ -2,72 +2,73 @@ #pragma once #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -// These API exports are unofficial and may be changed in future releases -// without notice. + // These API exports are unofficial and may be changed in future releases + // without notice. -extern EXPORT int _TreeXNciBeginSegment(void *dbid, int nid, const char *xnci, - mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, - int idx); -extern EXPORT int _TreeXNciMakeSegment(void *dbid, int nid, const char *xnci, - mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, mdsdsc_a_t *initialData, - int idx, int filled); -extern EXPORT int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, - const int rowidx, mdsdsc_a_t *data); -extern EXPORT int _TreeXNciSetRowsFilled(void *dbid, int nid, const char *xnci, - int rows_filled); -extern EXPORT int _TreeXNciUpdateSegment(void *dbid, int nid, const char *xnci, + extern EXPORT int _TreeXNciBeginSegment(void *dbid, int nid, const char *xnci, + mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, mdsdsc_a_t *initialData, + int idx); + extern EXPORT int _TreeXNciMakeSegment(void *dbid, int nid, const char *xnci, mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_t *dim, int idx); -extern EXPORT int _TreeXNciBeginTimestampedSegment(void *dbid, int nid, + mdsdsc_t *dim, mdsdsc_a_t *initialData, + int idx, int filled); + extern EXPORT int _TreeXNciPutSegment(void *dbid, int nid, const char *xnci, + const int rowidx, mdsdsc_a_t *data); + extern EXPORT int _TreeXNciSetRowsFilled(void *dbid, int nid, const char *xnci, + int rows_filled); + extern EXPORT int _TreeXNciUpdateSegment(void *dbid, int nid, const char *xnci, + mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_t *dim, int idx); + extern EXPORT int _TreeXNciBeginTimestampedSegment(void *dbid, int nid, + const char *xnci, + mdsdsc_a_t *initialValue, + int idx); + extern EXPORT int _TreeXNciPutTimestampedSegment(void *dbid, int nid, const char *xnci, - mdsdsc_a_t *initialValue, - int idx); -extern EXPORT int _TreeXNciPutTimestampedSegment(void *dbid, int nid, - const char *xnci, - int64_t *timestamp, - mdsdsc_a_t *rowdata); -extern EXPORT int _TreeXNciMakeTimestampedSegment(void *dbid, int nid, - const char *xnci, - int64_t *timestamp, - mdsdsc_a_t *rowdata, int idx, - int filled); -extern EXPORT int _TreeXNciPutRow(void *dbid, int nid, const char *xnci, - int bufsize, int64_t *timestamp, - mdsdsc_a_t *rowdata); -extern EXPORT int _TreeXNciGetNumSegments(void *dbid, int nid, const char *xnci, - int *num); -extern EXPORT int _TreeXNciGetSegmentLimits(void *dbid, int nid, - const char *xnci, int segidx, - mdsdsc_xd_t *start, - mdsdsc_xd_t *end); -extern EXPORT int _TreeXNciGetSegment(void *dbid, int nid, const char *xnci, - int segidx, mdsdsc_xd_t *data, - mdsdsc_xd_t *dim); -extern EXPORT int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, - mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_xd_t *retSegments); -extern EXPORT int _TreeXNciGetSegmentInfo(void *dbid, int nid, const char *xnci, - int idx, char *dtype, char *dimct, - int *dims, int *next_row); -extern EXPORT int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, - mdsdsc_t *start, mdsdsc_t *end, - mdsdsc_xd_t *out); -extern EXPORT int _TreeXNciGetSegmentTimes(void *dbid, int nid, - const char *xnci, int *numsegs, - int64_t **times); -extern EXPORT int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, + int64_t *timestamp, + mdsdsc_a_t *rowdata); + extern EXPORT int _TreeXNciMakeTimestampedSegment(void *dbid, int nid, + const char *xnci, + int64_t *timestamp, + mdsdsc_a_t *rowdata, int idx, + int filled); + extern EXPORT int _TreeXNciPutRow(void *dbid, int nid, const char *xnci, + int bufsize, int64_t *timestamp, + mdsdsc_a_t *rowdata); + extern EXPORT int _TreeXNciGetNumSegments(void *dbid, int nid, const char *xnci, + int *num); + extern EXPORT int _TreeXNciGetSegmentLimits(void *dbid, int nid, + const char *xnci, int segidx, + mdsdsc_xd_t *start, + mdsdsc_xd_t *end); + extern EXPORT int _TreeXNciGetSegment(void *dbid, int nid, const char *xnci, + int segidx, mdsdsc_xd_t *data, + mdsdsc_xd_t *dim); + extern EXPORT int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, + mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_xd_t *retSegments); + extern EXPORT int _TreeXNciGetSegmentInfo(void *dbid, int nid, const char *xnci, + int idx, char *dtype, char *dimct, + int *dims, int *next_row); + extern EXPORT int _TreeXNciGetSegments(void *dbid, int nid, const char *xnci, + mdsdsc_t *start, mdsdsc_t *end, + mdsdsc_xd_t *out); + extern EXPORT int _TreeXNciGetSegmentTimes(void *dbid, int nid, const char *xnci, int *numsegs, - mdsdsc_xd_t *start_list, - mdsdsc_xd_t *end_list); -extern EXPORT int _TreeXNciGetSegmentScale(void *dbid, int nid, - const char *xnci, - mdsdsc_xd_t *value); -extern EXPORT int _TreeXNciSetSegmentScale(void *dbid, int nid, - const char *xnci, mdsdsc_t *value); + int64_t **times); + extern EXPORT int _TreeXNciGetSegmentTimesXd(void *dbid, int nid, + const char *xnci, int *numsegs, + mdsdsc_xd_t *start_list, + mdsdsc_xd_t *end_list); + extern EXPORT int _TreeXNciGetSegmentScale(void *dbid, int nid, + const char *xnci, + mdsdsc_xd_t *value); + extern EXPORT int _TreeXNciSetSegmentScale(void *dbid, int nid, + const char *xnci, mdsdsc_t *value); #ifdef __cplusplus } #endif diff --git a/treeshr/treeshrp.h b/treeshr/treeshrp.h index 0a98f48c64..49f80de128 100644 --- a/treeshr/treeshrp.h +++ b/treeshr/treeshrp.h @@ -41,7 +41,8 @@ #define NciM_EXTENDED_NCI 0x10 #define NciV_EXTENDED_NCI 4 -typedef struct nci { +typedef struct nci +{ unsigned int flags; unsigned char flags2; unsigned char spare; @@ -53,17 +54,20 @@ typedef struct nci { unsigned char spare2; unsigned int status; union { - struct { + struct + { unsigned char file_level; unsigned char file_version; unsigned char rfa[6]; unsigned int record_length; } DATA_LOCATION; - struct { + struct + { unsigned char element_length; unsigned char data[11]; } DATA_IN_RECORD; - struct { + struct + { unsigned int error_status; unsigned int stv; } ERROR_INFO; @@ -72,20 +76,23 @@ typedef struct nci { } NCI; #define FACILITIES_PER_EA 8 -typedef struct extended_attributes { +typedef struct extended_attributes +{ int64_t next_ea_offset; int64_t facility_offset[FACILITIES_PER_EA]; int facility_length[FACILITIES_PER_EA]; } EXTENDED_ATTRIBUTES; -enum { +enum +{ STANDARD_RECORD_FACILITY = 0, SEGMENTED_RECORD_FACILITY = 1, NAMED_ATTRIBUTES_FACILITY = 2, }; #define MAX_DIMS 8 -typedef struct segment_header { +typedef struct segment_header +{ dtype_t dtype; char dimct; int dims[MAX_DIMS]; @@ -97,7 +104,8 @@ typedef struct segment_header { int64_t dim_offset; } SEGMENT_HEADER; -typedef struct segment_info { +typedef struct segment_info +{ int64_t start; int64_t end; int64_t start_offset; @@ -111,7 +119,8 @@ typedef struct segment_info { } SEGMENT_INFO; #define SEGMENTS_PER_INDEX 128 -typedef struct segment_index { +typedef struct segment_index +{ int64_t previous_offset; int first_idx; SEGMENT_INFO segment[SEGMENTS_PER_INDEX]; @@ -119,37 +128,42 @@ typedef struct segment_index { #define NAMED_ATTRIBUTES_PER_INDEX 128 #define NAMED_ATTRIBUTE_NAME_SIZE 64 -typedef struct named_attribute { +typedef struct named_attribute +{ char name[NAMED_ATTRIBUTE_NAME_SIZE]; int64_t offset; int length; } NAMED_ATTRIBUTE; -typedef struct named_attributes_index { +typedef struct named_attributes_index +{ int64_t previous_offset; NAMED_ATTRIBUTE attribute[NAMED_ATTRIBUTES_PER_INDEX]; } NAMED_ATTRIBUTES_INDEX; // #define WORDS_BIGENDIAN // use for testing #ifdef WORDS_BIGENDIAN -#define SWP(out, in, a, b) \ - ((char *)(out))[a] = ((char *)(in))[b]; \ +#define SWP(out, in, a, b) \ + ((char *)(out))[a] = ((char *)(in))[b]; \ ((char *)(out))[b] = ((char *)(in))[a]; -#define loadint16(out, in) \ - do { \ - SWP(out, in, 0, 1); \ +#define loadint16(out, in) \ + do \ + { \ + SWP(out, in, 0, 1); \ } while (0) -#define loadint32(out, in) \ - do { \ - SWP(out, in, 0, 3); \ - SWP(out, in, 2, 1); \ +#define loadint32(out, in) \ + do \ + { \ + SWP(out, in, 0, 3); \ + SWP(out, in, 2, 1); \ } while (0) -#define loadint64(out, in) \ - do { \ - SWP(out, in, 0, 7); \ - SWP(out, in, 2, 5); \ - SWP(out, in, 4, 3); \ - SWP(out, in, 6, 1); \ +#define loadint64(out, in) \ + do \ + { \ + SWP(out, in, 0, 7); \ + SWP(out, in, 2, 5); \ + SWP(out, in, 4, 3); \ + SWP(out, in, 6, 1); \ } while (0) #undef SWP #else @@ -157,67 +171,80 @@ typedef struct named_attributes_index { #define loadint32(out, in) memcpy((char *)(out), (char *)(in), 4) #define loadint64(out, in) memcpy((char *)(out), (char *)(in), 8) #endif -static inline int16_t swapint16(const void *buf) { +static inline int16_t swapint16(const void *buf) +{ int16_t ans; loadint16(&ans, buf); return ans; } -static inline int32_t swapint32(const void *buf) { +static inline int32_t swapint32(const void *buf) +{ int32_t ans; loadint32(&ans, buf); return ans; } -static inline int64_t swapint64(const void *buf) { +static inline int64_t swapint64(const void *buf) +{ int64_t ans; loadint64(&ans, buf); return ans; } -static inline void getchars(char **buf, void *ans, int n) { +static inline void getchars(char **buf, void *ans, int n) +{ memcpy(ans, *buf, n); *buf += n; } -static inline void getint8(char **buf, const void *ans) { +static inline void getint8(char **buf, const void *ans) +{ *(char *)ans = **buf; *buf += sizeof(int8_t); } -static inline void getint16(char **buf, void *ans) { +static inline void getint16(char **buf, void *ans) +{ loadint16(ans, *buf); *buf += sizeof(int16_t); } -static inline void getint32(char **buf, void *ans) { +static inline void getint32(char **buf, void *ans) +{ loadint32(ans, *buf); *buf += sizeof(int32_t); } -static inline void getint64(char **buf, void *ans) { +static inline void getint64(char **buf, void *ans) +{ loadint64(ans, *buf); *buf += sizeof(int64_t); } -static inline void putchars(char **buf, const void *ans, int n) { +static inline void putchars(char **buf, const void *ans, int n) +{ memcpy(*buf, ans, n); *buf += n; } -static inline void putint8(char **buf, const void *ans) { +static inline void putint8(char **buf, const void *ans) +{ **buf = *(char *)ans; *buf += sizeof(int8_t); } -static inline void putint16(char **buf, const void *ans) { +static inline void putint16(char **buf, const void *ans) +{ loadint16(*buf, ans); *buf += sizeof(int16_t); } -static inline void putint32(char **buf, const void *ans) { +static inline void putint32(char **buf, const void *ans) +{ loadint32(*buf, ans); *buf += sizeof(int32_t); } -static inline void putint64(char **buf, const void *ans) { +static inline void putint64(char **buf, const void *ans) +{ loadint64(*buf, ans); *buf += sizeof(int64_t); } -#define bitassign(bool, value, mask) \ +#define bitassign(bool, value, mask) \ value = (bool) ? (value) | (unsigned)(mask) : (value) & ~(unsigned)(mask) -#define bitassign_c(bool, value, mask) \ - value = (unsigned char)(((bool) ? (value) | (unsigned)(mask) \ - : (value) & ~(unsigned)(mask)) & \ +#define bitassign_c(bool, value, mask) \ + value = (unsigned char)(((bool) ? (value) | (unsigned)(mask) \ + : (value) & ~(unsigned)(mask)) & \ 0xFF) /***************************************** @@ -230,12 +257,14 @@ can be passed between processes. ******************************************/ #ifdef WORDS_BIGENDIAN -typedef struct nid { +typedef struct nid +{ unsigned int tree : 8; unsigned int node : 24; } NID; #else -typedef struct nid { +typedef struct nid +{ unsigned int node : 24; /* Node offset of root node of tree this node belongs to */ unsigned int @@ -243,7 +272,7 @@ typedef struct nid { } NID; #endif -#define MAX_SUBTREES \ +#define MAX_SUBTREES \ 256 /* since there are only 8 bits of tree number in a nid */ #define DEFAULT_STACK_LIMIT 8 @@ -266,7 +295,8 @@ typedef char TREE_NAME[12]; node it should be set to sizeof(NODE) etc. *********************************************/ #pragma pack(push, 1) -typedef struct node { +typedef struct node +{ NODE_NAME name; int parent; int member; @@ -293,11 +323,13 @@ static NODE empty_node = { 0}; #endif -static inline int node_offset(NODE *a, NODE *b) { +static inline int node_offset(NODE *a, NODE *b) +{ /* Returns byte offset of two nodes if both pointers are not NULL otherwise 0 */ int ans = 0; - if (a && b) { + if (a && b) + { ans = (int)((char *)a - (char *)b); ans = swapint32(&ans); } @@ -317,7 +349,8 @@ static inline int node_offset(NODE *a, NODE *b) { typedef char TAG_NAME[24]; -typedef struct tag_info { +typedef struct tag_info +{ TAG_NAME name; int node_idx; /* Node to which this tag is assigned */ int tag_link; /* Index of next tag also assigned to this node (index of first @@ -332,7 +365,8 @@ typedef struct tag_info { bytes of a tree file *********************************************/ -typedef struct tree_header { +typedef struct tree_header +{ char version; /* Version of tree file format */ #ifdef _AIX unsigned sort_children : 1; @@ -350,11 +384,11 @@ typedef struct tree_header { unsigned char : 3; #endif char fill1[6]; - int free; /* First node in free node list (connected by PARENT/CHILD indexes + int free; /* First node in free node list (connected by PARENT/CHILD indexes */ - int tags; /* Number of tags defined */ + int tags; /* Number of tags defined */ int externals; /* Number of externals/subtrees referenced */ - int nodes; /* Number of nodes allocated (both defined and free node) */ + int nodes; /* Number of nodes allocated (both defined and free node) */ char fill2[488]; } TREE_HEADER; @@ -363,18 +397,19 @@ Defines RFA type as 6 characters. Used for moving RFA's around efficiently. ************************************/ -typedef struct { +typedef struct +{ unsigned char rfa[6]; } RFA; #ifdef RFA_MACROS -#define RfaToSeek(rfa) \ - (((*(unsigned int *)rfa - 1) * 512) + \ +#define RfaToSeek(rfa) \ + (((*(unsigned int *)rfa - 1) * 512) + \ (*(unsigned short *)&((char *)rfa)[4] & 0x1ff)) -#define SeekToRfa(seek, rfa) \ - { \ - *(unsigned int *)rfa = (unsigned int)(seek / 512 + 1); \ - *(unsigned short *)&(((char *)rfa)[4]) = (unsigned short)(seek % 512); \ +#define SeekToRfa(seek, rfa) \ + { \ + *(unsigned int *)rfa = (unsigned int)(seek / 512 + 1); \ + *(unsigned short *)&(((char *)rfa)[4]) = (unsigned short)(seek % 512); \ } #endif @@ -383,7 +418,8 @@ RECORD_HEADER VFC portion of file. ***************************************/ #pragma pack(push, 1) -typedef struct record_header { +typedef struct record_header +{ unsigned short rlength; // packed! is aligned int node_number; // packed! is not aligned RFA rfa; @@ -392,7 +428,8 @@ typedef struct record_header { /***************************************************** * New Search structures *****************************************************/ -typedef enum yytokentype { +typedef enum yytokentype +{ TAG_TREE = 258, TAG = 259, CHILD = 260, @@ -407,18 +444,21 @@ typedef enum yytokentype { EOLL = 269 } YYTOKENTYPE; -typedef struct _st { +typedef struct _st +{ int search_type; char *term; struct _st *next; NODE *start_node; } SEARCH_TERM; -typedef struct node_list { +typedef struct node_list +{ NODE *node; struct node_list *next; } NODELIST; -typedef struct { +typedef struct +{ SEARCH_TERM *terms; char *wildcard; NODE *default_node; @@ -433,12 +473,14 @@ editting. It keeps track of dynamic memory allocations for tree expansions *********************************************/ -typedef struct deleted_nid { +typedef struct deleted_nid +{ NID nid; struct deleted_nid *next; } DELETED_NID; -typedef struct tree_edit { +typedef struct tree_edit +{ int header_pages; int node_vm_size; int tags_pages; @@ -465,7 +507,8 @@ in doing I/O to the tree files. #define DATAF_C_MAX_RECORD_SIZE (32765u - sizeof(RECORD_HEADER)) -typedef enum { +typedef enum +{ TREE_DIRECTORY = 0, // just directory TREE_TREEFILE_TYPE = 1, //".tree" TREE_NCIFILE_TYPE = 2, //".characteristics" @@ -481,7 +524,8 @@ needed to do I/O on the node characteristics file. *********************************************/ -typedef struct nci_file { +typedef struct nci_file +{ int get; int put; NCI nci; @@ -493,7 +537,8 @@ Structure used for passing information to asynchronous I/O completion routines ***************************************/ -typedef struct asy_nci { +typedef struct asy_nci +{ struct tree_info *info; NCI *nci; } ASY_NCI; @@ -502,7 +547,8 @@ typedef struct asy_nci { DATA_FILE structure used for I/O to datafile ********************************************/ -typedef struct data_file { +typedef struct data_file +{ unsigned open_for_write : 1; unsigned : 7; int get; @@ -520,45 +566,46 @@ of trees which have been activated. There will be one tree info block per tree activated. *********************************************/ -typedef struct tree_info { - struct tree_info *next_info; /* Pointer to next tree info block */ - int blockid; /* Identifier indicating a valid tree info block */ - char *treenam; /* Tree name */ - int shot; /* Shot number */ - int vm_pages; /* Number of pages and address of virtual memory */ - void *vm_addr; /* allocated for mapping the tree file */ - char *section_addr[2]; /* Beginning and ending addresses of mapped section */ - TREE_HEADER *header; /* Pointer to file header */ - NODE *node; /* Pointer to nodes */ - int *tags; /* Pointer to tag indexes */ - TAG_INFO *tag_info; /* Pointer to tag information blocks */ - int *external; /* Pointer to external reference node indexes */ - int channel; /* I/O channel to tree file */ - int alq; /* Blocks allocated to tree file */ - int speclen; /* length of filespec part defined by local treepath*/ - char *filespec; /* Pointer to full file spec of tree file */ - char dvi[16]; /* Tree file disk info */ +typedef struct tree_info +{ + struct tree_info *next_info; /* Pointer to next tree info block */ + int blockid; /* Identifier indicating a valid tree info block */ + char *treenam; /* Tree name */ + int shot; /* Shot number */ + int vm_pages; /* Number of pages and address of virtual memory */ + void *vm_addr; /* allocated for mapping the tree file */ + char *section_addr[2]; /* Beginning and ending addresses of mapped section */ + TREE_HEADER *header; /* Pointer to file header */ + NODE *node; /* Pointer to nodes */ + int *tags; /* Pointer to tag indexes */ + TAG_INFO *tag_info; /* Pointer to tag information blocks */ + int *external; /* Pointer to external reference node indexes */ + int channel; /* I/O channel to tree file */ + int alq; /* Blocks allocated to tree file */ + int speclen; /* length of filespec part defined by local treepath*/ + char *filespec; /* Pointer to full file spec of tree file */ + char dvi[16]; /* Tree file disk info */ unsigned short tree_info_w_fid[3]; /* Tree file file id */ - unsigned flush : 1; /* Flush I/O's buffers */ - unsigned rundown : 1; /* Doing rundown */ - unsigned mapped : 1; /* Tree is mapped into memory */ - unsigned has_lock : 1; /* is privte context */ - int rundown_id; /* Rundown event id */ - NODE *root; /* Pointer to top node */ - TREE_EDIT *edit; /* Pointer to edit block (if editting the tree */ - NCI_FILE *nci_file; /* Pointer to nci file block (if open) */ - DATA_FILE *data_file; /* Pointer to a datafile access block */ + unsigned flush : 1; /* Flush I/O's buffers */ + unsigned rundown : 1; /* Doing rundown */ + unsigned mapped : 1; /* Tree is mapped into memory */ + unsigned has_lock : 1; /* is privte context */ + int rundown_id; /* Rundown event id */ + NODE *root; /* Pointer to top node */ + TREE_EDIT *edit; /* Pointer to edit block (if editting the tree */ + NCI_FILE *nci_file; /* Pointer to nci file block (if open) */ + DATA_FILE *data_file; /* Pointer to a datafile access block */ pthread_rwlock_t lock; } TREE_INFO; -#define RDLOCKINFO(info) \ - if (info->has_lock) \ +#define RDLOCKINFO(info) \ + if (info->has_lock) \ pthread_rwlock_rdlock(&info->lock) -#define WRLOCKINFO(info) \ - if (info->has_lock) \ +#define WRLOCKINFO(info) \ + if (info->has_lock) \ pthread_rwlock_wrlock(&info->lock) -#define UNLOCKINFO(info) \ - if (info->has_lock) \ +#define UNLOCKINFO(info) \ + if (info->has_lock) \ pthread_rwlock_unlock(&info->lock) /******************************************** @@ -570,13 +617,15 @@ always passed as an argument to tree traversal routines. *********************************************/ -typedef struct { +typedef struct +{ struct descriptor_xd start; struct descriptor_xd end; struct descriptor_xd delta; } timecontext_t; -typedef struct pino_database { +typedef struct pino_database +{ struct pino_database *next; /* Link to next database in open list */ TREE_INFO *tree_info; /* Pointer to main tree info block */ NODE *default_node; /* Pointer to current default node */ @@ -597,7 +646,8 @@ typedef struct pino_database { */ } PINO_DATABASE; -static inline NODE *nid_to_node(PINO_DATABASE *dbid, NID *nid) { +static inline NODE *nid_to_node(PINO_DATABASE *dbid, NID *nid) +{ TREE_INFO *info; unsigned int i; for (info = dbid->tree_info, i = 0; (i < nid->tree) && (info != NULL); @@ -608,21 +658,28 @@ static inline NODE *nid_to_node(PINO_DATABASE *dbid, NID *nid) { : (NODE *)0; } -static inline NODE *parent_of(PINO_DATABASE *dbid, NODE *a) { +static inline NODE *parent_of(PINO_DATABASE *dbid, NODE *a) +{ NODE *ans = 0; - if (a) { - if (a->usage == TreeUSAGE_SUBTREE_TOP) { + if (a) + { + if (a->usage == TreeUSAGE_SUBTREE_TOP) + { ans = nid_to_node(dbid, (NID *)&a->parent); - } else if (a->parent) { + } + else if (a->parent) + { ans = (NODE *)((char *)a + swapint32(&a->parent)); } } return ans; } -static inline NODE *member_of(NODE *a) { +static inline NODE *member_of(NODE *a) +{ NODE *ans = 0; - if (a && a->member) { + if (a && a->member) + { ans = (NODE *)((char *)a + swapint32(&a->member)); } return ans; @@ -634,12 +691,17 @@ static inline NODE *member_of(NODE *a) { * however, when editing, the usage of the nde will never be * TreeUSAGE_SUBTREE_REF, so it will never call nid_to_node */ -static inline NODE *child_of(PINO_DATABASE *dbid, NODE *a) { +static inline NODE *child_of(PINO_DATABASE *dbid, NODE *a) +{ NODE *ans = 0; - if (a && a->child) { - if (a->usage == TreeUSAGE_SUBTREE_REF) { + if (a && a->child) + { + if (a->usage == TreeUSAGE_SUBTREE_REF) + { ans = nid_to_node(dbid, (NID *)&a->child); - } else { + } + else + { ans = (NODE *)((char *)a + swapint32(&a->child)); } } @@ -648,12 +710,17 @@ static inline NODE *child_of(PINO_DATABASE *dbid, NODE *a) { return ans; } -static inline NODE *brother_of(PINO_DATABASE *dbid, NODE *a) { +static inline NODE *brother_of(PINO_DATABASE *dbid, NODE *a) +{ NODE *ans = 0; - if (a && a->brother) { - if (a->usage == TreeUSAGE_SUBTREE_TOP) { + if (a && a->brother) + { + if (a->usage == TreeUSAGE_SUBTREE_TOP) + { ans = nid_to_node(dbid, (NID *)&a->brother); - } else { + } + else + { ans = (NODE *)((char *)a + swapint32(&a->brother)); if (ans->usage == TreeUSAGE_SUBTREE_REF) ans = nid_to_node(dbid, (NID *)&ans->child); @@ -664,12 +731,14 @@ static inline NODE *brother_of(PINO_DATABASE *dbid, NODE *a) { return ans; } -static inline NODE *descendant_of(PINO_DATABASE *dbid, NODE *a) { +static inline NODE *descendant_of(PINO_DATABASE *dbid, NODE *a) +{ NODE *answer = member_of(a); return (answer) ? answer : child_of(dbid, a); } -static inline int is_member(PINO_DATABASE *dblist, NODE *node) { +static inline int is_member(PINO_DATABASE *dblist, NODE *node) +{ NODE *n = 0; if (parent_of(dblist, node)) for (n = member_of(parent_of(dblist, node)); n && n != node; @@ -678,7 +747,8 @@ static inline int is_member(PINO_DATABASE *dblist, NODE *node) { return n == node; } -static inline NODE *sibling_of(PINO_DATABASE *dbid, NODE *a) { +static inline NODE *sibling_of(PINO_DATABASE *dbid, NODE *a) +{ NODE *answer = brother_of(dbid, a); if (!answer) if (is_member(dbid, a)) @@ -711,11 +781,13 @@ nid_to_node__info->next_info : 0;\ } */ -static inline int node_to_nid(PINO_DATABASE *dbid, NODE *node, NID *nid_out) { +static inline int node_to_nid(PINO_DATABASE *dbid, NODE *node, NID *nid_out) +{ TREE_INFO *info; NID nid = {0, 0}; for (info = dbid->tree_info, nid.tree = 0; info != NULL; - info = info->next_info, nid.tree++) { + info = info->next_info, nid.tree++) + { if ((node >= info->node) && (node <= (info->node + info->header->nodes))) break; } @@ -734,10 +806,11 @@ Another useful macro based on nid: nid_to_tree_nidx(pino, nid, info, nidx) *******************************************/ -#define nid_to_tree_nidx(pino, nid, info, nidx) \ +#define nid_to_tree_nidx(pino, nid, info, nidx) \ nidx = nid_to_tree_idx(pino, nid, &info) static inline int nid_to_tree_idx(PINO_DATABASE *pino, NID *nid, - TREE_INFO **info_out) { + TREE_INFO **info_out) +{ unsigned int i; TREE_INFO *info = pino->tree_info; for (i = 0; info && i < nid->tree; i++) diff --git a/treeshr/treethreadstatic.h b/treeshr/treethreadstatic.h index 798af5fd89..6cb00034f6 100644 --- a/treeshr/treethreadstatic.h +++ b/treeshr/treethreadstatic.h @@ -7,7 +7,8 @@ #define TREETHREADSTATIC_ARG TREETHREADSTATIC_TYPE *TREETHREADSTATIC_VAR #define TREETHREADSTATIC(MTS) TREETHREADSTATIC_ARG = TreeGetThreadStatic(MTS) #define TREETHREADSTATIC_INIT TREETHREADSTATIC(NULL) -typedef struct { +typedef struct +{ void *dbid; int64_t view_date; NCI temp_nci; diff --git a/treeshr/TreeFindNodeWild.l b/treeshr/yylex/TreeFindNodeWild.l similarity index 90% rename from treeshr/TreeFindNodeWild.l rename to treeshr/yylex/TreeFindNodeWild.l index e89b8e5e03..24535e627e 100644 --- a/treeshr/TreeFindNodeWild.l +++ b/treeshr/yylex/TreeFindNodeWild.l @@ -1,3 +1,7 @@ +%option prefix="treepath" outfile="treeshr/TreeFindNodeWild.c" +%option stack noyymore nodefault noyywrap noyylineno +%option nounput noinput noyy_push_state noyy_pop_state noyy_top_state +%option never-interactive reentrant %{ #include #include @@ -40,7 +44,7 @@ newline \n %option noinput %option nounput %option noyywrap -%option reentrant +%option reentrant %option prefix="yytreepath" %option extra-type="SEARCH_CTX *" %% @@ -88,11 +92,11 @@ newline \n } %% /* -STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) +STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) { const char * names[] = { "TAG_TREE", - "TAG", + "TAG", "CHILD", "MEMBER", "CHILD_OR_MEMBER", @@ -107,12 +111,12 @@ STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) return names[typ-TAG_TREE]; } -STATIC_ROUTINE void PrintCtx(SEARCH_CTX *ctx) +STATIC_ROUTINE void PrintCtx(SEARCH_CTX *ctx) { SEARCH_TERM *ptr; printf ("Print Context for %s\n", ctx->wildcard); - for ( ptr=ctx->terms; - ptr; + for ( ptr=ctx->terms; + ptr; ptr=ptr->next) { printf("\t%s -%s-\n", SearchTypeName(ptr->search_type), ptr->term); } @@ -159,7 +163,7 @@ static char *strtrim(char *str) return str; } -EXPORT int WildParse(char const *path, SEARCH_CTX *ctx, int *wild) +EXPORT int WildParse(char const *path, SEARCH_CTX *ctx, int *wild) { int status = 1; @@ -185,11 +189,11 @@ EXPORT int WildParse(char const *path, SEARCH_CTX *ctx, int *wild) /* now merge in trailing search clauses */ ctx->terms=SquishSearches(ctx->terms); /* check if any terms are wild */ - *wild = strchr(wild_path, '*') || - strchr(wild_path, '%') || - strstr(wild_path, "~~~") || - strstr(wild_path, "...") || - strstr(wild_path, ":::") || + *wild = strchr(wild_path, '*') || + strchr(wild_path, '%') || + strstr(wild_path, "~~~") || + strstr(wild_path, "...") || + strstr(wild_path, ":::") || strstr(wild_path, "^^^") ; } yytreepathlex_destroy(scanner); @@ -229,4 +233,3 @@ STATIC_ROUTINE void addSearchTerm(yyscan_t scanner, int type, char *str) p->next = ptr; } } - diff --git a/treeshr/yylex/fixme-files b/treeshr/yylex/fixme-files new file mode 100644 index 0000000000..3324dd5bcd --- /dev/null +++ b/treeshr/yylex/fixme-files @@ -0,0 +1 @@ +treeshr/TreeFindNodeWild.c \ No newline at end of file diff --git a/wfevent/wfevent.c b/wfevent/wfevent.c index e7d5e72353..9c3e5b673c 100644 --- a/wfevent/wfevent.c +++ b/wfevent/wfevent.c @@ -38,7 +38,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Program to wait for MDSPlus event from the command line. */ -static void printhelp(char *cmd) { +static void printhelp(char *cmd) +{ #ifdef _WIN32 printf("usage: %s [/d] [/D] [/t:n] [/?] event-name\n", cmd); printf("\n event-name is the event that you want to wait for." @@ -60,7 +61,8 @@ static void printhelp(char *cmd) { extern int TdiDecompile(); -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ int len; char data[MAXDATA]; int showdata = 0; @@ -71,9 +73,12 @@ int main(int argc, char **argv) { #ifdef _WIN32 int optind = argc; int i; - for (i = 1; i < argc; i++) { - if (argv[i][0] == '/') { - switch (argv[i][1]) { + for (i = 1; i < argc; i++) + { + if (argv[i][0] == '/') + { + switch (argv[i][1]) + { case '?': printhelp(argv[0]); return 0; @@ -94,10 +99,13 @@ int main(int argc, char **argv) { return 1; break; } - } else { + } + else + { if (optind == argc) optind = i; - else { + else + { printhelp(argv[0]); return 1; } @@ -110,8 +118,10 @@ int main(int argc, char **argv) { {"help", 0, 0, 'h'}, {"serialized", 0, 0, 'D'}, {0, 0, 0, 0}}; - while ((opt = getopt_long(argc, argv, "dDht:", longopts, 0)) > -1) { - switch (opt) { + while ((opt = getopt_long(argc, argv, "dDht:", longopts, 0)) > -1) + { + switch (opt) + { case 'h': printhelp(argv[0]); return 0; @@ -131,58 +141,75 @@ int main(int argc, char **argv) { } } #endif - if (optind == argc) { + if (optind == argc) + { printf("Missing event-name\n"); printhelp(argv[0]); return 1; } event = argv[optind]; status = MDSWfeventTimed(event, MAXDATA, data, &len, timeout); - if (status & 1) { - if (showdata && len) { + if (status & 1) + { + if (showdata && len) + { int i, istext = 1; - if (serialized) { + if (serialized) + { EMPTYXD(xd); struct descriptor ans = {0, DTYPE_T, CLASS_D, 0}; status = MdsSerializeDscIn(data, &xd); - if (status & 1) { + if (status & 1) + { TdiDecompile(&xd, &ans MDS_END_ARG); - if (ans.pointer) { + if (ans.pointer) + { printf("Event %s occurred with data = %.*s\n", event, ans.length, ans.pointer); return 0; } - } else { + } + else + { printf("Event %s occurred with invalid serialized data\n", event); return 1; } } if (len > MAXDATA) len = MAXDATA; - for (; data[len - 1] == 0 && len > 0; len--) { + for (; data[len - 1] == 0 && len > 0; len--) + { ; } - for (i = 0; i < len; i++) { - if (data[i] < 32 || data[i] >= 127) { + for (i = 0; i < len; i++) + { + if (data[i] < 32 || data[i] >= 127) + { istext = 0; break; } } if (istext) printf("Event %s occurred with data = \\%.*s\\\n", event, len, data); - else { + else + { printf("Event %s occured with data = [", event); - for (i = 0; i < len - 1; i++) { + for (i = 0; i < len - 1; i++) + { printf("%0dB,", (int)data[i]); } printf("%dB]\n", (int)data[i]); } } return (0); - } else if (timeout > 0) { + } + else if (timeout > 0) + { printf("Event %s timed out.\n", event); return 1; - } else { + } + else + { printf("Unknown error occurred\n"); return 1; } diff --git a/xmdsshr/ListTree.c b/xmdsshr/ListTree.c index e3aa80fe64..f6903afe8b 100644 --- a/xmdsshr/ListTree.c +++ b/xmdsshr/ListTree.c @@ -64,12 +64,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #ifdef DEBUG -#define DBG(fmt, ...) \ - do { \ - fprintf(stderr, "%s:%d %s() ", __FILE__, __LINE__, __FUNCTION__); \ - fprintf(stderr, fmt, __VA_ARGS__); \ +#define DBG(fmt, ...) \ + do \ + { \ + fprintf(stderr, "%s:%d %s() ", __FILE__, __LINE__, __FUNCTION__); \ + fprintf(stderr, fmt, __VA_ARGS__); \ } while (0) -#define DBGW(a) \ +#define DBGW(a) \ fprintf(stderr, "%s:%d %s() %s\n", __FILE__, __LINE__, __FUNCTION__, a) #else #define DBG(fmt...) @@ -79,23 +80,92 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define folder_width 16 #define folder_height 12 static unsigned char folder_bits[] = { - 0x00, 0x1f, 0x80, 0x20, 0x7c, 0x5f, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, - 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0xfc, 0x3f, + 0x00, + 0x1f, + 0x80, + 0x20, + 0x7c, + 0x5f, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0x02, + 0x40, + 0xfc, + 0x3f, }; #define folderopen_width 16 #define folderopen_height 12 static unsigned char folderopen_bits[] = { - 0x00, 0x3e, 0x00, 0x41, 0xf8, 0xd5, 0xac, 0xaa, 0x54, 0xd5, 0xfe, 0xaf, - 0x01, 0xd0, 0x02, 0xa0, 0x02, 0xe0, 0x04, 0xc0, 0x04, 0xc0, 0xf8, 0x7f, + 0x00, + 0x3e, + 0x00, + 0x41, + 0xf8, + 0xd5, + 0xac, + 0xaa, + 0x54, + 0xd5, + 0xfe, + 0xaf, + 0x01, + 0xd0, + 0x02, + 0xa0, + 0x02, + 0xe0, + 0x04, + 0xc0, + 0x04, + 0xc0, + 0xf8, + 0x7f, }; #define document_width 9 #define document_height 14 static unsigned char document_bits[] = { - 0x1f, 0x00, 0x31, 0x00, 0x51, 0x00, 0x91, 0x00, 0xf1, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0x01, + 0x1f, + 0x00, + 0x31, + 0x00, + 0x51, + 0x00, + 0x91, + 0x00, + 0xf1, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0x01, + 0xff, + 0x01, }; #define offset(field) XtOffsetOf(ListTreeRec, list.field) @@ -304,20 +374,23 @@ ListTreeClassRec listtreeClassRec = { EXPORT WidgetClass listtreeWidgetClass = (WidgetClass)&listtreeClassRec; -static void MakePixmap(ListTreeWidget w, Pixinfo *pix) { +static void MakePixmap(ListTreeWidget w, Pixinfo *pix) +{ Window root; int x, y; unsigned int width, height, bw, depth; if (pix->bitmap && XGetGeometry(XtDisplay((Widget)w), pix->bitmap, &root, &x, - &y, &width, &height, &bw, &depth)) { + &y, &width, &height, &bw, &depth)) + { pix->width = (int)width; pix->height = (int)height; if (pix->height > w->list.maxPixHeight) w->list.maxPixHeight = pix->height; /* Xmu dependency removed by Alan Marcinkowski */ - if (depth == 1) { + if (depth == 1) + { GC gc; XGCValues gcv; @@ -332,20 +405,25 @@ static void MakePixmap(ListTreeWidget w, Pixinfo *pix) { XCopyPlane(XtDisplay((Widget)w), pix->bitmap, pix->pix, gc, 0, 0, width, height, 0, 0, 1); XFreeGC(XtDisplay((Widget)w), gc); - } else + } + else pix->pix = pix->bitmap; - } else { + } + else + { pix->width = pix->height = 0; pix->pix = (Pixmap)NULL; } } -static void FreePixmap(ListTreeWidget w, Pixinfo *pix) { +static void FreePixmap(ListTreeWidget w, Pixinfo *pix) +{ if (pix->pix) XFreePixmap(XtDisplay((Widget)w), pix->pix); } -static void InitializePixmaps(ListTreeWidget w) { +static void InitializePixmaps(ListTreeWidget w) +{ w->list.maxPixHeight = 0; if (w->list.Closed.bitmap == XtUnspecifiedPixmap) @@ -385,7 +463,8 @@ static void InitializePixmaps(ListTreeWidget w) { w->list.LeafOpen.xoff = (w->list.pixWidth - w->list.LeafOpen.width) / 2; } -static void InitializeGC(ListTreeWidget w) { +static void InitializeGC(ListTreeWidget w) +{ XGCValues values; XtGCMask mask; @@ -412,13 +491,15 @@ static void InitializeGC(ListTreeWidget w) { w->list.highlightGC = XtGetGC((Widget)w, mask, &values); } -static void InitializeScrollBars(ListTreeWidget w) { +static void InitializeScrollBars(ListTreeWidget w) +{ if (XmIsScrolledWindow(XtParent(w))) w->list.mom = XtParent(w); else w->list.mom = NULL; - if (w->list.mom) { + if (w->list.mom) + { char *name = XtMalloc(strlen(XtName((Widget)w)) + 4); strcpy(name, XtName((Widget)w)); @@ -464,10 +545,12 @@ static void InitializeScrollBars(ListTreeWidget w) { } } -static void InitializeGeometry(ListTreeWidget w) { +static void InitializeGeometry(ListTreeWidget w) +{ w->list.XOffset = 0; - if (XtHeight(w) < 10) { + if (XtHeight(w) < 10) + { int working; working = FontHeight(w->list.font); @@ -484,7 +567,9 @@ static void InitializeGeometry(ListTreeWidget w) { 2 * Prim_HighlightThickness(w); XtHeight(w) = w->list.preferredHeight + 2 * Prim_ShadowThickness(w) + 2 * Prim_HighlightThickness(w); - } else { + } + else + { w->list.preferredWidth = XtWidth(w) - 2 * Prim_ShadowThickness(w) - 2 * Prim_HighlightThickness(w); w->list.preferredHeight = XtHeight(w) - 2 * Prim_ShadowThickness(w) - @@ -495,7 +580,8 @@ static void InitializeGeometry(ListTreeWidget w) { } static void Initialize(Widget request, Widget tnew, ArgList args, - Cardinal *num) { + Cardinal *num) +{ ListTreeWidget w; w = (ListTreeWidget)tnew; @@ -526,14 +612,17 @@ static void Initialize(Widget request, Widget tnew, ArgList args, InitializeGeometry(w); } -static void Destroy(ListTreeWidget w) { +static void Destroy(ListTreeWidget w) +{ ListTreeItem *item, *sibling; XtReleaseGC((Widget)w, w->list.drawGC); XtReleaseGC((Widget)w, w->list.highlightGC); item = w->list.first; - while (item) { - if (item->firstchild) { + while (item) + { + if (item->firstchild) + { DeleteChildren(w, item->firstchild); } sibling = item->nextsibling; @@ -547,15 +636,19 @@ static void Destroy(ListTreeWidget w) { FreePixmap(w, &w->list.LeafOpen); } -static void Redisplay(Widget aw, XExposeEvent *event, Region region) { +static void Redisplay(Widget aw, XExposeEvent *event, Region region) +{ ListTreeWidget w = (ListTreeWidget)aw; if (!XtIsRealized((Widget)w)) return; - if (event) { + if (event) + { Draw(w, (int)event->y, (int)event->height); - } else { /* event==NULL ==> repaint the entire list */ + } + else + { /* event==NULL ==> repaint the entire list */ DrawChanged(w); } @@ -568,14 +661,16 @@ static void Redisplay(Widget aw, XExposeEvent *event, Region region) { } static Boolean SetValues(Widget current, Widget request, Widget reply, - ArgList args, Cardinal *nargs) { + ArgList args, Cardinal *nargs) +{ if (!XtIsRealized(current)) return False; return True; } -static void ResizeStuff(ListTreeWidget w) { +static void ResizeStuff(ListTreeWidget w) +{ XRectangle clip; w->list.viewWidth = w->core.width - 2 * Prim_ShadowThickness(w) - @@ -600,22 +695,28 @@ static void ResizeStuff(ListTreeWidget w) { CountAll(w); w->list.visibleCount = 1; - if (w->list.itemHeight > 0) { + if (w->list.itemHeight > 0) + { w->list.visibleCount = w->list.viewHeight / (w->list.itemHeight + w->list.VSpacing); } } -#define HSB2X(w) \ - w->list.XOffset = -((int)w->list.Margin - w->list.Indent + \ +#define HSB2X(w) \ + w->list.XOffset = -((int)w->list.Margin - w->list.Indent + \ (w->list.Indent + w->list.pixWidth) * w->list.hsbPos); -static void SetScrollbars(ListTreeWidget w) { - if (w->list.vsb) { - if (w->list.itemCount == 0) { +static void SetScrollbars(ListTreeWidget w) +{ + if (w->list.vsb) + { + if (w->list.itemCount == 0) + { XtVaSetValues(w->list.vsb, XmNvalue, 0, XmNsliderSize, 1, XmNpageIncrement, 1, XmNmaximum, 1, NULL); - } else { + } + else + { int top, bot, size; top = w->list.topItemPos; @@ -634,27 +735,33 @@ static void SetScrollbars(ListTreeWidget w) { } } - if (w->list.hsb) { + if (w->list.hsb) + { int divisor, view; divisor = w->list.Indent + w->list.pixWidth; view = (w->list.viewWidth + divisor - 1) / divisor; w->list.hsbMax = (w->list.preferredWidth + divisor - 1) / divisor; - if (w->list.hsbPos > 0 && w->list.hsbPos + view > w->list.hsbMax) { + if (w->list.hsbPos > 0 && w->list.hsbPos + view > w->list.hsbMax) + { int save = w->list.hsbPos; w->list.hsbPos = w->list.hsbMax - view; if (w->list.hsbPos < 0) w->list.hsbPos = 0; - if (save != w->list.hsbPos) { + if (save != w->list.hsbPos) + { HSB2X(w); DrawAll(w); } } - if (w->list.itemCount == 0 || w->list.preferredWidth == 0) { + if (w->list.itemCount == 0 || w->list.preferredWidth == 0) + { XtVaSetValues(w->list.hsb, XmNvalue, 0, XmNsliderSize, 1, XmNpageIncrement, 1, XmNmaximum, 1, NULL); - } else { + } + else + { XtVaSetValues(w->list.hsb, XmNvalue, w->list.hsbPos, XmNsliderSize, min(w->list.hsbMax, view), XmNpageIncrement, view, XmNmaximum, w->list.hsbMax, NULL); @@ -665,7 +772,8 @@ static void SetScrollbars(ListTreeWidget w) { } static void VSBCallback(Widget scrollbar, XtPointer client_data, - XtPointer call_data) { + XtPointer call_data) +{ ListTreeWidget w = (ListTreeWidget)client_data; XmScrollBarCallbackStruct *cbs = (XmScrollBarCallbackStruct *)call_data; @@ -683,7 +791,8 @@ static void VSBCallback(Widget scrollbar, XtPointer client_data, SetScrollbars(w); } #else - if (w->list.topItemPos != w->list.lastItemPos) { + if (w->list.topItemPos != w->list.lastItemPos) + { GotoPosition(w); DrawAll(w); SetScrollbars(w); @@ -692,7 +801,8 @@ static void VSBCallback(Widget scrollbar, XtPointer client_data, } static void HSBCallback(Widget scrollbar, XtPointer client_data, - XtPointer call_data) { + XtPointer call_data) +{ ListTreeWidget w = (ListTreeWidget)client_data; XmScrollBarCallbackStruct *cbs = (XmScrollBarCallbackStruct *)call_data; @@ -701,12 +811,14 @@ static void HSBCallback(Widget scrollbar, XtPointer client_data, DBG("XOffset=%d prefWidth=%d viewWidth=%d\n", w->list.XOffset, w->list.preferredWidth, w->list.viewWidth); - if (w->list.XOffset != w->list.lastXOffset) { + if (w->list.XOffset != w->list.lastXOffset) + { DrawAll(w); } } -static void Resize(ListTreeWidget w) { +static void Resize(ListTreeWidget w) +{ if (!XtIsRealized((Widget)w)) return; @@ -716,7 +828,8 @@ static void Resize(ListTreeWidget w) { static XtGeometryResult QueryGeometry(ListTreeWidget w, XtWidgetGeometry *proposed, - XtWidgetGeometry *answer) { + XtWidgetGeometry *answer) +{ answer->request_mode = CWWidth | CWHeight; answer->width = w->list.preferredWidth + 2 * Prim_ShadowThickness(w) + 2 * Prim_HighlightThickness(w); @@ -727,15 +840,18 @@ static XtGeometryResult QueryGeometry(ListTreeWidget w, if (proposed->width >= answer->width && proposed->height >= answer->height) return XtGeometryYes; - else if (answer->width == XtWidth(w) && answer->height == XtHeight(w)) { + else if (answer->width == XtWidth(w) && answer->height == XtHeight(w)) + { answer->request_mode = 0; return XtGeometryNo; - } else + } + else return XtGeometryAlmost; } static void Realize(Widget aw, XtValueMask *value_mask, - XSetWindowAttributes *attributes) { + XSetWindowAttributes *attributes) +{ ListTreeWidget w = (ListTreeWidget)aw; #define superclass (&xmPrimitiveClassRec) @@ -748,7 +864,8 @@ static void Realize(Widget aw, XtValueMask *value_mask, /* DEBUGGING FUNCTIONS */ #ifdef DEBUG_TREE -void ItemCheck(ListTreeWidget w, ListTreeItem *item) { +void ItemCheck(ListTreeWidget w, ListTreeItem *item) +{ ListTreeItem *p; char text[1024]; @@ -763,7 +880,8 @@ void ItemCheck(ListTreeWidget w, ListTreeItem *item) { /* } */ /* fprintf(stderr,"\n"); */ - if (strcmp(item->text, "pixmaps") == 0) { + if (strcmp(item->text, "pixmaps") == 0) + { fprintf(stderr, "parent: %x\n", item->parent); fprintf(stderr, "firstchild: %x\n", item->firstchild); fprintf(stderr, "prevsibling: %x\n", item->prevsibling); @@ -771,8 +889,10 @@ void ItemCheck(ListTreeWidget w, ListTreeItem *item) { } } -void ChildrenCheck(ListTreeWidget w, ListTreeItem *item) { - while (item) { +void ChildrenCheck(ListTreeWidget w, ListTreeItem *item) +{ + while (item) + { ItemCheck(w, item); if (item->firstchild) ChildrenCheck(w, item->firstchild); @@ -780,12 +900,14 @@ void ChildrenCheck(ListTreeWidget w, ListTreeItem *item) { } } -void TreeCheck(ListTreeWidget w, char *txt) { +void TreeCheck(ListTreeWidget w, char *txt) +{ ListTreeItem *item; fprintf(stderr, "\n\n%s\n", txt); item = w->list.first; - while (item) { + while (item) + { ItemCheck(w, item); if (item->firstchild) ChildrenCheck(w, item->firstchild); @@ -799,13 +921,18 @@ void TreeCheck(ListTreeWidget w, char *txt) { /* Highlighting Utilities ----------------------------------------------- */ static void HighlightItem(ListTreeWidget w, ListTreeItem *item, Boolean state, - Boolean draw) { - if (item) { - if (item == w->list.highlighted && !state) { + Boolean draw) +{ + if (item) + { + if (item == w->list.highlighted && !state) + { w->list.highlighted = NULL; if (draw && item->count >= w->list.topItemPos) DrawItemHighlightClear(w, item); - } else if (state != item->highlighted) { + } + else if (state != item->highlighted) + { /* printf("Highlighting '%s' state=%d x=%d y=%d\n", item->text, draw, * item->x, item->ytext); */ item->highlighted = state; @@ -817,10 +944,13 @@ static void HighlightItem(ListTreeWidget w, ListTreeItem *item, Boolean state, } static void HighlightChildren(ListTreeWidget w, ListTreeItem *item, - Boolean state, Boolean draw) { - while (item) { + Boolean state, Boolean draw) +{ + while (item) + { HighlightItem(w, item, state, draw); - if (item->firstchild) { + if (item->firstchild) + { Boolean drawkids; if (item->open) @@ -833,36 +963,45 @@ static void HighlightChildren(ListTreeWidget w, ListTreeItem *item, } } -static void HighlightAll(ListTreeWidget w, Boolean state, Boolean draw) { +static void HighlightAll(ListTreeWidget w, Boolean state, Boolean draw) +{ HighlightChildren(w, w->list.first, state, draw); } static void HighlightVisibleChildren(ListTreeWidget w, ListTreeItem *item, - Boolean state, Boolean draw) { - while (item) { + Boolean state, Boolean draw) +{ + while (item) + { HighlightItem(w, item, state, draw); - if (item->firstchild && item->open) { + if (item->firstchild && item->open) + { HighlightVisibleChildren(w, item->firstchild, state, draw); } item = item->nextsibling; } } -static void HighlightAllVisible(ListTreeWidget w, Boolean state, Boolean draw) { +static void HighlightAllVisible(ListTreeWidget w, Boolean state, Boolean draw) +{ ListTreeItem *item; item = w->list.first; - while (item) { + while (item) + { HighlightItem(w, item, state, draw); - if (item->firstchild && item->open) { + if (item->firstchild && item->open) + { HighlightVisibleChildren(w, item->firstchild, state, draw); } item = item->nextsibling; } } -static void AddItemToReturnList(ListTreeWidget w, ListTreeItem *item, int loc) { - if (loc >= w->list.ret_item_alloc) { +static void AddItemToReturnList(ListTreeWidget w, ListTreeItem *item, int loc) +{ + if (loc >= w->list.ret_item_alloc) + { w->list.ret_item_alloc += ListTreeRET_ALLOC; w->list.ret_item_list = (ListTreeItem **)XtRealloc( (char *)w->list.ret_item_list, @@ -872,15 +1011,18 @@ static void AddItemToReturnList(ListTreeWidget w, ListTreeItem *item, int loc) { } static void MultiAddToReturn(ListTreeWidget w, ListTreeItem *item, - ListTreeMultiReturnStruct *ret) { + ListTreeMultiReturnStruct *ret) +{ AddItemToReturnList(w, item, ret->count); ret->items = w->list.ret_item_list; ret->count++; } static void HighlightCount(ListTreeWidget w, ListTreeItem *item, - ListTreeMultiReturnStruct *ret) { - while (item) { + ListTreeMultiReturnStruct *ret) +{ + while (item) + { if (item->highlighted) MultiAddToReturn(w, item, ret); if (item->firstchild && item->open) @@ -890,13 +1032,15 @@ static void HighlightCount(ListTreeWidget w, ListTreeItem *item, } static void MakeMultiCallbackStruct(ListTreeWidget w, - ListTreeMultiReturnStruct *ret) { + ListTreeMultiReturnStruct *ret) +{ ListTreeItem *item; ret->items = NULL; ret->count = 0; item = w->list.first; - while (item) { + while (item) + { if (item->highlighted) MultiAddToReturn(w, item, ret); if (item->firstchild && item->open) @@ -905,10 +1049,12 @@ static void MakeMultiCallbackStruct(ListTreeWidget w, } } -static void HighlightDoCallback(ListTreeWidget w) { +static void HighlightDoCallback(ListTreeWidget w) +{ ListTreeMultiReturnStruct ret; - if (w->list.HighlightCallback) { + if (w->list.HighlightCallback) + { MakeMultiCallbackStruct(w, &ret); XtCallCallbacks((Widget)w, XtNhighlightCallback, &ret); } @@ -917,13 +1063,15 @@ static void HighlightDoCallback(ListTreeWidget w) { /* Events ------------------------------------------------------------------ */ static void MakeActivateCallbackStruct(ListTreeWidget w, ListTreeItem *item, - ListTreeActivateStruct *ret) { + ListTreeActivateStruct *ret) +{ int count; ListTreeItem *parent; count = 1; parent = item; - while (parent->parent) { + while (parent->parent) + { parent = parent->parent; count++; } @@ -935,7 +1083,8 @@ static void MakeActivateCallbackStruct(ListTreeWidget w, ListTreeItem *item, ret->reason = XtBRANCH; else ret->reason = XtLEAF; - while (count > 0) { + while (count > 0) + { count--; AddItemToReturnList(w, item, count); item = item->parent; @@ -943,11 +1092,13 @@ static void MakeActivateCallbackStruct(ListTreeWidget w, ListTreeItem *item, ret->path = w->list.ret_item_list; } -static void SelectDouble(ListTreeWidget w) { +static void SelectDouble(ListTreeWidget w) +{ ListTreeActivateStruct ret; TreeCheck(w, "in SelectDouble"); - if (w->list.timer_item) { + if (w->list.timer_item) + { w->list.timer_type = TIMER_DOUBLE; w->list.timer_item->open = !w->list.timer_item->open; w->list.highlighted = w->list.timer_item; @@ -956,7 +1107,8 @@ static void SelectDouble(ListTreeWidget w) { MakeActivateCallbackStruct(w, w->list.timer_item, &ret); /* Highlight the path if we need to */ - if (w->list.HighlightPath) { + if (w->list.HighlightPath) + { Boolean save; save = w->list.Refresh; @@ -967,7 +1119,8 @@ static void SelectDouble(ListTreeWidget w) { /* ListTreeSetHighlighted(w,ret2.items,ret2.count,True); */ } - if (w->list.ActivateCallback) { + if (w->list.ActivateCallback) + { XtCallCallbacks((Widget)w, XtNactivateCallback, (XtPointer)&ret); } @@ -979,14 +1132,19 @@ static void SelectDouble(ListTreeWidget w) { } /* ARGSUSED */ -static void SelectSingle(XtPointer client_data, XtIntervalId *idp) { +static void SelectSingle(XtPointer client_data, XtIntervalId *idp) +{ ListTreeWidget w = (ListTreeWidget)client_data; w->list.timer_id = (XtIntervalId)0; - if (w->list.timer_item) { - if (w->list.ClickPixmapToOpen && w->list.timer_x < w->list.timer_item->x) { + if (w->list.timer_item) + { + if (w->list.ClickPixmapToOpen && w->list.timer_x < w->list.timer_item->x) + { SelectDouble(w); - } else { + } + else + { HighlightAll(w, False, True); HighlightItem(w, w->list.timer_item, True, True); if (w->list.timer_type != TIMER_CLEAR && @@ -999,7 +1157,8 @@ static void SelectSingle(XtPointer client_data, XtIntervalId *idp) { /* ARGSUSED */ static void select_start(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeWidget w = (ListTreeWidget)aw; w->list.timer_item = NULL; @@ -1008,17 +1167,24 @@ static void select_start(Widget aw, XEvent *event, String *params, w->list.timer_type = TIMER_WAITING; w->list.timer_item = GetItem(w, event->xbutton.y); - if (!w->list.timer_item) { - if (w->list.timer_id) { + if (!w->list.timer_item) + { + if (w->list.timer_id) + { XtRemoveTimeOut(w->list.timer_id); w->list.timer_id = (XtIntervalId)0; } - } else { - if (w->list.timer_id) { + } + else + { + if (w->list.timer_id) + { XtRemoveTimeOut(w->list.timer_id); w->list.timer_id = (XtIntervalId)0; SelectDouble(w); - } else { + } + else + { w->list.timer_id = XtAppAddTimeOut( XtWidgetToApplicationContext((Widget)w), (unsigned long)w->list.multi_click_time, SelectSingle, (XtPointer)w); @@ -1028,7 +1194,8 @@ static void select_start(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void extend_select_start(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeWidget w = (ListTreeWidget)aw; w->list.timer_item = NULL; @@ -1045,7 +1212,8 @@ static void extend_select_start(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void extend_select(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeItem *item; ListTreeWidget w = (ListTreeWidget)aw; int y, yend; @@ -1056,22 +1224,30 @@ static void extend_select(Widget aw, XEvent *event, String *params, /* We need the timer_item to be pointing to the first selection in this */ /* group. If we got here without it being set, something is very wrong. */ - if (w->list.timer_item) { + if (w->list.timer_item) + { y = w->list.timer_y; yend = event->xbutton.y; item = GetItem(w, y); - if (y < yend) { - while (item && y < yend && y < w->list.viewY + w->list.viewHeight) { - if (item) { + if (y < yend) + { + while (item && y < yend && y < w->list.viewY + w->list.viewHeight) + { + if (item) + { DBG("Highlighting y=%d item=%s\n", y, item->text); HighlightItem(w, item, True, True); y += item->height + w->list.VSpacing; } item = GetItem(w, y); } - } else { - while (item && y > yend && y > 0) { - if (item) { + } + else + { + while (item && y > yend && y > 0) + { + if (item) + { DBG("Highlighting y=%d item=%s\n", y, item->text); HighlightItem(w, item, True, True); y -= item->height + w->list.VSpacing; @@ -1087,12 +1263,14 @@ static void extend_select(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void unset(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeItem *item; ListTreeWidget w = (ListTreeWidget)aw; item = GetItem(w, event->xbutton.y); - if (item) { + if (item) + { /* item->open=False; */ /* lw->list.highlighted=item; */ /* DrawAll(lw); */ @@ -1102,13 +1280,17 @@ static void unset(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void notify(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeWidget w = (ListTreeWidget)aw; - if (w->list.timer_id) { + if (w->list.timer_id) + { /* don't call highlightCallback if we are waiting for a double click */ - } else if (w->list.timer_type != TIMER_CLEAR && - !w->list.DoIncrementalHighlightCallback) { + } + else if (w->list.timer_type != TIMER_CLEAR && + !w->list.DoIncrementalHighlightCallback) + { HighlightDoCallback(w); w->list.timer_type = TIMER_CLEAR; } @@ -1116,12 +1298,14 @@ static void notify(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void focus_in(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeWidget w = (ListTreeWidget)aw; DBGW("focus_in"); - if (!w->list.HasFocus) { + if (!w->list.HasFocus) + { XtCallActionProc(aw, "PrimitiveFocusIn", event, params, *num_params); w->list.HasFocus = True; @@ -1130,12 +1314,14 @@ static void focus_in(Widget aw, XEvent *event, String *params, /* ARGSUSED */ static void focus_out(Widget aw, XEvent *event, String *params, - Cardinal *num_params) { + Cardinal *num_params) +{ ListTreeWidget w = (ListTreeWidget)aw; DBGW("focus_out"); - if (w->list.HasFocus) { + if (w->list.HasFocus) + { XtCallActionProc(aw, "PrimitiveFocusOut", event, params, *num_params); w->list.HasFocus = False; @@ -1152,12 +1338,14 @@ Cardinal *num_params; ListTreeItem *item; ListTreeItemReturnStruct ret; - if (w->list.MenuCallback) { + if (w->list.MenuCallback) + { /* See if there is an item at the position of the click */ item = GetItem(w, event->xbutton.y); - if (item) { + if (item) + { ret.reason = XtMENU; ret.item = item; ret.event = event; @@ -1171,18 +1359,22 @@ static void keypress(aw, event, params, num_params) Widget aw; XEvent *event; String *params; Cardinal *num_params; -{ DBG("keypress\n"); } +{ + DBG("keypress\n"); +} /* ListTree private drawing functions ------------------------------------- */ /* Select the pixmap to use, if any */ -static Pixinfo *GetItemPix(ListTreeWidget w, ListTreeItem *item) { +static Pixinfo *GetItemPix(ListTreeWidget w, ListTreeItem *item) +{ Pixinfo *pix; pix = NULL; /* Another enhancement from Alan Marcinkowski */ - if (item->openPixmap || item->closedPixmap) { + if (item->openPixmap || item->closedPixmap) + { /* Guess that it is closed. */ Pixmap pixmap = item->closedPixmap; @@ -1192,12 +1384,14 @@ static Pixinfo *GetItemPix(ListTreeWidget w, ListTreeItem *item) { /* If it is not closed and there is a pixmap for it, then use that one * instead. */ - if (item->open && item->openPixmap) { + if (item->open && item->openPixmap) + { pixmap = item->openPixmap; } /* Make sure we got one. */ - if (pixmap) { + if (pixmap) + { /* Get the geometry of the pixmap. */ XGetGeometry(XtDisplay((Widget)w), pixmap, &root, (int *)&pixx, (int *)&pixy, &pixwidth, &pixheight, &pixbw, &pixdepth); @@ -1212,13 +1406,17 @@ static Pixinfo *GetItemPix(ListTreeWidget w, ListTreeItem *item) { } /* If we don't have a pixmap yet... */ - if (!pix) { - if (item->firstchild || item->type == ItemBranchType) { + if (!pix) + { + if (item->firstchild || item->type == ItemBranchType) + { if (item->open) pix = &w->list.Open; else pix = &w->list.Closed; - } else { + } + else + { if (item->open) pix = &w->list.LeafOpen; else @@ -1229,10 +1427,12 @@ static Pixinfo *GetItemPix(ListTreeWidget w, ListTreeItem *item) { return pix; } -static void DrawItemHighlight(ListTreeWidget w, ListTreeItem *item) { +static void DrawItemHighlight(ListTreeWidget w, ListTreeItem *item) +{ int width; - if (item->highlighted || item == w->list.highlighted) { + if (item->highlighted || item == w->list.highlighted) + { width = w->core.width - item->x - w->list.XOffset; XFillRectangle(XtDisplay(w), XtWindow(w), w->list.drawGC, item->x + w->list.XOffset, item->ytext, width, @@ -1241,18 +1441,22 @@ static void DrawItemHighlight(ListTreeWidget w, ListTreeItem *item) { item->x + w->list.XOffset, item->ytext + FontAscent(w->list.font), item->text, item->length); - } else { + } + else + { XDrawString( XtDisplay(w), XtWindow(w), w->list.drawGC, item->x + w->list.XOffset, item->ytext + FontAscent(w->list.font), item->text, item->length); } } -static void DrawItemHighlightClear(ListTreeWidget w, ListTreeItem *item) { +static void DrawItemHighlightClear(ListTreeWidget w, ListTreeItem *item) +{ int width; width = w->core.width - item->x - w->list.XOffset; - if (item->highlighted || item == w->list.highlighted) { + if (item->highlighted || item == w->list.highlighted) + { XFillRectangle(XtDisplay(w), XtWindow(w), w->list.drawGC, item->x + w->list.XOffset, item->ytext, width, FontHeight(w->list.font)); @@ -1260,7 +1464,9 @@ static void DrawItemHighlightClear(ListTreeWidget w, ListTreeItem *item) { item->x + w->list.XOffset, item->ytext + FontAscent(w->list.font), item->text, item->length); - } else { + } + else + { XFillRectangle(XtDisplay(w), XtWindow(w), w->list.highlightGC, item->x + w->list.XOffset, item->ytext, width, FontHeight(w->list.font)); @@ -1271,11 +1477,13 @@ static void DrawItemHighlightClear(ListTreeWidget w, ListTreeItem *item) { } static void DrawItem(ListTreeWidget w, ListTreeItem *item, int y, int *xroot, - int *yroot, int *retwidth, int *retheight) { + int *yroot, int *retwidth, int *retheight) +{ int height, xpix, ypix, xbranch, ybranch, xtext, ytext, yline; Pixinfo *pix; - if (item->count < w->list.topItemPos) { + if (item->count < w->list.topItemPos) + { *xroot = item->x - (int)w->list.HSpacing - w->list.pixWidth / 2; *yroot = 0; *retwidth = *retheight = 0; @@ -1289,18 +1497,24 @@ static void DrawItem(ListTreeWidget w, ListTreeItem *item, int y, int *xroot, xtext = item->x; xpix = xtext - (int)w->list.HSpacing - w->list.pixWidth + pix->xoff; - if (pix) { - if (pix->height > height) { + if (pix) + { + if (pix->height > height) + { ytext = y + ((pix->height - height) / 2); height = pix->height; ypix = y; - } else { + } + else + { ytext = y; ypix = y + ((height - pix->height) / 2); } ybranch = ypix + pix->height; yline = ypix + (pix->height / 2); - } else { + } + else + { ypix = ytext = y; yline = ybranch = ypix + (height / 2); yline = ypix + (height / 2); @@ -1319,7 +1533,8 @@ static void DrawItem(ListTreeWidget w, ListTreeItem *item, int y, int *xroot, XDrawLine(XtDisplay(w), XtWindow(w), w->list.drawGC, *xroot + w->list.XOffset, *yroot, *xroot + w->list.XOffset, yline); - if (y >= w->list.exposeTop && y <= w->list.exposeBot) { + if (y >= w->list.exposeTop && y <= w->list.exposeBot) + { if (*xroot >= 0) XDrawLine(XtDisplay(w), XtWindow(w), w->list.drawGC, *xroot + w->list.XOffset, yline, xbranch + w->list.XOffset, @@ -1336,11 +1551,13 @@ static void DrawItem(ListTreeWidget w, ListTreeItem *item, int y, int *xroot, } static int DrawChildren(ListTreeWidget w, ListTreeItem *item, - ListTreeItem **last, int y, int xroot, int yroot) { + ListTreeItem **last, int y, int xroot, int yroot) +{ int width, height; int xbranch, ybranch; - while (item && y < w->list.exposeBot) { + while (item && y < w->list.exposeBot) + { xbranch = xroot; ybranch = yroot; DrawItem(w, item, y, &xbranch, &ybranch, &width, &height); @@ -1368,14 +1585,17 @@ static int DrawChildren(ListTreeWidget w, ListTreeItem *item, * Draws vertical lines connecting items to their siblings below the last * visible item */ -static void DrawVertical(ListTreeWidget w, ListTreeItem *item) { +static void DrawVertical(ListTreeWidget w, ListTreeItem *item) +{ int xroot; int yroot; - while (item->parent) { + while (item->parent) + { /* If this parent has another child, that means that a line extends off * the screen to the bottom. */ - if (item->nextsibling) { + if (item->nextsibling) + { xroot = item->parent->x - (int)w->list.HSpacing - w->list.pixWidth / 2; if (item->parent->count < w->list.topItemPos) yroot = 0; @@ -1386,7 +1606,9 @@ static void DrawVertical(ListTreeWidget w, ListTreeItem *item) { XDrawLine(XtDisplay(w), XtWindow(w), w->list.drawGC, xroot + w->list.XOffset, yroot, xroot + w->list.XOffset, w->list.exposeBot); - } else { + } + else + { DBG("parent=%s NOT DRAWING\n", item->parent->text); } @@ -1395,7 +1617,8 @@ static void DrawVertical(ListTreeWidget w, ListTreeItem *item) { } /* Draws items starting from topItemPos */ -static void Draw(ListTreeWidget w, int yevent, int hevent) { +static void Draw(ListTreeWidget w, int yevent, int hevent) +{ int y, xbranch, ybranch; ListTreeItem *item, *lastdrawn; @@ -1433,7 +1656,8 @@ static void Draw(ListTreeWidget w, int yevent, int hevent) { w->list.lastXOffset = w->list.XOffset; } -static void DrawAll(ListTreeWidget w) { +static void DrawAll(ListTreeWidget w) +{ XClearArea(XtDisplay((Widget)w), XtWindow((Widget)w), w->list.viewX, w->list.viewY, w->list.viewWidth, w->list.viewHeight, False); if (w->list.recount) @@ -1441,14 +1665,17 @@ static void DrawAll(ListTreeWidget w) { Draw(w, w->list.viewY, w->list.viewY + w->list.viewHeight); } -static void DrawChanged(ListTreeWidget w) { +static void DrawChanged(ListTreeWidget w) +{ DrawAll(w); SetScrollbars(w); } /* Counting functions ------------------------------------------------------- */ -static int GotoPositionChildren(ListTreeWidget w, ListTreeItem *item, int i) { - while (item && i < w->list.topItemPos) { +static int GotoPositionChildren(ListTreeWidget w, ListTreeItem *item, int i) +{ + while (item && i < w->list.topItemPos) + { i++; w->list.topItem = item; @@ -1460,12 +1687,14 @@ static int GotoPositionChildren(ListTreeWidget w, ListTreeItem *item, int i) { return i; } -static void GotoPosition(ListTreeWidget w) { +static void GotoPosition(ListTreeWidget w) +{ w->list.topItem = w->list.first; GotoPositionChildren(w, w->list.topItem, -1); } -static int CountItem(ListTreeWidget w, ListTreeItem *item, int x, int y) { +static int CountItem(ListTreeWidget w, ListTreeItem *item, int x, int y) +{ int height; int xtext; Pixinfo *pix; @@ -1479,7 +1708,8 @@ static int CountItem(ListTreeWidget w, ListTreeItem *item, int x, int y) { /* Compute the height of this line */ height = FontHeight(w->list.font); xtext = x + (int)w->list.HSpacing; - if (pix && pix->height > height) { + if (pix && pix->height > height) + { height = pix->height; } @@ -1494,11 +1724,13 @@ static int CountItem(ListTreeWidget w, ListTreeItem *item, int x, int y) { return height; } -static int CountChildren(ListTreeWidget w, ListTreeItem *item, int x, int y) { +static int CountChildren(ListTreeWidget w, ListTreeItem *item, int x, int y) +{ int height; x += (int)w->list.Indent + w->list.pixWidth; - while (item) { + while (item) + { height = CountItem(w, item, x, y); y += height + (int)w->list.VSpacing; @@ -1510,7 +1742,8 @@ static int CountChildren(ListTreeWidget w, ListTreeItem *item, int x, int y) { return y; } -static void CountAll(ListTreeWidget w) { +static void CountAll(ListTreeWidget w) +{ int x, y; w->list.itemCount = 0; @@ -1537,13 +1770,15 @@ ListTreeItem *item; /* If there exists a previous sibling, just skip over item to be dereferenced */ - if (item->prevsibling) { + if (item->prevsibling) + { item->prevsibling->nextsibling = item->nextsibling; if (item->nextsibling) item->nextsibling->prevsibling = item->prevsibling; } /* If not, then the deleted item is the first item in some branch. */ - else { + else + { if (item->parent) item->parent->firstchild = item->nextsibling; else @@ -1564,14 +1799,17 @@ ListTreeItem *item; ListTreeItem *sibling; ListTreeItemReturnStruct ret; - while (item) { - if (item->firstchild) { + while (item) + { + if (item->firstchild) + { DeleteChildren(w, item->firstchild); item->firstchild = NULL; } sibling = item->nextsibling; - if (w->list.DestroyItemCallback) { + if (w->list.DestroyItemCallback) + { ret.reason = XtDESTROY; ret.item = item; ret.event = NULL; @@ -1592,27 +1830,37 @@ ListTreeItem *item; item->parent = parent; item->nextsibling = item->prevsibling = NULL; - if (parent) { - if (parent->firstchild) { + if (parent) + { + if (parent->firstchild) + { i = parent->firstchild; - while (i->nextsibling) { + while (i->nextsibling) + { i = i->nextsibling; } i->nextsibling = item; item->prevsibling = i; - } else { + } + else + { parent->firstchild = item; } - - } else { /* if parent==NULL, this is a top level entry */ - if (w->list.first) { + } + else + { /* if parent==NULL, this is a top level entry */ + if (w->list.first) + { i = w->list.first; - while (i->nextsibling) { + while (i->nextsibling) + { i = i->nextsibling; } i->nextsibling = item; item->prevsibling = i; - } else { + } + else + { w->list.first = w->list.topItem = item; } } @@ -1649,7 +1897,8 @@ ListTreeItem *item; /* Mark the parents of the new list to the new parent. The order of the */ /* rest of the new list should be OK, and the second item should still */ /* point to the first, even though the first was reparented. */ - while (item->nextsibling) { + while (item->nextsibling) + { item->parent = parent; item = item->nextsibling; } @@ -1662,15 +1911,19 @@ ListTreeItem *item; static int SearchChildren(ListTreeWidget w, ListTreeItem *item, ListTreeItem **last, int y, int findy, - ListTreeItem **finditem) { - while (item) { + ListTreeItem **finditem) +{ + while (item) + { DBG("searching y=%d item=%s\n", y, item->text); - if (findy >= y && findy <= y + item->height + w->list.VSpacing) { + if (findy >= y && findy <= y + item->height + w->list.VSpacing) + { *finditem = item; return -1; } y += item->height + (int)w->list.VSpacing; - if ((item->firstchild) && (item->open)) { + if ((item->firstchild) && (item->open)) + { y = SearchChildren(w, item->firstchild, NULL, y, findy, finditem); if (*finditem) return -1; @@ -1693,7 +1946,8 @@ int findy; item = w->list.topItem; finditem = NULL; lastdrawn = item; - while (!finditem && lastdrawn && y < w->core.height) { + while (!finditem && lastdrawn && y < w->core.height) + { y = SearchChildren(w, item, &lastdrawn, y, findy, &finditem); /* @@ -1701,12 +1955,14 @@ int findy; * siblings ran out, start checking up through the parents for more * items. */ - if (lastdrawn->parent && y < w->core.height) { + if (lastdrawn->parent && y < w->core.height) + { ListTreeItem *parent; /* continue with the item after the parent of the previous group */ parent = lastdrawn; - do { + do + { parent = parent->parent; if (parent) item = parent->nextsibling; @@ -1715,7 +1971,8 @@ int findy; } while (parent && !item); if (!item) lastdrawn = NULL; - } else + } + else lastdrawn = NULL; } TreeCheck(w, "exiting GetItem"); @@ -1730,9 +1987,11 @@ Boolean *found; int height; Pixinfo *pix; - while (item) { + while (item) + { /* DBG("Checking y=%d item=%s\n",y,item->text); */ - if (item == finditem) { + if (item == finditem) + { *found = True; return y; } @@ -1745,7 +2004,8 @@ Boolean *found; height = pix->height; y += height + (int)w->list.VSpacing; - if ((item->firstchild) && (item->open)) { + if ((item->firstchild) && (item->open)) + { y = SearchPosition(w, item->firstchild, y, finditem, found); if (*found) return y; @@ -1767,7 +2027,8 @@ ListTreeItem *finditem; y = (int)w->list.viewY + (int)w->list.Margin; item = w->list.first; found = False; - while (item && item != finditem) { + while (item && item != finditem) + { pix = GetItemPix(w, item); @@ -1777,7 +2038,8 @@ ListTreeItem *finditem; height = pix->height; y += height + (int)w->list.VSpacing; - if ((item->firstchild) && (item->open)) { + if ((item->firstchild) && (item->open)) + { y = SearchPosition(w, item->firstchild, y, finditem, &found); if (found) return (Position)y; @@ -1792,20 +2054,23 @@ ListTreeItem *finditem; /* Public Functions --------------------------------------------------------- */ -void ListTreeRefresh(ListTreeWidget w) { +void ListTreeRefresh(ListTreeWidget w) +{ if (XtIsRealized((Widget)w) && w->list.Refresh) DrawChanged(w); } void ListTreeRefreshOff(ListTreeWidget w) { w->list.Refresh = False; } -void ListTreeRefreshOn(ListTreeWidget w) { +void ListTreeRefreshOn(ListTreeWidget w) +{ w->list.Refresh = True; ListTreeRefresh(w); } static ListTreeItem *AddItem(ListTreeWidget w, ListTreeItem *parent, - char *string, ListTreeItemType type) { + char *string, ListTreeItemType type) +{ ListTreeItem *item; int len; char *copy; @@ -1831,32 +2096,38 @@ static ListTreeItem *AddItem(ListTreeWidget w, ListTreeItem *parent, } ListTreeItem *ListTreeAdd(ListTreeWidget w, ListTreeItem *parent, - char *string) { + char *string) +{ return (AddItem(w, parent, string, ItemDetermineType)); } ListTreeItem *ListTreeAddType(ListTreeWidget w, ListTreeItem *parent, - char *string, ListTreeItemType type) { + char *string, ListTreeItemType type) +{ return (AddItem(w, parent, string, type)); } ListTreeItem *ListTreeAddBranch(ListTreeWidget w, ListTreeItem *parent, - char *string) { + char *string) +{ return (AddItem(w, parent, string, ItemBranchType)); } ListTreeItem *ListTreeAddLeaf(ListTreeWidget w, ListTreeItem *parent, - char *string) { + char *string) +{ return (AddItem(w, parent, string, ItemLeafType)); } void ListTreeSetItemPixmaps(ListTreeWidget w, ListTreeItem *item, - Pixmap openPixmap, Pixmap closedPixmap) { + Pixmap openPixmap, Pixmap closedPixmap) +{ item->openPixmap = openPixmap; item->closedPixmap = closedPixmap; } -void ListTreeRenameItem(ListTreeWidget w, ListTreeItem *item, char *string) { +void ListTreeRenameItem(ListTreeWidget w, ListTreeItem *item, char *string) +{ int len; char *copy; @@ -1871,7 +2142,8 @@ void ListTreeRenameItem(ListTreeWidget w, ListTreeItem *item, char *string) { ListTreeRefresh(w); } -int ListTreeDelete(ListTreeWidget w, ListTreeItem *item) { +int ListTreeDelete(ListTreeWidget w, ListTreeItem *item) +{ if (item->firstchild) DeleteChildren(w, item->firstchild); item->firstchild = NULL; @@ -1886,7 +2158,8 @@ int ListTreeDelete(ListTreeWidget w, ListTreeItem *item) { return 1; } -int ListTreeDeleteChildren(ListTreeWidget w, ListTreeItem *item) { +int ListTreeDeleteChildren(ListTreeWidget w, ListTreeItem *item) +{ if (item->firstchild) DeleteChildren(w, item->firstchild); item->firstchild = NULL; @@ -1897,7 +2170,8 @@ int ListTreeDeleteChildren(ListTreeWidget w, ListTreeItem *item) { } int ListTreeReparent(ListTreeWidget w, ListTreeItem *item, - ListTreeItem *newparent) { + ListTreeItem *newparent) +{ TreeCheck(w, "in ListTreeReparent"); /* Remove the item from its old location. */ RemoveReference(w, item); @@ -1911,11 +2185,13 @@ int ListTreeReparent(ListTreeWidget w, ListTreeItem *item, } int ListTreeReparentChildren(ListTreeWidget w, ListTreeItem *item, - ListTreeItem *newparent) { + ListTreeItem *newparent) +{ ListTreeItem *first; TreeCheck(w, "in ListTreeReparentChildren"); - if (item->firstchild) { + if (item->firstchild) + { first = item->firstchild; item->firstchild = NULL; @@ -1927,13 +2203,15 @@ int ListTreeReparentChildren(ListTreeWidget w, ListTreeItem *item, return 0; } -int AlphabetizeItems(const void *item1, const void *item2) { +int AlphabetizeItems(const void *item1, const void *item2) +{ return strcmp((*((ListTreeItem **)item1))->text, (*((ListTreeItem **)item2))->text); } int ListTreeUserOrderSiblings(ListTreeWidget w, ListTreeItem *item, - int (*func)()) { + int (*func)()) +{ ListTreeItem *first, *parent, **list; size_t i, count, size; @@ -1955,7 +2233,8 @@ int ListTreeUserOrderSiblings(ListTreeWidget w, ListTreeItem *item, list = (ListTreeItem **)XtMalloc(size * count); list[0] = first; count = 1; - while (first->nextsibling) { + while (first->nextsibling) + { list[count] = first->nextsibling; count++; first = first->nextsibling; @@ -1964,7 +2243,8 @@ int ListTreeUserOrderSiblings(ListTreeWidget w, ListTreeItem *item, qsort(list, count, size, func); list[0]->prevsibling = NULL; - for (i = 0; i < count; i++) { + for (i = 0; i < count; i++) + { if (i < count - 1) list[i]->nextsibling = list[i + 1]; if (i > 0) @@ -1983,21 +2263,26 @@ int ListTreeUserOrderSiblings(ListTreeWidget w, ListTreeItem *item, return 1; } -int ListTreeOrderSiblings(ListTreeWidget w, ListTreeItem *item) { +int ListTreeOrderSiblings(ListTreeWidget w, ListTreeItem *item) +{ TreeCheck(w, "in ListTreeOrderSiblings"); return ListTreeUserOrderSiblings(w, item, AlphabetizeItems); } int ListTreeUserOrderChildren(ListTreeWidget w, ListTreeItem *item, - int (*func)()) { + int (*func)()) +{ ListTreeItem *first; TreeCheck(w, "in ListTreeUserOrderChildren"); - if (item) { + if (item) + { first = item->firstchild; if (first) ListTreeUserOrderSiblings(w, first, func); - } else { + } + else + { if (w->list.first) ListTreeUserOrderSiblings(w, w->list.first, func); } @@ -2005,15 +2290,19 @@ int ListTreeUserOrderChildren(ListTreeWidget w, ListTreeItem *item, return 1; } -int ListTreeOrderChildren(ListTreeWidget w, ListTreeItem *item) { +int ListTreeOrderChildren(ListTreeWidget w, ListTreeItem *item) +{ ListTreeItem *first; TreeCheck(w, "in ListTreeOrderChildren"); - if (item) { + if (item) + { first = item->firstchild; if (first) ListTreeOrderSiblings(w, first); - } else { + } + else + { if (w->list.first) ListTreeOrderSiblings(w, w->list.first); } @@ -2022,14 +2311,17 @@ int ListTreeOrderChildren(ListTreeWidget w, ListTreeItem *item) { } ListTreeItem *ListTreeFindSiblingName(ListTreeWidget w, ListTreeItem *item, - char *name) { + char *name) +{ TreeCheck(w, "in ListTreeFindSiblingName"); /* Get first child in list; */ - if (item) { + if (item) + { while (item->prevsibling) item = item->prevsibling; - while (item) { + while (item) + { if (strcmp(item->text, name) == 0) return item; item = item->nextsibling; @@ -2040,17 +2332,23 @@ ListTreeItem *ListTreeFindSiblingName(ListTreeWidget w, ListTreeItem *item, } ListTreeItem *ListTreeFindChildName(ListTreeWidget w, ListTreeItem *item, - char *name) { + char *name) +{ TreeCheck(w, "in ListTreeFindChildName"); /* Get first child in list; */ - if (item && item->firstchild) { + if (item && item->firstchild) + { item = item->firstchild; - } else if (!item && w->list.first) { + } + else if (!item && w->list.first) + { item = w->list.first; - } else + } + else item = NULL; - while (item) { + while (item) + { if (strcmp(item->text, name) == 0) return item; item = item->nextsibling; @@ -2058,40 +2356,50 @@ ListTreeItem *ListTreeFindChildName(ListTreeWidget w, ListTreeItem *item, return NULL; } -void ListTreeHighlightItem(ListTreeWidget w, ListTreeItem *item) { +void ListTreeHighlightItem(ListTreeWidget w, ListTreeItem *item) +{ HighlightAll(w, False, False); HighlightItem(w, item, True, False); ListTreeRefresh(w); } -void ListTreeHighlightAll(ListTreeWidget w) { +void ListTreeHighlightAll(ListTreeWidget w) +{ HighlightAllVisible(w, True, False); ListTreeRefresh(w); } -void ListTreeClearHighlighted(ListTreeWidget w) { +void ListTreeClearHighlighted(ListTreeWidget w) +{ HighlightAll(w, False, False); ListTreeRefresh(w); } -void ListTreeGetHighlighted(ListTreeWidget w, ListTreeMultiReturnStruct *ret) { +void ListTreeGetHighlighted(ListTreeWidget w, ListTreeMultiReturnStruct *ret) +{ if (ret) MakeMultiCallbackStruct(w, ret); } void ListTreeSetHighlighted(ListTreeWidget w, ListTreeItem **items, int count, - Boolean clear) { + Boolean clear) +{ if (clear) HighlightAll(w, False, False); - if (count < 0) { - while (*items) { + if (count < 0) + { + while (*items) + { HighlightItem(w, *items, True, False); items++; } - } else { + } + else + { int i; - for (i = 0; i < count; i++) { + for (i = 0; i < count; i++) + { HighlightItem(w, items[i], True, False); } } @@ -2107,11 +2415,13 @@ ListTreeItem *ListTreeFirstItem(w) ListTreeWidget w; return first; } -Position ListTreeGetItemPosition(ListTreeWidget w, ListTreeItem *item) { +Position ListTreeGetItemPosition(ListTreeWidget w, ListTreeItem *item) +{ return GetPosition(w, item); } -void ListTreeGetPathname(ListTreeReturnStruct *ret, char *dir) { +void ListTreeGetPathname(ListTreeReturnStruct *ret, char *dir) +{ int count; if (*ret->path[0]->text != '/') @@ -2120,22 +2430,26 @@ void ListTreeGetPathname(ListTreeReturnStruct *ret, char *dir) { strcpy(dir, ""); strcat(dir, ret->path[0]->text); count = 1; - while (count < ret->count) { + while (count < ret->count) + { strcat(dir, "/"); strcat(dir, ret->path[count]->text); count++; } } -void ListTreeGetPathnameFromItem(ListTreeItem *item, char *dir) { +void ListTreeGetPathnameFromItem(ListTreeItem *item, char *dir) +{ // build path from right to left char mem[1024]; char *tmp = mem + sizeof(mem) - 1; tmp[0] = '\0'; // prepend items - while (item) { + while (item) + { const ssize_t len = item->text ? strlen(item->text) : 0; - if (len == 0 || len >= tmp - mem) { // abort + if (len == 0 || len >= tmp - mem) + { // abort dir = ""; return; } @@ -2149,7 +2463,8 @@ void ListTreeGetPathnameFromItem(ListTreeItem *item, char *dir) { } Widget XmCreateScrolledListTree(Widget parent, char *name, Arg *args, - Cardinal count) { + Cardinal count) +{ Widget sw; char *sname; Cardinal i; @@ -2160,7 +2475,8 @@ Widget XmCreateScrolledListTree(Widget parent, char *name, Arg *args, strcat(sname, "SW"); al = (Arg *)XtCalloc(count + 4, sizeof(Arg)); - for (i = 0; i < count; i++) { + for (i = 0; i < count; i++) + { al[i].name = args[i].name; al[i].value = args[i].value; } diff --git a/xmdsshr/UilDBDef.h b/xmdsshr/UilDBDef.h index ffe7ab4760..6bad696de7 100644 --- a/xmdsshr/UilDBDef.h +++ b/xmdsshr/UilDBDef.h @@ -58,8 +58,8 @@ #define _BIT_MASK(_type) (1 << (((unsigned int)(_type)) & 0x7)) -#define _BIT_SET(table_entry_addr, _type) \ - (_BIT_MASK(_type) & \ +#define _BIT_SET(table_entry_addr, _type) \ + (_BIT_MASK(_type) & \ (((unsigned char *)(table_entry_addr))[_BIT_INDEX(_type)])) /******************************************************************* @@ -294,20 +294,21 @@ #define sym_k_or_op 14 #define sym_k_cat_op 15 #define sym_k_last_binary_op 15 -#define sym_k_valref_op \ - 16 /* az_exp_op1 points to the value node \ - whose value is referenced by this \ +#define sym_k_valref_op \ + 16 /* az_exp_op1 points to the value node \ + whose value is referenced by this \ value node. */ -#define sym_k_coerce_op \ - 17 /* az_exp_op1 points to the value node \ - whose value is to be coerced to the \ +#define sym_k_coerce_op \ + 17 /* az_exp_op1 points to the value node \ + whose value is to be coerced to the \ data type of this node. */ #define sym_k_last_special_op 17 /* * Structure of an enumeration set entry */ -typedef struct { +typedef struct +{ short int values_cnt; /* number of values in the enuemration set descriptor */ unsigned short int *values; @@ -337,7 +338,8 @@ typedef struct { /* * Keyword table entry structure */ -typedef struct { +typedef struct +{ unsigned char b_class; unsigned short int b_subclass; unsigned char b_length; @@ -389,7 +391,8 @@ typedef struct { */ #define DB_Compiled_Version 2 -typedef struct _db_globals_struct { +typedef struct _db_globals_struct +{ int version; int uil_max_arg; int uil_max_charset; @@ -403,7 +406,8 @@ typedef struct _db_globals_struct { int uil_max_child; } _db_globals; -typedef struct _db_header_struct { +typedef struct _db_header_struct +{ int table_id; int num_items; int table_size; diff --git a/xmdsshr/UilSymCSet.h b/xmdsshr/UilSymCSet.h index 68a1939cd7..ae19776809 100644 --- a/xmdsshr/UilSymCSet.h +++ b/xmdsshr/UilSymCSet.h @@ -191,36 +191,66 @@ externaldef(uil_sym_glbl) char **charset_lang_names_table = * The sym_k_..._charset codes for charset_lang_names */ static unsigned short int charset_lang_codes_table_vec[] = { - sym_k_gb_hanzi_charset, sym_k_gb_hanzi_charset, - sym_k_gb_hanzi_charset, sym_k_gb_hanzi_charset, - sym_k_gb_hanzi_gr_charset, sym_k_gb_hanzi_gr_charset, - sym_k_iso_arabic_charset, sym_k_iso_arabic_charset, - sym_k_iso_arabic_charset, sym_k_iso_arabic_charset, - sym_k_iso_arabic_charset, sym_k_iso_cyrillic_charset, - sym_k_iso_cyrillic_charset, sym_k_iso_greek_charset, - sym_k_iso_greek_charset, sym_k_iso_greek_charset, - sym_k_iso_greek_charset, sym_k_iso_greek_charset, - sym_k_iso_hebrew_charset, sym_k_iso_hebrew_charset, - sym_k_iso_hebrew_charset, sym_k_iso_hebrew_charset, - sym_k_iso_hebrew_charset, sym_k_iso_hebrew_lr_charset, - sym_k_iso_hebrew_lr_charset, sym_k_iso_hebrew_lr_charset, - sym_k_iso_latin1_charset, sym_k_iso_latin1_charset, - sym_k_iso_latin1_charset, sym_k_iso_latin1_charset, - sym_k_iso_latin1_charset, sym_k_iso_latin2_charset, - sym_k_iso_latin2_charset, sym_k_iso_latin2_charset, - sym_k_iso_latin2_charset, sym_k_iso_latin3_charset, - sym_k_iso_latin3_charset, sym_k_iso_latin3_charset, - sym_k_iso_latin3_charset, sym_k_iso_latin4_charset, - sym_k_iso_latin4_charset, sym_k_iso_latin4_charset, - sym_k_iso_latin4_charset, sym_k_iso_latin5_charset, - sym_k_iso_latin5_charset, sym_k_iso_latin5_charset, - sym_k_iso_latin5_charset, sym_k_jis_kanji_charset, - sym_k_jis_kanji_charset, sym_k_jis_kanji_charset, - sym_k_jis_kanji_charset, sym_k_jis_kanji_gr_charset, - sym_k_jis_kanji_gr_charset, sym_k_jis_katakana_charset, - sym_k_jis_katakana_charset, sym_k_ksc_hangul_charset, - sym_k_ksc_hangul_charset, sym_k_ksc_hangul_charset, - sym_k_ksc_hangul_charset, sym_k_ksc_hangul_gr_charset, + sym_k_gb_hanzi_charset, + sym_k_gb_hanzi_charset, + sym_k_gb_hanzi_charset, + sym_k_gb_hanzi_charset, + sym_k_gb_hanzi_gr_charset, + sym_k_gb_hanzi_gr_charset, + sym_k_iso_arabic_charset, + sym_k_iso_arabic_charset, + sym_k_iso_arabic_charset, + sym_k_iso_arabic_charset, + sym_k_iso_arabic_charset, + sym_k_iso_cyrillic_charset, + sym_k_iso_cyrillic_charset, + sym_k_iso_greek_charset, + sym_k_iso_greek_charset, + sym_k_iso_greek_charset, + sym_k_iso_greek_charset, + sym_k_iso_greek_charset, + sym_k_iso_hebrew_charset, + sym_k_iso_hebrew_charset, + sym_k_iso_hebrew_charset, + sym_k_iso_hebrew_charset, + sym_k_iso_hebrew_charset, + sym_k_iso_hebrew_lr_charset, + sym_k_iso_hebrew_lr_charset, + sym_k_iso_hebrew_lr_charset, + sym_k_iso_latin1_charset, + sym_k_iso_latin1_charset, + sym_k_iso_latin1_charset, + sym_k_iso_latin1_charset, + sym_k_iso_latin1_charset, + sym_k_iso_latin2_charset, + sym_k_iso_latin2_charset, + sym_k_iso_latin2_charset, + sym_k_iso_latin2_charset, + sym_k_iso_latin3_charset, + sym_k_iso_latin3_charset, + sym_k_iso_latin3_charset, + sym_k_iso_latin3_charset, + sym_k_iso_latin4_charset, + sym_k_iso_latin4_charset, + sym_k_iso_latin4_charset, + sym_k_iso_latin4_charset, + sym_k_iso_latin5_charset, + sym_k_iso_latin5_charset, + sym_k_iso_latin5_charset, + sym_k_iso_latin5_charset, + sym_k_jis_kanji_charset, + sym_k_jis_kanji_charset, + sym_k_jis_kanji_charset, + sym_k_jis_kanji_charset, + sym_k_jis_kanji_gr_charset, + sym_k_jis_kanji_gr_charset, + sym_k_jis_katakana_charset, + sym_k_jis_katakana_charset, + sym_k_ksc_hangul_charset, + sym_k_ksc_hangul_charset, + sym_k_ksc_hangul_charset, + sym_k_ksc_hangul_charset, + sym_k_ksc_hangul_gr_charset, sym_k_ksc_hangul_gr_charset, }; diff --git a/xmdsshr/UilSymEnum.h b/xmdsshr/UilSymEnum.h index 59ae19e92e..18e7cc678b 100644 --- a/xmdsshr/UilSymEnum.h +++ b/xmdsshr/UilSymEnum.h @@ -20,7 +20,13 @@ static unsigned short int enum_value_vec2[] = { }; static unsigned short int enum_value_vec3[] = { - 38, 37, 39, 43, 40, 41, 42, + 38, + 37, + 39, + 43, + 40, + 41, + 42, }; static unsigned short int enum_value_vec4[] = { @@ -41,7 +47,11 @@ static unsigned short int enum_value_vec6[] = { }; static unsigned short int enum_value_vec7[] = { - 23, 25, 22, 29, 30, + 23, + 25, + 22, + 29, + 30, }; static unsigned short int enum_value_vec8[] = { @@ -50,7 +60,13 @@ static unsigned short int enum_value_vec8[] = { }; static unsigned short int enum_value_vec9[] = { - 54, 56, 60, 63, 65, 70, 71, + 54, + 56, + 60, + 63, + 65, + 70, + 71, }; static unsigned short int enum_value_vec10[] = { @@ -60,11 +76,27 @@ static unsigned short int enum_value_vec10[] = { }; static unsigned short int enum_value_vec11[] = { - 72, 66, 64, 76, 59, 53, + 72, + 66, + 64, + 76, + 59, + 53, }; static unsigned short int enum_value_vec12[] = { - 67, 69, 76, 58, 57, 61, 62, 68, 74, 75, 73, 55, + 67, + 69, + 76, + 58, + 57, + 61, + 62, + 68, + 74, + 75, + 73, + 55, }; static unsigned short int enum_value_vec13[] = { @@ -142,7 +174,11 @@ static unsigned short int enum_value_vec25[] = { }; static unsigned short int enum_value_vec26[] = { - 145, 93, 96, 95, 94, + 145, + 93, + 96, + 95, + 94, }; static unsigned short int enum_value_vec27[] = { @@ -173,7 +209,15 @@ static unsigned short int enum_value_vec30[] = { }; static unsigned short int enum_value_vec31[] = { - 127, 78, 126, 77, 102, 120, 122, 121, 123, + 127, + 78, + 126, + 77, + 102, + 120, + 122, + 121, + 123, }; static unsigned short int enum_value_vec32[] = { @@ -194,7 +238,11 @@ static unsigned short int enum_value_vec34[] = { }; static unsigned short int enum_value_vec35[] = { - 110, 20, 18, 21, 19, + 110, + 20, + 18, + 21, + 19, }; static unsigned short int enum_value_vec36[] = { @@ -203,7 +251,11 @@ static unsigned short int enum_value_vec36[] = { }; static unsigned short int enum_value_vec37[] = { - 23, 25, 22, 27, 26, + 23, + 25, + 22, + 27, + 26, }; static unsigned short int enum_value_vec38[] = { @@ -223,7 +275,16 @@ static unsigned short int enum_value_vec40[] = { }; static unsigned short int enum_value_vec41[] = { - 156, 152, 153, 157, 148, 151, 149, 150, 154, 155, + 156, + 152, + 153, + 157, + 148, + 151, + 149, + 150, + 154, + 155, }; static unsigned short int enum_value_vec42[] = { @@ -233,7 +294,19 @@ static unsigned short int enum_value_vec42[] = { }; static unsigned short int enum_value_vec43[] = { - 6, 13, 5, 9, 10, 11, 12, 15, 16, 17, 7, 14, 8, + 6, + 13, + 5, + 9, + 10, + 11, + 12, + 15, + 16, + 17, + 7, + 14, + 8, }; /* @@ -293,24 +366,366 @@ externaldef(uil_sym_glbl) * is the sym_k_..._enumset code for the argument's enumeration set. */ static unsigned short int argument_enumset_table_vec[] = { - 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, - 6, 7, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 0, 0, 10, 0, 11, - 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 1, 0, 0, 37, 0, 0, 0, 0, - 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 16, 0, 0, 0, - 0, 0, 0, 0, 17, 0, 0, 0, 0, 18, 3, 0, 0, 0, 0, 0, 0, 0, 0, 19, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, - 0, 0, 21, 0, 0, 0, 0, 22, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 3, 0, 0, 0, 26, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 30, 0, 0, 31, 0, 0, 32, 35, 0, 0, 0, 0, 0, 0, - 0, 0, 33, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 35, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 41, 0, - 0, 42, 0, 0, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 5, + 6, + 7, + 0, + 0, + 0, + 0, + 0, + 8, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + 0, + 0, + 10, + 0, + 11, + 0, + 12, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 13, + 0, + 1, + 0, + 0, + 37, + 0, + 0, + 0, + 0, + 14, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 15, + 0, + 0, + 0, + 16, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 0, + 0, + 0, + 0, + 18, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 19, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 20, + 0, + 0, + 0, + 0, + 0, + 21, + 0, + 0, + 0, + 0, + 22, + 0, + 23, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 25, + 0, + 3, + 0, + 0, + 0, + 26, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 27, + 28, + 0, + 0, + 0, + 0, + 0, + 0, + 29, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 30, + 0, + 0, + 31, + 0, + 0, + 32, + 35, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 33, + 0, + 0, + 34, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 35, + 36, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 38, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 39, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 40, + 41, + 0, + 0, + 42, + 0, + 0, + 0, + 0, + 0, + 43, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, }; externaldef(uil_sym_glbl) unsigned short int *argument_enumset_table = diff --git a/xmdsshr/UilSymRArg.h b/xmdsshr/UilSymRArg.h index 314853559f..5152b93a29 100644 --- a/xmdsshr/UilSymRArg.h +++ b/xmdsshr/UilSymRArg.h @@ -6,24 +6,366 @@ */ static unsigned short int related_argument_table_vec[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 134, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 196, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 241, 244, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 62, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 76, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 122, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 134, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 196, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 241, + 244, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, }; externaldef(uil_sym_glbl) unsigned short int *related_argument_table = diff --git a/xmdsshr/XmdsBells.c b/xmdsshr/XmdsBells.c index 43c938578f..2491ccd85b 100644 --- a/xmdsshr/XmdsBells.c +++ b/xmdsshr/XmdsBells.c @@ -59,7 +59,8 @@ int XmdsBells(int *number_of_bells ) #include #include -EXPORT int XmdsBells(int *num_bells) { +EXPORT int XmdsBells(int *num_bells) +{ static Display *display = 0; int i; if (!display) diff --git a/xmdsshr/XmdsComplain.c b/xmdsshr/XmdsComplain.c index f11f799626..f2158177ea 100644 --- a/xmdsshr/XmdsComplain.c +++ b/xmdsshr/XmdsComplain.c @@ -64,7 +64,8 @@ char *string; _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif - EXPORT void XmdsComplain(Widget parent, char *string, ...) { + EXPORT void XmdsComplain(Widget parent, char *string, ...) +{ /*------------------------------------------------------------------------------ @@ -95,7 +96,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") for (new_parent = parent; new_parent && !XtIsWidget(new_parent); new_parent = XtParent(new_parent)) ; - if (new_parent) { + if (new_parent) + { static XtCallbackRec ok_callback_list[] = { {(XtCallbackProc)XtDestroyWidget, 0}, {0, 0}}; Arg args[] = {{XmNmessageString, (long)0}, @@ -116,7 +118,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") XmStringFree((XmString)args[0].value); XmStringFree((XmString)args[1].value); XmStringFree((XmString)args[2].value); - } else + } + else printf("Error displaying dialog box\nCould not find widget to 'parent' " "box\nError message was:\n\t%s\n", string); diff --git a/xmdsshr/XmdsDeviceSetup.c b/xmdsshr/XmdsDeviceSetup.c index 64c2d99067..e7bca1dd39 100644 --- a/xmdsshr/XmdsDeviceSetup.c +++ b/xmdsshr/XmdsDeviceSetup.c @@ -76,7 +76,8 @@ void XmdsSetDeviceNid(int nid); EXPORT int XmdsDeviceSetup(Widget parent, int *nid, String uids[], Cardinal num_uids, String ident, MrmRegisterArglist reglist, MrmCount regnum, - Widget *widget_return) { + Widget *widget_return) +{ static int device_nid; static NCI_ITM nci[] = { {sizeof(int), NciCONGLOMERATE_NIDS, (unsigned char *)&device_nid, 0}, @@ -88,7 +89,8 @@ EXPORT int XmdsDeviceSetup(Widget parent, int *nid, String uids[], TreeGetNci(*nid, nci); XmdsSetDeviceNid(device_nid); status = MrmOpenHierarchy(num_uids, uids, 0, &drm_hierarchy); - if (status == MrmSUCCESS) { + if (status == MrmSUCCESS) + { if (regnum) MrmRegisterNamesInHierarchy(drm_hierarchy, reglist, regnum); status = MrmFetchWidget(drm_hierarchy, ident, parent, &w, &class); diff --git a/xmdsshr/XmdsDigChans.c b/xmdsshr/XmdsDigChans.c index 3d6313cf9e..49dd27775c 100644 --- a/xmdsshr/XmdsDigChans.c +++ b/xmdsshr/XmdsDigChans.c @@ -102,7 +102,8 @@ XmdsDigChansApply(Widget w) Boolean XmdsIsDigChans(Widget w) void XmdsDigChansReset(Widget w); -typedef struct _DigChansPart { +typedef struct _DigChansPart +{ int channels; int nid; int nid_offset; @@ -137,7 +138,8 @@ static XtResource resources[] = { Executable: */ EXPORT Widget XmdsCreateDigChans(Widget parent, String name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ XmdsDigChansPart info = {4, -1, 0, 0, 1, 2, 3, 1}; static String hierarchy_name[] = {"XmdsDigChans.uid"}; MrmHierarchy drm_hierarchy; @@ -159,7 +161,8 @@ EXPORT Widget XmdsCreateDigChans(Widget parent, String name, ArgList args, XtVaSetValues(XtNameToWidget(channels_w, "this_is_a_DigChans_widget"), XmNuserData, (char *)0 + info.put_on_apply, NULL); rowcol_w = XtNameToWidget(channels_w, "*c_rowcol"); - for (i = 0; i < info.channels; i++) { + for (i = 0; i < info.channels; i++) + { char name_c[12]; XmString name; XmString path; @@ -206,13 +209,15 @@ EXPORT Widget XmdsCreateDigChans(Widget parent, String name, ArgList args, return channels_w; } -EXPORT void XmdsDigChansReset(Widget w) { +EXPORT void XmdsDigChansReset(Widget w) +{ Widget rowcol_w = XtNameToWidget(w, "*c_rowcol"); int i; int num; Widget *chan_w; XtVaGetValues(rowcol_w, XmNnumChildren, &num, XmNchildren, &chan_w, NULL); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { XtPointer userdata; int nid; XtVaGetValues(chan_w[i], XmNuserData, &userdata, NULL); @@ -223,15 +228,18 @@ EXPORT void XmdsDigChansReset(Widget w) { XmdsResetAllXds(rowcol_w); } -EXPORT int XmdsDigChansPut(Widget w) { +EXPORT int XmdsDigChansPut(Widget w) +{ Widget rowcol_w = XtNameToWidget(w, "*c_rowcol"); int i; int num; int status; Widget *chan_w; XtVaGetValues(rowcol_w, XmNnumChildren, &num, XmNchildren, &chan_w, NULL); - if ((status = XmdsXdsAreValid(w))) { - for (i = 0; i < num; i++) { + if ((status = XmdsXdsAreValid(w))) + { + for (i = 0; i < num; i++) + { XtPointer user_data; int nid; int num_ctls; @@ -243,7 +251,8 @@ EXPORT int XmdsDigChansPut(Widget w) { TreeTurnOn(nid); else TreeTurnOff(nid); - if (num_ctls > 3) { + if (num_ctls > 3) + { XmdsExprPut(children[2]); XmdsExprPut(children[3]); } @@ -252,13 +261,15 @@ EXPORT int XmdsDigChansPut(Widget w) { return status; } -EXPORT int XmdsDigChansApply(Widget w) { +EXPORT int XmdsDigChansApply(Widget w) +{ XtPointer PutOnApply; XtVaGetValues(XtNameToWidget(w, "this_is_a_DigChans_widget"), XmNuserData, &PutOnApply, NULL); return PutOnApply ? XmdsDigChansPut(w) : 1; } -EXPORT Boolean XmdsIsDigChans(Widget w) { +EXPORT Boolean XmdsIsDigChans(Widget w) +{ return XtNameToWidget(w, "this_is_a_DigChans_widget") != 0; } diff --git a/xmdsshr/XmdsDisplay.c b/xmdsshr/XmdsDisplay.c index 647514c0f8..bd05874f68 100644 --- a/xmdsshr/XmdsDisplay.c +++ b/xmdsshr/XmdsDisplay.c @@ -96,7 +96,8 @@ extern int TdiDecompile(); Local variables: */ -typedef struct _DisplayPart { +typedef struct _DisplayPart +{ int nid; int nid_offset; } XmdsDisplayPart; @@ -112,7 +113,8 @@ static XtResource resources[] = { Executable: */ EXPORT Widget XmdsCreateDisplay(Widget parent, String name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ XmdsDisplayPart info = {-1, 0}; Widget w; Arg lab_args[] = {{XmNlabelString, 0}, {XmNuserData, DisplayUserData}}; @@ -126,23 +128,28 @@ EXPORT Widget XmdsCreateDisplay(Widget parent, String name, ArgList args, nid = info.nid + info.nid_offset; else nid = -1; - if (nid != -1) { + if (nid != -1) + { static struct descriptor_d display_dsc = {0, DTYPE_T, CLASS_D, 0}; static struct descriptor_xd xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; struct descriptor nid_dsc = {sizeof(int), DTYPE_NID, CLASS_S, (char *)0}; int status; nid_dsc.pointer = (char *)&nid; status = TdiEvaluate(&nid_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (status & 1) + { status = TdiDecompile(&xd, &display_dsc MDS_END_ARG); - if (status & 1) { + if (status & 1) + { static DESCRIPTOR(zero_dsc, "\0"); StrConcat((struct descriptor *)&display_dsc, (struct descriptor *)&display_dsc, &zero_dsc MDS_END_ARG); lab_args[0].value = (long)XmStringCreateSimple(display_dsc.pointer); - } else + } + else lab_args[0].value = (long)XmStringCreateSimple("Error - Decomp"); - } else + } + else lab_args[0].value = (long)XmStringCreateSimple("Error - Eval"); } merged_args = XtMergeArgLists(args, argcount, lab_args, XtNumber(lab_args)); @@ -152,7 +159,8 @@ EXPORT Widget XmdsCreateDisplay(Widget parent, String name, ArgList args, return w; } -EXPORT Boolean XmdsIsDisplay(Widget w) { +EXPORT Boolean XmdsIsDisplay(Widget w) +{ XtPointer user_data = 0; XtVaGetValues(w, XmNuserData, &user_data, NULL); if (user_data && (user_data == (XtPointer)DisplayUserData)) diff --git a/xmdsshr/XmdsExpr.c b/xmdsshr/XmdsExpr.c index 8de5ef8a11..1dd789b189 100644 --- a/xmdsshr/XmdsExpr.c +++ b/xmdsshr/XmdsExpr.c @@ -198,8 +198,8 @@ static void Resize(Widget w); Macros: */ -#define IsText(ptr) \ - ((ptr->dtype == DTYPE_T) && \ +#define IsText(ptr) \ + ((ptr->dtype == DTYPE_T) && \ ((ptr->class == CLASS_S) || (ptr->class == CLASS_D))) /*------------------------------------------------------------------------------ @@ -319,7 +319,8 @@ WidgetClass xmdsExprFieldWidgetClass; the initial widget. ****************************************************/ EXPORT Widget XmdsCreateExpr(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ Widget widg; widg = XtCreateWidget(name, (WidgetClass)&xmdsExprClassRec, parent, args, argcount); @@ -327,7 +328,8 @@ EXPORT Widget XmdsCreateExpr(Widget parent, char *name, ArgList args, } EXPORT Widget XmdsCreateExprField(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ Widget widg; xmdsExprClassRec.core_class.initialize = InitializeExprField; widg = XtCreateWidget(name, (WidgetClass)&xmdsExprClassRec, parent, args, @@ -336,17 +338,19 @@ EXPORT Widget XmdsCreateExprField(Widget parent, char *name, ArgList args, return widg; } -#define GetString(w) \ +#define GetString(w) \ (XmIsTextField(w) ? XmTextFieldGetString(w) : XmTextGetString(w)) -#define SetString(w, string) \ - (XmIsTextField(w) ? XmTextFieldSetString(w, string) \ +#define SetString(w, string) \ + (XmIsTextField(w) ? XmTextFieldSetString(w, string) \ : XmTextSetString(w, string)) -EXPORT struct descriptor *XmdsExprFieldGetXd(Widget w) { +EXPORT struct descriptor *XmdsExprFieldGetXd(Widget w) +{ return XmdsExprGetXd(w); } -EXPORT struct descriptor *XmdsExprGetXd(Widget w) { +EXPORT struct descriptor *XmdsExprGetXd(Widget w) +{ struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); XmdsExprWidget ew = (XmdsExprWidget)w; @@ -358,16 +362,19 @@ EXPORT struct descriptor *XmdsExprGetXd(Widget w) { *ans = empty_xd; if (ew->expr.is_text) MdsCopyDxXd((struct descriptor *)&text_dsc, ans); - else { + else + { int status; int old_def; int def_nid = GetDefaultNid(ew); - if (def_nid != -1) { + if (def_nid != -1) + { TreeGetDefaultNid(&old_def); TreeSetDefaultNid(def_nid); } status = (*ew->expr.compile)(&text_dsc, ans MDS_END_ARG); - if ((status & 1) == 0) { + if ((status & 1) == 0) + { TdiComplain(w); XtFree((char *)ans); ans = 0; @@ -380,21 +387,25 @@ EXPORT struct descriptor *XmdsExprGetXd(Widget w) { EXPORT Boolean XmdsExprFieldPut(Widget w) { return XmdsExprPut(w); } -EXPORT Boolean XmdsExprPut(Widget w) { +EXPORT Boolean XmdsExprPut(Widget w) +{ int status = 1; XmdsExprWidget ew = (XmdsExprWidget)w; int nid = ew->expr.nid + ew->expr.nid_offset; - if (nid) { + if (nid) + { struct descriptor_xd *new_xd = (struct descriptor_xd *)XmdsExprGetXd((Widget)ew); - if (new_xd) { + if (new_xd) + { struct descriptor_xd *old_xd; old_xd = (struct descriptor_xd *)TdiGet(nid); if ((!old_xd && new_xd->l_length) || !MdsCompareXd((struct descriptor *)new_xd, (struct descriptor *)old_xd)) status = TreePutRecord(nid, (struct descriptor *)new_xd, 0); - if (old_xd) { + if (old_xd) + { MdsFree1Dx(old_xd, 0); XtFree((char *)old_xd); } @@ -407,18 +418,22 @@ EXPORT Boolean XmdsExprPut(Widget w) { EXPORT Boolean XmdsExprFieldApply(Widget w) { return XmdsExprApply(w); } -EXPORT Boolean XmdsExprApply(Widget w) { +EXPORT Boolean XmdsExprApply(Widget w) +{ XmdsExprWidget ew = (XmdsExprWidget)w; return ew->expr.put_on_apply ? XmdsExprPut(w) : 1; } -EXPORT void XmdsExprFieldSetDefaultNid(Widget w, int nid) { +EXPORT void XmdsExprFieldSetDefaultNid(Widget w, int nid) +{ XmdsExprSetDefaultNid(w, nid); } -EXPORT void XmdsExprSetDefaultNid(Widget w, int nid) { +EXPORT void XmdsExprSetDefaultNid(Widget w, int nid) +{ XmdsExprWidget ew = (XmdsExprWidget)w; - if (nid != ew->expr.default_nid) { + if (nid != ew->expr.default_nid) + { ew->expr.default_nid = nid; LoadExpr(ew, (struct descriptor *)ew->expr.xd); Resize((Widget)ew); @@ -427,34 +442,40 @@ EXPORT void XmdsExprSetDefaultNid(Widget w, int nid) { EXPORT void XmdsExprFieldRegister() { XmdsExprRegister(); } -EXPORT void XmdsExprRegister() { +EXPORT void XmdsExprRegister() +{ MrmRegisterClass(1, "XmdsExprWidget", "XmdsCreateExpr", (Widget(*)(void))XmdsCreateExpr, xmdsExprWidgetClass); } EXPORT void XmdsExprFieldReset(Widget w) { XmdsExprReset(w); } -EXPORT void XmdsExprReset(Widget w) { +EXPORT void XmdsExprReset(Widget w) +{ XmdsExprWidget ew = (XmdsExprWidget)w; if (ew->expr.nid) XmdsExprSetNid(w, ew->expr.nid, ew->expr.nid_offset); - else { + else + { LoadExpr(ew, (struct descriptor *)ew->expr.xd); Resize((Widget)ew); } } -EXPORT void XmdsExprFieldSetNid(Widget w, int nid, int offset) { +EXPORT void XmdsExprFieldSetNid(Widget w, int nid, int offset) +{ XmdsExprSetNid(w, nid, offset); } -EXPORT void XmdsExprSetNid(Widget w, int nid, int offset) { +EXPORT void XmdsExprSetNid(Widget w, int nid, int offset) +{ XmdsExprWidget ew = (XmdsExprWidget)w; int new_nid; int status; if (ew->expr.xd) MdsFree1Dx(ew->expr.xd, 0); - else { + else + { ew->expr.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ew->expr.xd = empty_xd; @@ -472,15 +493,18 @@ EXPORT void XmdsExprSetNid(Widget w, int nid, int offset) { ew->expr.nid_offset = offset; } -EXPORT void XmdsExprFieldSetXd(Widget w, struct descriptor *dsc) { +EXPORT void XmdsExprFieldSetXd(Widget w, struct descriptor *dsc) +{ XmdsExprSetXd(w, dsc); } -EXPORT void XmdsExprSetXd(Widget w, struct descriptor *dsc) { +EXPORT void XmdsExprSetXd(Widget w, struct descriptor *dsc) +{ XmdsExprWidget ew = (XmdsExprWidget)w; if (ew->expr.xd) MdsFree1Dx(ew->expr.xd, 0); - else { + else + { ew->expr.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ew->expr.xd = empty_xd; @@ -491,22 +515,26 @@ EXPORT void XmdsExprSetXd(Widget w, struct descriptor *dsc) { } static XtGeometryResult GeometryManager(Widget w, XtWidgetGeometry *desired, - XtWidgetGeometry *allowed) { + XtWidgetGeometry *allowed) +{ return XtGeometryYes; } static void InitializeExpr(Widget req, Widget new, ArgList args, - Cardinal *num_args) { + Cardinal *num_args) +{ Initialize(req, new, args, num_args, 0); } static void InitializeExprField(Widget req, Widget new, ArgList args, - Cardinal *num_args) { + Cardinal *num_args) +{ Initialize(req, new, args, num_args, 1); } static void Initialize(Widget req, Widget new, ArgList args, Cardinal *num_args, - Boolean is_field) { + Boolean is_field) +{ XmdsExprWidget w = (XmdsExprWidget) new; static XtCallbackRec change_quotes_callback_list[] = { {(XtCallbackProc)ChangeQuotes, (XtPointer)0}, {0, 0}}; @@ -516,7 +544,8 @@ static void Initialize(Widget req, Widget new, ArgList args, Cardinal *num_args, int nid; change_quotes_callback_list[0].closure = (XtPointer)w; w->manager.navigation_type = XmTAB_GROUP; - if (w->expr.auto_quote) { + if (w->expr.auto_quote) + { static Arg quote_args[] = { {XmNlabelString, 0}, {XmNx, 0}, @@ -529,7 +558,9 @@ static void Initialize(Widget req, Widget new, ArgList args, Cardinal *num_args, w->expr.close_quote_widget = XmCreatePushButton( (Widget)w, "close_quote", quote_args, XtNumber(quote_args)); XmStringFree((XmString)quote_args[0].value); - } else { + } + else + { w->expr.open_quote_widget = 0; w->expr.close_quote_widget = 0; } @@ -545,7 +576,8 @@ static void Initialize(Widget req, Widget new, ArgList args, Cardinal *num_args, nid = w->expr.nid + w->expr.nid_offset; if (nid) w->expr.xd = (struct descriptor_xd *)TdiGet(nid); - else if (w->expr.xd) { + else if (w->expr.xd) + { XmdsExprWidget req_e_w = (XmdsExprWidget)req; w->expr.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *w->expr.xd = empty_xd; @@ -559,12 +591,14 @@ static void Initialize(Widget req, Widget new, ArgList args, Cardinal *num_args, Resize((Widget)w); } -static void Resize(Widget w) { +static void Resize(Widget w) +{ XmdsExprWidget ew = (XmdsExprWidget)w; Widget tw = XmIsTextField(ew->expr.text_widget) ? ew->expr.text_widget : XtParent(ew->expr.text_widget); - if (ew->expr.is_text) { + if (ew->expr.is_text) + { Dimension text_width = XtWidth(ew) - 2 * (1 + XtWidth(ew->expr.open_quote_widget)); XtResizeWidget(tw, text_width, XtHeight(ew), 0); @@ -573,10 +607,13 @@ static void Resize(Widget w) { XtWidth(ew) - XtWidth(ew->expr.close_quote_widget), 0); XtManageChild(ew->expr.open_quote_widget); XtManageChild(ew->expr.close_quote_widget); - } else { + } + else + { XtMoveWidget(tw, 0, 0); XtResizeWidget(tw, XtWidth(ew), XtHeight(ew), 0); - if (ew->expr.open_quote_widget) { + if (ew->expr.open_quote_widget) + { XtUnmanageChild(ew->expr.open_quote_widget); XtUnmanageChild(ew->expr.close_quote_widget); XtMoveWidget(ew->expr.close_quote_widget, @@ -586,7 +623,8 @@ static void Resize(Widget w) { } static Boolean SetValues(Widget old, Widget req, Widget new, ArgList args, - Cardinal *arg_count) { + Cardinal *arg_count) +{ XmdsExprWidget old_ew = (XmdsExprWidget)old; XmdsExprWidget req_ew = (XmdsExprWidget)req; XmdsExprWidget new_ew = (XmdsExprWidget) new; @@ -594,24 +632,32 @@ static Boolean SetValues(Widget old, Widget req, Widget new, ArgList args, if ((old_ew->expr.nid != req_ew->expr.nid) || (old_ew->expr.nid_offset != req_ew->expr.nid_offset)) XmdsExprSetNid((Widget)new_ew, new_ew->expr.nid, new_ew->expr.nid_offset); - else if (old_ew->expr.default_nid != req_ew->expr.default_nid) { + else if (old_ew->expr.default_nid != req_ew->expr.default_nid) + { new_ew->expr.default_nid = 0; XmdsExprSetDefaultNid((Widget)new_ew, req_ew->expr.default_nid); - } else if (old_ew->expr.xd != req_ew->expr.xd) { - if (old_ew->expr.xd) { + } + else if (old_ew->expr.xd != req_ew->expr.xd) + { + if (old_ew->expr.xd) + { MdsFree1Dx(old_ew->expr.xd, 0); XtFree((char *)old_ew->expr.xd); }; new_ew->expr.xd = 0; XmdsExprSetXd((Widget)new_ew, (struct descriptor *)req_ew->expr.xd); } - if (req_ew->expr.auto_quote != old_ew->expr.auto_quote) { - if (req_ew->expr.auto_quote == 0) { + if (req_ew->expr.auto_quote != old_ew->expr.auto_quote) + { + if (req_ew->expr.auto_quote == 0) + { XtDestroyWidget(new_ew->expr.open_quote_widget); XtDestroyWidget(new_ew->expr.close_quote_widget); new_ew->expr.open_quote_widget = 0; new_ew->expr.close_quote_widget = 0; - } else { + } + else + { static XtCallbackRec change_quotes_callback_list[] = { {(XtCallbackProc)ChangeQuotes, (XtPointer)0}, {0, 0}}; static Arg quote_args[] = { @@ -637,7 +683,8 @@ static Boolean SetValues(Widget old, Widget req, Widget new, ArgList args, return 0; } -static void ChangeQuotes(Widget q_w, XmdsExprWidget e_w) { +static void ChangeQuotes(Widget q_w, XmdsExprWidget e_w) +{ char *text = GetString(e_w->expr.text_widget); int text_len = strlen(text); char *new_text = XtMalloc(text_len + 3); @@ -652,11 +699,14 @@ static void ChangeQuotes(Widget q_w, XmdsExprWidget e_w) { Resize((Widget)e_w); } -static int GetDefaultNid(XmdsExprWidget ew) { +static int GetDefaultNid(XmdsExprWidget ew) +{ int ans = ew->expr.default_nid; - if (ans == -1) { + if (ans == -1) + { int nid = ew->expr.nid + ew->expr.nid_offset; - if (nid) { + if (nid) + { if (ConglomerateElt(nid)) ans = NodeParent(ConglomerateHead(nid)); else @@ -667,13 +717,15 @@ static int GetDefaultNid(XmdsExprWidget ew) { } static void Focus_In(Widget w, XEvent *event, String *params, - Cardinal num_params) { + Cardinal num_params) +{ XmdsExprWidget ew = (XmdsExprWidget)w; XtCallActionProc(ew->expr.text_widget, "grab-focus", event, params, num_params); } -static void LoadExpr(XmdsExprWidget w, struct descriptor *dsc) { +static void LoadExpr(XmdsExprWidget w, struct descriptor *dsc) +{ struct descriptor_xd *xd = (struct descriptor_xd *)dsc; int status; for (; xd && xd->dtype == DTYPE_DSC; xd = (struct descriptor_xd *)xd->pointer) @@ -681,50 +733,62 @@ static void LoadExpr(XmdsExprWidget w, struct descriptor *dsc) { if (xd && ((xd->class == CLASS_R) || (((xd->class == CLASS_XD) || (xd->class == CLASS_XS)) ? xd->l_length - : xd->length))) { - if (w->expr.auto_quote && IsText(xd)) { + : xd->length))) + { + if (w->expr.auto_quote && IsText(xd)) + { char *c_text = DescToNull((struct descriptor_s *)xd); w->expr.is_text = 1; SetString(w->expr.text_widget, c_text); XmTextSetInsertionPosition(w->expr.text_widget, (XmTextPosition)0); XtFree(c_text); - } else { + } + else + { static struct descriptor_d text = {0, DTYPE_T, CLASS_D, 0}; int old_def; int def_nid = GetDefaultNid(w); - if (def_nid != -1) { + if (def_nid != -1) + { TreeGetDefaultNid(&old_def); TreeSetDefaultNid(def_nid); } status = (*w->expr.decompile)(xd, &text MDS_END_ARG); w->expr.is_text = 0; - if (status & 1) { + if (status & 1) + { char *c_text = DescToNull((struct descriptor_s *)&text); SetString(w->expr.text_widget, c_text); XmTextSetInsertionPosition(w->expr.text_widget, (XmTextPosition)0); XtFree(c_text); - } else + } + else SetString(w->expr.text_widget, ""); StrFree1Dx(&text); if (def_nid != -1) TreeSetDefaultNid(old_def); } - } else { + } + else + { SetString(w->expr.text_widget, ""); w->expr.is_text = w->expr.auto_quote && w->expr.default_quote; } } -static void SetEnclosures(XmdsExprWidget w, struct descriptor *dsc) { +static void SetEnclosures(XmdsExprWidget w, struct descriptor *dsc) +{ struct descriptor *ptr; for (ptr = dsc; ptr && (ptr->dtype == DTYPE_DSC); ptr = (struct descriptor *)ptr->pointer) ; w->expr.is_text = (ptr && IsText(ptr)) || ((ptr == 0) && w->expr.default_quote); - if (w->expr.is_text) { + if (w->expr.is_text) + { char *chrs = GetString(w->expr.text_widget); - if (chrs && strlen(chrs)) { + if (chrs && strlen(chrs)) + { chrs[strlen(chrs) - 1] = 0; SetString(w->expr.text_widget, &chrs[1]); XtFree(chrs); @@ -732,7 +796,8 @@ static void SetEnclosures(XmdsExprWidget w, struct descriptor *dsc) { } } -char *DescToNull(struct descriptor_s *text) { +char *DescToNull(struct descriptor_s *text) +{ char *answer = memcpy(XtMalloc(text->length + 1), text->pointer, text->length); answer[text->length] = '\0'; diff --git a/xmdsshr/XmdsGetPutNid.c b/xmdsshr/XmdsGetPutNid.c index 8fda2e6b44..923d98fb63 100644 --- a/xmdsshr/XmdsGetPutNid.c +++ b/xmdsshr/XmdsGetPutNid.c @@ -147,17 +147,21 @@ extern int TdiGetFloat(); Executable: */ -int XmdsGetNidLongValue(int nid, int minVal, int maxVal, int defaultVal) { +int XmdsGetNidLongValue(int nid, int minVal, int maxVal, int defaultVal) +{ int value; return (GetLong(nid, &value) & 1) ? max(minVal, min(maxVal, value)) : defaultVal; } -int XmdsGetNidFloatOption(int nid, float *options, int numOptions) { +int XmdsGetNidFloatOption(int nid, float *options, int numOptions) +{ static struct descriptor_xd xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; int option = numOptions; - if (TreeGetRecord(nid, &xd) & 1) { - if (xd.pointer->dtype == DTYPE_F) { + if (TreeGetRecord(nid, &xd) & 1) + { + if (xd.pointer->dtype == DTYPE_F) + { float f = *((float *)xd.pointer->pointer); int i; for (i = 0; i < numOptions; i++) @@ -170,11 +174,14 @@ int XmdsGetNidFloatOption(int nid, float *options, int numOptions) { return option; } -int XmdsGetNidIntOption(int nid, int *options, int numOptions) { +int XmdsGetNidIntOption(int nid, int *options, int numOptions) +{ static struct descriptor_xd xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; int option = numOptions; - if (TreeGetRecord(nid, &xd) & 1) { - if (xd.pointer->dtype == DTYPE_L) { + if (TreeGetRecord(nid, &xd) & 1) + { + if (xd.pointer->dtype == DTYPE_L) + { int f = *((int *)xd.pointer->pointer); int i; for (i = 0; i < numOptions; i++) @@ -187,51 +194,63 @@ int XmdsGetNidIntOption(int nid, int *options, int numOptions) { return option; } -char *XmdsGetNidText(int nid) { +char *XmdsGetNidText(int nid) +{ static struct descriptor_xd xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; char *value; - if (TreeGetRecord(nid, &xd) & 1) { - if (xd.pointer->dtype == DTYPE_T) { + if (TreeGetRecord(nid, &xd) & 1) + { + if (xd.pointer->dtype == DTYPE_T) + { value = XtMalloc(xd.pointer->length + 1); strncpy(value, xd.pointer->pointer, xd.pointer->length); value[xd.pointer->length] = 0; - } else + } + else value = XtNewString(""); - } else + } + else value = XtNewString(""); MdsFree1Dx(&xd, 0); return value; } int XmdsPutNidValue(int nid, unsigned short length, unsigned char dtype, - char *pointer, char *originalValue) { - if (memcmp(pointer, originalValue, length)) { + char *pointer, char *originalValue) +{ + if (memcmp(pointer, originalValue, length)) + { struct descriptor dsc = {0, 0, CLASS_S, (char *)0}; dsc.length = length; dsc.dtype = dtype; dsc.pointer = pointer; return TreePutRecord(nid, &dsc, 0); - } else + } + else return 1; } -int XmdsPutNidToggleButton(Widget w, int nid, int originalValue) { +int XmdsPutNidToggleButton(Widget w, int nid, int originalValue) +{ int value = XmToggleButtonGetState(w); return XmdsPutNidValue(nid, 4, DTYPE_L, (char *)&value, (char *)&originalValue); } -int XmdsPutNidScale(Widget w, int nid, int originalValue) { +int XmdsPutNidScale(Widget w, int nid, int originalValue) +{ int value; XmScaleGetValue(w, &value); return XmdsPutNidValue(nid, 4, DTYPE_L, (char *)&value, (char *)&originalValue); } -int XmdsPutNidSText(Widget w, int nid, char *originalValue) { +int XmdsPutNidSText(Widget w, int nid, char *originalValue) +{ char *value = XmTextGetString(w); int status = 1; - if (strcmp(value, originalValue)) { + if (strcmp(value, originalValue)) + { struct descriptor dsc = {0, DTYPE_T, CLASS_S, (char *)0}; dsc.length = strlen(value); dsc.pointer = value; @@ -240,7 +259,8 @@ int XmdsPutNidSText(Widget w, int nid, char *originalValue) { return status; } -static int GetLong(int nid, int *intptr) { +static int GetLong(int nid, int *intptr) +{ struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, (char *)0}; int status; float x; @@ -250,44 +270,61 @@ static int GetLong(int nid, int *intptr) { return status; } -int XmdsSetState(int nid, Widget w) { +int XmdsSetState(int nid, Widget w) +{ return (XmToggleButtonGetState(w)) ? TreeTurnOn(nid) : TreeTurnOff(nid); } -int XmdsGetNidBooleanValue(int nid, int defaultVal) { +int XmdsGetNidBooleanValue(int nid, int defaultVal) +{ int val; return (GetLong(nid, &val) & 1) ? val & 1 : defaultVal; } -int XmdsIsOn(int nid) { +int XmdsIsOn(int nid) +{ int status; return (((status = TreeIsOn(nid)) == TreeON) || (status == TreePARENT_OFF)); } -Boolean XmdsXdsAreValid(Widget w) { +Boolean XmdsXdsAreValid(Widget w) +{ int status = True; - if (XmdsIsExpr(w)) { + if (XmdsIsExpr(w)) + { struct descriptor_xd *xd = (struct descriptor_xd *)XmdsExprGetXd(w); - if (xd) { + if (xd) + { MdsFree1Dx(xd, 0); XtFree((char *)xd); - } else + } + else status = False; - } else if (XmdsIsExprField(w)) { + } + else if (XmdsIsExprField(w)) + { struct descriptor_xd *xd = (struct descriptor_xd *)XmdsExprFieldGetXd(w); - if (xd) { + if (xd) + { MdsFree1Dx(xd, 0); XtFree((char *)xd); - } else + } + else status = False; - } else if (XmdsIsXdBox(w)) { + } + else if (XmdsIsXdBox(w)) + { struct descriptor_xd *xd = (struct descriptor_xd *)XmdsXdBoxGetXd(w); - if (xd) { + if (xd) + { MdsFree1Dx(xd, 0); XtFree((char *)xd); - } else + } + else status = False; - } else if (XtIsComposite(w)) { + } + else if (XtIsComposite(w)) + { Widget *children; int num; int i; @@ -295,7 +332,8 @@ Boolean XmdsXdsAreValid(Widget w) { for (i = 0; i < num && status; i++) status = XmdsXdsAreValid(children[i]); } - if (XtIsWidget(w) && w->core.num_popups) { + if (XtIsWidget(w) && w->core.num_popups) + { Widget *popups = w->core.popup_list; int num = w->core.num_popups; int i; @@ -305,7 +343,8 @@ Boolean XmdsXdsAreValid(Widget w) { return status; } -void XmdsResetAllXds(Widget w) { +void XmdsResetAllXds(Widget w) +{ if (XmdsIsExpr(w)) XmdsExprReset(w); else if (XmdsIsExprField(w)) @@ -320,7 +359,8 @@ void XmdsResetAllXds(Widget w) { XmdsNidOptionMenuReset(w); else if (XmdsIsXdBoxOnOffButton(w)) XmdsXdBoxOnOffButtonReset(w); - else if (XtIsComposite(w)) { + else if (XtIsComposite(w)) + { Widget *children; int num; int i; @@ -328,7 +368,8 @@ void XmdsResetAllXds(Widget w) { for (i = 0; i < num; i++) XmdsResetAllXds(children[i]); } - if (XtIsWidget(w) && w->core.num_popups) { + if (XtIsWidget(w) && w->core.num_popups) + { Widget *popups = w->core.popup_list; int num = w->core.num_popups; int i; @@ -337,7 +378,8 @@ void XmdsResetAllXds(Widget w) { } } -Boolean XmdsApplyAllXds(Widget w) { +Boolean XmdsApplyAllXds(Widget w) +{ int status = 1; if (XmdsIsExpr(w)) return XmdsExprApply(w); @@ -353,7 +395,8 @@ Boolean XmdsApplyAllXds(Widget w) { return XmdsNidOptionMenuApply(w); else if (XmdsIsXdBoxOnOffButton(w)) return XmdsXdBoxOnOffButtonApply(w); - else if (XtIsComposite(w)) { + else if (XtIsComposite(w)) + { Widget *children; int num; int i; @@ -361,7 +404,8 @@ Boolean XmdsApplyAllXds(Widget w) { for (i = 0; i < num && status; i++) status = XmdsApplyAllXds(children[i]); } - if (XtIsWidget(w) && w->core.num_popups) { + if (XtIsWidget(w) && w->core.num_popups) + { Widget *popups = w->core.popup_list; int num = w->core.num_popups; int i; diff --git a/xmdsshr/XmdsGetSetOptionIdx.c b/xmdsshr/XmdsGetSetOptionIdx.c index aac35d58a8..3ce6ba9575 100644 --- a/xmdsshr/XmdsGetSetOptionIdx.c +++ b/xmdsshr/XmdsGetSetOptionIdx.c @@ -84,10 +84,12 @@ int XmdsGetOptionIdx(Widget w); Executable: */ -EXPORT void XmdsSetOptionIdx(Widget w, Cardinal idx) { +EXPORT void XmdsSetOptionIdx(Widget w, Cardinal idx) +{ static Widget pulldown; XtVaGetValues(w, XmNsubMenuId, &pulldown, NULL); - if (pulldown) { + if (pulldown) + { Widget *options; Cardinal num_options; XtVaGetValues(pulldown, XmNchildren, &options, XmNnumChildren, &num_options, @@ -97,19 +99,22 @@ EXPORT void XmdsSetOptionIdx(Widget w, Cardinal idx) { } } -EXPORT int XmdsGetOptionIdx(Widget w) { +EXPORT int XmdsGetOptionIdx(Widget w) +{ int idx = -1; static Widget pulldown; static Widget option; XtVaGetValues(w, XmNsubMenuId, &pulldown, XmNmenuHistory, &option, NULL); - if (pulldown && option) { + if (pulldown && option) + { static Widget *options; static Cardinal num_options; Cardinal i; XtVaGetValues(pulldown, XmNchildren, &options, XmNnumChildren, &num_options, NULL); for (i = 0; i < num_options; i++) - if (options[i] == option) { + if (options[i] == option) + { idx = i; break; } diff --git a/xmdsshr/XmdsInitialize.c b/xmdsshr/XmdsInitialize.c index e6c146aeb9..02bfc72fff 100644 --- a/xmdsshr/XmdsInitialize.c +++ b/xmdsshr/XmdsInitialize.c @@ -121,7 +121,8 @@ int XmdsInitialize( ) _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif - EXPORT extern void XmdsInitialize() { + EXPORT extern void XmdsInitialize() +{ #ifndef _NO_XDS static MrmRegisterArg callbacks[] = { {"XmdsApplyCallback", (char *)XmdsApplyCallback}, diff --git a/xmdsshr/XmdsInput.c b/xmdsshr/XmdsInput.c index 2f175e587d..7e3c9d2f78 100644 --- a/xmdsshr/XmdsInput.c +++ b/xmdsshr/XmdsInput.c @@ -150,7 +150,8 @@ widget of the device. the nids of a particular channel. ****************************************************/ EXPORT Widget XmdsCreateInput(Widget parent, char *name, ArgList args, - int argcount) { + int argcount) +{ Widget widg; static char *hierarchy_name[] = {"XmdsInput.uid"}; MrmHierarchy hierarchy = 0; @@ -162,7 +163,8 @@ EXPORT Widget XmdsCreateInput(Widget parent, char *name, ArgList args, return widg; } -EXPORT void XmdsInputSetNid(Widget w, int nid) { +EXPORT void XmdsInputSetNid(Widget w, int nid) +{ WidgetList children; XtPointer user_data; XtVaGetValues(w, XtNchildren, &children, NULL); @@ -177,7 +179,8 @@ EXPORT void XmdsInputSetNid(Widget w, int nid) { XtVaSetValues(children[IDX_TIME], XmNuserData, user_data, NULL); } -EXPORT void XmdsInputReset(Widget w) { +EXPORT void XmdsInputReset(Widget w) +{ WidgetList children; XtPointer userdata; int nid; @@ -202,7 +205,8 @@ EXPORT void XmdsInputReset(Widget w) { XmStringFree(label); } -EXPORT void XmdsInputPut(Widget w) { +EXPORT void XmdsInputPut(Widget w) +{ WidgetList children; XtPointer userdata; int nid; diff --git a/xmdsshr/XmdsInputs.c b/xmdsshr/XmdsInputs.c index bf5fd6d8b2..e8b1ea12c3 100644 --- a/xmdsshr/XmdsInputs.c +++ b/xmdsshr/XmdsInputs.c @@ -91,7 +91,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. expression widget to the coresponding nid in the conglomerate. ***************************************************/ -void XmdsInputCreateCallback(Widget w, XmdsInputCtx ctx) { +void XmdsInputCreateCallback(Widget w, XmdsInputCtx ctx) +{ XmdsExprSetNid( w, ctx->inputs_nid + @@ -103,12 +104,14 @@ void XmdsInputCreateCallback(Widget w, XmdsInputCtx ctx) { XmdsResetInput - Routine to 'RESET' a channel of the digitizer. Called by the DW_SETUP Reset routine. **************************************************************/ -void XmdsResetInput(Widget chans_dlog, XmdsInputCtx ctx, int chan) { +void XmdsResetInput(Widget chans_dlog, XmdsInputCtx ctx, int chan) +{ char input_name[12]; Widget input_w; sprintf(input_name, "*input_%d", chan); input_w = XtNameToWidget(chans_dlog, input_name); - if (input_w) { + if (input_w) + { int input_nid = ctx->inputs_nid + (chan - 1) * ctx->nodes_per_input; char *path; XmString label; @@ -127,12 +130,14 @@ void XmdsResetInput(Widget chans_dlog, XmdsInputCtx ctx, int chan) { routines. Writes out the information specified by the user for a channel. ******************************************************************/ -EXPORT void XmdsPutInputSetup(Widget inputs_dlog, XmdsInputCtx ctx, int chan) { +EXPORT void XmdsPutInputSetup(Widget inputs_dlog, XmdsInputCtx ctx, int chan) +{ char input_name[12]; Widget input_w; sprintf(input_name, "*input_%d", chan); input_w = XtNameToWidget(inputs_dlog, input_name); - if (input_w) { + if (input_w) + { int nid = ctx->inputs_nid + (chan - 1) * ctx->nodes_per_input; XmdsExprPut(XtNameToWidget(input_w, "start_idx")); XmdsExprPut(XtNameToWidget(input_w, "end_idx")); @@ -143,16 +148,20 @@ EXPORT void XmdsPutInputSetup(Widget inputs_dlog, XmdsInputCtx ctx, int chan) { } } -EXPORT int XmdsWidgetToNumber(Widget w, String prefix) { +EXPORT int XmdsWidgetToNumber(Widget w, String prefix) +{ Widget widg; int number = -1; int length = strlen(prefix); char *endptr; - for (widg = w; widg; widg = XtParent(widg)) { + for (widg = w; widg; widg = XtParent(widg)) + { String name = XtName(widg); int namelen = strlen(name); - if (namelen > length) { - if (!strncmp(prefix, name, length)) { + if (namelen > length) + { + if (!strncmp(prefix, name, length)) + { number = strtol(name + length, &endptr, 10); if (endptr >= (name + namelen)) break; diff --git a/xmdsshr/XmdsNidOptionMenu.c b/xmdsshr/XmdsNidOptionMenu.c index 002116ae63..53dd5975e6 100644 --- a/xmdsshr/XmdsNidOptionMenu.c +++ b/xmdsshr/XmdsNidOptionMenu.c @@ -101,7 +101,8 @@ XmdsNidOptionMenuApply(Widget w); struct dsc$descriptor_xd #include #include -typedef struct _Resources { +typedef struct _Resources +{ int nid; int nid_offset; Boolean put_on_apply; @@ -135,7 +136,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif EXPORT Widget XmdsCreateNidOptionMenu(Widget parent, String name, - ArgList args, Cardinal argcount) { + ArgList args, Cardinal argcount) +{ Widget w; WidgetList children; int num; @@ -152,7 +154,8 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") XtAddCallback(info->pulldown, XmNentryCallback, (XtCallbackProc)MenuChanged, info); for (idx = 0, s = info->labels, v = info->values; s && *s && v && *v; - s++, v++, idx++) { + s++, v++, idx++) + { String expression = ""; expression = XmStringUnparse(*v, NULL, XmCHARSET_TEXT, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); @@ -208,14 +211,16 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") return w; } -static void Destroy(Widget w, Resources *info, XtPointer cb) { +static void Destroy(Widget w, Resources *info, XtPointer cb) +{ int num; Widget *labels; int i; XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &labels, NULL); num--; - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { struct descriptor_xd *xd; XtVaGetValues(labels[i], XmNuserData, &xd, NULL); MdsFree1Dx(xd, 0); @@ -226,22 +231,26 @@ static void Destroy(Widget w, Resources *info, XtPointer cb) { EXPORT Boolean XmdsIsNidOptionMenu(Widget w) { return GetResources(w) != 0; } -EXPORT int *XmdsNidOptionMenuGetButtons(Widget w, int *num) { +EXPORT int *XmdsNidOptionMenuGetButtons(Widget w, int *num) +{ Widget par; int *ans = 0; for (par = w; par && !XmdsIsNidOptionMenu(par); par = XtParent(par)) ; - if (par) { + if (par) + { Resources *info = GetResources(par); XtVaGetValues(info->pulldown, XmNchildren, &ans, XmNnumChildren, num, NULL); } return ans; } -static Resources *GetResources(Widget w) { +static Resources *GetResources(Widget w) +{ Resources *answer = 0; if (XmIsRowColumn(w) && - (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) { + (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) + { XtCallbackList callbacks; XtVaGetValues(w, XmNdestroyCallback, &callbacks, NULL); for (; callbacks->callback && @@ -255,11 +264,14 @@ static Resources *GetResources(Widget w) { return answer; } -EXPORT void XmdsNidOptionMenuReset(Widget w) { +EXPORT void XmdsNidOptionMenuReset(Widget w) +{ Resources *info = GetResources(w); - if (info) { + if (info) + { int nid = info->nid + info->nid_offset; - if (nid) { + if (nid) + { int idx; int num; Widget *labels; @@ -268,7 +280,8 @@ EXPORT void XmdsNidOptionMenuReset(Widget w) { NULL); num--; TreeGetRecord(nid, &xd); - for (idx = 0; idx < num; idx++) { + for (idx = 0; idx < num; idx++) + { struct descriptor_xd *button_xd; XtVaGetValues(labels[idx], XmNuserData, &button_xd, NULL); if ((xd.l_length || button_xd->l_length) @@ -285,16 +298,19 @@ EXPORT void XmdsNidOptionMenuReset(Widget w) { return; } -EXPORT struct descriptor_xd *XmdsNidOptionMenuIdxGetXd(Widget w, int selected) { +EXPORT struct descriptor_xd *XmdsNidOptionMenuIdxGetXd(Widget w, int selected) +{ struct descriptor_xd *xd = 0; Resources *info = GetResources(w); - if (info) { + if (info) + { int num; Widget *buttons; XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &buttons, NULL); num--; - if (selected < num) { + if (selected < num) + { static EMPTYXD(empty); struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); @@ -302,24 +318,28 @@ EXPORT struct descriptor_xd *XmdsNidOptionMenuIdxGetXd(Widget w, int selected) { *ans = empty; MdsCopyDxXd((struct descriptor *)xd, ans); xd = ans; - } else + } + else xd = (struct descriptor_xd *)XmdsXdBoxGetXd(XmdsXdBoxDialogButtonGetXdBox( XtNameToWidget(info->pulldown, "computed"))); } return xd; } -EXPORT struct descriptor_xd *XmdsNidOptionMenuGetXd(Widget w) { +EXPORT struct descriptor_xd *XmdsNidOptionMenuGetXd(Widget w) +{ struct descriptor_xd *xd = 0; Resources *info = GetResources(w); - if (info) { + if (info) + { int selected = XmdsGetOptionIdx(w); int num; Widget *buttons; XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &buttons, NULL); num--; - if (selected < num) { + if (selected < num) + { static EMPTYXD(empty); struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); @@ -327,17 +347,20 @@ EXPORT struct descriptor_xd *XmdsNidOptionMenuGetXd(Widget w) { *ans = empty; MdsCopyDxXd((struct descriptor *)xd, ans); xd = ans; - } else + } + else xd = (struct descriptor_xd *)XmdsXdBoxGetXd(XmdsXdBoxDialogButtonGetXdBox( XtNameToWidget(info->pulldown, "computed"))); } return xd; } -EXPORT int XmdsNidOptionMenuPut(Widget w) { +EXPORT int XmdsNidOptionMenuPut(Widget w) +{ Resources *info = GetResources(w); int status = 0; - if (info) { + if (info) + { int selected = XmdsGetOptionIdx(w); int num; Widget *buttons; @@ -345,8 +368,10 @@ EXPORT int XmdsNidOptionMenuPut(Widget w) { XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &buttons, NULL); num--; - if (nid) { - if (selected < num) { + if (nid) + { + if (selected < num) + { struct descriptor_xd *button_xd; EMPTYXD(xd); XtVaGetValues(buttons[selected], XmNuserData, &button_xd, NULL); @@ -359,7 +384,8 @@ EXPORT int XmdsNidOptionMenuPut(Widget w) { status = TreePutRecord(nid, (struct descriptor *)button_xd, 0); else status = 1; - } else + } + else status = XmdsXdBoxDialogButtonPut( XtNameToWidget(info->pulldown, "computed")); } @@ -367,10 +393,12 @@ EXPORT int XmdsNidOptionMenuPut(Widget w) { return status; } -EXPORT int XmdsNidOptionMenuApply(Widget w) { +EXPORT int XmdsNidOptionMenuApply(Widget w) +{ Resources *info = GetResources(w); int status = 0; - if (info) { + if (info) + { if (info->put_on_apply) status = XmdsNidOptionMenuPut(w); else @@ -380,8 +408,10 @@ EXPORT int XmdsNidOptionMenuApply(Widget w) { } static void MenuChanged(Widget w, Resources *info, - XmRowColumnCallbackStruct *cb) { - if (cb->reason == XmCR_ACTIVATE) { + XmRowColumnCallbackStruct *cb) +{ + if (cb->reason == XmCR_ACTIVATE) + { int num; int bnum = (char *)cb->data - (char *)0; Widget *buttons; @@ -390,7 +420,8 @@ static void MenuChanged(Widget w, Resources *info, NULL); num--; XtCallCallbacks(cb->widget, XmNactivateCallback, cb->data); - if (bnum < num) { + if (bnum < num) + { XtVaGetValues(buttons[bnum], XmNuserData, &xd, NULL); XmdsXdBoxSetXd(XmdsXdBoxDialogButtonGetXdBox(buttons[num]), (struct descriptor *)xd); @@ -400,14 +431,16 @@ static void MenuChanged(Widget w, Resources *info, static void ButtonPushed(Widget w, int index, XmPushButtonCallbackStruct *cb) {} -EXPORT void XmdsNidOptionMenuSetButton(Widget w, int idx, String text) { +EXPORT void XmdsNidOptionMenuSetButton(Widget w, int idx, String text) +{ Resources *info = GetResources(w); int num; Widget *buttons; XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &buttons, NULL); num--; - if (idx < num) { + if (idx < num) + { XmString label = XmStringCreateSimple(text); XtVaSetValues(buttons[idx], XmNlabelString, label, NULL); XmStringFree(label); diff --git a/xmdsshr/XmdsOkButtons.c b/xmdsshr/XmdsOkButtons.c index 3b8934bc05..a8529ed295 100644 --- a/xmdsshr/XmdsOkButtons.c +++ b/xmdsshr/XmdsOkButtons.c @@ -102,9 +102,11 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #endif EXPORT Widget XmdsCreateOkButton(Widget parent, String name, ArgList args, - Cardinal numargs) { + Cardinal numargs) +{ Widget w = CreateButton(parent, name, args, numargs, "Ok", 1); - if (XtHasCallbacks(w, XmNactivateCallback) == XtCallbackHasSome) { + if (XtHasCallbacks(w, XmNactivateCallback) == XtCallbackHasSome) + { int num_callbacks; XtCallbackList callbacks; XtVaGetValues(w, XmNactivateCallback, &callbacks, NULL); @@ -115,31 +117,36 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") XtRemoveAllCallbacks(w, XmNactivateCallback); XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)Ok, callbacks); XtAddCallback(w, XmNdestroyCallback, (XtCallbackProc)Destroy, callbacks); - } else + } + else XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)XmdsOkCallback, 0); return w; } -static int CountCallbacks(XtCallbackList callbacks) { +static int CountCallbacks(XtCallbackList callbacks) +{ int i; for (i = 0; callbacks->callback; callbacks = callbacks + 1, i++) ; return i; } -static void Ok(Widget w, XtCallbackList callbacks) { +static void Ok(Widget w, XtCallbackList callbacks) +{ if (Apply(w, callbacks)) XtDestroyWidget(FindShellChild(w)); } -static Widget FindShellChild(Widget w) { +static Widget FindShellChild(Widget w) +{ Widget sc; for (sc = w; sc && !XtIsShell(XtParent(sc)); sc = XtParent(sc)) ; return sc; } -static int Apply(Widget w, XtCallbackList callbacks) { +static int Apply(Widget w, XtCallbackList callbacks) +{ int status = XmdsXdsAreValid(FindShellChild(w)); for (; callbacks->callback && status; callbacks++) status = (*(int (*)())callbacks->callback)(w, callbacks->closure); @@ -148,14 +155,17 @@ static int Apply(Widget w, XtCallbackList callbacks) { return status; } -static void Destroy(Widget w, XtCallbackList callbacks) { +static void Destroy(Widget w, XtCallbackList callbacks) +{ XtFree((char *)callbacks); } EXPORT Widget XmdsCreateApplyButton(Widget parent, String name, ArgList args, - Cardinal numargs) { + Cardinal numargs) +{ Widget w = CreateButton(parent, name, args, numargs, "Apply", 0); - if (XtHasCallbacks(w, XmNactivateCallback) == XtCallbackHasSome) { + if (XtHasCallbacks(w, XmNactivateCallback) == XtCallbackHasSome) + { int num_callbacks; XtCallbackList callbacks; XtVaGetValues(w, XmNactivateCallback, &callbacks, NULL); @@ -166,20 +176,23 @@ EXPORT Widget XmdsCreateApplyButton(Widget parent, String name, ArgList args, XtRemoveAllCallbacks(w, XmNactivateCallback); XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)Apply, callbacks); XtAddCallback(w, XmNdestroyCallback, (XtCallbackProc)Destroy, callbacks); - } else + } + else XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)XmdsApplyCallback, 0); return w; } EXPORT Widget XmdsCreateResetButton(Widget parent, String name, ArgList args, - Cardinal numargs) { + Cardinal numargs) +{ Widget w = CreateButton(parent, name, args, numargs, "Reset", 0); XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)XmdsResetCallback, 0); return w; } EXPORT Widget XmdsCreateCancelButton(Widget parent, String name, ArgList args, - Cardinal numargs) { + Cardinal numargs) +{ Widget w = CreateButton(parent, name, args, numargs, "Cancel", 0); XtAddCallback(w, XmNactivateCallback, (XtCallbackProc)XmdsCancelCallback, 0); return w; @@ -187,7 +200,8 @@ EXPORT Widget XmdsCreateCancelButton(Widget parent, String name, ArgList args, static Widget CreateButton(Widget parent, String name, ArgList args, Cardinal numargs, String ident, - Boolean set_default) { + Boolean set_default) +{ Arg arglist[] = {{XmNlabelString, 0}}; Widget w; diff --git a/xmdsshr/XmdsOnOffToggleButton.c b/xmdsshr/XmdsOnOffToggleButton.c index 65a3d482fb..e6127066dd 100644 --- a/xmdsshr/XmdsOnOffToggleButton.c +++ b/xmdsshr/XmdsOnOffToggleButton.c @@ -85,7 +85,8 @@ void XmdsOnOffToggleButtonReset(Widget w); int XmdsOnOffToggleButtonPut(Widget w); int XmdsOnOffToggleButtonApply(Widget w); -typedef struct _Resources { +typedef struct _Resources +{ int nid; int nid_offset; Boolean show_path; @@ -109,7 +110,8 @@ static XtResource resources[] = { XtOffsetOf(Resources, put_on_apply), XmRImmediate, (void *)1}}; EXPORT Widget XmdsCreateOnOffToggleButton(Widget parent, String name, - ArgList args, Cardinal argcount) { + ArgList args, Cardinal argcount) +{ Widget w; Resources *info = (Resources *)XtMalloc(sizeof(Resources)); Resources default_info = {0, 0, 0, 0, 1}; @@ -118,7 +120,8 @@ EXPORT Widget XmdsCreateOnOffToggleButton(Widget parent, String name, if (info->nid == -1) info->nid = XmdsGetDeviceNid(); w = XmCreateToggleButton(parent, name, args, argcount); - if (info->show_path && info->nid + info->nid_offset) { + if (info->show_path && info->nid + info->nid_offset) + { char *path_c; XmString path; path_c = TreeGetMinimumPath(0, info->nid + info->nid_offset); @@ -126,7 +129,8 @@ EXPORT Widget XmdsCreateOnOffToggleButton(Widget parent, String name, TreeFree(path_c); XtVaSetValues(w, XmNlabelString, path, NULL); XmStringFree(path); - } else if (info->label) + } + else if (info->label) XtVaSetValues(w, XmNlabelString, info->label, NULL); XtAddCallback(w, XmNdestroyCallback, (XtCallbackProc)Destroy, info); @@ -134,18 +138,22 @@ EXPORT Widget XmdsCreateOnOffToggleButton(Widget parent, String name, return w; } -static void Destroy(Widget w, Resources *info, XtPointer cb) { +static void Destroy(Widget w, Resources *info, XtPointer cb) +{ XtFree((char *)info); } -EXPORT Boolean XmdsIsOnOffToggleButton(Widget w) { +EXPORT Boolean XmdsIsOnOffToggleButton(Widget w) +{ return GetResources(w) != 0; } -static Resources *GetResources(Widget w) { +static Resources *GetResources(Widget w) +{ Resources *answer = 0; if (XmIsToggleButton(w) && - (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) { + (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) + { XtCallbackList callbacks; XtVaGetValues(w, XmNdestroyCallback, &callbacks, NULL); for (; callbacks->callback && @@ -159,18 +167,21 @@ static Resources *GetResources(Widget w) { return answer; } -EXPORT void XmdsOnOffToggleButtonReset(Widget w) { +EXPORT void XmdsOnOffToggleButtonReset(Widget w) +{ Resources *info = GetResources(w); if (info) XmToggleButtonSetState(w, XmdsIsOn(info->nid + info->nid_offset), 0); } -EXPORT int XmdsOnOffToggleButtonPut(Widget w) { +EXPORT int XmdsOnOffToggleButtonPut(Widget w) +{ Resources *info = GetResources(w); return info ? XmdsSetState(info->nid + info->nid_offset, w) : 0; } -EXPORT int XmdsOnOffToggleButtonApply(Widget w) { +EXPORT int XmdsOnOffToggleButtonApply(Widget w) +{ Resources *info = GetResources(w); return info ? (info->put_on_apply ? XmdsOnOffToggleButtonPut(w) : 1) : 0; } diff --git a/xmdsshr/XmdsPath.c b/xmdsshr/XmdsPath.c index 2aee5f9603..17cd75f280 100644 --- a/xmdsshr/XmdsPath.c +++ b/xmdsshr/XmdsPath.c @@ -98,7 +98,8 @@ argcount); Boolean XmdsIsPath(Widget w); Local variables: */ -typedef struct _PathPart { +typedef struct _PathPart +{ int nid; int nid_offset; int path_type; @@ -117,7 +118,8 @@ static XtResource resources[] = { Executable: */ EXPORT Widget XmdsCreatePath(Widget parent, String name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ XmdsPathPart info = {-1, 0, 0}; Widget w; Arg lab_args[] = {{XmNlabelString, 0}, {XmNuserData, PathUserData}}; @@ -131,18 +133,22 @@ EXPORT Widget XmdsCreatePath(Widget parent, String name, ArgList args, nid = info.nid + info.nid_offset; else nid = -1; - if (nid != -1) { + if (nid != -1) + { NCI_ITM nci[] = {{0, 0, 0, 0}, {0, NciEND_OF_LIST, 0, 0}}; int status; nci[0].code = (info.path_type == NciABSOLUTE_PATH) ? NciFULLPATH : NciMINPATH; status = TreeGetNci(nid, nci); - if (status & 1) { + if (status & 1) + { lab_args[0].value = (long)XmStringCreateSimple(nci[0].pointer); TreeFree(nci[0].pointer); - } else + } + else lab_args[0].value = (long)XmStringCreateSimple("Error getting path"); - } else + } + else lab_args[0].value = (long)XmStringCreateSimple("No node"); merged_args = XtMergeArgLists(args, argcount, lab_args, XtNumber(lab_args)); w = XmCreateLabel(parent, name, merged_args, XtNumber(lab_args) + argcount); @@ -151,7 +157,8 @@ EXPORT Widget XmdsCreatePath(Widget parent, String name, ArgList args, return w; } -EXPORT Boolean XmdsIsPath(Widget w) { +EXPORT Boolean XmdsIsPath(Widget w) +{ XtPointer user_data = 0; XtVaGetValues(w, XmNuserData, &user_data, NULL); if (user_data && (user_data == (XtPointer)PathUserData)) diff --git a/xmdsshr/XmdsPopupMenuPosition.c b/xmdsshr/XmdsPopupMenuPosition.c index ae1b818944..84b2c8b34d 100644 --- a/xmdsshr/XmdsPopupMenuPosition.c +++ b/xmdsshr/XmdsPopupMenuPosition.c @@ -85,7 +85,8 @@ void XmdsPopupMenuPosition(XmRowColumnWidget w, XButtonEvent *event) Executable: */ -EXPORT void XmdsPopupMenuPosition(XmRowColumnWidget w, XButtonEvent *event) { +EXPORT void XmdsPopupMenuPosition(XmRowColumnWidget w, XButtonEvent *event) +{ Widget option = w->row_column.memory_subwidget; XtX(w) = event->x_root - (option ? XtX(option) + XtWidth(option) / 2 : 0); XtY(w) = event->y_root - (option ? XtY(option) + XtHeight(option) / 2 : 0); diff --git a/xmdsshr/XmdsSetSubvalues.c b/xmdsshr/XmdsSetSubvalues.c index 36096fa236..f732446b5a 100644 --- a/xmdsshr/XmdsSetSubvalues.c +++ b/xmdsshr/XmdsSetSubvalues.c @@ -64,10 +64,13 @@ num_resources, Arglist args, Cardinal argcount ) #include int XmdsSetSubvalues(XtPointer record, XtResourceList resources, - Cardinal num_resources, ArgList args, Cardinal argcount) { + Cardinal num_resources, ArgList args, Cardinal argcount) +{ Cardinal i; - for (i = 0; i < num_resources; i++) { - if (*((int *)&resources[i].resource_offset) >= 0) { + for (i = 0; i < num_resources; i++) + { + if (*((int *)&resources[i].resource_offset) >= 0) + { resources[i].resource_name = XrmStringToQuark(resources[i].resource_name) + (char *)0; resources[i].resource_class = diff --git a/xmdsshr/XmdsSupport.c b/xmdsshr/XmdsSupport.c index ab4100a6d9..f0b788c1c8 100644 --- a/xmdsshr/XmdsSupport.c +++ b/xmdsshr/XmdsSupport.c @@ -102,7 +102,8 @@ static struct descriptor_xd empty_xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; /*------------------------------------------------------------------------------ Executable: */ -Boolean ConglomerateElt(int nid) { +Boolean ConglomerateElt(int nid) +{ static unsigned short cong_elt; static NCI_ITM lst[] = { {sizeof(cong_elt), NciCONGLOMERATE_ELT, (unsigned char *)&cong_elt, 0}, @@ -114,7 +115,8 @@ Boolean ConglomerateElt(int nid) { return 0; } -int ConglomerateHead(int nid) { +int ConglomerateHead(int nid) +{ static unsigned int head_nid; static NCI_ITM lst[] = { {sizeof(head_nid), NciCONGLOMERATE_NIDS, (unsigned char *)&head_nid, 0}, @@ -126,7 +128,8 @@ int ConglomerateHead(int nid) { return 0; } -int DefaultNid(int nid) { +int DefaultNid(int nid) +{ int ans = -1; if (ConglomerateElt(nid)) ans = NodeParent(ConglomerateHead(nid)); @@ -135,7 +138,8 @@ int DefaultNid(int nid) { return ans; } -int NodeParent(int nid) { +int NodeParent(int nid) +{ static int parent_nid; static NCI_ITM lst[] = { {sizeof(parent_nid), NciPARENT, (unsigned char *)&parent_nid, 0}, @@ -147,7 +151,8 @@ int NodeParent(int nid) { return 0; } -void ResetErrors() { +void ResetErrors() +{ static int four = 4; static struct descriptor clear_messages = {4, DTYPE_L, CLASS_S, (char *)&four}; @@ -156,41 +161,49 @@ void ResetErrors() { StrFree1Dx(&messages); } -void TdiComplain(Widget w) { +void TdiComplain(Widget w) +{ static struct descriptor_d messages = {0, DTYPE_T, CLASS_D, 0}; static DESCRIPTOR(null, "\0"); static int one = 1; static struct descriptor get_messages = {4, DTYPE_L, CLASS_S, (char *)&one}; TdiDebug(&get_messages, &messages MDS_END_ARG); - if (messages.length) { + if (messages.length) + { StrAppend(&messages, (struct descriptor *)&null); XmdsComplain(w, messages.pointer); StrFree1Dx(&messages); } } -struct descriptor *TdiGet(int nid) { +struct descriptor *TdiGet(int nid) +{ struct descriptor_xd *answer = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); int status; *answer = empty_xd; status = TreeGetRecord(nid, answer); - if ((status & 1) == 0) { + if ((status & 1) == 0) + { XtFree((char *)answer); answer = 0; } return (struct descriptor *)answer; } -Boolean PutIfChanged(int nid, struct descriptor_xd *xd) { +Boolean PutIfChanged(int nid, struct descriptor_xd *xd) +{ int status = 1; - if (nid) { - if (xd) { + if (nid) + { + if (xd) + { struct descriptor_xd *old_xd = (struct descriptor_xd *)TdiGet(nid); if ((!old_xd && xd->l_length) || !MdsCompareXd((struct descriptor *)xd, (struct descriptor *)old_xd)) status = TreePutRecord(nid, (struct descriptor *)xd, 0); - if (old_xd) { + if (old_xd) + { MdsFree1Dx(old_xd, 0); XtFree((char *)old_xd); } diff --git a/xmdsshr/XmdsUsageIcons.c b/xmdsshr/XmdsUsageIcons.c index b64ad19248..c458af240e 100644 --- a/xmdsshr/XmdsUsageIcons.c +++ b/xmdsshr/XmdsUsageIcons.c @@ -101,18 +101,21 @@ static Pixmap *gray_icons; Executable: */ -void XmdsUsageIconsInitialize(Widget w) { +void XmdsUsageIconsInitialize(Widget w) +{ static String hierarchy_name[] = {"xmds_usage_icons.uid"}; static MrmHierarchy mrm_hierarchy; int usage; int usages; - if (!icons) { + if (!icons) + { MrmInitialize(); MrmOpenHierarchy(1, hierarchy_name, 0, &mrm_hierarchy); usages = 13; icons = (unsigned long *)XtMalloc(sizeof(Pixmap) * usages * 2); gray_icons = icons + usages; - for (usage = 0; usage < usages; usage++) { + for (usage = 0; usage < usages; usage++) + { char name[] = {'U', 0, 0, 0, 0}; name[1] = '0' + (usage / 10); name[2] = '0' + usage - (usage / 10) * 10; diff --git a/xmdsshr/XmdsWavedraw.c b/xmdsshr/XmdsWavedraw.c index 6ab7afbb36..795b283408 100644 --- a/xmdsshr/XmdsWavedraw.c +++ b/xmdsshr/XmdsWavedraw.c @@ -194,14 +194,14 @@ int XmdsCreateWavedraw( parent, name, args, argcount ) #define waveformPanning(widget) ((widget)->waveform.panning) #define waveformRedraw(widget) ((widget)->waveform.redraw) #define waveformStepPlot(widget) ((widget)->waveform.step_plot) -#define waveformDeleteOnlySelected(widget) \ +#define waveformDeleteOnlySelected(widget) \ ((widget)->wavedraw.delete_only_selected) #define wavedrawMoveCallbacks(widget) ((widget)->wavedraw.move_callback) #define wavedrawSelectCallbacks(widget) ((widget)->wavedraw.select_callback) #define wavedrawDeselectCallbacks(widget) ((widget)->wavedraw.deselect_callback) -#define wavedrawAddPointCallbacks(widget) \ +#define wavedrawAddPointCallbacks(widget) \ ((widget)->wavedraw.add_point_callback) -#define wavedrawDeletePointCallbacks(widget) \ +#define wavedrawDeletePointCallbacks(widget) \ ((widget)->wavedraw.delete_point_callback) #define wavedrawFitCallbacks(widget) ((widget)->wavedraw.fit_callback) #define wavedrawSelectionIdx(widget) ((widget)->wavedraw.selection_idx) @@ -392,16 +392,18 @@ EXPORT WidgetClass xmdsWavedrawWidgetClass; Executable: */ EXPORT Widget XmdsCreateWavedraw(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ return XtCreateWidget(name, xmdsWavedrawWidgetClass, parent, args, argcount); } -static void ClassPartInitialize(XmdsWavedrawWidgetClass class) { +static void ClassPartInitialize(XmdsWavedrawWidgetClass class) +{ -#define initTrans(field, deftrans) \ - if (field == XmdsInheritTranslations) \ - field = XtParseTranslationTable(deftrans); \ - else \ +#define initTrans(field, deftrans) \ + if (field == XmdsInheritTranslations) \ + field = XtParseTranslationTable(deftrans); \ + else \ field = XtParseTranslationTable((const char *)field) initTrans(xmdsWavedrawClassRec.wavedraw_class.draw1_trans, @@ -417,10 +419,11 @@ static void ClassPartInitialize(XmdsWavedrawWidgetClass class) { :WaveformButton3()\n @Help :WaveformHelp()"); } -static void Initialize(XmdsWavedrawWidget req, XmdsWavedrawWidget w) { +static void Initialize(XmdsWavedrawWidget req, XmdsWavedrawWidget w) +{ -#define NewInstance(field, size) \ - if (field(req)) \ +#define NewInstance(field, size) \ + if (field(req)) \ field(w) = (void *)memcpy(XtMalloc(size), field(req), size) NewInstance(xLowLimit, sizeof(float)); @@ -442,10 +445,11 @@ static void Initialize(XmdsWavedrawWidget req, XmdsWavedrawWidget w) { #undef NewInstance -static void Destroy(XmdsWavedrawWidget w) { +static void Destroy(XmdsWavedrawWidget w) +{ -#define FreeInstance(field) \ - if (field(w)) \ +#define FreeInstance(field) \ + if (field(w)) \ XtFree((char *)field(w)) FreeInstance(xLowLimit); @@ -463,9 +467,11 @@ static void Destroy(XmdsWavedrawWidget w) { */ } -static void MoveBegin(XmdsWavedrawWidget w, XButtonEvent *event) { +static void MoveBegin(XmdsWavedrawWidget w, XButtonEvent *event) +{ int selection = SelectedPoint(w, event, 0); - if (selection >= 0) { + if (selection >= 0) + { XmdsWavedrawValueCBStruct cb = { XmdsCRMovePointBegin, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; cb.event = (XEvent *)event; @@ -483,12 +489,14 @@ static void MoveBegin(XmdsWavedrawWidget w, XButtonEvent *event) { XWarpPointer(XtDisplay(w), XtWindow(w), XtWindow(w), event->x, event->y, XtWidth(w), XtHeight(w), xPixValue(w, selection), yPixValue(w, selection)); - } else + } + else wavedrawSelectionIdx(w) = -1; waveformPanning(w) = -1; } -static void SetPen(XmdsWavedrawWidget w, XButtonEvent *event) { +static void SetPen(XmdsWavedrawWidget w, XButtonEvent *event) +{ int selection = SelectedSegment(w, event); XmdsWavedrawFitCBStruct fitcb = {XmdsCRSetPen, 0, 0, 0, 0, 0, 0}; ; @@ -504,7 +512,8 @@ static void SetPen(XmdsWavedrawWidget w, XButtonEvent *event) { Refresh(w); } -static void Refresh(XmdsWavedrawWidget w) { +static void Refresh(XmdsWavedrawWidget w) +{ waveformRedraw(w) = 1; (((XmdsWavedrawWidgetClass)w->core.widget_class)->core_class.expose)( (Widget)w, 0, 0); @@ -513,7 +522,8 @@ static void Refresh(XmdsWavedrawWidget w) { EXPORT Boolean XmdsWavedrawMovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, float *desired_y, float *new_x, float *new_y, - Boolean callcallbacks, XEvent *event) { + Boolean callcallbacks, XEvent *event) +{ return (((XmdsWavedrawWidgetClass)w->core.widget_class) ->wavedraw_class.move_point_proc)( w, idx, desired_x, desired_y, new_x, new_y, callcallbacks, event); @@ -521,7 +531,8 @@ EXPORT Boolean XmdsWavedrawMovePoint(XmdsWavedrawWidget w, int idx, static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, float *desired_y, float *new_x, float *new_y, - Boolean callcallbacks, XEvent *event) { + Boolean callcallbacks, XEvent *event) +{ Boolean stat = 0; int range = idx ? (idx >= (waveformCount(w) - 1) ? 3 : 2) : 1; if ((idx < 0) || (idx > (waveformCount(w) - 1))) @@ -530,18 +541,23 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, *desired_x = Round(*desired_x, *xGridSnap(w)); if (yGridSnap(w) && (*yGridSnap(w) > 0.0)) *desired_y = Round(*desired_y, *yGridSnap(w)); - if (xNumChoices(w)) { + if (xNumChoices(w)) + { float min_dif = 1E38; int i; int closest = -1; - for (i = 0; i < xNumChoices(w); i++) { + for (i = 0; i < xNumChoices(w); i++) + { if ((xLowLimit(w) && (xChoices(w)[i] >= *xLowLimit(w))) || - (!xLowLimit(w))) { + (!xLowLimit(w))) + { float dif = *desired_x - xChoices(w)[i]; dif = dif < 0.0 ? -dif : dif; - if (xIncreasing(w)) { + if (xIncreasing(w)) + { float mindist = xMinDistance(w) ? *xMinDistance(w) : xResolution(w); - switch (range) { + switch (range) + { case 1: if (xChoices(w)[i] > (xValue(w)[idx + 1] - mindist)) dif = 1E38; @@ -557,39 +573,49 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, break; } } - if (dif < min_dif) { + if (dif < min_dif) + { min_dif = dif; closest = i; } } } - if (closest >= 0) { + if (closest >= 0) + { *new_x = xChoices(w)[closest]; stat = 1; } - } else if (xIncreasing(w)) { + } + else if (xIncreasing(w)) + { float mindist = xMinDistance(w) ? *xMinDistance(w) : xResolution(w); *new_x = *desired_x; if (xLowLimit(w) && (*desired_x < *xLowLimit(w))) *new_x = *xLowLimit(w); if (xHighLimit(w) && (*desired_x > *xHighLimit(w))) *new_x = *xHighLimit(w); - switch (range) { + switch (range) + { case 1: - if (*desired_x > (xValue(w)[idx + 1] - mindist)) { + if (*desired_x > (xValue(w)[idx + 1] - mindist)) + { if ((xLowLimit(w) && (*xLowLimit(w) <= (xValue(w)[idx + 1] - mindist))) || - !xLowLimit(w)) { + !xLowLimit(w)) + { *new_x = xValue(w)[idx + 1] - mindist; stat = 1; } - } else { + } + else + { *new_x = *desired_x; stat = 1; } break; case 2: - if ((xValue(w)[idx + 1] - xValue(w)[idx - 1]) >= (1.99 * mindist)) { + if ((xValue(w)[idx + 1] - xValue(w)[idx - 1]) >= (1.99 * mindist)) + { stat = 1; if (*desired_x < (xValue(w)[idx - 1] + mindist)) *new_x = xValue(w)[idx - 1] + mindist; @@ -600,20 +626,26 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, } break; case 3: - if (*desired_x < (xValue(w)[idx - 1] + mindist)) { + if (*desired_x < (xValue(w)[idx - 1] + mindist)) + { if ((xHighLimit(w) && (*xHighLimit(w) >= (xValue(w)[idx - 1] + mindist))) || - !xHighLimit(w)) { + !xHighLimit(w)) + { *new_x = xValue(w)[idx - 1] + mindist; stat = 1; } - } else { + } + else + { *new_x = *desired_x; stat = 1; } break; } - } else { + } + else + { if (xLowLimit(w) && (*desired_x < *xLowLimit(w))) *new_x = *xLowLimit(w); else if (xHighLimit(w) && (*desired_x > *xHighLimit(w))) @@ -626,18 +658,23 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, return stat; stat = 0; /**********************************************/ - if (yNumChoices(w)) { + if (yNumChoices(w)) + { float min_dif = 1E38; int i; int closest = -1; - for (i = 0; i < yNumChoices(w); i++) { + for (i = 0; i < yNumChoices(w); i++) + { if ((yLowLimit(w) && (yChoices(w)[i] >= *yLowLimit(w))) || - (!yLowLimit(w))) { + (!yLowLimit(w))) + { float dif = *desired_y - yChoices(w)[i]; dif = dif < 0.0 ? -dif : dif; - if (yIncreasing(w)) { + if (yIncreasing(w)) + { float mindist = yMinDistance(w) ? *yMinDistance(w) : yResolution(w); - switch (range) { + switch (range) + { case 1: if (yChoices(w)[i] > (yValue(w)[idx + 1] - mindist)) dif = 1E38; @@ -653,39 +690,49 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, break; } } - if (dif < min_dif) { + if (dif < min_dif) + { min_dif = dif; closest = i; } } } - if (closest >= 0) { + if (closest >= 0) + { *new_y = yChoices(w)[closest]; stat = 1; } - } else if (yIncreasing(w)) { + } + else if (yIncreasing(w)) + { float mindist = yMinDistance(w) ? *yMinDistance(w) : yResolution(w); *new_y = *desired_y; if (yLowLimit(w) && (*desired_y < *yLowLimit(w))) *new_y = *yLowLimit(w); if (yHighLimit(w) && (*desired_y > *yHighLimit(w))) *new_y = *yHighLimit(w); - switch (range) { + switch (range) + { case 1: - if (*desired_y > (yValue(w)[idx + 1] - mindist)) { + if (*desired_y > (yValue(w)[idx + 1] - mindist)) + { if ((yLowLimit(w) && (*yLowLimit(w) <= (yValue(w)[idx + 1] - mindist))) || - !yLowLimit(w)) { + !yLowLimit(w)) + { *new_y = yValue(w)[idx + 1] - mindist; stat = 1; } - } else { + } + else + { *new_y = *desired_y; stat = 1; } break; case 2: - if ((yValue(w)[idx + 1] - yValue(w)[idx - 1]) >= (2 * mindist)) { + if ((yValue(w)[idx + 1] - yValue(w)[idx - 1]) >= (2 * mindist)) + { stat = 1; if (*desired_y < (yValue(w)[idx - 1] + mindist)) *new_y = yValue(w)[idx - 1] + mindist; @@ -696,20 +743,26 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, } break; case 3: - if (*desired_y < (yValue(w)[idx - 1] + mindist)) { + if (*desired_y < (yValue(w)[idx - 1] + mindist)) + { if ((yHighLimit(w) && (*yHighLimit(w) >= (yValue(w)[idx - 1] + mindist))) || - !yHighLimit(w)) { + !yHighLimit(w)) + { *new_y = yValue(w)[idx - 1] + mindist; stat = 1; } - } else { + } + else + { *new_y = *desired_y; stat = 1; } break; } - } else { + } + else + { if (yLowLimit(w) && (*desired_y < *yLowLimit(w))) *new_y = *yLowLimit(w); else if (yHighLimit(w) && (*desired_y > *yHighLimit(w))) @@ -720,8 +773,10 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, } if (!stat) return 0; - if (waveformSelections(w)) { - switch (waveformSelections(w)[idx]) { + if (waveformSelections(w)) + { + switch (waveformSelections(w)[idx]) + { case XmdsMOTION_XONLY: *new_y = yValue(w)[idx]; break; @@ -740,7 +795,8 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, if (yGridSnap(w) && (*yGridSnap(w) > 0.0)) *new_y = Round(*new_y,*yGridSnap(w)); */ - if (callcallbacks) { + if (callcallbacks) + { XmdsWavedrawValueCBStruct cb = { XmdsCRMovePoint, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; XmdsWavedrawFitCBStruct fitcb = {XmdsCRMovePoint, 0, 0, 0, 0, 0, 0}; @@ -765,7 +821,9 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, wavedrawSelectionIdx(w) = cb.idx; XtCallCallbacks((Widget)w, XmdsNfitCallback, &fitcb); Refresh(w); - } else { + } + else + { xValue(w)[idx] = *new_x; yValue(w)[idx] = *new_y; } @@ -775,7 +833,8 @@ static Boolean MovePoint(XmdsWavedrawWidget w, int idx, float *desired_x, static void SlideStretch(XmdsWavedrawWidget w, int idx, float *desired_x, float *desired_y, float *new_x, float *new_y, Boolean callcallbacks, XEvent *event, - Boolean stretch) { + Boolean stretch) +{ int i; float xoff = *desired_x - xValue(w)[idx]; float yoff = *desired_y - yValue(w)[idx]; @@ -786,15 +845,18 @@ static void SlideStretch(XmdsWavedrawWidget w, int idx, float *desired_x, float *oldy = (float *)memcpy(XtMalloc(waveformCount(w) * sizeof(float)), yValue(w), waveformCount(w) * sizeof(float)); Boolean ok = 1; - for (i = 0; i < waveformCount(w); i++) { + for (i = 0; i < waveformCount(w); i++) + { xValue(w)[i] = stretch ? xValue(w)[i] * xratio : xValue(w)[i] + xoff; yValue(w)[i] = stretch ? yValue(w)[i] * yratio : yValue(w)[i] + yoff; } for (i = 0; i < waveformCount(w); i++) ok = ok & MovePoint(w, i, &xValue(w)[i], &yValue(w)[i], &xValue(w)[i], &yValue(w)[i], 0, 0); - if (ok) { - if (callcallbacks) { + if (ok) + { + if (callcallbacks) + { XmdsWavedrawValueCBStruct cb = { XmdsCRMovePoint, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; XmdsWavedrawFitCBStruct fitcb = {XmdsCRMovePoint, 0, 0, 0, 0, 0, 0}; @@ -820,7 +882,9 @@ static void SlideStretch(XmdsWavedrawWidget w, int idx, float *desired_x, XtCallCallbacks((Widget)w, XmdsNfitCallback, &fitcb); Refresh(w); } - } else { + } + else + { memcpy(xValue(w), oldx, waveformCount(w) * sizeof(float)); memcpy(yValue(w), oldy, waveformCount(w) * sizeof(float)); } @@ -828,7 +892,8 @@ static void SlideStretch(XmdsWavedrawWidget w, int idx, float *desired_x, XtFree((char *)oldy); } -static void Move(XmdsWavedrawWidget w, XButtonEvent *event) { +static void Move(XmdsWavedrawWidget w, XButtonEvent *event) +{ int idx = wavedrawSelectionIdx(w); Boolean warp = FALSE; float x; @@ -837,7 +902,8 @@ static void Move(XmdsWavedrawWidget w, XButtonEvent *event) { ; if (idx < 0) return; - if (event->state & LockMask) { + if (event->state & LockMask) + { x = xValue(w)[idx] + ((event->x == xPixValue(w, idx)) ? 0 : ((event->state & ShiftMask) @@ -853,7 +919,9 @@ static void Move(XmdsWavedrawWidget w, XButtonEvent *event) { ? yResolution(w) : -1 * yResolution(w))))); warp = TRUE; - } else { + } + else + { x = (event->state & ShiftMask) ? xValue(w)[idx] : Round(event->x * (*xMax(w) - *xMin(w)) / XtWidth(w) + *xMin(w), @@ -876,10 +944,12 @@ static void Move(XmdsWavedrawWidget w, XButtonEvent *event) { Refresh(w); } -static void MoveEnd(XmdsWavedrawWidget w, XButtonEvent *event) { +static void MoveEnd(XmdsWavedrawWidget w, XButtonEvent *event) +{ int selection = wavedrawSelectionIdx(w); waveformPanning(w) = 0; - if (selection >= 0) { + if (selection >= 0) + { XmdsWavedrawValueCBStruct cb = { XmdsCRMovePointEnd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; cb.event = (XEvent *)event; @@ -898,8 +968,10 @@ static void MoveEnd(XmdsWavedrawWidget w, XButtonEvent *event) { } } -static void SelectDeselect(XmdsWavedrawWidget w, XButtonEvent *event) { - if (waveformSelections(w)) { +static void SelectDeselect(XmdsWavedrawWidget w, XButtonEvent *event) +{ + if (waveformSelections(w)) + { int selection = SelectedPoint(w, event, !(event->state & ControlMask)); XmdsWavedrawValueCBStruct cb = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; XmdsWavedrawFitCBStruct fitcb = {0, 0, 0, 0, 0, 0, 0}; @@ -920,9 +992,12 @@ static void SelectDeselect(XmdsWavedrawWidget w, XButtonEvent *event) { fitcb.selected = waveformSelections(w); fitcb.pen_down = waveformPenDown(w); - if (selection >= 0) { - if (event->state & ControlMask) { - if (waveformSelections(w)[selection]) { + if (selection >= 0) + { + if (event->state & ControlMask) + { + if (waveformSelections(w)[selection]) + { waveformSelections(w)[selection] = 0; wavedrawNumSelections(w)--; fitcb.reason = cb.reason = XmdsCRDeselectPoint; @@ -930,7 +1005,9 @@ static void SelectDeselect(XmdsWavedrawWidget w, XButtonEvent *event) { XtCallCallbacks((Widget)w, XmdsNfitCallback, &fitcb); Refresh(w); } - } else { + } + else + { if (!waveformSelections(w)[selection]) wavedrawNumSelections(w)++; waveformSelections(w)[selection] = @@ -947,7 +1024,8 @@ static void SelectDeselect(XmdsWavedrawWidget w, XButtonEvent *event) { } } -static void AddDelete(XmdsWavedrawWidget w, XButtonEvent *event) { +static void AddDelete(XmdsWavedrawWidget w, XButtonEvent *event) +{ float newx = Round((float)event->x / XtWidth(w) * (*xMax(w) - *xMin(w)) + *xMin(w), xResolution(w)); @@ -955,19 +1033,25 @@ static void AddDelete(XmdsWavedrawWidget w, XButtonEvent *event) { (*yMax(w) - *yMin(w)) + *yMin(w), yResolution(w)); - if (event->state & ShiftMask) { - if (waveformCount(w) > 2) { + if (event->state & ShiftMask) + { + if (waveformCount(w) > 2) + { int selection = SelectedPoint(w, event, !waveformDeleteOnlySelected(w)); if (selection >= 0) XmdsWavedrawDeletePoint((Widget)w, selection, 1); } - } else { + } + else + { int selection; - if (waveformStepPlot(w)) { + if (waveformStepPlot(w)) + { for (selection = 0; selection < waveformCount(w); selection++) if (xValue(w)[selection] > newx) break; - } else + } + else selection = InsertionPoint(w, event, SelectedPoint(w, event, 1)); if (!XmdsWavedrawAddPoint((Widget)w, selection, &newx, &newy, 1, XmdsMOTION_BOTH)) @@ -976,10 +1060,13 @@ static void AddDelete(XmdsWavedrawWidget w, XButtonEvent *event) { } static int InsertionPoint(XmdsWavedrawWidget w, XButtonEvent *event, - int selection) { + int selection) +{ int idx = selection; - if (selection) { - if (selection < (waveformCount(w) - 1)) { + if (selection) + { + if (selection < (waveformCount(w) - 1)) + { if ((Distance(event->x - xPixValue(w, selection + 1), waveformStepPlot(w) ? 0 @@ -997,7 +1084,9 @@ static int InsertionPoint(XmdsWavedrawWidget w, XButtonEvent *event, : yPixValue(w, selection + 1) - yPixValue(w, selection)))) idx++; - } else { + } + else + { if (Distance(event->x - xPixValue(w, selection - 1), waveformStepPlot(w) ? 0 @@ -1008,7 +1097,9 @@ static int InsertionPoint(XmdsWavedrawWidget w, XButtonEvent *event, : yPixValue(w, selection) - yPixValue(w, selection - 1))) idx++; } - } else { + } + else + { if (Distance(event->x - xPixValue(w, selection + 1), waveformStepPlot(w) ? 0 : event->y - yPixValue(w, selection + 1)) < @@ -1021,16 +1112,19 @@ static int InsertionPoint(XmdsWavedrawWidget w, XButtonEvent *event, return idx; } -static int SelectedSegment(XmdsWavedrawWidget w, XButtonEvent *event) { +static int SelectedSegment(XmdsWavedrawWidget w, XButtonEvent *event) +{ int i; int selection = -1; double min_distance = 2000000000; int count = waveformCount(w) - 1; - for (i = 0; i < count; i++) { + for (i = 0; i < count; i++) + { double distance = SegDistance(xPixValue(w, i), yPixValue(w, i), xPixValue(w, i + 1), yPixValue(w, i + 1), event->x, event->y); - if (distance < min_distance) { + if (distance < min_distance) + { min_distance = distance; selection = i; } @@ -1039,7 +1133,8 @@ static int SelectedSegment(XmdsWavedrawWidget w, XButtonEvent *event) { } static double SegDistance(double ax, double ay, double bx, double by, double cx, - double cy) { + double cy) +{ double distance; double theta = (ax == bx) ? 3.14159 / 2 : atan((by - ay) / (bx - ax)); double sin_theta = sin(theta); @@ -1049,7 +1144,8 @@ static double SegDistance(double ax, double ay, double bx, double by, double cx, double t_cy = (cy - ay) * cos_theta - (cx - ax) * sin_theta; if ((t_bx < 0) ? t_cx > 0 : t_cx < 0) distance = sqrt((ax - cx) * (ax - cx) + (ay - cy) * (ay - cy)); - else { + else + { if ((t_bx < 0) ? t_cx < t_bx : t_cx > t_bx) distance = sqrt((bx - cx) * (bx - cx) + (by - cy) * (by - cy)); else @@ -1059,16 +1155,19 @@ static double SegDistance(double ax, double ay, double bx, double by, double cx, } static int SelectedPoint(XmdsWavedrawWidget w, XButtonEvent *event, - Boolean anypoint) { + Boolean anypoint) +{ int i; int selection = -1; unsigned int min_distance = 2000000000; - for (i = 0; i < waveformCount(w); i++) { + for (i = 0; i < waveformCount(w); i++) + { unsigned int distance = Distance(event->x - xPixValue(w, i), event->y - yPixValue(w, i)); if ((anypoint || !waveformSelections(w) || (waveformSelections(w) && waveformSelections(w)[i])) && - (distance < min_distance)) { + (distance < min_distance)) + { min_distance = distance; selection = i; } @@ -1076,18 +1175,21 @@ static int SelectedPoint(XmdsWavedrawWidget w, XButtonEvent *event, return selection; } -static unsigned int Distance(int xdistance, int ydistance) { +static unsigned int Distance(int xdistance, int ydistance) +{ return xdistance * xdistance + ydistance * ydistance; } static Boolean SetValues(XmdsWavedrawWidget old, XmdsWavedrawWidget req, - XmdsWavedrawWidget new) { -#define NewInstance(field, size) \ - if (field(old) != field(req)) { \ - if (field(old)) \ - XtFree((char *)field(old)); \ - if (field(req)) \ - field(new) = (void *)memcpy(XtMalloc(size), field(req), size); \ + XmdsWavedrawWidget new) +{ +#define NewInstance(field, size) \ + if (field(old) != field(req)) \ + { \ + if (field(old)) \ + XtFree((char *)field(old)); \ + if (field(req)) \ + field(new) = (void *)memcpy(XtMalloc(size), field(req), size); \ } NewInstance(xLowLimit, sizeof(float)); @@ -1111,16 +1213,20 @@ static Boolean SetValues(XmdsWavedrawWidget old, XmdsWavedrawWidget req, return 0; } -static void SetCursor(XmdsWavedrawWidget w) { +static void SetCursor(XmdsWavedrawWidget w) +{ static Boolean first = 1; static Cursor draw_cursor; - if (first) { + if (first) + { draw_cursor = XCreateFontCursor(XtDisplay(w), XC_dotbox); first = 0; } - if (XtWindow(w)) { - switch (waveformPointerMode(w)) { + if (XtWindow(w)) + { + switch (waveformPointerMode(w)) + { case XmdsPOINTER_MODE_DRAW1: case XmdsPOINTER_MODE_DRAW2: case XmdsPOINTER_MODE_SET_PEN: @@ -1131,10 +1237,13 @@ static void SetCursor(XmdsWavedrawWidget w) { } } -static void SetTranslations(XmdsWavedrawWidget w) { +static void SetTranslations(XmdsWavedrawWidget w) +{ Arg arglist[] = {{XmNtranslations, 0}}; - if (waveformCount(w)) { - switch (waveformPointerMode(w)) { + if (waveformCount(w)) + { + switch (waveformPointerMode(w)) + { case XmdsPOINTER_MODE_DRAW1: arglist[0].value = (long)xmdsWavedrawClassRec.wavedraw_class.draw1_trans; XtSetValues((Widget)w, arglist, XtNumber(arglist)); @@ -1152,13 +1261,15 @@ static void SetTranslations(XmdsWavedrawWidget w) { } } -EXPORT void XmdsWavedrawDeletePoint(Widget w, int idx, Boolean callcallbacks) { +EXPORT void XmdsWavedrawDeletePoint(Widget w, int idx, Boolean callcallbacks) +{ XmdsWavedrawWidget wdw = (XmdsWavedrawWidget)w; (((XmdsWavedrawWidgetClass)wdw->core.widget_class) ->wavedraw_class.delete_point_proc)(wdw, idx, callcallbacks); } -static void DeletePoint(XmdsWavedrawWidget w, int idx, Boolean callcallbacks) { +static void DeletePoint(XmdsWavedrawWidget w, int idx, Boolean callcallbacks) +{ float oldx = xValue(w)[idx]; float oldy = yValue(w)[idx]; memcpy(xValue(w) + idx, xValue(w) + idx + 1, @@ -1172,7 +1283,8 @@ static void DeletePoint(XmdsWavedrawWidget w, int idx, Boolean callcallbacks) { memcpy(waveformPenDown(w) + idx, waveformPenDown(w) + idx + 1, (waveformCount(w) - idx - 1) * sizeof(*waveformPenDown(w))); waveformCount(w)--; - if (callcallbacks) { + if (callcallbacks) + { XmdsWavedrawValueCBStruct cb = { XmdsCRDeletePoint, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; XmdsWavedrawFitCBStruct fitcb = {XmdsCRDeletePoint, 0, 0, 0, 0, 0, 0}; @@ -1199,7 +1311,8 @@ static void DeletePoint(XmdsWavedrawWidget w, int idx, Boolean callcallbacks) { EXPORT Boolean XmdsWavedrawAddPoint(Widget w, int idx, float *newx, float *newy, Boolean callcallbacks, - enum XmdsWaveformMotionRestriction motion) { + enum XmdsWaveformMotionRestriction motion) +{ XmdsWavedrawWidget wdw = (XmdsWavedrawWidget)w; return (((XmdsWavedrawWidgetClass)wdw->core.widget_class) ->wavedraw_class.add_point_proc)(wdw, idx, newx, newy, @@ -1208,7 +1321,8 @@ EXPORT Boolean XmdsWavedrawAddPoint(Widget w, int idx, float *newx, float *newy, static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, Boolean callcallbacks, - enum XmdsWaveformMotionRestriction motion) { + enum XmdsWaveformMotionRestriction motion) +{ float *oldxvals = xValue(w); float *oldyvals = yValue(w); Boolean *oldselections = waveformSelections(w); @@ -1220,38 +1334,46 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, (yLowLimit(w) && y < *yLowLimit(w)) || (yHighLimit(w) && y > *yHighLimit(w))) return 0; - if (xNumChoices(w)) { + if (xNumChoices(w)) + { float min_dif = 1E38; int i; int closest = 0; - for (i = 0; i < xNumChoices(w); i++) { + for (i = 0; i < xNumChoices(w); i++) + { float dif = x - xChoices(w)[i]; dif = dif < 0.0 ? -dif : dif; - if (dif < min_dif) { + if (dif < min_dif) + { min_dif = dif; closest = i; } } x = xChoices(w)[closest]; } - if (yNumChoices(w)) { + if (yNumChoices(w)) + { float min_dif = 1E38; int i; int closest = 0; - for (i = 0; i < yNumChoices(w); i++) { + for (i = 0; i < yNumChoices(w); i++) + { float dif = y - yChoices(w)[i]; dif = dif < 0.0 ? -dif : dif; - if (dif < min_dif) { + if (dif < min_dif) + { min_dif = dif; closest = i; } } y = yChoices(w)[closest]; } - if (xIncreasing(w)) { + if (xIncreasing(w)) + { float mindist = xMinDistance(w) ? *xMinDistance(w) : xResolution(w); int range = idx ? (idx >= (waveformCount(w) - 1) ? 3 : 2) : 1; - switch (range) { + switch (range) + { case 1: if (x > (xValue(w)[idx] - mindist)) return 0; @@ -1266,10 +1388,12 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, break; } } - if (yIncreasing(w)) { + if (yIncreasing(w)) + { float mindist = yMinDistance(w) ? *yMinDistance(w) : yResolution(w); int range = idx ? (idx >= (waveformCount(w) - 1) ? 3 : 2) : 1; - switch (range) { + switch (range) + { case 1: if (y > (yValue(w)[idx] - mindist)) return 0; @@ -1294,7 +1418,8 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, if (waveformPenDown(w)) waveformPenDown(w) = waveformPenDownValPtr(w) = XtCalloc((waveformCount(w) + 1), sizeof(*waveformPenDown(w))); - if (idx) { + if (idx) + { memcpy(xValue(w), oldxvals, idx * sizeof(*xValue(w))); memcpy(yValue(w), oldyvals, idx * sizeof(*yValue(w))); if (waveformSelections(w)) @@ -1303,7 +1428,8 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, if (waveformPenDown(w)) memcpy(waveformPenDown(w), oldpendown, idx * sizeof(*waveformPenDown(w))); } - if (idx < waveformCount(w)) { + if (idx < waveformCount(w)) + { memcpy(xValue(w) + idx + 1, oldxvals + idx, (waveformCount(w) - idx) * sizeof(*xValue(w))); memcpy(yValue(w) + idx + 1, oldyvals + idx, @@ -1330,7 +1456,8 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, XtFree(oldselections); if (oldpendown) XtFree(oldpendown); - if (callcallbacks) { + if (callcallbacks) + { XmdsWavedrawValueCBStruct cb = { XmdsCRAddPoint, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; XmdsWavedrawFitCBStruct fitcb = {XmdsCRAddPoint, 0, 0, 0, 0, 0, 0}; @@ -1357,7 +1484,8 @@ static Boolean AddPoint(XmdsWavedrawWidget w, int idx, float *newx, float *newy, return 1; } -static double Round(double value, double resolution) { +static double Round(double value, double resolution) +{ return (resolution > 0) ? ((value >= 0) @@ -1366,14 +1494,16 @@ static double Round(double value, double resolution) { : value; } -static void SetPointerMode(XmdsWavedrawWidget w, int mode) { +static void SetPointerMode(XmdsWavedrawWidget w, int mode) +{ (*(void (*)(XmdsWavedrawWidget, int)) xmdsWaveformClassRec.waveform_class.set_pointer_mode_proc)(w, mode); SetTranslations(w); SetCursor(w); } -static int XPix(XmdsWavedrawWidget w, int idx) { +static int XPix(XmdsWavedrawWidget w, int idx) +{ float value = xValue(w)[idx]; float minval = *xMin(w); float maxval = *xMax(w); @@ -1383,7 +1513,8 @@ static int XPix(XmdsWavedrawWidget w, int idx) { return (value - minval) * pix_over_span; } -static int YPix(XmdsWavedrawWidget w, int idx) { +static int YPix(XmdsWavedrawWidget w, int idx) +{ float value = yValue(w)[idx]; float minval = *yMin(w); float maxval = *yMax(w); diff --git a/xmdsshr/XmdsWaveform.c b/xmdsshr/XmdsWaveform.c index 314bb4cd58..c23fae3b4e 100644 --- a/xmdsshr/XmdsWaveform.c +++ b/xmdsshr/XmdsWaveform.c @@ -58,10 +58,10 @@ Widget XmdsCreateWaveform( parent, name, args, argcount ) #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) -#define compare_sign(a, b) \ +#define compare_sign(a, b) \ (((a) > 0 && (b) > 0) ? 1 : (((a) < 0 && (b) < 0) ? 1 : 0)) -#define interp(x1, y1, x2, y2, x) \ - (((y2) - (y1)) * ((x) / ((x2) - (x1))) + \ +#define interp(x1, y1, x2, y2, x) \ + (((y2) - (y1)) * ((x) / ((x2) - (x1))) + \ (((y1) * ((x2) / ((x2) - (x1)))) - ((y2) * ((x1) / ((x2) - (x1)))))) #define pointsPerIo 1024 #define recsPerIo 256 @@ -99,7 +99,7 @@ Widget XmdsCreateWaveform( parent, name, args, argcount ) #define waveformPointerMode(widget) ((widget)->waveform.pointer_mode) #define waveformGridStyle(widget) ((widget)->waveform.grid_style) #define waveformAttachCrosshairs(widget) ((widget)->waveform.attach_crosshairs) -#define waveformCrosshairsCallbacks(widget) \ +#define waveformCrosshairsCallbacks(widget) \ ((widget)->waveform.crosshairs_callback) #define waveformAlignCallbacks(widget) ((widget)->waveform.align_callback) #define waveformButton3Callbacks(widget) ((widget)->waveform.button3_callback) @@ -114,18 +114,18 @@ Widget XmdsCreateWaveform( parent, name, args, argcount ) #define waveformEraseGC(widget) ((widget)->waveform.erase_gc) #define waveformCount(widget) ((widget)->waveform.count) #define waveformSelectionsValue(widget) ((widget)->waveform.selections) -#define waveformSelectionsValStruct(widget) \ +#define waveformSelectionsValStruct(widget) \ ((widget)->waveform.selections_val_struct) #define waveformSelectionsValPtr(widget) ((widget)->waveform.selections_val_ptr) #define waveformPenDownValue(widget) ((widget)->waveform.pen_down) -#define waveformPenDownValStruct(widget) \ +#define waveformPenDownValStruct(widget) \ ((widget)->waveform.pen_down_val_struct) #define waveformPenDownValPtr(widget) ((widget)->waveform.pen_down_val_ptr) #define waveformPanning(widget) ((widget)->waveform.panning) #define waveformPixmap(widget) ((widget)->waveform.pixmap) #define waveformDrawable(widget) ((widget)->waveform.drawable) #define waveformFontStruct(widget) ((widget)->waveform.font_struct) -#define waveformCrosshairsPix(widget) \ +#define waveformCrosshairsPix(widget) \ ((widget)->waveform.cross_box.crosshairs_pix) #define waveformBoxPix(widget) ((widget)->waveform.cross_box.rectangle) #define waveformPanWith(widget) ((widget)->waveform.pan_with) @@ -152,7 +152,12 @@ Widget XmdsCreateWaveform( parent, name, args, argcount ) Local variables: */ static float height_page; -enum crosshairsmode { move_xh, first_xh, last_xh }; +enum crosshairsmode +{ + move_xh, + first_xh, + last_xh +}; static void ClassPartInitialize(); static void Initialize(); @@ -429,15 +434,17 @@ static float resinc; Executable: */ EXPORT Widget XmdsCreateWaveform(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ return XtCreateWidget(name, xmdsWaveformWidgetClass, parent, args, argcount); } -static void ClassPartInitialize(XmdsWaveformWidgetClass class) { -#define initTrans(field, deftrans) \ - if (field == XmdsInheritTranslations) \ - field = XtParseTranslationTable(deftrans); \ - else \ +static void ClassPartInitialize(XmdsWaveformWidgetClass class) +{ +#define initTrans(field, deftrans) \ + if (field == XmdsInheritTranslations) \ + field = XtParseTranslationTable(deftrans); \ + else \ field = XtParseTranslationTable((const char *)field) initTrans(class->waveform_class.default_trans, @@ -470,7 +477,8 @@ static void ClassPartInitialize(XmdsWaveformWidgetClass class) { } static void Initialize(XmdsWaveformWidget req, XmdsWaveformWidget w, - ArgList args, Cardinal *num_args) { + ArgList args, Cardinal *num_args) +{ XGCValues values; static char dashes[] = {1, 4}; xMin(w) = xMax(w) = yMin(w) = yMax(w) = (XtPointer)NULL; @@ -515,9 +523,11 @@ static void Initialize(XmdsWaveformWidget req, XmdsWaveformWidget w, } static void VisibilityChange(XmdsWaveformWidget w, XtPointer dummy, - XVisibilityEvent *event) { + XVisibilityEvent *event) +{ if (event->state == VisibilityUnobscured || - event->state == VisibilityPartiallyObscured) { + event->state == VisibilityPartiallyObscured) + { XtRemoveEventHandler((Widget)w, VisibilityChangeMask, False, (void (*)())VisibilityChange, dummy); ForceUpdate(w); @@ -525,24 +535,29 @@ static void VisibilityChange(XmdsWaveformWidget w, XtPointer dummy, } static void Realize(XmdsWaveformWidget w, XtValueMask *mask, - XSetWindowAttributes *attr) { + XSetWindowAttributes *attr) +{ *mask |= CWBackingStore; attr->backing_store = XDoesBackingStore(XtScreen(w->core.parent)) == Always ? Always : 0; (*xmPrimitiveClassRec.core_class.realize)((Widget)w, mask, attr); - if (attr->backing_store != Always) { + if (attr->backing_store != Always) + { waveformPixmap(w) = waveformDrawable(w) = XCreatePixmap(XtDisplay(w), XtWindow(w), XtWidth(w), XtHeight(w), XDefaultDepthOfScreen(XtScreen(w))); waveformRedraw(w) = True; ForceUpdate(w); - } else + } + else waveformDrawable(w) = XtWindow(w); } -static void Redisplay(XmdsWaveformWidget w, XExposeEvent *event) { +static void Redisplay(XmdsWaveformWidget w, XExposeEvent *event) +{ XEvent ev; - if (event) { + if (event) + { /* XEvent visibility_event; if @@ -556,7 +571,8 @@ static void Redisplay(XmdsWaveformWidget w, XExposeEvent *event) { */ while (XCheckWindowEvent(XtDisplay(w), XtWindow(w), ExposureMask, &ev)) event = (XExposeEvent *)&ev; - if (XtIsRealized((Widget)w) && XtIsManaged((Widget)w)) { + if (XtIsRealized((Widget)w) && XtIsManaged((Widget)w)) + { if (waveformPixmap(w) && !waveformRedraw(w)) XCopyArea(XtDisplay(w), waveformPixmap(w), XtWindow(w), waveformPlotGC(w), 0, 0, XtWidth(w), XtHeight(w), 0, 0); @@ -570,14 +586,18 @@ static void Redisplay(XmdsWaveformWidget w, XExposeEvent *event) { /* } */ - } else { + } + else + { Plot(w, 1); SetCursor(w); } } -static void Resize(XmdsWaveformWidget w) { - if (waveformPixmap(w)) { +static void Resize(XmdsWaveformWidget w) +{ + if (waveformPixmap(w)) + { XFreePixmap(XtDisplay(w), waveformPixmap(w)); waveformPixmap(w) = waveformDrawable(w) = XCreatePixmap(XtDisplay(w), XtWindow(w), XtWidth(w), XtHeight(w), @@ -592,21 +612,24 @@ static void Resize(XmdsWaveformWidget w) { */ } -static void Destroy(XmdsWaveformWidget w) { +static void Destroy(XmdsWaveformWidget w) +{ if (waveformTitle(w)) XtFree(waveformTitle(w)); if (waveformPixmap(w)) XFreePixmap(XtDisplay(w), waveformPixmap(w)); FreePixVals(w); -#define destroyVal(field) \ - if (field##ValStruct(w)) { \ - if (field##ValStruct(w)->destroy) { \ - (*field##ValStruct(w)->destroy)(w, field##ValStruct(w)->destroy_arg); \ - } \ - XtFree((char *)field##ValStruct(w)); \ - } \ - if (field##ValPtr(w)) \ +#define destroyVal(field) \ + if (field##ValStruct(w)) \ + { \ + if (field##ValStruct(w)->destroy) \ + { \ + (*field##ValStruct(w)->destroy)(w, field##ValStruct(w)->destroy_arg); \ + } \ + XtFree((char *)field##ValStruct(w)); \ + } \ + if (field##ValPtr(w)) \ XtFree((char *)field##ValPtr(w)); destroyVal(y); @@ -619,16 +642,20 @@ static void Destroy(XmdsWaveformWidget w) { XtReleaseGC((Widget)w, waveformEraseGC(w)); } -static void Pan(XmdsWaveformWidget w, XButtonEvent *event) { +static void Pan(XmdsWaveformWidget w, XButtonEvent *event) +{ XEvent ev; XmdsWaveformWidget pan_w; while (XCheckMaskEvent(XtDisplay(w), Button2MotionMask, &ev)) event = (XButtonEvent *)&ev; - for (pan_w = w; pan_w; pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) { - if (waveformCount(pan_w)) { + for (pan_w = w; pan_w; pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) + { + if (waveformCount(pan_w)) + { if (event->state & Button2Mask) yMotion(pan_w) = event->y; - if (waveformPanning(pan_w)) { + if (waveformPanning(pan_w)) + { XmdsWaveformLimitsCBStruct limits = {XmdsCRDrag, 0, 0, 0, 0, 0}; float delta_x = ((*xMin(pan_w) - *xMax(pan_w)) / (float)XtWidth(pan_w)) * @@ -659,7 +686,9 @@ static void Pan(XmdsWaveformWidget w, XButtonEvent *event) { *yMin(pan_w) = min(huge, max(-huge, *yMin(pan_w))); *yMax(pan_w) = min(huge, max(-huge, *yMax(pan_w))); Plot(pan_w, 0); - } else { + } + else + { waveformPanning(pan_w) = 1; xMotion(pan_w) = event->x; yMotion(pan_w) = event->y; @@ -672,11 +701,15 @@ static void Pan(XmdsWaveformWidget w, XButtonEvent *event) { } } -static void PanEnd(XmdsWaveformWidget w, XButtonEvent *event) { +static void PanEnd(XmdsWaveformWidget w, XButtonEvent *event) +{ XmdsWaveformWidget pan_w; - for (pan_w = w; pan_w; pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) { - if (waveformCount(pan_w)) { - if (event->state & ShiftMask) { + for (pan_w = w; pan_w; pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) + { + if (waveformCount(pan_w)) + { + if (event->state & ShiftMask) + { XmdsWaveformLimitsCBStruct limits = {XmdsCRDragEnd, 0, 0, 0, 0, 0}; limits.event = (XEvent *)event; limits.xminval = xMin(pan_w); @@ -693,10 +726,13 @@ static void PanEnd(XmdsWaveformWidget w, XButtonEvent *event) { waveformPanning(pan_w) = 0; SetResolutions(pan_w); Plot(pan_w, 1); - } else { + } + else + { if (event->state & Button2Mask) yMotion(pan_w) = event->y; - if (waveformPanning(pan_w)) { + if (waveformPanning(pan_w)) + { XmdsWaveformLimitsCBStruct limits = {XmdsCRDragEnd, 0, 0, 0, 0, 0}; float delta_x = ((*xMin(pan_w) - *xMax(pan_w)) / (float)XtWidth(pan_w)) * @@ -733,9 +769,12 @@ static void PanEnd(XmdsWaveformWidget w, XButtonEvent *event) { } } -static void DragZoom(XmdsWaveformWidget w, XButtonEvent *event) { - if (waveformCount(w)) { - if (waveformPanning(w)) { +static void DragZoom(XmdsWaveformWidget w, XButtonEvent *event) +{ + if (waveformCount(w)) + { + if (waveformPanning(w)) + { DrawRectangles(XtDisplay(w), XtWindow(w), waveformFlipGC(w), waveformBoxPix(w), 1, XtWidth(w), XtHeight(w)); waveformBoxPix(w)[0].x = min(xMotion(w), event->x); @@ -747,7 +786,9 @@ static void DragZoom(XmdsWaveformWidget w, XButtonEvent *event) { if (((max(xMotion(w), event->x) - min(xMotion(w), event->x)) > 2) || ((max(yMotion(w), event->y) - min(yMotion(w), event->y)) > 2)) waveformPanning(w) = 2; - } else { + } + else + { xMotion(w) = event->x; yMotion(w) = event->y; waveformBoxPix(w)[0].x = 0; @@ -759,15 +800,19 @@ static void DragZoom(XmdsWaveformWidget w, XButtonEvent *event) { } } -static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { +static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) +{ if (!waveformCount(w)) return; if (waveformPanning(w) == 2 && ((max(xMotion(w), event->x) - min(xMotion(w), event->x)) < 5) && - ((max(yMotion(w), event->y) - min(yMotion(w), event->y)) < 5)) { + ((max(yMotion(w), event->y) - min(yMotion(w), event->y)) < 5)) + { waveformPanning(w) = 0; Plot(w, 1); - } else { + } + else + { XmdsWaveformLimitsCBStruct limits = {0, 0, 0, 0, 0, 0}; double xspan = *xMax(w) - *xMin(w); double xbase = *xMin(w); @@ -782,7 +827,8 @@ static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { limits.xmaxval = xMax(w); limits.yminval = yMin(w); limits.ymaxval = yMax(w); - if (waveformPanning(w) == 2) { + if (waveformPanning(w) == 2) + { limits.reason = XmdsCRBoxZoom; *xMin(w) = xbase + min(xMotion(w), event->x) * (xspan / XtWidth(w)); *xMax(w) = xbase + max(xMotion(w), event->x) * (xspan / XtWidth(w)); @@ -793,7 +839,9 @@ static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { ybase + (double)(XtHeight(w) - (double)min(yMotion(w), event->y)) * (yspan / XtHeight(w)); waveformPanning(w) = 0; - } else { + } + else + { limits.reason = XmdsCRZoomIn; *xMin(w) = xbase + (event->x - .25 * XtWidth(w)) * (xspan / XtWidth(w)); *xMax(w) = xbase + (event->x + .25 * XtWidth(w)) * (xspan / XtWidth(w)); @@ -802,11 +850,13 @@ static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { ybase + (1.25 * XtHeight(w) - event->y) * (yspan / XtHeight(w)); waveformPanning(w) = 0; } - if ((*xMin(w) >= *xMax(w)) || (*xMin(w) < -huge) || (*xMax(w) > huge)) { + if ((*xMin(w) >= *xMax(w)) || (*xMin(w) < -huge) || (*xMax(w) > huge)) + { *xMin(w) = xmin_save; *xMax(w) = xmax_save; } - if ((*yMin(w) >= *yMax(w)) || (*yMin(w) < -huge) || (*yMax(w) > huge)) { + if ((*yMin(w) >= *yMax(w)) || (*yMin(w) < -huge) || (*yMax(w) > huge)) + { *yMin(w) = ymin_save; *yMax(w) = ymax_save; } @@ -819,11 +869,14 @@ static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { Plot(w, 1); XWarpPointer(XtDisplay(w), None, XtWindow(w), event->x, event->y, XtWidth(w), XtHeight(w), XtWidth(w) / 2, XtHeight(w) / 2); - if (event->state & ShiftMask) { + if (event->state & ShiftMask) + { XmdsWaveformWidget pan_w; for (pan_w = (XmdsWaveformWidget)waveformPanWith(w); pan_w; - pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) { - if (waveformCount(pan_w)) { + pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) + { + if (waveformCount(pan_w)) + { XmdsWaveformLimitsCBStruct limits = {XmdsCRZoomIn, 0, 0, 0, 0, 0}; limits.event = (XEvent *)event; limits.xminval = xMin(pan_w); @@ -849,7 +902,8 @@ static void ZoomIn(XmdsWaveformWidget w, XButtonEvent *event) { } } -static void ZoomOut(XmdsWaveformWidget w, XButtonEvent *event) { +static void ZoomOut(XmdsWaveformWidget w, XButtonEvent *event) +{ XmdsWaveformLimitsCBStruct limits = {XmdsCRZoomOut, 0, 0, 0, 0, 0}; double xspan = *xMax(w) - *xMin(w); double xbase = *xMin(w); @@ -881,11 +935,14 @@ static void ZoomOut(XmdsWaveformWidget w, XButtonEvent *event) { Plot(w, 1); XWarpPointer(XtDisplay(w), None, XtWindow(w), event->x, event->y, XtWidth(w), XtHeight(w), XtWidth(w) / 2, XtHeight(w) / 2); - if (event->state & ShiftMask) { + if (event->state & ShiftMask) + { XmdsWaveformWidget pan_w; for (pan_w = (XmdsWaveformWidget)waveformPanWith(w); pan_w; - pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) { - if (waveformCount(pan_w)) { + pan_w = (XmdsWaveformWidget)waveformPanWith(pan_w)) + { + if (waveformCount(pan_w)) + { XmdsWaveformLimitsCBStruct limits = {XmdsCRZoomOut, 0, 0, 0, 0, 0}; limits.event = (XEvent *)event; limits.xminval = xMin(pan_w); @@ -910,7 +967,8 @@ static void ZoomOut(XmdsWaveformWidget w, XButtonEvent *event) { } } -static void Point(XmdsWaveformWidget w, XButtonEvent *event) { +static void Point(XmdsWaveformWidget w, XButtonEvent *event) +{ XEvent ev; XmdsWaveformCrosshairsCBStruct crosshair = {XmdsCRCrosshairs, 0, 0, 0}; float x, y; @@ -932,7 +990,8 @@ static void Point(XmdsWaveformWidget w, XButtonEvent *event) { XtCallCallbacks((Widget)w, XmdsNcrosshairsCallback, &crosshair); } -static void Align(XmdsWaveformWidget w, XButtonEvent *event) { +static void Align(XmdsWaveformWidget w, XButtonEvent *event) +{ XmdsWaveformLimitsCBStruct limits = {XmdsCRAlign, 0, 0, 0, 0, 0}; limits.event = (XEvent *)event; limits.xminval = xMin(w); @@ -946,7 +1005,8 @@ static void Align(XmdsWaveformWidget w, XButtonEvent *event) { static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, XmdsWaveformWidget new, ArgList args, - Cardinal *num_args) { + Cardinal *num_args) +{ Boolean values_changed = SetupXandY(old, req, new); Boolean limits_changed = UpdateLimits(old, xMin(req), xMax(req), yMin(req), yMax(req), new); @@ -962,7 +1022,8 @@ static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, waveformPanning(new) = 0; FreePixVals(new); - if (waveformFontStruct(old) != waveformFontStruct(req)) { + if (waveformFontStruct(old) != waveformFontStruct(req)) + { XGCValues values; static char dashes[] = {1, 4}; values.foreground = XBlackPixelOfScreen(XtScreen(req)); @@ -987,7 +1048,8 @@ static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, waveformFlipGC(new) = XtGetGC((Widget) new, GCFunction | GCPlaneMask | GCFont, &values); } - if (waveformPointerMode(old) != waveformPointerMode(req)) { + if (waveformPointerMode(old) != waveformPointerMode(req)) + { if (waveformPointerMode(old) == XmdsPOINTER_MODE_POINT) DrawCrosshairs(new, last_xh); else if (waveformPointerMode(new) == XmdsPOINTER_MODE_POINT) @@ -998,7 +1060,8 @@ static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, (!(waveformCount(old) && waveformCount(new)))) || (waveformPointerMode(old) != waveformPointerMode(new))) SetTranslations(new); - if (waveformTitle(req) != waveformTitle(old)) { + if (waveformTitle(req) != waveformTitle(old)) + { if (waveformTitle(old) != 0) XtFree(waveformTitle(old)); waveformTitle(new) = @@ -1007,7 +1070,8 @@ static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, if (waveformDisabled(req) ? 0 : (waveformDisabled(old) ? 1 : plot_changed)) Plot(new, 1); else if (!(waveformDisabled(req)) && ((xCrosshair(old) != xCrosshair(req)) || - (yCrosshair(old) != yCrosshair(req)))) { + (yCrosshair(old) != yCrosshair(req)))) + { float float_x = (float)xCrosshair(new); float float_y = (float)yCrosshair(new); SetCrosshairs((Widget) new, &float_x, &float_y, @@ -1016,7 +1080,8 @@ static Boolean SetValues(XmdsWaveformWidget old, XmdsWaveformWidget req, return 0; } -static void FreePixVals(XmdsWaveformWidget w) { +static void FreePixVals(XmdsWaveformWidget w) +{ if (xPixValue(w)) XtFree((char *)xPixValue(w)); if (yPixValue(w)) @@ -1025,7 +1090,8 @@ static void FreePixVals(XmdsWaveformWidget w) { } static void GetPixVals(XmdsWaveformWidget w, Dimension width, - Dimension height) { + Dimension height) +{ FreePixVals(w); xPixValue(w) = (int *)XtCalloc(waveformCount(w), sizeof(*xPixValue(w))); ConvertToPix(waveformCount(w), xMin(w), xMax(w), xValue(w), width, @@ -1047,18 +1113,21 @@ static void GetPixVals(XmdsWaveformWidget w, Dimension width, Boolean pen_down; \ if (is_missing) \ pen_down = 0; \ - else { \ + else \ + { \ int xval = x + xoff; \ int yval = y + yoff; \ this_point.x = xval; \ - if (this_point.x != xval) { \ + if (this_point.x != xval) \ + { \ if (xval < -32768) \ this_point.x = -32768; \ else if (xval > 32767) \ this_point.x = 32767; \ } \ this_point.y = yval; \ - if (this_point.y != yval) { \ + if (this_point.y != yval) \ + { \ if (yval < -32768) \ this_point.y = -32768; \ else if (yval > 32767) \ @@ -1068,25 +1137,31 @@ static void GetPixVals(XmdsWaveformWidget w, Dimension width, ((this_point.y == 32767) || (this_point.y == -32768)); \ pen_down = penDown && !is_missing; \ } \ - if (pen_down || (last_pen_down && idx)) { \ - if (step && pidx) { \ + if (pen_down || (last_pen_down && idx)) \ + { \ + if (step && pidx) \ + { \ points[pidx].x = this_point.x; \ points[pidx].y = points[pidx - 1].y; \ pidx++; \ } \ points[pidx++] = this_point; \ } \ - if (((pidx + 1 >= maxP) || (!pen_down && pidx >= 2))) { \ + if (((pidx + 1 >= maxP) || (!pen_down && pidx >= 2))) \ + { \ DrawLines(XtDisplay(w), waveformDrawable(w), waveformPlotGC(w), points, \ pidx, XtWidth(w), XtHeight(w)); \ - if (pen_down) { \ + if (pen_down) \ + { \ points[0] = points[pidx - 1]; \ pidx = 1; \ - } else \ + } \ + else \ pidx = 0; \ } \ last_pen_down = pen_down; \ - if (!is_missing && (ss || sm)) { \ + if (!is_missing && (ss || sm)) \ + { \ if (ss && selections[idx]) \ recs[ridx].height = sss; \ else if (sm) \ @@ -1095,12 +1170,14 @@ static void GetPixVals(XmdsWaveformWidget w, Dimension width, recs[ridx].height = 0; \ if (waveformPrint) \ recs[ridx].height *= resinc; \ - if (recs[ridx].height) { \ + if (recs[ridx].height) \ + { \ recs[ridx].width = recs[ridx].height; \ recs[ridx].x = this_point.x - recs[ridx].width / 2; \ recs[ridx].y = this_point.y - recs[ridx].height / 2; \ (ridx)++; \ - if (ridx >= maxR) { \ + if (ridx >= maxR) \ + { \ DrawRectangles(XtDisplay(w), waveformDrawable(w), waveformPlotGC(w), \ recs, ridx, XtWidth(w), XtHeight(w)); \ recs[0] = recs[ridx - 1]; \ @@ -1110,16 +1187,19 @@ static void GetPixVals(XmdsWaveformWidget w, Dimension width, } \ } -static void Plot(XmdsWaveformWidget w, Boolean free_mem) { +static void Plot(XmdsWaveformWidget w, Boolean free_mem) +{ waveformRedraw(w) = False; if (!XtIsRealized((Widget)w)) return; - if (!waveformPrint) { + if (!waveformPrint) + { if (w->core.background_pixmap == XtUnspecifiedPixmap) XFillRectangle(XtDisplay(w), waveformDrawable(w), waveformEraseGC(w), 0, 0, XtWidth(w), XtHeight(w)); - else { + else + { int x, y; unsigned long root; unsigned int width = 0, height = 0, bw, depth; @@ -1133,7 +1213,8 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { XtCallCallbacks((Widget)w, XmdsNunderlayCallback, (void *)waveformDrawable(w)); } - if (waveformCount(w)) { + if (waveformCount(w)) + { if (xPixValue(w) == 0 || yPixValue(w) == 0) GetPixVals(w, XtWidth(w), XtHeight(w)); { @@ -1167,20 +1248,24 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { int maxR = max_req / sizeof(XRectangle) > recsPerIo ? recsPerIo : max_req / sizeof(XRectangle); - if (waveformPanning(w) > 0) { + if (waveformPanning(w) > 0) + { int j; int pix; int xmin = -xoff; int xmax = XtWidth(w) - xoff; for (i = 0; (xp[i] < xmin) && (i < count); i++) ; - if (i != count) { + if (i != count) + { j = i ? i - 1 : 0; if (pd && ((waveformShowMode(w) == XmdsSHOW_MODE_LINE) || - (waveformShowMode(w) == XmdsSHOW_MODE_BOTH))) { + (waveformShowMode(w) == XmdsSHOW_MODE_BOTH))) + { LoadPoint(j, pd[j]); LoadPoint(i, pd[i]); - for (pix = xmin; pix < xmax; pix = max(pix + 1, xp[i])) { + for (pix = xmin; pix < xmax; pix = max(pix + 1, xp[i])) + { for (i++; xp[i] < pix && i < count; i++) ; if (i == count) @@ -1189,12 +1274,15 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { } i = i < count ? i : count - 1; LoadPoint(i, pd[i]); - } else { + } + else + { Boolean pd = ((waveformShowMode(w) == XmdsSHOW_MODE_LINE) || (waveformShowMode(w) == XmdsSHOW_MODE_BOTH)); LoadPoint(j, pd); LoadPoint(i, pd); - for (pix = xmin; pix < xmax; pix = max(pix + 1, xp[i])) { + for (pix = xmin; pix < xmax; pix = max(pix + 1, xp[i])) + { for (i++; xp[i] < pix && i < count; i++) ; if (i == count) @@ -1205,14 +1293,19 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { LoadPoint(i, pd); } } - } else { + } + else + { if (pd && ((waveformShowMode(w) == XmdsSHOW_MODE_LINE) || - (waveformShowMode(w) == XmdsSHOW_MODE_BOTH))) { + (waveformShowMode(w) == XmdsSHOW_MODE_BOTH))) + { for (i = 0; i < count; i++) LoadPoint(i, pd[i]); if (waveformClosed(w)) LoadPoint(0, pd[0]); - } else { + } + else + { Boolean pd = ((waveformShowMode(w) == XmdsSHOW_MODE_LINE) || (waveformShowMode(w) == XmdsSHOW_MODE_BOTH)); for (i = 0; i < count; i++) @@ -1226,12 +1319,14 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { if (free_mem) FreePixVals(w); } - if (!waveformPanning(w)) { + if (!waveformPanning(w)) + { DrawGrid(w); if (waveformPointerMode(w) == XmdsPOINTER_MODE_POINT && !waveformPrint) DrawCrosshairs(w, first_xh); } - if (!waveformPrint) { + if (!waveformPrint) + { XtCallCallbacks((Widget)w, XmdsNoverlayCallback, (void *)waveformDrawable(w)); if (waveformReverse(w)) @@ -1244,7 +1339,8 @@ static void Plot(XmdsWaveformWidget w, Boolean free_mem) { } static void Flush(XmdsWaveformWidget w, XPoint *points, int numpoints, - XRectangle *recs, int numrecs) { + XRectangle *recs, int numrecs) +{ if (numpoints >= 2) DrawLines(XtDisplay(w), waveformDrawable(w), waveformPlotGC(w), points, numpoints, XtWidth(w), XtHeight(w)); @@ -1253,7 +1349,8 @@ static void Flush(XmdsWaveformWidget w, XPoint *points, int numpoints, numrecs, XtWidth(w), XtHeight(w)); } -static void DrawGrid(XmdsWaveformWidget w) { +static void DrawGrid(XmdsWaveformWidget w) +{ int xlines = 0; float xfirst; float xinc; @@ -1271,13 +1368,16 @@ static void DrawGrid(XmdsWaveformWidget w) { Boolean toosmall = width < 100 || height < 40; if (!XtIsRealized((Widget)w) || toosmall) return; - if (waveformCount(w)) { - if (xGridLines(w)) { + if (waveformCount(w)) + { + if (xGridLines(w)) + { GridScaling(*xMin(w), *xMax(w), xGridLines(w), (int)XtWidth(w), &xlines, &xfirst, &xinc, &xfirstv, &xvinc); { float *line = (float *)XtMalloc(xlines * sizeof(float) * 4); - for (i = 0; i < xlines * 4; i = i + 4) { + for (i = 0; i < xlines * 4; i = i + 4) + { line[i] = line[i + 1] = xfirst + i / 4 * xinc; line[i + 2] = 0; line[i + 3] = waveformGridStyle(w) == XmdsGRID_STYLE_TICKS @@ -1289,8 +1389,10 @@ static void DrawGrid(XmdsWaveformWidget w) { ? waveformPlotGC(w) : waveformGridGC(w), line, xlines); - if (waveformGridStyle(w) == XmdsGRID_STYLE_TICKS) { - for (i = 0; i < xlines * 4; i = i + 4) { + if (waveformGridStyle(w) == XmdsGRID_STYLE_TICKS) + { + for (i = 0; i < xlines * 4; i = i + 4) + { line[i] = line[i + 1] = xfirst + i / 4 * xinc; line[i + 2] = height - XtHeight(w) * .02; line[i + 3] = height; @@ -1301,12 +1403,14 @@ static void DrawGrid(XmdsWaveformWidget w) { XtFree((char *)line); } } - if (yGridLines(w)) { + if (yGridLines(w)) + { GridScaling(*yMin(w), *yMax(w), yGridLines(w), (int)XtHeight(w), &ylines, &yfirst, &yinc, &yfirstv, &yvinc); { float *line = (float *)XtMalloc(ylines * sizeof(float) * 4); - for (i = 0; i < ylines * 4; i = i + 4) { + for (i = 0; i < ylines * 4; i = i + 4) + { line[i] = 0; line[i + 1] = waveformGridStyle(w) == XmdsGRID_STYLE_TICKS ? XtWidth(w) * .02 @@ -1318,8 +1422,10 @@ static void DrawGrid(XmdsWaveformWidget w) { ? waveformPlotGC(w) : waveformGridGC(w), line, ylines); - if (waveformGridStyle(w) == XmdsGRID_STYLE_TICKS) { - for (i = 0; i < ylines * 4; i = i + 4) { + if (waveformGridStyle(w) == XmdsGRID_STYLE_TICKS) + { + for (i = 0; i < ylines * 4; i = i + 4) + { line[i] = width - XtWidth(w) * .02; line[i + 1] = width; line[i + 2] = line[i + 3] = height - (yfirst + i / 4 * yinc); @@ -1330,8 +1436,10 @@ static void DrawGrid(XmdsWaveformWidget w) { XtFree((char *)line); } } - if (xLabels(w)) { - for (i = 0; i < xlines; i++) { + if (xLabels(w)) + { + for (i = 0; i < xlines; i++) + { float x = xfirst + i * xinc, twidth; double value = Round(xfirstv + i * xvinc, xResolution(w)); int length = 0; @@ -1347,8 +1455,10 @@ static void DrawGrid(XmdsWaveformWidget w) { (float)(XtHeight(w) - 2.), label, length); } } - if (yLabels(w)) { - for (i = 0; i < ylines; i++) { + if (yLabels(w)) + { + for (i = 0; i < ylines; i++) + { float y = XtHeight(w) - (yfirst + i * yinc); double value = Round(yfirstv + i * yvinc, yResolution(w)); int length = 0; @@ -1373,7 +1483,8 @@ static void DrawGrid(XmdsWaveformWidget w) { } } } - if (waveformTitle(w)) { + if (waveformTitle(w)) + { char *tptr; char *eptr; int line; @@ -1382,7 +1493,8 @@ static void DrawGrid(XmdsWaveformWidget w) { waveformFontStruct(w)->max_bounds.descent + 2; float lasty = -1E20; for (line = 0, tptr = waveformTitle(w), eptr = tptr + strlen(tptr); - tptr < eptr; tptr += (length + 1), line++) { + tptr < eptr; tptr += (length + 1), line++) + { char *lf = strchr(tptr, '\n'); int twidth; float x; @@ -1416,7 +1528,8 @@ static void DrawGrid(XmdsWaveformWidget w) { static void GridScaling(float min_in, float max_in, int divisions_in, int width, int *divisions_out, float *first_pix, float *pix_inc, - float *first_val, float *val_inc) { + float *first_val, float *val_inc) +{ float divlog; float grid; double power10; @@ -1435,11 +1548,14 @@ static void GridScaling(float min_in, float max_in, int divisions_in, int width, pow(10.0, ((divlog < 0) ? -log10(intinc) : log10(intinc)) + power10); grid = ceil(min_in / (*val_inc)) * (*val_inc); *divisions_out = floor((max_in - grid + (*val_inc)) / (*val_inc)); - if (max_in > min_in) { + if (max_in > min_in) + { *first_pix = width * ((grid - min_in) / (max_in - min_in)); *pix_inc = width * ((*val_inc) / (max_in - min_in)); *first_val = (*first_pix * ((max_in - min_in) / width)) + min_in; - } else { + } + else + { *divisions_out = 2; *first_pix = 0; *pix_inc = width; @@ -1449,27 +1565,35 @@ static void GridScaling(float min_in, float max_in, int divisions_in, int width, return; } -static void RemoveZeroes(char *string, int *length) { +static void RemoveZeroes(char *string, int *length) +{ int i; int done = 0; - while (!done) { + while (!done) + { done = 1; - for (i = *length; i > 0; i--) { + for (i = *length; i > 0; i--) + { if (((string[i] == 'e') && (string[i + 1] == '0')) || ((string[i] == '-') && (string[i + 1] == '0')) || - ((string[i] == '+') && (string[i + 1] == '0'))) { + ((string[i] == '+') && (string[i + 1] == '0'))) + { int j; for (j = i + 1; j < *length; j++) string[j] = string[j + 1]; (*length)--; done = 0; - } else if ((string[i] == '0') && (string[i + 1] == 'e')) { + } + else if ((string[i] == '0') && (string[i + 1] == 'e')) + { int j; for (j = i; j < *length; j++) string[j] = string[j + 1]; (*length)--; done = 0; - } else if ((string[i] == '.') && (string[i + 1] == 'e')) { + } + else if ((string[i] == '.') && (string[i + 1] == 'e')) + { int j; for (j = i; j < *length; j++) string[j] = string[j + 1]; @@ -1480,11 +1604,14 @@ static void RemoveZeroes(char *string, int *length) { return; } -static void DrawCrosshairs(XmdsWaveformWidget w, enum crosshairsmode mode) { - if (xMax(w) && xMin(w) && yMax(w) && yMin(w)) { +static void DrawCrosshairs(XmdsWaveformWidget w, enum crosshairsmode mode) +{ + if (xMax(w) && xMin(w) && yMax(w) && yMin(w)) + { float xspan = *xMax(w) - *xMin(w); float yspan = *yMax(w) - *yMin(w); - if (xspan > 0 && yspan > 0) { + if (xspan > 0 && yspan > 0) + { unsigned short xpix = max(0, min(XtWidth(w), (xCrosshair(w) - *xMin(w)) * (XtWidth(w) / xspan)) + .499999); @@ -1510,8 +1637,10 @@ static void DrawCrosshairs(XmdsWaveformWidget w, enum crosshairsmode mode) { crosshairs[3].x2 = XtWidth(w); crosshairs[3].y2 = ypix; - if (XtIsRealized((Widget)w)) { - switch (mode) { + if (XtIsRealized((Widget)w)) + { + switch (mode) + { case move_xh: XDrawSegments(XtDisplay(w), XtWindow(w), waveformFlipGC(w), crosshairs, 4); @@ -1545,13 +1674,15 @@ static void DrawCrosshairs(XmdsWaveformWidget w, enum crosshairsmode mode) { } } -static void WaveformButton3(XmdsWaveformWidget w, XButtonEvent *event) { +static void WaveformButton3(XmdsWaveformWidget w, XButtonEvent *event) +{ XmAnyCallbackStruct cb = {XmdsCRButton3, 0}; cb.event = (XEvent *)event; XtCallCallbacks((Widget)w, XmdsNbutton3Callback, &cb); } -static void WaveformHelp(XmdsWaveformWidget w, XButtonEvent *event) { +static void WaveformHelp(XmdsWaveformWidget w, XButtonEvent *event) +{ XmAnyCallbackStruct cb = {0, 0}; cb.event = (XEvent *)event; XtCallCallbacks((Widget)w, XmNhelpCallback, &cb); @@ -1559,31 +1690,41 @@ static void WaveformHelp(XmdsWaveformWidget w, XButtonEvent *event) { static void ConvertToPix(int num, float *minvalin, float *maxvalin, float *value, unsigned short pixspan, int *pixval, - unsigned int reverse) { + unsigned int reverse) +{ int i; float minval = *minvalin; float maxval = *maxvalin; float span = maxval - minval; int *ival = (int *)value; - if (span) { + if (span) + { float pix_over_span = pixspan / span; - if (value) { - for (i = 0; i < num; i++) { + if (value) + { + for (i = 0; i < num; i++) + { if (ival[i] == roprand) pixval[i] = missing; - else { + else + { float fpixval = (reverse) ? (maxval - value[i]) : (value[i] - minval); - if (pix_over_span > 1E9) { + if (pix_over_span > 1E9) + { fpixval = (fpixval > 1) ? 1.1E9 : ((fpixval < -1) ? -1.1E9 : fpixval * pix_over_span); - } else { + } + else + { fpixval *= pix_over_span; } pixval[i] = fpixval < -1E9 ? -1E9 : (fpixval > 1E9 ? 1E9 : fpixval); } } - } else { + } + else + { if (reverse) for (i = 0; i < num; i++) pixval[i] = @@ -1597,83 +1738,110 @@ static void ConvertToPix(int num, float *minvalin, float *maxvalin, } static void AutoScale(int num, float *value, float *minval, float *maxval, - float *xval, float *minxval, float *maxxval) { + float *xval, float *minxval, float *maxxval) +{ int i; float span; float vmin; float vmax; int *ival = (int *)value; int *ixval = (int *)xval; - if (value) { + if (value) + { vmin = huge; vmax = -huge; - for (i = 0; i < num; i++) { - if ((ival[i] != roprand) && (ixval[i] != roprand)) { - if (vmin > value[i]) { - if (minxval && maxxval) { + for (i = 0; i < num; i++) + { + if ((ival[i] != roprand) && (ixval[i] != roprand)) + { + if (vmin > value[i]) + { + if (minxval && maxxval) + { if (xval[i] >= *minxval && xval[i] <= *maxxval) vmin = value[i]; - } else if (minxval) { + } + else if (minxval) + { if (xval[i] >= *minxval) vmin = value[i]; - } else if (maxxval) { + } + else if (maxxval) + { if (xval[i] <= *maxxval) vmin = value[i]; - } else + } + else vmin = value[i]; } - if (vmax < value[i]) { - if (minxval && maxxval) { + if (vmax < value[i]) + { + if (minxval && maxxval) + { if (xval[i] >= *minxval && xval[i] <= *maxxval) vmax = value[i]; - } else if (minxval) { + } + else if (minxval) + { if (xval[i] >= *minxval) vmax = value[i]; - } else if (maxxval) { + } + else if (maxxval) + { if (xval[i] <= *maxxval) vmax = value[i]; - } else + } + else vmax = value[i]; } } } - if ((minxval || maxxval) && (vmin > vmax)) { + if ((minxval || maxxval) && (vmin > vmax)) + { AutoScale(num, value, minval, maxval, xval, 0, 0); return; } - } else { + } + else + { vmin = 0.; vmax = num - 1; } vmin = max(vmin, -huge); vmax = max(vmin, min(vmax, huge)); - if (vmax == vmin) { + if (vmax == vmin) + { if (vmin == huge) vmin = vmax = 0.0; span = fabs(vmax); if (span <= 0.0) span = 10.0; - } else + } + else span = vmax - vmin; *maxval = vmax + span * .1; *minval = vmin - span * .1; } -static void SetCursor(XmdsWaveformWidget w) { +static void SetCursor(XmdsWaveformWidget w) +{ static Boolean first = 1; static Cursor zoom_cursor; static Cursor drag_cursor; static Cursor point_cursor; static Cursor edit_cursor; - if (first) { + if (first) + { drag_cursor = XCreateFontCursor(XtDisplay(w), XC_fleur); point_cursor = XCreateFontCursor(XtDisplay(w), XC_crosshair); zoom_cursor = XCreateFontCursor(XtDisplay(w), XC_sizing); edit_cursor = XCreateFontCursor(XtDisplay(w), XC_exchange); first = 0; } - if (XtWindow(w)) { - switch (waveformPointerMode(w)) { + if (XtWindow(w)) + { + switch (waveformPointerMode(w)) + { case XmdsPOINTER_MODE_NONE: XUndefineCursor(XtDisplay(w), XtWindow(w)); break; @@ -1693,7 +1861,8 @@ static void SetCursor(XmdsWaveformWidget w) { } } -static void SetTranslations(XmdsWaveformWidget w) { +static void SetTranslations(XmdsWaveformWidget w) +{ Arg arglist[] = {{XmNtranslations, 0}}; int mode = (waveformPointerMode(w) == XmdsPOINTER_MODE_USER) ? XmdsPOINTER_MODE_USER @@ -1701,7 +1870,8 @@ static void SetTranslations(XmdsWaveformWidget w) { ? XmdsPOINTER_MODE_EDIT : (waveformCount(w) ? waveformPointerMode(w) : XmdsPOINTER_MODE_NONE)); - switch (mode) { + switch (mode) + { case XmdsPOINTER_MODE_USER: break; case XmdsPOINTER_MODE_NONE: @@ -1732,10 +1902,12 @@ static void SetTranslations(XmdsWaveformWidget w) { } } -static void SetResolutions(XmdsWaveformWidget w) { +static void SetResolutions(XmdsWaveformWidget w) +{ float divlog; if (xMin(w) && xMax(w) && yMin(w) && yMax(w) && (*xMin(w) < *xMax(w)) && - (*yMin(w) < *yMax(w))) { + (*yMin(w) < *yMax(w))) + { divlog = log10(*xMax(w) - *xMin(w)); xResolution(w) = pow(10.0, (divlog < 0 ? ceil(divlog) : floor(divlog)) - 4); divlog = log10(*yMax(w) - *yMin(w)); @@ -1743,18 +1915,22 @@ static void SetResolutions(XmdsWaveformWidget w) { } } -static double Round(double value, double resolution) { +static double Round(double value, double resolution) +{ return (resolution > 0) ? floor(value / resolution + .4999999) * resolution : value; } static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, - XmdsWaveformWidget new) { + XmdsWaveformWidget new) +{ /* Macros used in this routine only */ #define destroyValStructIfChanged(field) \ - if (field##ValStruct(req) != field##ValStruct(old)) { \ - if (field##ValStruct(old)) { \ + if (field##ValStruct(req) != field##ValStruct(old)) \ + { \ + if (field##ValStruct(old)) \ + { \ if (field##ValStruct(old)->destroy) \ (*field##ValStruct(old)->destroy)(old, \ field##ValStruct(old)->destroy_arg); \ @@ -1763,29 +1939,36 @@ static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, changed = TRUE; \ } -#define updateValStruct(field, type, minsize) \ - if (((!old) || (field##ValStruct(req) != field##ValStruct(old))) && \ - field##ValStruct(req)) { \ - field##ValStruct(new) = (XmdsWaveformValStruct *)memcpy( \ - XtNew(XmdsWaveformValStruct), field##ValStruct(req), \ - sizeof(XmdsWaveformValStruct)); \ - waveformCount(new) = \ - min((int)(field##ValStruct(req)->size / sizeof(type)), (minsize)); \ - field##Value(new) = (type *)field##ValStruct(req)->addr; \ - field##ValPtr(new) = (type *)NULL; \ - changed = TRUE; \ +#define updateValStruct(field, type, minsize) \ + if (((!old) || (field##ValStruct(req) != field##ValStruct(old))) && \ + field##ValStruct(req)) \ + { \ + field##ValStruct(new) = (XmdsWaveformValStruct *)memcpy( \ + XtNew(XmdsWaveformValStruct), field##ValStruct(req), \ + sizeof(XmdsWaveformValStruct)); \ + waveformCount(new) = \ + min((int)(field##ValStruct(req)->size / sizeof(type)), (minsize)); \ + field##Value(new) = (type *)field##ValStruct(req)->addr; \ + field##ValPtr(new) = (type *)NULL; \ + changed = TRUE; \ } #define updateValPtr(field, type) \ - if (field##ValPtr(old) && (field##ValPtr(old) == field##Value(old))) { \ - if (old_count != waveformCount(new)) { \ - if ((field##ValPtr(new) == field##Value(new)) && waveformCount(new)) { \ + if (field##ValPtr(old) && (field##ValPtr(old) == field##Value(old))) \ + { \ + if (old_count != waveformCount(new)) \ + { \ + if ((field##ValPtr(new) == field##Value(new)) && waveformCount(new)) \ + { \ field##Value(new) = (type *)XtRealloc((char *)field##Value(new), \ waveformCount(new) * \ sizeof(*field##Value(new))); \ field##ValPtr(new) = field##Value(new); \ - } else { \ - if (field##ValPtr(new)) { \ + } \ + else \ + { \ + if (field##ValPtr(new)) \ + { \ field##Value(new) = (type *)XtMalloc(waveformCount(new) * \ sizeof(*field##Value(new))); \ memcpy(field##Value(new), field##ValPtr(req), \ @@ -1795,14 +1978,18 @@ static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, XtFree((char *)field##ValPtr(old)); \ } \ changed = TRUE; \ - } else if (field##ValPtr(new) && \ - (field##ValPtr(new) != field##Value(new))) { \ + } \ + else if (field##ValPtr(new) && \ + (field##ValPtr(new) != field##Value(new))) \ + { \ memcpy(field##Value(new), field##ValPtr(req), \ waveformCount(new) * sizeof(*field##Value(new))); \ field##ValPtr(new) = field##Value(new); \ changed = TRUE; \ } \ - } else if (field##ValPtr(new)) { \ + } \ + else if (field##ValPtr(new)) \ + { \ field##Value(new) = \ (type *)XtMalloc(waveformCount(new) * sizeof(*field##Value(new))); \ memcpy(field##Value(new), field##ValPtr(req), \ @@ -1811,19 +1998,21 @@ static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, changed = TRUE; \ } -#define initializeValPtr(field, type) \ - if (field##ValPtr(new)) { \ - field##Value(new) = \ - (type *)XtMalloc(waveformCount(new) * sizeof(*field##Value(new))); \ - memcpy(field##Value(new), field##ValPtr(req), \ - waveformCount(new) * sizeof(*field##Value(new))); \ - field##ValPtr(new) = field##Value(new); \ - changed = TRUE; \ +#define initializeValPtr(field, type) \ + if (field##ValPtr(new)) \ + { \ + field##Value(new) = \ + (type *)XtMalloc(waveformCount(new) * sizeof(*field##Value(new))); \ + memcpy(field##Value(new), field##ValPtr(req), \ + waveformCount(new) * sizeof(*field##Value(new))); \ + field##ValPtr(new) = field##Value(new); \ + changed = TRUE; \ } int old_count = 0; Boolean changed = FALSE; - if (old) { + if (old) + { old_count = waveformCount(old); destroyValStructIfChanged(y); destroyValStructIfChanged(x); @@ -1837,21 +2026,27 @@ static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, /* waveformCount(new) = (waveformCount(new) > 1) ? waveformCount(new) : 0; */ - if (old) { + if (old) + { if (old_count != waveformCount(new)) changed = TRUE; updateValPtr(y, float); updateValPtr(x, float); updateValPtr(waveformSelections, Boolean); updateValPtr(waveformPenDown, Boolean); - } else { - if (waveformCount(new)) { + } + else + { + if (waveformCount(new)) + { changed = TRUE; initializeValPtr(y, float); initializeValPtr(x, float); initializeValPtr(waveformSelections, Boolean); initializeValPtr(waveformPenDown, Boolean); - } else { + } + else + { yValue(new) = yValPtr(new) = 0; xValue(new) = xValPtr(new) = 0; waveformSelectionsValue(new) = waveformSelectionsValPtr(new) = 0; @@ -1864,25 +2059,29 @@ static Boolean SetupXandY(XmdsWaveformWidget old, XmdsWaveformWidget req, EXPORT void XmdsWaveformUpdate(Widget w, XmdsWaveformValStruct *x, XmdsWaveformValStruct *y, char *title, float *xmin, float *xmax, float *ymin, - float *ymax, Boolean defer) { + float *ymax, Boolean defer) +{ (((XmdsWaveformWidgetClass)w->core.widget_class)->waveform_class.update_proc)( w, x, y, title, xmin, xmax, ymin, ymax, defer); } EXPORT void XmdsWaveformSetCrosshairs(Widget w, float *x, float *y, - Boolean attach) { + Boolean attach) +{ (((XmdsWaveformWidgetClass)w->core.widget_class) ->waveform_class.set_crosshairs_proc)(w, x, y, attach); } -EXPORT void XmdsWaveformSetPointerMode(Widget w, int mode) { +EXPORT void XmdsWaveformSetPointerMode(Widget w, int mode) +{ (((XmdsWaveformWidgetClass)w->core.widget_class) ->waveform_class.set_pointer_mode_proc)(w, mode); } EXPORT void XmdsWaveformSetWave(Widget w, int count, float *x, float *y, Boolean *select, Boolean *pendown, - Boolean autoscale, Boolean defer_update) { + Boolean autoscale, Boolean defer_update) +{ (((XmdsWaveformWidgetClass)w->core.widget_class) ->waveform_class.set_wave_proc)(w, count, x, y, select, pendown, autoscale, defer_update); @@ -1891,17 +2090,20 @@ EXPORT void XmdsWaveformSetWave(Widget w, int count, float *x, float *y, static void Update(Widget w_in, XmdsWaveformValStruct *x, XmdsWaveformValStruct *y, char *title, float *xmin, float *xmax, float *ymin, float *ymax, - Boolean defer_update) { + Boolean defer_update) +{ XmdsWaveformWidget w = (XmdsWaveformWidget)w_in; int old_count = waveformCount(w); waveformPanning(w) = 0; FreePixVals(w); - if (xValStruct(w)) { + if (xValStruct(w)) + { if (xValStruct(w)->destroy) (*xValStruct(w)->destroy)(w, xValStruct(w)->destroy_arg); XtFree((char *)xValStruct(w)); } - if (yValStruct(w)) { + if (yValStruct(w)) + { if (yValStruct(w)->destroy) (*yValStruct(w)->destroy)(w, yValStruct(w)->destroy_arg); XtFree((char *)yValStruct(w)); @@ -1933,42 +2135,52 @@ static void Update(Widget w_in, XmdsWaveformValStruct *x, static void SetWave(Widget w_in, int count, float *x, float *y, Boolean *waveformSelections, Boolean *waveformPenDown, - Boolean autoscale, Boolean defer_update) { + Boolean autoscale, Boolean defer_update) +{ XmdsWaveformWidget w = (XmdsWaveformWidget)w_in; int old_count = waveformCount(w); waveformPanning(w) = 0; FreePixVals(w); waveformCount(w) = count; -#define UpdateField(field, type) \ - if (old_count != count) { \ - if (count) { \ - field##Value(w) = \ - (type *)(old_count ? XtRealloc((char *)field##Value(w), \ - count * sizeof(*field##Value(w))) \ - : XtMalloc(count * sizeof(*field##Value(w)))); \ - field##ValPtr(w) = field##Value(w); \ - } else { \ - XtFree((char *)field##ValPtr(w)); \ - field##Value(w) = 0; \ - field##ValPtr(w) = 0; \ - } \ - } \ - if (count) \ +#define UpdateField(field, type) \ + if (old_count != count) \ + { \ + if (count) \ + { \ + field##Value(w) = \ + (type *)(old_count ? XtRealloc((char *)field##Value(w), \ + count * sizeof(*field##Value(w))) \ + : XtMalloc(count * sizeof(*field##Value(w)))); \ + field##ValPtr(w) = field##Value(w); \ + } \ + else \ + { \ + XtFree((char *)field##ValPtr(w)); \ + field##Value(w) = 0; \ + field##ValPtr(w) = 0; \ + } \ + } \ + if (count) \ memcpy(field##ValPtr(w), field, count * sizeof(*field##Value(w))); - if (x) { + if (x) + { UpdateField(x, float); } - if (y) { + if (y) + { UpdateField(y, float); } - if (waveformSelections) { + if (waveformSelections) + { UpdateField(waveformSelections, Boolean); } - if (waveformPenDown) { + if (waveformPenDown) + { UpdateField(waveformPenDown, Boolean); } - if (count && (autoscale || !(xMin(w) && yMin(w) && xMax(w) && yMax(w)))) { + if (count && (autoscale || !(xMin(w) && yMin(w) && xMax(w) && yMax(w)))) + { if (!xMin(w)) xMin(w) = (float *)XtMalloc(sizeof(float *)); if (!xMax(w)) @@ -1987,12 +2199,15 @@ static void SetWave(Widget w_in, int count, float *x, float *y, Plot(w, 1); } -static void SetCrosshairs(Widget w_in, float *x, float *y, Boolean attach) { +static void SetCrosshairs(Widget w_in, float *x, float *y, Boolean attach) +{ XmdsWaveformWidget w = (XmdsWaveformWidget)w_in; - if (waveformCount(w)) { + if (waveformCount(w)) + { xCrosshair(w) = *x; yCrosshair(w) = *y; - if (attach) { + if (attach) + { int *xint = (int *)xValue(w); int *yint = (int *)yValue(w); float *xval = xValue(w); @@ -2002,17 +2217,21 @@ static void SetCrosshairs(Widget w_in, float *x, float *y, Boolean attach) { if ((xint[i] != roprand) && (yint[i] != roprand) && (xCrosshair(w) <= xval[i])) break; - if ((i == 0) || (i == num)) { + if ((i == 0) || (i == num)) + { i = min(i, waveformCount(w) - 1); xCrosshair(w) = xint[i] != roprand ? xValue(w)[i] : 0.0; yCrosshair(w) = yint[i] != roprand ? yValue(w)[i] : 0.0; - } else { + } + else + { if (waveformStepPlot(w)) yCrosshair(w) = yValue( w)[i - ((xCrosshair(w) < xValue(w)[i] && yint[i - 1] != roprand) ? 1 : 0)]; - else { + else + { if (xint[i - 1] == roprand || yint[i - 1] == roprand) yCrosshair(w) = yValue(w)[i]; else @@ -2028,11 +2247,14 @@ static void SetCrosshairs(Widget w_in, float *x, float *y, Boolean attach) { } } -static void SetPointerMode(XmdsWaveformWidget w, int mode) { +static void SetPointerMode(XmdsWaveformWidget w, int mode) +{ int old_mode = waveformPointerMode(w); waveformPointerMode(w) = mode; - if (old_mode != waveformPointerMode(w)) { - if (waveformCount(w)) { + if (old_mode != waveformPointerMode(w)) + { + if (waveformCount(w)) + { if (old_mode == XmdsPOINTER_MODE_POINT) DrawCrosshairs(w, last_xh); else if (waveformPointerMode(w) == XmdsPOINTER_MODE_POINT) @@ -2045,25 +2267,29 @@ static void SetPointerMode(XmdsWaveformWidget w, int mode) { EXPORT void XmdsWaveformPrint(Widget w, FILE *fid, int width, int height, int rotate, char *title, char *window_title, - int inp_resolution) { + int inp_resolution) +{ (((XmdsWaveformWidgetClass)w->core.widget_class)->waveform_class.print_proc)( w, fid, width, height, rotate, title, window_title, inp_resolution); } -static void SetScale(int scaleit) { +static void SetScale(int scaleit) +{ static int scaled = 0; if (scaleit == scaled) return; scaled = scaleit; - if (scaleit) { + if (scaleit) + { fprintf(printfid, "gsave\n"); fprintf(printfid, "%g %g translate\n", 0., 825. * (1. - scale)); /* Grid y values are set to ylimit-y (decwindows y are reversed from postscript), but the ylimit, normally 825, changes due to scale */ fprintf(printfid, "%g %g scale\n", scale, scale); - } else + } + else fprintf(printfid, "grestore\n"); } @@ -2097,13 +2323,19 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, if (printfid == NULL) return; - if (ftell(printfid) == 0) { + if (ftell(printfid) == 0) + { char fontname[80]; - if (inp_rotate == 1) { /* Portrait */ + if (inp_rotate == 1) + { /* Portrait */ rotate = 0; - } else if (inp_rotate == 2) { /* Landscape */ + } + else if (inp_rotate == 2) + { /* Landscape */ rotate = 90; - } else { + } + else + { if (((inp_total_height) ? inp_total_height : XtHeight(w)) >= ((inp_total_width) ? inp_total_width : XtWidth(w))) rotate = 0; @@ -2116,17 +2348,23 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, resinc = resolution / 75.; - if (getenv("A4PAPER") == NULL) { + if (getenv("A4PAPER") == NULL) + { width_page = 8.5; height_page = 11.; - } else { + } + else + { width_page = 8.27; height_page = 11.69; } - if (rotate == 0) { + if (rotate == 0) + { width_limit = (width_page - 2. * margin) * resolution; height_limit = (height_page - 2. * margin) * resolution; - } else { + } + else + { width_limit = (height_page - 2. * margin) * resolution; height_limit = (width_page - 2. * margin) * resolution; } @@ -2164,9 +2402,11 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, fatom = XInternAtom(XtDisplay(w), "FAMILY_NAME", False); if (!fatom) strcpy(fontname, "Courier"); - else { + else + { for (i = 0; i < fs->n_properties; i++) - if (fs->properties[i].name == fatom) { + if (fs->properties[i].name == fatom) + { fontinfo = XGetAtomName(XtDisplay(w), fs->properties[i].card32); break; } @@ -2184,35 +2424,41 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, #pragma GCC diagnostic pop fatom = XInternAtom(XtDisplay(w), "WEIGHT_NAME", False); for (i = 0; i < fs->n_properties; i++) - if (fs->properties[i].name == fatom) { + if (fs->properties[i].name == fatom) + { fontinfo = XGetAtomName(XtDisplay(w), fs->properties[i].card32); break; } if (fontinfo != NULL && strstr(fontinfo, "Bold")) strcat(fontname, "-Bold"); - if (fontinfo != NULL) { + if (fontinfo != NULL) + { XFree(fontinfo); fontinfo = NULL; } fatom = XInternAtom(XtDisplay(w), "FULL_NAME", False); for (i = 0; i < fs->n_properties; i++) - if (fs->properties[i].name == fatom) { + if (fs->properties[i].name == fatom) + { fontinfo = XGetAtomName(XtDisplay(w), fs->properties[i].card32); break; } - if (fontinfo != NULL && strstr(fontinfo, "Italic")) { + if (fontinfo != NULL && strstr(fontinfo, "Italic")) + { if (!strstr(fontname, "-Bold")) strcat(fontname, "-"); strcat(fontname, "Italic"); } - if (fontinfo != NULL && strstr(fontinfo, "Oblique")) { + if (fontinfo != NULL && strstr(fontinfo, "Oblique")) + { if (!strstr(fontname, "-Bold")) strcat(fontname, "-"); strcat(fontname, "Oblique"); } if (!strcmp(fontname, "Times") || !strcmp(fontname, "NewCenturySchlbk")) strcat(fontname, "-Roman"); - if (fontinfo != NULL) { + if (fontinfo != NULL) + { XFree(fontinfo); fontinfo = NULL; } @@ -2244,7 +2490,8 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, 1.5); /* Specify 13 as fontsize (see note on fontsize) */ fprintf(printfid, "setfont\n"); - if (rotate != 0) { + if (rotate != 0) + { float y = XtBorderWidth(w) * scale; if (!inp_total_height) y = -(72. * (height_page - 2. * margin) - height) / 2. - @@ -2261,7 +2508,9 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, /* Scale so bottom of plot still at same place, */ fprintf(printfid, "%g %g scale\n", 1., yscale); fprintf(printfid, "%g %g translate\n", 0., y * (yscale - 1)); - } else { + } + else + { fprintf(printfid, "(%s) %g %g centershow\n", window_title, width_limit * 72. / resolution + 72. * 2. * margin, ury - 1.125 * fontsize); @@ -2289,7 +2538,9 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, fontsize * 1.5 / scale); /* Specify 13 as fontsize (see note on fontsize) */ fprintf(printfid, "setfont\n"); - } else { + } + else + { fseek(printfid, -10, 1); /* rewind past showpage command */ } @@ -2337,7 +2588,8 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, ((!inp_total_height) ? 1. : (int)(XtBorderWidth(w)) * scale); if (inp_total_width && (inp_total_width > XtWidth(w) + 4 || - inp_total_height > XtHeight(w) + 4)) { + inp_total_height > XtHeight(w) + 4)) + { float xtest = xorigin * scale; float ytest = yorigin * scale; @@ -2350,42 +2602,53 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, /* corners and draws them in succession to obtain rounded corners. */ if (xoffset == xtest && intAbs((yoffset / scale + inp_total_height) - - (yorigin + XtHeight(w))) > 5) { + (yorigin + XtHeight(w))) > 5) + { fprintf(printfid, "%g %g moveto\n", xstart, ystart); fprintf(printfid, "%g %g lineto\n", xstart, yend); - if (yoffset == ytest) { + if (yoffset == ytest) + { fprintf(printfid, "%g %g lineto\n", xend, yend); if (intAbs((xoffset / scale + inp_total_width) - (xorigin + XtWidth(w))) < 5) fprintf(printfid, "%g %g lineto\n", xend, ystart); - } else if (intAbs((xoffset / scale + inp_total_width) - - (xorigin + XtWidth(w))) < 5) { + } + else if (intAbs((xoffset / scale + inp_total_width) - + (xorigin + XtWidth(w))) < 5) + { fprintf(printfid, "stroke\n"); fprintf(printfid, "%g %g moveto\n", xend, yend); fprintf(printfid, "%g %g lineto\n", xend, ystart); } fprintf(printfid, "stroke\n"); - } else if (yoffset == ytest && - (xoffset != xtest || - intAbs((yoffset / scale + inp_total_height) - - (yorigin + XtHeight(w))) > 5)) { + } + else if (yoffset == ytest && + (xoffset != xtest || + intAbs((yoffset / scale + inp_total_height) - + (yorigin + XtHeight(w))) > 5)) + { fprintf(printfid, "%g %g moveto\n", xstart, yend); fprintf(printfid, "%g %g lineto\n", xend, yend); if (intAbs((xoffset / scale + inp_total_width) - (xorigin + XtWidth(w))) < - 5) { + 5) + { fprintf(printfid, "%g %g lineto\n", xend, ystart); if (intAbs((yoffset / scale + inp_total_height) - (yorigin + XtHeight(w))) < 5) fprintf(printfid, "%g %g lineto\n", xstart, ystart); - } else if (intAbs((yoffset / scale + inp_total_height) - - (yorigin + XtHeight(w))) < 5) { + } + else if (intAbs((yoffset / scale + inp_total_height) - + (yorigin + XtHeight(w))) < 5) + { fprintf(printfid, "stroke\n"); fprintf(printfid, "%g %g moveto\n", xstart, ystart); fprintf(printfid, "%g %g lineto\n", xend, ystart); } fprintf(printfid, "stroke\n"); - } else if (intAbs((xoffset / scale + inp_total_width) - - (xorigin + XtWidth(w))) < 5) { + } + else if (intAbs((xoffset / scale + inp_total_width) - + (xorigin + XtWidth(w))) < 5) + { fprintf(printfid, "%g %g moveto\n", xend, yend); fprintf(printfid, "%g %g lineto\n", xend, ystart); if (intAbs((yoffset / scale + inp_total_height) - @@ -2394,8 +2657,10 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, if (xoffset == xtest) fprintf(printfid, "%g %g lineto\n", xstart, yend); fprintf(printfid, "stroke\n"); - } else if (intAbs((yoffset / scale + inp_total_height) - - (yorigin + XtHeight(w))) < 5) { + } + else if (intAbs((yoffset / scale + inp_total_height) - + (yorigin + XtHeight(w))) < 5) + { fprintf(printfid, "%g %g moveto\n", xend, ystart); fprintf(printfid, "%g %g lineto\n", xstart, ystart); if (xoffset == xtest) @@ -2431,7 +2696,8 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, SetScale(0); fprintf(printfid, "grestore\n"); /* To clear clipping region */ - if (title && strlen(title)) { + if (title && strlen(title)) + { int length = strlen(title); int twidth = XTextWidth(waveformFontStruct(w), title, length); float x = max(0, ((int)XtWidth(w) - twidth) / 2); @@ -2440,7 +2706,8 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, x + twidth / 2 - XTextWidth(waveformFontStruct(w), title, 1) / 2.; int i; SetScale(1); - for (i = 0; i < length; i++) { + for (i = 0; i < length; i++) + { char c[2]; fprintf(printfid, "%g %g moveto\n", middle + (x - middle) / scale, y); c[0] = title[i]; @@ -2456,9 +2723,11 @@ static void Print(XmdsWaveformWidget w, FILE *filefid, int inp_total_width, } static void DrawLines(Display *display, Window win, GC gc, XPoint *point, - int kp, Dimension pwidth, Dimension pheight) { + int kp, Dimension pwidth, Dimension pheight) +{ static int i, imax, imin, ymax, ymin; - if (!waveformPrint) { + if (!waveformPrint) + { int kpnew = 0; int num_to_left = 0; int num_to_right = 0; @@ -2468,46 +2737,64 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, short max_y = 0; short min_y = 0; short leave_y; - for (i = 0; i < kp; i++) { - if (point[i].x < 0) { + for (i = 0; i < kp; i++) + { + if (point[i].x < 0) + { num_to_right = 0; num_in_middle = 0; - if (num_to_left < 2) { + if (num_to_left < 2) + { point[kpnew].x = point[i].x; point[kpnew++].y = point[i].y; - } else { + } + else + { point[kpnew - 1].x = point[i].x; point[kpnew - 1].y = point[i].y; } num_to_left++; - } else if (point[i].x > pwidth && num_to_right > 0) { + } + else if (point[i].x > pwidth && num_to_right > 0) + { num_to_left = 0; num_in_middle = 0; - if (num_to_right < 2) { + if (num_to_right < 2) + { point[kpnew].x = point[i].x; point[kpnew++].y = point[i].y; - } else { + } + else + { point[kpnew - 1].x = point[i].x; point[kpnew - 1].y = point[i].y; } num_to_right++; - } else { + } + else + { num_to_left = 0; num_to_right = (point[i].x > pwidth) ? 1 : 0; - if (num_in_middle < 1) { + if (num_in_middle < 1) + { point[kpnew].x = lastx = point[i].x; point[kpnew++].y = min_y = max_y = enter_y = leave_y = point[i].y; - } else if (point[i].x == lastx) { + } + else if (point[i].x == lastx) + { leave_y = point[i].y; if (point[i].y < min_y) min_y = point[i].y; else if (point[i].y > max_y) max_y = point[i].y; } - if ((point[i].x != lastx) || (i == kp - 1)) { - if (min_y != max_y) { + if ((point[i].x != lastx) || (i == kp - 1)) + { + if (min_y != max_y) + { switch (((enter_y == min_y) * 1) | ((enter_y == max_y) * 2) | - ((min_y == leave_y) * 4) | ((max_y == leave_y) * 8)) { + ((min_y == leave_y) * 4) | ((max_y == leave_y) * 8)) + { case 0: point[kpnew].x = lastx; point[kpnew++].y = min_y; @@ -2555,7 +2842,9 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, } XDrawLines(display, win, gc, point, kpnew, CoordModeOrigin); return; - } else { + } + else + { int pen_down = 1; int plot; @@ -2564,53 +2853,65 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, SetScale(0); fprintf(printfid, "gsave\n"); fprintf(printfid, "%g %g scale\n", 1. / resinc, 1. / resinc); - for (i = 1; i < kp; i++) { - if (pen_down) { + for (i = 1; i < kp; i++) + { + if (pen_down) + { plot = (point[lastpoint].x != point[i].x || point[lastpoint].y != point[i].y); - if (plot) { + if (plot) + { while (i < kp - 2 && point[i + 1].x == point[i].x && point[i + 1].y == point[i].y) i++; if (point[i + 1].x == point[i].x && - point[lastpoint].x == point[i].x) { + point[lastpoint].x == point[i].x) + { ymin = ymax = point[lastpoint].y; imin = imax = lastpoint; - while (point[i].x == point[i + 1].x && i < kp - 2) { - if (ymax < point[i].y) { + while (point[i].x == point[i + 1].x && i < kp - 2) + { + if (ymax < point[i].y) + { ymax = point[i].y; imax = i; } - if (ymin > point[i].y) { + if (ymin > point[i].y) + { ymin = point[i].y; imin = i; } i++; } - if (ymin < point[i].y && imin != lastpoint) { + if (ymin < point[i].y && imin != lastpoint) + { fprintf(printfid, "%d %d\n", point[lastpoint].x - point[imin].x, point[imin].y - point[lastpoint].y); np++; lastpoint = imin; - if (np == 100) { + if (np == 100) + { fprintf(printfid, "%d %d %d v\n", np, point[lastpoint].x, (int)(height_page * resolution - point[lastpoint].y)); np = 0; } } - if (ymax > point[i].y && imax != lastpoint) { + if (ymax > point[i].y && imax != lastpoint) + { fprintf(printfid, "%d %d \n", point[lastpoint].x - point[imax].x, point[imax].y - point[lastpoint].y); np++; lastpoint = imax; - if (np == 100) { + if (np == 100) + { fprintf(printfid, "%d %d %d v\n", np, point[lastpoint].x, (int)(height_page * resolution - point[lastpoint].y)); np = 0; } } - } else if (point[i + 1].y == point[i].y && - point[lastpoint].y == point[i].y) + } + else if (point[i + 1].y == point[i].y && + point[lastpoint].y == point[i].y) plot = !compare_sign(point[i + 1].x - point[i].x, point[i].x - point[lastpoint].x); else @@ -2621,12 +2922,14 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, (float)(point[i].x - point[lastpoint].x) / (float)(point[i].y - point[lastpoint].y)); } - if (plot) { + if (plot) + { fprintf(printfid, "%d %d\n", point[lastpoint].x - point[i].x, point[i].y - point[lastpoint].y); np++; lastpoint = i; - if (np == 100) { + if (np == 100) + { fprintf(printfid, "%d %d %d v\n", np, point[lastpoint].x, (int)(height_page * resolution - point[lastpoint].y)); np = 0; @@ -2640,8 +2943,10 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, /* Skip lines that occur outside of grid. Algorithm eliminates most, but not all. */ { - if (np) { - if (lastpoint != i) { + if (np) + { + if (lastpoint != i) + { fprintf(printfid, "%d %d\n", point[lastpoint].x - point[i].x, point[i].y - point[lastpoint].y); np++; @@ -2651,7 +2956,9 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, np = 0; } pen_down = 0; - } else if (!pen_down) { + } + else if (!pen_down) + { fprintf(printfid, "%d %d\n", point[i - 1].x - point[i].x, point[i].y - point[i - 1].y); np = 1; @@ -2659,7 +2966,8 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, lastpoint = i; } } - if (np) { + if (np) + { fprintf(printfid, "%d %d %d v\n", np, point[lastpoint].x, (int)(height_page * resolution - point[lastpoint].y)); } @@ -2669,11 +2977,14 @@ static void DrawLines(Display *display, Window win, GC gc, XPoint *point, static void DrawRectangles(Display *display, Window win, GC gc, XRectangle *rectangle, int num, Dimension pwidth, - Dimension pheight) { + Dimension pheight) +{ static int i; - if (!waveformPrint) { + if (!waveformPrint) + { int n = 0; - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { if (((rectangle[i].x + rectangle[i].width) >= 0) && (rectangle[i].x <= pwidth) && ((rectangle[i].y + rectangle[i].height) >= 0) && @@ -2682,11 +2993,14 @@ static void DrawRectangles(Display *display, Window win, GC gc, } XDrawRectangles(display, win, gc, rectangle, n); return; - } else { + } + else + { SetScale(0); fprintf(printfid, "gsave\n"); fprintf(printfid, "%g %g scale\n", 1. / resinc, 1. / resinc); - for (i = 0; i < num; i++) { + for (i = 0; i < num; i++) + { if (((rectangle[i].x >= 0 && rectangle[i].x < width) || (rectangle[i].x + rectangle[i].width >= 0 && rectangle[i].x + rectangle[i].width < width)) && @@ -2714,7 +3028,8 @@ static float offset_dashes_ps; static GC dash_gc; static void SetDashes(Display *display, GC gc, int offset, char *dashes, - int num) { + int num) +{ int i; if (dashes_ps) XtFree((char *)dashes_ps); @@ -2728,11 +3043,14 @@ static void SetDashes(Display *display, GC gc, int offset, char *dashes, } static void DrawSegments(Display *display, Window win, GC gc, float *crosshairs, - int num) { + int num) +{ static int i; - if (!waveformPrint) { + if (!waveformPrint) + { XSegment *line = (XSegment *)XtMalloc(num * sizeof(XSegment)); - for (i = 0; i < num * 4; i = i + 4) { + for (i = 0; i < num * 4; i = i + 4) + { line[i / 4].x1 = crosshairs[i]; line[i / 4].x2 = crosshairs[i + 1]; line[i / 4].y1 = crosshairs[i + 2]; @@ -2741,7 +3059,9 @@ static void DrawSegments(Display *display, Window win, GC gc, float *crosshairs, XDrawSegments(display, win, gc, line, num); XtFree((char *)line); return; - } else { + } + else + { float *dashes = (float *)XtMalloc(num_dashes_ps * sizeof(float)); float offset_dashes = offset_dashes_ps * resinc; fprintf(printfid, "gsave\n"); @@ -2754,7 +3074,8 @@ static void DrawSegments(Display *display, Window win, GC gc, float *crosshairs, XtFree((char *)dashes); fprintf(printfid, "%g %g scale\n", 1. / resinc, 1. / resinc); fprintf(printfid, "%g setlinewidth\n", .25); /* Width for grid lines */ - for (i = 0; i < num * 4; i = i + 4) { + for (i = 0; i < num * 4; i = i + 4) + { fprintf(printfid, "%d %d mv\n", (int)(crosshairs[i] * scale * resinc), (int)(height_page * resolution) - (int)(crosshairs[i + 2] * scale * resinc)); @@ -2769,31 +3090,39 @@ static void DrawSegments(Display *display, Window win, GC gc, float *crosshairs, } static void DrawString(XmdsWaveformWidget w, Display *display, Window win, - GC gc, float x, float y, char *label, int length) { - if (!waveformPrint) { + GC gc, float x, float y, char *label, int length) +{ + if (!waveformPrint) + { int sx = x; int sy = y; XDrawString(display, win, gc, sx, sy, label, length); return; - } else { + } + else + { SetScale(1); if (x < 0) fprintf(printfid, "(%s) %g %g centershow\n", label, -x * 2, 825. - y); - else { + else + { fprintf(printfid, "%g %g moveto\n", x, 825. - y); fprintf(printfid, "(%s) show\n", label); } } } -EXPORT void XmdsWaveformReverse(Widget w, int reverse) { +EXPORT void XmdsWaveformReverse(Widget w, int reverse) +{ (((XmdsWaveformWidgetClass)w->core.widget_class) ->waveform_class.reverse_proc)(w, reverse); } -static void Reverse(Widget w_in, int reverse) { +static void Reverse(Widget w_in, int reverse) +{ XmdsWaveformWidget w = (XmdsWaveformWidget)w_in; - if (reverse != waveformReverse(w) && XtIsRealized((Widget)w)) { + if (reverse != waveformReverse(w) && XtIsRealized((Widget)w)) + { XCopyArea(XtDisplay(w), waveformDrawable(w), waveformDrawable(w), waveformFlipGC(w), 0, 0, XtWidth(w), XtHeight(w), 0, 0); if (waveformPixmap(w)) @@ -2803,13 +3132,15 @@ static void Reverse(Widget w_in, int reverse) { waveformReverse(w) = reverse; } -static void Cut(XmdsWaveformWidget w, XButtonEvent *event) { +static void Cut(XmdsWaveformWidget w, XButtonEvent *event) +{ XmAnyCallbackStruct cb = {0, 0}; cb.event = (XEvent *)event; XtCallCallbacks((Widget)w, XmdsNcutCallback, &cb); } -static void Paste(XmdsWaveformWidget w, XButtonEvent *event) { +static void Paste(XmdsWaveformWidget w, XButtonEvent *event) +{ XmAnyCallbackStruct cb = {0, 0}; cb.event = (XEvent *)event; XtCallCallbacks((Widget)w, XmdsNpasteCallback, &cb); @@ -2821,7 +3152,8 @@ static void Paste(XmdsWaveformWidget w, XButtonEvent *event) { #include #include -int FixupMissing(unsigned sig_args[], unsigned mech_args[]) { +int FixupMissing(unsigned sig_args[], unsigned mech_args[]) +{ unsigned code; int FixupFault(); static struct dsc$descriptor_p fixup = {4, DSC$K_DTYPE_L, DSC$K_CLASS_P, @@ -2842,7 +3174,8 @@ int FixupMissing(unsigned sig_args[], unsigned mech_args[]) { union real { long l[4]; }; -struct dcf { +struct dcf +{ unsigned dcfacc : 3; unsigned dcftyp : 5; unsigned : 24; @@ -2853,13 +3186,17 @@ int FixupFault(unsigned *opcode, unsigned *ipc, unsigned *psl, unsigned regs[16], unsigned *opcount, struct dcf optypes[], unsigned short *readops[], union real *writeops[], unsigned sig_args[], int sig_routine(), int context, int userarg, - unsigned original[16]) { + unsigned original[16]) +{ int n; unsigned found = 0; - for (n = *opcount; --n >= 0;) { - if (writeops[n] != 0) { + for (n = *opcount; --n >= 0;) + { + if (writeops[n] != 0) + { *psl |= (PSL$M_N | PSL$M_Z | PSL$M_V | PSL$M_C); - switch (optypes[n].dcftyp) { + switch (optypes[n].dcftyp) + { case LIB$K_DCFTYP_L: (*writeops[n]).l[0] = missing; found = 1; @@ -2881,7 +3218,8 @@ int FixupFault(unsigned *opcode, unsigned *ipc, unsigned *psl, /**************************** Look for a bad input operand. ****************************/ - for (n = *opcount; --n >= 0;) { + for (n = *opcount; --n >= 0;) + { if (readops[n] && (optypes[n].dcftyp >= LIB$K_DCFTYP_F) && (*readops[n] == 0x8000)) break; @@ -2890,7 +3228,8 @@ int FixupFault(unsigned *opcode, unsigned *ipc, unsigned *psl, /***************************************** Set all bits for compare/test of reserved. *****************************************/ - if (n >= 0) { + if (n >= 0) + { *psl |= (PSL$M_N | PSL$M_Z | PSL$M_V | PSL$M_C); return SS$_CONTINUE; } @@ -2900,37 +3239,45 @@ int FixupFault(unsigned *opcode, unsigned *ipc, unsigned *psl, #endif static Boolean UpdateLimits(XmdsWaveformWidget old, float *xmin, float *xmax, - float *ymin, float *ymax, XmdsWaveformWidget new) { + float *ymin, float *ymax, XmdsWaveformWidget new) +{ Boolean changed = UpdateLimit(xMin(old), xmin, &xMin(new)) | UpdateLimit(xMax(old), xmax, &xMax(new)) | UpdateLimit(yMin(old), ymin, &yMin(new)) | UpdateLimit(yMax(old), ymax, &yMax(new)); - if (waveformCount(new)) { - if (!(xMin(new) && xMax(new))) { + if (waveformCount(new)) + { + if (!(xMin(new) && xMax(new))) + { float _xmin; float _xmax; AutoScale(waveformCount(new), xValue(new), &_xmin, &_xmax, yValue(new), yMin(new), yMax(new)); - if (!xMin(new)) { + if (!xMin(new)) + { xMin(new) = XtNew(float); *xMin(new) = _xmin; } - if (!xMax(new)) { + if (!xMax(new)) + { xMax(new) = XtNew(float); *xMax(new) = _xmax; } changed = TRUE; } - if (!(yMin(new) && yMax(new))) { + if (!(yMin(new) && yMax(new))) + { float _ymin; float _ymax; AutoScale(waveformCount(new), yValue(new), &_ymin, &_ymax, xValue(new), xMin(new), xMax(new)); - if (!yMin(new)) { + if (!yMin(new)) + { yMin(new) = XtNew(float); *yMin(new) = _ymin; } - if (!yMax(new)) { + if (!yMax(new)) + { yMax(new) = XtNew(float); *yMax(new) = _ymax; } @@ -2941,25 +3288,32 @@ static Boolean UpdateLimits(XmdsWaveformWidget old, float *xmin, float *xmax, return changed; } -static Boolean UpdateLimit(float *old, float *req, float **new) { +static Boolean UpdateLimit(float *old, float *req, float **new) +{ if (old == req) return FALSE; - else if ((((char *)req - (char *)0) & 0xffffffff) == 0xffffffff) { + else if ((((char *)req - (char *)0) & 0xffffffff) == 0xffffffff) + { *new = old; return FALSE; - } else { + } + else + { if (old) XtFree((char *)old); - if (req) { + if (req) + { *new = XtNew(float); **new = min(huge, max(-huge, *req)); - } else + } + else *new = req; } return TRUE; } -static void ForceUpdate(XmdsWaveformWidget w) { +static void ForceUpdate(XmdsWaveformWidget w) +{ XEvent event; while (XCheckWindowEvent(XtDisplay(w), XtWindow(w), ExposureMask, &event)) ; diff --git a/xmdsshr/XmdsWidgetCallbacks.c b/xmdsshr/XmdsWidgetCallbacks.c index 70b1c45af5..23ad2e243e 100644 --- a/xmdsshr/XmdsWidgetCallbacks.c +++ b/xmdsshr/XmdsWidgetCallbacks.c @@ -76,14 +76,16 @@ void XmdsManageWindow(Widget w); #include #include -static Widget FindShellChild(Widget w) { +static Widget FindShellChild(Widget w) +{ Widget sc; for (sc = w; sc && !XtIsShell(XtParent(sc)); sc = XtParent(sc)) ; return sc; } -void XmdsRaiseWindow(Widget w) { +void XmdsRaiseWindow(Widget w) +{ Widget shell; for (shell = w; shell && !XtIsShell(shell); shell = XtParent(shell)) ; @@ -91,7 +93,8 @@ void XmdsRaiseWindow(Widget w) { XtPopup(shell, XtGrabNone); } -void XmdsManageWindow(Widget w) { +void XmdsManageWindow(Widget w) +{ if (!XtIsManaged(w)) XtManageChild(w); else @@ -111,18 +114,21 @@ extern void XmdsResetAllXds(Widget w); extern Boolean XmdsXdsAreValid(Widget w); extern Boolean XmdsApplyAllXds(Widget w); -void XmdsResetCallback(Widget w) { +void XmdsResetCallback(Widget w) +{ XmdsResetAllXds(FindShellChild(w)); return; } -void XmdsOkCallback(Widget w) { +void XmdsOkCallback(Widget w) +{ int XmdsApplyCallback(Widget w); if (XmdsApplyCallback(w)) XtDestroyWidget(FindShellChild(w)); } -int XmdsApplyCallback(Widget w) { +int XmdsApplyCallback(Widget w) +{ int status; Widget db = FindShellChild(w); if ((status = XmdsXdsAreValid(db))) @@ -131,4 +137,7 @@ int XmdsApplyCallback(Widget w) { } #endif /* _NO_XDS */ -void XmdsCancelCallback(Widget w) { XtDestroyWidget(FindShellChild(w)); } +void XmdsCancelCallback(Widget w) +{ + XtDestroyWidget(FindShellChild(w)); +} diff --git a/xmdsshr/XmdsXdBox.c b/xmdsshr/XmdsXdBox.c index 6fc56d276f..8e3983678d 100644 --- a/xmdsshr/XmdsXdBox.c +++ b/xmdsshr/XmdsXdBox.c @@ -362,44 +362,53 @@ WidgetClass xmdsXdBoxWidgetClass; the initial widget. ****************************************************/ EXPORT Widget XmdsCreateXdBox(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ return XtCreateWidget(name, (WidgetClass)&xmdsXdBoxClassRec, parent, args, argcount); } -EXPORT Boolean XmdsXdBoxApply(Widget w) { +EXPORT Boolean XmdsXdBoxApply(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; return xdbw->xdbox.put_on_apply ? XmdsXdBoxPut(w) : 1; } -EXPORT struct descriptor *XmdsXdBoxGetXd(Widget w) { +EXPORT struct descriptor *XmdsXdBoxGetXd(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; return (struct descriptor *)Unload(xdbw->xdbox.specific_dlog); } -EXPORT Boolean XmdsXdBoxPut(Widget w) { +EXPORT Boolean XmdsXdBoxPut(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; return Put(xdbw); } -EXPORT void XmdsXdBoxReset(Widget w) { +EXPORT void XmdsXdBoxReset(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; - if (xdbw->xdbox.nid) { + if (xdbw->xdbox.nid) + { int nid = xdbw->xdbox.nid + xdbw->xdbox.nid_offset; - if (xdbw->xdbox.xd) { + if (xdbw->xdbox.xd) + { MdsFree1Dx(xdbw->xdbox.xd, 0); XtFree((char *)xdbw->xdbox.xd); } xdbw->xdbox.xd = (struct descriptor_xd *)TdiGet(nid); GenericGet(xdbw); } - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { GenericLoad(xdbw); Load(xdbw->xdbox.specific_dlog, xdbw->xdbox.xd); } } -EXPORT void XmdsXdBoxSetState(Widget w, Boolean state) { +EXPORT void XmdsXdBoxSetState(Widget w, Boolean state) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; XmToggleButtonGadgetSetState( XtNameToWidget(xdbw->xdbox.xdb_dlog, "generic_box.on_off_toggle"), state, @@ -407,7 +416,8 @@ EXPORT void XmdsXdBoxSetState(Widget w, Boolean state) { xdbw->xdbox.on_off = state; } -EXPORT Boolean XmdsXdBoxGetState(Widget w) { +EXPORT Boolean XmdsXdBoxGetState(Widget w) +{ Boolean state; XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; if (!xdbw->xdbox.loaded) @@ -418,11 +428,13 @@ EXPORT Boolean XmdsXdBoxGetState(Widget w) { return state; } -void XmdsXdBoxSetNid(Widget w, int nid) { +void XmdsXdBoxSetNid(Widget w, int nid) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; if (xdbw->xdbox.xd) MdsFree1Dx(xdbw->xdbox.xd, 0); - else { + else + { xdbw->xdbox.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *xdbw->xdbox.xd = empty_xd; @@ -433,24 +445,28 @@ void XmdsXdBoxSetNid(Widget w, int nid) { xdbw->xdbox.nid = nid; TreeGetRecord(xdbw->xdbox.nid, xdbw->xdbox.xd); GenericGet(xdbw); - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { Load(xdbw->xdbox.specific_dlog, xdbw->xdbox.xd); GenericLoad(xdbw); } } -EXPORT void XmdsXdBoxSetDefaultNid(Widget w, int def_nid) { +EXPORT void XmdsXdBoxSetDefaultNid(Widget w, int def_nid) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; xdbw->xdbox.default_nid = def_nid; SetDefault(w); } -EXPORT void XmdsXdBoxSetXd(Widget w, struct descriptor *dsc) { +EXPORT void XmdsXdBoxSetXd(Widget w, struct descriptor *dsc) +{ struct descriptor_xd *xd = (struct descriptor_xd *)dsc; XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; if (xdbw->xdbox.xd) MdsFree1Dx(xdbw->xdbox.xd, 0); - else { + else + { xdbw->xdbox.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *xdbw->xdbox.xd = empty_xd; @@ -460,25 +476,30 @@ EXPORT void XmdsXdBoxSetXd(Widget w, struct descriptor *dsc) { Load(xdbw->xdbox.specific_dlog, xdbw->xdbox.xd); } -EXPORT void XmdsXdBoxLoad(Widget w) { +EXPORT void XmdsXdBoxLoad(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; - if (!xdbw->xdbox.loaded) { + if (!xdbw->xdbox.loaded) + { xdbw->xdbox.loaded = 1; Load(xdbw->xdbox.specific_dlog, xdbw->xdbox.xd); GenericLoad(xdbw); } } -static void ChangeManaged(Widget w) { +static void ChangeManaged(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; XtWidgetGeometry request; XtGeometryResult result; CalculateNewSize(xdbw, &request.width, &request.height); - if (request.width != XtWidth(xdbw) || request.height != XtHeight(xdbw)) { + if (request.width != XtWidth(xdbw) || request.height != XtHeight(xdbw)) + { request.request_mode = CWWidth | CWHeight; - do { + do + { result = XtMakeGeometryRequest(w, &request, &request); } while (result == XtGeometryAlmost); }; @@ -488,7 +509,8 @@ static void ChangeManaged(Widget w) { ClassInitialize - Opens the DRM Hierarchy and **********************************/ -static void ClassInitialize() { +static void ClassInitialize() +{ static MrmRegisterArg routines[] = { {"apply_button_proc", (char *)apply_button_proc}, {"cancel_button_proc", (char *)cancel_button_proc}, @@ -508,12 +530,14 @@ static void ClassInitialize() { XtNumber(routines)); } -static void Destroy(Widget w) { +static void Destroy(Widget w) +{ XmdsXdBoxWidget xdbw = (XmdsXdBoxWidget)w; Widget par = XtParent(w); if (XtIsShell(par)) XtDestroyWidget(par); - if (xdbw->xdbox.xd) { + if (xdbw->xdbox.xd) + { MdsFree1Dx(xdbw->xdbox.xd, 0); XtFree((char *)xdbw->xdbox.xd); xdbw->xdbox.xd = 0; @@ -524,16 +548,19 @@ static void Destroy(Widget w) { XtFree((char *)xdbw->xdbox.path); } -static void Resize(XmdsXdBoxWidget w) { +static void Resize(XmdsXdBoxWidget w) +{ if (w->xdbox.xdb_dlog) XtResizeWidget(w->xdbox.xdb_dlog, XtWidth(w), XtHeight(w), XtBorderWidth(w->xdbox.xdb_dlog)); } static XtGeometryResult GeometryManager(Widget w, XtWidgetGeometry *req, - XtWidgetGeometry *ret) { + XtWidgetGeometry *ret) +{ XtGeometryResult res = XtMakeGeometryRequest(XtParent(w), req, ret); - if (res == XtGeometryYes) { + if (res == XtGeometryYes) + { if (req->request_mode & CWX) w->core.x = XtParent(w)->core.x; if (req->request_mode & CWY) @@ -546,13 +573,15 @@ static XtGeometryResult GeometryManager(Widget w, XtWidgetGeometry *req, w->core.width = XtParent(w)->core.width; if (req->request_mode & CWBorderWidth) w->core.border_width = XtParent(w)->core.border_width; - } else if (res == XtGeometryAlmost) + } + else if (res == XtGeometryAlmost) res = GeometryManager(w, ret, ret); return res; } static void Initialize(Widget req, Widget new, ArgList args, - Cardinal *argcount) { + Cardinal *argcount) +{ XmdsXdBoxWidget w = (XmdsXdBoxWidget) new; MrmType class; int nid = 0; @@ -560,12 +589,15 @@ static void Initialize(Widget req, Widget new, ArgList args, w->xdbox.tag_list = 0; w->xdbox.path = 0; - if (w->xdbox.nid) { + if (w->xdbox.nid) + { if (w->xdbox.nid == -1) w->xdbox.nid = XmdsGetDeviceNid(); nid = w->xdbox.nid + w->xdbox.nid_offset; w->xdbox.xd = (struct descriptor_xd *)TdiGet(nid); - } else { + } + else + { XmdsXdBoxWidget req_xdb = (XmdsXdBoxWidget)req; w->xdbox.xd = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); @@ -574,16 +606,21 @@ static void Initialize(Widget req, Widget new, ArgList args, } MrmFetchWidgetOverride(xmdsXdBoxClassRec.xdbox_class.drm, "xd_box", (Widget)w, "xd_box", args, *argcount, &w->xdbox.xdb_dlog, &class); - if (nid == 0) { + if (nid == 0) + { XtVaSetValues(XtNameToWidget(w->xdbox.xdb_dlog, "detail_box"), XmNtopAttachment, XmATTACH_FORM, NULL); XtUnmanageChild(XtNameToWidget(w->xdbox.xdb_dlog, "generic_box")); - } else { + } + else + { GenericGet(w); } XtManageChild(w->xdbox.xdb_dlog); - if (w->xdbox.usage == 0) { - if (w->xdbox.nid) { + if (w->xdbox.usage == 0) + { + if (w->xdbox.nid) + { NCI_ITM itms[] = {{sizeof(w->xdbox.usage), NciUSAGE, 0, 0}, {0, 0, 0, 0}}; int nid = w->xdbox.nid + w->xdbox.nid_offset; int status; @@ -591,11 +628,14 @@ static void Initialize(Widget req, Widget new, ArgList args, status = TreeGetNci(nid, itms); if ((status & 1) == 0) w->xdbox.usage = 0; - } else { + } + else + { w->xdbox.usage = 0; } } - switch (w->xdbox.usage) { + switch (w->xdbox.usage) + { case TreeUSAGE_WINDOW: WindowCreate(w, args, *argcount); break; @@ -632,7 +672,8 @@ static void Initialize(Widget req, Widget new, ArgList args, status = 0; break; } - if (status) { + if (status) + { w->xdbox.loaded = 0; Load(w->xdbox.specific_dlog, w->xdbox.xd); w->core.width = XtWidth(w->xdbox.xdb_dlog); @@ -640,23 +681,28 @@ static void Initialize(Widget req, Widget new, ArgList args, } } -static Boolean SetValues(Widget old, Widget req, Widget new) { +static Boolean SetValues(Widget old, Widget req, Widget new) +{ XmdsXdBoxWidget old_xd_w = (XmdsXdBoxWidget)old; XmdsXdBoxWidget req_xd_w = (XmdsXdBoxWidget)req; XmdsXdBoxWidget new_xd_w = (XmdsXdBoxWidget) new; if ((req_xd_w->xdbox.nid != old_xd_w->xdbox.nid) || - (req_xd_w->xdbox.nid_offset != old_xd_w->xdbox.nid_offset)) { + (req_xd_w->xdbox.nid_offset != old_xd_w->xdbox.nid_offset)) + { if (req_xd_w->xdbox.nid == -1) new_xd_w->xdbox.nid = XmdsGetDeviceNid(); XmdsXdBoxSetNid(new, new_xd_w->xdbox.nid + new_xd_w->xdbox.nid_offset); - } else if (req_xd_w->xdbox.xd != old_xd_w->xdbox.xd) { + } + else if (req_xd_w->xdbox.xd != old_xd_w->xdbox.xd) + { new_xd_w->xdbox.xd = 0; XmdsXdBoxSetXd(new, (struct descriptor *)req_xd_w->xdbox.xd); } return 0; } -static void ActionCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { +static void ActionCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -698,7 +744,8 @@ static void ActionCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { XtManageChild(w->xdbox.specific_dlog); } -static void ActionLoad(Widget w, struct descriptor_xd *xd) { +static void ActionLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); struct descriptor *ptr = (struct descriptor *)xd; Widget menu_widget = XtNameToWidget(w, "action_menu"); @@ -710,16 +757,20 @@ static void ActionLoad(Widget w, struct descriptor_xd *xd) { for (ptr = (struct descriptor *)xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor *)ptr->pointer) ; - if (ptr) { + if (ptr) + { xd = (struct descriptor_xd *)ptr; - if (NotEmptyXd(xd)) { - if (xd->dtype == DTYPE_ACTION) { + if (NotEmptyXd(xd)) + { + if (xd->dtype == DTYPE_ACTION) + { Widget dispatch_w = XtNameToWidget(action_widget, "dispatch_dlog"); Widget task_w = XtNameToWidget(action_widget, "task_dlog"); struct descriptor_action *a_dsc = (struct descriptor_action *)xd; TaskLoad(task_w, (struct descriptor_xd *)a_dsc->task); DispatchLoad(dispatch_w, (struct descriptor_xd *)a_dsc->dispatch); - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { static EMPTYXD(xd); if (a_dsc->ndesc >= 3) XmdsExprSetXd(action_notify, (struct descriptor *)a_dsc->errorlogs); @@ -731,7 +782,9 @@ static void ActionLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(action_notify_label); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 1); - } else { + } + else + { if (xdbw->xdbox.loaded) XmdsExprSetXd(expr_widget, (struct descriptor *)xd); XtUnmanageChild(action_widget); @@ -740,14 +793,18 @@ static void ActionLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 2); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(action_widget); XtUnmanageChild(action_notify); XtUnmanageChild(action_notify_label); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(action_widget); @@ -756,7 +813,8 @@ static void ActionLoad(Widget w, struct descriptor_xd *xd) { } } -struct descriptor_xd *ActionUnload(Widget w) { +struct descriptor_xd *ActionUnload(Widget w) +{ struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); struct descriptor_xd *data = 0; @@ -765,10 +823,14 @@ struct descriptor_xd *ActionUnload(Widget w) { *ans = empty_xd; - if (XtIsManaged(action_expr) || XtIsManaged(action_box)) { - if (XtIsManaged(action_expr)) { + if (XtIsManaged(action_expr) || XtIsManaged(action_box)) + { + if (XtIsManaged(action_expr)) + { data = (struct descriptor_xd *)XmdsExprGetXd(action_expr); - } else if (XtIsManaged(action_box)) { + } + else if (XtIsManaged(action_box)) + { static DESCRIPTOR(action, "BUILD_ACTION($, $, $)"); Widget dispatch_w = XtNameToWidget(action_box, "dispatch_dlog"); Widget task_w = XtNameToWidget(action_box, "task_dlog"); @@ -789,7 +851,8 @@ struct descriptor_xd *ActionUnload(Widget w) { /* * Routines for Axis type. */ -static void AxisCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { +static void AxisCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -809,7 +872,8 @@ static void AxisCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { XtManageChild(w->xdbox.specific_dlog); } -static void AxisLoad(Widget w, struct descriptor_xd *xd) { +static void AxisLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); struct descriptor *ptr = (struct descriptor *)xd; Widget menu_widget = XtNameToWidget(w, "axis_menu"); @@ -821,24 +885,31 @@ static void AxisLoad(Widget w, struct descriptor_xd *xd) { for (ptr = (struct descriptor *)xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor *)ptr->pointer) ; - if (ptr) { - if (ptr->dtype == DTYPE_WITH_UNITS) { + if (ptr) + { + if (ptr->dtype == DTYPE_WITH_UNITS) + { struct descriptor_with_units *w_u = (struct descriptor_with_units *)ptr; XmdsExprSetXd(units_widget, w_u->units); xd = (struct descriptor_xd *)w_u->data; - } else { + } + else + { XmdsExprSetXd(units_widget, (struct descriptor *)&empty_xd); xd = (struct descriptor_xd *)ptr; } - if (NotEmptyXd(xd)) { + if (NotEmptyXd(xd)) + { XtManageChild(units_label_widget); XtManageChild(units_widget); - if (xd->dtype == DTYPE_RANGE) { + if (xd->dtype == DTYPE_RANGE) + { Widget start_w = XtNameToWidget(axis_widget, "axis_start"); Widget end_w = XtNameToWidget(axis_widget, "axis_end"); Widget inc_w = XtNameToWidget(axis_widget, "axis_inc"); struct descriptor_range *a_dsc = (struct descriptor_range *)xd; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { XmdsExprFieldSetXd(start_w, a_dsc->begin); XmdsExprFieldSetXd(end_w, a_dsc->ending); XmdsExprFieldSetXd(inc_w, a_dsc->deltaval); @@ -846,7 +917,9 @@ static void AxisLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(axis_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 1); - } else { + } + else + { if (xdbw->xdbox.loaded) XmdsExprSetXd(expr_widget, (struct descriptor *)xd); XtUnmanageChild(axis_widget); @@ -855,14 +928,18 @@ static void AxisLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(units_label_widget); XtManageChild(units_widget); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(units_label_widget); XtUnmanageChild(units_widget); XtUnmanageChild(expr_widget); XtUnmanageChild(axis_widget); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(axis_widget); @@ -871,7 +948,8 @@ static void AxisLoad(Widget w, struct descriptor_xd *xd) { } } -struct descriptor_xd *AxisUnload(Widget w) { +struct descriptor_xd *AxisUnload(Widget w) +{ struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); struct descriptor_xd *data = 0; @@ -883,11 +961,15 @@ struct descriptor_xd *AxisUnload(Widget w) { *ans = empty_xd; - if (XtIsManaged(expr_widget) || XtIsManaged(axis_widget)) { + if (XtIsManaged(expr_widget) || XtIsManaged(axis_widget)) + { units = (struct descriptor_xd *)XmdsExprGetXd(units_widget); - if (XtIsManaged(expr_widget)) { + if (XtIsManaged(expr_widget)) + { data = (struct descriptor_xd *)XmdsExprGetXd(expr_widget); - } else if (XtIsManaged(axis_widget)) { + } + else if (XtIsManaged(axis_widget)) + { static DESCRIPTOR(range, "$ : $ : $"); Widget start_w = XtNameToWidget(axis_widget, "axis_start"); Widget end_w = XtNameToWidget(axis_widget, "axis_end"); @@ -903,7 +985,8 @@ struct descriptor_xd *AxisUnload(Widget w) { TdiCompile(&range, start, end, inc, data MDS_END_ARG); } if (units && units->l_length && - (units->pointer->dtype != DTYPE_T || units->pointer->length)) { + (units->pointer->dtype != DTYPE_T || units->pointer->length)) + { ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ans = empty_xd; TdiCompile(&w_units, data, units, ans MDS_END_ARG); @@ -911,7 +994,8 @@ struct descriptor_xd *AxisUnload(Widget w) { MdsFree1Dx(data, 0); XtFree((char *)units); XtFree((char *)data); - } else + } + else ans = data; } return ans; @@ -920,7 +1004,8 @@ struct descriptor_xd *AxisUnload(Widget w) { /* * Routines for Dispatch type. */ -static void DispatchCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { +static void DispatchCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -940,7 +1025,8 @@ static void DispatchCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { XtManageChild(w->xdbox.specific_dlog); } -static void DispatchLoad(Widget w, struct descriptor_xd *xd) { +static void DispatchLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); struct descriptor_xd *ptr = xd; Widget menu_widget = XtNameToWidget(w, "dispatch_menu"); @@ -950,17 +1036,21 @@ static void DispatchLoad(Widget w, struct descriptor_xd *xd) { for (ptr = xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor_xd *)ptr->pointer) ; - if (ptr) { + if (ptr) + { xd = ptr; - if (NotEmptyXd(xd)) { - if (xd->dtype == DTYPE_DISPATCH) { + if (NotEmptyXd(xd)) + { + if (xd->dtype == DTYPE_DISPATCH) + { Widget ident_w = XtNameToWidget(dispatch_widget, "dispatch_ident"); Widget phase_w = XtNameToWidget(dispatch_widget, "dispatch_phase"); Widget when_w = XtNameToWidget(dispatch_widget, "dispatch_when"); Widget completion_w = XtNameToWidget(dispatch_widget, "dispatch_completion"); struct descriptor_dispatch *w_dsc = (struct descriptor_dispatch *)xd; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { XmdsExprFieldSetXd(ident_w, w_dsc->ident); XmdsExprFieldSetXd(when_w, w_dsc->when); XmdsExprFieldSetXd(completion_w, w_dsc->completion); @@ -969,26 +1059,33 @@ static void DispatchLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(dispatch_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 1); - } else { + } + else + { if (xdbw->xdbox.loaded) XmdsExprSetXd(expr_widget, (struct descriptor *)xd); XtUnmanageChild(dispatch_widget); XtManageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 2); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(dispatch_widget); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(dispatch_widget); } } -EXPORT struct descriptor_xd *DispatchUnload(Widget w) { +EXPORT struct descriptor_xd *DispatchUnload(Widget w) +{ struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); struct descriptor_xd *data = 0; @@ -997,10 +1094,14 @@ EXPORT struct descriptor_xd *DispatchUnload(Widget w) { *ans = empty_xd; - if (XtIsManaged(dispatch_expr) || XtIsManaged(dispatch_box)) { - if (XtIsManaged(dispatch_expr)) { + if (XtIsManaged(dispatch_expr) || XtIsManaged(dispatch_box)) + { + if (XtIsManaged(dispatch_expr)) + { data = (struct descriptor_xd *)XmdsExprGetXd(dispatch_expr); - } else if (XtIsManaged(dispatch_box)) { + } + else if (XtIsManaged(dispatch_box)) + { static int dispatch_type = 2; static struct descriptor_s type = {sizeof(int), DTYPE_L, CLASS_S, (char *)&dispatch_type}; @@ -1028,7 +1129,8 @@ EXPORT struct descriptor_xd *DispatchUnload(Widget w) { } static void ExpressionCreate(XmdsXdBoxWidget w, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -1048,7 +1150,8 @@ static void ExpressionCreate(XmdsXdBoxWidget w, ArgList args, XtManageChild(w->xdbox.specific_dlog); } -static void ExpressionLoad(Widget w, struct descriptor_xd *xd) { +static void ExpressionLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); struct descriptor_xd *ptr = xd; Widget menu_widget = XtNameToWidget(w, "expression_menu"); @@ -1059,13 +1162,18 @@ static void ExpressionLoad(Widget w, struct descriptor_xd *xd) { for (ptr = xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor_xd *)ptr->pointer) ; - if (ptr) { - if (xdbw->xdbox.loaded) { - if (ptr->dtype == DTYPE_WITH_UNITS) { + if (ptr) + { + if (xdbw->xdbox.loaded) + { + if (ptr->dtype == DTYPE_WITH_UNITS) + { struct descriptor_with_units *w_u = (struct descriptor_with_units *)ptr; XmdsExprSetXd(units_widget, w_u->units); XmdsExprSetXd(expr_widget, w_u->data); - } else { + } + else + { XmdsExprSetXd(units_widget, (struct descriptor *)&empty_xd); XmdsExprSetXd(expr_widget, (struct descriptor *)xd); } @@ -1074,7 +1182,9 @@ static void ExpressionLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(expr_widget); XtManageChild(units_widget); XtManageChild(units_label_widget); - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(units_widget); @@ -1082,7 +1192,8 @@ static void ExpressionLoad(Widget w, struct descriptor_xd *xd) { } } -static struct descriptor_xd *ExpressionUnload(Widget w) { +static struct descriptor_xd *ExpressionUnload(Widget w) +{ struct descriptor_xd *ans = 0; struct descriptor_xd *data = 0; struct descriptor_xd *units = 0; @@ -1090,36 +1201,45 @@ static struct descriptor_xd *ExpressionUnload(Widget w) { Widget units_widget = XtNameToWidget(w, "expression_units"); Widget expr_widget = XtNameToWidget(w, "expression_expr"); - if (XtIsManaged(w)) { + if (XtIsManaged(w)) + { if (XtIsManaged(units_widget)) units = (struct descriptor_xd *)XmdsExprGetXd(units_widget); if (XtIsManaged(expr_widget)) data = (struct descriptor_xd *)XmdsExprGetXd(expr_widget); - else { + else + { data = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); memcpy(data, &empty_xd, sizeof(struct descriptor_xd)); } if (data && units && units->l_length && - (units->pointer->dtype != DTYPE_T || units->pointer->length)) { + (units->pointer->dtype != DTYPE_T || units->pointer->length)) + { int status; ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ans = empty_xd; status = TdiCompile(&w_units, data, units, ans MDS_END_ARG); - if (!(status & 1)) { + if (!(status & 1)) + { TdiComplain(w); ans = 0; } - if (units) { + if (units) + { MdsFree1Dx(units, 0); XtFree((char *)units); } - if (data) { + if (data) + { MdsFree1Dx(data, 0); XtFree((char *)data); } - } else + } + else ans = data; - } else { + } + else + { ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ans = empty_xd; } @@ -1129,7 +1249,8 @@ static struct descriptor_xd *ExpressionUnload(Widget w) { /* * Routines for Task type. */ -static void TaskCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { +static void TaskCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -1149,7 +1270,8 @@ static void TaskCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { XtManageChild(w->xdbox.specific_dlog); } -static void TaskLoad(Widget w, struct descriptor_xd *xd) { +static void TaskLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); int arg; struct descriptor_xd *ptr = xd; @@ -1162,20 +1284,25 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { for (ptr = xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor_xd *)ptr->pointer) ; - if (ptr) { + if (ptr) + { xd = ptr; - if (NotEmptyXd(xd)) { - if (xd->dtype == DTYPE_ROUTINE) { + if (NotEmptyXd(xd)) + { + if (xd->dtype == DTYPE_ROUTINE) + { Widget timeout_w = XtNameToWidget(routine_widget, "routine_timeout"); Widget image_w = XtNameToWidget(routine_widget, "routine_image"); Widget routine_w = XtNameToWidget(routine_widget, "routine_routine"); Widget arg_box_w = XtNameToWidget(routine_widget, "*arg_box"); struct descriptor_routine *r_dsc = (struct descriptor_routine *)xd; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { XmdsExprFieldSetXd(timeout_w, r_dsc->time_out); XmdsExprFieldSetXd(image_w, r_dsc->image); XmdsExprFieldSetXd(routine_w, r_dsc->routine); - for (arg = 0; arg < 8; arg++) { + for (arg = 0; arg < 8; arg++) + { char arg_name[] = {'a', 'r', 'g', 0, 0}; Widget arg_w; arg_name[3] = '1' + arg; @@ -1191,7 +1318,9 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { XtUnmanageChild((Widget)method_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 2); - } else if (xd->dtype == DTYPE_METHOD) { + } + else if (xd->dtype == DTYPE_METHOD) + { Widget timeout_w = XtNameToWidget((Widget)method_widget, "method_timeout"); Widget object_w = @@ -1200,11 +1329,13 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { XtNameToWidget((Widget)method_widget, "method_method"); Widget arg_box_w = XtNameToWidget((Widget)method_widget, "*arg_box"); struct descriptor_method *m_dsc = (struct descriptor_method *)xd; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { XmdsExprFieldSetXd(timeout_w, m_dsc->time_out); XmdsExprFieldSetXd(object_w, m_dsc->object); XmdsExprFieldSetXd(method_w, m_dsc->method); - for (arg = 0; arg < 8; arg++) { + for (arg = 0; arg < 8; arg++) + { char arg_name[] = {'a', 'r', 'g', 0, 0}; Widget arg_w; arg_name[3] = '1' + arg; @@ -1220,7 +1351,9 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { XtManageChild((Widget)method_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 1); - } else { + } + else + { if (xdbw->xdbox.loaded) XmdsExprSetXd(expr_widget, (struct descriptor *)xd); XtUnmanageChild(routine_widget); @@ -1228,13 +1361,17 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 3); } - } else { + } + else + { XtUnmanageChild(routine_widget); XtUnmanageChild((Widget)method_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 0); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(routine_widget); @@ -1242,7 +1379,8 @@ static void TaskLoad(Widget w, struct descriptor_xd *xd) { } } -EXPORT struct descriptor_xd *TaskUnload(Widget w) { +EXPORT struct descriptor_xd *TaskUnload(Widget w) +{ struct descriptor_xd *data = 0; Widget expr_widget = XtNameToWidget(w, "task_expr"); Widget routine_widget = XtNameToWidget(w, "routine_box"); @@ -1250,10 +1388,14 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { (XmdsXdBoxWidget)XtNameToWidget(w, "method_box"); if (XtIsManaged(expr_widget) || XtIsManaged(routine_widget) || - XtIsManaged((Widget)method_widget)) { - if (XtIsManaged(expr_widget)) { + XtIsManaged((Widget)method_widget)) + { + if (XtIsManaged(expr_widget)) + { data = (struct descriptor_xd *)XmdsExprGetXd(expr_widget); - } else if (XtIsManaged((Widget)method_widget)) { + } + else if (XtIsManaged((Widget)method_widget)) + { int i; int nargs = 0; Widget timeout_w = @@ -1269,7 +1411,8 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { object = (struct descriptor_xd *)XmdsExprFieldGetXd(object_w); method = (struct descriptor_xd *)XmdsExprFieldGetXd(method_w); { - METHOD(8) method_dsc; + METHOD(8) + method_dsc; method_dsc.length = 0; method_dsc.dtype = DTYPE_METHOD; method_dsc.class = CLASS_R; @@ -1277,7 +1420,8 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { method_dsc.time_out = (struct descriptor *)timeout; method_dsc.method = (struct descriptor *)method; method_dsc.object = (struct descriptor *)object; - for (i = 0; i < 8; i++) { + for (i = 0; i < 8; i++) + { char arg_name[] = {'a', 'r', 'g', 0, 0}; Widget arg_w; arg_name[3] = '1' + i; @@ -1292,7 +1436,9 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { *data = empty_xd; MdsCopyDxXd((struct descriptor *)&method_dsc, data); } - } else if (XtIsManaged(routine_widget)) { + } + else if (XtIsManaged(routine_widget)) + { int i; int nargs = 0; Widget timeout_w = XtNameToWidget(routine_widget, "routine_timeout"); @@ -1307,7 +1453,8 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { image = (struct descriptor_xd *)XmdsExprFieldGetXd(image_w); routine = (struct descriptor_xd *)XmdsExprFieldGetXd(routine_w); { - ROUTINE(8) routine_dsc; + ROUTINE(8) + routine_dsc; routine_dsc.length = 0; routine_dsc.dtype = DTYPE_ROUTINE; routine_dsc.class = CLASS_R; @@ -1315,7 +1462,8 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { routine_dsc.time_out = (struct descriptor *)timeout; routine_dsc.image = (struct descriptor *)image; routine_dsc.routine = (struct descriptor *)routine; - for (i = 0; i < 8; i++) { + for (i = 0; i < 8; i++) + { char arg_name[] = {'a', 'r', 'g', 0, 0}; Widget arg_w; arg_name[3] = '1' + i; @@ -1335,7 +1483,8 @@ EXPORT struct descriptor_xd *TaskUnload(Widget w) { return data; } -static void WindowCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { +static void WindowCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) +{ MrmType class; XmdsXdUserPart *user_part = (XmdsXdUserPart *)XtMalloc(sizeof(XmdsXdUserPart)); @@ -1355,7 +1504,8 @@ static void WindowCreate(XmdsXdBoxWidget w, ArgList args, Cardinal argcount) { XtManageChild(w->xdbox.specific_dlog); } -static void WindowLoad(Widget w, struct descriptor_xd *xd) { +static void WindowLoad(Widget w, struct descriptor_xd *xd) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); struct descriptor_xd *ptr = xd; Widget menu_widget = XtNameToWidget(w, "window_menu"); @@ -1365,15 +1515,19 @@ static void WindowLoad(Widget w, struct descriptor_xd *xd) { for (ptr = xd; ptr && ptr->dtype == DTYPE_DSC; ptr = (struct descriptor_xd *)ptr->pointer) ; - if (ptr) { + if (ptr) + { xd = ptr; - if (NotEmptyXd(xd)) { - if (xd->dtype == DTYPE_WINDOW) { + if (NotEmptyXd(xd)) + { + if (xd->dtype == DTYPE_WINDOW) + { Widget start_idx_w = XtNameToWidget(window_widget, "window_start_idx"); Widget end_idx_w = XtNameToWidget(window_widget, "window_end_idx"); Widget tzero_w = XtNameToWidget(window_widget, "window_tzero"); struct descriptor_window *w_dsc = (struct descriptor_window *)xd; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { XmdsExprFieldSetXd(start_idx_w, w_dsc->startidx); XmdsExprFieldSetXd(end_idx_w, w_dsc->endingidx); XmdsExprFieldSetXd(tzero_w, w_dsc->value_at_idx0); @@ -1381,26 +1535,33 @@ static void WindowLoad(Widget w, struct descriptor_xd *xd) { XtManageChild(window_widget); XtUnmanageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 1); - } else { + } + else + { if (xdbw->xdbox.loaded) XmdsExprSetXd(expr_widget, (struct descriptor *)xd); XtUnmanageChild(window_widget); XtManageChild(expr_widget); XmdsSetOptionIdx(menu_widget, 2); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(window_widget); } - } else { + } + else + { XmdsSetOptionIdx(menu_widget, 0); XtUnmanageChild(expr_widget); XtUnmanageChild(window_widget); } } -EXPORT struct descriptor_xd *WindowUnload(Widget w) { +EXPORT struct descriptor_xd *WindowUnload(Widget w) +{ struct descriptor_xd *ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); struct descriptor_xd *data = 0; @@ -1409,10 +1570,14 @@ EXPORT struct descriptor_xd *WindowUnload(Widget w) { *ans = empty_xd; - if (XtIsManaged(window_expr) || XtIsManaged(window_box)) { - if (XtIsManaged(window_expr)) { + if (XtIsManaged(window_expr) || XtIsManaged(window_box)) + { + if (XtIsManaged(window_expr)) + { data = (struct descriptor_xd *)XmdsExprGetXd(window_expr); - } else if (XtIsManaged(window_box)) { + } + else if (XtIsManaged(window_box)) + { static DESCRIPTOR(wind, "BUILD_WINDOW($, $, $)"); Widget start_idx_w = XtNameToWidget(window_box, "window_start_idx"); Widget end_idx_w = XtNameToWidget(window_box, "window_end_idx"); @@ -1436,11 +1601,15 @@ EXPORT struct descriptor_xd *WindowUnload(Widget w) { * Generic Widget Callbacks. */ -static void apply_button_proc(Widget w) { +static void apply_button_proc(Widget w) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (Apply(xdbw)) { - if (xdbw->xdbox.apply_callback) { + if (xdbw) + { + if (Apply(xdbw)) + { + if (xdbw->xdbox.apply_callback) + { XmdsButtonCallbackStruct button_callback_data = {XmCR_APPLY, 0, 0, 0}; button_callback_data.xd = xdbw->xdbox.xd; button_callback_data.on_off = xdbw->xdbox.on_off; @@ -1451,10 +1620,13 @@ static void apply_button_proc(Widget w) { } } -static void cancel_button_proc(Widget w) { +static void cancel_button_proc(Widget w) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (xdbw->xdbox.cancel_callback) { + if (xdbw) + { + if (xdbw->xdbox.cancel_callback) + { XmdsButtonCallbackStruct button_callback_data = {XmCR_CANCEL, 0, 0, 0}; button_callback_data.on_off = xdbw->xdbox.on_off; XtCallCallbackList((Widget)xdbw, xdbw->xdbox.cancel_callback, @@ -1462,17 +1634,20 @@ static void cancel_button_proc(Widget w) { } if (xdbw->xdbox.auto_destroy) XtDestroyWidget(XtParent(xdbw)); - else if (xdbw->xdbox.auto_unmanage) { + else if (xdbw->xdbox.auto_unmanage) + { XtUnmanageChild((Widget)xdbw); xdbw->xdbox.loaded = 0; } } } -static void reset_button_proc(Widget w) { +static void reset_button_proc(Widget w) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); XmdsXdBoxReset((Widget)xdbw); - if (xdbw->xdbox.reset_callback) { + if (xdbw->xdbox.reset_callback) + { XmdsButtonCallbackStruct button_callback_data = {XmCR_OK, 0, 0, 0}; button_callback_data.xd = xdbw->xdbox.xd; button_callback_data.on_off = xdbw->xdbox.on_off; @@ -1481,11 +1656,15 @@ static void reset_button_proc(Widget w) { } } -static void ok_button_proc(Widget w) { +static void ok_button_proc(Widget w) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (Apply(xdbw)) { - if (xdbw->xdbox.ok_callback) { + if (xdbw) + { + if (Apply(xdbw)) + { + if (xdbw->xdbox.ok_callback) + { XmdsButtonCallbackStruct button_callback_data = {XmCR_OK, 0, 0, 0}; button_callback_data.xd = xdbw->xdbox.xd; button_callback_data.on_off = xdbw->xdbox.on_off; @@ -1494,7 +1673,8 @@ static void ok_button_proc(Widget w) { } if (xdbw->xdbox.auto_destroy) XtDestroyWidget(XtParent(xdbw)); - else if (xdbw->xdbox.auto_unmanage) { + else if (xdbw->xdbox.auto_unmanage) + { XtUnmanageChild((Widget)xdbw); xdbw->xdbox.loaded = 0; } @@ -1506,10 +1686,13 @@ static void ok_button_proc(Widget w) { * Type Specific Widget Callbacks. */ -static void action_change_type_proc(Widget w, int *tag) { +static void action_change_type_proc(Widget w, int *tag) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (*tag == 1) { + if (xdbw) + { + if (*tag == 1) + { XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.action_dlog.action_box")); XtManageChild(XtNameToWidget( @@ -1518,7 +1701,9 @@ static void action_change_type_proc(Widget w, int *tag) { "detail_box.action_dlog.action_notify")); XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.action_dlog.action_expr")); - } else if (*tag == 2) { + } + else if (*tag == 2) + { XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.action_dlog.action_box")); XtUnmanageChild(XtNameToWidget( @@ -1527,7 +1712,9 @@ static void action_change_type_proc(Widget w, int *tag) { "detail_box.action_dlog.action_notify")); XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.action_dlog.action_expr")); - } else { + } + else + { XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.action_dlog.action_box")); XtUnmanageChild(XtNameToWidget( @@ -1540,10 +1727,13 @@ static void action_change_type_proc(Widget w, int *tag) { } } -static void axis_change_type_proc(Widget w, int *tag) { +static void axis_change_type_proc(Widget w, int *tag) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (*tag == 1) { + if (xdbw) + { + if (*tag == 1) + { XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.axis_dlog.axis_units_label")); XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, @@ -1552,7 +1742,9 @@ static void axis_change_type_proc(Widget w, int *tag) { "detail_box.axis_dlog.axis_box")); XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.axis_dlog.axis_expr")); - } else if (*tag == 2) { + } + else if (*tag == 2) + { XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.axis_dlog.axis_units_label")); XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, @@ -1561,7 +1753,9 @@ static void axis_change_type_proc(Widget w, int *tag) { "detail_box.axis_dlog.axis_box")); XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.axis_dlog.axis_expr")); - } else { + } + else + { XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.axis_dlog.axis_units_label")); XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, @@ -1574,45 +1768,58 @@ static void axis_change_type_proc(Widget w, int *tag) { } } -static int WidgetNameCmp(Widget w, char *string) { +static int WidgetNameCmp(Widget w, char *string) +{ return ((w->core.name == 0) || (w->core.name == (char *)0xffffff) || strcmp(w->core.name, string)); } -static void dispatch_change_type_proc(Widget w, int *tag) { +static void dispatch_change_type_proc(Widget w, int *tag) +{ Widget dispatch_dlog; for (dispatch_dlog = w; dispatch_dlog && WidgetNameCmp(dispatch_dlog, "dispatch_dlog"); dispatch_dlog = dispatch_dlog->core.parent) ; - if (dispatch_dlog) { - if (*tag == 1) { + if (dispatch_dlog) + { + if (*tag == 1) + { XtManageChild(XtNameToWidget(dispatch_dlog, "dispatch_box")); XtUnmanageChild(XtNameToWidget(dispatch_dlog, "dispatch_expr")); - } else if (*tag == 2) { + } + else if (*tag == 2) + { XtUnmanageChild(XtNameToWidget(dispatch_dlog, "dispatch_box")); XtManageChild(XtNameToWidget(dispatch_dlog, "dispatch_expr")); - } else { + } + else + { XtUnmanageChild(XtNameToWidget(dispatch_dlog, "dispatch_box")); XtUnmanageChild(XtNameToWidget(dispatch_dlog, "dispatch_expr")); } } } -static void expression_change_type_proc(Widget w, int *tag) { +static void expression_change_type_proc(Widget w, int *tag) +{ Widget expression_dlog; for (expression_dlog = w; expression_dlog && WidgetNameCmp(expression_dlog, "expression_dlog"); expression_dlog = expression_dlog->core.parent) ; - if (expression_dlog) { - if (*tag) { + if (expression_dlog) + { + if (*tag) + { XtManageChild(XtNameToWidget(expression_dlog, "expression_units_label")); XtManageChild(XtNameToWidget(expression_dlog, "expression_units")); XtManageChild(XtNameToWidget(expression_dlog, "expression_expr")); - } else { + } + else + { XtUnmanageChild( XtNameToWidget(expression_dlog, "expression_units_label")); XtUnmanageChild(XtNameToWidget(expression_dlog, "expression_units")); @@ -1621,27 +1828,36 @@ static void expression_change_type_proc(Widget w, int *tag) { } } -static void task_change_type_proc(Widget w, int *tag) { +static void task_change_type_proc(Widget w, int *tag) +{ Widget task_dlog; for (task_dlog = w; task_dlog && WidgetNameCmp(task_dlog, "task_dlog"); task_dlog = task_dlog->core.parent) ; - if (task_dlog) { - if (*tag == 1) { + if (task_dlog) + { + if (*tag == 1) + { XtManageChild(XtNameToWidget(task_dlog, "method_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "routine_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "task_expr")); - } else if (*tag == 2) { + } + else if (*tag == 2) + { XtUnmanageChild(XtNameToWidget(task_dlog, "method_box")); XtManageChild(XtNameToWidget(task_dlog, "routine_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "task_expr")); - } else if (*tag == 3) { + } + else if (*tag == 3) + { XtUnmanageChild(XtNameToWidget(task_dlog, "method_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "routine_box")); XtManageChild(XtNameToWidget(task_dlog, "task_expr")); - } else { + } + else + { XtUnmanageChild(XtNameToWidget(task_dlog, "method_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "routine_box")); XtUnmanageChild(XtNameToWidget(task_dlog, "task_expr")); @@ -1649,20 +1865,27 @@ static void task_change_type_proc(Widget w, int *tag) { } } -static void window_change_type_proc(Widget w, int *tag) { +static void window_change_type_proc(Widget w, int *tag) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); - if (xdbw) { - if (*tag == 1) { + if (xdbw) + { + if (*tag == 1) + { XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.window_dlog.window_box")); XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.window_dlog.window_expr")); - } else if (*tag == 2) { + } + else if (*tag == 2) + { XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.window_dlog.window_box")); XtManageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.window_dlog.window_expr")); - } else { + } + else + { XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, "detail_box.window_dlog.window_box")); XtUnmanageChild(XtNameToWidget(xdbw->xdbox.xdb_dlog, @@ -1675,18 +1898,23 @@ static void window_change_type_proc(Widget w, int *tag) { * Support routines. */ -static Boolean Apply(XmdsXdBoxWidget w) { +static Boolean Apply(XmdsXdBoxWidget w) +{ Boolean status = 1; - if (w->xdbox.loaded) { + if (w->xdbox.loaded) + { if (w->xdbox.auto_put && w->xdbox.nid) status = Put(w); - else { + else + { w->xdbox.xd = Unload(w->xdbox.specific_dlog); Load(w->xdbox.specific_dlog, w->xdbox.xd); - if (w->xdbox.nid) { + if (w->xdbox.nid) + { w->xdbox.on_off = XmToggleButtonGadgetGetState( XtNameToWidget(w->xdbox.xdb_dlog, "generic_box.on_off_toggle")); - if (w->xdbox.tag_list) { + if (w->xdbox.tag_list) + { XtFree((char *)w->xdbox.tag_list); w->xdbox.tag_list = 0; } @@ -1700,15 +1928,18 @@ static Boolean Apply(XmdsXdBoxWidget w) { } static void CalculateNewSize(XmdsXdBoxWidget w, unsigned short *width, - unsigned short *height) { + unsigned short *height) +{ Widget *children; int num; int right, bottom; int i; *width = *height = 0; XtVaGetValues((Widget)w, XmNchildren, &children, XmNnumChildren, &num, NULL); - for (i = 0; i < num; i++) { - if (XtIsManaged(children[i])) { + for (i = 0; i < num; i++) + { + if (XtIsManaged(children[i])) + { right = XtX(children[i]) + XtWidth(children[i]) + 2 * children[i]->core.border_width; bottom = XtY(children[i]) + XtHeight(children[i]) + @@ -1725,7 +1956,8 @@ static void CalculateNewSize(XmdsXdBoxWidget w, unsigned short *width, *width = 5; } -static XmdsXdBoxWidget FindXdBoxWidget(Widget w) { +static XmdsXdBoxWidget FindXdBoxWidget(Widget w) +{ Widget xdbw; for (xdbw = w; xdbw && WidgetNameCmp(xdbw, "xd_box"); xdbw = XtParent(xdbw)) ; @@ -1734,11 +1966,14 @@ static XmdsXdBoxWidget FindXdBoxWidget(Widget w) { return (XmdsXdBoxWidget)xdbw; } -static void GenericGet(XmdsXdBoxWidget w) { - if (w->xdbox.nid) { +static void GenericGet(XmdsXdBoxWidget w) +{ + if (w->xdbox.nid) + { int nid = w->xdbox.nid + w->xdbox.nid_offset; char *path = TreeGetMinimumPath(0, nid); - if (path) { + if (path) + { char *tag; static struct descriptor_d tags = {0, DTYPE_T, CLASS_D, 0}; static DESCRIPTOR(comma, ", "); @@ -1749,32 +1984,42 @@ static void GenericGet(XmdsXdBoxWidget w) { w->xdbox.path = strcpy(XtMalloc(strlen(path) + 1), path); TreeFree(path); status = TreeIsOn(nid); - if (status == TreeON) { + if (status == TreeON) + { w->xdbox.on_off = 1; w->xdbox.parent_on_off = 1; - } else if (status == TreeOFF) { + } + else if (status == TreeOFF) + { w->xdbox.on_off = 0; w->xdbox.parent_on_off = 1; - } else if (status == TreePARENT_OFF) { + } + else if (status == TreePARENT_OFF) + { w->xdbox.on_off = 1; w->xdbox.parent_on_off = 0; - } else if (status == TreeBOTH_OFF) { + } + else if (status == TreeBOTH_OFF) + { w->xdbox.on_off = 0; w->xdbox.parent_on_off = 0; } - if (w->xdbox.tag_list) { + if (w->xdbox.tag_list) + { XtFree((char *)w->xdbox.tag_list); w->xdbox.tag_list = 0; } - while ((tag = TreeFindNodeTags(nid, &ctx))) { + while ((tag = TreeFindNodeTags(nid, &ctx))) + { static struct descriptor tag_d = {0, DTYPE_T, CLASS_S, 0}; tag_d.length = strlen(tag); tag_d.pointer = tag; StrConcat((struct descriptor *)&tags, (struct descriptor *)&tags, &comma, &tag_d MDS_END_ARG); } - if (tags.length) { + if (tags.length) + { tags.length -= 2; tags.pointer += 2; w->xdbox.tag_list = DescToNull((struct descriptor_s *)&tags); @@ -1786,13 +2031,17 @@ static void GenericGet(XmdsXdBoxWidget w) { } } -static void GenericLoad(XmdsXdBoxWidget w) { - if (w->xdbox.path) { +static void GenericLoad(XmdsXdBoxWidget w) +{ + if (w->xdbox.path) + { XmString path_str = XmStringCreateSimple(w->xdbox.path); XtVaSetValues(XtNameToWidget(w->xdbox.xdb_dlog, "generic_box.path_label"), XmNlabelString, path_str, NULL); XmStringFree(path_str); - } else { + } + else + { XmString path_str = XmStringCreateSimple("No Path"); XtVaSetValues(XtNameToWidget(w->xdbox.xdb_dlog, "generic_box.path_label"), XmNlabelString, path_str, NULL); @@ -1821,7 +2070,8 @@ static void GenericLoad(XmdsXdBoxWidget w) { w->xdbox.parent_on_off, 0); } -static void Load(Widget w, struct descriptor_xd *xd) { +static void Load(Widget w, struct descriptor_xd *xd) +{ int old_def = SetDefault(w); XmdsXdUserPart *user; @@ -1831,7 +2081,8 @@ static void Load(Widget w, struct descriptor_xd *xd) { TreeSetDefaultNid(old_def); } -static Boolean NotEmptyXd(struct descriptor_xd *xd) { +static Boolean NotEmptyXd(struct descriptor_xd *xd) +{ Boolean ans; if (xd == 0) ans = 0; @@ -1845,30 +2096,36 @@ static Boolean NotEmptyXd(struct descriptor_xd *xd) { return ans; } -static Boolean Put(XmdsXdBoxWidget w) { +static Boolean Put(XmdsXdBoxWidget w) +{ int status = 1; static EMPTYXD(empty_xd); int nid = w->xdbox.nid + w->xdbox.nid_offset; - if (nid) { + if (nid) + { struct descriptor_xd *xd = 0; Boolean node_on; Boolean editing = (TreeIsOpen() == TreeOPEN_EDIT); char *tag_txt = 0; - if (w->xdbox.loaded) { + if (w->xdbox.loaded) + { xd = (struct descriptor_xd *)XmdsXdBoxGetXd((Widget)w); node_on = XmToggleButtonGadgetGetState( XtNameToWidget(w->xdbox.xdb_dlog, "generic_box.on_off_toggle")); if (editing) tag_txt = XmTextFieldGetString( XtNameToWidget(w->xdbox.xdb_dlog, "generic_box.tag_text")); - } else { + } + else + { xd = w->xdbox.xd ? w->xdbox.xd : &empty_xd; node_on = w->xdbox.on_off; if (editing) tag_txt = w->xdbox.tag_list; } - if (xd) { + if (xd) + { status = TreeIsOn(nid); if (node_on && ((status == TreeOFF) || (status == TreeBOTH_OFF))) status = TreeTurnOn(nid); @@ -1876,64 +2133,82 @@ static Boolean Put(XmdsXdBoxWidget w) { status = TreeTurnOff(nid); else status = 1; - if (status) { + if (status) + { status = PutIfChanged(nid, xd); - if (status) { - if (editing) { + if (status) + { + if (editing) + { TreeRemoveNodesTags(nid); UpdateTags((Widget)w, nid, tag_txt); } - } else + } + else XmdsComplain((Widget)w, "Error Writing Record to Tree"); - } else + } + else XmdsComplain((Widget)w, "Error turning node On/Off"); - if (w->xdbox.loaded) { + if (w->xdbox.loaded) + { MdsFree1Dx(xd, 0); XtFree((char *)xd); } - } else + } + else status = 0; } return status; } -static int SetDefault(Widget widg) { +static int SetDefault(Widget widg) +{ int ans; int def_nid = -1; XmdsXdBoxWidget w = FindXdBoxWidget(widg); - if (w) { - if (TreeIsOpen() & 1) { - if (w->xdbox.nid) { + if (w) + { + if (TreeIsOpen() & 1) + { + if (w->xdbox.nid) + { if (w->xdbox.default_nid != -1) def_nid = w->xdbox.default_nid; else def_nid = DefaultNid(w->xdbox.nid + w->xdbox.nid_offset); } } - if (def_nid != -1) { + if (def_nid != -1) + { TreeGetDefaultNid(&ans); TreeSetDefaultNid(def_nid); - } else + } + else ans = -1; - } else + } + else ans = -1; return ans; } -static struct descriptor_xd *Unload(Widget w) { +static struct descriptor_xd *Unload(Widget w) +{ XmdsXdBoxWidget xdbw = FindXdBoxWidget(w); static EMPTYXD(empty_xd); struct descriptor_xd *ans; - if (xdbw->xdbox.loaded) { + if (xdbw->xdbox.loaded) + { int old_def = SetDefault(w); XmdsXdUserPart *user; XtVaGetValues(w, XmNuserData, &user, NULL); ans = (*user->unload_dlog_proc)(w); if (old_def != -1) TreeSetDefaultNid(old_def); - } else { + } + else + { ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ans = empty_xd; MdsCopyDxXd((struct descriptor *)xdbw->xdbox.xd, ans); @@ -1941,10 +2216,12 @@ static struct descriptor_xd *Unload(Widget w) { return ans; } -static void UpdateTags(Widget w, int nid, char *tags) { +static void UpdateTags(Widget w, int nid, char *tags) +{ int status; char *t_ptr = strtok(tags, ", "); - while (t_ptr) { + while (t_ptr) + { status = TreeAddTag(nid, t_ptr); if (!status & 1) XmdsComplain(w, "Error adding tag %s to node number %d", t_ptr, nid); diff --git a/xmdsshr/XmdsXdBoxDialog.c b/xmdsshr/XmdsXdBoxDialog.c index a6154f11d8..2706ca3116 100644 --- a/xmdsshr/XmdsXdBoxDialog.c +++ b/xmdsshr/XmdsXdBoxDialog.c @@ -68,7 +68,8 @@ extern void XmdsXdBoxLoad(); the initial widget. ****************************************************/ EXPORT Widget XmdsCreateXdBoxDialog(Widget parent, char *name, ArgList args, - Cardinal argcount) { + Cardinal argcount) +{ /*------------------------------------------------------------------------------ @@ -122,9 +123,11 @@ EXPORT Widget XmdsCreateXdBoxDialog(Widget parent, char *name, ArgList args, XmNx and XmNy *************************************/ sub_args = (Arg *)XtMalloc(sizeof(Arg) * argcount); - for (i = 0, cnt = 0; i < argcount; i++) { + for (i = 0, cnt = 0; i < argcount; i++) + { if ((strcmp(args[i].name, XmNx) != 0) && - (strcmp(args[i].name, XmNy) != 0)) { + (strcmp(args[i].name, XmNy) != 0)) + { sub_args[cnt].name = args[i].name; sub_args[cnt++].value = args[i].value; } @@ -142,6 +145,7 @@ EXPORT Widget XmdsCreateXdBoxDialog(Widget parent, char *name, ArgList args, } static void LoadDialog(Widget shell, void *xdbw, - void *unused __attribute__((unused))) { + void *unused __attribute__((unused))) +{ XmdsXdBoxLoad((Widget)xdbw); } diff --git a/xmdsshr/XmdsXdBoxDialogButton.c b/xmdsshr/XmdsXdBoxDialogButton.c index 62ab6c5e3c..6b2e99f00e 100644 --- a/xmdsshr/XmdsXdBoxDialogButton.c +++ b/xmdsshr/XmdsXdBoxDialogButton.c @@ -77,7 +77,8 @@ Widget XmdsXdBoxDialogButtonGetXdBox(Widget w); #include #include -typedef struct _Resources { +typedef struct _Resources +{ int nid; int nid_offset; Boolean put_on_apply; @@ -97,7 +98,8 @@ static XtResource resources[] = { XtOffsetOf(Resources, put_on_apply), XmRImmediate, (void *)1}}; EXPORT Widget XmdsCreateXdBoxDialogButton(Widget parent, String name, - ArgList args, Cardinal argcount) { + ArgList args, Cardinal argcount) +{ Widget w; Resources *info = (Resources *)XtMalloc(sizeof(Resources)); Resources default_info = {0, 0, 1, 0}; @@ -119,23 +121,28 @@ EXPORT Widget XmdsCreateXdBoxDialogButton(Widget parent, String name, return w; } -static void Destroy(Widget w, Resources *info, XtPointer cb) { +static void Destroy(Widget w, Resources *info, XtPointer cb) +{ XtFree((char *)info); } -static void Popup(Widget w, Resources *info, XtPointer cb) { +static void Popup(Widget w, Resources *info, XtPointer cb) +{ if (info->popup_w) XmdsManageWindow(info->popup_w); } -EXPORT Boolean XmdsIsXdBoxDialogButton(Widget w) { +EXPORT Boolean XmdsIsXdBoxDialogButton(Widget w) +{ return GetResources(w) != 0; } -static Resources *GetResources(Widget w) { +static Resources *GetResources(Widget w) +{ Resources *answer = 0; if (XmIsPushButton(w) && - (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) { + (XtHasCallbacks(w, XmNdestroyCallback) == XtCallbackHasSome)) + { XtCallbackList callbacks; XtVaGetValues(w, XmNdestroyCallback, &callbacks, NULL); for (; callbacks->callback && @@ -149,24 +156,28 @@ static Resources *GetResources(Widget w) { return answer; } -EXPORT void XmdsXdBoxDialogButtonReset(Widget w) { +EXPORT void XmdsXdBoxDialogButtonReset(Widget w) +{ Resources *info = GetResources(w); if (info) XmdsXdBoxReset(info->popup_w); return; } -EXPORT int XmdsXdBoxDialogButtonPut(Widget w) { +EXPORT int XmdsXdBoxDialogButtonPut(Widget w) +{ Resources *info = GetResources(w); return info ? XmdsXdBoxPut(info->popup_w) : 0; } -EXPORT int XmdsXdBoxDialogButtonApply(Widget w) { +EXPORT int XmdsXdBoxDialogButtonApply(Widget w) +{ Resources *info = GetResources(w); return info ? XmdsXdBoxApply(info->popup_w) : 0; } -EXPORT Widget XmdsXdBoxDialogButtonGetXdBox(Widget w) { +EXPORT Widget XmdsXdBoxDialogButtonGetXdBox(Widget w) +{ Resources *info = GetResources(w); return info ? info->popup_w : 0; } diff --git a/xmdsshr/XmdsXdBoxOnOffButton.c b/xmdsshr/XmdsXdBoxOnOffButton.c index 3312dccd68..e53673e418 100644 --- a/xmdsshr/XmdsXdBoxOnOffButton.c +++ b/xmdsshr/XmdsXdBoxOnOffButton.c @@ -81,7 +81,8 @@ XmdsXdBoxOnOffButtonApply(Widget w); #include #include -typedef struct _Resources { +typedef struct _Resources +{ int nid; int nid_offset; Boolean put_on_apply; @@ -102,7 +103,8 @@ static void SetXdState(Widget w, Widget xd_w, XmToggleButtonCallbackStruct *cb); static void SetTbState(Widget w, Widget oo_w, XmdsButtonCallbackStruct *cb); EXPORT Widget XmdsCreateXdBoxOnOffButton(Widget parent, String name, - ArgList args, Cardinal argcount) { + ArgList args, Cardinal argcount) +{ Widget w; Resources info = {0, 0, 1, 0}; XmdsSetSubvalues(&info, resources, XtNumber(resources), args, argcount); @@ -137,27 +139,33 @@ EXPORT Widget XmdsCreateXdBoxOnOffButton(Widget parent, String name, } static void SetXdState(Widget w, Widget xd_w, - XmToggleButtonCallbackStruct *cb) { + XmToggleButtonCallbackStruct *cb) +{ XmdsXdBoxSetState(xd_w, cb->set); } -static void SetTbState(Widget w, Widget oo_w, XmdsButtonCallbackStruct *cb) { +static void SetTbState(Widget w, Widget oo_w, XmdsButtonCallbackStruct *cb) +{ XmToggleButtonSetState(oo_w, cb->on_off, 0); } -EXPORT Boolean XmdsIsXdBoxOnOffButton(Widget w) { +EXPORT Boolean XmdsIsXdBoxOnOffButton(Widget w) +{ return XtNameToWidget(w, "xmds_xdbox_on_off") && XtNameToWidget(w, "xmds_xdbox_dialog_button"); } -EXPORT void XmdsXdBoxOnOffButtonReset(Widget w) { - if (XmdsIsXdBoxOnOffButton(w)) { +EXPORT void XmdsXdBoxOnOffButtonReset(Widget w) +{ + if (XmdsIsXdBoxOnOffButton(w)) + { XmdsOnOffToggleButtonReset(XtNameToWidget(w, "xmds_xdbox_on_off")); XmdsXdBoxDialogButtonReset(XtNameToWidget(w, "xmds_xdbox_dialog_button")); } } -EXPORT int XmdsXdBoxOnOffButtonPut(Widget w) { +EXPORT int XmdsXdBoxOnOffButtonPut(Widget w) +{ int status = 0; if (XmdsIsXdBoxOnOffButton(w)) if ((status = @@ -168,7 +176,8 @@ EXPORT int XmdsXdBoxOnOffButtonPut(Widget w) { return status; } -EXPORT int XmdsXdBoxOnOffButtonApply(Widget w) { +EXPORT int XmdsXdBoxOnOffButtonApply(Widget w) +{ int status = 0; if (XmdsIsXdBoxOnOffButton(w)) if ((status = XmdsOnOffToggleButtonApply( diff --git a/xmdsshr/wmldbcreate-xmdsshr.c b/xmdsshr/wmldbcreate-xmdsshr.c index 6a91a68d53..ffbe9ddfaf 100644 --- a/xmdsshr/wmldbcreate-xmdsshr.c +++ b/xmdsshr/wmldbcreate-xmdsshr.c @@ -228,22 +228,29 @@ char **argv; strcpy(outfilename, "motif.wmd"); strcpy(debugfilename, "motif.dbg"); - for (argc--, argv++; argc; argc--, argv++) { - if (strcmp("-debug", *argv) == 0) { + for (argc--, argv++; argc; argc--, argv++) + { + if (strcmp("-debug", *argv) == 0) + { DEBUG = TRUE; - } else if ((strcmp("-o", *argv) == 0)) { + } + else if ((strcmp("-o", *argv) == 0)) + { strcpy(outfilename, argv[1]); } } bfile = fopen(outfilename, "w"); - if (bfile == (FILE *)NULL) { + if (bfile == (FILE *)NULL) + { printf("\nCouldnt't open %s", outfilename); return; } - if (DEBUG) { + if (DEBUG) + { afile = fopen(debugfilename, "w"); - if (afile == (FILE *)NULL) { + if (afile == (FILE *)NULL) + { printf("\nCouldn't open %s", debugfilename); return; } @@ -318,7 +325,8 @@ char **argv; exit(0); } -emit_globals() { +emit_globals() +{ _db_globals globals; globals.version = DB_Compiled_Version; @@ -358,7 +366,8 @@ emit_chars(table_id) int table_id; unsigned char *ptr; int i; - switch (table_id) { + switch (table_id) + { case Constraint_Tab: /* * NOTE: The first entry is not used but we copy it anyway @@ -418,8 +427,10 @@ emit_chars(table_id) int table_id; emit_header(&header); fwrite(ptr, header.table_size, 1, bfile); - if (DEBUG) { - for (i = 0; i <= header.num_items; i++) { + if (DEBUG) + { + for (i = 0; i <= header.num_items; i++) + { fprintf(afile, "%d ", ptr[i]); } } @@ -431,7 +442,8 @@ emit_ints_and_string(table_id) int table_id; key_keytable_entry_type *table; int i; - switch (table_id) { + switch (table_id) + { /* * All tables are zero based unless otherwise noted */ @@ -451,7 +463,8 @@ emit_ints_and_string(table_id) int table_id; emit_header(&header); fwrite(table, header.table_size, 1, bfile); - for (i = 0; i < header.num_items; i++) { + for (i = 0; i < header.num_items; i++) + { fwrite(table[i].at_name, table[i].b_length + 1, 1, bfile); if (DEBUG) fprintf(afile, "%d %d %d %d %s", table[i].b_class, table[i].b_subclass, @@ -467,7 +480,8 @@ emit_char_table(table_id) int table_id; int i, j; int num_bits = (uil_max_object + 7) / 8; - switch (table_id) { + switch (table_id) + { /* * All tables are 1 based unless otherwise specified */ @@ -499,11 +513,14 @@ emit_char_table(table_id) int table_id; emit_header(&header); - for (i = 1; i <= header.num_items; i++) { /* First not used */ + for (i = 1; i <= header.num_items; i++) + { /* First not used */ entry_vec = table[i]; fwrite(entry_vec, sizeof(char) * num_bits, 1, bfile); - if (DEBUG) { - for (j = 0; j < num_bits; j++) { + if (DEBUG) + { + for (j = 0; j < num_bits; j++) + { fprintf(afile, "%d, ", entry_vec[j]); } fprintf(afile, "\n"); @@ -519,7 +536,8 @@ emit_length_and_string(table_id) int table_id; char **table; int i; - switch (table_id) { + switch (table_id) + { /* * all the tables are 1 based unless otherwise documented */ @@ -598,21 +616,27 @@ emit_length_and_string(table_id) int table_id; lengths = (int *)malloc(sizeof(int) * (header.num_items + 1)); - for (i = 0; i <= header.num_items; i++) { - if (table[i] != NULL) { + for (i = 0; i <= header.num_items; i++) + { + if (table[i] != NULL) + { /* * Add one to the length for the null terminator */ lengths[i] = strlen(table[i]) + 1; - } else { + } + else + { lengths[i] = 0; } if (DEBUG) fprintf(afile, "%d ", lengths[i]); } fwrite(lengths, sizeof(int) * (header.num_items + 1), 1, bfile); - for (i = 0; i <= header.num_items; i++) { - if (lengths[i]) { + for (i = 0; i <= header.num_items; i++) + { + if (lengths[i]) + { /* * assumed lengths[i] = lengths[i] * sizeof(char) * Add one for the null terminator @@ -631,7 +655,8 @@ emit_shorts(table_id) int table_id; unsigned short int *ptr; int i; - switch (table_id) { + switch (table_id) + { /* * All tables are 1 based unless otherwise noted */ @@ -679,8 +704,10 @@ emit_shorts(table_id) int table_id; emit_header(&header); fwrite(ptr, header.table_size, 1, bfile); - if (DEBUG) { - for (i = 0; i < header.num_items; i++) { + if (DEBUG) + { + for (i = 0; i < header.num_items; i++) + { fprintf(afile, "%d ", ptr[i]); } } @@ -693,7 +720,8 @@ emit_int_and_table_shorts(table_id) int table_id; int j, i; unsigned short int *value_vec; - switch (table_id) { + switch (table_id) + { /* * All tables are 1 based unless otherwise noted */ @@ -707,8 +735,10 @@ emit_int_and_table_shorts(table_id) int table_id; emit_header(&header); fwrite(table, header.table_size, 1, bfile); - for (i = 0; i <= header.num_items; i++) { /* first is not used */ - if (table[i].values_cnt) { + for (i = 0; i <= header.num_items; i++) + { /* first is not used */ + if (table[i].values_cnt) + { fwrite(table[i].values, sizeof(short) * table[i].values_cnt, 1, bfile); } } @@ -736,8 +766,10 @@ emit_ints(table_id) int table_id; emit_header(&header); fwrite(ptr, header.table_size, 1, bfile); - if (DEBUG) { - for (i = 0; i < header.num_items; i++) { + if (DEBUG) + { + for (i = 0; i < header.num_items; i++) + { fprintf(afile, "%d ", ptr[i]); } } diff --git a/xtreeshr/XTreeConvertToLongTime.c b/xtreeshr/XTreeConvertToLongTime.c index ec375df04c..3976bf66f1 100644 --- a/xtreeshr/XTreeConvertToLongTime.c +++ b/xtreeshr/XTreeConvertToLongTime.c @@ -36,17 +36,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Convert a time expression to 64 bit integer #define L9223372036854775807L 0x7fffffffffffffffL -EXPORT int XTreeConvertToLongTime(mdsdsc_t *timeD, int64_t *retTime) { +EXPORT int XTreeConvertToLongTime(mdsdsc_t *timeD, int64_t *retTime) +{ int status; EMPTYXD(xd); FREEXD_ON_EXIT(&xd); status = TdiData(timeD, &xd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; if (!xd.pointer || xd.pointer->class != CLASS_S) status = MDSplusERROR; // InvalidTimeFormat else - switch (xd.pointer->dtype) { + switch (xd.pointer->dtype) + { case DTYPE_B: *retTime = ((int64_t) * (int8_t *)xd.pointer->pointer) * 1000000000L; break; @@ -74,40 +76,43 @@ EXPORT int XTreeConvertToLongTime(mdsdsc_t *timeD, int64_t *retTime) { else *retTime = *(int64_t *)xd.pointer->pointer; break; - default: { + default: + { // Not a 64 bit integer, try to convert it via float or double * 1e9 status = TdiFloat((mdsdsc_t *)&xd, &xd MDS_END_ARG); - if - STATUS_OK { - double dbl; - if (xd.pointer->dtype == DTYPE_DOUBLE) - dbl = *(double *)xd.pointer->pointer; - else - dbl = *(float *)xd.pointer->pointer; - if (dbl < -9223372036.854775807) - *retTime = -L9223372036854775807L - 1; - else if (dbl > 9223372036.854775806) - *retTime = L9223372036854775807L; - else - *retTime = (int64_t)(dbl * 1e9); - } + if (STATUS_OK) + { + double dbl; + if (xd.pointer->dtype == DTYPE_DOUBLE) + dbl = *(double *)xd.pointer->pointer; + else + dbl = *(float *)xd.pointer->pointer; + if (dbl < -9223372036.854775807) + *retTime = -L9223372036854775807L - 1; + else if (dbl > 9223372036.854775806) + *retTime = L9223372036854775807L; + else + *retTime = (int64_t)(dbl * 1e9); + } } } FREEXD_NOW(&xd); return status; } -EXPORT int XTreeConvertToDouble(mdsdsc_t *const timeD, double *const retTime) { +EXPORT int XTreeConvertToDouble(mdsdsc_t *const timeD, double *const retTime) +{ int status; EMPTYXD(xd); FREEXD_ON_EXIT(&xd); status = TdiData(timeD, &xd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; if (!xd.pointer || xd.pointer->class != CLASS_S) status = MDSplusERROR; // InvalidTimeFormat else - switch (xd.pointer->dtype) { + switch (xd.pointer->dtype) + { case DTYPE_B: *retTime = (double)*(int8_t *)xd.pointer->pointer; break; @@ -138,15 +143,16 @@ EXPORT int XTreeConvertToDouble(mdsdsc_t *const timeD, double *const retTime) { case DTYPE_DOUBLE: *retTime = *(double *)xd.pointer->pointer; break; - default: { + default: + { status = TdiFloat((mdsdsc_t *)&xd, &xd MDS_END_ARG); - if - STATUS_OK { - if (xd.pointer->dtype == DTYPE_DOUBLE) - *retTime = *(double *)xd.pointer->pointer; - else - *retTime = *(float *)xd.pointer->pointer; - } + if (STATUS_OK) + { + if (xd.pointer->dtype == DTYPE_DOUBLE) + *retTime = *(double *)xd.pointer->pointer; + else + *retTime = *(float *)xd.pointer->pointer; + } } } FREEXD_NOW(&xd); diff --git a/xtreeshr/XTreeDefaultResample.c b/xtreeshr/XTreeDefaultResample.c index f598861e9e..1691d77f94 100644 --- a/xtreeshr/XTreeDefaultResample.c +++ b/xtreeshr/XTreeDefaultResample.c @@ -33,7 +33,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -typedef enum { +typedef enum +{ AVERAGE, INTERPOLATION, CLOSEST, @@ -56,8 +57,10 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_xd_t *outSignalXd); inline static double *convertTimebaseToDouble(mds_signal_t *inSignalD, - int *outSamples, dtype_t *isQ) { - if (inSignalD->ndesc < 3) { + int *outSamples, dtype_t *isQ) +{ + if (inSignalD->ndesc < 3) + { ARRAY_COEFF(char *, MAX_DIMS) *dataD = (void *)inSignalD->data; if (dataD->dimct == 1) *outSamples = dataD->arsize / dataD->length; @@ -69,22 +72,24 @@ inline static double *convertTimebaseToDouble(mds_signal_t *inSignalD, EMPTYXD(currXd); int numSamples, i; mdsdsc_a_t *currDim = (mdsdsc_a_t *)inSignalD->dimensions[0]; - if (currDim->class != CLASS_A) { - if - IS_NOT_OK(TdiData(currDim, &currXd MDS_END_ARG)) - goto return_out; + if (currDim->class != CLASS_A) + { + if (IS_NOT_OK(TdiData(currDim, &currXd MDS_END_ARG))) + goto return_out; currDim = (mdsdsc_a_t *)currXd.pointer; } if (currDim->class != CLASS_A || currDim->arsize == 0) goto return_out; - if (currDim->dtype == DTYPE_DOUBLE) { + if (currDim->dtype == DTYPE_DOUBLE) + { numSamples = currDim->arsize / currDim->length; outPtr = malloc(currDim->arsize); memcpy(outPtr, currDim->pointer, currDim->arsize); *outSamples = numSamples; goto return_out; } - if (currDim->dtype == DTYPE_Q || currDim->dtype == DTYPE_QU) { + if (currDim->dtype == DTYPE_Q || currDim->dtype == DTYPE_QU) + { *isQ = currDim->dtype; outPtr = malloc(currDim->arsize); numSamples = currDim->arsize / currDim->length; @@ -93,10 +98,10 @@ inline static double *convertTimebaseToDouble(mds_signal_t *inSignalD, *outSamples = numSamples; goto return_out; } - if (currDim->dtype != DTYPE_FLOAT) { - if - IS_NOT_OK(TdiFloat(currDim, &currXd MDS_END_ARG)) - goto return_out; + if (currDim->dtype != DTYPE_FLOAT) + { + if (IS_NOT_OK(TdiFloat(currDim, &currXd MDS_END_ARG))) + goto return_out; currDim = (mdsdsc_a_t *)currXd.pointer; } if (currDim->class != CLASS_A || @@ -104,11 +109,13 @@ inline static double *convertTimebaseToDouble(mds_signal_t *inSignalD, goto return_out; // Cannot perform conversion numSamples = currDim->arsize / currDim->length; outPtr = malloc(sizeof(double) * numSamples); - if (currDim->dtype == DTYPE_FLOAT) { + if (currDim->dtype == DTYPE_FLOAT) + { const float *floatPtr = (float *)currDim->pointer; for (i = 0; i < numSamples; i++) outPtr[i] = floatPtr[i]; - } else // currDim->dtype == DTYPE_DOUBLE) + } + else // currDim->dtype == DTYPE_DOUBLE) memcpy(outPtr, currDim->pointer, currDim->arsize); *outSamples = numSamples; return_out:; @@ -118,7 +125,8 @@ return_out:; EXPORT mdsdsc_xd_t *XTreeResampleClosest(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, - mdsdsc_t *deltaD) { // deprecated + mdsdsc_t *deltaD) +{ // deprecated static EMPTYXD(retXd); XTreeDefaultResampleMode(inSignalD, startD, endD, deltaD, CLOSEST, &retXd); return &retXd; @@ -126,13 +134,15 @@ EXPORT mdsdsc_xd_t *XTreeResampleClosest(mds_signal_t *inSignalD, EXPORT mdsdsc_xd_t *XTreeResamplePrevious(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, - mdsdsc_t *deltaD) { // deprecated + mdsdsc_t *deltaD) +{ // deprecated static EMPTYXD(retXd); XTreeDefaultResampleMode(inSignalD, startD, endD, deltaD, PREVIOUS, &retXd); return &retXd; } -static inline res_mode_t get_default() { +static inline res_mode_t get_default() +{ char *resampleMode = TranslateLogical("MDSPLUS_DEFAULT_RESAMPLE_MODE"); if (!resampleMode) return AVERAGE; @@ -150,7 +160,8 @@ static inline res_mode_t get_default() { default_mode = CLOSEST; else if (!strncasecmp(resampleMode, "Previous", len)) default_mode = PREVIOUS; - else { + else + { fprintf(stderr, "Error: Resample mode must be one of 'Average', 'MinMax', " "'Interpolation', 'Closest', or 'Previous' but was '%s'; using " @@ -163,18 +174,20 @@ static inline res_mode_t get_default() { } int XTreeDefaultResample(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, mdsdsc_t *deltaD, - mdsdsc_xd_t *outSignalXd) { + mdsdsc_xd_t *outSignalXd) +{ // get_env is cheap compared to what is comming next, we can affort to reload // it return XTreeDefaultResampleMode(inSignalD, startD, endD, deltaD, get_default(), outSignalXd); } -#define RESAMPLE_FUN(name, mode) \ - int name(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, \ - mdsdsc_t *deltaD, mdsdsc_xd_t *outSignalXd) { \ - return XTreeDefaultResampleMode(inSignalD, startD, endD, deltaD, mode, \ - outSignalXd); \ +#define RESAMPLE_FUN(name, mode) \ + int name(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, \ + mdsdsc_t *deltaD, mdsdsc_xd_t *outSignalXd) \ + { \ + return XTreeDefaultResampleMode(inSignalD, startD, endD, deltaD, mode, \ + outSignalXd); \ } EXPORT RESAMPLE_FUN(XTreeAverageResample, AVERAGE) EXPORT @@ -188,28 +201,32 @@ EXPORT RESAMPLE_FUN(XTreeAverageResample, AVERAGE) EXPORT static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, mdsdsc_t *deltaD, const res_mode_t mode, - mdsdsc_xd_t *outSignalXd) { + mdsdsc_xd_t *outSignalXd) +{ int status; // Get shapes(dimensions) for data EMPTYXD(dataXd); mdsdsc_a_t *dataD; - if (inSignalD->data->class == CLASS_A) { + if (inSignalD->data->class == CLASS_A) + { dataD = (mdsdsc_a_t *)inSignalD->data; - } else { + } + else + { status = TdiData(inSignalD->data, &dataXd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; dataD = (mdsdsc_a_t *)dataXd.pointer; } int dims[MAX_DIMS]; int numDims; status = getShape((mdsdsc_t *)dataD, dims, &numDims); - if - STATUS_NOT_OK { - MdsFree1Dx(&dataXd, 0); - return status; - } + if (STATUS_NOT_OK) + { + MdsFree1Dx(&dataXd, 0); + return status; + } // get timebase dtype_t isQ = 0; @@ -218,7 +235,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, ? (int)(dataD->arsize / dataD->length) : dims[numDims - 1]; fulltimebase = convertTimebaseToDouble(inSignalD, &numTimebase, &isQ); - if (!fulltimebase) { + if (!fulltimebase) + { MdsFree1Dx(&dataXd, 0); MdsCopyDxXd((mdsdsc_t *)&inSignalD, outSignalXd); return 3; // Cannot convert timebase to 64 bit int @@ -229,29 +247,35 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, numTimebase = numData; int startIdx = 0; - if (startD) { + if (startD) + { status = XTreeConvertToDouble(startD, &start); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; if (start < fulltimebase[0]) start = fulltimebase[0]; for (; startIdx < numTimebase && fulltimebase[startIdx] < start; startIdx++) ; - } else + } + else start = fulltimebase[0]; - if (endD) { + if (endD) + { status = XTreeConvertToDouble(endD, &end); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; if (end > fulltimebase[numTimebase - 1]) end = fulltimebase[numTimebase - 1]; - } else + } + else end = fulltimebase[numTimebase - 1]; - if (deltaD) { + if (deltaD) + { status = XTreeConvertToDouble(deltaD, &delta); - if - STATUS_NOT_OK return status; - } else + if (STATUS_NOT_OK) + return status; + } + else delta = 0; int i, j; @@ -260,8 +284,11 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, int numDataItems = itemSize / dataD->length; int outItemSize; DESCRIPTOR_A_COEFF(outDataArray, 0, 0, 0, MAX_DIMS, 0); - if (mode == AVERAGE && delta > 0) { // use FLOAT or DOUBLE - } else { + if (mode == AVERAGE && delta > 0) + { // use FLOAT or DOUBLE + } + else + { outDataArray.length = dataD->length; outDataArray.dtype = dataD->dtype; } @@ -273,11 +300,13 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, double *timebase = &fulltimebase[startIdx]; char *data = &dataD->pointer[startIdx * itemSize]; int outSamples = 0; - if (delta > 0 && startIdx < numTimebase) { + if (delta > 0 && startIdx < numTimebase) + { double refTime = start; double delta1 = delta / 2; double delta2 = delta + delta1; - switch (mode) { + switch (mode) + { case MINMAX: case AVERAGE: refTime += delta; @@ -287,16 +316,22 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, break; } int reqSamples = (int)((end - start) / delta + 1.5); - if (mode == AVERAGE) { // use FLOAT or DOUBLE - if (dataD->length < 8) { + if (mode == AVERAGE) + { // use FLOAT or DOUBLE + if (dataD->length < 8) + { outDataArray.length = sizeof(float); outDataArray.dtype = DTYPE_FLOAT; - } else { + } + else + { outDataArray.length = sizeof(double); outDataArray.dtype = DTYPE_DOUBLE; } outItemSize = itemSize * outDataArray.length / dataD->length; - } else { + } + else + { if (mode == MINMAX) reqSamples *= 2; // Make enough room for MINMAX mode outItemSize = itemSize; @@ -306,12 +341,15 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, outData = malloc(reqSamples * outItemSize); outDim = malloc(reqSamples * sizeof(double)); int prevTimebaseIdx = timebaseIdx; - while (refTime <= end) { + while (refTime <= end) + { while (timebaseIdx < timebaseSamples && timebase[timebaseIdx] < refTime) timebaseIdx++; - switch (mode) { + switch (mode) + { case CLOSEST: // Select closest sample - if (timebaseIdx > 0) { + if (timebaseIdx > 0) + { delta1 = timebase[timebaseIdx] - refTime; delta2 = refTime - timebase[timebaseIdx - 1]; if (delta2 < delta1) @@ -328,7 +366,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, break; case INTERPOLATION: #define INTERPOLATION_FORLOOP(type) \ - for (i = 0; i < numDataItems; i++) { \ + for (i = 0; i < numDataItems; i++) \ + { \ prevData = ((type *)(&data[(timebaseIdx - 1) * itemSize]))[i]; \ nextData = ((type *)(&data[timebaseIdx * itemSize]))[i]; \ currData = prevData + \ @@ -338,7 +377,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, } if (timebaseIdx <= 0) timebaseIdx = 1; // Avoid referring to negative indexes - switch (dataD->dtype) { + switch (dataD->dtype) + { case DTYPE_BU: INTERPOLATION_FORLOOP(uint8_t); break; @@ -374,21 +414,24 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, } break; case MINMAX: // Two points for every (resampled) sample!!!!!!!!!!! -#define MINMAX_FORLOOP(type) \ - for (i = 0; i < numDataItems; i++) { \ - type currData, minData, maxData; \ - minData = maxData = ((type *)(&data[(prevTimebaseIdx)*itemSize]))[i]; \ - for (j = prevTimebaseIdx + 1; j < timebaseIdx && j < numTimebase; j++) { \ - currData = ((type *)(&data[j * itemSize]))[i]; \ - if (currData > maxData) \ - maxData = currData; \ - if (currData < minData) \ - minData = currData; \ - } \ - ((type *)(&outData[(outSamples)*outItemSize]))[i] = minData; \ - ((type *)(&outData[(outSamples + 1) * outItemSize]))[i] = maxData; \ +#define MINMAX_FORLOOP(type) \ + for (i = 0; i < numDataItems; i++) \ + { \ + type currData, minData, maxData; \ + minData = maxData = ((type *)(&data[(prevTimebaseIdx)*itemSize]))[i]; \ + for (j = prevTimebaseIdx + 1; j < timebaseIdx && j < numTimebase; j++) \ + { \ + currData = ((type *)(&data[j * itemSize]))[i]; \ + if (currData > maxData) \ + maxData = currData; \ + if (currData < minData) \ + minData = currData; \ + } \ + ((type *)(&outData[(outSamples)*outItemSize]))[i] = minData; \ + ((type *)(&outData[(outSamples + 1) * outItemSize]))[i] = maxData; \ } - switch (dataD->dtype) { + switch (dataD->dtype) + { case DTYPE_BU: MINMAX_FORLOOP(uint8_t); break; @@ -424,16 +467,18 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, } break; case AVERAGE: -#define AVERAGE_FORLOOP(type_out, type) \ - for (i = 0; i < numDataItems; i++) { \ - type_out accData = ((type *)(&data[(prevTimebaseIdx)*itemSize]))[i]; \ - for (j = prevTimebaseIdx + 1; j < timebaseIdx; j++) \ - accData += ((type *)(&data[j * itemSize]))[i]; \ - const int range = (timebaseIdx - prevTimebaseIdx); \ - ((type_out *)(&outData[outSamples * outItemSize]))[i] = \ - range > 0 ? accData / range : accData; \ +#define AVERAGE_FORLOOP(type_out, type) \ + for (i = 0; i < numDataItems; i++) \ + { \ + type_out accData = ((type *)(&data[(prevTimebaseIdx)*itemSize]))[i]; \ + for (j = prevTimebaseIdx + 1; j < timebaseIdx; j++) \ + accData += ((type *)(&data[j * itemSize]))[i]; \ + const int range = (timebaseIdx - prevTimebaseIdx); \ + ((type_out *)(&outData[outSamples * outItemSize]))[i] = \ + range > 0 ? accData / range : accData; \ } - switch (dataD->dtype) { + switch (dataD->dtype) + { case DTYPE_BU: AVERAGE_FORLOOP(float, uint8_t); break; @@ -475,7 +520,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, &data[timebaseIdx * itemSize], itemSize); break; } - switch (mode) { + switch (mode) + { case MINMAX: case AVERAGE: refTime -= delta1; @@ -491,7 +537,9 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, } prevTimebaseIdx = timebaseIdx; } - } else { // delta <= 0 + } + else + { // delta <= 0 while (timebaseIdx < timebaseSamples && timebase[timebaseIdx] <= end) timebaseIdx++; outData = data; @@ -513,7 +561,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, outDataArray.m[numDims - 1] = outSamples; // If originally float, convert dimension to float int64_t *timebaseQ; - if (isQ) { + if (isQ) + { timebaseQ = (int64_t *)malloc(outSamples * sizeof(int64_t)); for (i = 0; i < outSamples; i++) timebaseQ[i] = (int64_t)((outDim[i] * 1e9) + 0.5); @@ -521,7 +570,9 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, outDimArray.arsize = sizeof(int64_t) * outSamples; outDimArray.dtype = isQ; outDimArray.pointer = outDataArray.a0 = (char *)timebaseQ; - } else { + } + else + { timebaseQ = NULL; outDimArray.length = sizeof(double); outDimArray.arsize = sizeof(double) * outSamples; @@ -532,7 +583,8 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, MdsCopyDxXd((mdsdsc_t *)&outSignalD, outSignalXd); free(fulltimebase); free(timebaseQ); - if (timebase != outDim) { + if (timebase != outDim) + { free(outData); free(outDim); } diff --git a/xtreeshr/XTreeDefaultSquish.c b/xtreeshr/XTreeDefaultSquish.c index 056b665ed7..9c1b1c43b5 100644 --- a/xtreeshr/XTreeDefaultSquish.c +++ b/xtreeshr/XTreeDefaultSquish.c @@ -32,27 +32,32 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -int getShape(struct descriptor *dataD, int *dims, int *numDims) { +int getShape(struct descriptor *dataD, int *dims, int *numDims) +{ /* * returns 1-D and N-D shaped arrays */ ARRAY_COEFF(char *, MAX_DIMS) * arrPtr; - if (dataD->class != CLASS_A) { + if (dataD->class != CLASS_A) + { *numDims = 1; dims[0] = 0; return 0; } arrPtr = (void *)dataD; - if (arrPtr->dimct == 1) { + if (arrPtr->dimct == 1) + { *numDims = 1; dims[0] = arrPtr->arsize / arrPtr->length; - } else + } + else memcpy(dims, arrPtr->m, (*numDims = arrPtr->dimct) * sizeof(*arrPtr->m)); return 1; } static inline int checkShapes(struct descriptor_a *signalsApd, int *totShapes, - int *outShape) { + int *outShape) +{ /* * checks if data shapes are fit for concatenation */ @@ -63,14 +68,16 @@ static inline int checkShapes(struct descriptor_a *signalsApd, int *totShapes, int minNumShapes = 0, maxNumShapes = 0; int *numShapes = (int *)malloc(numSignals * sizeof(int)); int **shapes = (int **)malloc(numSignals * sizeof(int *)); - for (i = 0; i < numSignals; i++) { + for (i = 0; i < numSignals; i++) + { currSignalD = ((struct descriptor_signal **)signalsApd->pointer)[i]; shapes[i] = (int *)malloc(54 * sizeof(int)); getShape((struct descriptor *)(currSignalD->data), shapes[i], &numShapes[i]); if (i == 0) minNumShapes = maxNumShapes = numShapes[i]; - else { + else + { if (numShapes[i] < minNumShapes) minNumShapes = numShapes[i]; if (numShapes[i] > maxNumShapes) @@ -90,21 +97,22 @@ static inline int checkShapes(struct descriptor_a *signalsApd, int *totShapes, if (shapes[i][j] != shapes[0][j]) status = InvalidShapeInSegments; - if - STATUS_OK { - // Shapes Ok, build definitive shapes array for this signal; - for (i = 0; i < minNumShapes; i++) - outShape[i] = shapes[0][i]; - int lastDimension = 0; - for (i = 0; i < numSignals; i++) { - if (numShapes[i] == maxNumShapes) - lastDimension += shapes[i][numShapes[i] - 1]; - else - lastDimension++; - } - *totShapes = maxNumShapes; - outShape[*totShapes - 1] = lastDimension; + if (STATUS_OK) + { + // Shapes Ok, build definitive shapes array for this signal; + for (i = 0; i < minNumShapes; i++) + outShape[i] = shapes[0][i]; + int lastDimension = 0; + for (i = 0; i < numSignals; i++) + { + if (numShapes[i] == maxNumShapes) + lastDimension += shapes[i][numShapes[i] - 1]; + else + lastDimension++; } + *totShapes = maxNumShapes; + outShape[*totShapes - 1] = lastDimension; + } else *totShapes = 0; @@ -117,7 +125,8 @@ static inline int checkShapes(struct descriptor_a *signalsApd, int *totShapes, } static inline int checkNumDimensions(struct descriptor_a *signalsApd, - int *numDimensions) { + int *numDimensions) +{ /* * checks if dimensions are fit for merge */ @@ -130,7 +139,8 @@ static inline int checkNumDimensions(struct descriptor_a *signalsApd, return 1; } -static inline int checkRanges(struct descriptor_a *signalsApd) { +static inline int checkRanges(struct descriptor_a *signalsApd) +{ /* * checks if class and dtypes of dimensions are fit for mergeRanges */ @@ -147,7 +157,8 @@ static inline int checkRanges(struct descriptor_a *signalsApd) { (!firstRangeD->begin || firstRangeD->begin->class != CLASS_S)) return B_FALSE; // delta given but invalid int i, numSignals = signalsApd->arsize / signalsApd->length; - for (i = 1; i < numSignals; i++) { + for (i = 1; i < numSignals; i++) + { currSignalD = ((struct descriptor_signal **)signalsApd->pointer)[i]; struct descriptor_range *currRangeD = (struct descriptor_range *)currSignalD->dimensions[0]; @@ -168,7 +179,8 @@ static inline int checkRanges(struct descriptor_a *signalsApd) { static inline struct descriptor * mergeRanges(struct descriptor_a *signalsApd, - struct descriptor_range *outRangeD) { + struct descriptor_range *outRangeD) +{ /* * combines all Range dimensions into one total dimension */ @@ -191,7 +203,8 @@ mergeRanges(struct descriptor_a *signalsApd, rangeD->ending->length * numSignals; ((struct descriptor_a *)outRangeD->ending)->pointer = malloc(rangeD->ending->length * numSignals); - if (rangeD->ndesc > 2) { + if (rangeD->ndesc > 2) + { ((struct descriptor_a *)outRangeD->deltaval)->length = rangeD->deltaval->length; ((struct descriptor_a *)outRangeD->deltaval)->dtype = @@ -200,10 +213,12 @@ mergeRanges(struct descriptor_a *signalsApd, rangeD->deltaval->length * numSignals; ((struct descriptor_a *)outRangeD->deltaval)->pointer = malloc(rangeD->deltaval->length * numSignals); - } else + } + else outRangeD->ndesc = 2; int i; - for (i = 0; i < numSignals; i++) { + for (i = 0; i < numSignals; i++) + { rangeD = (struct descriptor_range *)((((struct descriptor_signal **) signalsApd->pointer)[i]) ->dimensions[0]); @@ -225,7 +240,8 @@ static EMPTYXD(emptyXd); static inline int mergeArrays(struct descriptor_a *signalsApd, struct descriptor_xd **dimensionsXd, struct descriptor_a *outDimD, char **arraysBuf, - char **outDimBuf) { + char **outDimBuf) +{ /* * converts all dimensions into arrays and concatenates to total array */ @@ -242,31 +258,33 @@ static inline int mergeArrays(struct descriptor_a *signalsApd, malloc(numSignals * sizeof(char *))); // Evaluate first dimension for all segments int totSize = 0; - for (i = 0; i < numSignals; i++) { + for (i = 0; i < numSignals; i++) + { struct descriptor_signal *currSignalD = ((struct descriptor_signal **)signalsApd->pointer)[i]; if (currSignalD->dimensions[0]->class == CLASS_A) // Data evaluation not needed arraysD[i] = arrayD = (struct descriptor_a *)currSignalD->dimensions[0]; - else { + else + { extern int TdiData(); status = TdiData(currSignalD->dimensions[0], &(*dimensionsXd)[i] MDS_END_ARG); - if - STATUS_NOT_OK - break; + if (STATUS_NOT_OK) + break; arraysD[i] = arrayD = (struct descriptor_a *)(*dimensionsXd)[i].pointer; if (!arrayD || arrayD->class != - CLASS_A) { // Every first dimension must be evaluated to an array + CLASS_A) + { // Every first dimension must be evaluated to an array status = InvalidDimensionInSegments; break; } } totSize += arrayD->arsize; } - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; // Merge first dimension in outDim array. It is assumed that the first // dimension has been evaluaed to a 1D array memcpy(outDimD, arraysD[0], sizeof(struct descriptor_a)); @@ -274,7 +292,8 @@ static inline int mergeArrays(struct descriptor_a *signalsApd, *outDimBuf = malloc(totSize); outDimD->pointer = *outDimBuf; outDimD->arsize = totSize; - for (i = j = 0; i < numSignals; i++) { + for (i = j = 0; i < numSignals; i++) + { arrayD = arraysD[i]; memcpy(&(*outDimBuf)[j], arrayD->pointer, arrayD->arsize); j += arrayD->arsize; @@ -287,12 +306,14 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, struct descriptor *endD __attribute__((unused)), struct descriptor *minDeltaD __attribute__((unused)), - struct descriptor_xd *outXd) { + struct descriptor_xd *outXd) +{ if (signalsApd->class == CLASS_XD) signalsApd = (struct descriptor_a *)((struct descriptor_xd *)signalsApd)->pointer; int numSignals = signalsApd->arsize / signalsApd->length; - if (numSignals <= 0) { + if (numSignals <= 0) + { MdsCopyDxXd((struct descriptor *)&emptyXd, outXd); return 1; } @@ -300,13 +321,13 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, int totShapes; int outShape[MAX_DIMS]; int status = checkShapes(signalsApd, &totShapes, outShape); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; // Check that the number of dimensions in signals is the same int numDimensions = 0; status = checkNumDimensions(signalsApd, &numDimensions); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; DESCRIPTOR_SIGNAL(outSignalD, MAX_DIMS, 0, 0); // Check whether all dimensions are expressed as a range. @@ -324,14 +345,15 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, if (canDoMergeRanges) // merge in total range outSignalD.dimensions[0] = mergeRanges(signalsApd, &outRangeD); - else { // Not all dimensions are ranges, merge arrays + else + { // Not all dimensions are ranges, merge arrays status = mergeArrays(signalsApd, &dimensionsXd, (struct descriptor_a *)&outDimD, &arraysBuf, &outDimBuf); - if - STATUS_OK - outSignalD.dimensions[0] = (struct descriptor *)&outDimD; - else { + if (STATUS_OK) + outSignalD.dimensions[0] = (struct descriptor *)&outDimD; + else + { numDimensions = 0; } } @@ -348,7 +370,8 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, // arrays // Collect total data size int totSize = 0; - for (i = 0; i < numSignals; i++) { + for (i = 0; i < numSignals; i++) + { currSignalD = ((struct descriptor_signal **)signalsApd->pointer)[i]; totSize += ((struct descriptor_a *)currSignalD->data)->arsize; } @@ -360,7 +383,8 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, struct descriptor_a *arrayD = (struct descriptor_a *)currSignalD->data; outDataD.length = arrayD->length; outDataD.dtype = arrayD->dtype; - for (i = j = 0; i < numSignals; i++) { + for (i = j = 0; i < numSignals; i++) + { currSignalD = ((struct descriptor_signal **)signalsApd->pointer)[i]; arrayD = (struct descriptor_a *)currSignalD->data; memcpy(&outDataBuf[j], arrayD->pointer, arrayD->arsize); @@ -376,13 +400,17 @@ EXPORT int XTreeDefaultSquish(struct descriptor_a *signalsApd, // free stuff free(outDataBuf); - if (canDoMergeRanges) { - if (numSignals > 1) { + if (canDoMergeRanges) + { + if (numSignals > 1) + { free(beginArrD.pointer); free(endingArrD.pointer); free(deltavalArrD.pointer); } - } else { + } + else + { for (i = 0; i < numSignals; i++) MdsFree1Dx(&dimensionsXd[i], 0); free(dimensionsXd); diff --git a/xtreeshr/XTreeGetSegmentList.c b/xtreeshr/XTreeGetSegmentList.c index b75db3ae6a..b5c5c272ce 100644 --- a/xtreeshr/XTreeGetSegmentList.c +++ b/xtreeshr/XTreeGetSegmentList.c @@ -74,7 +74,8 @@ static void printDecompiled(struct descriptor *inD) */ static int check(char *compExpr, struct descriptor *time1Dsc, - struct descriptor *time2Dsc, char *answ) { + struct descriptor *time2Dsc, char *answ) +{ struct descriptor compExprDsc = {strlen(compExpr), DTYPE_T, CLASS_S, compExpr}; int status; @@ -87,18 +88,22 @@ static int check(char *compExpr, struct descriptor *time1Dsc, return 1; } static int checkGreaterOrEqual(struct descriptor *time1Dsc, - struct descriptor *time2Dsc, char *answ) { + struct descriptor *time2Dsc, char *answ) +{ return check("$ >= $", time1Dsc, time2Dsc, answ); } static int checkGreater(struct descriptor *time1Dsc, - struct descriptor *time2Dsc, char *answ) { + struct descriptor *time2Dsc, char *answ) +{ return check("$ > $", time1Dsc, time2Dsc, answ); } static void freeResources(struct descriptor_xd *startTimeXds, - struct descriptor_xd *endTimeXds, int numSegments) { + struct descriptor_xd *endTimeXds, int numSegments) +{ int i; - for (i = 0; i < numSegments; i++) { + for (i = 0; i < numSegments; i++) + { MdsFree1Dx(&startTimeXds[i], 0); MdsFree1Dx(&endTimeXds[i], 0); } @@ -109,7 +114,8 @@ static void freeResources(struct descriptor_xd *startTimeXds, EXPORT int _XTreeGetSegmentList(void *dbid, int nid, struct descriptor *startDsc, struct descriptor *endDsc, - struct descriptor_xd *outSignalXd) { + struct descriptor_xd *outSignalXd) +{ int status; char isGreater; int numSegments; @@ -133,45 +139,48 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, status = (dbid) ? _TreeGetNumSegments(dbid, nid, &numSegments) : TreeGetNumSegments(nid, &numSegments); - if - STATUS_NOT_OK - return status; + if (STATUS_NOT_OK) + return status; startTimeXds = (struct descriptor_xd *)malloc(numSegments * sizeof(struct descriptor_xd)); endTimeXds = (struct descriptor_xd *)malloc(numSegments * sizeof(struct descriptor_xd)); - for (i = 0; i < numSegments; i++) { + for (i = 0; i < numSegments; i++) + { startTimeXds[i] = emptyXd; endTimeXds[i] = emptyXd; } - for (currIdx = 0; currIdx < numSegments; currIdx++) { + for (currIdx = 0; currIdx < numSegments; currIdx++) + { status = (dbid) ? _TreeGetSegmentLimits(dbid, nid, currIdx, &startTimeXds[currIdx], &endTimeXds[currIdx]) : TreeGetSegmentLimits(nid, currIdx, &startTimeXds[currIdx], &endTimeXds[currIdx]); - if - STATUS_NOT_OK { - freeResources(startTimeXds, endTimeXds, numSegments); - return status; - } + if (STATUS_NOT_OK) + { + freeResources(startTimeXds, endTimeXds, numSegments); + return status; + } } startIdx = 0; currIdx = 0; if (!startDsc) // If no start time specified, take all initial segments startIdx = 0; - else { - while (startIdx < numSegments) { + else + { + while (startIdx < numSegments) + { // if(currEnd > start) //First overlapping segment status = checkGreaterOrEqual((struct descriptor *)&endTimeXds[startIdx], startDsc, &isGreater); - if - STATUS_NOT_OK { - freeResources(startTimeXds, endTimeXds, numSegments); - return status; - } + if (STATUS_NOT_OK) + { + freeResources(startTimeXds, endTimeXds, numSegments); + return status; + } if (isGreater) break; startIdx++; @@ -187,25 +196,28 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, if (!endDsc) endIdx = numSegments - 1; - else { + else + { segmentIdx = startIdx; - while (segmentIdx < numSegments) { + while (segmentIdx < numSegments) + { status = checkGreaterOrEqual((struct descriptor *)&endTimeXds[segmentIdx], endDsc, &isGreater); - if - STATUS_NOT_OK { - freeResources(startTimeXds, endTimeXds, numSegments); - return status; - } + if (STATUS_NOT_OK) + { + freeResources(startTimeXds, endTimeXds, numSegments); + return status; + } // if(currEnd >= end) //Last overlapping segment - if (isGreater) { + if (isGreater) + { status = checkGreater((struct descriptor *)&startTimeXds[segmentIdx], endDsc, &isGreater); - if - STATUS_NOT_OK { - freeResources(startTimeXds, endTimeXds, numSegments); - return status; - } + if (STATUS_NOT_OK) + { + freeResources(startTimeXds, endTimeXds, numSegments); + return status; + } // if(currStart > end) //all the segment lies outside the specifid // range, it has to be excluded if (isGreater && segmentIdx > startIdx) @@ -225,22 +237,27 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, // an array currType = startTimeXds[startIdx].pointer->dtype; isSigCandidate = 1; - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { if (!startTimeXds[currIdx].pointer || - startTimeXds[currIdx].pointer->class != CLASS_S) { + startTimeXds[currIdx].pointer->class != CLASS_S) + { isSigCandidate = 0; break; } - if (startTimeXds[currIdx].pointer->dtype != currType) { + if (startTimeXds[currIdx].pointer->dtype != currType) + { isSigCandidate = 0; break; } } - if (isSigCandidate) { + if (isSigCandidate) + { startTimesBuf = malloc((endIdx - startIdx + 1) * startTimeXds[startIdx].pointer->length); - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { memcpy(&startTimesBuf[(currIdx - startIdx) * startTimeXds[startIdx].pointer->length], startTimeXds[currIdx].pointer->pointer, @@ -252,11 +269,13 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, startTimeXds[startIdx].pointer->length * (endIdx - startIdx + 1); startTimesArray.pointer = startTimesBuf; retSignalDsc.dimensions[0] = (struct descriptor *)&startTimesArray; - } else // build an APD + } + else // build an APD { startTimesBuf = malloc((endIdx - startIdx + 1) * sizeof(struct descriptor *)); - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { memcpy(&startTimesBuf[(currIdx - startIdx) * sizeof(struct descriptor *)], &startTimeXds[currIdx].pointer, sizeof(struct descriptor *)); } @@ -269,22 +288,27 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, // The same for endTimes currType = endTimeXds[startIdx].pointer->dtype; isSigCandidate = 1; - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { if (!endTimeXds[currIdx].pointer || - endTimeXds[currIdx].pointer->class != CLASS_S) { + endTimeXds[currIdx].pointer->class != CLASS_S) + { isSigCandidate = 0; break; } - if (endTimeXds[currIdx].pointer->dtype != currType) { + if (endTimeXds[currIdx].pointer->dtype != currType) + { isSigCandidate = 0; break; } } - if (isSigCandidate) { + if (isSigCandidate) + { endTimesBuf = (char *)malloc((endIdx - startIdx + 1) * endTimeXds[startIdx].pointer->length); - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { memcpy(&endTimesBuf[(currIdx - startIdx) * endTimeXds[startIdx].pointer->length], endTimeXds[currIdx].pointer->pointer, @@ -296,10 +320,12 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, endTimeXds[startIdx].pointer->length * (endIdx - startIdx + 1); endTimesArray.pointer = endTimesBuf; retSignalDsc.dimensions[1] = (struct descriptor *)&endTimesArray; - } else // build an APD + } + else // build an APD { endTimesBuf = malloc((endIdx - startIdx + 1) * sizeof(struct descriptor *)); - for (currIdx = startIdx; currIdx <= endIdx; currIdx++) { + for (currIdx = startIdx; currIdx <= endIdx; currIdx++) + { memcpy(&endTimesBuf[(currIdx - startIdx) * sizeof(struct descriptor *)], &endTimeXds[currIdx].pointer, sizeof(struct descriptor *)); } @@ -319,6 +345,7 @@ EXPORT int _XTreeGetSegmentList(void *dbid, int nid, EXPORT int XTreeGetSegmentList(int nid, struct descriptor *startD, struct descriptor *endD, - struct descriptor_xd *outSignal) { + struct descriptor_xd *outSignal) +{ return _XTreeGetSegmentList(0, nid, startD, endD, outSignal); } diff --git a/xtreeshr/XTreeGetTimedRecord.c b/xtreeshr/XTreeGetTimedRecord.c index 51bcadd72b..6f0b55503d 100644 --- a/xtreeshr/XTreeGetTimedRecord.c +++ b/xtreeshr/XTreeGetTimedRecord.c @@ -42,8 +42,8 @@ static int timedAccessFlag = 0; #endif extern int XTreeConvertToLongTime(mdsdsc_t *timeD, int64_t *converted); extern int XTreeConvertToDouble(mdsdsc_t *timeD, double *converted); -#define RESAMPLE_FUN(name) \ - int name(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, \ +#define RESAMPLE_FUN(name) \ + int name(mds_signal_t *inSignalD, mdsdsc_t *startD, mdsdsc_t *endD, \ mdsdsc_t *deltaD, mdsdsc_xd_t *outSignalXd) extern RESAMPLE_FUN(XTreeAverageResample); extern RESAMPLE_FUN(XTreeMinMaxResample); @@ -58,7 +58,8 @@ EXPORT int XTreeTestTimedAccessFlag() { return timedAccessFlag; } // Check if resampled versions of this node exist in case a sampling interval is // specified -static int checkResampledVersion(int nid, mdsdsc_t *deltaD) { +static int checkResampledVersion(int nid, mdsdsc_t *deltaD) +{ EMPTYXD(xd); EMPTYXD(startXd); EMPTYXD(endXd); @@ -74,32 +75,29 @@ static int checkResampledVersion(int nid, mdsdsc_t *deltaD) { if (deltaD == 0) return nid; status = XTreeConvertToLongTime(deltaD, &deltaNs); - if - STATUS_NOT_OK return nid; + if (STATUS_NOT_OK) + return nid; status = TreeGetXNci(nid, "ResampleFactor", &xd); - if - STATUS_NOT_OK return nid; + if (STATUS_NOT_OK) + return nid; status = TdiGetLong((mdsdsc_t *)&xd, &resampleFactor); MdsFree1Dx(&xd, 0); status = TreeGetSegmentLimits(nid, 0, &startXd, &endXd); - if - STATUS_NOT_OK - return nid; + if (STATUS_NOT_OK) + return nid; status = XTreeConvertToLongTime(startXd.pointer, &startNs); - if - STATUS_OK status = XTreeConvertToLongTime(endXd.pointer, &endNs); + if (STATUS_OK) + status = XTreeConvertToLongTime(endXd.pointer, &endNs); MdsFree1Dx(&startXd, 0); MdsFree1Dx(&endXd, 0); - if - STATUS_NOT_OK - return nid; + if (STATUS_NOT_OK) + return nid; status = TreeGetSegmentInfo(nid, 0, &dtype, &dimct, dims, &nextRow); - if - STATUS_NOT_OK - return nid; + if (STATUS_NOT_OK) + return nid; // numRows = dims[dimct-1]; numRows = nextRow; actDeltaNs = (endNs - startNs) / numRows; @@ -111,7 +109,8 @@ static int checkResampledVersion(int nid, mdsdsc_t *deltaD) { return nid; status = TreeGetXNci(nid, "ResampleNid", &xd); if (STATUS_NOT_OK || !xd.pointer || xd.pointer->class != CLASS_S || - xd.pointer->dtype != DTYPE_NID) { + xd.pointer->dtype != DTYPE_NID) + { MdsFree1Dx(&xd, 0); return nid; } @@ -121,7 +120,8 @@ static int checkResampledVersion(int nid, mdsdsc_t *deltaD) { } EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, - mdsdsc_t *minDeltaD, mdsdsc_xd_t *outSignal) { + mdsdsc_t *minDeltaD, mdsdsc_xd_t *outSignal) +{ int status, nid; int actNumSegments, currSegIdx, nonEmptySegIdx, numSegments, currIdx, numDimensions; @@ -156,44 +156,50 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, timedAccessFlag = 1; // Get names for (possible) user defined resample and squish funs status = TreeGetXNci(nid, "ResampleFun", &xd); - if (STATUS_OK && xd.pointer) { // If a user defined fun exists + if (STATUS_OK && xd.pointer) + { // If a user defined fun exists nameLen = xd.pointer->length; if (nameLen >= MAX_FUN_NAMELEN) nameLen = MAX_FUN_NAMELEN - 1; memcpy(resampleFunName, xd.pointer->pointer, nameLen); resampleFunName[nameLen] = 0; MdsFree1Dx(&xd, 0); - } else + } + else resampleFunName[0] = 0; status = TreeGetXNci(nid, "SquishFun", &xd); - if (STATUS_OK & 1 && xd.pointer) { // If a user defined fun exists + if (STATUS_OK & 1 && xd.pointer) + { // If a user defined fun exists nameLen = xd.pointer->length; if (nameLen >= MAX_FUN_NAMELEN) nameLen = MAX_FUN_NAMELEN - 1; memcpy(squishFunName, xd.pointer->pointer, nameLen); squishFunName[nameLen] = 0; MdsFree1Dx(&xd, 0); - } else + } + else squishFunName[0] = 0; status = TreeGetXNci(nid, "ResampleMode", &xd); - if (STATUS_OK && xd.pointer) { // If a user defined fun exists + if (STATUS_OK && xd.pointer) + { // If a user defined fun exists nameLen = xd.pointer->length; if (nameLen >= MAX_FUN_NAMELEN) nameLen = MAX_FUN_NAMELEN - 1; memcpy(resampleMode, xd.pointer->pointer, nameLen); resampleMode[nameLen] = 0; MdsFree1Dx(&xd, 0); - } else + } + else resampleMode[0] = 0; // Get segment limits. If not evaluated to 64 bit int, make the required // conversion. // New management based on TreeGetSegmentLimits() status = TreeGetSegmentTimesXd(nid, &numSegments, &startTimesXd, &endTimesXd); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; // Convert read times into 64 bit representation if (startTimesXd.pointer == 0 || endTimesXd.pointer == 0) return 0; // Internal error @@ -201,19 +207,21 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, endTimesApd = (struct descriptor_a *)endTimesXd.pointer; status = TdiData(*(mdsdsc_t **)startTimesApd->pointer, &xd MDS_END_ARG); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; MdsFree1Dx(&xd, 0); // Evaluate start, end to int64 - if (startD) { + if (startD) + { status = XTreeConvertToDouble(startD, &start); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } - if (endD) { + if (endD) + { status = XTreeConvertToDouble(endD, &end); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } if ((int)(startTimesApd->arsize / startTimesApd->length) != numSegments) @@ -222,17 +230,18 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, return 0; // Internal error startTimes = (double *)malloc(numSegments * sizeof(double)); endTimes = (double *)malloc(numSegments * sizeof(double)); - for (currSegIdx = 0; currSegIdx < numSegments; currSegIdx++) { + for (currSegIdx = 0; currSegIdx < numSegments; currSegIdx++) + { status = XTreeConvertToDouble( ((mdsdsc_t **)(startTimesApd->pointer))[currSegIdx], &startTimes[currSegIdx]); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; status = XTreeConvertToDouble(((mdsdsc_t **)(endTimesApd->pointer))[currSegIdx], &endTimes[currSegIdx]); - if - STATUS_NOT_OK return status; + if (STATUS_NOT_OK) + return status; } MdsFree1Dx(&startTimesXd, 0); MdsFree1Dx(&endTimesXd, 0); @@ -243,15 +252,19 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, for (startIdx = 0; startIdx < numSegments && endTimes[startIdx] < start; startIdx++) ; - if (startIdx == numSegments) { + if (startIdx == numSegments) + { MdsCopyDxXd((mdsdsc_t *)&emptyXd, outSignal); // return an empty XD return 1; } if (!endD) endIdx = numSegments - 1; - else { - for (currSegIdx = startIdx; currSegIdx < numSegments; currSegIdx++) { - if (endTimes[currSegIdx] >= end) { // Last overlapping segment + else + { + for (currSegIdx = startIdx; currSegIdx < numSegments; currSegIdx++) + { + if (endTimes[currSegIdx] >= end) + { // Last overlapping segment if (startTimes[currSegIdx] > end && currSegIdx > startIdx) currSegIdx--; break; @@ -272,49 +285,58 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, resampledXds = (mdsdsc_xd_t *)malloc(actNumSegments * sizeof(mdsdsc_xd_t)); dataXds = (mdsdsc_xd_t *)malloc(actNumSegments * sizeof(mdsdsc_xd_t)); dimensionXds = (mdsdsc_xd_t *)malloc(actNumSegments * sizeof(mdsdsc_xd_t)); - for (i = 0; i < actNumSegments; i++) { + for (i = 0; i < actNumSegments; i++) + { resampledXds[i] = emptyXd; dataXds[i] = emptyXd; dimensionXds[i] = emptyXd; } for (currIdx = startIdx, currSegIdx = 0, nonEmptySegIdx = 0; - currIdx <= endIdx; currIdx++, currSegIdx++) { + currIdx <= endIdx; currIdx++, currSegIdx++) + { status = TreeGetSegment(nid, currIdx, &dataXds[currSegIdx], &dimensionXds[currSegIdx]); // decompress if compressed - if (STATUS_OK && dataXds[currSegIdx].pointer->class == CLASS_CA) { + if (STATUS_OK && dataXds[currSegIdx].pointer->class == CLASS_CA) + { mdsdsc_xd_t compressed = dataXds[currSegIdx]; dataXds[currSegIdx] = emptyXd; status = MdsDecompress((struct descriptor_r *)compressed.pointer, &dataXds[currSegIdx]); MdsFree1Dx(&compressed, 0); } - if - STATUS_NOT_OK { - free(signals); - for (i = 0; i < actNumSegments; i++) { - MdsFree1Dx(&resampledXds[i], 0); - MdsFree1Dx(&dataXds[i], 0); - MdsFree1Dx(&dimensionXds[i], 0); - } - free(resampledXds); - free(dataXds); - free(dimensionXds); - return status; + if (STATUS_NOT_OK) + { + free(signals); + for (i = 0; i < actNumSegments; i++) + { + MdsFree1Dx(&resampledXds[i], 0); + MdsFree1Dx(&dataXds[i], 0); + MdsFree1Dx(&dimensionXds[i], 0); } + free(resampledXds); + free(dataXds); + free(dimensionXds); + return status; + } // Check if returned dimension is an APD for multidimensional dimensions - if (!dimensionXds[currSegIdx].pointer) { + if (!dimensionXds[currSegIdx].pointer) + { currSignalD.ndesc = 1; currSignalD.dimensions[0] = NULL; - } else if (dimensionXds[currSegIdx].pointer->class == CLASS_APD) { + } + else if (dimensionXds[currSegIdx].pointer->class == CLASS_APD) + { currApd = (struct descriptor_a *)dimensionXds[currSegIdx].pointer; numDimensions = currApd->arsize / currApd->length; currSignalD.ndesc = 2 + numDimensions; for (i = 0; i < numDimensions; i++) currSignalD.dimensions[i] = ((mdsdsc_t **)currApd->pointer)[i]; - } else { + } + else + { currSignalD.ndesc = 3; currSignalD.dimensions[0] = dimensionXds[currSegIdx].pointer; } @@ -322,7 +344,8 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, // If defined, call User Provided resampling function, oterwise use default // one (XTreeDefaultResample()) - if (resampleFunName[0]) { + if (resampleFunName[0]) + { resampleFunD.length = sizeof(unsigned short); resampleFunD.pointer = (unsigned char *)&OpcExtFunction; resampleFunNameD.length = strlen(resampleFunName); @@ -335,8 +358,9 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, resampleFunD.dscptrs[5] = minDeltaD; status = TdiEvaluate((mdsdsc_t *)&resampleFunD, &resampledXds[currSegIdx] MDS_END_ARG); - } else if ((!startD && !endD && !minDeltaD) || - currSignalD.ndesc == 1) // If no resampling required + } + else if ((!startD && !endD && !minDeltaD) || + currSignalD.ndesc == 1) // If no resampling required status = MdsCopyDxXd((const mdsdsc_t *)&currSignalD, &resampledXds[currSegIdx]); else if (!strcasecmp(resampleMode, "Average")) @@ -358,19 +382,20 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, status = XTreeDefaultResample((mds_signal_t *)&currSignalD, startD, endD, minDeltaD, &resampledXds[currSegIdx]); - if - STATUS_NOT_OK { - free(signals); - for (i = 0; i < actNumSegments; i++) { - MdsFree1Dx(&resampledXds[i], 0); - MdsFree1Dx(&dataXds[i], 0); - MdsFree1Dx(&dimensionXds[i], 0); - } - free(resampledXds); - free(dataXds); - free(dimensionXds); - return status; + if (STATUS_NOT_OK) + { + free(signals); + for (i = 0; i < actNumSegments; i++) + { + MdsFree1Dx(&resampledXds[i], 0); + MdsFree1Dx(&dataXds[i], 0); + MdsFree1Dx(&dimensionXds[i], 0); } + free(resampledXds); + free(dataXds); + free(dimensionXds); + return status; + } MdsFree1Dx(&dataXds[currSegIdx], 0); MdsFree1Dx(&dimensionXds[currSegIdx], 0); @@ -388,7 +413,8 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, // squish fun defined, call it Otherwise call default Squish fun // XTreeDefaultSquish() - if (squishFunName[0]) { + if (squishFunName[0]) + { unsigned short funCode = OpcExtFunction; squishFunD.length = sizeof(unsigned short); squishFunD.pointer = (unsigned char *)&funCode; @@ -402,20 +428,24 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, squishFunD.dscptrs[5] = minDeltaD; status = TdiEvaluate((mdsdsc_t *)&squishFunD, outSignal MDS_END_ARG); - } else + } + else status = XTreeDefaultSquish((struct descriptor_a *)&signalsApd, startD, endD, minDeltaD, outSignal); // Free stuff free(signals); - for (i = 0; i < actNumSegments; i++) { + for (i = 0; i < actNumSegments; i++) + { MdsFree1Dx(&resampledXds[i], NULL); } free(resampledXds); free(dataXds); free(dimensionXds); - if (outSignal->pointer && (TreeGetSegmentScale(inNid, &xd) & 1)) { - if (xd.pointer) { + if (outSignal->pointer && (TreeGetSegmentScale(inNid, &xd) & 1)) + { + if (xd.pointer) + { mds_signal_t *sig = (mds_signal_t *)outSignal->pointer; emptyXd = *outSignal; outSignal->pointer = NULL; @@ -431,7 +461,8 @@ EXPORT int XTreeGetTimedRecord(int inNid, mdsdsc_t *startD, mdsdsc_t *endD, EXPORT int _XTreeGetTimedRecord(void *dbid, int nid, mdsdsc_t *startD, mdsdsc_t *endD, mdsdsc_t *minDeltaD, - mdsdsc_xd_t *outSignal) { + mdsdsc_xd_t *outSignal) +{ int status; CTX_PUSH(&dbid); status = XTreeGetTimedRecord(nid, startD, endD, minDeltaD, outSignal); From 42383b51160d0257cb870d840813258a963aa6c8 Mon Sep 17 00:00:00 2001 From: Antoine Merle Date: Tue, 20 Apr 2021 20:39:28 +0200 Subject: [PATCH 05/27] Fix: fix exit condition in loop over tag links in _RemoveTagIdx (#2278) (#2287) --- treeshr/TreeRemoveNodesTags.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/treeshr/TreeRemoveNodesTags.c b/treeshr/TreeRemoveNodesTags.c index a82db5534b..b4dce6baf1 100644 --- a/treeshr/TreeRemoveNodesTags.c +++ b/treeshr/TreeRemoveNodesTags.c @@ -144,7 +144,7 @@ static void _RemoveTagIdx(PINO_DATABASE *dblist, int tagidx) for (tag_link = swapint32(&node_ptr->tag_link), info_ptr = dblist->tree_info->tag_info + tag_link - 1; (swapint32(&info_ptr->tag_link) != tagidx) && - (swapint32(&info_ptr->tag_link) >= 0); + (swapint32(&info_ptr->tag_link) > 0); info_ptr = dblist->tree_info->tag_info + swapint32(&info_ptr->tag_link) - 1) ; From 008b7b2c3f3e5bf502ebf3c4912e0950cffaa1da Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Wed, 21 Apr 2021 14:45:59 +0200 Subject: [PATCH 06/27] Fix: Gm jscope perf (#2294) * Fix:avoid reading whole waveform * Get XLabel and YLabel when defined Co-authored-by: GabrieleManduchi --- .../java/mds/provider/MdsDataProvider.java | 62 ++++++++++--------- .../jscope/src/main/java/mds/wave/Signal.java | 7 ++- 2 files changed, 40 insertions(+), 29 deletions(-) diff --git a/java/jscope/src/main/java/mds/provider/MdsDataProvider.java b/java/jscope/src/main/java/mds/provider/MdsDataProvider.java index ee9f459149..937ed4e460 100644 --- a/java/jscope/src/main/java/mds/provider/MdsDataProvider.java +++ b/java/jscope/src/main/java/mds/provider/MdsDataProvider.java @@ -511,21 +511,20 @@ public SimpleWaveData(String in_y, String in_x, String experiment, long shot, St var_idx += 2; if (segmentMode == SEGMENTED_UNKNOWN) { - final Vector args = new Vector<>(); - final String fixedY = in_y.replaceAll("\\\\", "\\\\\\\\"); - args.addElement(new Descriptor(null, fixedY)); - try + final String fixedY = duplicateBackslashes(in_y); + try + { + final String segExpr = "long(MdsMisc->IsSegmented(\"" + fixedY + "\"))"; + final int[] retData = getIntArray(segExpr); + if (retData[0] != 0) { - final byte[] retData = GetByteArray("byte(MdsMisc->IsSegmented($))", args); - if (retData[0] > 0) - { - segmentNodeName = getStringValue("MdsMisc->GetPathOf:DSC(" + retData[0] + ")"); - if (debug) - System.out.println("Segmented Node: " + segmentNodeName); - segmentMode = SEGMENTED_YES; - } - else - segmentMode = SEGMENTED_NO; + segmentNodeName = getStringValue("MdsMisc->GetPathOf:DSC(" + retData[0] + ")"); + if (debug) + System.out.println("Segmented Node: " + segmentNodeName); + segmentMode = SEGMENTED_YES; + } + else + segmentMode = SEGMENTED_NO; } catch (final Exception exc) { @@ -590,20 +589,22 @@ public XYData getData(double xmin, double xmax, int numPoints, boolean isLong) t return null; if (segmentMode == SEGMENTED_UNKNOWN) { - final Vector args = new Vector<>(); - args.addElement(new Descriptor(null, in_y)); - try + final String fixedY = duplicateBackslashes(in_y); + try + { + final String segExpr = "long(MdsMisc->IsSegmented(\"" + fixedY + "\"))"; + final int[] retData = getIntArray(segExpr); + if (debug) + System.out.println(segExpr + " " + retData[0]); + if (retData[0] != 0) { - final byte[] retData = GetByteArray("byte(MdsMisc->IsSegmented($))", args); - if (retData[0] > 0) - { - segmentMode = SEGMENTED_YES; - segmentNodeName = getStringValue("MdsMisc->GetPathOf:DSC(" + retData[0] + ")"); - if (debug) - System.out.println("Segmented Node: " + segmentNodeName); - } - else - segmentMode = SEGMENTED_NO; + segmentMode = SEGMENTED_YES; + segmentNodeName = getStringValue("MdsMisc->GetPathOf:DSC(" + retData[0] + ")"); + if (debug) + System.out.println("Segmented Node: " + segmentNodeName); + } + else + segmentMode = SEGMENTED_NO; } catch (final Exception exc) { @@ -966,7 +967,12 @@ public String GetXLabel() throws IOException } else { - xLabel = getStringValue("Units(" + in_x + ")"); + if (segmentMode == SEGMENTED_YES) + { + xLabel = ""; //Shall be set afterwards + } + else + xLabel = getStringValue("Units(" + in_x + ")"); } } return xLabel; diff --git a/java/jscope/src/main/java/mds/wave/Signal.java b/java/jscope/src/main/java/mds/wave/Signal.java index 943b11e08a..443a849461 100644 --- a/java/jscope/src/main/java/mds/wave/Signal.java +++ b/java/jscope/src/main/java/mds/wave/Signal.java @@ -1413,7 +1413,12 @@ else if (numDimensions == 2) { System.out.println("ERROR: UP TO 2 Dimensions supported"); } - } + //Update X and Y labels if not defined + if(xlabel == null || xlabel.trim().length() == 0) + xlabel = data.GetXLabel(); + if(ylabel == null || ylabel.trim().length() == 0) + ylabel = data.GetYLabel(); + } /** * Check if x array coordinates are increasing. From 850778e64f8b0d9c8a8aba18a5860821b9298878 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Wed, 21 Apr 2021 15:32:51 +0200 Subject: [PATCH 07/27] Feature: cleanup Mdsip (#2289) * update testing/memcheck/helgrind scripts * tests: removed mdsip timeout from tests * added fast_remte_write test to connectionsUintTest; optional * EXPORT newMDSplusThreadStatic and destroyMDSplusThreadStatic * removed timeout from mdsip; source of dead-locks * ProcessMessage: cleanup * removed unimplemented methods * ProcessMessage: cleanup message * python tests: added TestThread for easier threadded tests * reactivate TaskUnitTest * provide __traceback__ for python2 * valgrind.supp for fc32 python --- conf/valgrind.supp/fc32.supp | 7 + deploy/packaging/debian/kernel_bin.amd64 | 2 - deploy/packaging/debian/kernel_bin.armhf | 2 - deploy/packaging/debian/kernel_bin.i386 | 2 - deploy/packaging/redhat/kernel_bin.i686 | 2 - deploy/packaging/redhat/kernel_bin.x86_64 | 2 - mdsshr/MdsThreadStatic.c | 21 +- mdstcpip/CloseConnection.c | 43 - mdstcpip/DisconnectFromMds.c | 31 - mdstcpip/FreeMessage.c | 29 - mdstcpip/Makefile.in | 148 +- mdstcpip/ProcessMessage.c | 1299 ----------------- mdstcpip/b_order.h | 17 - mdstcpip/docs/Makefile.am | 23 +- mdstcpip/{ => io_routines}/IoRoutinesGsi.c | 2 +- mdstcpip/{ => io_routines}/IoRoutinesTcp.c | 0 mdstcpip/{ => io_routines}/IoRoutinesTcpV6.c | 0 mdstcpip/{ => io_routines}/IoRoutinesThread.c | 1 + mdstcpip/{ => io_routines}/IoRoutinesTunnel.c | 0 mdstcpip/{ => io_routines}/IoRoutinesUdt.c | 0 mdstcpip/{ => io_routines}/IoRoutinesUdtV6.c | 0 mdstcpip/{ => io_routines}/ioroutines.h | 2 +- mdstcpip/{ => io_routines}/ioroutinesV6.h | 2 +- mdstcpip/{ => io_routines}/ioroutines_pipes.h | 2 +- mdstcpip/{ => io_routines}/ioroutinestcp.h | 42 +- mdstcpip/{ => io_routines}/ioroutinesudt.h | 2 +- mdstcpip/{ => io_routines}/ioroutinesx.h | 23 +- mdstcpip/mdsip_connections.h | 25 +- mdstcpip/{ => mdsipshr}/ArgLen.c | 2 +- mdstcpip/{ => mdsipshr}/CheckClient.c | 2 +- mdstcpip/{ => mdsipshr}/ClientType.c | 2 +- .../CloseConnection.c} | 31 +- mdstcpip/{ => mdsipshr}/ConnectToMds.c | 14 +- mdstcpip/{ => mdsipshr}/Connections.c | 22 +- mdstcpip/{ => mdsipshr}/DoMessage.c | 38 +- mdstcpip/{ => mdsipshr}/FlipData.c | 2 +- mdstcpip/{ => mdsipshr}/FlipHeader.c | 2 +- mdstcpip/{ => mdsipshr}/GetAnswerInfo.c | 2 +- mdstcpip/{ => mdsipshr}/GetMdsMsg.c | 14 +- mdstcpip/{ => mdsipshr}/GetSetSettings.c | 3 +- mdstcpip/{ => mdsipshr}/IdlApi.c | 0 mdstcpip/{ => mdsipshr}/LoadIo.c | 2 +- mdstcpip/{ => mdsipshr}/LockAsts.c | 2 +- mdstcpip/{ => mdsipshr}/MakeDescrip.c | 2 +- mdstcpip/{ => mdsipshr}/MdsClose.c | 2 +- mdstcpip/{ => mdsipshr}/MdsDispatchEvent.c | 2 +- mdstcpip/{ => mdsipshr}/MdsEventAst.c | 2 +- mdstcpip/{ => mdsipshr}/MdsEventCan.c | 2 +- mdstcpip/{ => mdsipshr}/MdsOpen.c | 2 +- mdstcpip/{ => mdsipshr}/MdsPut.c | 2 +- mdstcpip/{ => mdsipshr}/MdsSetCompression.c | 2 +- mdstcpip/{ => mdsipshr}/MdsSetDefault.c | 2 +- mdstcpip/{ => mdsipshr}/MdsValue.c | 4 +- mdstcpip/{ => mdsipshr}/ParseCommand.c | 13 +- mdstcpip/mdsipshr/ProcessMessage.c | 1212 +++++++++++++++ mdstcpip/{ => mdsipshr}/SendArg.c | 4 +- mdstcpip/{ => mdsipshr}/SendMdsMsg.c | 4 +- mdstcpip/{ => mdsipshr}/cvtdef.h | 0 python/MDSplus/tests/_UnitTest.py | 62 +- python/MDSplus/tests/connectionUnitTest.py | 100 +- python/MDSplus/tests/dclUnitTest.py | 2 - python/MDSplus/tests/devices/TestDevice.py | 45 +- python/MDSplus/tests/taskUnitTest.py | 23 +- testing/helgrind | 5 +- testing/memcheck | 5 +- 65 files changed, 1593 insertions(+), 1771 deletions(-) delete mode 100644 mdstcpip/CloseConnection.c delete mode 100644 mdstcpip/DisconnectFromMds.c delete mode 100644 mdstcpip/FreeMessage.c delete mode 100644 mdstcpip/ProcessMessage.c delete mode 100644 mdstcpip/b_order.h rename mdstcpip/{ => io_routines}/IoRoutinesGsi.c (99%) rename mdstcpip/{ => io_routines}/IoRoutinesTcp.c (100%) rename mdstcpip/{ => io_routines}/IoRoutinesTcpV6.c (100%) rename mdstcpip/{ => io_routines}/IoRoutinesThread.c (99%) rename mdstcpip/{ => io_routines}/IoRoutinesTunnel.c (100%) rename mdstcpip/{ => io_routines}/IoRoutinesUdt.c (100%) rename mdstcpip/{ => io_routines}/IoRoutinesUdtV6.c (100%) rename mdstcpip/{ => io_routines}/ioroutines.h (96%) rename mdstcpip/{ => io_routines}/ioroutinesV6.h (97%) rename mdstcpip/{ => io_routines}/ioroutines_pipes.h (99%) rename mdstcpip/{ => io_routines}/ioroutinestcp.h (93%) rename mdstcpip/{ => io_routines}/ioroutinesudt.h (99%) rename mdstcpip/{ => io_routines}/ioroutinesx.h (97%) rename mdstcpip/{ => mdsipshr}/ArgLen.c (98%) rename mdstcpip/{ => mdsipshr}/CheckClient.c (99%) rename mdstcpip/{ => mdsipshr}/ClientType.c (98%) rename mdstcpip/{RemoveConnection.c => mdsipshr/CloseConnection.c} (78%) rename mdstcpip/{ => mdsipshr}/ConnectToMds.c (97%) rename mdstcpip/{ => mdsipshr}/Connections.c (97%) rename mdstcpip/{ => mdsipshr}/DoMessage.c (74%) rename mdstcpip/{ => mdsipshr}/FlipData.c (98%) rename mdstcpip/{ => mdsipshr}/FlipHeader.c (98%) rename mdstcpip/{ => mdsipshr}/GetAnswerInfo.c (99%) rename mdstcpip/{ => mdsipshr}/GetMdsMsg.c (94%) rename mdstcpip/{ => mdsipshr}/GetSetSettings.c (99%) rename mdstcpip/{ => mdsipshr}/IdlApi.c (100%) rename mdstcpip/{ => mdsipshr}/LoadIo.c (98%) rename mdstcpip/{ => mdsipshr}/LockAsts.c (98%) rename mdstcpip/{ => mdsipshr}/MakeDescrip.c (98%) rename mdstcpip/{ => mdsipshr}/MdsClose.c (98%) rename mdstcpip/{ => mdsipshr}/MdsDispatchEvent.c (98%) rename mdstcpip/{ => mdsipshr}/MdsEventAst.c (98%) rename mdstcpip/{ => mdsipshr}/MdsEventCan.c (98%) rename mdstcpip/{ => mdsipshr}/MdsOpen.c (98%) rename mdstcpip/{ => mdsipshr}/MdsPut.c (98%) rename mdstcpip/{ => mdsipshr}/MdsSetCompression.c (98%) rename mdstcpip/{ => mdsipshr}/MdsSetDefault.c (98%) rename mdstcpip/{ => mdsipshr}/MdsValue.c (99%) rename mdstcpip/{ => mdsipshr}/ParseCommand.c (97%) create mode 100644 mdstcpip/mdsipshr/ProcessMessage.c rename mdstcpip/{ => mdsipshr}/SendArg.c (98%) rename mdstcpip/{ => mdsipshr}/SendMdsMsg.c (98%) rename mdstcpip/{ => mdsipshr}/cvtdef.h (100%) diff --git a/conf/valgrind.supp/fc32.supp b/conf/valgrind.supp/fc32.supp index a5f82df54c..391ea8cf81 100644 --- a/conf/valgrind.supp/fc32.supp +++ b/conf/valgrind.supp/fc32.supp @@ -146,6 +146,13 @@ fun:realloc fun:_PyBytes_Resize } +{ + _PyObject_GC_Resize + Memcheck:Leak + match-leak-kinds: definite + fun:realloc + fun:_PyObject_GC_Resize +} { _PyLong_New Memcheck:Leak diff --git a/deploy/packaging/debian/kernel_bin.amd64 b/deploy/packaging/debian/kernel_bin.amd64 index d9d337e479..77f46b3973 100644 --- a/deploy/packaging/debian/kernel_bin.amd64 +++ b/deploy/packaging/debian/kernel_bin.amd64 @@ -17,7 +17,6 @@ ./usr/local/mdsplus/bin/mdsip-server-ssh ./usr/local/mdsplus/bin/mdsip_server ./usr/local/mdsplus/bin/mdsipd -./usr/local/mdsplus/bin/mdsiptest ./usr/local/mdsplus/bin/mdstcl ./usr/local/mdsplus/bin/remote_submit ./usr/local/mdsplus/bin/setevent @@ -27,7 +26,6 @@ ./usr/local/mdsplus/bin/unix_submit ./usr/local/mdsplus/bin/wfevent ./usr/local/mdsplus/lib/libMdsIpShr.so -./usr/local/mdsplus/lib/libMdsIpSrvShr.so ./usr/local/mdsplus/lib/libMdsIpTCP.so ./usr/local/mdsplus/lib/libMdsIpTCPV6.so ./usr/local/mdsplus/lib/libMdsIpUDT.so diff --git a/deploy/packaging/debian/kernel_bin.armhf b/deploy/packaging/debian/kernel_bin.armhf index d9d337e479..77f46b3973 100644 --- a/deploy/packaging/debian/kernel_bin.armhf +++ b/deploy/packaging/debian/kernel_bin.armhf @@ -17,7 +17,6 @@ ./usr/local/mdsplus/bin/mdsip-server-ssh ./usr/local/mdsplus/bin/mdsip_server ./usr/local/mdsplus/bin/mdsipd -./usr/local/mdsplus/bin/mdsiptest ./usr/local/mdsplus/bin/mdstcl ./usr/local/mdsplus/bin/remote_submit ./usr/local/mdsplus/bin/setevent @@ -27,7 +26,6 @@ ./usr/local/mdsplus/bin/unix_submit ./usr/local/mdsplus/bin/wfevent ./usr/local/mdsplus/lib/libMdsIpShr.so -./usr/local/mdsplus/lib/libMdsIpSrvShr.so ./usr/local/mdsplus/lib/libMdsIpTCP.so ./usr/local/mdsplus/lib/libMdsIpTCPV6.so ./usr/local/mdsplus/lib/libMdsIpUDT.so diff --git a/deploy/packaging/debian/kernel_bin.i386 b/deploy/packaging/debian/kernel_bin.i386 index d9d337e479..77f46b3973 100644 --- a/deploy/packaging/debian/kernel_bin.i386 +++ b/deploy/packaging/debian/kernel_bin.i386 @@ -17,7 +17,6 @@ ./usr/local/mdsplus/bin/mdsip-server-ssh ./usr/local/mdsplus/bin/mdsip_server ./usr/local/mdsplus/bin/mdsipd -./usr/local/mdsplus/bin/mdsiptest ./usr/local/mdsplus/bin/mdstcl ./usr/local/mdsplus/bin/remote_submit ./usr/local/mdsplus/bin/setevent @@ -27,7 +26,6 @@ ./usr/local/mdsplus/bin/unix_submit ./usr/local/mdsplus/bin/wfevent ./usr/local/mdsplus/lib/libMdsIpShr.so -./usr/local/mdsplus/lib/libMdsIpSrvShr.so ./usr/local/mdsplus/lib/libMdsIpTCP.so ./usr/local/mdsplus/lib/libMdsIpTCPV6.so ./usr/local/mdsplus/lib/libMdsIpUDT.so diff --git a/deploy/packaging/redhat/kernel_bin.i686 b/deploy/packaging/redhat/kernel_bin.i686 index 6943351375..adb61e638b 100644 --- a/deploy/packaging/redhat/kernel_bin.i686 +++ b/deploy/packaging/redhat/kernel_bin.i686 @@ -18,7 +18,6 @@ ./usr/local/mdsplus/bin32/mdsip-server-ssh ./usr/local/mdsplus/bin32/mdsip_server ./usr/local/mdsplus/bin32/mdsipd -./usr/local/mdsplus/bin32/mdsiptest ./usr/local/mdsplus/bin32/mdstcl ./usr/local/mdsplus/bin32/remote_submit ./usr/local/mdsplus/bin32/setevent @@ -29,7 +28,6 @@ ./usr/local/mdsplus/bin32/wfevent ./usr/local/mdsplus/lib32 ./usr/local/mdsplus/lib32/libMdsIpShr.so -./usr/local/mdsplus/lib32/libMdsIpSrvShr.so ./usr/local/mdsplus/lib32/libMdsIpTCP.so ./usr/local/mdsplus/lib32/libMdsIpTCPV6.so ./usr/local/mdsplus/lib32/libMdsIpUDT.so diff --git a/deploy/packaging/redhat/kernel_bin.x86_64 b/deploy/packaging/redhat/kernel_bin.x86_64 index 5020e2a6b5..e24271d16c 100644 --- a/deploy/packaging/redhat/kernel_bin.x86_64 +++ b/deploy/packaging/redhat/kernel_bin.x86_64 @@ -18,7 +18,6 @@ ./usr/local/mdsplus/bin64/mdsip-server-ssh ./usr/local/mdsplus/bin64/mdsip_server ./usr/local/mdsplus/bin64/mdsipd -./usr/local/mdsplus/bin64/mdsiptest ./usr/local/mdsplus/bin64/mdstcl ./usr/local/mdsplus/bin64/remote_submit ./usr/local/mdsplus/bin64/setevent @@ -29,7 +28,6 @@ ./usr/local/mdsplus/bin64/wfevent ./usr/local/mdsplus/lib64 ./usr/local/mdsplus/lib64/libMdsIpShr.so -./usr/local/mdsplus/lib64/libMdsIpSrvShr.so ./usr/local/mdsplus/lib64/libMdsIpTCP.so ./usr/local/mdsplus/lib64/libMdsIpTCPV6.so ./usr/local/mdsplus/lib64/libMdsIpUDT.so diff --git a/mdsshr/MdsThreadStatic.c b/mdsshr/MdsThreadStatic.c index 9f65c857a0..934770c207 100644 --- a/mdsshr/MdsThreadStatic.c +++ b/mdsshr/MdsThreadStatic.c @@ -42,7 +42,17 @@ static inline void free_buffer(buffer_t *buf) buf->free(buf->buffer); free(buf); } -static void free_mts(MDSplusThreadStatic_t *mts) + +EXPORT MDSplusThreadStatic_t *newMDSplusThreadStatic() +{ + MDSplusThreadStatic_t *mts = + (MDSplusThreadStatic_t *)malloc(sizeof(MDSplusThreadStatic_t)); + mts->is_owned = TRUE; + mts->buffers = calloc(THREADSTATIC_SIZE, sizeof(buffer_t *)); + return mts; +} + +EXPORT void destroyMDSplusThreadStatic(MDSplusThreadStatic_t *mts) { if (mts->is_owned) { @@ -53,7 +63,8 @@ static void free_mts(MDSplusThreadStatic_t *mts) } free(mts); } -static void init_mts_key() { pthread_key_create(&mts_key, (void *)free_mts); } + +static void init_mts_key() { pthread_key_create(&mts_key, (void *)destroyMDSplusThreadStatic); } EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) { // mts = MDSplusThreadStatic(NULL) : get current thread's mts @@ -71,16 +82,14 @@ EXPORT MDSplusThreadStatic_t *MDSplusThreadStatic(MDSplusThreadStatic_t *in) mts->buffers = in->buffers; pthread_setspecific(mts_key, (void *)mts); if (old_mts) - free_mts(old_mts); + destroyMDSplusThreadStatic(old_mts); } else { // create if NULL if (!mts) { - mts = (MDSplusThreadStatic_t *)malloc(sizeof(MDSplusThreadStatic_t)); - mts->is_owned = TRUE; - mts->buffers = calloc(THREADSTATIC_SIZE, sizeof(buffer_t *)); + mts = newMDSplusThreadStatic(); pthread_setspecific(mts_key, (void *)mts); } } diff --git a/mdstcpip/CloseConnection.c b/mdstcpip/CloseConnection.c deleted file mode 100644 index f3391722cd..0000000000 --- a/mdstcpip/CloseConnection.c +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include -#include - -#include "mdsip_connections.h" - -int CloseConnection(int id) -{ - INIT_STATUS_AS MDSplusERROR; - static int (*removeConnection)(int) = NULL; - Connection *c = FindConnection(id, 0); - if (c) - { - status = LibFindImageSymbol_C("MdsIpSrvShr", "RemoveConnection", - &removeConnection); - if (STATUS_OK) - status = (*removeConnection)(id); - } - return status; -} diff --git a/mdstcpip/DisconnectFromMds.c b/mdstcpip/DisconnectFromMds.c deleted file mode 100644 index 50591187ad..0000000000 --- a/mdstcpip/DisconnectFromMds.c +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "mdsip_connections.h" - -//////////////////////////////////////////////////////////////////////////////// -// DisconnectiFromMds //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -int DisconnectFromMds(int id) { return DisconnectConnection(id); } diff --git a/mdstcpip/FreeMessage.c b/mdstcpip/FreeMessage.c deleted file mode 100644 index 2aa06e358b..0000000000 --- a/mdstcpip/FreeMessage.c +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "mdsip_connections.h" -#include - -void FreeMessage(void *m) { free(m); } diff --git a/mdstcpip/Makefile.in b/mdstcpip/Makefile.in index f59c022c6d..4f842115c9 100644 --- a/mdstcpip/Makefile.in +++ b/mdstcpip/Makefile.in @@ -3,31 +3,21 @@ include @top_builddir@/Makefile.inc LIBPREFIX = MdsIp srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ MKDIR_P=@MKDIR_P@ @AX_RECONFIGURE_TARGET@ @MINGW_TRUE@ IMPLIB_MdsIpShr=@MAKELIBDIR@MdsIpShr.dll.a -@MINGW_TRUE@ IMPLIB_MdsIpSrvShr=@MAKELIBDIR@MdsIpSrvShr.dll.a @MINGW_TRUE@ WIN=.win -COMPRESSION_SOURCES = zlib/adler32.c \ - zlib/compress.c \ - zlib/deflate.c \ - zlib/infblock.c \ - zlib/infcodes.c \ - zlib/inffast.c \ - zlib/inflate.c \ - zlib/inftrees.c \ - zlib/infutil.c \ - zlib/trees.c \ - zlib/uncompr.c \ - zlib/zutil.c -COMPRESSION_OBJECTS = $(COMPRESSION_SOURCES:.c=.o) - COMPRESSION_SWITCH= +COMPRESSION_SOURCES = $(wildcard @srcdir@/zlib/*.c) +COMPRESSION_OBJECTS = $(COMPRESSION_SOURCES:@srcdir@/%.c=@builddir@/%.o) +$(COMPRESSION_OBJECTS): | --zlib-dir +--zlib-dir: + @$(MKDIR_P) zlib CFLAGS += $(THREAD) $(COMPRESSION_SWITCH) -I@srcdir@/udt4/src -I@srcdir@/udt4/udtc LDFLAGS += $(THREAD) @@ -49,41 +39,54 @@ MdsIpUDTV6 = @MAKESHLIBDIR@@LIBPRE@MdsIpUDTV6@SHARETYPE@ ifeq "@SHARETYPEMOD@" "@SHARETYPE@" modules = else #SHARETYPE - modules = @MAKESHLIBDIR@@LIBPRE@MdsIpShr@SHARETYPEMOD@ + modules = @MAKESHLIBDIR@@LIBPRE@MdsIpShr@SHARETYPEMOD@ endif #SHARETYPE + ## MdsIpShr sources ## -LIB_SOURCES = MdsValue.c MdsPut.c MdsOpen.c MdsClose.c MdsSetDefault.c MdsEventAst.c \ - MdsEventCan.c MdsDispatchEvent.c MdsSetCompression.c FreeMessage.c \ - IdlApi.c SendMdsMsg.c GetMdsMsg.c FlipData.c FlipHeader.c GetAnswerInfo.c ClientType.c \ - MakeDescrip.c LoadIo.c ArgLen.c GetSetSettings.c DoMessage.c \ - LockAsts.c Connections.c SendArg.c ConnectToMds.c DisconnectFromMds.c CloseConnection.c \ - CheckClient.c ParseCommand.c IoRoutinesTunnel.c IoRoutinesThread.c +LIB_SOURCES = $(wildcard @srcdir@/mdsipshr/*.c) +LIB_OBJECTS = $(LIB_SOURCES:@srcdir@/%.c=%.o) +$(LIB_OBJECTS): | --mdsipshr-dir +--mdsipshr-dir: + @$(MKDIR_P) mdsipshr + +SERVER_SOURCES = mdsip.c +SERVER_OBJECTS = $(SERVER_SOURCES:.c=.o) -LIB_OBJECTS = $(LIB_SOURCES:.c=.o) -## MdsIpSrvShr sources ## -SERVER_LIB_SOURCES = ProcessMessage.c RemoveConnection.c -SERVER_LIB_OBJECTS = $(SERVER_LIB_SOURCES:.c=.o) +--io_routines-dir: + @$(MKDIR_P) io_routines -SERVER_SOURCES = mdsip.c -SERVER_OBJECTS = $(SERVER_SOURCES:.c=.o) +TCP_SOURCES = @srcdir@/io_routines/IoRoutinesTcp.c +TCP_OBJECTS = $(TCP_SOURCES:@srcdir@/%.c=%.o) +$(TCP_OBJECTS): | --io_routines-dir + +TCPV6_SOURCES = @srcdir@/io_routines/IoRoutinesTcpV6.c +TCPV6_OBJECTS = $(TCPV6_SOURCES:@srcdir@/%.c=%.o) +$(TCPV6_OBJECTS): | --io_routines-dir + + +PIPE_SOURCES = $(addprefix @srcdir@/io_routines/, IoRoutinesTunnel.c IoRoutinesThread.c) +PIPE_OBJECTS = $(PIPE_SOURCES:@srcdir@/%.c=%.o) +$(PIPE_OBJECTS): | --io_routines-dir +LIB_SOURCES += $(PIPE_SOURCES) +LIB_OBJECTS += $(PIPE_OBJECTS) + + +--udt4-dirs: + @$(MKDIR_P) udt4/src udt4/udtc +UDT4_SOURCES = $(wildcard @srcdir@/udt4/src/*.cpp) $(wildcard @srcdir@/udt4/udtc/*.cpp) +UDT4_OBJECTS = $(UDT4_SOURCES:@srcdir@/%.cpp=%.o) +$(UDT4_OBJECTS): | --udt4-dirs +UDT_OBJECTS = io_routines/IoRoutinesUdt.o $(UDT4_OBJECTS) + +$(UDT_OBJECTS): | --io_routines-dir +UDTV6_OBJECTS = io_routines/IoRoutinesUdtV6.o $(UDT4_OBJECTS) +$(UDTV6_OBJECTS): | --io_routines-dir -TCP_SOURCES = IoRoutinesTcp.c -TCP_OBJECTS = $(TCP_SOURCES:.c=.o) -TCPV6_SOURCES = IoRoutinesTcpV6.c -TCPV6_OBJECTS = $(TCPV6_SOURCES:.c=.o) -UDT4 = udt4/src -UDT4_SOURCES = udt4/src/api.cpp udt4/src/buffer.cpp udt4/src/cache.cpp udt4/src/ccc.cpp udt4/src/channel.cpp \ - udt4/src/common.cpp udt4/src/core.cpp udt4/src/epoll.cpp udt4/src/list.cpp udt4/src/md5.cpp \ - udt4/src/packet.cpp udt4/src/queue.cpp udt4/src/window.cpp\ - udt4/udtc/udtc.cpp -UDT4_DIRS = @builddir@/udt4/src @builddir@/udt4/udtc -UDT4_OBJECTS=$(UDT4_SOURCES:.cpp=.o) -UDT_OBJECTS = IoRoutinesUdt.o $(UDT4_OBJECTS) -UDTV6_OBJECTS = IoRoutinesUdtV6.o $(UDT4_OBJECTS) -CLEAN_OBJECTS = $(COMPRESSION_OBJECTS) $(LIB_OBJECTS) $(TCP_OBJECTS) $(TCPV6_OBJECTS) $(UDT_OBJECTS) $(UDTV6_OBJECTS) $(SERVER_LIB_OBJECTS) $(SERVER_OBJECTS) -ALL_SOURCES = $(LIB_SOURCES) $(TCP_SOURCES) $(SERVER_LIB_SOURCES) $(SERVER_SOURCES) + +CLEAN_OBJECTS = $(COMPRESSION_OBJECTS) $(LIB_OBJECTS) $(TCP_OBJECTS) $(TCPV6_OBJECTS) $(UDT_OBJECTS) $(UDTV6_OBJECTS) +ALL_SOURCES = $(LIB_SOURCES) $(TCP_SOURCES) bin_SCRIPTS = @MINGW_TRUE@bin_SCRIPTS += @MAKEBINDIR@mdsip_service.exe.manifest @@ -105,15 +108,15 @@ bin_SCRIPTS = ifneq "@GLOBUS_FLAVOR@" "" MdsIpGSI = @MAKESHLIBDIR@@LIBPRE@MdsIpGSI@SHARETYPE@ -ALL_SOURCES = $(ALL_SOURCES) $(GSI_SOURCES) -CLEAN_OBJECTS = $(COMPRESSION_OBJECTS) $(LIB_OBJECTS) $(TCP_OBJECTS)\ - $(TCPV6_OBJECTS) $(UDT_OBJECTS) $(UDTV6_OBJECTS)\ - $(SERVER_LIB_OBJECTS) $(SERVER_OBJECTS) IoRoutinesGsi.o +GSI_SOURCES = @srcdir@/io_routines/IoRoutinesGsi.c +GSI_OBJECTS = $(GSI_SOURCES:@srcdir@/%.c=%.o) +ALL_SOURCES += $(GSI_SOURCES) +CLEAN_OBJECTS += $(GSI_OBJECTS) MDSIPSD = @MAKEBINDIR@mdsipsd endif #GLOBUS_FLAVOR -PROGRAMS = $(bin_SCRIPTS) $(MDSIPSD) @MAKEBINDIR@mdsip$(EXE) @MAKEBINDIR@mdsiptest$(EXE) $(MDSIP_SERVICE) +PROGRAMS = $(bin_SCRIPTS) $(MDSIPSD) @MAKEBINDIR@mdsip$(EXE) $(MDSIP_SERVICE) all : primary $(MAKE) secundary @MAKEFLAG_J@ @MAKEFLAG_O@ @@ -127,7 +130,6 @@ primary : \ secundary : primary \ $(modules) \ - $(MdsIpSrvShr) \ $(MdsIpTCP) \ $(MdsIpTCPV6) \ $(IPV6_UDT) \ @@ -148,34 +150,32 @@ clean : @ $(RM) $(PROGRAMS) @ $(RM) @MAKEETCDIR@mdsip.hosts @ $(RM) @MAKEETCDIR@multi.hosts - @ $(RM) $(MdsIpSrvShr) @ $(RM) @MAKELIBDIR@@LIBPRE@MdsIpTCP@SHARETYPE@ @ $(RM) @MAKELIBDIR@@LIBPRE@MdsIpTCPV6@SHARETYPE@ @ $(RM) @MAKELIBDIR@@LIBPRE@MdsIpUDT@SHARETYPE@ @ $(RM) @MAKELIBDIR@@LIBPRE@MdsIpUDTV6@SHARETYPE@ - ifdef MdsIpGSI +ifdef MdsIpGSI @ $(RM) $(MdsIpGSI) @ $(RM) $(MDSIPSD) - endif +endif install: $(bindir) $(libdir) $(sysconfdir) $(INSTALL) -m 755 $(PROGRAMS) @bindir@ $(INSTALL) -m 755 $(MdsIpShr) @libdir@ - ifdef modules - $(INSTALL) -m 755 @MAKESHLIBDIR@@LIBPRE@MdsIpShr@SHARETYPEMOD@ @libdir@ - endif +ifdef modules + $(INSTALL) -m 755 @MAKESHLIBDIR@@LIBPRE@MdsIpShr@SHARETYPEMOD@ @libdir@ +endif if test "@SHARETYPE@" != ".a" ; then \ $(INSTALL) -m 644 @MAKELIBDIR@@LIBPRE@MdsIpShr.a @libdir@; \ fi; $(INSTALL) -m 755 @MAKEETCDIR@mdsip.hosts $(sysconfdir) $(INSTALL) -m 755 @MAKEETCDIR@multi.hosts $(sysconfdir) - $(INSTALL) -m 755 $(MdsIpSrvShr) @libdir@ $(INSTALL) -m 755 $(MdsIpTCP) @libdir@ $(INSTALL) -m 755 $(MdsIpTCPV6) @libdir@ @MINGW_FALSE@ $(INSTALL) -m 755 $(IPV6_UDT) @libdir@ - ifdef MdsIpGSI - $(INSTALL) -m 755 $(MdsIpGSI) @libdir@ - endif +ifdef MdsIpGSI + $(INSTALL) -m 755 $(MdsIpGSI) @libdir@ +endif .PHONY: docs docs: @@ -183,17 +183,12 @@ docs: EXTRALIBS = -L@MAKESHLIBDIR@ -lMdsShr -lTdiShr -lTreeShr -@MAKEBINDIR@mdsiptest$(EXE): testing/mdsiptest.c $(MdsIpShr) - $(LINK.c) $< $(OUTPUT_OPTION) $(EXTRALIBS) -lMdsIpShr $(LIBS) - @MAKEBINDIR@mdsip_service.exe: mdsip_service.c $(MdsIpShr) $(LINK.c) $< $(OUTPUT_OPTION) $(EXTRALIBS) -lMdsIpShr $(LIBS) -@MAKEBINDIR@mdsip$(EXE): $(MdsIpSrvShr) - @MAKEBINDIR@mdsip$(EXE): $(MdsIpShr) @MAKEBINDIR@mdsip$(EXE): $(SERVER_OBJECTS) - $(LINK.c) $(OUTPUT_OPTION) $(SERVER_OBJECTS) $(EXTRALIBS) -lMdsIpShr -lMdsIpSrvShr $(LIBS) + $(LINK.c) $(OUTPUT_OPTION) $(SERVER_OBJECTS) $(EXTRALIBS) -lMdsIpShr $(LIBS) @MAKELIBDIR@@LIBPRE@MdsIpShr.a : $(LIB_OBJECTS) $(COMPRESSION_OBJECTS) $(AR) -cr $@ $^ @@ -208,12 +203,8 @@ $(MDSIP_UTIL) : mdsiputil.o mdsip_socket_io.o mdsip_parallel.o $(COMPRESSION_OBJ @MINGW_TRUE@ MAKE_IMPLIB_MdsIpShr=-Wl,--out-implib,$(IMPLIB_MdsIpShr) $(MdsIpShr): $(LIB_OBJECTS) $(COMPRESSION_OBJECTS) - $(LINK.c) $(OUTPUT_OPTION) $^ @LINKSHARED@ $(EXTRALIBS) $(LIBS) $(MAKE_IMPLIB_MdsIpShr) - + $(LINK.c) $(OUTPUT_OPTION) $^ @LINKSHARED@ $(EXTRALIBS) $(LIBS) -lMdsShr -lTreeShr -lTdiShr $(MAKE_IMPLIB_MdsIpShr) LINK_MDSIPSHR = -L@MAKESHLIBDIR@ -lMdsIpShr -lMdsShr -@MINGW_TRUE@ MAKE_IMPLIB_MdsIpSrvShr=-Wl,--out-implib,$(IMPLIB_MdsIpSrvShr) -$(MdsIpSrvShr): $(SERVER_LIB_OBJECTS) $(MdsIpShr) - $(LINK.c) $(OUTPUT_OPTION) @LINKSHARED@ $(SERVER_LIB_OBJECTS) $(LINK_MDSIPSHR) -lTreeShr -lTdiShr $(LIBS) $(MAKE_IMPLIB_MdsIpSrvShr) $(MdsIpTCP): $(TCP_OBJECTS) $(MdsIpShr) $(LINK.c) $(OUTPUT_OPTION) @LINKSHARED@ $(TCP_OBJECTS) $(LINK_MDSIPSHR) $(LIBS) @@ -221,15 +212,10 @@ $(MdsIpTCP): $(TCP_OBJECTS) $(MdsIpShr) $(MdsIpTCPV6): $(TCPV6_OBJECTS) $(MdsIpShr) $(LINK.c) $(OUTPUT_OPTION) @LINKSHARED@ $(TCPV6_OBJECTS) $(LINK_MDSIPSHR) $(LIBS) -.PHONY: $(UDT4_DIRS) -$(UDT4_DIRS): - $(MKDIR_P) @builddir@/udt4/src - $(MKDIR_P) @builddir@/udt4/udtc - -$(MdsIpUDT): $(UDT4_DIRS) $(UDT_OBJECTS) $(MdsIpShr) +$(MdsIpUDT): $(UDT_OBJECTS) $(MdsIpShr) $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDT_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) -$(MdsIpUDTV6): $(UDT4_DIRS) $(UDTV6_OBJECTS) $(MdsIpShr) +$(MdsIpUDTV6): $(UDTV6_OBJECTS) $(MdsIpShr) $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDTV6_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) @MAKEETCDIR@mdsip.hosts : mdsip.hosts$(WIN) @@ -243,13 +229,13 @@ $(bin_SCRIPTS): @MAKEBINDIR@%: % ifdef MdsIpGSI -#makefile-header: +#makefile-header: # GLOBUS_LOCATION=@GLOBUS_LOCATION@; $$GLOBUS_LOCATION/bin/globus-makefile-header --flavor=@GLOBUS_FLAVOR@pthr globus_xio globus_xio_gsi_driver > makefile-eader #include makefile-header -$(MdsIpGSI): IoRoutinesGsi.c - $(LINK.c) $(OUTPUT_OPTION) $^ $$(pkg-config --cflags globus-xio) @LINKSHARED@ $(LIBS) $(LINK_MDSIPSHR) $$(pkg-config --libs globus-xio globus-xio-gsi-driver globus-gssapi-gsi globus-gss-assist globus-common) +$(MdsIpGSI): io_routines/IoRoutinesGsi.c | --io_routines-dir + $(LINK.c) $(OUTPUT_OPTION) $< $$(pkg-config --cflags globus-xio) @LINKSHARED@ $(LIBS) $(LINK_MDSIPSHR) $$(pkg-config --libs globus-xio globus-xio-gsi-driver globus-gssapi-gsi globus-gss-assist globus-common) @MAKEBINDIR@mdsipsd : mdsipsd cp $< $@ diff --git a/mdstcpip/ProcessMessage.c b/mdstcpip/ProcessMessage.c deleted file mode 100644 index 282e15ebbf..0000000000 --- a/mdstcpip/ProcessMessage.c +++ /dev/null @@ -1,1299 +0,0 @@ -/* -Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include - -#if defined(linux) && !defined(_LARGEFILE_SOURCE) -#define _LARGEFILE_SOURCE -#define _FILE_OFFSET_BITS 64 -#define __USE_FILE_OFFSET64 -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef _WIN32 -#include -#else -#ifdef HAVE_UNISTD_H -#include -#endif -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include "../tdishr/tdithreadstatic.h" -#include "../treeshr/treeshrp.h" -#include "cvtdef.h" -#include "mdsIo.h" -#include "mdsip_connections.h" - -extern int TdiRestoreContext(); -extern int TdiSaveContext(); - -#ifdef min -#undef min -#endif -#define min(a, b) (((a) < (b)) ? (a) : (b)) -#ifdef max -#undef max -#endif -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -static void ConvertBinary(int num, int sign_extend, short in_length, - char *in_ptr, short out_length, char *out_ptr) -{ - int i; - int j; - signed char *in_p = (signed char *)in_ptr; - signed char *out_p = (signed char *)out_ptr; - short min_len = min(out_length, in_length); - for (i = 0; i < num; i++, in_p += in_length, out_p += out_length) - { - for (j = 0; j < min_len; j++) - out_p[j] = in_p[j]; - for (; j < out_length; j++) - out_p[j] = sign_extend ? (in_p[min_len - 1] < 0 ? -1 : 0) : 0; - } -} - -static void ConvertFloat(int num, int in_type, char in_length, char *in_ptr, - int out_type, char out_length, char *out_ptr) -{ - int i; - char *in_p; - char *out_p; - for (i = 0, in_p = in_ptr, out_p = out_ptr; i < num; - i++, in_p += in_length, out_p += out_length) - { - char *ptr = in_p; - char cray_f[8]; - if (in_type == CvtCRAY) - { - int j, k; - for (j = 0; j < 2; j++) - for (k = 0; k < 4; k++) -#ifdef WORDS_BIGENDIAN - cray_f[j * 4 + k] = ptr[j * 4 + 3 - k]; -#else - cray_f[(1 - j) * 4 + k] = ptr[j * 4 + 3 - k]; -#endif - ptr = cray_f; - } - CvtConvertFloat(ptr, in_type, out_p, out_type, 0); -#ifdef WORDS_BIGENDIAN - if (out_type == CvtCRAY) - { - int j, k; - ptr = out_p; - for (j = 0; j < 2; j++) - for (k = 0; k < 4; k++) - cray_f[j * 4 + k] = ptr[j * 4 + 3 - k]; - for (j = 0; j < 8; j++) - ptr[j] = cray_f[j]; - } -#endif - } -} - -/// -/// -/// \param client_type -/// \param message_id -/// \param status -/// \param d -/// \return -/// - -static Message *BuildResponse(int client_type, unsigned char message_id, - int status, struct descriptor *d) -{ - Message *m = NULL; - /* - if (SupportsCompression(client_type)) { - INIT_AND_FREEXD_ON_EXIT(out); - if (IS_OK(MdsSerializeDscOut(d, &out))) { - struct descriptor_a* array = (struct descriptor_a*)out.pointer; - m = malloc(sizeof(MsgHdr) + array->arsize); - memset(&m->h,0,sizeof(MsgHdr)); - m->h.msglen = sizeof(MsgHdr) + array->arsize; - m->h.client_type= client_type; - m->h.message_id = message_id; - m->h.status = status; - m->h.dtype = DTYPE_SERIAL; - m->h.length = 1; - memcpy(m->bytes, array->pointer, array->arsize); - } - FREEXD_NOW(out); - return m; - } - */ - int nbytes = (d->class == CLASS_S) ? d->length : ((array_coeff *)d)->arsize; - int num = nbytes / ((d->length < 1) ? 1 : d->length); - short length = d->length; - if (CType(client_type) == CRAY_CLIENT) - { - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - case DTYPE_SHORT: - case DTYPE_LONG: - case DTYPE_F: - case DTYPE_FS: - length = 8; - break; - case DTYPE_FC: - case DTYPE_FSC: - case DTYPE_D: - case DTYPE_G: - case DTYPE_FT: - length = 16; - break; - default: - length = d->length; - break; - } - nbytes = num * length; - } - else if (CType(client_type) == CRAY_IEEE_CLIENT) - { - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_SHORT: - length = 4; - break; - case DTYPE_ULONG: - case DTYPE_LONG: - length = 8; - break; - default: - length = d->length; - break; - } - nbytes = num * length; - } - m = malloc(sizeof(MsgHdr) + nbytes); - memset(&m->h, 0, sizeof(MsgHdr)); - m->h.msglen = sizeof(MsgHdr) + nbytes; - m->h.client_type = client_type; - m->h.message_id = message_id; - m->h.status = status; - m->h.dtype = d->dtype; - m->h.length = length; - if (d->class == CLASS_S) - m->h.ndims = 0; - else - { - int i; - array_coeff *a = (array_coeff *)d; - m->h.ndims = a->dimct; - if (a->aflags.coeff) - for (i = 0; i < m->h.ndims && i < MAX_DIMS; i++) - m->h.dims[i] = a->m[i]; - else - m->h.dims[0] = a->length ? a->arsize / a->length : 0; - for (i = m->h.ndims; i < MAX_DIMS; i++) - m->h.dims[i] = 0; - } - switch (CType(client_type)) - { - case IEEE_CLIENT: - case JAVA_CLIENT: - switch (d->dtype) - { - case DTYPE_F: - ConvertFloat(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - ConvertFloat(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtIEEE_S, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FS: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - ConvertFloat(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - ConvertFloat(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - ConvertFloat(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - ConvertFloat(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FT: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } - break; - case CRAY_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - ConvertBinary(num, 0, d->length, d->pointer, m->h.length, m->bytes); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - ConvertBinary(num, 1, (char)d->length, d->pointer, (char)m->h.length, - m->bytes); - break; - case DTYPE_F: - ConvertFloat(num, CvtVAX_F, (char)d->length, d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FS: - ConvertFloat(num, CvtIEEE_S, (char)d->length, d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FC: - ConvertFloat(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtCRAY, (char)(m->h.length / 2), m->bytes); - break; - case DTYPE_FSC: - ConvertFloat(num * 2, CvtIEEE_S, (char)(d->length / 2), d->pointer, - CvtCRAY, (char)(m->h.length / 2), m->bytes); - break; - case DTYPE_D: - ConvertFloat(num, CvtVAX_D, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_G: - ConvertFloat(num, CvtVAX_G, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FT: - ConvertFloat(num, CvtIEEE_T, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } - break; - case CRAY_IEEE_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - ConvertBinary(num, 0, d->length, d->pointer, m->h.length, m->bytes); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - ConvertBinary(num, 1, (char)d->length, d->pointer, (char)m->h.length, - m->bytes); - break; - case DTYPE_F: - ConvertFloat(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - ConvertFloat(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtIEEE_S, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FS: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - ConvertFloat(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - ConvertFloat(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - ConvertFloat(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - ConvertFloat(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FT: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } - break; - case VMSG_CLIENT: - switch (d->dtype) - { - case DTYPE_F: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - ConvertFloat(num, CvtVAX_D, sizeof(double), d->pointer, CvtVAX_G, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - ConvertFloat(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtVAX_G, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FS: - ConvertFloat(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - ConvertFloat(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FT: - ConvertFloat(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - ConvertFloat(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } - break; - default: - switch (d->dtype) - { - case DTYPE_F: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - ConvertFloat(num, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - ConvertFloat(num * 2, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FS: - ConvertFloat(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - ConvertFloat(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FT: - ConvertFloat(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - ConvertFloat(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } - break; - } - return m; -} - -static void GetErrorText(int status, mdsdsc_xd_t *xd) -{ - static DESCRIPTOR(unknown, "unknown error occured"); - struct descriptor message = {0, DTYPE_T, CLASS_S, 0}; - if ((message.pointer = MdsGetMsg(status)) != NULL) - { - message.length = strlen(message.pointer); - MdsCopyDxXd(&message, xd); - } - else - MdsCopyDxXd((struct descriptor *)&unknown, xd); -} - -static void ClientEventAst(MdsEventList *e, int data_len, char *data) -{ - int conid = e->conid; - Connection *c = FindConnection(e->conid, 0); - int i; - char client_type; - Message *m; - JMdsEventInfo *info; - int len; - // Check Connection: if down, cancel the event and return - if (!c) - { - MDSEventCan(e->eventid); - return; - } - client_type = c->client_type; - LockAsts(); - if (CType(client_type) == JAVA_CLIENT) - { - len = sizeof(MsgHdr) + sizeof(JMdsEventInfo); - m = memset(malloc(len), 0, len); - m->h.ndims = 0; - m->h.client_type = client_type; - m->h.msglen = len; - m->h.dtype = DTYPE_EVENT_NOTIFY; - info = (JMdsEventInfo *)m->bytes; - if (data_len > 0) - memcpy(info->data, data, (data_len < 12) ? data_len : 12); - for (i = data_len; i < 12; i++) - info->data[i] = 0; - info->eventid = e->jeventid; - } - else - { - m = memset(malloc(sizeof(MsgHdr) + e->info_len), 0, - sizeof(MsgHdr) + e->info_len); - m->h.ndims = 0; - m->h.client_type = client_type; - m->h.msglen = sizeof(MsgHdr) + e->info_len; - m->h.dtype = DTYPE_EVENT_NOTIFY; - if (data_len > 0) - memcpy(e->info->data, data, (data_len < 12) ? data_len : 12); - for (i = data_len; i < 12; i++) - e->info->data[i] = 0; - memcpy(m->bytes, e->info, e->info_len); - } - SendMdsMsg(conid, m, MSG_DONTWAIT); - free(m); - UnlockAsts(); -} - -/* The following implementation of a cancelable worker is used in: - * tdishr/TdiDoTask.c - * mdstcpip/ProcessMessage.c - * Problems with the implementation are likely to be fixed in all locations. - */ -typedef struct -{ - void **ctx; - int status; -#ifndef _WIN32 - Condition *const condition; -#endif - MDSplusThreadStatic_t *mts; - Connection *const connection; - mdsdsc_xd_t *const xd_out; -} worker_args_t; - -typedef struct -{ - worker_args_t *const wa; - mdsdsc_xd_t *const xdp; -} worker_cleanup_t; - -static void WorkerCleanup(worker_cleanup_t *const wc) -{ -#ifndef _WIN32 - CONDITION_SET(wc->wa->condition); -#endif - free_xd(wc->xdp); -} - -static int WorkerThread(void *args) -{ - EMPTYXD(xd); - worker_cleanup_t wc = {(worker_args_t *)args, &xd}; - pthread_cleanup_push((void *)WorkerCleanup, (void *)&wc); - TDITHREADSTATIC(MDSplusThreadStatic(wc.wa->mts)); - --TDI_INTRINSIC_REC; - wc.wa->status = TdiIntrinsic(OPC_EXECUTE, wc.wa->connection->nargs, - wc.wa->connection->descrip, &xd); - ++TDI_INTRINSIC_REC; - if (IS_OK(wc.wa->status)) - wc.wa->status = TdiData(xd.pointer, wc.wa->xd_out MDS_END_ARG); - pthread_cleanup_pop(1); - return wc.wa->status; -} - -static inline int executeCommand(Connection *connection, mdsdsc_xd_t *ans_xd) -{ - // fprintf(stderr,"starting task for connection %d\n",connection->id); - void *tdicontext[6], *pc = NULL; - MDSplusThreadStatic_t *mts = MDSplusThreadStatic(NULL); -#ifdef _WIN32 - worker_args_t wa = { -#else - Condition WorkerRunning = CONDITION_INITIALIZER; - worker_args_t wa = {.condition = &WorkerRunning, -#endif - .mts = mts, - .status = -1, - .connection = connection, - .xd_out = ans_xd - }; - if (GetContextSwitching()) - { - pc = TreeCtxPush(&connection->DBID); - TdiSaveContext(tdicontext); - TdiRestoreContext(connection->tdicontext); - } -#ifdef _WIN32 - HANDLE hWorker = CreateThread(NULL, DEFAULT_STACKSIZE * 16, - (void *)WorkerThread, &wa, 0, NULL); - if (!hWorker) - { - errno = GetLastError(); - perror("ERROR CreateThread"); - wa.status = MDSplusFATAL; - goto end; - } - int canceled = B_FALSE; - if (connection->io->check) - while (WaitForSingleObject(hWorker, 100) == WAIT_TIMEOUT) - { - if (!connection->io->check(connection)) - continue; - fflush(stdout); - fprintf(stderr, "Client disconnected, terminating Worker\n"); - TerminateThread(hWorker, 2); - canceled = B_TRUE; - break; - } - WaitForSingleObject(hWorker, INFINITE); - if (canceled) - wa.status = TdiABORT; -#else - pthread_t Worker; - _CONDITION_LOCK(wa.condition); - CREATE_THREAD(Worker, *16, WorkerThread, &wa); - if (c_status) - { - perror("ERROR pthread_create"); - _CONDITION_UNLOCK(wa.condition); - pthread_cond_destroy(&WorkerRunning.cond); - pthread_mutex_destroy(&WorkerRunning.mutex); - wa.status = MDSplusFATAL; - goto end; - } - int canceled = B_FALSE; - for (;;) - { - _CONDITION_WAIT_1SEC(wa.condition, ); - if (WorkerRunning.value) - break; - if (canceled) - continue; // skip check if already canceled - if (!connection->io->check) - continue; // if no io->check def - if (!connection->io->check(connection)) - continue; - fflush(stdout); - fprintf(stderr, "Client disconnected, canceling Worker .."); - pthread_cancel(Worker); - canceled = B_TRUE; - _CONDITION_WAIT_1SEC(wa.condition, ); - fflush(stdout); - if (WorkerRunning.value) - fprintf(stderr, " ok\n"); - else - { - fprintf(stderr, " failed - sending SIGCHLD\n"); - pthread_kill(Worker, SIGCHLD); - } - break; - } - _CONDITION_UNLOCK(wa.condition); - void *result; - pthread_join(Worker, &result); - pthread_cond_destroy(&WorkerRunning.cond); - pthread_mutex_destroy(&WorkerRunning.mutex); - if (canceled && result == PTHREAD_CANCELED) - wa.status = TdiABORT; -#endif -end:; - if (pc) - { - TdiSaveContext(connection->tdicontext); - TdiRestoreContext(tdicontext); - TreeCtxPop(pc); - } - return wa.status; -} - -/// -/// Executes TDI expression held by a connecion instance. This first searches if -/// connection message corresponds to AST or CAN requests, if no asyncronous ops -/// are requested the TDI actual expression is parsed through tdishr library. -/// In this case the current TDI context and tree is switched to the connection -/// ones stored in the connection context field. -/// -/// ### AST and CAN -/// AST and CAN stands for "Asynchronous System Trap" and "CANcel event -/// request". This is an asyncronous message mechanism taken from the OpenVMS -/// system. The event handler is passed inside the message arguments and -/// executed by the MDSEventAst() function from mdslib. -/// -/// \param connection the Connection instance filled with proper descriptor -/// arguments \return the execute message answer built using BuildAnswer() -/// -static Message *ExecuteMessage(Connection *connection) -{ - Message *ans = 0; // return message instance // - int status = 1; // return status // - - char *evname; - static DESCRIPTOR(eventastreq, EVENTASTREQUEST); // AST request descriptor // - static DESCRIPTOR(eventcanreq, EVENTCANREQUEST); // Can request descriptor // - - int client_type = connection->client_type; - int java = CType(client_type) == JAVA_CLIENT; - int message_id = connection->message_id; - - // AST REQUEST // - if (StrCompare(connection->descrip[0], (struct descriptor *)&eventastreq) == - 0) - { - static int eventid = -1; - static DESCRIPTOR_LONG(eventiddsc, &eventid); - MdsEventList *newe = (MdsEventList *)malloc(sizeof(MdsEventList)); - struct descriptor_a *info = (struct descriptor_a *)connection->descrip[2]; - newe->conid = connection->id; - - evname = malloc(connection->descrip[1]->length + 1); - memcpy(evname, connection->descrip[1]->pointer, - connection->descrip[1]->length); - evname[connection->descrip[1]->length] = 0; - - // Manage AST Event // - status = MDSEventAst(evname, (void (*)(void *, int, char *))ClientEventAst, - newe, &newe->eventid); - - free(evname); - if (java) - { - newe->info = 0; - newe->info_len = 0; - newe->jeventid = *connection->descrip[2]->pointer; - } - else - { - newe->info = (MdsEventInfo *)memcpy(malloc(info->arsize), info->pointer, - info->arsize); - newe->info_len = info->arsize; - newe->info->eventid = newe->eventid; - } - newe->next = 0; - if (!(status & 1)) - { - eventiddsc.pointer = (void *)&eventid; - free(newe->info); - free(newe); - } - else - { - MdsEventList *e; - eventiddsc.pointer = (void *)&newe->eventid; - if (connection->event) - { - for (e = connection->event; e->next; e = e->next) - ; - e->next = newe; - } - else - connection->event = newe; - } - if (!java) - ans = BuildResponse(client_type, message_id, status, &eventiddsc); - } - // CAN REQUEST // - else if (StrCompare(connection->descrip[0], - (struct descriptor *)&eventcanreq) == 0) - { - static int eventid; - static DESCRIPTOR_LONG(eventiddsc, &eventid); - MdsEventList *e; - MdsEventList **p; - if (!java) - eventid = *(int *)connection->descrip[1]->pointer; - else - eventid = (int)*connection->descrip[1]->pointer; - if (connection->event) - { - for (p = &connection->event, e = connection->event; - e && (e->eventid != eventid); p = &e->next, e = e->next) - ; - if (e) - { - /**/ MDSEventCan(e->eventid); - /**/ *p = e->next; - free(e); - } - } - if (!java) - ans = BuildResponse(client_type, message_id, status, &eventiddsc); - } - // NORMAL TDI COMMAND // - else - { - INIT_AND_FREEXD_ON_EXIT(ans_xd); - status = executeCommand(connection, &ans_xd); - if (STATUS_NOT_OK) - GetErrorText(status, &ans_xd); - if (GetCompressionLevel() != connection->compression_level) - { - connection->compression_level = GetCompressionLevel(); - if (connection->compression_level > GetMaxCompressionLevel()) - connection->compression_level = GetMaxCompressionLevel(); - SetCompressionLevel(connection->compression_level); - } - ans = BuildResponse(connection->client_type, connection->message_id, status, - ans_xd.pointer); - FREEXD_NOW(ans_xd); - } - FreeDescriptors(connection); - return ans; -} - -static inline char *replaceBackslashes(char *filename) -{ - char *ptr; - while ((ptr = strchr(filename, '\\')) != NULL) - *ptr = '/'; - return filename; -} - -/// -/// Handle message from server listen routine. A new descriptor instance is -/// created with the message buffer size and the message memory is copyed -/// inside. A proper conversion of memory structure is applied if neede for the -/// type of client connected. -/// -/// \param connection the connection instance to handle -/// \param message the message to process -/// \return message answer -/// -Message *ProcessMessage(Connection *connection, Message *message) -{ - - Message *ans = 0; - - // COMING NEW MESSAGE // - // reset connection id // - if (connection->message_id != message->h.message_id) - { - FreeDescriptors(connection); - if (message->h.nargs < MDSIP_MAX_ARGS - 1) - { - connection->message_id = message->h.message_id; - connection->nargs = message->h.nargs; - } - else - { - DESCRIPTOR_LONG(status_d, 0); - int status = 0; - status_d.pointer = (char *)&status; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - (struct descriptor *)&status_d); - return ans; - } - } - - // STANADARD COMMANDS //////////////////////////////////////////////////////// - // idx < nargs //////////////////////////////////////////////////////// - if (message->h.descriptor_idx < connection->nargs) - { - - // set connection to the message client_type // - connection->client_type = message->h.client_type; - -#define COPY_DESC(name, GENERATOR, ...) \ - do \ - { \ - const GENERATOR(__VA_ARGS__); \ - *(void **)&d = memcpy(malloc(sizeof(tmp)), &tmp, sizeof(tmp)); \ - } while (0) - - // d -> reference to curent idx argument desctriptor // - struct descriptor *d = connection->descrip[message->h.descriptor_idx]; - if (message->h.dtype == DTYPE_SERIAL) - { - if (d && d->class != CLASS_XD) - { - if (d->class == CLASS_D && d->pointer) - free(d->pointer); - free(d); - } - COPY_DESC(d, EMPTYXD, tmp); - connection->descrip[message->h.descriptor_idx] = d; - return ans; - } - if (!d) - { - // instance the connection descriptor field // - const short lengths[] = {0, 0, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 8, 16, 0}; - if (message->h.ndims == 0) - { - d = calloc(1, sizeof(struct descriptor_s)); - d->class = CLASS_S; - } - else - COPY_DESC(d, DESCRIPTOR_A_COEFF, tmp, 0, 0, 0, MAX_DIMS, 0); - d->length = message->h.dtype < DTYPE_CSTRING ? lengths[message->h.dtype] - : message->h.length; - d->dtype = message->h.dtype; - if (d->class == CLASS_A) - { - array_coeff *a = (array_coeff *)d; - int num = 1; - int i; - a->dimct = message->h.ndims; - for (i = 0; i < a->dimct; i++) - { - a->m[i] = message->h.dims[i]; - num *= a->m[i]; - } - a->arsize = a->length * num; - a->pointer = a->a0 = malloc(a->arsize); - } - else - d->pointer = d->length ? malloc(d->length) : 0; - // set new instance // - connection->descrip[message->h.descriptor_idx] = d; - } - if (d) - { - // have valid connection descriptor instance // - // copy the message buffer into the descriptor // - - int dbytes = d->class == CLASS_S ? (int)d->length - : (int)((array_coeff *)d)->arsize; - int num = dbytes / max(1, d->length); - - switch (CType(connection->client_type)) - { - case IEEE_CLIENT: - case JAVA_CLIENT: - memcpy(d->pointer, message->bytes, dbytes); - break; - case CRAY_IEEE_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - ConvertBinary(num, 0, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - ConvertBinary(num, 1, message->h.length, message->bytes, d->length, - d->pointer); - break; - default: - memcpy(d->pointer, message->bytes, dbytes); - break; - } - break; - case CRAY_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - ConvertBinary(num, 0, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - ConvertBinary(num, 1, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_FLOAT: - ConvertFloat(num, CvtCRAY, (char)message->h.length, message->bytes, - CvtIEEE_S, (char)d->length, d->pointer); - break; - case DTYPE_COMPLEX: - ConvertFloat(num * 2, CvtCRAY, (char)(message->h.length / 2), - message->bytes, CvtIEEE_S, (char)(d->length / 2), - d->pointer); - break; - case DTYPE_DOUBLE: - ConvertFloat(num, CvtCRAY, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); - break; - default: - memcpy(d->pointer, message->bytes, dbytes); - break; - } - break; - default: - switch (d->dtype) - { - case DTYPE_FLOAT: - ConvertFloat(num, CvtVAX_F, (char)message->h.length, message->bytes, - CvtIEEE_S, sizeof(float), d->pointer); - break; - case DTYPE_COMPLEX: - ConvertFloat(num * 2, CvtVAX_F, (char)message->h.length, - message->bytes, CvtIEEE_S, sizeof(float), d->pointer); - break; - case DTYPE_DOUBLE: - if (CType(connection->client_type) == VMSG_CLIENT) - ConvertFloat(num, CvtVAX_G, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); - else - ConvertFloat(num, CvtVAX_D, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); - break; - - case DTYPE_COMPLEX_DOUBLE: - if (CType(connection->client_type) == VMSG_CLIENT) - ConvertFloat(num * 2, CvtVAX_G, (char)(message->h.length / 2), - message->bytes, CvtIEEE_T, sizeof(double), d->pointer); - else - ConvertFloat(num * 2, CvtVAX_D, (char)(message->h.length / 2), - message->bytes, CvtIEEE_T, sizeof(double), d->pointer); - break; - default: - memcpy(d->pointer, message->bytes, dbytes); - break; - } - } - switch (d->dtype) - { - default: - break; - case DTYPE_FLOAT: - d->dtype = DTYPE_FS; - break; - case DTYPE_COMPLEX: - d->dtype = DTYPE_FSC; - break; - case DTYPE_DOUBLE: - d->dtype = DTYPE_FT; - break; - case DTYPE_COMPLEX_DOUBLE: - d->dtype = DTYPE_FTC; - break; - } - - // CALL EXECUTE MESSAGE // - if (message->h.descriptor_idx == (message->h.nargs - 1)) - { - ans = ExecuteMessage(connection); - } - } - } - - // SPECIAL I/O MESSAGES ////////////////////////////////////////////////////// - // idx >= nargs ////////////////////////////////////////////////////// - else - { - - connection->client_type = message->h.client_type; - const mdsio_t *mdsio = (mdsio_t *)message->h.dims; - switch (message->h.descriptor_idx) - { - case MDS_IO_OPEN_K: - { - char *filename = (char *)message->bytes; - int options = mdsio->open.options; - mode_t mode = mdsio->open.mode; - int fopts = 0; - if (options & MDS_IO_O_CREAT) - fopts |= O_CREAT; - if (options & MDS_IO_O_TRUNC) - fopts |= O_TRUNC; - if (options & MDS_IO_O_EXCL) - fopts |= O_EXCL; - if (options & MDS_IO_O_WRONLY) - fopts |= O_WRONLY; - if (options & MDS_IO_O_RDONLY) - fopts |= O_RDONLY; - if (options & MDS_IO_O_RDWR) - fopts |= O_RDWR; - int fd = MDS_IO_OPEN(filename, fopts, mode); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&fd}; - ans = BuildResponse(connection->client_type, connection->message_id, 3, - &ans_d); - break; - } - case MDS_IO_CLOSE_K: - { - int fd = mdsio->close.fd; - int ans_o = MDS_IO_CLOSE(fd); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - case MDS_IO_LSEEK_K: - { - int fd = mdsio->lseek.fd; - int64_t offset = mdsio->lseek.offset; - SWAP_INT_IF_BIGENDIAN(&offset); - int whence = mdsio->lseek.whence; - int64_t ans_o = MDS_IO_LSEEK(fd, offset, whence); - struct descriptor ans_d = {8, DTYPE_Q, CLASS_S, 0}; - ans_d.pointer = (char *)&ans_o; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - (struct descriptor *)&ans_d); - SWAP_INT_IF_BIGENDIAN(ans_d.pointer); - break; - } - case MDS_IO_READ_K: - { - int fd = mdsio->read.fd; - size_t count = mdsio->read.count; - void *buf = malloc(count); - ssize_t nbytes = MDS_IO_READ(fd, buf, count); -#ifdef USE_PERF - TreePerfRead(nbytes); -#endif - if (nbytes > 0) - { - DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); - if ((size_t)nbytes != count) - perror("READ_K wrong byte count"); - ans = BuildResponse(connection->client_type, connection->message_id, 1, - (struct descriptor *)&ans_d); - } - else - { - DESCRIPTOR(ans_d, ""); - ans = BuildResponse(connection->client_type, connection->message_id, 1, - (struct descriptor *)&ans_d); - } - free(buf); - break; - } - case MDS_IO_WRITE_K: - { - /* from http://man7.org/linux/man-pages/man2/write.2.html - * On Linux, write() (and similar system calls) will transfer at most - * 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes - * actually transferred. (This is true on both 32-bit and 64-bit - * systems.) => ergo uint32 will suffice - */ - int fd = mdsio->write.fd; - size_t count = mdsio->write.count; - uint32_t ans_o = - (uint32_t)(MDS_IO_WRITE(fd, message->bytes, count) & 0xFFFFFFFFL); - struct descriptor ans_d = {sizeof(ans_o), DTYPE_LU, CLASS_S, - (char *)&ans_o}; - SWAP_INT_IF_BIGENDIAN(ans_d.pointer); - if (ans_o != mdsio->write.count) - perror("WRITE_K wrong byte count"); - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - case MDS_IO_LOCK_K: - { - int fd = mdsio->lock.fd; - off_t offset = mdsio->lock.offset; - SWAP_INT_IF_BIGENDIAN(&offset); - int size = mdsio->lock.size; - int mode_in = mdsio->lock.mode; - int mode = mode_in & 0x3; - int nowait = mode_in & 0x8; - int deleted; - int ans_o = MDS_IO_LOCK(fd, offset, size, mode | nowait, &deleted); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, - deleted ? 3 : 1, &ans_d); - break; - } - case MDS_IO_EXISTS_K: - { - char *filename = message->bytes; - int ans_o = MDS_IO_EXISTS(filename); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - case MDS_IO_REMOVE_K: - { - char *filename = message->bytes; - int ans_o = MDS_IO_REMOVE(filename); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - case MDS_IO_RENAME_K: - { - char *old = message->bytes; - char *new = message->bytes + strlen(old) + 1; - int ans_o = MDS_IO_RENAME(old, new); - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - case MDS_IO_READ_X_K: - { - int fd = mdsio->read_x.fd; - off_t offset = mdsio->read_x.offset; - SWAP_INT_IF_BIGENDIAN(&offset); - size_t count = mdsio->read_x.count; - void *buf = malloc(count); - int deleted; - size_t nbytes = MDS_IO_READ_X(fd, offset, buf, count, &deleted); - if (nbytes > 0) - { - DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); - if ((size_t)nbytes != count) - perror("READ_X_K wrong byte count"); - ans = BuildResponse(connection->client_type, connection->message_id, - deleted ? 3 : 1, (struct descriptor *)&ans_d); - } - else - { - DESCRIPTOR(ans_d, ""); - ans = BuildResponse(connection->client_type, connection->message_id, - deleted ? 3 : 1, (struct descriptor *)&ans_d); - } - free(buf); - break; - } - case MDS_IO_OPEN_ONE_K: - { - char *treename = message->bytes; - char *filepath = message->bytes + strlen(treename) + 1; - int shot = mdsio->open_one.shot; - tree_type_t type = (tree_type_t)mdsio->open_one.type; - int new = mdsio->open_one.new; - int edit_flag = mdsio->open_one.edit; - int fd; - char *fullpath = NULL; - int status = MDS_IO_OPEN_ONE(filepath, treename, shot, type, new, - edit_flag, &fullpath, NULL, &fd); - int msglen = fullpath ? strlen(fullpath) + 9 : 8; - char *msg = malloc(msglen); - DESCRIPTOR_A(ans_d, sizeof(char), DTYPE_B, msg, msglen); - memcpy(msg, &status, 4); - memcpy(msg + 4, &fd, 4); - if (fullpath) - { - memcpy(msg + 8, fullpath, msglen - 8); - free(fullpath); - } - ans = BuildResponse(connection->client_type, connection->message_id, 3, - (struct descriptor *)&ans_d); - free(msg); - break; - } - default: - { - int ans_o = 0; - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - ans = BuildResponse(connection->client_type, connection->message_id, 1, - &ans_d); - break; - } - } - } - return ans; -} diff --git a/mdstcpip/b_order.h b/mdstcpip/b_order.h deleted file mode 100644 index 97fdab7562..0000000000 --- a/mdstcpip/b_order.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Find out what the byte order is on this machine. - * Big endian is for machines that place the most significant byte first. - * (eg. Sun SPARC) - * Little endian is for machines that place the least significant byte first. - * (eg. VAX) - * - * We figure out the byte order by stuffing a 2 byte string into a short and - * examining the left byte. '@' = 0x40 and 'P' = 0x50 - * If the left byte is the 'high' byte, then it is 'big endian'. If the left - * byte is the 'low' byte, then the machine is 'little endian'. - * - * -- Shawn A. Clifford (sac@eng.ufl.edu) - */ - -#define BIG_ENDIAN (((unsigned short)('@P') >> 8) == 0x40) -#define LITTLE_ENDIAN (((unsigned short)('@P') >> 8) == 0x50) diff --git a/mdstcpip/docs/Makefile.am b/mdstcpip/docs/Makefile.am index 7abdf02b5d..b867ad112d 100644 --- a/mdstcpip/docs/Makefile.am +++ b/mdstcpip/docs/Makefile.am @@ -17,26 +17,17 @@ DX_PAGES = .. \ index.md \ Clients_connection.md \ Objects_bindings.md \ - Protocols_plugins.md - - + Protocols_plugins.md + + DX_EXCLUDE_PAGES = \ - ../b_order.h \ - ../mdsip_u.h \ - ../mdsip_u.c \ - ../vmshpwd.c \ - ../cvtdef.h \ - ../IoRoutinesGsi.c \ - ../IoRoutinesTcp.c \ - ../IoRoutinesTcpv6.c \ - ../IoRoutinesUdt.c \ - ../IoRoutinesUdtV6.c \ - ../IoRoutinesTunnel.c \ + ../io_routines/* \ + ../udt4/* \ + ../zlib/* \ ../mdsip.c \ ../mdsip.h \ - ../mdsipshr.c \ ../mdsip_service.c - + DX_TAGFILES = docs.tag diff --git a/mdstcpip/IoRoutinesGsi.c b/mdstcpip/io_routines/IoRoutinesGsi.c similarity index 99% rename from mdstcpip/IoRoutinesGsi.c rename to mdstcpip/io_routines/IoRoutinesGsi.c index 0887e57548..bb38f45463 100644 --- a/mdstcpip/IoRoutinesGsi.c +++ b/mdstcpip/io_routines/IoRoutinesGsi.c @@ -57,7 +57,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" static ssize_t gsi_send(Connection *c, const void *buffer, size_t buflen, int nowait); diff --git a/mdstcpip/IoRoutinesTcp.c b/mdstcpip/io_routines/IoRoutinesTcp.c similarity index 100% rename from mdstcpip/IoRoutinesTcp.c rename to mdstcpip/io_routines/IoRoutinesTcp.c diff --git a/mdstcpip/IoRoutinesTcpV6.c b/mdstcpip/io_routines/IoRoutinesTcpV6.c similarity index 100% rename from mdstcpip/IoRoutinesTcpV6.c rename to mdstcpip/io_routines/IoRoutinesTcpV6.c diff --git a/mdstcpip/IoRoutinesThread.c b/mdstcpip/io_routines/IoRoutinesThread.c similarity index 99% rename from mdstcpip/IoRoutinesThread.c rename to mdstcpip/io_routines/IoRoutinesThread.c index 0a2b9a5720..bd194e9985 100644 --- a/mdstcpip/IoRoutinesThread.c +++ b/mdstcpip/io_routines/IoRoutinesThread.c @@ -79,6 +79,7 @@ static void io_listen(void *pp) status = AcceptConnection("thread", "thread", 0, pp, sizeof(io_pipes_t), &id, &username); FREE_NOW(username); + while (STATUS_OK) status = DoMessage(id); close_pipe(((io_pipes_t *)pp)->in); diff --git a/mdstcpip/IoRoutinesTunnel.c b/mdstcpip/io_routines/IoRoutinesTunnel.c similarity index 100% rename from mdstcpip/IoRoutinesTunnel.c rename to mdstcpip/io_routines/IoRoutinesTunnel.c diff --git a/mdstcpip/IoRoutinesUdt.c b/mdstcpip/io_routines/IoRoutinesUdt.c similarity index 100% rename from mdstcpip/IoRoutinesUdt.c rename to mdstcpip/io_routines/IoRoutinesUdt.c diff --git a/mdstcpip/IoRoutinesUdtV6.c b/mdstcpip/io_routines/IoRoutinesUdtV6.c similarity index 100% rename from mdstcpip/IoRoutinesUdtV6.c rename to mdstcpip/io_routines/IoRoutinesUdtV6.c diff --git a/mdstcpip/ioroutines.h b/mdstcpip/io_routines/ioroutines.h similarity index 96% rename from mdstcpip/ioroutines.h rename to mdstcpip/io_routines/ioroutines.h index 5535470a09..3cd91943a9 100644 --- a/mdstcpip/ioroutines.h +++ b/mdstcpip/io_routines/ioroutines.h @@ -26,7 +26,7 @@ #include #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" static int GetHostAndPort(char *hostin, struct sockaddr_in *sin); diff --git a/mdstcpip/ioroutinesV6.h b/mdstcpip/io_routines/ioroutinesV6.h similarity index 97% rename from mdstcpip/ioroutinesV6.h rename to mdstcpip/io_routines/ioroutinesV6.h index 81cd829b31..ba107064a5 100644 --- a/mdstcpip/ioroutinesV6.h +++ b/mdstcpip/io_routines/ioroutinesV6.h @@ -25,7 +25,7 @@ #include #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include static int GetHostAndPort(char *hostin, struct sockaddr_in6 *sin); diff --git a/mdstcpip/ioroutines_pipes.h b/mdstcpip/io_routines/ioroutines_pipes.h similarity index 99% rename from mdstcpip/ioroutines_pipes.h rename to mdstcpip/io_routines/ioroutines_pipes.h index b0ae55a6f7..0c454a307b 100644 --- a/mdstcpip/ioroutines_pipes.h +++ b/mdstcpip/io_routines/ioroutines_pipes.h @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include #include diff --git a/mdstcpip/ioroutinestcp.h b/mdstcpip/io_routines/ioroutinestcp.h similarity index 93% rename from mdstcpip/ioroutinestcp.h rename to mdstcpip/io_routines/ioroutinestcp.h index d1a233661c..0722407a18 100644 --- a/mdstcpip/ioroutinestcp.h +++ b/mdstcpip/io_routines/ioroutinestcp.h @@ -351,10 +351,9 @@ static int io_listen(int argc, char **argv) SetPortname("mdsip"); INITIALIZESOCKETS; if (!GetMulti()) - return runServerMode(&options[1]); - ////////////////////////////////////////////////////////////////////////// - // MULTIPLE CONNECTION MODE ///////////////////////////////// - // multiple connections with own context ///////////////////////////////// + return run_server_mode(&options[1]); + /// MULTIPLE CONNECTION MODE /// + /// multiple connections with own context /// char *matchString[] = {"multi"}; if (CheckClient(0, 1, matchString) == ACCESS_DENIED) #ifdef _WIN32 @@ -435,28 +434,25 @@ static int io_listen(int argc, char **argv) FD_SET(sock, &fdactive); } } - else + // Process Clients in list searching for active sockets // + Client *c = ClientList; + while (c) { - // Process Clients in list searching for active sockets // - Client *c = ClientList; - while (c) + if (FD_ISSET(c->sock, &readfds)) { - if (FD_ISSET(c->sock, &readfds)) - { - // process active socket client // - MdsSetClientAddr(c->addr); - // DO MESSAGE ---> ProcessMessage() on client c // - DoMessage(c->id); - Client *c_chk; - for (c_chk = ClientList; c_chk && c_chk != c; c_chk = c_chk->next) - ; - if (c_chk) - FD_CLR(c->sock, &readfds); - c = ClientList; - } - else - c = c->next; + // process active socket client // + MdsSetClientAddr(c->addr); + // DO MESSAGE ---> ProcessMessage() on client c // + DoMessage(c->id); + Client *c_chk; + for (c_chk = ClientList; c_chk && c_chk != c; c_chk = c_chk->next) + ; + if (c_chk) + FD_CLR(c->sock, &readfds); + c = ClientList; } + else + c = c->next; } } else if (errno == EINTR) diff --git a/mdstcpip/ioroutinesudt.h b/mdstcpip/io_routines/ioroutinesudt.h similarity index 99% rename from mdstcpip/ioroutinesudt.h rename to mdstcpip/io_routines/ioroutinesudt.h index 1b85ed30c6..ed1b38e340 100644 --- a/mdstcpip/ioroutinesudt.h +++ b/mdstcpip/io_routines/ioroutinesudt.h @@ -227,6 +227,6 @@ static int io_listen(int argc, char **argv) } } else - runServerMode(&options[1]); + run_server_mode(&options[1]); return C_ERROR; } diff --git a/mdstcpip/ioroutinesx.h b/mdstcpip/io_routines/ioroutinesx.h similarity index 97% rename from mdstcpip/ioroutinesx.h rename to mdstcpip/io_routines/ioroutinesx.h index 6ecc69fefa..b09c89e200 100644 --- a/mdstcpip/ioroutinesx.h +++ b/mdstcpip/io_routines/ioroutinesx.h @@ -29,15 +29,16 @@ static IoRoutines io_routines = { [0], IP(a)[1], IP(a)[2], IP(a)[3] // Connected client definition for client list + typedef struct _client { + struct _client *next; SOCKET sock; int id; char *username; uint32_t addr; char *host; char *iphost; - struct _client *next; } Client; // List of clients connected to server instance. @@ -534,20 +535,15 @@ static int io_disconnect(Connection *con) return err; } -#ifdef _WIN32 -int runServerMode(Options *options) -{ -#else -int runServerMode(Options *options __attribute__((unused))) +static int run_server_mode(Options *options) { -#endif - ////////////////////////////////////////////////////////////////////////// - // SERVER MODE //////////////////////////// - // multiple connections with the same context //////////////////////////// + /// SERVER MODE /////////////// + /// Handle single connection /// #ifdef _WIN32 SOCKET sock = getSocketHandle(options->value); #else SOCKET sock = 0; + (void)options; #endif int id; char *username; @@ -567,7 +563,10 @@ int runServerMode(Options *options __attribute__((unused))) #ifdef _TCP FD_SET(sock, &fdactive); #endif - while (DoMessage(id)) - ; + int status; + do + { + status = DoMessage(id); + } while (STATUS_OK); return C_ERROR; } diff --git a/mdstcpip/mdsip_connections.h b/mdstcpip/mdsip_connections.h index d75844c1ec..4c0ef38afe 100644 --- a/mdstcpip/mdsip_connections.h +++ b/mdstcpip/mdsip_connections.h @@ -65,8 +65,8 @@ typedef uint8_t con_t; typedef struct _connection { - int id; // unique connection id struct _connection *next; + int id; // unique connection id pthread_cond_t cond; con_t state; char *protocol; @@ -77,8 +77,7 @@ typedef struct _connection unsigned char message_id; int client_type; int nargs; - struct descriptor - *descrip[MDSIP_MAX_ARGS]; // list of descriptors for the message arguments + struct descriptor *descrip[MDSIP_MAX_ARGS]; // list for message arguments MdsEventList *event; void *tdicontext[6]; int addr; @@ -257,6 +256,7 @@ EXPORT char ClientType(void); /// the server "MdsIpSrvShr" library. /// EXPORT int CloseConnection(int conid); +int CloseConnectionC(Connection *connection); // internal use //////////////////////////////////////////////////////////////////////////////// /// @@ -455,8 +455,6 @@ EXPORT Message *GetMdsMsgTO(int id, int *status, int timeout); EXPORT Message *GetMdsMsgOOB(int id, int *status); Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec); -EXPORT unsigned char GetMode(); - //////////////////////////////////////////////////////////////////////////////// /// /// Get multi mode active in this scope. Mutiple connection mode (accepts @@ -468,12 +466,8 @@ EXPORT char *GetPortname(); EXPORT char *GetProtocol(); -EXPORT int GetService(); - EXPORT SOCKET GetSocketHandle(); -EXPORT int GetWorker(); - //////////////////////////////////////////////////////////////////////////////// /// /// Finds the Connection intance held in the list of connections by id and @@ -625,8 +619,6 @@ EXPORT void ParseCommand(int argc, char **argv, Options options[], int more, EXPORT void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv); -EXPORT void PrintHelp(char *); - EXPORT int ReuseCheck(char *hostin, char *unique, size_t buflen); //////////////////////////////////////////////////////////////////////////////// @@ -716,20 +708,14 @@ EXPORT int SetMaxCompressionLevel(int setting); EXPORT int SetMdsConnectTimeout(int sec); -EXPORT unsigned char SetMode(unsigned char newmode); - EXPORT unsigned char SetMulti(unsigned char setting); EXPORT char *SetPortname(char *); EXPORT char *SetProtocol(char *); -EXPORT int SetService(int setting); - EXPORT SOCKET SetSocketHandle(SOCKET handle); -EXPORT int SetWorker(int setting); - EXPORT void UnlockAsts(); //////////////////////////////////////////////////////////////////////////////// @@ -789,9 +775,4 @@ EXPORT int MdsGetClientAddr(); EXPORT void MdsSetClientAddr(int); EXPORT char *MdsGetServerPortname(); -/* MdsIpSrvShr routines */ - -EXPORT Message *ProcessMessage(Connection *connection, Message *message); -EXPORT int RemoveConnection(int id); - #endif diff --git a/mdstcpip/ArgLen.c b/mdstcpip/mdsipshr/ArgLen.c similarity index 98% rename from mdstcpip/ArgLen.c rename to mdstcpip/mdsipshr/ArgLen.c index a8baf8cf1a..aa29a46180 100644 --- a/mdstcpip/ArgLen.c +++ b/mdstcpip/mdsipshr/ArgLen.c @@ -24,7 +24,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" short ArgLen(struct descrip *d) { diff --git a/mdstcpip/CheckClient.c b/mdstcpip/mdsipshr/CheckClient.c similarity index 99% rename from mdstcpip/CheckClient.c rename to mdstcpip/mdsipshr/CheckClient.c index fbefb82570..7e77af53ba 100644 --- a/mdstcpip/CheckClient.c +++ b/mdstcpip/mdsipshr/CheckClient.c @@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" extern int TdiExecute(); diff --git a/mdstcpip/ClientType.c b/mdstcpip/mdsipshr/ClientType.c similarity index 98% rename from mdstcpip/ClientType.c rename to mdstcpip/mdsipshr/ClientType.c index 5b324e1327..588b120445 100644 --- a/mdstcpip/ClientType.c +++ b/mdstcpip/mdsipshr/ClientType.c @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include /// diff --git a/mdstcpip/RemoveConnection.c b/mdstcpip/mdsipshr/CloseConnection.c similarity index 78% rename from mdstcpip/RemoveConnection.c rename to mdstcpip/mdsipshr/CloseConnection.c index 787ac9597e..07b5668f87 100644 --- a/mdstcpip/RemoveConnection.c +++ b/mdstcpip/mdsipshr/CloseConnection.c @@ -22,31 +22,26 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include -#include "mdsip_connections.h" -#include +#include "../mdsip_connections.h" +extern int _TreeClose(); extern int TdiSaveContext(); extern int TdiDeleteContext(); extern int TdiRestoreContext(); extern int MDSEventCan(); -/// -/// \brief RemoveConnection -/// \param conid -/// \return -/// -int RemoveConnection(int conid) +int CloseConnectionC(Connection *connection) { int status = 0; - Connection *c = FindConnection(conid, 0); - if (c) + if (connection) { void *tdi_context[6]; MdsEventList *e, *nexte; - FreeDescriptors(c); - for (e = c->event; e; e = nexte) + FreeDescriptors(connection); + for (e = connection->event; e; e = nexte) { nexte = e->next; /**/ MDSEventCan(e->eventid); @@ -56,12 +51,18 @@ int RemoveConnection(int conid) } do { - status = _TreeClose(&c->DBID, 0, 0); + status = _TreeClose(&connection->DBID, 0, 0); } while (STATUS_OK); TdiSaveContext(tdi_context); - TdiDeleteContext(c->tdicontext); + TdiDeleteContext(connection->tdicontext); TdiRestoreContext(tdi_context); - status = DisconnectConnection(conid); + status = DisconnectConnection(connection->id); } return status; } + +int CloseConnection(int id) +{ + Connection *connection = FindConnection(id, NULL); + return CloseConnectionC(connection); +} diff --git a/mdstcpip/ConnectToMds.c b/mdstcpip/mdsipshr/ConnectToMds.c similarity index 97% rename from mdstcpip/ConnectToMds.c rename to mdstcpip/mdsipshr/ConnectToMds.c index 6ba082ec86..584f7a9231 100644 --- a/mdstcpip/ConnectToMds.c +++ b/mdstcpip/mdsipshr/ConnectToMds.c @@ -30,8 +30,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" -#include "mdsIo.h" +#include "../mdsip_connections.h" +#include "../mdsIo.h" //////////////////////////////////////////////////////////////////////////////// // Parse Host //////////////////////////////////////////////////////////////// @@ -189,3 +189,13 @@ int ConnectToMds(char *hostin) free(protocol); return id; } + +int DisconnectFromMds(int id) +{ + return DisconnectConnection(id); +} + +void FreeMessage(void *m) +{ + free(m); +} \ No newline at end of file diff --git a/mdstcpip/Connections.c b/mdstcpip/mdsipshr/Connections.c similarity index 97% rename from mdstcpip/Connections.c rename to mdstcpip/mdsipshr/Connections.c index d883eab3e4..a4de0e7bc6 100644 --- a/mdstcpip/Connections.c +++ b/mdstcpip/mdsipshr/Connections.c @@ -27,8 +27,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" -#include "mdsIo.h" +#include "../mdsip_connections.h" +#include "../mdsIo.h" #include #include @@ -521,7 +521,7 @@ int GetConnectionClientType(int conid) } //////////////////////////////////////////////////////////////////////////////// -// AuthorizeClient /////////////////////////////////////////////////////////// +// authorize_client /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// Authorize client by username calling protocol IoRoutine. @@ -529,10 +529,9 @@ int GetConnectionClientType(int conid) /// \param username of the user to be authorized for access /// \return true if authorized user found, false otherwise -static inline int authorizeClient(Connection *c, char *username) +static inline int authorize_client(Connection *c, char *username) { - if (c && c->io) - return c->io->authorize ? c->io->authorize(c, username) : MDSplusSUCCESS; + return c->io->authorize ? c->io->authorize(c, username) : MDSplusSUCCESS; return MDSplusERROR; } @@ -541,12 +540,11 @@ static inline int authorizeClient(Connection *c, char *username) //////////////////////////////////////////////////////////////////////////////// int AddConnection(Connection *c) { - static int id = 1; + static int id = 0; CONNECTIONLIST_LOCK; - if (id == INVALID_CONNECTION_ID) - while (_FindConnection(++id, 0)) - ; // find next free id - c->id = id++; + while (++id == INVALID_CONNECTION_ID && _FindConnection(++id, 0)) + ; // find next free id + c->id = id; c->next = ConnectionList; ConnectionList = c; CONNECTIONLIST_UNLOCK; @@ -583,7 +581,7 @@ int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, } c->rm_user = user; user_p = user ? user : "?"; - status = authorizeClient(c, user_p); + status = authorize_client(c, user_p); // SET COMPRESSION // if (STATUS_OK) { diff --git a/mdstcpip/DoMessage.c b/mdstcpip/mdsipshr/DoMessage.c similarity index 74% rename from mdstcpip/DoMessage.c rename to mdstcpip/mdsipshr/DoMessage.c index 8178d46a56..bc5086c33e 100644 --- a/mdstcpip/DoMessage.c +++ b/mdstcpip/mdsipshr/DoMessage.c @@ -26,36 +26,34 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" +extern void ProcessMessage(Connection *, Message *); //////////////////////////////////////////////////////////////////////////////// // DoMessage ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - -int DoMessage(int id) +int DoMessageC(Connection *connection) { - Connection *c = FindConnection(id, 0); - static Message *(*processMessage)(Connection *, Message *) = NULL; - int status = - LibFindImageSymbol_C("MdsIpSrvShr", "ProcessMessage", &processMessage); - if (STATUS_NOT_OK || !c) - return 0; // will cause tunnel to terminate - Message *msgptr = GetMdsMsg(id, &status); - Message *ans = 0; + int status = MDSplusFATAL; + if (!connection) + return status; // will cause tunnel to terminate + Message *message = GetMdsMsgTOC(connection, &status, -1); + if (STATUS_OK && !message) + status = MDSplusFATAL; if (STATUS_OK) { - ans = processMessage(c, msgptr); - if (ans) - { - status = SendMdsMsg(id, ans, 0); - free(ans); - } + ProcessMessage(connection, message); } else { - CloseConnection(id); - status = 0; // will cause tunnel to terminate + free(message); + CloseConnectionC(connection); } - free(msgptr); return status; } + +int DoMessage(int id) +{ + Connection *connection = FindConnection(id, NULL); + return DoMessageC(connection); +} diff --git a/mdstcpip/FlipData.c b/mdstcpip/mdsipshr/FlipData.c similarity index 98% rename from mdstcpip/FlipData.c rename to mdstcpip/mdsipshr/FlipData.c index 4415bf158e..b26487b4ac 100644 --- a/mdstcpip/FlipData.c +++ b/mdstcpip/mdsipshr/FlipData.c @@ -26,7 +26,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #include #endif -#include "mdsip_connections.h" +#include "../mdsip_connections.h" void FlipData(Message *m) { diff --git a/mdstcpip/FlipHeader.c b/mdstcpip/mdsipshr/FlipHeader.c similarity index 98% rename from mdstcpip/FlipHeader.c rename to mdstcpip/mdsipshr/FlipHeader.c index 73f9c6a852..25e3541e44 100644 --- a/mdstcpip/FlipHeader.c +++ b/mdstcpip/mdsipshr/FlipHeader.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" void FlipHeader(MsgHdr *header) { diff --git a/mdstcpip/GetAnswerInfo.c b/mdstcpip/mdsipshr/GetAnswerInfo.c similarity index 99% rename from mdstcpip/GetAnswerInfo.c rename to mdstcpip/mdsipshr/GetAnswerInfo.c index 223ca551d3..4242817cc5 100644 --- a/mdstcpip/GetAnswerInfo.c +++ b/mdstcpip/mdsipshr/GetAnswerInfo.c @@ -25,7 +25,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef DEBUG #include #endif -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/GetMdsMsg.c b/mdstcpip/mdsipshr/GetMdsMsg.c similarity index 94% rename from mdstcpip/GetMdsMsg.c rename to mdstcpip/mdsipshr/GetMdsMsg.c index 3438892891..11e81dbbf7 100644 --- a/mdstcpip/GetMdsMsg.c +++ b/mdstcpip/mdsipshr/GetMdsMsg.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" -#include "zlib/zlib.h" +#include "../mdsip_connections.h" +#include "../zlib/zlib.h" #include #include #include @@ -32,8 +32,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -static int GetBytesTO(Connection *c, void *buffer, size_t bytes_to_recv, - int to_msec) + +static int get_bytes_to(Connection *c, void *buffer, size_t bytes_to_recv, + int to_msec) { char *bptr = (char *)buffer; if (c && c->io) @@ -81,8 +82,7 @@ Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) { MsgHdr header; Message *msg = NULL; - // MdsSetClientAddr(0); - *status = GetBytesTO(c, (void *)&header, sizeof(MsgHdr), to_msec); + *status = get_bytes_to(c, (void *)&header, sizeof(MsgHdr), to_msec); if (*status == SsINTERNAL) return NULL; if (IS_OK(*status)) @@ -111,7 +111,7 @@ Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) unsigned long dlen; msg = malloc(msglen); msg->h = header; - *status = GetBytesTO(c, msg->bytes, msglen - sizeof(MsgHdr), 1000); + *status = get_bytes_to(c, msg->bytes, msglen - sizeof(MsgHdr), 1000); if (IS_OK(*status) && IsCompressed(header.client_type)) { Message *m; diff --git a/mdstcpip/GetSetSettings.c b/mdstcpip/mdsipshr/GetSetSettings.c similarity index 99% rename from mdstcpip/GetSetSettings.c rename to mdstcpip/mdsipshr/GetSetSettings.c index 6b3f3fae36..5bee89bd67 100644 --- a/mdstcpip/GetSetSettings.c +++ b/mdstcpip/mdsipshr/GetSetSettings.c @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include @@ -199,7 +199,6 @@ int SetMdsConnectTimeout(int sec) //////////////////////////////////////////////////////////////////////////////// // CLIENT ADDRESS //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - static int ClientAddr = 0; int MdsGetClientAddr() { return ClientAddr; } diff --git a/mdstcpip/IdlApi.c b/mdstcpip/mdsipshr/IdlApi.c similarity index 100% rename from mdstcpip/IdlApi.c rename to mdstcpip/mdsipshr/IdlApi.c diff --git a/mdstcpip/LoadIo.c b/mdstcpip/mdsipshr/LoadIo.c similarity index 98% rename from mdstcpip/LoadIo.c rename to mdstcpip/mdsipshr/LoadIo.c index 10353c6e8a..2a712737ab 100644 --- a/mdstcpip/LoadIo.c +++ b/mdstcpip/mdsipshr/LoadIo.c @@ -30,7 +30,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "../mdsshr/version.h" -#include "mdsip_connections.h" +#include "../mdsip_connections.h" //////////////////////////////////////////////////////////////////////////////// // LoadIo //////////////////////////////////////////////////////////////////// diff --git a/mdstcpip/LockAsts.c b/mdstcpip/mdsipshr/LockAsts.c similarity index 98% rename from mdstcpip/LockAsts.c rename to mdstcpip/mdsipshr/LockAsts.c index 30a594abc2..a3dd095226 100644 --- a/mdstcpip/LockAsts.c +++ b/mdstcpip/mdsipshr/LockAsts.c @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/MakeDescrip.c b/mdstcpip/mdsipshr/MakeDescrip.c similarity index 98% rename from mdstcpip/MakeDescrip.c rename to mdstcpip/mdsipshr/MakeDescrip.c index b87bf64e12..58c4b2532a 100644 --- a/mdstcpip/MakeDescrip.c +++ b/mdstcpip/mdsipshr/MakeDescrip.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" //////////////////////////////////////////////////////////////////////////////// // MakeDescripWithLength ///////////////////////////////////////////////////// diff --git a/mdstcpip/MdsClose.c b/mdstcpip/mdsipshr/MdsClose.c similarity index 98% rename from mdstcpip/MdsClose.c rename to mdstcpip/mdsipshr/MdsClose.c index 1027c6757b..c6a932a374 100644 --- a/mdstcpip/MdsClose.c +++ b/mdstcpip/mdsipshr/MdsClose.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/MdsDispatchEvent.c b/mdstcpip/mdsipshr/MdsDispatchEvent.c similarity index 98% rename from mdstcpip/MdsDispatchEvent.c rename to mdstcpip/mdsipshr/MdsDispatchEvent.c index 66e7833469..849e247e13 100644 --- a/mdstcpip/MdsDispatchEvent.c +++ b/mdstcpip/mdsipshr/MdsDispatchEvent.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/MdsEventAst.c b/mdstcpip/mdsipshr/MdsEventAst.c similarity index 98% rename from mdstcpip/MdsEventAst.c rename to mdstcpip/mdsipshr/MdsEventAst.c index 234dfa346f..2b56c29e99 100644 --- a/mdstcpip/MdsEventAst.c +++ b/mdstcpip/mdsipshr/MdsEventAst.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include //////////////////////////////////////////////////////////////////////////////// diff --git a/mdstcpip/MdsEventCan.c b/mdstcpip/mdsipshr/MdsEventCan.c similarity index 98% rename from mdstcpip/MdsEventCan.c rename to mdstcpip/mdsipshr/MdsEventCan.c index 774342f948..8b46ac2f51 100644 --- a/mdstcpip/MdsEventCan.c +++ b/mdstcpip/mdsipshr/MdsEventCan.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include //////////////////////////////////////////////////////////////////////////////// diff --git a/mdstcpip/MdsOpen.c b/mdstcpip/mdsipshr/MdsOpen.c similarity index 98% rename from mdstcpip/MdsOpen.c rename to mdstcpip/mdsipshr/MdsOpen.c index 8744d90977..e72502922a 100644 --- a/mdstcpip/MdsOpen.c +++ b/mdstcpip/mdsipshr/MdsOpen.c @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include #include diff --git a/mdstcpip/MdsPut.c b/mdstcpip/mdsipshr/MdsPut.c similarity index 98% rename from mdstcpip/MdsPut.c rename to mdstcpip/mdsipshr/MdsPut.c index ee5bd6962a..2a0463f89a 100644 --- a/mdstcpip/MdsPut.c +++ b/mdstcpip/mdsipshr/MdsPut.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include #include diff --git a/mdstcpip/MdsSetCompression.c b/mdstcpip/mdsipshr/MdsSetCompression.c similarity index 98% rename from mdstcpip/MdsSetCompression.c rename to mdstcpip/mdsipshr/MdsSetCompression.c index e5155369fa..b954c32de2 100644 --- a/mdstcpip/MdsSetCompression.c +++ b/mdstcpip/mdsipshr/MdsSetCompression.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/MdsSetDefault.c b/mdstcpip/mdsipshr/MdsSetDefault.c similarity index 98% rename from mdstcpip/MdsSetDefault.c rename to mdstcpip/mdsipshr/MdsSetDefault.c index 8d91f71c2f..40d99f6f31 100644 --- a/mdstcpip/MdsSetDefault.c +++ b/mdstcpip/mdsipshr/MdsSetDefault.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" +#include "../mdsip_connections.h" #include #include diff --git a/mdstcpip/MdsValue.c b/mdstcpip/mdsipshr/MdsValue.c similarity index 99% rename from mdstcpip/MdsValue.c rename to mdstcpip/mdsipshr/MdsValue.c index 07ff5a4953..d3d3adbb00 100644 --- a/mdstcpip/MdsValue.c +++ b/mdstcpip/mdsipshr/MdsValue.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" -#include "mdsIo.h" +#include "../mdsip_connections.h" +#include "../mdsIo.h" #include #include #include diff --git a/mdstcpip/ParseCommand.c b/mdstcpip/mdsipshr/ParseCommand.c similarity index 97% rename from mdstcpip/ParseCommand.c rename to mdstcpip/mdsipshr/ParseCommand.c index c169438825..9d5650871e 100644 --- a/mdstcpip/ParseCommand.c +++ b/mdstcpip/mdsipshr/ParseCommand.c @@ -31,9 +31,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "mdsip_connections.h" +#include "../mdsip_connections.h" -void PrintHelp(char *option) +static void print_help(char *option) { if (option) printf("Invalid options specified: %s\n\n", option); @@ -103,7 +103,7 @@ void ParseCommand(int argc, char **argv, Options options[], int more, arglen--; } if (strcmp("help", arg) == 0) - PrintHelp(0); + print_help(0); for (opt = 0; options[opt].short_name || options[opt].long_name; opt++) { if (islong) @@ -171,7 +171,7 @@ void ParseCommand(int argc, char **argv, Options options[], int more, if (!option_found) { if (!more) - PrintHelp(argv[i]); + print_help(argv[i]); else { extra_argv[extra_argc] = argv[i]; @@ -219,7 +219,8 @@ void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv) fprintf( stderr, "Invalid option: Cannot select both server mode and multi mode\n\n"); - PrintHelp(0); + + print_help(0); } else { @@ -248,5 +249,5 @@ void ParseStdArgs(int argc, char **argv, int *extra_argc, char ***extra_argv) SetCompressionLevel(cmpr); } if (options[5].present) - PrintHelp(0); + print_help(0); } diff --git a/mdstcpip/mdsipshr/ProcessMessage.c b/mdstcpip/mdsipshr/ProcessMessage.c new file mode 100644 index 0000000000..2b553f768b --- /dev/null +++ b/mdstcpip/mdsipshr/ProcessMessage.c @@ -0,0 +1,1212 @@ +/* +Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include + +#if defined(linux) && !defined(_LARGEFILE_SOURCE) +#define _LARGEFILE_SOURCE +#define _FILE_OFFSET_BITS 64 +#define __USE_FILE_OFFSET64 +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#ifdef HAVE_UNISTD_H +#include +#endif +#endif + +#include +#include +#include +#include +#include +#include + +#include "../tdishr/tdithreadstatic.h" +#include "../treeshr/treeshrp.h" +#include "cvtdef.h" +#include "../mdsIo.h" +#include "../mdsip_connections.h" + +extern int TdiRestoreContext(void **); +extern int TdiSaveContext(void **); + +static void convert_binary(int num, int sign_extend, short in_length, + char *in_ptr, short out_length, char *out_ptr) +{ + int i; + int j; + signed char *in_p = (signed char *)in_ptr; + signed char *out_p = (signed char *)out_ptr; + short min_len = out_length < in_length ? out_length : in_length; + for (i = 0; i < num; i++, in_p += in_length, out_p += out_length) + { + for (j = 0; j < min_len; j++) + out_p[j] = in_p[j]; + for (; j < out_length; j++) + out_p[j] = sign_extend ? (in_p[min_len - 1] < 0 ? -1 : 0) : 0; + } +} + +static void convert_float(int num, int in_type, char in_length, char *in_ptr, + int out_type, char out_length, char *out_ptr) +{ + int i; + char *in_p; + char *out_p; + for (i = 0, in_p = in_ptr, out_p = out_ptr; i < num; + i++, in_p += in_length, out_p += out_length) + { + char *ptr = in_p; + char cray_f[8]; + if (in_type == CvtCRAY) + { + int j, k; + for (j = 0; j < 2; j++) + for (k = 0; k < 4; k++) +#ifdef WORDS_BIGENDIAN + cray_f[j * 4 + k] = ptr[j * 4 + 3 - k]; +#else + cray_f[(1 - j) * 4 + k] = ptr[j * 4 + 3 - k]; +#endif + ptr = cray_f; + } + CvtConvertFloat(ptr, in_type, out_p, out_type, 0); +#ifdef WORDS_BIGENDIAN + if (out_type == CvtCRAY) + { + int j, k; + ptr = out_p; + for (j = 0; j < 2; j++) + for (k = 0; k < 4; k++) + cray_f[j * 4 + k] = ptr[j * 4 + 3 - k]; + for (j = 0; j < 8; j++) + ptr[j] = cray_f[j]; + } +#endif + } +} + +static void send_response(Connection *connection, Message *message, + int status, mdsdsc_t *d) +{ + const int client_type = connection->client_type; + const unsigned char message_id = connection->message_id; + Message *m = NULL; + int nbytes = (d->class == CLASS_S) ? d->length : ((array_coeff *)d)->arsize; + int num = nbytes / ((d->length < 1) ? 1 : d->length); + short length = d->length; + if (CType(client_type) == CRAY_CLIENT) + { + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + case DTYPE_SHORT: + case DTYPE_LONG: + case DTYPE_F: + case DTYPE_FS: + length = 8; + break; + case DTYPE_FC: + case DTYPE_FSC: + case DTYPE_D: + case DTYPE_G: + case DTYPE_FT: + length = 16; + break; + default: + length = d->length; + break; + } + nbytes = num * length; + } + else if (CType(client_type) == CRAY_IEEE_CLIENT) + { + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_SHORT: + length = 4; + break; + case DTYPE_ULONG: + case DTYPE_LONG: + length = 8; + break; + default: + length = d->length; + break; + } + nbytes = num * length; + } + m = malloc(sizeof(MsgHdr) + nbytes); + memset(&m->h, 0, sizeof(MsgHdr)); + m->h.msglen = sizeof(MsgHdr) + nbytes; + m->h.client_type = client_type; + m->h.message_id = message_id; + m->h.status = status; + m->h.dtype = d->dtype; + m->h.length = length; + if (d->class == CLASS_S) + m->h.ndims = 0; + else + { + int i; + array_coeff *a = (array_coeff *)d; + m->h.ndims = a->dimct; + if (a->aflags.coeff) + for (i = 0; i < m->h.ndims && i < MAX_DIMS; i++) + m->h.dims[i] = a->m[i]; + else + m->h.dims[0] = a->length ? a->arsize / a->length : 0; + for (i = m->h.ndims; i < MAX_DIMS; i++) + m->h.dims[i] = 0; + } + switch (CType(client_type)) + { + case IEEE_CLIENT: + case JAVA_CLIENT: + switch (d->dtype) + { + case DTYPE_F: + convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, + CvtIEEE_S, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FS: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, + CvtIEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, + CvtIEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FT: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } + break; + case CRAY_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, + m->bytes); + break; + case DTYPE_F: + convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtCRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FS: + convert_float(num, CvtIEEE_S, (char)d->length, d->pointer, CvtCRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FC: + convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, + CvtCRAY, (char)(m->h.length / 2), m->bytes); + break; + case DTYPE_FSC: + convert_float(num * 2, CvtIEEE_S, (char)(d->length / 2), d->pointer, + CvtCRAY, (char)(m->h.length / 2), m->bytes); + break; + case DTYPE_D: + convert_float(num, CvtVAX_D, sizeof(double), d->pointer, CvtCRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_G: + convert_float(num, CvtVAX_G, sizeof(double), d->pointer, CvtCRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FT: + convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtCRAY, + (char)m->h.length, m->bytes); + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } + break; + case CRAY_IEEE_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, + m->bytes); + break; + case DTYPE_F: + convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, + CvtIEEE_S, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FS: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, + CvtIEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, + CvtIEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FT: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } + break; + case VMSG_CLIENT: + switch (d->dtype) + { + case DTYPE_F: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, CvtVAX_D, sizeof(double), d->pointer, CvtVAX_G, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, + CvtVAX_G, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FS: + convert_float(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + convert_float(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FT: + convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + convert_float(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } + break; + default: + switch (d->dtype) + { + case DTYPE_F: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FS: + convert_float(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + convert_float(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FT: + convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + convert_float(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } + break; + } + status = SendMdsMsgC(connection, m, 0); + free(m); + free(message); + if (STATUS_NOT_OK) + DisconnectConnection(connection->id); +} + +static void GetErrorText(int status, mdsdsc_xd_t *xd) +{ + static DESCRIPTOR(unknown, "unknown error occured"); + struct descriptor message = {0, DTYPE_T, CLASS_S, 0}; + if ((message.pointer = MdsGetMsg(status)) != NULL) + { + message.length = strlen(message.pointer); + MdsCopyDxXd(&message, xd); + } + else + MdsCopyDxXd((mdsdsc_t *)&unknown, xd); +} + +static void client_event_ast(MdsEventList *e, int data_len, char *data) +{ + Connection *c = FindConnection(e->conid, 0); + int i; + char client_type; + Message *m; + JMdsEventInfo *info; + int len; + // Check Connection: if down, cancel the event and return + if (!c) + { + MDSEventCan(e->eventid); + return; + } + client_type = c->client_type; + LockAsts(); + if (CType(client_type) == JAVA_CLIENT) + { + len = sizeof(MsgHdr) + sizeof(JMdsEventInfo); + m = memset(malloc(len), 0, len); + m->h.ndims = 0; + m->h.client_type = client_type; + m->h.msglen = len; + m->h.dtype = DTYPE_EVENT_NOTIFY; + info = (JMdsEventInfo *)m->bytes; + if (data_len > 0) + memcpy(info->data, data, (data_len < 12) ? data_len : 12); + for (i = data_len; i < 12; i++) + info->data[i] = 0; + info->eventid = e->jeventid; + } + else + { + m = memset(malloc(sizeof(MsgHdr) + e->info_len), 0, + sizeof(MsgHdr) + e->info_len); + m->h.ndims = 0; + m->h.client_type = client_type; + m->h.msglen = sizeof(MsgHdr) + e->info_len; + m->h.dtype = DTYPE_EVENT_NOTIFY; + if (data_len > 0) + memcpy(e->info->data, data, (data_len < 12) ? data_len : 12); + for (i = data_len; i < 12; i++) + e->info->data[i] = 0; + memcpy(m->bytes, e->info, e->info_len); + } + SendMdsMsg(e->conid, m, MSG_DONTWAIT); + free(m); + UnlockAsts(); +} + +typedef struct +{ + void *tdicontext[6]; + Connection *connection; + mdsdsc_xd_t *xdp; + int cs; +} cleanup_command_t; + +static void cleanup_command(void *args) +{ + cleanup_command_t *p = (cleanup_command_t *)args; + MdsFree1Dx(p->xdp, NULL); + if (p->cs) + { + TdiSaveContext(p->connection->tdicontext); + TdiRestoreContext(p->tdicontext); + } +} + +static inline int execute_command(Connection *connection, mdsdsc_xd_t *ans_xd) +{ + int status; + cleanup_command_t p; + p.cs = !!GetContextSwitching(); + if (p.cs) + { + TdiSaveContext(p.tdicontext); + TdiRestoreContext(connection->tdicontext); + } + p.connection = connection; + EMPTYXD(xd); + p.xdp = &xd; + pthread_cleanup_push(cleanup_command, (void *)&p); + TDITHREADSTATIC_INIT; + --TDI_INTRINSIC_REC; + status = TdiIntrinsic(OPC_EXECUTE, connection->nargs, connection->descrip, &xd); + ++TDI_INTRINSIC_REC; + if (STATUS_OK) + status = TdiData(xd.pointer, ans_xd MDS_END_ARG); + pthread_cleanup_pop(1); + return status; +} + +/// +/// Executes TDI expression held by a connecion instance. This first searches if +/// connection message corresponds to AST or CAN requests, if no asyncronous ops +/// are requested the TDI actual expression is parsed through tdishr library. +/// In this case the current TDI context and tree is switched to the connection +/// ones stored in the connection context field. +/// +/// ### AST and CAN +/// AST and CAN stands for "Asynchronous System Trap" and "CANcel event +/// request". This is an asyncronous message mechanism taken from the OpenVMS +/// system. The event handler is passed inside the message arguments and +/// executed by the MDSEventAst() function from mdslib. +/// +/// \param connection the Connection instance filled with proper descriptor +/// arguments \return the execute message answer built using BuildAnswer() +/// + +static void execute_message(Connection *connection, Message *message) +{ + int status = 1; // return status // + + char *evname; + DESCRIPTOR(eventastreq, EVENTASTREQUEST); // AST request descriptor // + DESCRIPTOR(eventcanreq, EVENTCANREQUEST); // Can request descriptor // + const int java = CType(connection->client_type) == JAVA_CLIENT; + + if (StrCompare(connection->descrip[0], (mdsdsc_t *)&eventastreq) == 0) + { // AST REQUEST // + int eventid = -1; + DESCRIPTOR_LONG(eventiddsc, &eventid); + MdsEventList *newe = (MdsEventList *)malloc(sizeof(MdsEventList)); + struct descriptor_a *info = (struct descriptor_a *)connection->descrip[2]; + newe->conid = connection->id; + + evname = malloc(connection->descrip[1]->length + 1); + memcpy(evname, connection->descrip[1]->pointer, + connection->descrip[1]->length); + evname[connection->descrip[1]->length] = 0; + // Manage AST Event // + status = MDSEventAst(evname, (void (*)(void *, int, char *))client_event_ast, + newe, &newe->eventid); + free(evname); + if (java) + { + newe->info = 0; + newe->info_len = 0; + newe->jeventid = *connection->descrip[2]->pointer; + } + else + { + newe->info = (MdsEventInfo *)memcpy(malloc(info->arsize), info->pointer, + info->arsize); + newe->info_len = info->arsize; + newe->info->eventid = newe->eventid; + } + newe->next = 0; + if (STATUS_NOT_OK) + { + eventiddsc.pointer = (void *)&eventid; + free(newe->info); + free(newe); + } + else + { + MdsEventList *e; + eventiddsc.pointer = (void *)&newe->eventid; + if (connection->event) + { + for (e = connection->event; e->next; e = e->next) + ; + e->next = newe; + } + else + connection->event = newe; + } + if (!java) + send_response(connection, message, status, &eventiddsc); + else + free(message); + } + else if (StrCompare(connection->descrip[0], (mdsdsc_t *)&eventcanreq) == 0) + { // CAN REQUEST // + int eventid; + DESCRIPTOR_LONG(eventiddsc, &eventid); + MdsEventList *e; + MdsEventList **p; + if (!java) + eventid = *(int *)connection->descrip[1]->pointer; + else + eventid = (int)*connection->descrip[1]->pointer; + if (connection->event) + { + for (p = &connection->event, e = connection->event; + e && (e->eventid != eventid); p = &e->next, e = e->next) + ; + if (e) + { + /**/ MDSEventCan(e->eventid); + /**/ *p = e->next; + free(e); + } + } + if (!java) + send_response(connection, message, status, &eventiddsc); + else + free(message); + } + else // NORMAL TDI COMMAND // + { + INIT_AND_FREEXD_ON_EXIT(ans_xd); + status = execute_command(connection, &ans_xd); + if (STATUS_NOT_OK) + GetErrorText(status, &ans_xd); + if (GetCompressionLevel() != connection->compression_level) + { + connection->compression_level = GetCompressionLevel(); + if (connection->compression_level > GetMaxCompressionLevel()) + connection->compression_level = GetMaxCompressionLevel(); + SetCompressionLevel(connection->compression_level); + } + + send_response(connection, message, status, ans_xd.pointer); + FREEXD_NOW(ans_xd); + } + FreeDescriptors(connection); +} + +static void standard_command(Connection *connection, Message *message) +{ + // set connection to the message client_type // + connection->client_type = message->h.client_type; +#define COPY_DESC(name, GENERATOR, ...) \ + do \ + { \ + const GENERATOR(__VA_ARGS__); \ + *(void **)&d = memcpy(malloc(sizeof(tmp)), &tmp, sizeof(tmp)); \ + } while (0) + // d -> reference to curent idx argument desctriptor // + + mdsdsc_t *d = connection->descrip[message->h.descriptor_idx]; + if (message->h.dtype == DTYPE_SERIAL) + { + if (d && d->class != CLASS_XD) + { + if (d->class == CLASS_D && d->pointer) + free(d->pointer); + free(d); + } + COPY_DESC(d, EMPTYXD, tmp); + connection->descrip[message->h.descriptor_idx] = d; + free(message); + return; + } + if (!d) + { + // instance the connection descriptor field // + const short lengths[] = {0, 0, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 8, 16, 0}; + if (message->h.ndims == 0) + { + d = calloc(1, sizeof(struct descriptor_s)); + d->class = CLASS_S; + } + else + COPY_DESC(d, DESCRIPTOR_A_COEFF, tmp, 0, 0, 0, MAX_DIMS, 0); + d->length = message->h.dtype < DTYPE_CSTRING ? lengths[message->h.dtype] + : message->h.length; + d->dtype = message->h.dtype; + if (d->class == CLASS_A) + { + array_coeff *a = (array_coeff *)d; + int num = 1; + int i; + a->dimct = message->h.ndims; + for (i = 0; i < a->dimct; i++) + { + a->m[i] = message->h.dims[i]; + num *= a->m[i]; + } + a->arsize = a->length * num; + a->pointer = a->a0 = malloc(a->arsize); + } + else + d->pointer = d->length ? malloc(d->length) : 0; + // set new instance // + connection->descrip[message->h.descriptor_idx] = d; + } + if (d) + { + // have valid connection descriptor instance // + // copy the message buffer into the descriptor // + + int dbytes = d->class == CLASS_S ? (int)d->length + : (int)((array_coeff *)d)->arsize; + int num = d->length > 1 ? (dbytes / d->length) : dbytes; + + switch (CType(connection->client_type)) + { + case IEEE_CLIENT: + case JAVA_CLIENT: + memcpy(d->pointer, message->bytes, dbytes); + break; + case CRAY_IEEE_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, message->h.length, message->bytes, d->length, + d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } + break; + case CRAY_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_FLOAT: + convert_float(num, CvtCRAY, (char)message->h.length, message->bytes, + CvtIEEE_S, (char)d->length, d->pointer); + break; + case DTYPE_COMPLEX: + convert_float(num * 2, CvtCRAY, (char)(message->h.length / 2), + message->bytes, CvtIEEE_S, (char)(d->length / 2), + d->pointer); + break; + case DTYPE_DOUBLE: + convert_float(num, CvtCRAY, (char)message->h.length, message->bytes, + CvtIEEE_T, sizeof(double), d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } + break; + default: + switch (d->dtype) + { + case DTYPE_FLOAT: + convert_float(num, CvtVAX_F, (char)message->h.length, message->bytes, + CvtIEEE_S, sizeof(float), d->pointer); + break; + case DTYPE_COMPLEX: + convert_float(num * 2, CvtVAX_F, (char)message->h.length, + message->bytes, CvtIEEE_S, sizeof(float), d->pointer); + break; + case DTYPE_DOUBLE: + if (CType(connection->client_type) == VMSG_CLIENT) + convert_float(num, CvtVAX_G, (char)message->h.length, message->bytes, + CvtIEEE_T, sizeof(double), d->pointer); + else + convert_float(num, CvtVAX_D, (char)message->h.length, message->bytes, + CvtIEEE_T, sizeof(double), d->pointer); + break; + + case DTYPE_COMPLEX_DOUBLE: + if (CType(connection->client_type) == VMSG_CLIENT) + convert_float(num * 2, CvtVAX_G, (char)(message->h.length / 2), + message->bytes, CvtIEEE_T, sizeof(double), d->pointer); + else + convert_float(num * 2, CvtVAX_D, (char)(message->h.length / 2), + message->bytes, CvtIEEE_T, sizeof(double), d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } + } + switch (d->dtype) + { + default: + break; + case DTYPE_FLOAT: + d->dtype = DTYPE_FS; + break; + case DTYPE_COMPLEX: + d->dtype = DTYPE_FSC; + break; + case DTYPE_DOUBLE: + d->dtype = DTYPE_FT; + break; + case DTYPE_COMPLEX_DOUBLE: + d->dtype = DTYPE_FTC; + break; + } + // CALL EXECUTE MESSAGE // + if (message->h.descriptor_idx == (message->h.nargs - 1)) + { + execute_message(connection, message); + } + else + { + free(message); + } + } +} + +static inline void mdsio_open_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + char *filename = (char *)message->bytes; + int options = mdsio->open.options; + mode_t mode = mdsio->open.mode; + int fopts = 0; + if (options & MDS_IO_O_CREAT) + fopts |= O_CREAT; + if (options & MDS_IO_O_TRUNC) + fopts |= O_TRUNC; + if (options & MDS_IO_O_EXCL) + fopts |= O_EXCL; + if (options & MDS_IO_O_WRONLY) + fopts |= O_WRONLY; + if (options & MDS_IO_O_RDONLY) + fopts |= O_RDONLY; + if (options & MDS_IO_O_RDWR) + fopts |= O_RDWR; + int fd = MDS_IO_OPEN(filename, fopts, mode); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&fd}; + send_response(connection, message, 3, &ans_d); +} + +static inline void mdsio_close_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + int fd = mdsio->close.fd; + int ans_o = MDS_IO_CLOSE(fd); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, 1, &ans_d); +} + +static inline void mdsio_lseek_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + int fd = mdsio->lseek.fd; + int64_t offset = mdsio->lseek.offset; + SWAP_INT_IF_BIGENDIAN(&offset); + int whence = mdsio->lseek.whence; + int64_t ans_o = MDS_IO_LSEEK(fd, offset, whence); + struct descriptor ans_d = {8, DTYPE_Q, CLASS_S, 0}; + ans_d.pointer = (char *)&ans_o; + SWAP_INT_IF_BIGENDIAN(ans_d.pointer); + send_response(connection, message, 1, (mdsdsc_t *)&ans_d); +} + +static inline void mdsio_read_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + int fd = mdsio->read.fd; + size_t count = mdsio->read.count; + void *buf = malloc(count); + ssize_t nbytes = MDS_IO_READ(fd, buf, count); +#ifdef USE_PERF + TreePerfRead(nbytes); +#endif + if (nbytes > 0) + { + DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); + if ((size_t)nbytes != count) + perror("READ_K wrong byte count"); + send_response(connection, message, 1, (mdsdsc_t *)&ans_d); + } + else + { + DESCRIPTOR(ans_d, ""); + send_response(connection, message, 1, (mdsdsc_t *)&ans_d); + } + free(buf); +} + +static inline void mdsio_write_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + /* from http://man7.org/linux/man-pages/man2/write.2.html + * On Linux, write() (and similar system calls) will transfer at most + * 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes + * actually transferred. (This is true on both 32-bit and 64-bit + * systems.) => ergo uint32 will suffice + */ + int fd = mdsio->write.fd; + size_t count = mdsio->write.count; + uint32_t ans_o = + (uint32_t)(MDS_IO_WRITE(fd, message->bytes, count) & 0xFFFFFFFFL); + struct descriptor ans_d = {sizeof(ans_o), DTYPE_LU, CLASS_S, + (char *)&ans_o}; + SWAP_INT_IF_BIGENDIAN(ans_d.pointer); + if (ans_o != mdsio->write.count) + perror("WRITE_K wrong byte count"); + send_response(connection, message, 1, &ans_d); +} + +static inline void mdsio_lock_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + int fd = mdsio->lock.fd; + off_t offset = mdsio->lock.offset; + SWAP_INT_IF_BIGENDIAN(&offset); + int size = mdsio->lock.size; + int mode_in = mdsio->lock.mode; + int mode = mode_in & 0x3; + int nowait = mode_in & 0x8; + int deleted; + int ans_o = MDS_IO_LOCK(fd, offset, size, mode | nowait, &deleted); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, deleted ? 3 : 1, &ans_d); +} + +static inline void mdsio_exists_k(Connection *connection, Message *message) +{ + char *filename = message->bytes; + int ans_o = MDS_IO_EXISTS(filename); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, 1, &ans_d); +} + +static inline void mdsio_remove_k(Connection *connection, Message *message) +{ + char *filename = message->bytes; + int ans_o = MDS_IO_REMOVE(filename); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, 1, &ans_d); +} + +static inline void mdsio_rename_k(Connection *connection, Message *message) +{ + char *old = message->bytes; + char *new = message->bytes + strlen(old) + 1; + int ans_o = MDS_IO_RENAME(old, new); + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, 1, &ans_d); +} + +static inline void mdsio_read_x_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + int fd = mdsio->read_x.fd; + off_t offset = mdsio->read_x.offset; + SWAP_INT_IF_BIGENDIAN(&offset); + size_t count = mdsio->read_x.count; + void *buf = malloc(count); + int deleted; + size_t nbytes = MDS_IO_READ_X(fd, offset, buf, count, &deleted); + if (nbytes > 0) + { + DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); + if ((size_t)nbytes != count) + perror("READ_X_K wrong byte count"); + send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); + } + else + { + DESCRIPTOR(ans_d, ""); + send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); + } + free(buf); +} + +static inline void mdsio_open_one_k(Connection *connection, Message *message) +{ + const mdsio_t *mdsio = (mdsio_t *)message->h.dims; + char *treename = message->bytes; + char *filepath = message->bytes + strlen(treename) + 1; + int shot = mdsio->open_one.shot; + tree_type_t type = (tree_type_t)mdsio->open_one.type; + int new = mdsio->open_one.new; + int edit_flag = mdsio->open_one.edit; + int fd; + char *fullpath = NULL; + int status = MDS_IO_OPEN_ONE(filepath, treename, shot, type, new, + edit_flag, &fullpath, NULL, &fd); + int msglen = fullpath ? strlen(fullpath) + 9 : 8; + char *msg = malloc(msglen); + DESCRIPTOR_A(ans_d, sizeof(char), DTYPE_B, msg, msglen); + memcpy(msg, &status, 4); + memcpy(msg + 4, &fd, 4); + if (fullpath) + { + memcpy(msg + 8, fullpath, msglen - 8); + free(fullpath); + } + send_response(connection, message, 3, (mdsdsc_t *)&ans_d); + free(msg); +} + +static void return_status(Connection *connection, Message *message, int ans_o) +{ + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; + send_response(connection, message, 1, &ans_d); +} + +static void mdsio_command(Connection *connection, Message *message) +{ + connection->client_type = message->h.client_type; + switch (message->h.descriptor_idx) + { + case MDS_IO_OPEN_K: + mdsio_open_k(connection, message); + break; + case MDS_IO_CLOSE_K: + mdsio_close_k(connection, message); + break; + case MDS_IO_LSEEK_K: + mdsio_lseek_k(connection, message); + break; + case MDS_IO_READ_K: + mdsio_read_k(connection, message); + break; + case MDS_IO_WRITE_K: + mdsio_write_k(connection, message); + break; + case MDS_IO_LOCK_K: + mdsio_lock_k(connection, message); + break; + case MDS_IO_EXISTS_K: + mdsio_exists_k(connection, message); + break; + case MDS_IO_REMOVE_K: + mdsio_remove_k(connection, message); + break; + case MDS_IO_RENAME_K: + mdsio_rename_k(connection, message); + break; + case MDS_IO_READ_X_K: + mdsio_read_x_k(connection, message); + break; + case MDS_IO_OPEN_ONE_K: + mdsio_open_one_k(connection, message); + break; + default: + return_status(connection, message, 0); + break; + } +} + +//#define THREADED_IO +#ifdef THREADED_IO +struct command +{ + void (*method)(Connection *, Message *); + Connection *connection; + Message *message; +}; + +static void *thread_command(void *args) +{ + struct command *cm = (struct command *)args; + cm->method(cm->connection, cm->message); + return NULL; +} + +static Message *dispatch_command( + void (*method)(Connection *, Message *), + Connection *connection, + Message *message) +{ + struct command *args = (struct command *)malloc(sizeof(struct command)); + if (args) + { + args->method = method; + args->connection = connection; + args->message = message; + pthread_t thread; + if (pthread_create(&thread, NULL, thread_command, (void *)args)) + perror("pthread_create"); + else if (pthread_detach(thread)) + perror("pthread_detach"); + } + return_status(connection, message, MDSplusFATAL); +} +#endif + +/// Handle message from server listen routine. A new descriptor instance is +/// created with the message buffer size and the message memory is copyed +/// inside. A proper conversion of memory structure is applied if neede for the +/// type of client connected. +/// +/// \param connection the connection instance to handle +/// \param message the message to process +/// \return message answer +/// +void ProcessMessage(Connection *connection, Message *message) +{ + //MDSplusThreadStatic(connection->mts); + // COMING NEW MESSAGE // + // reset connection id // + if (connection->message_id != message->h.message_id) + { + FreeDescriptors(connection); + if (message->h.nargs < MDSIP_MAX_ARGS - 1) + { + connection->message_id = message->h.message_id; + connection->nargs = message->h.nargs; + } + else + { + return_status(connection, message, 0); + return; + } + } + if (message->h.descriptor_idx < connection->nargs) + { +#ifdef THREADED_IO + dispatch_command(standard_command, connection, message); +#else + standard_command(connection, message); +#endif + } + else + { +#ifdef THREADED_IO + dispatch_command(mdsio_command, connection, message); +#else + mdsio_command(connection, message); +#endif + } +} diff --git a/mdstcpip/SendArg.c b/mdstcpip/mdsipshr/SendArg.c similarity index 98% rename from mdstcpip/SendArg.c rename to mdstcpip/mdsipshr/SendArg.c index 63becd3b31..39488788be 100644 --- a/mdstcpip/SendArg.c +++ b/mdstcpip/mdsipshr/SendArg.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mdsip_connections.h" -#include "mdsIo.h" +#include "../mdsip_connections.h" +#include "../mdsIo.h" #include #include #include diff --git a/mdstcpip/SendMdsMsg.c b/mdstcpip/mdsipshr/SendMdsMsg.c similarity index 98% rename from mdstcpip/SendMdsMsg.c rename to mdstcpip/mdsipshr/SendMdsMsg.c index c6aa762c12..e98991bad1 100644 --- a/mdstcpip/SendMdsMsg.c +++ b/mdstcpip/mdsipshr/SendMdsMsg.c @@ -28,9 +28,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "zlib/zlib.h" +#include "../zlib/zlib.h" -#include "mdsip_connections.h" +#include "../mdsip_connections.h" static int SendBytes(Connection *c, void *buffer, size_t bytes_to_send, int options) diff --git a/mdstcpip/cvtdef.h b/mdstcpip/mdsipshr/cvtdef.h similarity index 100% rename from mdstcpip/cvtdef.h rename to mdstcpip/mdsipshr/cvtdef.h diff --git a/python/MDSplus/tests/_UnitTest.py b/python/MDSplus/tests/_UnitTest.py index 3b005aa192..c482b42271 100755 --- a/python/MDSplus/tests/_UnitTest.py +++ b/python/MDSplus/tests/_UnitTest.py @@ -25,8 +25,9 @@ from unittest import TestCase, TestSuite, TextTestRunner from MDSplus import Tree, getenv, setenv, tcl, TreeWRITEFIRST, TreeNOT_OPEN -from threading import RLock -from re import match +import traceback +import threading +import re import gc import os import sys @@ -50,6 +51,38 @@ def __exit__(self, *a, **kv): return self.close() def __getattr__(self, name): return self.__f.__getattribute__(name) +class TestThread(threading.Thread): + """ Run Tests in parralel and evaluate """ + + @staticmethod + def assertRun(*threads): + for thread in threads: + thread.start() + for thread in threads: + thread.join() + for thread in threads: + thread.check() + + def __init__(self, name, test, *args, **kwargs): + super(TestThread, self).__init__(name=name) + self.exc = None + self.test = test + self.args = args + self.kwargs = kwargs + + def run(self): + try: + self.test(*self.args, **self.kwargs) + except Exception as exc: + if not hasattr(exc, "__traceback__"): + _, _, exc.__traceback__ = sys.exc_info() + self.exc = exc + + def check(self): + if self.exc: + traceback.print_tb(self.exc.__traceback__) + raise self.exc + class Tests(TestCase): debug = False is_win = sys.platform.startswith('win') @@ -78,35 +111,37 @@ def runTest(self): finally: sys.stdout, sys.stderr = stdout, stderr - def _doTCLTest(self, expr, out=None, err=None, re=False, verify=False, quiet=False): + def _doTCLTest(self, expr, out=None, err=None, regex=False, verify=False, quiet=False, tree=None): def checkre(pattern, string): if pattern is None: self.assertEqual(string is None, True) else: self.assertEqual(string is None, False) - self.assertEqual(match(pattern, str(string)) is None, + self.assertEqual(re.match(pattern, str(string)) is None, False, '"%s"\nnot matched by\n"%s"' % (string, pattern)) if not quiet: sys.stderr.write("TCL> %s\n" % (expr,)) - outo, erro = tcl(expr, True, True, True) + outo, erro = (tree.tcl if tree else tcl)( + expr, True, True, True) if verify: ver, erro = erro.split('\n', 2) self.assertEqual(ver.endswith("%s" % expr), True) if len(erro) == 0: erro = None - if not re: + if not regex: self.assertEqual(outo, out) self.assertEqual(erro, err) else: checkre(out, outo) checkre(err, erro) - def _doExceptionTest(self, expr, exc): + def _doExceptionTest(self, expr, exc, tree=None): if Tests.debug: sys.stderr.write("TCL(%s) # expected exception: %s\n" % (expr, exc.__name__)) try: - tcl(expr, True, True, True) + (tree.tcl if tree else tcl)( + expr, True, True, True) except Exception as e: self.assertEqual(e.__class__, exc) return @@ -182,7 +217,7 @@ def _testDispatchCommandNoWait(self, mdsip, command, stdout=None, stderr=None): def _checkIdle(self, server, **opt): show_server = "Checking server: %s\n[^,]+, [^,]+, logging enabled, Inactive\n" % server self._doTCLTest('show server %s' % - server, out=show_server, re=True, **opt) + server, out=show_server, regex=True, **opt) def _waitIdle(self, server, timeout): timeout = time.time()+timeout @@ -288,7 +323,7 @@ def _start_mdsip(self, server, port, logname, protocol='TCP'): class TreeTests(Tests): - lock = RLock() + lock = threading.RLock() shotinc = 1 instances = 0 trees = [] @@ -339,13 +374,13 @@ def tearDown(self): if not self.is_win or self.inThread: return - def isTree(o): + def is_tree(o): try: return isinstance(o, Tree) except Exception as e: print(e) return False - trees = [o for o in gc.get_objects() if isTree(o)] + trees = [o for o in gc.get_objects() if is_tree(o)] for t in trees: try: t.close() @@ -353,6 +388,5 @@ def isTree(o): t.quit() except TreeNOT_OPEN: pass - except: - import traceback + except Exception: traceback.print_exc() diff --git a/python/MDSplus/tests/connectionUnitTest.py b/python/MDSplus/tests/connectionUnitTest.py index 575a71dd2c..52ea16547b 100755 --- a/python/MDSplus/tests/connectionUnitTest.py +++ b/python/MDSplus/tests/connectionUnitTest.py @@ -23,9 +23,12 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -from threading import Thread -from MDSplus import Connection, GetMany, Float32, Range, setenv, Tree, TreeNNF, TreeNodeArray, ADD +import os +import shutil +import subprocess +import tempfile import time +from MDSplus import Connection, GetMany, Float32, Range, setenv, Tree, TreeNNF, ADD def _mimport(name, level=1): @@ -37,7 +40,6 @@ def _mimport(name, level=1): _UnitTest = _mimport("_UnitTest") - class Tests(_UnitTest.TreeTests, _UnitTest.MdsIp): index = 0 trees = ["pysub"] @@ -145,7 +147,7 @@ def threadsTcp(self): def requests(c, idx): args = [Float32(i/10+idx) for i in range(10)] - for i in range(10): + for _ in range(10): self.assertEqual( c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(), args) c = Connection(server) @@ -161,12 +163,10 @@ def requests(c, idx): self.assertEqual(g.get('a'), 1) self.assertEqual(g.get('b'), 2) self.assertEqual(g.get('c'), 3) - threads = [Thread(name="C%d" % i, target=requests, - args=(c, i)) for i in range(10)] - for thread in threads: - thread.start() - for thread in threads: - thread.join() + _UnitTest.TestThread.assertRun(*( + _UnitTest.TestThread("C%d" % i, requests, c, i) + for i in range(10) + )) finally: if svr and svr.poll() is None: svr.terminate() @@ -176,20 +176,72 @@ def requests(c, idx): svr_log.close() def threadsLocal(self): - c = Connection('local://gub') - - class ConnectionThread(Thread): - def run(self): - for i in range(1000): - self.test.assertEqual(int(c.get('%d' % i)), i) - t1 = ConnectionThread() - t1.test = self - t2 = ConnectionThread() - t2.test = self - t1.start() - t2.start() - t1.join() - t2.join() + connection = Connection('local://gub') + def test(s, c): + for i in range(1000): + s.assertEqual(int(c.get('%d' % i)), i) + _UnitTest.TestThread.assertRun(*( + _UnitTest.TestThread("C%d" % i, test, self, connection) + for i in range(10) + )) + + + def fast_remote_write(self): + count = 100 + + def mdsip(hostfile): + with open(hostfile, "w") as f: + f.write("multi|SELF\n*") + process = subprocess.Popen(( + 'mdsip', '-m', + '-p', '8000', + '-P', 'TCP', + '-h', hostfile, + )) + time.sleep(1) + return process + + def thread(test, name, node, count): + start = time.time() + i = -1 + for i in range(count): + data = Float32([i*10+1]) + now = Float32([time.time()]) + node.makeSegment(now[0], now[0], data, now) + end = time.time() + i += 1 + test.assertEqual(i, count) + print("%s: rate %f" % (name, i / (end-start))) + + tempdir = tempfile.mkdtemp() + try: + server = mdsip(os.path.join(tempdir, "mdsip.hosts")) + try: + con = Connection('127.0.0.1') + def check(line, *args): + sts = con.get(line, *args) + self.assertTrue(sts & 1, "error %d in '%s'" % (sts, line)) + check("setenv('test_path='//$)", tempdir) + for line in ( + "TreeOpenNew('test', 1)", + "TreeAddNode('EV1', _, 6)", + "TreeAddNode('EV2', _, 6)", + "TreeWrite()", + "TreeClose()", + ): + check(line) + setenv("test_path", "127.0.0.1::" + tempdir) + tree = Tree("test", 1) + _UnitTest.TestThread.assertRun( + _UnitTest.TestThread('EV1', thread, self, 'EV1', tree.EV1.copy(), count), + _UnitTest.TestThread('EV2', thread, self, 'EV2', tree.EV2.copy(), count), + ) + finally: + if server: + server.kill() + server.wait() + finally: + shutil.rmtree(tempdir, ignore_errors=False, onerror=None) @staticmethod def getTests(): diff --git a/python/MDSplus/tests/dclUnitTest.py b/python/MDSplus/tests/dclUnitTest.py index 18fa6a3f56..12c88799ca 100755 --- a/python/MDSplus/tests/dclUnitTest.py +++ b/python/MDSplus/tests/dclUnitTest.py @@ -228,8 +228,6 @@ def getTests(): if Tests.inThread: return lst lst.append('dispatcher') - if sys.platform.startswith('win') or sys.maxsize > 1 << 32: - lst.append('timeout') return lst diff --git a/python/MDSplus/tests/devices/TestDevice.py b/python/MDSplus/tests/devices/TestDevice.py index b375a60652..7eca111401 100644 --- a/python/MDSplus/tests/devices/TestDevice.py +++ b/python/MDSplus/tests/devices/TestDevice.py @@ -57,47 +57,26 @@ class TestDevice(Device): {'path': ':ACTIONSERVER:PULSE', 'type': 'ACTION', 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Action(node.DISPATCH, node.TASK)' - }, - {'path': ':ACTIONSERVER:PULSE:DISPATCH', - 'type': 'DISPATCH', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Dispatch(head.ACTIONSERVER, "PULSE", 10)' - }, - {'path': ':ACTIONSERVER:PULSE:TASK', - 'type': 'TASK', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Method(None, "pulse", head)' + 'valueExpr': ( + 'Action(' + 'Dispatch(head.ACTIONSERVER, "PULSE", 10),' + 'Method(None, "pulse", head))'), }, {'path': ':ACTIONSERVER:STORE', 'type': 'ACTION', 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Action(node.DISPATCH, node.TASK)', - }, - {'path': ':ACTIONSERVER:STORE:DISPATCH', - 'type': 'DISPATCH', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Dispatch(head.ACTIONSERVER, "STORE", 10)', - }, - {'path': ':ACTIONSERVER:STORE:TASK', - 'type': 'TASK', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Method(None,"store",head)', + 'valueExpr': ( + 'Action(' + 'Dispatch(head.ACTIONSERVER, "STORE", 10),' + 'Method(None, "store", head))'), }, {'path': ':ACTIONSERVER:MANUAL', 'type': 'ACTION', 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Action(node.DISPATCH,node.TASK)', - }, - {'path': ':ACTIONSERVER:MANUAL:DISPATCH', - 'type': 'DISPATCH', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Dispatch(head.ACTIONSERVER, "MANUAL", 10)', - }, - {'path': ':ACTIONSERVER:MANUAL:TASK', - 'type': 'TASK', - 'options': ('no_write_shot', 'write_once'), - 'valueExpr': 'Method(None,"manual",head)', + 'valueExpr': ( + 'Action(' + 'Dispatch(head.ACTIONSERVER, "MANUAL", 10),' + 'Method(None, "manual", head))'), }, {'path': ':TASK_TEST', 'type': 'TASK', diff --git a/python/MDSplus/tests/taskUnitTest.py b/python/MDSplus/tests/taskUnitTest.py index 2c6b5da081..691d285dcc 100755 --- a/python/MDSplus/tests/taskUnitTest.py +++ b/python/MDSplus/tests/taskUnitTest.py @@ -23,9 +23,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -import sys -from re import match -from MDSplus import Tree, tcl, mdsExceptions as Exc +from MDSplus import Tree, Device, mdsExceptions as Exc def _mimport(name, level=1): @@ -43,12 +41,19 @@ class Tests(_UnitTest.TreeTests): tree = 'pytree' def dotask_timeout(self): - def test(): - with Tree(self.tree, self.shot): - for i in range(1000): - self._doExceptionTest( - 'do TESTDEVICE:TASK_TIMEOUT', Exc.TdiTIMEOUT) - + with Tree(self.tree, self.shot, 'new') as tree: + Device.PyDevice('TestDevice').Add(tree, 'TESTDEVICE') + tree.write() + tree.normal() + for _ in range(2): + self._doTCLTest( + 'do TESTDEVICE:TASK_TEST', tree=tree) + self._doExceptionTest( + 'do TESTDEVICE:TASK_ERROR1', Exc.DevUNKOWN_STATE, tree) + self._doExceptionTest( + 'do TESTDEVICE:TASK_ERROR2', Exc.DevUNKOWN_STATE, tree) + self._doExceptionTest( + 'do TESTDEVICE:TASK_TIMEOUT', Exc.TdiTIMEOUT, tree) @staticmethod def getTests(): return ['dotask_timeout'] diff --git a/testing/helgrind b/testing/helgrind index 00f90d1355..adc9a8022e 100755 --- a/testing/helgrind +++ b/testing/helgrind @@ -4,8 +4,5 @@ exec valgrind --tool=helgrind --history-level=full\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-mdsplus.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python-disableleak.supp\ + --suppressions=$MDSPLUS_DIR/conf/valgrind.supp/mdsplus.supp\ "$@" diff --git a/testing/memcheck b/testing/memcheck index eb60fa0c2c..8c87f297ea 100755 --- a/testing/memcheck +++ b/testing/memcheck @@ -4,8 +4,5 @@ exec valgrind --tool=memcheck --leak-check=full --show-reachable=no\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-mdsplus.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python.supp\ - --suppressions=$MDSPLUS_DIR/conf/valgrind-python-disableleak.supp\ + --suppressions=$MDSPLUS_DIR/conf/valgrind.supp/mdsplus.supp\ "$@" From c1bab5dda6a4d1e944eb66960c8c218aa269b177 Mon Sep 17 00:00:00 2001 From: cloud Date: Thu, 22 Apr 2021 16:47:37 +0200 Subject: [PATCH 08/27] Tests: fixed fc32 helgrind suppression file --- conf/valgrind.supp/fc32.supp | 1 + 1 file changed, 1 insertion(+) diff --git a/conf/valgrind.supp/fc32.supp b/conf/valgrind.supp/fc32.supp index 391ea8cf81..37a5c6fde3 100644 --- a/conf/valgrind.supp/fc32.supp +++ b/conf/valgrind.supp/fc32.supp @@ -254,6 +254,7 @@ Helgrind:Race fun:memmove obj:/usr/lib64/libpython3.8.so.1.0 +} { PyEval_AcquireThread Helgrind:Race From 6c4adc4a8f8990793f6bf3d213285ba0aafcf23f Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Mon, 3 May 2021 11:33:29 +0200 Subject: [PATCH 09/27] Fix:avoid division by zero foir empty segment (#2301) * Fix:avoid division by zero foir empty segment * apply clang-format to change * Better handle for empty segments Co-authored-by: GabrieleManduchi Co-authored-by: Timo Schroeder --- xtreeshr/XTreeDefaultResample.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/xtreeshr/XTreeDefaultResample.c b/xtreeshr/XTreeDefaultResample.c index 1691d77f94..1425778ecc 100644 --- a/xtreeshr/XTreeDefaultResample.c +++ b/xtreeshr/XTreeDefaultResample.c @@ -238,9 +238,15 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, if (!fulltimebase) { MdsFree1Dx(&dataXd, 0); - MdsCopyDxXd((mdsdsc_t *)&inSignalD, outSignalXd); + MdsCopyDxXd((mdsdsc_t *)inSignalD, outSignalXd); return 3; // Cannot convert timebase to 64 bit int } + if(numData == 0) //If empty segment + { + MdsFree1Dx(&dataXd, 0); + MdsCopyDxXd((mdsdsc_t *)inSignalD, outSignalXd); + return 1; + } // Check data array too short if (numData < numTimebase) From cc1c8cf5438f4a4301b3790a289be98ea60fa644 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Mon, 3 May 2021 16:20:37 +0200 Subject: [PATCH 10/27] Build: fixed windows 32 to ship libgcc_s_dw2 as SEH is not supported for 32 bit yet (#2302) Solved the issue with libgcc_s_dw2 in #2297 --- deploy/packaging/windows/mdsplus.nsi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/deploy/packaging/windows/mdsplus.nsi b/deploy/packaging/windows/mdsplus.nsi index a169e8844a..958484d50c 100644 --- a/deploy/packaging/windows/mdsplus.nsi +++ b/deploy/packaging/windows/mdsplus.nsi @@ -21,6 +21,7 @@ InstType "Minimal" !define READLINELIB libreadline8.dll !define GCC_STDCPP_LIB libstdc++-6.dll !define GCC_S_SEH_LIB libgcc_s_seh-1.dll +!define GCC_S_DW2_LIB libgcc_s_dw2-1.dll !define GFORTRAN_LIB libgfortran-5.dll !define QUADMATH_LIB libquadmath-0.dll !define LIBXML2_LIB libxml2-2.dll @@ -257,6 +258,7 @@ SectionGroup "!core" core File ${MINGWLIB32}/${READLINELIB} File ${MINGWLIB32}/${TERMCAPLIB} File ${MINGWLIB32}/${GCC_STDCPP_LIB} + File ${MINGWLIB32}/${GCC_S_DW2_LIB} File ${MINGWLIB32}/${GFORTRAN_LIB} File ${MINGWLIB32}/${QUADMATH_LIB} File ${MINGWLIB32}/${LIBXML2_LIB} From 98c2f5378a8ea154eb9adc13c8b59dae6656e3e4 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Mon, 3 May 2021 16:55:39 +0200 Subject: [PATCH 11/27] Tests: splits up python tests to get finer results (#2296) * Tests: fixed valgrind test tools * Tests: reafactor python tests for fine results * Fixed minor bugs * mdsdcl: fixed memory leak: clear_history on exit * servershr SOURCES OBJECTS * attempt to fix memoryleak in show_server * tcl: use SOURCES and OBJECTS with wildcard * Cannot resolve issue in TclDispatch_show_server; lacking information * added suppression for python GIL stuff * dont inline EXPORTED function GetAnswerInfoTS * added python suppression * set after pthread_cleanup_push in INIT_AS_AND_FREE_ON_EXIT * fix memory leak in case of pthread_cancel * Tests: disable thread_* tests; they take forever and have little extra value\n threaded tests can be implemented in sub testcases * added suppression for java Co-authored-by: Timo Schroeder --- .gitignore | 1 + Makefile.in | 1 + bootstrap | 2 + conf/valgrind-supp.py | 55 ++++++ conf/valgrind.supp/fc32.supp | 28 +++ conf/valgrind.supp/mdsplus.supp | 28 +++ deploy/gen_messages.py | 20 +- deploy/packaging/debian/python.noarch | 21 +- deploy/packaging/redhat/python.noarch | 21 +- include/pthread_port.h | 9 +- m4/m4_ax_valgrind_check.m4 | 5 +- mdsdcl/mdsdcl.c | 6 +- mdstcpip/mdsipshr/GetAnswerInfo.c | 2 +- python/MDSplus/apd.py | 4 +- python/MDSplus/mdsdata.py | 2 +- python/MDSplus/tests/Makefile.am | 55 +++++- .../tests/{_UnitTest.py => _common.py} | 132 +++++++------ ...nnectionUnitTest.py => connection_case.py} | 124 ++++++------ .../tests/{dataUnitTest.py => data_case.py} | 48 ++--- .../tests/{dclUnitTest.py => dcl_case.py} | 66 +++---- .../{devicesUnitTest.py => devices_case.py} | 41 ++-- ...exceptionUnitTest.py => exception_case.py} | 31 +-- .../{segmentsUnitTest.py => segment_case.py} | 86 ++++---- python/MDSplus/tests/simulateSegfault.py | 59 ------ .../tests/{taskUnitTest.py => task_case.py} | 14 +- .../{threadsUnitTest.py => thread_case.py} | 89 ++++----- .../tests/{treeUnitTest.py => tree_case.py} | 179 +++++++++-------- python/MDSplus/tree.py | 25 ++- python/MDSplus/version.py | 7 +- python/generate_tests | 17 ++ servershr/Makefile.in | 26 +-- tcl/Makefile.in | 48 +---- tcl/tcl_dispatch.c | 42 ++-- testing/generate_valgrind_suppressions.sh | 20 +- testing/helgrind | 10 +- testing/memcheck | 10 +- testing/parse_valgrind_suppressions.sh | 4 +- treeshr/TreeGetRecord.c | 183 ++++++++++-------- 38 files changed, 816 insertions(+), 705 deletions(-) create mode 100644 conf/valgrind-supp.py rename python/MDSplus/tests/{_UnitTest.py => _common.py} (79%) mode change 100755 => 100644 rename python/MDSplus/tests/{connectionUnitTest.py => connection_case.py} (72%) rename python/MDSplus/tests/{dataUnitTest.py => data_case.py} (95%) rename python/MDSplus/tests/{dclUnitTest.py => dcl_case.py} (84%) rename python/MDSplus/tests/{devicesUnitTest.py => devices_case.py} (80%) rename python/MDSplus/tests/{exceptionUnitTest.py => exception_case.py} (78%) rename python/MDSplus/tests/{segmentsUnitTest.py => segment_case.py} (90%) delete mode 100644 python/MDSplus/tests/simulateSegfault.py rename python/MDSplus/tests/{taskUnitTest.py => task_case.py} (91%) rename python/MDSplus/tests/{threadsUnitTest.py => thread_case.py} (57%) rename python/MDSplus/tests/{treeUnitTest.py => tree_case.py} (79%) create mode 100755 python/generate_tests diff --git a/.gitignore b/.gitignore index c9e054857a..8b21a4a867 100644 --- a/.gitignore +++ b/.gitignore @@ -170,6 +170,7 @@ mdstcpip/zlib/Makefile.in python/MDSplus/docs/Makefile.in python/MDSplus/compound.py python/MDSplus/mdsExceptions.py +python/MDSplus/tests/*_test.py python/MDSplus/tests/Makefile.in rpm/Makefile.in scripts/Makefile.in diff --git a/Makefile.in b/Makefile.in index 9d96b76fba..d734d23a92 100644 --- a/Makefile.in +++ b/Makefile.in @@ -192,6 +192,7 @@ install: $(install_DIRS) --exclude=__pycache__ \ --exclude=python/MDSplus/build \ --exclude=python/MDSplus/docs \ + --exclude=python/MDSplus/tests/*_test.py \ --exclude=tdi/*Devices/build \ --exclude='*egg-info' \ --exclude='*\.in' \ diff --git a/bootstrap b/bootstrap index adeb30657a..8fb031923d 100755 --- a/bootstrap +++ b/bootstrap @@ -39,6 +39,8 @@ fi conf/update_submodules +python/generate_tests + aclocal -I ./m4 autoheader diff --git a/conf/valgrind-supp.py b/conf/valgrind-supp.py new file mode 100644 index 0000000000..971c971205 --- /dev/null +++ b/conf/valgrind-supp.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +import sys +import re + +maxdepth = 7 +root = dict() +curr = None +record = -1 +filter = {'fun:UnknownInlinedFun', re.compile(r'fun:.+\.lto_priv\..+'), "obj:*"} + + +for filepath in sys.argv[1:]: + with open(filepath, 'r') as f: + gen = (l for l in f) + for line in gen: + line = line.strip() + if record >= 0: + if line == "}": + record = -1 + curr = None + elif record < maxdepth: + record += 1 + curr = curr.setdefault(line, dict()) + elif line == "{": + record = 0 + curr = root + next(gen) + + +def print_level(curr, pre): + if curr: + for k, v in curr.items(): + print_level(v, pre + [k]) + else: + while True: + for flt in filter: + if isinstance(flt, str): + if flt == pre[-1]: + break + else: + if flt.search(pre[-1]): + break + else: + break + if len(pre) <= 2: + break + pre.pop() + print("{") + print(" %s" % pre[-1].split(":", 2)[-1]) + for l in pre: + print(" %s" % l) + print("}") + + +print_level(root, []) diff --git a/conf/valgrind.supp/fc32.supp b/conf/valgrind.supp/fc32.supp index 37a5c6fde3..6b97acb63d 100644 --- a/conf/valgrind.supp/fc32.supp +++ b/conf/valgrind.supp/fc32.supp @@ -40,6 +40,11 @@ fun:calloc fun:_dl_allocate_tls } +{ + mempcpy e.g. caused by printf + Helgrind:Race + fun:mempcpy +} # python @@ -72,6 +77,14 @@ obj:/usr/lib64/libpython3.8.so.1.0 fun:PyBytes_FromStringAndSize } +{ + likely GIL stuff + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + obj:/usr/lib64/libpython3.8.so.1.0 + obj:/usr/lib64/libpython3.8.so.1.0 +} { PyObject_Malloc Memcheck:Leak @@ -93,6 +106,13 @@ fun:malloc fun:_PyObject_New } +{ + _PyObject_New + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_PyObject_New +} { PyMem_Calloc Memcheck:Leak @@ -381,3 +401,11 @@ Memcheck:Cond fun:_ZN10InlineTreeC1EP7CompilePKS_P8ciMethodP8JVMStateifi } +{ + os::PlatformEvent::unpark() + Helgrind:Misc + fun:pthread_cond_signal@@GLIBC_2.3.2 + fun:pthread_cond_signal_WRK + fun:pthread_cond_signal@* + fun:_ZN2os13PlatformEvent6unparkEv +} \ No newline at end of file diff --git a/conf/valgrind.supp/mdsplus.supp b/conf/valgrind.supp/mdsplus.supp index 5868952807..c520223266 100644 --- a/conf/valgrind.supp/mdsplus.supp +++ b/conf/valgrind.supp/mdsplus.supp @@ -6,3 +6,31 @@ ... fun:xmlInitParser_supp } +{ + pthread_once false positive + Helgrind:Race + fun:MDSplusThreadStatic +} +{ + pthread_once is meant to be thrad safe and blocking + Helgrind:Race + fun:* + fun:__pthread_once_slow +} +{ + PyGIL locked on exit + Helgrind:Misc + fun:raise + fun:abort + fun:PyGILState_Cleanup +} +{ + unresolved issue in TclDispatch_show_server + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + obj:* + obj:* + obj:* + fun:TclDispatch_show_server +} \ No newline at end of file diff --git a/deploy/gen_messages.py b/deploy/gen_messages.py index 64f68a1776..8cbeb36967 100755 --- a/deploy/gen_messages.py +++ b/deploy/gen_messages.py @@ -60,17 +60,17 @@ class MDSplusException(MdsException): fac="MDSplus" statusDict={} severities=["W", "S", "E", "I", "F", "?", "?", "?"] - def __new__(cls,*argv): + def __new__(cls, *argv): if not argv or cls is not MDSplusException: - return super(MDSplusException,cls).__new__(cls,*argv) + return super(MDSplusException,cls).__new__(cls, *argv) status = int(argv[0]) code = status & -8 if code in cls.statusDict: cls = cls.statusDict[code] else: cls = MDSplusUnknown - return cls.__new__(cls,*argv) - def __init__(self,status=None,message=None): + return cls.__new__(cls, *argv) + def __init__(self, status=None, message=None): if isinstance(status,int): self.status = status else: @@ -83,8 +83,8 @@ def __init__(self,status=None,message=None): self.fac='MDSplus' if message is not None: message = str(message) - if len(message)>0: - self.message = "%s:%s"%(self.message,message) + if message: + self.message = message self.severity=self.severities[self.status & 7] super(Exception,self).__init__(self.message) @@ -312,10 +312,10 @@ def gen_include(root, filename, faclist, msglistm, f_test): msgnum = int(status.get('value')) sev = sevs[status.get('severity').lower()] msgn = (facnum << 16)+(msgnum << 3)+sev - text = status.get('text', "") - if len(text) == 0: - raise Exception( - "missing or empty text: %s in %s." % (facnam, filename)) + text = status.get('text', None) + if not text: + raise Exception("missing or empty text: %s in %s." % ( + facnam, filename)) depr = status.get('deprecated', "0") sfacnam = status.get('facnam') facabb = status.get('facabb') diff --git a/deploy/packaging/debian/python.noarch b/deploy/packaging/debian/python.noarch index ff55a76823..54b5779491 100644 --- a/deploy/packaging/debian/python.noarch +++ b/deploy/packaging/debian/python.noarch @@ -15,23 +15,22 @@ ./usr/local/mdsplus/python/MDSplus/modpython.py ./usr/local/mdsplus/python/MDSplus/scope.py ./usr/local/mdsplus/python/MDSplus/setup.py -./usr/local/mdsplus/python/MDSplus/tests/_UnitTest.py ./usr/local/mdsplus/python/MDSplus/tests/__init__.py -./usr/local/mdsplus/python/MDSplus/tests/connectionUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/dataUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/dclUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/_common.py +./usr/local/mdsplus/python/MDSplus/tests/connection_case.py +./usr/local/mdsplus/python/MDSplus/tests/data_case.py +./usr/local/mdsplus/python/MDSplus/tests/dcl_case.py +./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices/TestDevice.py -./usr/local/mdsplus/python/MDSplus/tests/devicesUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/exceptionUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/exception_case.py ./usr/local/mdsplus/python/MDSplus/tests/images/test.gif ./usr/local/mdsplus/python/MDSplus/tests/images/test.jpg ./usr/local/mdsplus/python/MDSplus/tests/images/test.mpg ./usr/local/mdsplus/python/MDSplus/tests/mdsip.hosts -./usr/local/mdsplus/python/MDSplus/tests/segmentsUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/simulateSegfault.py -./usr/local/mdsplus/python/MDSplus/tests/taskUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/threadsUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/treeUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/segment_case.py +./usr/local/mdsplus/python/MDSplus/tests/task_case.py +./usr/local/mdsplus/python/MDSplus/tests/thread_case.py +./usr/local/mdsplus/python/MDSplus/tests/tree_case.py ./usr/local/mdsplus/python/MDSplus/tests/trees/testing_model.characteristics ./usr/local/mdsplus/python/MDSplus/tests/trees/testing_model.datafile ./usr/local/mdsplus/python/MDSplus/tests/trees/testing_model.tree diff --git a/deploy/packaging/redhat/python.noarch b/deploy/packaging/redhat/python.noarch index 13401a00eb..fdb78b2d6a 100644 --- a/deploy/packaging/redhat/python.noarch +++ b/deploy/packaging/redhat/python.noarch @@ -17,25 +17,24 @@ ./usr/local/mdsplus/python/MDSplus/scope.py ./usr/local/mdsplus/python/MDSplus/setup.py ./usr/local/mdsplus/python/MDSplus/tests -./usr/local/mdsplus/python/MDSplus/tests/_UnitTest.py ./usr/local/mdsplus/python/MDSplus/tests/__init__.py -./usr/local/mdsplus/python/MDSplus/tests/connectionUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/dataUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/dclUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/_common.py +./usr/local/mdsplus/python/MDSplus/tests/connection_case.py +./usr/local/mdsplus/python/MDSplus/tests/data_case.py +./usr/local/mdsplus/python/MDSplus/tests/dcl_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices +./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices/TestDevice.py -./usr/local/mdsplus/python/MDSplus/tests/devicesUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/exceptionUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/exception_case.py ./usr/local/mdsplus/python/MDSplus/tests/images ./usr/local/mdsplus/python/MDSplus/tests/images/test.gif ./usr/local/mdsplus/python/MDSplus/tests/images/test.jpg ./usr/local/mdsplus/python/MDSplus/tests/images/test.mpg ./usr/local/mdsplus/python/MDSplus/tests/mdsip.hosts -./usr/local/mdsplus/python/MDSplus/tests/segmentsUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/simulateSegfault.py -./usr/local/mdsplus/python/MDSplus/tests/taskUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/threadsUnitTest.py -./usr/local/mdsplus/python/MDSplus/tests/treeUnitTest.py +./usr/local/mdsplus/python/MDSplus/tests/segment_case.py +./usr/local/mdsplus/python/MDSplus/tests/task_case.py +./usr/local/mdsplus/python/MDSplus/tests/thread_case.py +./usr/local/mdsplus/python/MDSplus/tests/tree_case.py ./usr/local/mdsplus/python/MDSplus/tests/trees ./usr/local/mdsplus/python/MDSplus/tests/trees/testing_model.characteristics ./usr/local/mdsplus/python/MDSplus/tests/trees/testing_model.datafile diff --git a/include/pthread_port.h b/include/pthread_port.h index 56bbf19e42..64eb31f3f3 100644 --- a/include/pthread_port.h +++ b/include/pthread_port.h @@ -73,11 +73,12 @@ static void __attribute__((unused)) free_if(void *ptr) { free(*(void **)ptr); } #define FREE_IF(ptr, c) pthread_cleanup_pop(c); #define FREE_NOW(ptr) FREE_IF(ptr, 1) #define FREE_CANCEL(ptr) FREE_IF(ptr, 0) -#define INIT_AS_AND_FREE_ON_EXIT(type, ptr, value) \ - type ptr = value; \ - FREE_ON_EXIT(ptr) #define INIT_AND_FREE_ON_EXIT(type, ptr) \ - INIT_AS_AND_FREE_ON_EXIT(type, ptr, NULL) + type ptr = NULL; \ + FREE_ON_EXIT(ptr) +#define INIT_AS_AND_FREE_ON_EXIT(type, ptr, value) \ + INIT_AND_FREE_ON_EXIT(type, ptr); \ + ptr = (type)value; // FCLOSE #include diff --git a/m4/m4_ax_valgrind_check.m4 b/m4/m4_ax_valgrind_check.m4 index a12b6b42c4..d0002cd8b1 100644 --- a/m4/m4_ax_valgrind_check.m4 +++ b/m4/m4_ax_valgrind_check.m4 @@ -169,8 +169,7 @@ VALGRIND_FLAGS ?= VALGRIND_FLAGS += --gen-suppressions=all \ --num-callers=64 \ --trace-children=yes \ - --child-silent-after-fork=yes \ - --trace-children-skip-by-arg=*SetMdsplusFileProtection* + --child-silent-after-fork=yes VALGRIND_memcheck_FLAGS ?= VALGRIND_memcheck_FLAGS += --leak-check=full --show-reachable=no @@ -322,7 +321,7 @@ MOSTLYCLEANFILES ?= MOSTLYCLEANFILES += $(valgrind_log_files) ' -dnl VALGRIND_CHECK_RULES subsituition +dnl VALGRIND_CHECK_RULES subsituition AC_SUBST([VALGRIND_CHECK_RULES],["${VALGRIND_CHECK_RULES_PRE} ${VALGRIND_CHECK_RULES}"]) m4_ifdef([_AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE([VALGRIND_CHECK_RULES])]) diff --git a/mdsdcl/mdsdcl.c b/mdsdcl/mdsdcl.c index 77098050c1..3b3fbe1676 100644 --- a/mdsdcl/mdsdcl.c +++ b/mdsdcl/mdsdcl.c @@ -340,7 +340,11 @@ int main(int argc, char const *argv[]) free(error); history_file = mdsdclGetHistoryFile(); if (history_file) + { write_history(history_file); - free(history_file); + free(history_file); + } + else + clear_history(); return status; } diff --git a/mdstcpip/mdsipshr/GetAnswerInfo.c b/mdstcpip/mdsipshr/GetAnswerInfo.c index 4242817cc5..666590e90d 100644 --- a/mdstcpip/mdsipshr/GetAnswerInfo.c +++ b/mdstcpip/mdsipshr/GetAnswerInfo.c @@ -51,7 +51,7 @@ __attribute__((deprecated)) int GetAnswerInfo(int id, char *dtype, // GetAnswerInfoTS /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -inline int GetAnswerInfoTS(int id, char *dtype, short *length, char *ndims, +int GetAnswerInfoTS(int id, char *dtype, short *length, char *ndims, int *dims, int *numbytes, void **dptr, void **mout) { return GetAnswerInfoTO(id, dtype, length, ndims, dims, numbytes, dptr, mout, diff --git a/python/MDSplus/apd.py b/python/MDSplus/apd.py index f51c8a0fb5..f9066a2c6b 100644 --- a/python/MDSplus/apd.py +++ b/python/MDSplus/apd.py @@ -92,7 +92,7 @@ def __init__(self, value=None, dtype=0): self.dtype_id = dtype self._descs = [] if value is not None: - if isinstance(value, (Apd, tuple, list, _ver.mapclass, _ver.generator, _N.ndarray)): + if isinstance(value, _ver.listlike): for val in value: self.append(_dat.Data(val)) else: @@ -116,7 +116,7 @@ def value(self): def _value(self): """Returns native representation of the List""" return _N.asarray(tuple(d.value for d in self._descs), 'object') - +_ver.listlike = tuple(set(_ver.listlike).union(set((Apd,)))) class Dictionary(dict, Apd): """dictionary class""" diff --git a/python/MDSplus/mdsdata.py b/python/MDSplus/mdsdata.py index 846b53731c..e8df4e02db 100644 --- a/python/MDSplus/mdsdata.py +++ b/python/MDSplus/mdsdata.py @@ -928,7 +928,7 @@ def getDescAt(self, idx): """ if isinstance(idx, (slice,)): return self._descs[idx] - if idx < len(self.descs): + if isinstance(idx, int) and idx < len(self.descs): return self._descs[idx] return None diff --git a/python/MDSplus/tests/Makefile.am b/python/MDSplus/tests/Makefile.am index 8ea830c290..46a3b15a6c 100644 --- a/python/MDSplus/tests/Makefile.am +++ b/python/MDSplus/tests/Makefile.am @@ -11,15 +11,52 @@ TEST_EXTENSIONS = .py TEST_FLAGS = @MAKEFLAG_J@ -# simulateSegfault.py TESTS = \ - dataUnitTest.py \ - treeUnitTest.py \ - segmentsUnitTest.py \ - taskUnitTest.py \ - connectionUnitTest.py \ - dclUnitTest.py \ - threadsUnitTest.py +data_data_test.py \ +data_scalars_test.py \ +data_arrays_test.py \ +data_vms_test.py \ +data_tdi_test.py \ +data_decompile_test.py \ +data_casts_test.py \ +data_tdipy_test.py \ +devices_mit_test.py \ +devices_rfx_test.py \ +devices_w7x_test.py \ +exception_default_test.py \ +exception_custom_test.py \ +exception_tcl_test.py \ +exception_segfault_test.py \ +segment_dim_order_test.py \ +segment_block_rows_test.py \ +segment_write_test.py \ +segment_opaque_test.py \ +segment_update_test.py \ +segment_time_context_test.py \ +segment_scaled_test.py \ +segment_dimless_test.py \ +segment_compress_test.py \ +segment_compress_ts_test.py \ +task_do_test.py \ +tree_attr_test.py \ +tree_open_test.py \ +tree_node_test.py \ +tree_find_test.py \ +tree_default_test.py \ +tree_linkage_test.py \ +tree_nci_test.py \ +tree_data_test.py \ +tree_xysignal_test.py \ +tree_compression_test.py \ +tree_records_test.py \ +connection_io_test.py \ +connection_thick_test.py \ +connection_thread_test.py \ +connection_tunnel_test.py \ +connection_tcp_test.py \ +dcl_interface_test.py \ +dcl_dispatcher_test.py + VALGRIND_SUPPRESSIONS_FILES = @@ -29,7 +66,7 @@ VALGRIND_FLAGS = --trace-children-skip=*/ld,*/collect2,*/ldconfig,*/sh # Files produced by tests that must be purged # -MOSTLYCLEANFILES = *.log +MOSTLYCLEANFILES = *.log *.trs ## ////////////////////////////////////////////////////////////////////////// ## ## // TARGETS ////////////////////////////////////////////////////////////// ## diff --git a/python/MDSplus/tests/_UnitTest.py b/python/MDSplus/tests/_common.py old mode 100755 new mode 100644 similarity index 79% rename from python/MDSplus/tests/_UnitTest.py rename to python/MDSplus/tests/_common.py index c482b42271..a68fb2f23f --- a/python/MDSplus/tests/_UnitTest.py +++ b/python/MDSplus/tests/_common.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -24,7 +23,8 @@ # from unittest import TestCase, TestSuite, TextTestRunner -from MDSplus import Tree, getenv, setenv, tcl, TreeWRITEFIRST, TreeNOT_OPEN +from MDSplus import Tree, getenv, setenv, tcl, Connection +from MDSplus import checkStatus, TreeWRITEFIRST, TreeNOT_OPEN import traceback import threading import re @@ -83,15 +83,28 @@ def check(self): traceback.print_tb(self.exc.__traceback__) raise self.exc + class Tests(TestCase): debug = False is_win = sys.platform.startswith('win') in_valgrind = 'VALGRIND' in os.environ inThread = False index = 0 + NOT_IN_THREADS = set() + TESTS = set() + + @classmethod + def getTests(cls): + if cls.__module__.endswith("_test"): + _, test=cls.__module__[:-5].split('_', 1) + return [test] + if not cls.inThread: + return list(cls.TESTS) + return list(cls.TESTS.difference(cls.NOT_IN_THREADS)) @property - def module(self): return self.__module__.split('.')[-1] + def module(self): + return self.__module__.split('.')[-1] def assertEqual(self, fst, snd, *a, **kv): if isinstance(fst, str): @@ -171,37 +184,41 @@ def runWithObjgraph(cls, tests=None): a, '__del__')], filename='%s.png' % __file__[:-3]) @classmethod - def main(cls, _name_): - if _name_ == '__main__': + def main(cls): + cls.maxDiff = None # show full diffs + if cls.__module__ == '__main__': + cls.__module__ = os.path.basename(sys.argv[0]).split('.', 1)[0] if len(sys.argv) == 2 and sys.argv[1] == 'all': cls.runTests() elif len(sys.argv) > 1: cls.runTests(sys.argv[1:]) + elif cls.__module__.endswith("_test"): + cls.runTests() else: print('Available tests: %s' % (' '.join(cls.getTests()))) - envx = {} - env = {} + envx={} + env={} @classmethod def _setenv(cls, name, value): - value = str(value) - cls.env[name] = value - cls.envx[name] = value + value=str(value) + cls.env[name]=value + cls.envx[name]=value setenv(name, value) class MdsIp(object): - root = os.path.dirname(os.path.realpath(__file__)) + root=os.path.dirname(os.path.realpath(__file__)) @staticmethod def _setup_mdsip(server_env, port_env, default_port, fix0): - host = getenv(server_env, '') + host=getenv(server_env, '') if len(host) > 0: return host, 0 - port = int(getenv(port_env, default_port)) + port=int(getenv(port_env, default_port)) if port == 0: if fix0: - port = default_port + port=default_port else: return None, 0 return 'localhost:%d' % (port,), port @@ -215,12 +232,12 @@ def _testDispatchCommandNoWait(self, mdsip, command, stdout=None, stderr=None): (mdsip, command)) def _checkIdle(self, server, **opt): - show_server = "Checking server: %s\n[^,]+, [^,]+, logging enabled, Inactive\n" % server + show_server="Checking server: %s\n[^,]+, [^,]+, logging enabled, Inactive\n" % server self._doTCLTest('show server %s' % server, out=show_server, regex=True, **opt) def _waitIdle(self, server, timeout): - timeout = time.time()+timeout + timeout=time.time()+timeout while 1: time.sleep(.3) try: @@ -236,11 +253,12 @@ def _wait(self, svr, to): if to <= 0: return svr.poll() if sys.version_info < (3, 3): - for i in range(int(10*to)): - rtn = svr.poll() + rtn=svr.poll() + for _ in range(int(10*to)): if rtn is not None: break time.sleep(.1) + rtn=svr.poll() return rtn try: svr.wait(to) @@ -258,9 +276,9 @@ def _stop_mdsip(self, *procs_in): except: pass # filter external mdsip - procs = [(svr, server) for svr, server in procs_in if svr is not None] - procs = [(svr, server) for svr, server in procs if svr.poll() - is None] # filter terminated + procs=[(svr, server) for svr, server in procs_in if svr is not None] + # filter terminated + procs=[(svr, server) for svr, server in procs if svr.poll() is None] if len(procs) == 0: return # stop server @@ -269,8 +287,8 @@ def _stop_mdsip(self, *procs_in): self._doTCLTest('stop server %s' % server) except: pass - t = time.time()+6 - procs = [(svr, server) + t=time.time()+6 + procs=[(svr, server) for svr, server in procs if self._wait(svr, t-time.time()) is None] if len(procs) == 0: return @@ -278,8 +296,8 @@ def _stop_mdsip(self, *procs_in): for svr, server in procs: sys.stderr.write("sending SIGTERM to %s" % server) svr.terminate() - t = time.time()+3 - procs = [(svr, server) + t=time.time()+3 + procs=[(svr, server) for svr, server in procs if self._wait(svr, t-time.time()) is None] if len(procs) == 0: return @@ -287,51 +305,48 @@ def _stop_mdsip(self, *procs_in): for svr, server in procs: sys.stderr.write("sending SIGKILL to %s" % server) svr.kill() - t = time.time()+3 - procs = [server for svr, server in procs if self._wait( + t=time.time()+3 + procs=[server for svr, server in procs if self._wait( svr, t-time.time()) is None] if len(procs) == 0: return - raise Exception("FALIED cleaning up mdsips: %s" % (", ".join(procs),)) + raise Exception("FAILED cleaning up mdsips: %s" % (", ".join(procs),)) def _start_mdsip(self, server, port, logname, protocol='TCP'): if port > 0: from subprocess import Popen, STDOUT - logfile = '%s-%s%d.log' % (self.module, logname, self.index) - log = open(logfile, 'w') + logfile='%s-%s%d.log' % (self.module, logname, self.index) + log=open(logfile, 'w') try: - hosts = '%s/mdsip.hosts' % self.root - params = ['mdsip', '-s', '-p', + hosts='%s/mdsip.hosts' % self.root + params=['mdsip', '-s', '-p', str(port), '-P', protocol, '-h', hosts] print(' '.join(params+['>', logfile, '2>&1'])) - mdsip = Popen(params, stdout=log, stderr=STDOUT) + mdsip=Popen(params, stdout=log, stderr=STDOUT) except: log.close() raise time.sleep(.3) self._waitIdle(server, 10) # allow mdsip to launch - for envpair in self.envx.items(): - self._testDispatchCommandNoWait(server, 'env %s=%s' % envpair) - self._testDispatchCommand(server, 'set verify') - return mdsip, log - if server: - self._checkIdle(server) - for envpair in self.envx.items(): - self._testDispatchCommandNoWait(server, 'env %s=%s' % envpair) - self._testDispatchCommand(server, 'set verify') - return None, None + else: + mdsip, log=None, None + c=Connection(server) + for envpair in self.envx.items(): + checkStatus(c.get('setenv($//"="//$)', *envpair)) + c.get('tcl($)', 'set verify') + return mdsip, log class TreeTests(Tests): - lock = threading.RLock() - shotinc = 1 - instances = 0 - trees = [] - tree = None + lock=threading.RLock() + shotinc=1 + instances=0 + trees=[] + tree=None @property def shot(self): - return self.index*self.__class__.shotinc+1 + return self.index * self.__class__.shotinc + 1 @classmethod def setUpClass(cls): @@ -340,20 +355,19 @@ def setUpClass(cls): gc.collect() from tempfile import mkdtemp if getenv("TEST_DISTRIBUTED_TREES") is not None: - treepath = "localhost::%s" + treepath="thread://tree::%s" else: - treepath = "%s" - cls.tmpdir = mkdtemp() - cls.root = os.path.dirname(os.path.realpath(__file__)) - cls.topsrc = os.path.realpath( + treepath="%s" + cls.tmpdir=mkdtemp() + cls.root=os.path.dirname(os.path.realpath(__file__)) + cls.topsrc=os.path.realpath( cls.root+"%s..%s..%s.." % tuple([os.sep]*3)) - cls.env = dict((k, str(v)) for k, v in os.environ.items()) - cls.envx = {} + cls.env=dict((k, str(v)) for k, v in os.environ.items()) + cls.envx={} cls._setenv('PyLib', getenv('PyLib')) cls._setenv("MDS_PYDEVICE_PATH", '%s/pydevices;%s/devices' % (cls.topsrc, cls.root)) - trees = cls.trees if cls.tree is None else cls.trees + \ - [cls.tree] + trees = cls.trees if cls.tree is None else set(cls.trees).union([cls.tree]) for treename in trees: cls._setenv("%s_path" % treename, treepath % cls.tmpdir) if getenv("testing_path") is None: @@ -380,7 +394,7 @@ def is_tree(o): except Exception as e: print(e) return False - trees = [o for o in gc.get_objects() if is_tree(o)] + trees=[o for o in gc.get_objects() if is_tree(o)] for t in trees: try: t.close() diff --git a/python/MDSplus/tests/connectionUnitTest.py b/python/MDSplus/tests/connection_case.py similarity index 72% rename from python/MDSplus/tests/connectionUnitTest.py rename to python/MDSplus/tests/connection_case.py index 52ea16547b..02f42738f7 100755 --- a/python/MDSplus/tests/connectionUnitTest.py +++ b/python/MDSplus/tests/connection_case.py @@ -28,7 +28,9 @@ import subprocess import tempfile import time -from MDSplus import Connection, GetMany, Float32, Range, setenv, Tree, TreeNNF, ADD + +from MDSplus import Connection, GetMany +from MDSplus import Int32, Float32, ADD, Range, setenv, Tree, TreeNNF def _mimport(name, level=1): @@ -38,12 +40,15 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") + -class Tests(_UnitTest.TreeTests, _UnitTest.MdsIp): +class Tests(_common.TreeTests, _common.MdsIp): index = 0 - trees = ["pysub"] - tree = "pytree" + trees = ["consub"] + tree = "con" + treesub = "consub" + TESTS = {'io', 'thick', 'thread', 'tunnel', 'tcp', 'write'} def thick(self): def testnci(thick, local, con, nci): @@ -64,7 +69,7 @@ def testnci(thick, local, con, nci): print(nci, t, l, c) raise server, server_port = self._setup_mdsip( - 'ACTION_SERVER', 'ACTION_PORT', 7100+self.index, True) + 'ACTION_SERVER', 'ACTION_PORT', 7000+self.index, True) svr = svr_log = None try: svr, svr_log = self._start_mdsip(server, server_port, 'thick') @@ -73,7 +78,7 @@ def testnci(thick, local, con, nci): self.assertEqual(con.get("zero([1,1,1,1,1,1,1,1],1)").tolist(), [ [[[[[[[0]]]]]]]]) with Tree(self.tree, -1, "new") as local: - local.addNode("pysub", "SUBTREE") + local.addNode(self.treesub, "SUBTREE") s = local.addNode("S", "SIGNAL") s.addTag("tagS") s.record = ADD(Float32(1), Float32(2)) @@ -82,20 +87,24 @@ def testnci(thick, local, con, nci): t.record = t.TT t.TT = "recTT" local.write() - with Tree(self.trees[0], -1, "new") as sub: + with Tree(self.treesub, -1, "new") as sub: sub.addNode("OK") sub.write() local.normal() Tree.setCurrent(self.tree, 7) - setenv("pytree_path", "%s::" % server) + setenv("%s_path" % self.tree, "%s::" % server) print(con.get("getenv($//'_path')", self.tree)) con.get("TreeShr->TreeOpen(ref($),val($),val(1))", self.tree, -1) thick = Tree(self.tree, -1) thick.createPulse(1) thick1 = Tree(self.tree, 1) - self.assertEqual(local.PYSUB.OK.nid, thick1.PYSUB.OK.nid) - self.assertEqual(local.getFileName(), - thick.getFileName().split("::", 2)[1]) + self.assertEqual( + getattr(local, self.treesub.upper()).OK.nid, + getattr(thick1, self.treesub.upper()).OK.nid) + local_filename = local.getFileName() + thick_filename = thick.getFileName() + self.assertTrue("::" in thick_filename, thick_filename) + self.assertTrue(local_filename, thick_filename.split("::", 1)[1]) """ TreeTurnOff / TreeTurnOn """ thick.S.on = False self.assertEqual(local.S.on, False) @@ -124,7 +133,11 @@ def testnci(thick, local, con, nci): """ nci """ thick.S.write_once = True self.assertEqual(thick.S.write_once, True) - for nci in ('on', 'depth', 'usage_str', 'dtype', 'length', 'rlength', 'fullpath', 'minpath', 'member_nids', 'children_nids', 'rfa', 'write_once'): + for nci in ( + 'on', 'depth', 'usage_str', 'dtype', 'length', + 'rlength', 'fullpath', 'minpath', 'member_nids', + 'children_nids', 'rfa', 'write_once', + ): testnci(thick, local, con, nci) """ new stuff """ self.assertEqual(local.getFileName(), con.get( @@ -135,38 +148,43 @@ def testnci(thick, local, con, nci): if svr_log: svr_log.close() - def threadsTcp(self): + def io(self): + connection = Connection("thread://io") + """ mdsconnect """ + self.assertEqual(connection.get('_a=1').tolist(), 1) + self.assertEqual(connection.get('_a').tolist(), 1) + self.assertEqual(connection.getObject('1:3:1').__class__, Range) + g = GetMany(connection) + g.append('a', '1') + g.append('b', '$', 2) + g.append('c', '$+$', 1, 2) + g.execute() + self.assertEqual(g.get('a'), 1) + self.assertEqual(g.get('b'), 2) + self.assertEqual(g.get('c'), 3) + + def _thread_test(self, server): + def requests(self, c, idx): + args = [Int32(i+idx+10) for i in range(10)] + for _ in range(20): + self.assertEqual( + c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(), args) + connection = Connection(server) + _common.TestThread.assertRun(*( + _common.TestThread("T%d" % idx, requests, self, connection, idx) + for idx in range(5) + )) + + def tcp(self): server, server_port = self._setup_mdsip( - 'ACTION_SERVER', 'ACTION_PORT', 7100+self.index, True) + 'ACTION_SERVER', 'ACTION_PORT', 7010+self.index, True) svr = svr_log = None try: svr, svr_log = self._start_mdsip(server, server_port, 'tcp') try: if svr is not None: time.sleep(1) - - def requests(c, idx): - args = [Float32(i/10+idx) for i in range(10)] - for _ in range(10): - self.assertEqual( - c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(), args) - c = Connection(server) - """ mdsconnect """ - self.assertEqual(c.get('_a=1').tolist(), 1) - self.assertEqual(c.get('_a').tolist(), 1) - self.assertEqual(c.getObject('1:3:1').__class__, Range) - g = GetMany(c) - g.append('a', '1') - g.append('b', '$', 2) - g.append('c', '$+$', 1, 2) - g.execute() - self.assertEqual(g.get('a'), 1) - self.assertEqual(g.get('b'), 2) - self.assertEqual(g.get('c'), 3) - _UnitTest.TestThread.assertRun(*( - _UnitTest.TestThread("C%d" % i, requests, c, i) - for i in range(10) - )) + self._thread_test(server) finally: if svr and svr.poll() is None: svr.terminate() @@ -175,18 +193,13 @@ def requests(c, idx): if svr_log: svr_log.close() - def threadsLocal(self): - connection = Connection('local://gub') - def test(s, c): - for i in range(1000): - s.assertEqual(int(c.get('%d' % i)), i) - _UnitTest.TestThread.assertRun(*( - _UnitTest.TestThread("C%d" % i, test, self, connection) - for i in range(10) - )) + def tunnel(self): + self._thread_test('local://threads') + def thread(self): + self._thread_test('thread://threads') - def fast_remote_write(self): + def write(self): count = 100 def mdsip(hostfile): @@ -218,6 +231,7 @@ def thread(test, name, node, count): server = mdsip(os.path.join(tempdir, "mdsip.hosts")) try: con = Connection('127.0.0.1') + def check(line, *args): sts = con.get(line, *args) self.assertTrue(sts & 1, "error %d in '%s'" % (sts, line)) @@ -232,9 +246,11 @@ def check(line, *args): check(line) setenv("test_path", "127.0.0.1::" + tempdir) tree = Tree("test", 1) - _UnitTest.TestThread.assertRun( - _UnitTest.TestThread('EV1', thread, self, 'EV1', tree.EV1.copy(), count), - _UnitTest.TestThread('EV2', thread, self, 'EV2', tree.EV2.copy(), count), + _common.TestThread.assertRun( + _common.TestThread('EV1', thread, self, + 'EV1', tree.EV1.copy(), count), + _common.TestThread('EV2', thread, self, + 'EV2', tree.EV2.copy(), count), ) finally: if server: @@ -243,9 +259,5 @@ def check(line, *args): finally: shutil.rmtree(tempdir, ignore_errors=False, onerror=None) - @staticmethod - def getTests(): - return ['threadsTcp', 'threadsLocal', 'thick'] - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/dataUnitTest.py b/python/MDSplus/tests/data_case.py similarity index 95% rename from python/MDSplus/tests/dataUnitTest.py rename to python/MDSplus/tests/data_case.py index 31124b6016..e153de3e1a 100755 --- a/python/MDSplus/tests/dataUnitTest.py +++ b/python/MDSplus/tests/data_case.py @@ -35,10 +35,15 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.Tests): +class Tests(_common.Tests): + TESTS = { + 'data', 'scalars', 'arrays', 'vms', + 'tdi', 'decompile', 'casts', 'tdipy', + } + def _doThreeTest(self, tdiexpr, pyexpr, ans, **kwargs): """ tests Scalars tdi expression vs. python Expression vs. expected result """ almost = kwargs.get('almost', False) @@ -172,18 +177,19 @@ def scalars(self): def doTest(suffix, cl, scl, ucl, **kw): """ test scalar """ import warnings - results = [cl(13), cl(7), cl(30), cl(10./3), cl(1000), - ucl(11), ucl(2), - False, True, - cl(80), cl(1), scl(-10), scl(10), scl(10), scl(100), - cl(22026.4658), cl(2.30258509), - cl(-0.54402111), cl(-0.83907153), cl(0.64836083), - cl(1.57079633), cl(0.), cl(1.47112767), cl(1.47112767), - cl(3.32192809), cl(1.), - cl(0.17364818), cl(0.98480775), cl(0.17632698), - cl(3), - cl(1), True, True, False, False, - ] + results = [ + cl(13), cl(7), cl(30), cl(10./3), cl(1000), + ucl(11), ucl(2), + False, True, + cl(80), cl(1), scl(-10), scl(10), scl(10), scl(100), + cl(22026.4658), cl(2.30258509), + cl(-0.54402111), cl(-0.83907153), cl(0.64836083), + cl(1.57079633), cl(0.), cl(1.47112767), cl(1.47112767), + cl(3.32192809), cl(1.), + cl(0.17364818), cl(0.98480775), cl(0.17632698), + cl(3), + cl(1), True, True, False, False, + ] m.Data.execute('_a=10%s,_b=3%s' % tuple([suffix]*2)) a, b = cl(10), cl(3) with warnings.catch_warnings(): @@ -276,7 +282,7 @@ def Sucl(v): return m.Signal(ucl(v)) doTest('*cmplx(1D0,0D0)', m.Complex128Array, m.Complex128Array, m.Uint64Array, almost=7, real=False) - def vmsSupport(self): + def vms(self): self.assertEqual(str(m.TdiExecute('1.23F0')), "1.23") self.assertEqual(str(m.TdiExecute('1.23V0')), "1.23D0") self.assertEqual(str(m.TdiExecute('1.23G0')), "1.23D0") @@ -302,7 +308,7 @@ def _doTdiTest(self, expr, res): else: self.assertEqual(m.Data.execute(expr), res) - def tdiFunctions(self): + def tdi(self): from MDSplus import mdsExceptions as Exc """Test Exceptions""" self._doExceptionTest('abort()', Exc.TdiABORT) @@ -431,7 +437,7 @@ def decompile(self): self.assertEqual(str(m.Signal(m.ZERO(100000, 0.).evaluate( ), None, 0.)), "Build_Signal(Set_Range(100000,0D0 /*** etc. ***/), *, 0D0)") - def python_casts(self): + def casts(self): for WITH in (m.WithError, m.Parameter, m.WithUnits): data = WITH(1, "with") self.assertEqual(int(data), 1, WITH) @@ -441,7 +447,7 @@ def python_casts(self): self.assertEqual(str(data), "1", WITH) self.assertEqual(bytes(data), b"1", WITH) - def tdiPythonInterface(self): + def tdipy(self): self._doTdiTest("Py('a=None')", 1) self._doTdiTest("Py('a=None','a')", None) self._doTdiTest("Py('a=123','a')", 123) @@ -457,9 +463,5 @@ def tdiPythonInterface(self): if not self.inThread: self._doTdiTest("TEST()", m.Array([1, 2])) - @staticmethod - def getTests(): - return ['data', 'scalars', 'arrays', 'vmsSupport', 'tdiFunctions', 'decompile', 'python_casts', 'tdiPythonInterface'] - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/dclUnitTest.py b/python/MDSplus/tests/dcl_case.py similarity index 84% rename from python/MDSplus/tests/dclUnitTest.py rename to python/MDSplus/tests/dcl_case.py index 12c88799ca..8052b2af82 100755 --- a/python/MDSplus/tests/dclUnitTest.py +++ b/python/MDSplus/tests/dcl_case.py @@ -24,7 +24,6 @@ # import sys -from time import sleep from MDSplus import Tree, Device, Connection from MDSplus import dcl, ccl, tcl, cts, mdsExceptions as Exc @@ -36,15 +35,22 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.TreeTests, _UnitTest.MdsIp): - shotinc = 1 - tree = 'pytree' +class Tests(_common.TreeTests, _common.MdsIp): + shotinc = 2 + tree = 'dcl' + NOT_IN_THREADS = {'dispatcher'} + TESTS = {'interface', 'dispatcher'} def interface(self): - with Tree(self.tree, self.shot, 'new') as pytree: + shot = self.shot + 0 + fmt = { + 'EXPT': self.tree.upper(), + 'SHOT': shot, + } + with Tree(self.tree, shot, 'new') as pytree: Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE_I') Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE_S') pytree.write() @@ -64,10 +70,10 @@ def interface(self): Tree.usePrivateCtx(1) self._doTCLTest('close/all') self._doTCLTest('show db', '\n') - self._doTCLTest('set tree pytree/shot=%d' % (self.shot,)) + self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) self._doTCLTest( - 'show db', '000 PYTREE shot: %d [\\PYTREE::TOP] \n\n' % self.shot) - self._doTCLTest('edit PYTREE/shot=%d' % (self.shot,)) + 'show db', '000\\s+%(EXPT)s\\s+shot:\\s+%(SHOT)d\\s+\\[\\\\%(EXPT)s::TOP\\]\\s+\n\n' % fmt, regex=True) + self._doTCLTest('edit %(EXPT)s/shot=%(SHOT)d' % fmt) self._doTCLTest('add node TCL_NUM/usage=numeric') self._doTCLTest('add node TCL_PY_DEV/model=TESTDEVICE') self._doTCLTest('do TESTDEVICE_I:TASK_TEST') @@ -86,10 +92,10 @@ def interface(self): self._doTCLTest('close') self._doTCLTest('show db', '\n') """ context """ - self._doTCLTest('set tree pytree/shot=%d' % (self.shot,)) + self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) pytree = Tree() - self.assertEqual(str(pytree), 'Tree("PYTREE",%d,"Normal")' % self.shot) - self._doTCLTest('close pytree/shot=%d' % (self.shot,)) + self.assertEqual(str(pytree), 'Tree("%(EXPT)s",%(SHOT)d,"Normal")' % fmt) + self._doTCLTest('close %(EXPT)s/shot=%(SHOT)d' % fmt) self.assertEqual(str(pytree), 'Tree("?",?,"Closed")') if self.inThread: Tree.usePrivateCtx(0) @@ -101,17 +107,22 @@ def interface(self): 'dispatch/command/server type test', Exc.MdsdclIVVERB) def dispatcher(self): - shot = self.shot+1 + shot = self.shot + 1 + fmt = { + 'EXPT': self.tree.upper(), + 'SHOT': shot, + } + print(self.envx) with Tree(self.tree, shot, 'new') as pytree: Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE_I') Device.PyDevice('TestDevice').Add( pytree, 'TESTDEVICE_S', add_source=True) pytree.write() monitor, monitor_port = self._setup_mdsip( - 'ACTION_MONITOR', 'MONITOR_PORT', 7010+self.index, False) + 'ACTION_MONITOR', 'MONITOR_PORT', 7100+self.index, False) monitor_opt = "/monitor=%s" % monitor if monitor_port > 0 else "" server, server_port = self._setup_mdsip( - 'ACTION_SERVER', 'ACTION_PORT', 7000+self.index, True) + 'ACTION_SERVER', 'ACTION_PORT', 7110+self.index, True) pytree.normal() pytree.TESTDEVICE_I.ACTIONSERVER.no_write_shot = False pytree.TESTDEVICE_I.ACTIONSERVER.record = server @@ -127,16 +138,11 @@ def dispatcher(self): self.assertEqual(mon.poll(), None) if svr: self.assertEqual(svr.poll(), None) - # Connection(server).get("""py("MDSplus.Device.PyDevice('TestDevice')","None")""") """ tcl dispatch """ self._testDispatchCommand(server, 'type test') - self._doTCLTest('set tree pytree/shot=%d' % shot) - # if not self.in_valgrind: - # self._doTCLTest('dispatch TESTDEVICE_S:ACTIONSERVER:MANUAL') - # self._waitIdle(server,3) - # else: - # sys.stdout.write("VALGRIND: skipping 'dispatch TESTDEVICE_S:ACTIONSERVER:MANUAL'\n") - # sys.stdout.flush() + env = "%s_path" % self.tree + self._doTCLTest('env '+ env, '%s=%s\n' % (env, self.envx[env])) + self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) self._doTCLTest('dispatch/build%s' % monitor_opt) self._doTCLTest('dispatch/phase%s INIT' % monitor_opt) self._waitIdle(server, 3) @@ -161,8 +167,6 @@ def dispatcher(self): mon_log.close() self._doTCLTest('close/all') pytree.readonly() - # if not self.in_valgrind: - # self.assertTrue(pytree.TESTDEVICE_S.MANUAL_DONE.record<= pytree.TESTDEVICE_S.INIT1_DONE.record) self.assertTrue(pytree.TESTDEVICE_I.INIT1_DONE.record <= pytree.TESTDEVICE_I.INIT2_DONE.record) self.assertTrue(pytree.TESTDEVICE_S.INIT1_DONE.record <= @@ -192,7 +196,7 @@ def test_normal(c, expr, **kv): print(expr) c.get(expr, **kv) server, server_port = self._setup_mdsip( - 'ACTION_SERVER', 'ACTION_PORT', 7000+self.index, True) + 'ACTION_SERVER', 'ACTION_PORT', 7120+self.index, True) svr = svr_log = None try: svr, svr_log = self._start_mdsip(server, server_port, 'timeout') @@ -222,13 +226,5 @@ def test_normal(c, expr, **kv): def timeoutfull(self): self.timeout(full=True) - @staticmethod - def getTests(): - lst = ['interface'] - if Tests.inThread: - return lst - lst.append('dispatcher') - return lst - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/devicesUnitTest.py b/python/MDSplus/tests/devices_case.py similarity index 80% rename from python/MDSplus/tests/devicesUnitTest.py rename to python/MDSplus/tests/devices_case.py index 84817745d8..29c691d900 100755 --- a/python/MDSplus/tests/devicesUnitTest.py +++ b/python/MDSplus/tests/devices_case.py @@ -23,7 +23,8 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -from MDSplus import Tree, Device, tdi +import unittest +from MDSplus import Tree, Device, tdi, TreeNNF def _mimport(name, level=1): @@ -33,11 +34,12 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.TreeTests): - tree = 'devtree' +class Tests(_common.TreeTests): + tree = 'devices' + TESTS = {'mit', 'rfx', 'w7x'} @staticmethod def getNodeName(t, model): @@ -53,13 +55,13 @@ def getNodeName(t, model): return node, model try: node = node.getNode(base) - except: + except TreeNNF: node = node.addNode(base, 'STRUCTURE') else: name = model return node, name - def DevicesTests(self, package): + def _add_devices(self, package): with Tree(self.tree, self.shot, 'new') as t: devices = __import__(package).__dict__ for model in sorted(devices.keys()): @@ -68,7 +70,7 @@ def DevicesTests(self, package): node, name = self.getNodeName(t, model) cls.Add(node, name) - def XyzDevices(self, package, expected=None): + def _xyz_devices(self, package, expected=None): if expected is None: expected = [s for s in (str(s).strip() for s, p in tdi('%s()' % package))] @@ -86,21 +88,20 @@ def XyzDevices(self, package, expected=None): if Device.debug: print('FAILED %s' % model) self.assertEqual(passed, expected) - self.DevicesTests(package) + self._add_devices(package) - def MitDevices(self): - self.XyzDevices('MitDevices', ['CHS_A14', 'DC1394', 'DC1394A', 'DIO2', 'DT196AO', - 'DT200', 'DT_ACQ16', 'INCAA_TR10', 'JRG_ADC32A', 'JRG_TR1612', 'L6810', 'MATROX']) + def mit(self): + self._xyz_devices('MitDevices', [ + 'CHS_A14', 'DC1394', 'DC1394A', 'DIO2', 'DT196AO', + 'DT200', 'DT_ACQ16', 'INCAA_TR10', 'JRG_ADC32A', + 'JRG_TR1612', 'L6810', 'MATROX']) - def RfxDevices(self): - self.XyzDevices('RfxDevices') # check them all + @unittest.skip("not clean yet") + def rfx(self): + self._xyz_devices('RfxDevices', ) # check them all - def W7xDevices(self): - self.XyzDevices('W7xDevices', []) # no tdi devices to check - - @staticmethod - def getTests(): - return ['MitDevices', 'RfxDevices', 'W7xDevices'] + def w7x(self): + self._xyz_devices('W7xDevices', []) # no tdi devices to check -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/exceptionUnitTest.py b/python/MDSplus/tests/exception_case.py similarity index 78% rename from python/MDSplus/tests/exceptionUnitTest.py rename to python/MDSplus/tests/exception_case.py index 5fdd94007b..9fe292c48e 100755 --- a/python/MDSplus/tests/exceptionUnitTest.py +++ b/python/MDSplus/tests/exception_case.py @@ -23,8 +23,10 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +import sys +import unittest -from MDSplus import DevNOT_TRIGGERED, TclNORMAL +from MDSplus import TdiExecute, DevNOT_TRIGGERED, TclNORMAL def _mimport(name, level=1): @@ -34,11 +36,22 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.Tests): - def defaultErrorValues(self): +class Tests(_common.Tests): + TESTS = {'default', 'custom', 'tcl', 'segfault'} + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def segfault(self): + try: + TdiExecute('MdsShr->LibFindImageSymbol(val(0))') + except Exception as exc: + expected = 'exception: access violation reading 0x0000000000000000' + self.assertEqual(exc.__class__, WindowsError) + self.assertEqual(exc.message, expected[0:len(exc.message)]) + + def default(self): err = DevNOT_TRIGGERED() self.assertEqual(err.status, 662470754) self.assertEqual(err.severity, 'E') @@ -48,7 +61,7 @@ def defaultErrorValues(self): self.assertEqual(str( err), '%DEV-E-NOT_TRIGGERED, device was not triggered, check wires and triggering device') - def customErrorString(self): + def custom(self): err = DevNOT_TRIGGERED('This is a custom error string') self.assertEqual(err.status, 662470754) self.assertEqual(err.severity, 'E') @@ -57,15 +70,11 @@ def customErrorString(self): self.assertEqual( str(err), '%DEV-E-NOT_TRIGGERED, This is a custom error string') - def tclErrors(self): + def tcl(self): err = TclNORMAL() self.assertEqual(err.status, 2752521) self.assertEqual(err.severity, 'S') self.assertEqual(err.fac, 'Tcl') - @staticmethod - def getTests(): - return ['defaultErrorValues', 'customErrorString', 'tclErrors'] - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/segmentsUnitTest.py b/python/MDSplus/tests/segment_case.py similarity index 90% rename from python/MDSplus/tests/segmentsUnitTest.py rename to python/MDSplus/tests/segment_case.py index c4ffa41d80..81a037a55c 100755 --- a/python/MDSplus/tests/segmentsUnitTest.py +++ b/python/MDSplus/tests/segment_case.py @@ -24,7 +24,11 @@ # import os - +import numpy +from MDSplus import Int32, Int64, Float32 +from MDSplus import DateToQuad, Float32Array, Int16Array, Int32Array, Int64Array +from MDSplus import Tree, Dimension, Range, Window, DIVIDE, ADD, MULTIPLY, ZERO +from MDSplus import set_default_resample_mode, Opaque, tdi, TreeBUFFEROVF def _mimport(name, level=1): try: @@ -33,16 +37,19 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") -from MDSplus import setenv, set_default_resample_mode +_common = _mimport("_common") -class Tests(_UnitTest.TreeTests): +class Tests(_common.TreeTests): shotinc = 12 - tree = 'segments' + tree = 'segment' + TESTS = { + 'dim_order', 'block_rows', 'write', 'opaque', 'update', + 'time_context', 'scaled', 'dimless', 'compress', 'compress_ts', + } + - def ArrayDimensionOrder(self): - from MDSplus import Tree, Float32, Float32Array, Int16Array + def dim_order(self): from numpy import zeros with Tree(self.tree, self.shot+0, 'NEW') as ptree: @@ -51,19 +58,18 @@ def ArrayDimensionOrder(self): ptree.normal() WIDTH = 32 HEIGHT = 16 - currFrame = zeros((1, HEIGHT, WIDTH), 'int16').shape - currTime = float(0) - startTime = Float32(currTime) - endTime = Float32(currTime) - dim = Float32Array(currTime) - segment = Int16Array(currFrame) + curr_frame = zeros((1, HEIGHT, WIDTH), 'int16').shape + curr_time = float(0) + start_time = Float32(curr_time) + end_time = Float32(curr_time) + dim = Float32Array(curr_time) + segment = Int16Array(curr_frame) shape = segment.getShape() - node.makeSegment(startTime, endTime, dim, segment) - retShape = node.getShape() - self.assertEqual(shape, retShape) + node.makeSegment(start_time, end_time, dim, segment) + ret_shape = node.getShape() + self.assertEqual(shape, ret_shape) - def BlockAndRows(self): - from MDSplus import Tree, Int32Array + def block_rows(self): with Tree(self.tree, self.shot+1, 'NEW') as ptree: ptree.addNode('S') ptree.write() @@ -86,13 +92,12 @@ def BlockAndRows(self): self.assertEqual(str(node.getSegment(0)), "Build_Signal([1,7], *, [-1Q,0Q])") - def WriteSegments(self): + def write(self): def check_signal(node, dim, dat): signal = node.record self.assertEqual(dim, signal.dim_of().tolist()) self.assertEqual(dat, signal.data() .tolist()) - from MDSplus import Tree from numpy import array, zeros, int32 with Tree(self.tree, self.shot+2, 'NEW') as ptree: ptree.addNode('MS') @@ -190,8 +195,7 @@ def check_signal(node, dim, dat): self.assertEqual(node.getSegmentLimits(1), (10, 16)) check_signal(node, dim, dat) - def WriteOpaque(self): - from MDSplus import Tree, Opaque + def opaque(self): with Tree(self.tree, self.shot+3, 'NEW') as ptree: ptree.addNode('JPGS') ptree.addNode('JPG') @@ -218,15 +222,14 @@ def WriteOpaque(self): seg = node.getSegment(i) self.assertEqual(len(seg.value.value.data()), lens[i]) - def UpdateSegments(self): - from MDSplus import Tree, Int32, Int64, Dimension, Range, Window, DIVIDE, ADD, MULTIPLY + def update(self): from numpy import arange, ones, int16, int64 slp = 3.3 off = 1.1 trg = -1000000 clk = 1000000 with Tree(self.tree, self.shot+4, 'NEW') as ptree: - sig = ptree.addNode('SIG').record = ADD( + ptree.addNode('SIG').record = ADD( MULTIPLY(ptree.addNode('RAW'), ptree.addNode('SLP')), ptree.addNode('OFF')) ptree.addNode('TRG').record = Int64(trg) ptree.addNode('CLK').record = Int32(clk) @@ -267,8 +270,7 @@ def UpdateSegments(self): self.assertTrue(sig.dim_of().tolist(), (arange( 0, length, dtype=int64)*int(1e9/clk)).tolist()) - def TimeContext(self): - from MDSplus import Tree, Int64, Int64Array, Float32Array, tdi + def time_context(self): Tree.setTimeContext() # test initPinoDb self.assertEqual(Tree.getTimeContext(), (None, None, None)) with Tree(self.tree, self.shot+5, 'NEW') as ptree: @@ -351,8 +353,7 @@ def TimeContext(self): tdi('treeclose()') self.assertEqual(Tree.getTimeContext(), (2, 3, 4)) - def ScaledSegments(self): - from MDSplus import Tree, Int64, Int64Array, Int16Array + def scaled(self): with Tree(self.tree, self.shot+7, 'NEW') as ptree: node = ptree.addNode('S') ptree.write() @@ -376,21 +377,20 @@ def ScaledSegments(self): self.assertEqual(ptree.tdiExecute("S").decompile( ), "Build_Signal($VALUE + 1D0, Word([-1000,0,1000]), [-1000Q,0Q,1000Q])") - def DimensionlessSegments(self): - from MDSplus import Tree, Int32Array, numpy, TreeBUFFEROVF + def dimless(self): with Tree(self.tree, self.shot+8, 'NEW') as ptree: ptree.addNode('S') ptree.write() ptree.normal() node = ptree.S - len = 10 - seg0 = Int32Array(numpy.array(range(len))) + length = 10 + seg0 = Int32Array(numpy.array(range(length))) for i in range(10): - seg = seg0 + i*len - start, end = seg[0], seg[len-1] + seg = seg0 + i*length + start, end = seg[0], seg[length-1] node.makeSegment(start, end, None, seg) - seg = seg0 + 10*len - start, end = seg[0], seg[len-1] + seg = seg0 + 10*length + start, end = seg[0], seg[length-1] node.beginSegment(start, end, None, seg) node.putSegment(seg[0:1]) self.assertEqual(node.record.data() @@ -415,8 +415,7 @@ def DimensionlessSegments(self): ptree.setTimeContext(17, 21, None) self.assertEqual(node.record.data().tolist(), [17, 18, 19, 20, 21]) - def CompressSegments(self): - from MDSplus import Tree, DateToQuad, ZERO, Int32, Int32Array, Int64Array, Range + def compress(self): with Tree(self.tree, self.shot+9, 'NEW') as ptree: node = ptree.addNode('S') node.compress_on_put = False @@ -456,8 +455,7 @@ def CompressSegments(self): self.assertEqual(node.getSegmentDim(i).data().tolist(), node1.getSegmentDim(i).data().tolist()) - def CompressTimestampedSegments(self): - from MDSplus import Tree, Int32, Int64 + def compress_ts(self): with Tree(self.tree, self.shot+10, 'NEW') as ptree: s = ptree.addNode('s', 'SIGNAL') ptree.write() @@ -474,9 +472,5 @@ def CompressTimestampedSegments(self): self.assertEqual(True, (before.dim_of().data() == after.dim_of( ).data()).all(), "%r != %r" % (before.dim_of(), after.dim_of())) - @staticmethod - def getTests(): - return ['ArrayDimensionOrder', 'BlockAndRows', 'WriteSegments', 'WriteOpaque', 'UpdateSegments', 'TimeContext', 'ScaledSegments', 'DimensionlessSegments', 'CompressSegments', 'CompressTimestampedSegments'] - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/simulateSegfault.py b/python/MDSplus/tests/simulateSegfault.py deleted file mode 100644 index 69578c14ee..0000000000 --- a/python/MDSplus/tests/simulateSegfault.py +++ /dev/null @@ -1,59 +0,0 @@ -# -# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# Redistributions in binary form must reproduce the above copyright notice, this -# list of conditions and the following disclaimer in the documentation and/or -# other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -# This test is meant to intentionally rise a segmentation fault within the -# mdsplus libraries to see if the python test library can manage it. -# -import sys -from MDSplus import Data - - -def _mimport(name, level=1): - try: - return __import__(name, globals(), level=level) - except: - return __import__(name, globals()) - - -_UnitTest = _mimport("_UnitTest") - - -class Tests(_UnitTest.Tests): - def generateSegFault(self): - try: - Data.execute('MdsShr->LibFindImageSymbol(val(0))') - except Exception as exc: - expected = 'exception: access violation reading 0x0000000000000000' - self.assertEqual(exc.__class__, WindowsError) - self.assertEqual(exc.message, expected[0:len(exc.message)]) - - @staticmethod - def getTests(): - if sys.platform.startswith("win"): - return ['generateSegFault'] - return [] - - -Tests.main(__name__) diff --git a/python/MDSplus/tests/taskUnitTest.py b/python/MDSplus/tests/task_case.py similarity index 91% rename from python/MDSplus/tests/taskUnitTest.py rename to python/MDSplus/tests/task_case.py index 691d285dcc..76438e487c 100755 --- a/python/MDSplus/tests/taskUnitTest.py +++ b/python/MDSplus/tests/task_case.py @@ -33,14 +33,15 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.TreeTests): +class Tests(_common.TreeTests): shotinc = 1 - tree = 'pytree' + tree = 'task' + TESTS = {'do'} - def dotask_timeout(self): + def do(self): with Tree(self.tree, self.shot, 'new') as tree: Device.PyDevice('TestDevice').Add(tree, 'TESTDEVICE') tree.write() @@ -54,9 +55,6 @@ def dotask_timeout(self): 'do TESTDEVICE:TASK_ERROR2', Exc.DevUNKOWN_STATE, tree) self._doExceptionTest( 'do TESTDEVICE:TASK_TIMEOUT', Exc.TdiTIMEOUT, tree) - @staticmethod - def getTests(): - return ['dotask_timeout'] -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/threadsUnitTest.py b/python/MDSplus/tests/thread_case.py similarity index 57% rename from python/MDSplus/tests/threadsUnitTest.py rename to python/MDSplus/tests/thread_case.py index 93e4bafe5b..ddff71c0a8 100755 --- a/python/MDSplus/tests/threadsUnitTest.py +++ b/python/MDSplus/tests/thread_case.py @@ -38,45 +38,49 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") - - -class threadJob(Thread): - def __init__(self, testclass, test, idx): - super(threadJob, self).__init__() - self.test = testclass(test) - self.test.index = idx - """Thread to execute the treeTests""" - - def run(self): - """Run test1.test() function""" - # Tree.usePrivateCtx() - stream = StringIO() - try: - self.result = TextTestRunner( - stream=stream, verbosity=2).run(self.test) - finally: - stream.seek(0) - self.stream = stream.read() - stream.close() - - -class Tests(_UnitTest.Tests): - def doThreadsTestCase(self, testclass, test, numthreads): +_common = _mimport("_common") + + +class Tests(_common.Tests): + TESTS = {'data', 'dcl', 'segment', 'task', 'tree'} + + class Job(Thread): + def __init__(self, testclass, test, idx): + super(Tests.Job, self).__init__() + self.test = testclass(test) + self.test.index = idx + """Thread to execute the treeTests""" + + def run(self): + """Run test1.test() function""" + # Tree.usePrivateCtx() + stream = StringIO() + try: + self.result = TextTestRunner( + stream=stream, verbosity=2).run(self.test) + finally: + stream.seek(0) + self.stream = stream.read() + stream.close() + + def _run_testcase(self, testclass, test, numthreads): numsuccess = 0 stack_size(0x100000) # 1MB - # start at idx=1 in case its running in parallel to single test - threads = [threadJob(testclass, test, i+1) for i in range(numthreads)] - for i, t in enumerate(threads): + # start at idx = 1 in case its running in parallel to single test + threads = [ + self.Job(testclass, test, i+1) + for i in range(numthreads) + ] + for t in threads: t.start() - for i, t in enumerate(threads): + for i, t in enumerate(threads, 1): t.join() if t.result.wasSuccessful(): numsuccess += 1 else: - print('### begin thread %2d: %s##################' % (i, test)) + print('### begin thread %2d: %s ##################' % (i, test)) print(t.stream) - print('### end thread %2d: %s##################' % (i, test)) + print('### end thread %2d: %s ##################' % (i, test)) self.assertEqual(numsuccess, numthreads, test) def _xxxThreadsTest(self, tests, numthreads): @@ -84,32 +88,25 @@ def _xxxThreadsTest(self, tests, numthreads): tests.setUpClass() try: for test in tests.getTests(): - self.doThreadsTestCase(tests, test, numthreads) + self._run_testcase(tests, test, numthreads) finally: tests.inThread = False tests.tearDownClass() def data(self): - self._xxxThreadsTest(_mimport('dataUnitTest').Tests, 3) + self._xxxThreadsTest(_mimport('data_case').Tests, 3) def dcl(self): - self._xxxThreadsTest(_mimport('dclUnitTest').Tests, 3) + self._xxxThreadsTest(_mimport('dcl_case').Tests, 3) - def mdsip(self): - self._xxxThreadsTest(_mimport('mdsipUnitTest').Tests, 3) - - def segments(self): - self._xxxThreadsTest(_mimport('segmentsUnitTest').Tests, 3) + def segment(self): + self._xxxThreadsTest(_mimport('segment_case').Tests, 3) def task(self): - self._xxxThreadsTest(_mimport('treeUnitTest').Tests, 3) + self._xxxThreadsTest(_mimport('task_case').Tests, 3) def tree(self): - self._xxxThreadsTest(_mimport('treeUnitTest').Tests, 3) - - @staticmethod - def getTests(): - return ['data', 'dcl', 'task', 'tree'] # ,'mdsip','segments' + self._xxxThreadsTest(_mimport('tree_case').Tests, 3) -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tests/treeUnitTest.py b/python/MDSplus/tests/tree_case.py similarity index 79% rename from python/MDSplus/tests/treeUnitTest.py rename to python/MDSplus/tests/tree_case.py index cb10ba1dc2..127e480a37 100755 --- a/python/MDSplus/tests/treeUnitTest.py +++ b/python/MDSplus/tests/tree_case.py @@ -24,9 +24,8 @@ # import os -import gc import numpy -from MDSplus import Tree, TreeNode, Data, Array, Signal, Range, Device, tree, tcl, Int32, Float32Array +from MDSplus import Tree, TreeNode, Data, Array, Signal, Range, Device, Int32, Float32Array from MDSplus import TreeNOEDIT, ADD, COMPILE, mdsrecord @@ -37,18 +36,25 @@ def _mimport(name, level=1): return __import__(name, globals()) -_UnitTest = _mimport("_UnitTest") +_common = _mimport("_common") -class Tests(_UnitTest.TreeTests): +att2 = '1 : 200 : *' +att3 = 'this is plasma current' + + +class Tests(_common.TreeTests): trees = ['pytree', 'pytreesub'] shotinc = 11 + TESTS = { + 'attr', 'open', 'node', 'find', 'default', 'linkage', + 'nci', 'data', 'xysignal', 'compression', 'records' + } - def extAttr(self): - with Tree('pytree', self.shot+0, 'new') as pytree: - if pytree.shot != self.shot+0: - raise Exception("Shot number changed! tree.shot=%d, thread.shot=%d" % ( - pytree.shot, self.shot+0)) + def attr(self): + shot = self.shot + 0 + with Tree('pytree', shot, 'new') as pytree: + self.assertEqual(pytree.shot, shot) pytree.default.addNode( 'pytreesub', 'subtree').include_in_pulse = True pytree.write() @@ -60,58 +66,57 @@ def extAttr(self): pytree.versions_in_pulse = 1 self.assertEqual(pytree.versions_in_model, True) self.assertEqual(pytree.versions_in_pulse, True) - with Tree('pytreesub', self.shot+0, 'new') as pytreesub: - if pytreesub.shot != self.shot+0: - raise Exception("Shot number changed! tree.shot=%d, thread.shot=%d" % ( - pytreesub.shot, self.shot+0)) + with Tree('pytreesub', shot, 'new') as pytreesub: + self.assertEqual(pytreesub.shot, shot) node = pytreesub.addNode('node', 'signal') node.setExtendedAttribute('ATT1', 100) node.setExtendedAttribute('ATT2', Range(1, 200)) node.setExtendedAttribute('ATT3', 'this is ip') - node.setExtendedAttribute('ATT3', 'this is plasma current') + node.setExtendedAttribute('ATT3', att3) pytreesub.write() pytree.readonly() node = pytree.getNode(".PYTREESUB:NODE") self.assertEqual(str(node.getExtendedAttribute('ATT1')), '100') - self.assertEqual(str(node.getExtendedAttribute('ATT2')), '1 : 200 : *') - self.assertEqual(str(node.getExtendedAttribute('ATT3')), - 'this is plasma current') + self.assertEqual(str(node.getExtendedAttribute('ATT2')), att2) + self.assertEqual(str(node.getExtendedAttribute('ATT3')), att3) exattr = node.getExtendedAttributes() self.assertEqual(exattr['ATT1'], 100) - self.assertEqual(str(exattr['ATT2']), '1 : 200 : *') - self.assertEqual(exattr['ATT3'], 'this is plasma current') + self.assertEqual(str(exattr['ATT2']), att2) + self.assertEqual(exattr['ATT3'], att3) - def openTrees(self): - with Tree('pytree', self.shot+1, 'new') as pytree: + def open(self): + shot1 = self.shot + 1 + shot2 = shot1 + 1 + with Tree('pytree', shot1, 'new') as pytree: a = pytree.addNode('A', 'TEXT') pytree.write() pytree.open() a.record = 'a'*64 self.assertEqual(pytree.getDatafileSize(), 84) pytree.close() - with Tree('pytree', self.shot+1, 'new') as pytree: + with Tree('pytree', shot1, 'new') as pytree: # new should clear datafile (O_TRUNC) self.assertEqual(pytree.getDatafileSize(), 0) filepath = ('%s/pytree_%03d.tree' % - (self.tmpdir, self.shot+1)).replace(os.sep, '/') - self.assertEqual(Tree.getFileName('pytree', self.shot+1), filepath) - pytree = Tree('pytree', self.shot+1) + (self.tmpdir, shot1)).replace(os.sep, '/') + self.assertEqual(Tree.getFileName('pytree', shot1), filepath) + pytree = Tree('pytree', shot1) self.assertEqual(pytree.getFileName(), filepath) self.assertEqual( - str(pytree), 'Tree("PYTREE",%d,"Normal")' % (self.shot+1,)) - pytree.createPulse(self.shot+2) + str(pytree), 'Tree("PYTREE",%d,"Normal")' % (shot1,)) + pytree.createPulse(shot2) self.assertEqual(pytree.number_opened, 1) if not Tests.inThread: - Tree.setCurrent('pytree', self.shot+2) + Tree.setCurrent('pytree', shot2) pytree2 = Tree('pytree', 0) self.assertEqual( - str(pytree2), 'Tree("PYTREE",%d,"Normal")' % (self.shot+2,)) - self.assertEqual(pytree2.incrementCurrent(1000), self.shot+1002) - self.assertEqual(pytree2.getCurrent(), self.shot+1002) + str(pytree2), 'Tree("PYTREE",%d,"Normal")' % (shot2,)) + self.assertEqual(pytree2.incrementCurrent(1000), shot2+1000) + self.assertEqual(pytree2.getCurrent(), shot2+1000) pytree2.setCurrent() - self.assertEqual(Tree.getCurrent('pytree'), self.shot+2) + self.assertEqual(Tree.getCurrent('pytree'), shot2) else: - pytree2 = Tree('pytree', self.shot+2) + pytree2 = Tree('pytree', shot2) self.assertEqual(pytree2.number_opened, 1) self.assertEqual(pytree.shotid, pytree.shot) self.assertEqual(pytree.tree, pytree.expt) @@ -129,45 +134,48 @@ def openTrees(self): else: self.assertEqual("TreeSUCCESS", "TreeNOEDIT") - def getNode(self): - with Tree('pytree', self.shot+3, 'new') as pytree: + def node(self): + shot = self.shot + 3 + with Tree('pytree', shot, 'new') as pytree: pytree.addNode('pytreesub', 'subtree').include_in_pulse = True pytree.write() - with Tree('pytreesub', self.shot+3, 'new') as pytreesub: + with Tree('pytreesub', shot, 'new') as pytreesub: ip = pytreesub.addNode('ip', 'signal') ip.tag = 'IP' pytreesub.write() - pytree = Tree('pytree', self.shot+3, 'ReadOnly') + pytree = Tree('pytree', shot, 'ReadOnly') ip = pytree.getNode('\\ip') self.assertEqual(str(ip), '\\PYTREESUB::IP') self.assertEqual(ip.nid, pytree._IP.nid) self.assertEqual(ip.nid, pytree.__PYTREESUB.IP.nid) self.assertEqual(ip.nid, pytree.__PYTREESUB__IP.nid) - def findNode(self): - pytree = Tree('pytree', self.shot+4, 'ReadOnly') - nodes = pytree.getNodeWild('***:SIG_CMPRS') - self.assertEqual(len(nodes), 1) - self.assertEqual(str(nodes[0]), '\\PYTREE::TOP:SIG_CMPRS') + def find(self): + tree = Tree('main', -1, 'ReadOnly') + nodes = tree.getNodeWild('***:COMMENT') + self.assertEqual(len(nodes), 71) + self.assertEqual(str(nodes[0]), '\\SUBTREE::TOP:COMMENT') - def setDefault(self): - with Tree('pytree', self.shot+5, 'new') as pytree: + def default(self): + shot = self.shot + 4 + with Tree('pytree', shot, 'new') as pytree: pytree.default.addNode( 'pytreesub', 'subtree').include_in_pulse = True pytree.write() - with Tree('pytreesub', self.shot+5, 'new') as pytreesub: + with Tree('pytreesub', shot, 'new') as pytreesub: pytreesub.default.addNode('mynode', 'numeric').addTag("mytag") pytreesub.write() pytree.readonly() - pytree2 = Tree('pytree', self.shot+5, "ReadOnly") + pytree2 = Tree('pytree', shot, "ReadOnly") pytree.setDefault(pytree._MYTAG) self.assertEqual(str(pytree.getDefault()), '\\PYTREESUB::MYTAG') self.assertEqual(str(pytree2.getDefault()), '\\PYTREE::TOP') pytree.getNode("\\PYTREESUB::TOP").setDefault() self.assertEqual(str(pytree.getDefault()), '\\PYTREESUB::TOP') - def nodeLinkage(self): - with Tree('pytree', self.shot+6, 'new') as pytree: + def linkage(self): + shot = self.shot + 5 + with Tree('pytree', shot, 'new') as pytree: pytree.default.addNode( 'pytreesub', 'subtree').include_in_pulse = True for i in range(10): @@ -179,7 +187,7 @@ def nodeLinkage(self): node.addNode('text', 'text') node.addNode('child', 'structure') pytree.write() - with Tree('pytreesub', self.shot+6, 'new') as pytreesub: + with Tree('pytreesub', shot, 'new') as pytreesub: ip = pytreesub.addNode('ip', 'signal') ip.tag = 'IP' for i in range(3): @@ -250,13 +258,14 @@ def nodeLinkage(self): self.assertEqual(ip.path, "\\PYTREESUB::IP") self.assertEqual(ip.path, ip.getPath()) - def nciInfo(self): - with Tree('pytree', self.shot+7, 'new') as pytree: + def nci(self): + shot = self.shot + 6 + with Tree('pytree', shot, 'new') as pytree: pytree.addNode('pytreesub', 'subtree').include_in_pulse = True Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE') Device.PyDevice('CYGNET4K').Add(pytree, 'CYGNET4K').on = False pytree.write() - with Tree('pytreesub', self.shot+7, 'new') as pytreesub: + with Tree('pytreesub', shot, 'new') as pytreesub: ip = pytreesub.addNode('ip', 'signal') ip.record = Signal(Int32(range(10)), None, Range(1., 10.)) ip.tag = 'MAG_PLASMA_CURRENT' @@ -266,17 +275,14 @@ def nciInfo(self): ip.tag = 'IP' ip.setExtendedAttribute('ATT1', 100) ip.setExtendedAttribute('ATT2', Range(1, 200)) - ip.setExtendedAttribute('ATT3', 'this is ip') - ip.setExtendedAttribute('ATT3', 'this is plasma current') + ip.setExtendedAttribute('ATT3', att3) self.assertEqual(str(ip.getExtendedAttribute('ATT1')), '100') - self.assertEqual( - str(ip.getExtendedAttribute('ATT2')), '1 : 200 : *') - self.assertEqual(str(ip.getExtendedAttribute( - 'ATT3')), 'this is plasma current') + self.assertEqual(str(ip.getExtendedAttribute('ATT2')), att2) + self.assertEqual(str(ip.getExtendedAttribute('ATT3')), att3) exattr = ip.getExtendedAttributes() self.assertEqual(exattr['ATT1'], 100) - self.assertEqual(str(exattr['ATT2']), '1 : 200 : *') - self.assertEqual(exattr['ATT3'], 'this is plasma current') + self.assertEqual(str(exattr['ATT2']), att2) + self.assertEqual(exattr['ATT3'], att3) for i in range(3): node = pytreesub.addNode('child%02d' % (i,), 'structure') node.addDevice('dt200_%02d' % (i,), 'dt200').on = False @@ -329,7 +335,8 @@ def nciInfo(self): self.assertEqual(part.PART_NAME(), ':ACTIONSERVER') self.assertEqual(part.original_part_name, ':ACTIONSERVER') self.assertEqual( - str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part)), ':ACTIONSERVER') + str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part)), + ':ACTIONSERVER') self.assertEqual(pydev.__class__, Device.PyDevice('TestDevice')) devs = pytree.getNodeWild('\\PYTREESUB::TOP.***', 'DEVICE') part = devs[0].conglomerate_nids[3] @@ -344,16 +351,18 @@ def nciInfo(self): self.assertEqual(ip.status, 0) self.assertEqual(ip.status, ip.getStatus()) self.assertEqual((ip.tags == Array( - ['IP', 'MAGNETICS_IP', 'MAG_IP', 'MAGNETICS_PLASMA_CURRENT', 'MAG_PLASMA_CURRENT'])).all(), True) + ['IP', 'MAGNETICS_IP', 'MAG_IP', 'MAGNETICS_PLASMA_CURRENT', + 'MAG_PLASMA_CURRENT'])).all(), True) self.assertEqual((ip.tags == ip.getTags()).all(), True) self.assertEqual(ip.time_inserted, ip.getTimeInserted()) - def getData(self): - with Tree('pytree', self.shot+8, 'new') as pytree: + def data(self): + shot = self.shot + 7 + with Tree('pytree', shot, 'new') as pytree: pytree.default.addNode( 'pytreesub', 'subtree').include_in_pulse = True pytree.write() - with Tree('pytreesub', self.shot+8, 'new') as pytreesub: + with Tree('pytreesub', shot, 'new') as pytreesub: node = pytreesub.addNode('.rog', 'structure') for i in range(10): node = node.addNode('.child', 'structure') @@ -367,17 +376,18 @@ def getData(self): node.compress_on_put = True node.record = Signal(Range(2., 2000., 2.), None, Range(1., 1000.)) ip = pytreesub.addNode('ip', 'signal') - ip.tag = "ip" + ip.tag = "IP" rec = pytreesub.tdiCompile( "Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, 'ampere'), *, DIM_OF(\\BTOR))") ip.record = rec pytreesub.versions_in_pulse = True pytreesub.write() pytree.readonly() - ip = pytree.getNode('\\ip') + ip = pytree.getNode('\\IP') pytree.setDefault(ip) - self.assertEqual(str( - ip.record), 'Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, "ampere"), *, DIM_OF(\\BTOR))') + self.assertEqual( + str(ip.record), + 'Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, "ampere"), *, DIM_OF(\\BTOR))') self.assertEqual(str(ip.record), str(ip.getData())) self.assertEqual(ip.segmented, ip.isSegmented()) self.assertEqual(ip.versions, ip.containsVersions()) @@ -391,21 +401,24 @@ def getData(self): self.assertEqual(ip.record.data().tolist(), (pytree.getNode("\\BTOR").data()+1).tolist()) - def getXYSignal(self): - with Tree('pytree', self.shot+9, 'new') as pytree: + def xysignal(self): + shot = self.shot + 8 + with Tree('pytree', shot, 'new') as pytree: node = pytree.addNode('SIG', 'signal') pytree.write() pytree.normal() dim = numpy.array(range(100000), 'float32')/10000 - pytree.SIG.record = Signal(Float32Array(numpy.sin(dim)).setUnits( - "ylabel"), None, Float32Array(dim).setUnits("xlabel")).setHelp('title') + pytree.SIG.record = Signal( + Float32Array(numpy.sin(dim)).setUnits("ylabel"), None, + Float32Array(dim).setUnits("xlabel")).setHelp('title') sig = node.getXYSignal(num=100) self.assertEqual(sig.units, "ylabel") self.assertEqual(sig.dim_of().units, "xlabel") self.assertEqual(sig.help, "title") - def getCompression(self): - with Tree('pytree', self.shot+10, 'new') as pytree: + def compression(self): + shot = self.shot + 9 + with Tree('pytree', shot, 'new') as pytree: node = pytree.addNode('SIG_CMPRS', 'signal') node.compress_on_put = True pytree.write() @@ -413,11 +426,13 @@ def getCompression(self): testing = Tree('testing', -1) for node in testing.getNodeWild(".compression:*"): pytree.SIG_CMPRS.record = node.record - self.assertTrue((pytree.SIG_CMPRS.record == node.record).all(), - msg="Error writing compressed signal%s" % node) + self.assertTrue( + (pytree.SIG_CMPRS.record == node.record).all(), + msg="Error writing compressed signal%s" % node) - def mdsrecords(self): - with Tree('pytree', self.shot+11, 'new') as pytree: + def records(self): + shot = self.shot + 10 + with Tree('pytree', shot, 'new') as pytree: node = pytree.addDevice('DEV', 'TestDevice') pytree.write() pytree.normal() @@ -439,9 +454,5 @@ def mdsrecords(self): self.assertEqual(cls._parts_str.filter, mdsrecord.str) self.assertEqual(cls._parts_int_list.filter, mdsrecord.int_list) - @staticmethod - def getTests(): - return ['extAttr', 'openTrees', 'getNode', 'setDefault', 'nodeLinkage', 'nciInfo', 'getData', 'getXYSignal', 'getCompression', 'mdsrecords'] - -Tests.main(__name__) +Tests.main() diff --git a/python/MDSplus/tree.py b/python/MDSplus/tree.py index 247a0d191e..f1ca8dbac8 100644 --- a/python/MDSplus/tree.py +++ b/python/MDSplus/tree.py @@ -1660,23 +1660,22 @@ def addTags(self, names, replace=False): Use replace=True if any existing tags should be removed. Tag names must be either a str or a list or tuple containing str instances.""" - def checkstr(s): - if not isinstance(s, str): + if isinstance(names, _ver.basestring): + names = (names,) + else: + try: + names = tuple(names) + for name in names: + if not isinstance(name, _ver.basestring): + raise TypeError + except TypeError: raise TypeError( "Tag names must be a string or list of strings") - if isinstance(names, (list, tuple)): - for name in names: - checkstr(name) - else: - checkstr(names) if replace: for name in self.tags: self.removeTag(name) - if isinstance(names, str): - self.addTag(names) - else: - for name in names: - self.addTag(name) + for name in names: + self.addTag(name) def addTag(self, tag): """Add a tagname to this node @@ -3270,7 +3269,7 @@ def __set__(self, inst, value): with self.lock: if (self.cache_on_set): inst.__dict__[self.target] = value - else: + elif self.target in inst.__dict__: del(inst.__dict__[self.target]) def __delete__(self, inst): diff --git a/python/MDSplus/version.py b/python/MDSplus/version.py index fd84e49c35..43a9a9614b 100644 --- a/python/MDSplus/version.py +++ b/python/MDSplus/version.py @@ -82,9 +82,9 @@ def load_library(name): try: libnam = find_library(name) except: - raise Exception("Could not find library: %s" % (name,)) + raise ImportError("Could not find library: %s" % (name,)) if libnam is None: - raise Exception("Could not find library: %s" % (name,)) + raise ImportError("Could not find library: %s" % (name,)) try: return C.CDLL(libnam) except: @@ -92,7 +92,7 @@ def load_library(name): try: return C.CDLL(os.path.basename(libnam)) except: - raise Exception('Could not load library: %s' % (name,)) + raise ImportError('Could not load library: %s' % (name,)) from types import GeneratorType as generator # analysis:ignore @@ -124,6 +124,7 @@ def load_library(name): mapclass = map else: mapclass = tuple +listlike = (tuple, list, mapclass, generator, nparray) if ispy3: def superdir(cls, self): diff --git a/python/generate_tests b/python/generate_tests new file mode 100755 index 0000000000..36325206c4 --- /dev/null +++ b/python/generate_tests @@ -0,0 +1,17 @@ +#!/bin/bash +PYTHON=${PYTHON:-python} +here=$(dirname $(realpath $0)) +testdir=$here/MDSplus/tests/ +rm $testdir/*_test.py 2>/dev/null +get_tests() { + $PYTHON -c "0;$(sed -n '/TESTS\s*=/,/^\s*$/p' $1);print(' '.join(TESTS))" +} +for c in $testdir/*_case.py; do + c=$(basename $c) + for t in $(get_tests $testdir/$c); do + test=${c:0:-8}_${t}_test.py + echo $test \\ + ln -s $c $testdir/$test + done & +done | sort +wait & \ No newline at end of file diff --git a/servershr/Makefile.in b/servershr/Makefile.in index 1f400add01..21b721a9a5 100644 --- a/servershr/Makefile.in +++ b/servershr/Makefile.in @@ -1,33 +1,14 @@ include @top_builddir@/Makefile.inc srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ @AX_RECONFIGURE_TARGET@ @MINGW_TRUE@ IMPLIB=@MAKELIBDIR@MdsServerShr.dll.a -SOURCES = \ - ServerDispatchAction.c\ - ServerSetDetailProc.c\ - ServerAbortServer.c\ - ServerDispatchClose.c\ - ServerGetInfo.c\ - ServerSetLogging.c\ - ServerBuildDispatchTable.c\ - ServerDispatchCommand.c\ - ServerMonitorCheckin.c\ - ServerStartServer.c\ - ServerCloseTrees.c\ - ServerDispatchPhase.c\ - ServerStopServer.c\ - ServerCreatePulse.c\ - ServerFindServers.c\ - ServerSendMessage.c\ - ServerSendMonitor.c\ - ServerQAction.c - -OBJECTS = $(SOURCES:.c=.o) +SOURCES = $(wildcard @srcdir@/Server*.c) +OBJECTS = $(SOURCES:@srcdir@/%.c=%.o) all: @MAKELIBDIR@ @MAKESHLIBDIR@@LIBPRE@MdsServerShr@SHARETYPE@ @MAKELIBDIR@@LIBPRE@MdsServerShr.a @@ -53,4 +34,3 @@ install: $(libdir) @MAKELIBDIR@@LIBPRE@MdsServerShr.a: $(OBJECTS) $(AR) -cr $@ $^ @RANLIB@ $@ - diff --git a/tcl/Makefile.in b/tcl/Makefile.in index b6b68d2be5..1fa310402d 100644 --- a/tcl/Makefile.in +++ b/tcl/Makefile.in @@ -1,60 +1,24 @@ include @top_builddir@/Makefile.inc srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ @AX_RECONFIGURE_TARGET@ -CFLAGS += $(THREAD) +CFLAGS += $(THREAD) LDFLAGS += $(THREAD) @MINGW_TRUE@ MDSTCL=mdstcl.bat @MINGW_FALSE@ MDSTCL=mdstcl -SOURCES = \ - tcl_add_node.c \ - tcl_add_tag.c \ - tcl_clean_datafile.c \ - tcl_close.c \ - tcl_compress_datafile.c \ - tcl_create_pulse.c \ - tcl_decompile.c \ - tcl_delete_node.c \ - tcl_delete_pulse.c \ - tcl_directory.c \ - tcl_directory_tag.c \ - tcl_dispatch.c \ - tcl_do_method.c \ - tcl_do_node.c \ - tcl_edit.c \ - tcl_help_device.c \ - tcl_put_expression.c \ - tcl_remove_tag.c \ - tcl_rename.c \ - tcl_set_callbacks.c \ - tcl_set_current.c \ - tcl_set_default.c \ - tcl_set_node.c \ - tcl_set_tree.c \ - tcl_set_view.c \ - tcl_setevent.c \ - tcl_set_readonly.c \ - tcl_setshow_attribute.c \ - tcl_setshow_versions.c \ - tcl_show_current.c \ - tcl_show_data.c \ - tcl_show_db.c \ - tcl_verify_tree.c \ - tcl_wfevent.c \ - tcl_write.c -@MINGW_TRUE@ SOURCES += icon.o - -OBJECTS = $(SOURCES:.c=.o) +SOURCES = $(wildcard @srcdir@/tcl_*.c) +@MINGW_TRUE@SOURCES += icon.o +OBJECTS = $(SOURCES:@srcdir@/%.c=%.o) EXPORTS = tcl_commands.export all: @MAKEBINDIR@$(MDSTCL) @MAKESHLIBDIR@@LIBPRE@tcl_commands@SHARETYPE@ -depend: +depend: - @makedepend -- $(CFLAGS) -- $(SOURCES) 2>/dev/null clean: diff --git a/tcl/tcl_dispatch.c b/tcl/tcl_dispatch.c index 439286a30f..2ac6256120 100644 --- a/tcl/tcl_dispatch.c +++ b/tcl/tcl_dispatch.c @@ -340,58 +340,50 @@ EXPORT int TclDispatch_show_server(void *ctx, char **error __attribute__((unused)), char **output) { - INIT_TCLSTATUS; - char *ident; int dooutput = IS_OK(cli_present(ctx, "OUTPUT")); int full = IS_OK(cli_present(ctx, "FULL")); if (dooutput) *output = strdup(""); - while (STATUS_OK && IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) + char *ident = NULL; + while (IS_OK(cli_get_value(ctx, "SERVER_NAME", &ident))) { - FREE_ON_EXIT(ident); if (IS_WILD(ident)) { /* contains wildcard? */ void *ctx1 = NULL; - char *server = NULL; + char *server; while ((server = ServerFindServers(&ctx1, ident))) { - FREE_ON_EXIT(server); tclAppend(output, "Checking server: "); tclAppend(output, server); tclAppend(output, "\n"); mdsdclFlushOutput(*output); - char *info = NULL; - FREE_ON_EXIT(info); + char *info = ServerGetInfo(full, ident); if (dooutput) { - tclAppend(output, info = ServerGetInfo(full, server)); + tclAppend(output, info); tclAppend(output, "\n"); } - else - info = ServerGetInfo(full, server); - FREE_NOW(info); - FREE_NOW(server); + free(info); + free(server); } } else { - char *info = NULL; tclAppend(output, "Checking server: "); tclAppend(output, ident); tclAppend(output, "\n"); mdsdclFlushOutput(*output); - FREE_ON_EXIT(info); - info = ServerGetInfo(full, ident); + char *info = ServerGetInfo(full, ident); if (dooutput) { tclAppend(output, info); tclAppend(output, "\n"); } - FREE_NOW(info); + free(info); } - FREE_NOW(ident); + free(ident); } - return status; + return TclNORMAL; } static inline void printIt(char *output) { fprintf(stdout, "%s\n", output); } @@ -403,9 +395,9 @@ EXPORT int TclDispatch_phase(void *ctx, char **error, char **output __attribute__((unused))) { int status; - INIT_AND_FREE_ON_EXIT(char *, phase); - INIT_AND_FREE_ON_EXIT(char *, synch_str); - INIT_AND_FREE_ON_EXIT(char *, monitor); + char *phase = NULL; + char *synch_str = NULL; + char *monitor = NULL; int synch; int noaction = IS_OK(cli_present(ctx, "NOACTION")); void (*output_rtn)() = IS_OK(cli_present(ctx, "LOG")) ? printIt : 0; @@ -419,6 +411,9 @@ EXPORT int TclDispatch_phase(void *ctx, char **error, output_rtn, monitor); else status = TclNO_DISPATCH_TABLE; + free(monitor); + free(synch_str); + free(phase); if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); @@ -428,9 +423,6 @@ EXPORT int TclDispatch_phase(void *ctx, char **error, "Error message was: %s\n", msg); } - FREE_NOW(monitor); - FREE_NOW(synch_str); - FREE_NOW(phase); return status; } diff --git a/testing/generate_valgrind_suppressions.sh b/testing/generate_valgrind_suppressions.sh index 84e40fe85d..740dd9e9e3 100755 --- a/testing/generate_valgrind_suppressions.sh +++ b/testing/generate_valgrind_suppressions.sh @@ -1,10 +1,10 @@ -valgrind --quiet --trace-children=yes --error-exitcode=1 \ - --suppressions=valgrind-stdlib.supp \ - --suppressions=valgrind-dlerr.supp \ - --suppressions=valgrind-connection.supp \ - --suppressions=valgrind-treenode.supp \ - --dsymutil=yes --leak-check=yes \ - --gen-suppressions=all \ - $1 \ - 2>&1 | ./parse_valgrind_suppressions.sh - +#!/bin/sh +valgrind --quiet --trace-children=yes --error-exitcode=1 \ + --suppressions=valgrind-stdlib.supp \ + --suppressions=valgrind-dlerr.supp \ + --suppressions=valgrind-connection.supp \ + --suppressions=valgrind-treenode.supp \ + --dsymutil=yes --leak-check=yes \ + --gen-suppressions=all \ + "$@" \ + 2>&1 | $(dirname $0)/parse_valgrind_suppressions.sh diff --git a/testing/helgrind b/testing/helgrind index adc9a8022e..490f5a15f4 100755 --- a/testing/helgrind +++ b/testing/helgrind @@ -1,8 +1,14 @@ +#!/bin/sh +repo=$(dirname $(dirname $(realpath $0))) +supp=$repo/conf/valgrind.supp +suppressions="--suppressions=$supp/mdsplus.supp" +if test -f "$supp/${DISTNAME}.supp" +then suppressions="${suppressions} --suppressions=$supp/${DISTNAME}.supp" +fi exec valgrind --tool=helgrind --history-level=full\ --xml=yes --xml-file=$(basename $1)-helgrind-%p.xml\ --gen-suppressions=all --num-callers=64\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ - --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ - --suppressions=$MDSPLUS_DIR/conf/valgrind.supp/mdsplus.supp\ + $suppressions\ "$@" diff --git a/testing/memcheck b/testing/memcheck index 8c87f297ea..487ad4f81a 100755 --- a/testing/memcheck +++ b/testing/memcheck @@ -1,8 +1,14 @@ +#!/bin/sh +repo=$(dirname $(dirname $(realpath $0))) +supp=$repo/conf/valgrind.supp +suppressions="--suppressions=$supp/mdsplus.supp" +if test -f "$supp/${DISTNAME}.supp" +then suppressions="${suppressions} --suppressions=$supp/${DISTNAME}.supp" +fi exec valgrind --tool=memcheck --leak-check=full --show-reachable=no\ --xml=yes --xml-file=$(basename $1)-memcheck-%p.xml\ --gen-suppressions=all --num-callers=64\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ - --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ - --suppressions=$MDSPLUS_DIR/conf/valgrind.supp/mdsplus.supp\ + $suppressions\ "$@" diff --git a/testing/parse_valgrind_suppressions.sh b/testing/parse_valgrind_suppressions.sh index 1ea98e4e1e..0c6c014a85 100755 --- a/testing/parse_valgrind_suppressions.sh +++ b/testing/parse_valgrind_suppressions.sh @@ -1,4 +1,4 @@ -#! /usr/bin/awk -f +#!/usr/bin/gawk -f # A script to extract the actual suppression info from the output of (for example) valgrind --leak-check=full --show-reachable=yes --error-limit=no --gen-suppressions=all ./minimal # The desired bits are between ^{ and ^} (including the braces themselves). # The combined output should either be appended to /usr/lib/valgrind/default.supp, or placed in a .supp of its own @@ -32,7 +32,6 @@ BEGIN { suppression=0; md5sum = "md5sum" } } } - function ProcessInput() { # Pipe the result from md5sum, then close it @@ -55,4 +54,3 @@ BEGIN { suppression=0; md5sum = "md5sum" } { print supparray[n] } print "}" } - diff --git a/treeshr/TreeGetRecord.c b/treeshr/TreeGetRecord.c index 8ce447f20d..e8235f88bc 100644 --- a/treeshr/TreeGetRecord.c +++ b/treeshr/TreeGetRecord.c @@ -46,8 +46,8 @@ static int64_t ViewDate = -1; extern void **TreeCtx(); #define min(a, b) (((a) < (b)) ? (a) : (b)) -int TreeGetRecord(int nid_in, struct descriptor_xd *dsc); -int _TreeGetRecord(void *dbid, int nid_in, struct descriptor_xd *dsc) +int TreeGetRecord(int nid_in, mdsdsc_xd_t *dsc); +int _TreeGetRecord(void *dbid, int nid_in, mdsdsc_xd_t *dsc) { int status; CTX_PUSH(&dbid); @@ -56,7 +56,29 @@ int _TreeGetRecord(void *dbid, int nid_in, struct descriptor_xd *dsc) return status; } -int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) +static inline int read_descriptor(TREE_INFO *info, int length, NCI *nci, int nidx, mdsdsc_xd_t *dsc) +{ + int status = 0; + INIT_AS_AND_FREE_ON_EXIT(char *, data, malloc(length)); + int nodenum; + int retsize; + status = TreeGetDatafile( + info, nci->DATA_INFO.DATA_LOCATION.rfa, &length, + data, &retsize, &nodenum, nci->flags2); + if (STATUS_NOT_OK) + status = TreeBADRECORD; + else if (!(nci->flags2 & NciM_NON_VMS) && + ((retsize != length) || (nodenum != nidx))) + status = TreeBADRECORD; + else + status = (MdsSerializeDscIn(data, dsc) & 1) + ? TreeSUCCESS + : TreeBADRECORD; + FREE_NOW(data); + return status; +} + +int TreeGetRecord(int nid_in, mdsdsc_xd_t *dsc) { void *dbid = *TreeCtx(); PINO_DATABASE *dblist = (PINO_DATABASE *)dbid; @@ -64,16 +86,13 @@ int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) struct descriptor *dptr; int status; NCI nci; - TREE_INFO *info; - int nidx; - int retsize; - int nodenum; MdsFree1Dx(dsc, NULL); if (!(IS_OPEN(dblist))) return TreeNOT_OPEN; if (dblist->remote) return GetRecordRemote(dblist, nid_in, dsc); - nid_to_tree_nidx(dblist, nid, info, nidx); + TREE_INFO *info; + int nidx = nid_to_tree_idx(dblist, nid, &info); if (info) { TreeCallHookFun("TreeNidHook", "GetNci", info->treenam, info->shot, nid, @@ -179,20 +198,7 @@ int TreeGetRecord(int nid_in, struct descriptor_xd *dsc) int length = nci.DATA_INFO.DATA_LOCATION.record_length; if (length > 0) { - char *data = malloc(length); - status = TreeGetDatafile( - info, nci.DATA_INFO.DATA_LOCATION.rfa, &length, - data, &retsize, &nodenum, nci.flags2); - if (STATUS_NOT_OK) - status = TreeBADRECORD; - else if (!(nci.flags2 & NciM_NON_VMS) && - ((retsize != length) || (nodenum != nidx))) - status = TreeBADRECORD; - else - status = (MdsSerializeDscIn(data, dsc) & 1) - ? TreeSUCCESS - : TreeBADRECORD; - free(data); + status = read_descriptor(info, length, &nci, nidx, dsc); } else status = TreeBADRECORD; @@ -329,12 +335,12 @@ int TreeMakeNidsLocal(struct descriptor *dsc_ptr, int nid) DATA_FILE *TreeGetVmDatafile() { DATA_FILE *datafile_ptr; - static const struct descriptor_xd empty_xd = {0, 0, CLASS_XD, 0, 0}; + static const mdsdsc_xd_t empty_xd = {0, 0, CLASS_XD, 0, 0}; int length = align(sizeof(DATA_FILE), sizeof(void *)) + align(sizeof(RECORD_HEADER), sizeof(void *)) + align(sizeof(ASY_NCI), sizeof(void *)) + align(sizeof(NCI), sizeof(void *)) + - align(sizeof(struct descriptor_xd), sizeof(void *)); + align(sizeof(mdsdsc_xd_t), sizeof(void *)); datafile_ptr = malloc(length * 2); if (datafile_ptr != NULL) { @@ -345,34 +351,74 @@ DATA_FILE *TreeGetVmDatafile() datafile_ptr->asy_nci = (ASY_NCI *)(ptr += align(sizeof(RECORD_HEADER), sizeof(void *))); datafile_ptr->data = - (struct descriptor_xd *)(ptr += align(sizeof(ASY_NCI), sizeof(void *))); + (mdsdsc_xd_t *)(ptr += align(sizeof(ASY_NCI), sizeof(void *))); *datafile_ptr->data = empty_xd; datafile_ptr->asy_nci->nci = - (NCI *)(ptr += align(sizeof(struct descriptor_xd), sizeof(void *))); + (NCI *)(ptr += align(sizeof(mdsdsc_xd_t), sizeof(void *))); } return datafile_ptr; } +inline static int read_datablob(TREE_INFO *info, int *nodenum, const int64_t rfa_in, char *const record, uint32_t const buffer_space) +{ + int status; + const int blen = buffer_space // + + (buffer_space + DATAF_C_MAX_RECORD_SIZE + 1) / + (DATAF_C_MAX_RECORD_SIZE + 2) * + sizeof(RECORD_HEADER); + INIT_AS_AND_FREE_ON_EXIT(char *, buffer, malloc(blen)); + char *bptr = record + buffer_space; +#define RECORD_ALIGN (DATAF_C_MAX_RECORD_SIZE + 2 + sizeof(RECORD_HEADER)) + uint32_t partlen = ((blen - 1) % RECORD_ALIGN) + 1; + int64_t rfa_l = rfa_in - blen + partlen; + int deleted = 1; + do + { + status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)buffer, + blen, &deleted) == blen) + ? TreeSUCCESS + : TreeDFREAD; + if (STATUS_OK && deleted) + status = TreeReopenDatafile(info); + else + break; + } while (STATUS_OK); + loadint32(nodenum, &((RECORD_HEADER *)buffer)->node_number); + char *bptr_in; + uint32_t bytes_remaining = buffer_space; + for (bptr_in = buffer; bytes_remaining > 0;) + { + const int bytes_this_time = min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_remaining); + bptr_in += sizeof(RECORD_HEADER); + memcpy(bptr - bytes_this_time, bptr_in, bytes_this_time); + bptr_in += bytes_this_time; + bptr -= bytes_this_time; + bytes_remaining -= bytes_this_time; + } + FREE_NOW(buffer); + return status; +} + EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, - int *buffer_size, char *record, int *retsize, + int *buffer_size, char *const record, int *retsize, int *nodenum, unsigned char flags) { int status = 1; - int buffer_space = *buffer_size; int first = 1; unsigned char rfa[6]; - char *bptr = (char *)record; *retsize = 0; memcpy(rfa, rfa_in, sizeof(rfa)); if (!(flags & NciM_DATA_CONTIGUOUS)) { + char *bptr = (char *)record; + uint32_t buffer_space = (uint32_t)*buffer_size; while ((rfa[0] || rfa[1] || rfa[2] || rfa[3] || rfa[4] || rfa[5]) && buffer_space && STATUS_OK) { RECORD_HEADER hdr; int64_t rfa_l = RfaToSeek(rfa); int deleted = 1; - while (STATUS_OK && deleted) + do { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)&hdr, 12, &deleted) == 12) @@ -380,11 +426,13 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, : TreeDFREAD; if (STATUS_OK && deleted) status = TreeReopenDatafile(info); - } + else + break; + } while (STATUS_OK); if (STATUS_OK) { - unsigned int partlen = - min(swapint16(&hdr.rlength) - 10, buffer_space); + uint32_t partlen = (uint32_t)(swapint16(&hdr.rlength) - 10); + partlen = min(partlen, buffer_space); int nidx = swapint32(&hdr.node_number); if (first) *nodenum = nidx; @@ -394,16 +442,18 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, break; } deleted = 1; - while (STATUS_OK && deleted) + do { - status = ((unsigned int)MDS_IO_READ_X(info->data_file->get, - rfa_l + 12, (void *)bptr, - partlen, &deleted) == partlen) + status = ((uint32_t)MDS_IO_READ_X(info->data_file->get, + rfa_l + 12, (void *)bptr, + partlen, &deleted) == partlen) ? TreeSUCCESS : TreeDFREAD; if (STATUS_OK && deleted) status = TreeReopenDatafile(info); - } + else + break; + } while (STATUS_OK); if (STATUS_OK) { bptr += partlen; @@ -416,11 +466,11 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, } else { + int64_t rfa_l = RfaToSeek(rfa); if (flags & NciM_NON_VMS) { - int64_t rfa_l = RfaToSeek(rfa); int deleted = 1; - while (STATUS_OK && deleted) + do { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)record, *buffer_size, &deleted) == *buffer_size) @@ -428,49 +478,15 @@ EXPORT int TreeGetDatafile(TREE_INFO *info, unsigned char *rfa_in, : TreeDFREAD; if (STATUS_OK && deleted) status = TreeReopenDatafile(info); - } - *retsize = *buffer_size; + else + break; + } while (STATUS_OK); } else { - int blen = *buffer_size + (*buffer_size + DATAF_C_MAX_RECORD_SIZE + 1) / - (DATAF_C_MAX_RECORD_SIZE + 2) * - sizeof(RECORD_HEADER); - char *buffer = (char *)malloc(blen); - char *bptr_in; - unsigned int bytes_remaining; - unsigned int partlen = - (blen % (DATAF_C_MAX_RECORD_SIZE + 2 + sizeof(RECORD_HEADER))); - int64_t rfa_l = RfaToSeek(rfa); - int deleted = 1; - rfa_l -= - blen - (partlen - ? partlen - : (DATAF_C_MAX_RECORD_SIZE + 2 + sizeof(RECORD_HEADER))); - while (STATUS_OK && deleted) - { - status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)buffer, - blen, &deleted) == blen) - ? TreeSUCCESS - : TreeDFREAD; - if (STATUS_OK && deleted) - status = TreeReopenDatafile(info); - } - loadint32(nodenum, &((RECORD_HEADER *)buffer)->node_number); - for (bptr_in = buffer, bptr = record + *buffer_size, - bytes_remaining = *buffer_size; - bytes_remaining;) - { - int bytes_this_time = min(DATAF_C_MAX_RECORD_SIZE + 2, bytes_remaining); - bptr_in += sizeof(RECORD_HEADER); - memcpy(bptr - bytes_this_time, bptr_in, bytes_this_time); - bptr_in += bytes_this_time; - bptr -= bytes_this_time; - bytes_remaining -= bytes_this_time; - } - free(buffer); - *retsize = *buffer_size; + status = read_datablob(info, nodenum, rfa_l, record, *buffer_size); } + *retsize = *buffer_size; } return status; } @@ -510,7 +526,7 @@ int TreeGetVersionNci(TREE_INFO *info, NCI *nci, NCI *v_nci) int status = TreeOpenDatafileR(info); if (STATUS_OK) { - int deleted = 1; + int64_t rfa_l = RfaToSeek(nci->DATA_INFO.DATA_LOCATION.rfa); rfa_l += ((nci->DATA_INFO.DATA_LOCATION.record_length == (DATAF_C_MAX_RECORD_SIZE + 2)) @@ -518,7 +534,8 @@ int TreeGetVersionNci(TREE_INFO *info, NCI *nci, NCI *v_nci) : (nci->DATA_INFO.DATA_LOCATION.record_length % (DATAF_C_MAX_RECORD_SIZE + 2))); rfa_l += sizeof(RECORD_HEADER); - while (STATUS_OK && deleted) + int deleted = 1; + do { status = (MDS_IO_READ_X(info->data_file->get, rfa_l, (void *)nci_bytes, 42, &deleted) == 42) @@ -526,7 +543,9 @@ int TreeGetVersionNci(TREE_INFO *info, NCI *nci, NCI *v_nci) : TreeDFREAD; if (STATUS_OK && deleted) status = TreeReopenDatafile(info); - } + else + break; + } while (STATUS_OK); if (STATUS_OK) { TreeSerializeNciIn(nci_bytes, v_nci); From e4da171eb64ea80066b26df735f24b7f4a689739 Mon Sep 17 00:00:00 2001 From: Stephen Lane-Walsh Date: Mon, 3 May 2021 19:56:16 -0400 Subject: [PATCH 12/27] Fix: Refactor out _MOVC3 macro (#2300) Replace all instances of _MOVC3(a, b, c) with memcpy(c, b, a) --- mdsshr/MdsCompress.c | 20 +++++++++++--------- mdsshr/MdsXdRoutines.c | 19 +++++++++---------- tdishr/TdiIntrinsic.c | 5 ++--- tdishr/TdiMatrix.c | 3 +-- tdishr/TdiPower.c | 15 +++++++-------- tdishr/TdiScalar.c | 3 +-- tdishr/TdiSort.c | 8 +++----- tdishr/TdiSql.c | 1 - tdishr/TdiSubscript.c | 12 ++++++------ tdishr/TdiTrans.c | 31 +++++++++++++++---------------- 10 files changed, 55 insertions(+), 62 deletions(-) diff --git a/mdsshr/MdsCompress.c b/mdsshr/MdsCompress.c index 82598c298f..1ef4654c03 100644 --- a/mdsshr/MdsCompress.c +++ b/mdsshr/MdsCompress.c @@ -82,7 +82,6 @@ output number of bits in packed. (untested) #include #include -#define _MOVC3(a, b, c) memcpy(c, b, (size_t)(a)) #define align(bytes, size) ((((bytes) + (size)-1) / (size)) * (size)) typedef ARRAY_COEFF(char, 1) array_coef; typedef RECORD(4) mds_decompress_t; @@ -207,8 +206,9 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, { prec->dscptrs[0] = pd0; *pd0 = *(mdsdsc_t *)&dximage; - _MOVC3(dximage.length, dximage.pointer, - pd0->pointer = (char *)&pd0[1]); + pd0->pointer = (char *)&pd0[1]; + memcpy(pd0->pointer, dximage.pointer, + dximage.length); } pd0 = pd1; StrFree1Dx(&dximage); @@ -220,8 +220,9 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, { prec->dscptrs[1] = pd0; *pd0 = *(mdsdsc_t *)&dxentry; - _MOVC3(dxentry.length, dxentry.pointer, - pd0->pointer = (char *)&pd0[1]); + pd0->pointer = (char *)&pd0[1]; + memcpy(pd0->pointer, dxentry.pointer, + dxentry.length); } pd0 = pd1; StrFree1Dx(&dxentry); @@ -235,7 +236,8 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, bit = 0; prec->dscptrs[0] = 0; prec->dscptrs[1] = 0; - _MOVC3(pdat->arsize = (unsigned int)(plim - pcmp), pcmp + delta, pcmp); + pdat->arsize = (unsigned int)(plim - pcmp); + memcpy(pcmp, pcmp + delta, pdat->arsize); } /******************** @@ -249,14 +251,14 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, Did not do a good job, so restore all. *************************************/ status = 1; - _MOVC3(asize + porig->arsize, porig, pwork); + memcpy(pwork, porig, asize + porig->arsize); break; good: pca0 = (array_coef *)pwork; pca0->class = CLASS_CA; if (pca0->aflags.coeff) pca0->a0 = (char *)(pca0->a0 - porig->pointer); - _MOVC3((short)asize, (char *)pca0, (char *)pca1); + memcpy((char *)pca1, (char *)pca0, (short)asize); pca0->pointer = (char *)prec; pca1->pointer = 0; @@ -321,7 +323,7 @@ Compact/copy from work. #ifdef _RECURSIVE_COMPRESS int orig_len = work.l_length; #endif - _MOVC3(work.l_length, work.pointer, out_ptr->pointer); + memcpy(out_ptr->pointer, work.pointer, work.l_length); status = compress(cimage_ptr, centry_ptr, (char *)out_ptr->pointer - (char *)work.pointer, work.pointer); diff --git a/mdsshr/MdsXdRoutines.c b/mdsshr/MdsXdRoutines.c index 08b4b3f872..8cea0d1677 100644 --- a/mdsshr/MdsXdRoutines.c +++ b/mdsshr/MdsXdRoutines.c @@ -52,7 +52,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define LibVM_EXTEND_AREA 32 #define LibVM_TAIL_LARGE 128 #define compression_threshold 128 -#define _MOVC3(a, b, c) memcpy(c, b, (size_t)(a)) inline static size_t _sizeAligned(const size_t bytes) { @@ -214,7 +213,7 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, *po = in; po->class = CLASS_XS; po->pointer = (mdsdsc_t *)po + sizeof(in); - _MOVC3(in.l_length, in.pointer, po->pointer); + memcpy(po->pointer, in.pointer, in.l_length); } if (path.pointer) StrFree1Dx(&path); @@ -230,11 +229,11 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, (pi->ndesc - 1u) * (uint32_t)sizeof(mdsdsc_t *); if (po) { - _MOVC3(bytes, (char *)pi, (char *)po); + memcpy((char *)po, (char *)pi, bytes); if (pi->length > 0) { po->pointer = (unsigned char *)po + bytes; - _MOVC3(pi->length, (char *)pi->pointer, (char *)po->pointer); + memcpy((char *)po->pointer, (char *)pi->pointer, pi->length); } } bytes = (uint32_t)_sizeAligned(bytes + pi->length); @@ -265,9 +264,9 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); if (po) { - _MOVC3(bytes, (char *)pi, (char *)po); + memcpy((char *)po, (char *)pi, bytes); po->pointer = (char *)po + bytes; - _MOVC3(pi->arsize, pi->pointer, po->pointer); + memcpy(po->pointer, pi->pointer, pi->arsize); if (pi->aflags.coeff) po->a0 = po->pointer + (pi->a0 - pi->pointer); } @@ -295,10 +294,10 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, bytes = dscsize + pi->arsize + align_size; if (po) { - _MOVC3(dscsize, (char *)pi, (char *)po); + memcpy((char *)po, (char *)pi, dscsize); po->pointer = _align((char *)po, dscsize, align_size); if (pi->arsize > 0 && pi->pointer != NULL) - _MOVC3(pi->arsize, pi->pointer, po->pointer); + memcpy(po->pointer, pi->pointer, pi->arsize); if (pi->aflags.coeff) po->a0 = po->pointer + (pi->a0 - pi->pointer); } @@ -324,7 +323,7 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u); if (po) { - _MOVC3(bytes, (char *)pi, (char *)po); + memcpy((char *)po, (char *)pi, bytes); pdo = (mdsdsc_t **)(po->pointer = (char *)po + bytes); } bytes = (uint32_t)_sizeAligned(bytes + pi->arsize); @@ -357,7 +356,7 @@ static int copy_dx(const mdsdsc_xd_t *const in_dsc_ptr, (pi->aflags.bounds ? (uint32_t)sizeof(int) * pi->dimct * 2u : 0u)); if (po) { - _MOVC3(bytes, (char *)pi, (char *)po); + memcpy((char *)po, (char *)pi, bytes); if (pi->pointer) po->pointer = _align((char *)po, bytes, sizeof(void *)); else diff --git a/tdishr/TdiIntrinsic.c b/tdishr/TdiIntrinsic.c index d95ee73632..5019ff1dea 100644 --- a/tdishr/TdiIntrinsic.c +++ b/tdishr/TdiIntrinsic.c @@ -70,7 +70,6 @@ typedef struct _bounds int u; } BOUNDS; -#define _MOVC3(a, b, c) memcpy(c, b, a) extern int TdiFaultHandlerNoFixup(); extern int Tdi0Decompile(); extern int TdiConvert(); @@ -315,8 +314,8 @@ EXPORT int TdiIntrinsic(opcode_t opcode, int narg, mdsdsc_t *list[], { out_ptr->dtype = dsc_ptr->dtype; if ((out_ptr->length > 0) && (dsc_ptr != NULL)) - _MOVC3(out_ptr->length, dsc_ptr->pointer, - (char *)out_ptr->pointer); + memcpy((char *)out_ptr->pointer, dsc_ptr->pointer, + out_ptr->length); } break; default: diff --git a/tdishr/TdiMatrix.c b/tdishr/TdiMatrix.c index 0698fb965b..564165545c 100644 --- a/tdishr/TdiMatrix.c +++ b/tdishr/TdiMatrix.c @@ -30,7 +30,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Ken Klare, LANL CTR-7 (c)1990 */ -#define _MOVC3(a, b, c) memcpy(c, b, a) #include "tdinelements.h" #include "tdirefcat.h" #include "tdirefstandard.h" @@ -72,7 +71,7 @@ static int copy(int len, int n, char *x, int incx, char *y, int incy) break; default: for (; --n >= 0; x += incx, y += incy) - _MOVC3(len, x, y); + memcpy(y, x, len); break; } return 1; diff --git a/tdishr/TdiPower.c b/tdishr/TdiPower.c index 632aab7c3e..e2a07322b5 100644 --- a/tdishr/TdiPower.c +++ b/tdishr/TdiPower.c @@ -31,7 +31,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use double. Ken Klare, LANL P-4 (c)1990,1991 */ #include -#define _MOVC3(a, b, c) memcpy(c, b, a) #include "tdinelements.h" #include #include @@ -92,9 +91,9 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, for (; !(yy & 1) && STATUS_OK; yy >>= 1) status = Tdi3Multiply(x, x, x); if (x->class != CLASS_A) - _MOVC3(z->length, x->pointer, z->pointer); + memcpy(z->pointer, x->pointer, z->length); else - _MOVC3(z->arsize, x->pointer, z->pointer); + memcpy(z->pointer, x->pointer, z->arsize); for (; (yy >>= 1) > 0 && STATUS_OK;) { status = Tdi3Multiply(x, x, x); @@ -128,12 +127,12 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, status = TdiConvert(&one_dsc, &duno); for (; --n >= 0 && STATUS_OK; px += incx, dz.pointer += incz) { - _MOVC3(dx.length, px, xx); + memcpy(xx, px, dx.length); if ((int)(yy = *py++) <= 0) { if (yy == 0) { - _MOVC3(dz.length, uno, dz.pointer); + memcpy(dz.pointer, uno, dz.length); continue; } yy = -yy; @@ -141,7 +140,7 @@ int Tdi3Power(struct descriptor *x, struct descriptor *y, } for (; !(yy & 1) && STATUS_OK; yy >>= 1) status = Tdi3Multiply(&dx, &dx, &dx); - _MOVC3(dz.length, dx.pointer, dz.pointer); + memcpy(dz.pointer, dx.pointer, dz.length); for (; (yy >>= 1) > 0 && STATUS_OK;) { status = Tdi3Multiply(&dx, &dx, &dx); @@ -223,9 +222,9 @@ int Tdi3Merge(struct descriptor_a *pdtrue, struct descriptor_a *pdfalse, int sm = stepm, st = stept, sf = stepf; for (; --n >= 0; pm += sm, pt += st, pf += sf, po += len) if (*pm & 1) - _MOVC3(len, pt, po); + memcpy(po, pt, len); else - _MOVC3(len, pf, po); + memcpy(po, pf, len); } break; } diff --git a/tdishr/TdiScalar.c b/tdishr/TdiScalar.c index 785f8aeab5..b7045dae5a 100644 --- a/tdishr/TdiScalar.c +++ b/tdishr/TdiScalar.c @@ -32,7 +32,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Ken Klare, LANL P-4 (c)1989,1990,1991 */ -#define _MOVC3(a, b, c) memcpy(c, b, a) #include "tdinelements.h" #include "tdirefcat.h" #include "tdireffunction.h" @@ -725,7 +724,7 @@ int Tdi3DotProduct(struct descriptor_a *in1_ptr, struct descriptor_a *in2_ptr, status = TdiSum(in2_ptr, &tmp MDS_END_ARG); } if (STATUS_OK) - _MOVC3(out_ptr->length, tmp.pointer->pointer, out_ptr->pointer); + memcpy(out_ptr->pointer, tmp.pointer->pointer, out_ptr->length); break; } MdsFree1Dx(&tmp, 0); diff --git a/tdishr/TdiSort.c b/tdishr/TdiSort.c index 7e3aa1542b..17dc2d902e 100644 --- a/tdishr/TdiSort.c +++ b/tdishr/TdiSort.c @@ -60,8 +60,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define _MOVC3(a, b, c) memcpy(c, b, a) - extern int TdiGetArgs(); extern int TdiCvtArgs(); extern int TdiMasterData(); @@ -788,7 +786,7 @@ int Tdi1Union(opcode_t opcode __attribute__((unused)), int narg, if (j < len) { po += len; - _MOVC3(len, pi, po); + memcpy(po, pi, len); } } break; @@ -802,7 +800,7 @@ int Tdi1Union(opcode_t opcode __attribute__((unused)), int narg, if (j < len) { po += len; - _MOVC3(len, pi, po); + memcpy(po, pi, len); } } break; @@ -816,7 +814,7 @@ int Tdi1Union(opcode_t opcode __attribute__((unused)), int narg, if (j < len) { po += len; - _MOVC3(len, pi, po); + memcpy(po, pi, len); } } break; diff --git a/tdishr/TdiSql.c b/tdishr/TdiSql.c index 10a3b5af09..3ba06c267d 100644 --- a/tdishr/TdiSql.c +++ b/tdishr/TdiSql.c @@ -43,7 +43,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Ken Klare, LANL P-4 (c)1991,1992 */ #include -#define _MOVC3(a, b, c) memcpy(c, b, a) #include "tdirefstandard.h" #include #include /*for pow definition */ diff --git a/tdishr/TdiSubscript.c b/tdishr/TdiSubscript.c index 6e57ac328c..e1e23ad29d 100644 --- a/tdishr/TdiSubscript.c +++ b/tdishr/TdiSubscript.c @@ -66,8 +66,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define _MOVC3(a, b, c) memcpy(c, b, a) - extern int TdiGetArgs(); extern int TdiMasterData(); extern int TdiIcull(); @@ -321,7 +319,7 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], else status = MdsGet1DxS(&llen, &dtype, out_ptr); if (STATUS_OK) - _MOVC3(len, pin, out_ptr->pointer->pointer); + memcpy(out_ptr->pointer->pointer, pin, len); } else { @@ -344,8 +342,10 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], pin -= len * *px[0]; row = arr.m[0] * sizeof(int); inner: - for (j = 0; j < row; j += sizeof(int)) - _MOVC3(len, pin + len * *(int *)((char *)px[0] + j), pout), pout += len; + for (j = 0; j < row; j += sizeof(int)) { + memcpy(pout, pin + len * *(int *)((char *)px[0] + j), len); + pout += len; + } /****************************************************** Find the index to increment, reset those that overflow. Must avoid reading beyond end of vector. @@ -530,7 +530,7 @@ int Tdi1Map(opcode_t opcode, int narg __attribute__((unused)), default: while (--n >= 0) { - _MOVC3(len, (char *)abase + (len * *pindex++), po); + memcpy(po, (char *)abase + (len * *pindex++), len); po += len; } break; diff --git a/tdishr/TdiTrans.c b/tdishr/TdiTrans.c index ace4043834..90c6c24dc7 100644 --- a/tdishr/TdiTrans.c +++ b/tdishr/TdiTrans.c @@ -78,7 +78,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. NEED to know about REPLICATE and SPREAD with subscript ranges. */ -#define _MOVC3(a, b, c) memcpy(c, b, a) #ifdef WORDS_BIGENDIAN #define MaskTrue (pi0[leni - 1] & 1) #else @@ -293,11 +292,11 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) pmask = (mdsdsc_t *)&ncopies; /** scalar to simple vector **/ if (rank == 0) - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); /** simple and coefficient vector **/ else { - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); arr.m[dim] *= ncopies; } arr.arsize *= ncopies; @@ -329,18 +328,18 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) pmask = (mdsdsc_t *)&ncopies; /** scalar to simple vector **/ if (rank == 0) - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); else if (rank >= MAX_DIMS) status = TdiNDIM_OVER; /** coefficient vector **/ else if (pa->aflags.coeff) { - _MOVC3(head, (char *)pa, (char *)&arr); - _MOVC3((short)(sizeof(int) * (rank - dim) * 2), + memcpy((char *)&arr, (char *)pa, head); + memcpy((char *)&arr.m[rank + 2 * dim + 3], (char *)&arr.m[rank + 2 * dim], - (char *)&arr.m[rank + 2 * dim + 3]); - _MOVC3((short)(sizeof(int) * (rank - dim)), (char *)&arr.m[dim], - (char *)&arr.m[dim + 1]); + (short)(sizeof(int) * (rank - dim) * 2)); + memcpy((char *)&arr.m[dim + 1], (char *)&arr.m[dim], + (short)(sizeof(int) * (rank - dim))); arr.m[dim] = ncopies; arr.m[rank + 2 * dim + 1] = 0; arr.m[rank + 2 * dim + 2] = ncopies - 1; @@ -349,7 +348,7 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) /** simple vector to 2-D **/ else { - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); arr.dimct = 2; arr.aflags.coeff = 1; arr.a0 = arr.pointer; @@ -385,7 +384,7 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) else if (pfun->f2 == Tdi2Mask2) { psig = 0; - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); arr.arsize = pa->length * rank; status = MdsGet1DxA((mdsdsc_a_t *)&arr, &digits, &out_dtype, out_ptr); } @@ -398,13 +397,13 @@ int Tdi1Trans(int opcode, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) --psig->ndesc; for (j = dim; ++j < ndim;) psig->dimensions[j - 1] = psig->dimensions[j]; - _MOVC3(head, (char *)pa, (char *)&arr); + memcpy((char *)&arr, (char *)pa, head); arr.arsize /= arr.m[dim]; - _MOVC3((short)(sizeof(int) * (rank - dim - 1)), (char *)&arr.m[dim + 1], - (char *)&arr.m[dim]); - _MOVC3((short)(sizeof(int) * (rank - dim - 1) * 2), + memcpy((char *)&arr.m[dim], (char *)&arr.m[dim + 1], + (short)(sizeof(int) * (rank - dim - 1))); + memcpy((char *)&arr.m[rank + 2 * dim - 1], (char *)&arr.m[rank + 2 * dim + 2], - (char *)&arr.m[rank + 2 * dim - 1]); + (short)(sizeof(int) * (rank - dim - 1) * 2)); --arr.dimct; status = MdsGet1DxA((mdsdsc_a_t *)&arr, &digits, &out_dtype, out_ptr); } From e25968ba46a84717bf8f7a0f586ce72f91ec8c39 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Tue, 4 May 2021 14:45:48 +0200 Subject: [PATCH 13/27] Build: platform builds on empty/new release folder and format (#2304) * fixed platform builds on empty release folder; and format * fixed python3 issue with pexpect --- deploy/packaging/alpine/build_apks.sh | 26 +- deploy/packaging/windows/create_installer.sh | 46 +-- deploy/platform/alpine/alpine_docker_build.sh | 106 +++---- deploy/platform/debian/debian_docker_build.sh | 273 +++++++++--------- deploy/platform/redhat/redhat_build_rpms.py | 10 +- deploy/platform/redhat/redhat_docker_build.sh | 208 +++++++------ 6 files changed, 328 insertions(+), 341 deletions(-) diff --git a/deploy/packaging/alpine/build_apks.sh b/deploy/packaging/alpine/build_apks.sh index 9f3c4a2e5a..2c752256cc 100755 --- a/deploy/packaging/alpine/build_apks.sh +++ b/deploy/packaging/alpine/build_apks.sh @@ -1,24 +1,26 @@ #!/bin/bash -[ -z ${BRANCH} ] && exit 1 +[ -z "${BUILDROOT}" ] && exit 1 +[ -z "${BRANCH}" ] && exit 1 +[ -z "${RELEASE_VERSION}" ] && exit 1 +[ -z "${ARCH}" ] && exit 1 +[ -z "${DISTNAME}" ] && exit 1 pckdir=$(dirname $(realpath $0)) export HOME=/workspace cd /workspace signkeys="/sign_keys/mdsplus@mdsplus.org-589e05b6.rsa" mkdir -p /workspace/.abuild -if [ -f $signkeys ] -then - echo -e "PACKAGER_PRIVKEY=\"$signkeys\"\n" > /workspace/.abuild/abuild.conf -elif [ ! -f /workspace/.abuild/abuild.conf ] -then +if [ -f $signkeys ]; then + echo -e "PACKAGER_PRIVKEY=\"$signkeys\"\n" >/workspace/.abuild/abuild.conf +elif [ ! -f /workspace/.abuild/abuild.conf ]; then touch /workspace/.abuild/abuild.conf abuild-keygen -aqn # generate new keys fi # we have to unset srcdir as it is a reserved name in abuild # in the process of building the apks it will wipe $srcdir srcdir= \ -BUILDROOT=/workspace/releasebld/buildroot \ -BRANCH=${BRANCH} \ -RELEASE_VERSION=${RELEASE_VERSION} \ -ARCH=${ARCH} \ -DISTNAME=${DISTNAME} \ -${pckdir}/alpine_build_apks.py + BUILDROOT=${BUILDROOT} \ + BRANCH=${BRANCH} \ + RELEASE_VERSION=${RELEASE_VERSION} \ + ARCH=${ARCH} \ + DISTNAME=${DISTNAME} \ + ${pckdir}/alpine_build_apks.py diff --git a/deploy/packaging/windows/create_installer.sh b/deploy/packaging/windows/create_installer.sh index 47f759156f..9788cfa433 100755 --- a/deploy/packaging/windows/create_installer.sh +++ b/deploy/packaging/windows/create_installer.sh @@ -1,7 +1,7 @@ #!/bin/bash -if [ -z ${MDSPLUS_DIR} ] -then MDSPLUS_DIR=/workspace/releasebld/buildroot +if [ -z ${MDSPLUS_DIR} ]; then + MDSPLUS_DIR=/workspace/releasebld/buildroot fi abort=0 @@ -9,30 +9,30 @@ major=$(echo ${RELEASE_VERSION} | cut -d. -f1) minor=$(echo ${RELEASE_VERSION} | cut -d. -f2) release=$(echo ${RELEASE_VERSION} | cut -d. -f3) -if [ "${BRANCH}" = "stable" ] -then bname="" -else bname="-${BRANCH}" +if [ "${BRANCH}" = "stable" ]; then + bname="" +else + bname="-${BRANCH}" fi pushd ${MDSPLUS_DIR} makensis -V4 -DMAJOR=${major} -DMINOR=${minor} -DRELEASE=${release} -DFLAVOR=${bname} -NOCD -DBRANCH=${BRANCH} \ - -DINCLUDE=${srcdir}/deploy/packaging/${PLATFORM} \ - -DOUTDIR=/release/${BRANCH} -Dsrcdir=${srcdir} ${vs} ${srcdir}/deploy/packaging/${PLATFORM}/mdsplus.nsi + -DINCLUDE=${srcdir}/deploy/packaging/${PLATFORM} \ + -DOUTDIR=/release/${BRANCH} -Dsrcdir=${srcdir} ${vs} ${srcdir}/deploy/packaging/${PLATFORM}/mdsplus.nsi popd -if [ -d /sign_keys ] -then - echo "Signing installer" - if ( osslsigncode sign -certs /sign_keys/mdsplus.spc \ - -key /sign_keys/mdsplus.pvk -pass mdsplus \ - -n "MDSplus" -i http://www.mdsplus.org/ \ - -in /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe \ - -out /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe - ) - then - mv -v /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe \ - /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe - echo "Installer successfully signed" - else - echo "Failed to sign installer" - fi +if [ -d /sign_keys ]; then + echo "Signing installer" + if ( + osslsigncode sign -certs /sign_keys/mdsplus.spc \ + -key /sign_keys/mdsplus.pvk -pass mdsplus \ + -n "MDSplus" -i http://www.mdsplus.org/ \ + -in /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe \ + -out /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe + ); then + mv -v /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe \ + /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe + echo "Installer successfully signed" + else + echo "Failed to sign installer" + fi fi diff --git a/deploy/platform/alpine/alpine_docker_build.sh b/deploy/platform/alpine/alpine_docker_build.sh index 4ab5c1804d..5574107548 100644 --- a/deploy/platform/alpine/alpine_docker_build.sh +++ b/deploy/platform/alpine/alpine_docker_build.sh @@ -1,4 +1,3 @@ - #!/bin/bash # # alphine_docker_build is used to build, test, package and add apk's to a @@ -11,71 +10,76 @@ testarmhf="arm armv6-alpine-linux-muslgnueabihf bin lib" srcdir=$(readlink -f $(dirname ${0})/../..) gethost() { - case $1 in - x86) echo i686-linux;; - x86_64) echo x86_64-linux;; - armhf) echo armv6-alpine-linux-muslgnueabihf;; - esac + case $1 in + x86) echo i686-linux ;; + x86_64) echo x86_64-linux ;; + armhf) echo armv6-alpine-linux-muslgnueabihf ;; + esac } -if [ -z "$host" ] -then - host=$(gethost ${ARCH}) +if [ -z "$host" ]; then + host=$(gethost ${ARCH}) fi export CFLAGS="-DASSERT_LINE_TYPE=int" export CPPFLAGS="-DASSERT_LINE_TYPE=int" runtests() { - testarch ${ARCH} ${host} bin lib - checktests + testarch ${ARCH} ${host} bin lib + checktests } -makelist(){ - echo +makelist() { + echo } buildrelease() { - ### Build release version of MDSplus and then construct installer debs - set -e - MDSPLUS_DIR=/workspace/releasebld/buildroot/usr/local/mdsplus - mkdir -p ${MDSPLUS_DIR} - mkdir -p /workspace/releasebld/${ARCH} - rm -Rf /workspace/releasebld/${ARCH}/* - pushd /workspace/releasebld/${ARCH} - config ${ARCH} ${host} bin lib ${ALPHA_DEBUG_INFO} - if [ -z "$NOMAKE" ]; then - $MAKE - $MAKE install - fi - popd; - if [ -z "$NOMAKE" ] - then - rm -Rf /release/${BRANCH}/${ARCH} - mkdir -p /release/${BRANCH}/${ARCH} - ${srcdir}/deploy/packaging/alpine/build_apks.sh + ### Build release version of MDSplus and then construct installer debs + set -e + RELEASEBLD=/workspace/releasebld + BUILDROOT=${RELEASEBLD}/buildroot + MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus + rm -Rf ${RELEASEBLD} + mkdir -p ${RELEASEBLD} ${BUILDROOT} ${MDSPLUS_DIR} + pushd ${RELEASEBLD} + config ${ARCH} ${host} bin lib ${ALPHA_DEBUG_INFO} + if [ -z "$NOMAKE" ]; then + $MAKE + $MAKE install + fi + popd + if [ -z "$NOMAKE" ]; then + rm -Rf /release/${BRANCH}/${ARCH} /release/${BRANCH}/noarch + mkdir -p /release/${BRANCH}/${ARCH} /release/${BRANCH}/noarch + BUILDROOT=${BUILDROOT} \ + BRANCH=${BRANCH} \ + RELEASE_VERSION=${RELEASE_VERSION} \ + ARCH=${ARCH} \ + DISTNAME=${DISTNAME} \ + ${srcdir}/deploy/packaging/alpine/build_apks.sh fi } publish() { - ### DO NOT CLEAN /publish as it may contain valid older release apks - ## this will move new files into publish and update APKINDEX.tar.gz - # if NEW.tar.gz exists or if an old APKINDEX.tar.gz does not yet exist, - # it will create a new repository (takes longer, exspecially on a remote fs) - R=/release/${BRANCH} - P=/publish/${BRANCH} - mkdir -p $P/${ARCH} $P/noarch - cd $P - rsync -a $R/${ARCH}/*.apk $P/${ARCH}/ &&: - checkstatus abort "Failure: Problem copying arch apks to publish area!" $? - rsync -a $R/noarch/*.apk $P/noarch/ &&: - checkstatus abort "Failure: Problem copying noarch apks to publish area!" $? - if [ -r $P/${ARCH}/APKINDEX.tar.gz -a ! -r $P/${ARCH}/NEW.tar.gz ] - then apk index -x $P/${ARCH}/APKINDEX.tar.gz -o $P/${ARCH}/NEW.tar.gz $P/${ARCH}/*.apk noarch/*.apk - else apk index -o $P/${ARCH}/NEW.tar.gz $P/${ARCH}/*.apk noarch/*.apk - fi - checkstatus abort "Failure: Problem updating apk repository in publish!" $? - abuild-sign -k /sign_keys/mdsplus@mdsplus.org-589e05b6.rsa $P/${ARCH}/NEW.tar.gz - checkstatus abort "Failure: Problem signing apk repository in publish!" $? - mv -f $P/${ARCH}/NEW.tar.gz $P/${ARCH}/APKINDEX.tar.gz + ### DO NOT CLEAN /publish as it may contain valid older release apks + ## this will move new files into publish and update APKINDEX.tar.gz + # if NEW.tar.gz exists or if an old APKINDEX.tar.gz does not yet exist, + # it will create a new repository (takes longer, exspecially on a remote fs) + R=/release/${BRANCH} + P=/publish/${BRANCH} + mkdir -p $P/${ARCH} $P/noarch + cd $P + rsync -a $R/${ARCH}/*.apk $P/${ARCH}/ && : + checkstatus abort "Failure: Problem copying arch apks to publish area!" $? + rsync -a $R/noarch/*.apk $P/noarch/ && : + checkstatus abort "Failure: Problem copying noarch apks to publish area!" $? + if [ -r $P/${ARCH}/APKINDEX.tar.gz -a ! -r $P/${ARCH}/NEW.tar.gz ]; then + apk index -x $P/${ARCH}/APKINDEX.tar.gz -o $P/${ARCH}/NEW.tar.gz $P/${ARCH}/*.apk noarch/*.apk + else + apk index -o $P/${ARCH}/NEW.tar.gz $P/${ARCH}/*.apk noarch/*.apk + fi + checkstatus abort "Failure: Problem updating apk repository in publish!" $? + abuild-sign -k /sign_keys/mdsplus@mdsplus.org-589e05b6.rsa $P/${ARCH}/NEW.tar.gz + checkstatus abort "Failure: Problem signing apk repository in publish!" $? + mv -f $P/${ARCH}/NEW.tar.gz $P/${ARCH}/APKINDEX.tar.gz } diff --git a/deploy/platform/debian/debian_docker_build.sh b/deploy/platform/debian/debian_docker_build.sh index cec429a585..a47166c2df 100755 --- a/deploy/platform/debian/debian_docker_build.sh +++ b/deploy/platform/debian/debian_docker_build.sh @@ -16,25 +16,24 @@ srcdir=$(readlink -e $(dirname ${0})/../..) # configure based on ARCH case "${ARCH}" in - "amd64") - host=x86_64-linux - gsi_param="--with-gsi=/usr:gcc64" - bits=64 - ;; - "armhf") - host=arm-linux-gnueabihf - gsi_param="--with-gsi=/usr:gcc32" - bits=32 - ;; - *) - host=i686-linux - gsi_param="--with-gsi=/usr:gcc32" - bits=32 - ;; +"amd64") + host=x86_64-linux + gsi_param="--with-gsi=/usr:gcc64" + bits=64 + ;; +"armhf") + host=arm-linux-gnueabihf + gsi_param="--with-gsi=/usr:gcc32" + bits=32 + ;; +*) + host=i686-linux + gsi_param="--with-gsi=/usr:gcc32" + bits=32 + ;; esac -if [ "$OS" == "debian_wheezy" -o "${OS:0:7}" = "debian7" ] -then +if [ "$OS" == "debian_wheezy" -o "${OS:0:7}" = "debian7" ]; then export JDK_DIR=/usr/lib/jvm/java-7-openjdk-${ARCH} fi config_param="${bits} ${host} bin lib ${gsi_param}" @@ -42,109 +41,98 @@ runtests() { testarch ${config_param} checktests } -makelist(){ - dpkg -c $1 | \ - grep -v MDSplus/dist | \ - grep -v MDSplus/build | \ - grep -v MDSplus/doc | \ - grep -v egg-info | \ - grep -v '/$' | \ - awk '{for (i=6; i "); print a[1]}' | \ +makelist() { + dpkg -c $1 | + grep -v MDSplus/dist | + grep -v MDSplus/build | + grep -v MDSplus/doc | + grep -v egg-info | + grep -v '/$' | + awk '{for (i=6; i "); print a[1]}' | sort } debtopkg() { - if ( echo $1 | grep mdsplus${2}_${3} >/dev/null ) - then - echo "" - else - echo ${1:8+${#2}:-${#3}-${#4}-6} - fi + if (echo $1 | grep mdsplus${2}_${3} >/dev/null); then + echo "" + else + echo ${1:8+${#2}:-${#3}-${#4}-6} + fi } buildrelease() { - ### Build release version of MDSplus and then construct installer debs - major=$(echo ${RELEASE_VERSION} | cut -d. -f1) - minor=$(echo ${RELEASE_VERSION} | cut -d. -f2) - release=$(echo ${RELEASE_VERSION} | cut -d. -f3) - set -e - mkdir -p /release/${BRANCH}/DEBS/${ARCH} - rm -Rf /workspace/releasebld/* /release/${BRANCH}/DEBS/${ARCH}/* - MDSPLUS_DIR=/workspace/releasebld/buildroot/usr/local/mdsplus - mkdir -p ${MDSPLUS_DIR}; - mkdir -p /workspace/releasebld/${bits}; - pushd /workspace/releasebld/${bits}; - config ${config_param} ${ALPHA_DEBUG_INFO} - if [ -z "$NOMAKE" ]; then - $MAKE - $MAKE install - fi - popd; + ### Build release version of MDSplus and then construct installer debs + set -e + RELEASEDEBS=/release/${BRANCH}/DEBS/${ARCH} + RELEASEBLD=/workspace/releasebld + BUILDROOT=${RELEASEBLD}/buildroot + MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus + rm -Rf ${RELEASEBLD}/${bits} + mkdir -p ${RELEASEBLD}/${bits} ${BUILDROOT} ${MDSPLUS_DIR} + rm -Rf ${RELEASEDEBS} + mkdir -p ${RELEASEDEBS} + pushd ${RELEASEBLD}/${bits} + config ${config_param} ${ALPHA_DEBUG_INFO} + if [ -z "$NOMAKE" ]; then + $MAKE + $MAKE install + fi + popd if [ -z "$NOMAKE" ]; then - BUILDROOT=/workspace/releasebld/buildroot \ - BRANCH=${BRANCH} \ - RELEASE_VERSION=${RELEASE_VERSION} \ - ARCH=${ARCH} \ - DISTNAME=${DISTNAME} \ - PLATFORM=${PLATFORM} \ - ${srcdir}/deploy/platform/debian/debian_build_debs.py + BRANCH=${BRANCH} \ + RELEASE_VERSION=${RELEASE_VERSION} \ + ARCH=${ARCH} \ + DISTNAME=${DISTNAME} \ + BUILDROOT=${BUILDROOT} \ + PLATFORM=${PLATFORM} \ + ${srcdir}/deploy/platform/debian/debian_build_debs.py baddeb=0 - for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*\.deb") - do - pkg=$(debtopkg $(basename $deb) "${BNAME}" ${RELEASE_VERSION} ${ARCH}) - if [ "${#pkg}" = "0" ] - then - continue - fi - if [ "${pkg: -4}" = "_bin" ] # ends with _bin - then - checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg.$ARCH + for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*${RELEASE_VERSION}_*\.deb"); do + pkg=$(debtopkg $(basename $deb) "${BNAME}" ${RELEASE_VERSION} ${ARCH}) + if [ "${#pkg}" = "0" ]; then + continue + fi + if [ "${pkg: -4}" = "_bin" ]; then # ends with _bin + checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg.$ARCH + else + checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg.noarch + fi + if [ "$UPDATEPKG" = "yes" ]; then + mkdir -p ${srcdir}/deploy/packaging/${PLATFORM} + makelist $deb >${checkfile} + else + set +e + echo "Checking contents of $(basename $deb)" + if (diff <(makelist $deb) <(sort ${checkfile})); then + echo "Contents of $(basename $deb) is correct." else - checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg.noarch + checkstatus baddeb "Failure: Problem with contents of $(basename $deb)" 1 fi - if [ "$UPDATEPKG" = "yes" ] - then - mkdir -p ${srcdir}/deploy/packaging/${PLATFORM} - makelist $deb > ${checkfile} - else - set +e - echo "Checking contents of $(basename $deb)" - if ( diff <(makelist $deb) <(sort ${checkfile}) ) - then - echo "Contents of $(basename $deb) is correct." - else - checkstatus baddeb "Failure: Problem with contents of $(basename $deb)" 1 - fi - set -e - fi + set -e + fi done checkstatus abort "Failure: Problem with contents of one or more debs. (see above)" $baddeb - if [ -z "$abort" ] || [ "$abort" = "0" ] - then - echo "Building repo"; - mkdir -p /release/repo/conf - mkdir -p /release/repo/db - mkdir -p /release/repo/dists - mkdir -p /release/repo/pool - if [ "${BRANCH}" = "alpha" -o "${BRANCH}" = "stable" ] - then + if [ -z "$abort" ] || [ "$abort" = "0" ]; then + echo "Building repo" + mkdir -p /release/repo/conf + mkdir -p /release/repo/db + mkdir -p /release/repo/dists + mkdir -p /release/repo/pool + if [ "${BRANCH}" = "alpha" -o "${BRANCH}" = "stable" ]; then component="" - else + else component=" ${BRANCH}" - fi - GPG_HOME="" - if [ -d /sign_keys/${OS}/.gnupg ] - then - GPG_HOME="/sign_keys/${OS}" - elif [ -d /sign_keys/.gnupg ] - then - GPG_HOME="/sign_keys" - fi - if [ ! -z "$GPG_HOME" ] - then - SIGN_WITH="SignWith: MDSplus" - rsync -a ${GPG_HOME}/.gnupg /tmp - fi - cat - < /release/repo/conf/distributions + fi + GPG_HOME="" + if [ -d /sign_keys/${OS}/.gnupg ]; then + GPG_HOME="/sign_keys/${OS}" + elif [ -d /sign_keys/.gnupg ]; then + GPG_HOME="/sign_keys" + fi + if [ ! -z "$GPG_HOME" ]; then + SIGN_WITH="SignWith: MDSplus" + rsync -a ${GPG_HOME}/.gnupg /tmp + fi + cat - </release/repo/conf/distributions Origin: MDSplus Development Team Label: MDSplus Codename: MDSplus @@ -161,48 +149,47 @@ Components: alpha stable${component} Description: Previous MDSplus release packages ${SIGN_WITH} EOF - pushd /release/repo - reprepro clearvanished - for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*${major}\.${minor}\.${release}_*") - do - if [ -z "$abort" ] || [ "$abort" = "0" ] - then - :&& HOME=/tmp reprepro -V -C ${BRANCH} includedeb MDSplus $deb - checkstatus abort "Failure: Problem installing $deb into repository." $? + pushd /release/repo + reprepro clearvanished + for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*${RELEASE_VERSION}_*\.deb"); do + if [ -z "$abort" ] || [ "$abort" = "0" ]; then + : && HOME=/tmp reprepro -V -C ${BRANCH} includedeb MDSplus $deb + checkstatus abort "Failure: Problem installing $deb into repository." $? else break fi - done - popd - fi #abort - fi #nomake + done + popd + fi #abort + fi #nomake } - publish() { - ### DO NOT CLEAN /publish as it may contain valid older release packages - mkdir -p /publish/${BRANCH}/DEBS - rsync -a /release/${BRANCH}/DEBS/${ARCH} /publish/${BRANCH}/DEBS/ - LAST_RELEASE_INFO=/publish/${BRANCH}_${OS} - if [ ! -r /publish/repo ] - then - :&& rsync -a /release/repo /publish/ - checkstatus abort "Failure: Problem copying repo into publish area." $? + ### DO NOT CLEAN /publish as it may contain valid older release packages + mkdir -p /publish/${BRANCH}/DEBS + rsync -a /release/${BRANCH}/DEBS/${ARCH} /publish/${BRANCH}/DEBS/ + LAST_RELEASE_INFO=/publish/${BRANCH}_${OS} + if [ ! -r /publish/repo ]; then + : && rsync -a /release/repo /publish/ + checkstatus abort "Failure: Problem copying repo into publish area." $? + else + pushd /publish/repo + rsync -a /release/repo/conf/distributions /publish/repo/conf/ + reprepro clearvanished + : && env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus ../${BRANCH}/DEBS/${ARCH}/*${RELEASE_VERSION}_*.deb || + env HOME=/sign_keys reprepro export MDSplus + checkstatus abort "Failure: Problem installing ${BRANCH} into debian repository." $? + if [ -f ${LAST_RELEASE_INFO} ]; then + PREVIOUS_VERSION="$(cat ${LAST_RELEASE_INFO})" else - pushd /publish/repo - rsync -a /release/repo/conf/distributions /publish/repo/conf/ - reprepro clearvanished - :&& env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus ../${BRANCH}/DEBS/${ARCH}/*${RELEASE_VERSION}_* \ - || env HOME=/sign_keys reprepro export MDSplus - checkstatus abort "Failure: Problem installing ${BRANCH} into debian repository." $? - PREVIOUS_VERSION="$(cat ${LAST_RELEASE_INFO})" - echo "PREVIOUS_VERSION=${PREVIOUS_VERSION}" - if [ ! -z $PREVIOUS_VERSION ] - then - :&& env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus-previous ../${BRANCH}/DEBS/${ARCH}/*${PREVIOUS_VERSION}_* \ - || env HOME=/sign_keys reprepro export MDSplus-previous - checkstatus abort "Failure: Problem installing previous ${BRANCH} into debian repository." $? - fi - popd + PREVIOUS_VERSION= + fi + echo "PREVIOUS_VERSION=${PREVIOUS_VERSION}" + if [ -n $PREVIOUS_VERSION ]; then + : && env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus-previous ../${BRANCH}/DEBS/${ARCH}/*${PREVIOUS_VERSION}_*.deb || + env HOME=/sign_keys reprepro export MDSplus-previous + checkstatus abort "Failure: Problem installing previous ${BRANCH} into debian repository." $? fi + popd + fi } diff --git a/deploy/platform/redhat/redhat_build_rpms.py b/deploy/platform/redhat/redhat_build_rpms.py index 6380ff96af..eec423e868 100755 --- a/deploy/platform/redhat/redhat_build_rpms.py +++ b/deploy/platform/redhat/redhat_build_rpms.py @@ -258,7 +258,15 @@ def buildRpms(): os.stat('/sign_keys/.gnupg') try: cmd = "/bin/sh -c 'rsync -a /sign_keys /tmp/; HOME=/tmp/sign_keys rpmsign --addsign /release/%(branch)s/RPMS/*/*%(major)d.%(minor)d-%(release)d*.rpm'" % info - child = pexpect.spawn(cmd, timeout=60, logfile=sys.stdout) + try: + if sys.version_info < (3,): + bout = sys.stdout + else: + bout = sys.stdout.buffer + except: + child = pexpect.spawn(cmd, timeout=60) + else: + child = pexpect.spawn(cmd, timeout=60, logfile=bout) index = child.expect(["Enter pass phrase: ", pexpect.EOF]) if index == 0: child.sendline("") diff --git a/deploy/platform/redhat/redhat_docker_build.sh b/deploy/platform/redhat/redhat_docker_build.sh index 02ed3dfd0f..b7b8fd23e1 100755 --- a/deploy/platform/redhat/redhat_docker_build.sh +++ b/deploy/platform/redhat/redhat_docker_build.sh @@ -14,17 +14,16 @@ # do_createrepo() { - repodir=$1 - tmpdir=$(mktemp -d) - trap 'rm -Rf ${tmpdir}' EXIT - if [ -d ${repodir}/${BRANCH}/RPMS/repodata ] - then - rsync -a ${repodir}/${BRANCH}/RPMS/repodata ${tmpdir} - update_args="--update --cachedir ${repodir}/${BRANCH}/cache ${use_deltas}" - fi - :&& createrepo -q $update_args -o ${tmpdir} ${repodir}/${BRANCH}/RPMS - checkstatus abort "Failure: Problem creating rpm repository in ${repodir}!" $? - :&& rsync -a ${tmpdir}/repodata ${repodir}/${BRANCH}/RPMS/ + repodir=$1 + tmpdir=$(mktemp -d) + trap 'rm -Rf ${tmpdir}' EXIT + if [ -d ${repodir}/${BRANCH}/RPMS/repodata ]; then + rsync -a ${repodir}/${BRANCH}/RPMS/repodata ${tmpdir} + update_args="--update --cachedir ${repodir}/${BRANCH}/cache ${use_deltas}" + fi + : && createrepo -q $update_args -o ${tmpdir} ${repodir}/${BRANCH}/RPMS + checkstatus abort "Failure: Problem creating rpm repository in ${repodir}!" $? + : && rsync -a ${tmpdir}/repodata ${repodir}/${BRANCH}/RPMS/ } srcdir=$(readlink -e $(dirname ${0})/../..) @@ -33,79 +32,69 @@ test64="64 x86_64-linux bin64 lib64 --with-gsi=/usr:gcc64" test32="32 i686-linux bin32 lib32 --with-gsi=/usr:gcc32 --with-valgrind-lib=/usr/lib32/valgrind" runtests() { - # run tests with the platform specific params read from test32 and test64 - testarch ${test64} - if [ "${ARCHES}" != "amd64" ] - then - if [ -f /usr/bin/python-i686 ] - then - PYTHON=/usr/bin/python-i686 testarch ${test32}; - else - testarch ${test32}; - fi + # run tests with the platform specific params read from test32 and test64 + testarch ${test64} + if [ "${ARCHES}" != "amd64" ]; then + if [ -f /usr/bin/python-i686 ]; then + PYTHON=/usr/bin/python-i686 testarch ${test32} + else + testarch ${test32} fi - checktests; + fi + checktests } -makelist(){ - rpm2cpio $1 | \ - cpio --list --quiet | \ - grep -v MDSplus/dist | \ - grep -v MDSplus/doc | \ - grep -v MDSplus/build | \ - grep -v egg-info | \ - grep -v '\.build\-id' | \ - sort +makelist() { + rpm2cpio $1 | + cpio --list --quiet | + grep -v MDSplus/dist | + grep -v MDSplus/doc | + grep -v MDSplus/build | + grep -v egg-info | + grep -v '\.build\-id' | + sort } -buildrelease(){ - ### - ### Clean up workspace - ### - rm -Rf /workspace/releasebld - ### - ### Build release version of MDSplus and then construct installer rpms - ### - set -e - MDSPLUS_DIR=/workspace/releasebld/buildroot/usr/local/mdsplus - mkdir -p ${MDSPLUS_DIR}; - mkdir -p /workspace/releasebld/64; - pushd /workspace/releasebld/64; - config ${test64} ${ALPHA_DEBUG_INFO} +buildrelease() { + set -e + RELEASEBLD=/workspace/releasebld + BUILDROOT=${RELEASEBLD}/buildroot + MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus + rm -Rf ${RELEASEBLD} + mkdir -p ${RELEASEBLD}/64 ${BUILDROOT} ${MDSPLUS_DIR} + pushd ${RELEASEBLD}/64 + config ${test64} ${ALPHA_DEBUG_INFO} + if [ -z "$NOMAKE" ]; then + $MAKE + $MAKE install + fi + popd + if [ "${ARCHES}" != "amd64" ]; then + mkdir -p ${RELEASEBLD}/32 + pushd ${RELEASEBLD}/32 + config ${test32} ${ALPHA_DEBUG_INFO} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install fi - popd; - if [ "${ARCHES}" != "amd64" ]; then - mkdir -p /workspace/releasebld/32; - pushd /workspace/releasebld/32; - config ${test32} ${ALPHA_DEBUG_INFO} - if [ -z "$NOMAKE" ]; then - $MAKE - $MAKE install - fi - popd - fi + popd + fi if [ -z "$NOMAKE" ]; then - BUILDROOT=/workspace/releasebld/buildroot - echo "Building rpms"; + echo "Building rpms" ### ### Setup repository rpm info ### - mkdir -p ${BUILDROOT}/etc/yum.repos.d; - mkdir -p ${BUILDROOT}/etc/pki/rpm-gpg/; - cp ${srcdir}/deploy/platform/redhat/RPM-GPG-KEY-MDSplus ${BUILDROOT}/etc/pki/rpm-gpg/; - if [ -d /sign_keys/.gnupg ] - then - GPGCHECK="1" + mkdir -p ${BUILDROOT}/etc/yum.repos.d + mkdir -p ${BUILDROOT}/etc/pki/rpm-gpg/ + cp ${srcdir}/deploy/platform/redhat/RPM-GPG-KEY-MDSplus ${BUILDROOT}/etc/pki/rpm-gpg/ + if [ -d /sign_keys/.gnupg ]; then + GPGCHECK="1" else - echo "WARNING: Signing Keys Unavailable. Building unsigned RPMS" - GPGCHECK="0" + echo "WARNING: Signing Keys Unavailable. Building unsigned RPMS" + GPGCHECK="0" fi - if [ -r /sign_keys/RPM-GPG-KEY-MDSplus ] - then - cp /sign_keys/RPM-GPG-KEY-MDSplus ${BUILDROOT}/etc/pki/rpm-gpg/; + if [ -r /sign_keys/RPM-GPG-KEY-MDSplus ]; then + cp /sign_keys/RPM-GPG-KEY-MDSplus ${BUILDROOT}/etc/pki/rpm-gpg/ fi - cat - > ${BUILDROOT}/etc/yum.repos.d/mdsplus${BNAME}.repo <${BUILDROOT}/etc/yum.repos.d/mdsplus${BNAME}.repo </dev/null ) || ( echo ${pkg} | grep repo >/dev/null ) - then - continue - fi - pkg=${pkg}.$(echo $(basename $rpm) | cut -f5 -d- | cut -f3 -d.) - checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg - if [ "$UPDATEPKG" = "yes" ] - then - mkdir -p ${srcdir}/deploy/packaging/${PLATFORM}/ - makelist $rpm > ${checkfile} + for rpm in $(find /release/${BRANCH}/RPMS -name '*\.rpm'); do + pkg=$(echo $(basename $rpm) | cut -f3 -d-) + # + # Skip main installer which only has package dependencies and no files + # Skip the repo rpm which will contain the branch name + # + if (echo ${pkg} | grep '\.' >/dev/null) || (echo ${pkg} | grep repo >/dev/null); then + continue + fi + pkg=${pkg}.$(echo $(basename $rpm) | cut -f5 -d- | cut -f3 -d.) + checkfile=${srcdir}/deploy/packaging/${PLATFORM}/$pkg + if [ "$UPDATEPKG" = "yes" ]; then + mkdir -p ${srcdir}/deploy/packaging/${PLATFORM}/ + makelist $rpm >${checkfile} + else + echo "Checking contents of $(basename $rpm)" + if (diff <(makelist $rpm) <(sort ${checkfile})); then + echo "Contents of $(basename $rpm) is correct." else - echo "Checking contents of $(basename $rpm)" - if ( diff <(makelist $rpm) <(sort ${checkfile}) ) - then - echo "Contents of $(basename $rpm) is correct." - else - checkstatus badrpm "Failure: Problem with contents of $(basename $rpm)" 1 - fi + checkstatus badrpm "Failure: Problem with contents of $(basename $rpm)" 1 fi + fi done checkstatus abort "Failure: Problem with contents of one or more rpms. (see above)" $badrpm fi #nomake } -publish(){ - ### DO NOT CLEAN /publish as it may contain valid older release rpms - :&& rsync -a --exclude=repodata /release/${BRANCH}/* /publish/${BRANCH} - checkstatus abort "Failure: Problem copying release rpms to publish area!" $? - if ( createrepo -h | grep '\-\-deltas' > /dev/null ) - then - use_deltas="--deltas" - fi - do_createrepo /publish - checkstatus abort "Failure: Problem updating rpm repository in publish area!" $? +publish() { + ### DO NOT CLEAN /publish as it may contain valid older release rpms + mkdir -p /publish/${BRANCH} + : && rsync -a --exclude=repodata /release/${BRANCH}/* /publish/${BRANCH} + checkstatus abort "Failure: Problem copying release rpms to publish area!" $? + if (createrepo -h | grep '\-\-deltas' >/dev/null); then + use_deltas="--deltas" + fi + do_createrepo /publish + checkstatus abort "Failure: Problem updating rpm repository in publish area!" $? } From 1cdd50332cd668311277254d8db39c6b8ca751d6 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 15:02:09 +0200 Subject: [PATCH 14/27] Build: isolate docker containers with --network=none --- deploy/platform/platform_build.sh | 181 ++++++++++++++---------------- 1 file changed, 87 insertions(+), 94 deletions(-) diff --git a/deploy/platform/platform_build.sh b/deploy/platform/platform_build.sh index df27bf868f..864f69f52f 100755 --- a/deploy/platform/platform_build.sh +++ b/deploy/platform/platform_build.sh @@ -8,60 +8,55 @@ # set -e volume() { - if [ -n "$1" ] - then echo "-v $(realpath ${1}):${2}" - fi + if [ -n "$1" ]; then + echo "-v $(realpath ${1}):${2}" + fi } RED() { - if [ "$COLOR" = "yes" ] - then echo -e "\033[31m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[31m" + fi } GREEN() { - if [ "$COLOR" = "yes" ] - then echo -e "\033[32m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[32m" + fi } NORMAL() { - if [ "$COLOR" = "yes" ] - then echo -e "\033[0m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[0m" + fi } spacedelim() { - if [ -n "$1" ] - then - if [ "$1" = "skip" ] - then + if [ -n "$1" ]; then + if [ "$1" = "skip" ]; then ans="" else - IFS=',' read -ra ARR <<< "$1" + IFS=',' read -ra ARR <<<"$1" ans="${ARR[*]}" fi fi echo $ans } -rundocker(){ +rundocker() { images=(${DOCKERIMAGE}) ARCH="$(spacedelim ${ARCH})" arches=(${ARCH}) SANITIZE="$(spacedelim $SANITIZE)" VALGRIND_TOOLS="$(spacedelim $VALGRIND_TOOLS)" idx=0 - if [ -z "$INTERACTIVE" ] - then + if [ -z "$INTERACTIVE" ]; then stdio="-a stdout -a stderr" program="${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" else stdio="-i" program="/bin/bash" fi - while [[ $idx -lt ${#images[*]} ]] - do + while [[ $idx -lt ${#images[*]} ]]; do image=${images[$idx]} arch=${arches[$idx]} echo "Building installers for ${arch} using ${image}" - if [ -n "$INTERACTIVE" ] - then + if [ -n "$INTERACTIVE" ]; then echo "env: source ${DOCKER_SRCDIR}/deploy/os/${OS}.env" echo "run: ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" echo "or: NOMAKE=1 ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" @@ -71,68 +66,68 @@ rundocker(){ # only build the deb's after both 32-bit and 64-bit builds are # complete. Likewise only publish the release once. # - if [ -z $JARS_DIR ] - then jars_dir= - else jars_dir=/jars_dir + if [ -z $JARS_DIR ]; then + jars_dir= + else + jars_dir=/jars_dir fi - if [ -z $FORWARD_PORT ] - then port_forwarding= - else port_forwarding="-p ${FORWARD_PORT}:${FORWARD_PORT}" - echo $port_forwarding + if [ -z $FORWARD_PORT ]; then + port_forwarding= + else + port_forwarding="-p ${FORWARD_PORT}:${FORWARD_PORT}" + echo $port_forwarding fi - status=127 - loop_count=0 - while [ $status = 127 -a $loop_count -lt 5 ] - do - let loop_count=$loop_count+1 - docker run --cap-add=SYS_PTRACE -t $stdio --cidfile=${WORKSPACE}/${OS}_docker-cid \ - -u $(id -u):$(id -g) --privileged \ - -h $DISTNAME \ - -e "srcdir=${DOCKER_SRCDIR}"\ - -e "ARCH=${arch}" \ - -e "ARCHES=${ARCH}" \ - -e "BRANCH" \ - -e "COLOR" \ - -e "DISPLAY" \ - -e "DISTNAME" \ - -e "GIT_COMMIT" \ - -e "OS" \ - -e "PLATFORM" \ - -e "PUBLISH" \ - -e "RELEASE" \ - -e "RELEASE_VERSION" \ - -e "SANITIZE" \ - -e "TEST" \ - -e "TESTFORMAT" \ - -e "UPDATEPKG" \ - -e "VALGRIND_TOOLS" \ - -e "MAKE_JARS" \ - -e "CONFIGURE_PARAMS" \ - -e "mdsevent_port=$EVENT_PORT" \ - -e "HOME=/workspace" \ - -e "JARS_DIR=$jars_dir" \ - -e "TEST_TIMEUNIT" \ - -e "ALPHA_DEBUG_INFO" \ - -v ${SRCDIR}:${DOCKER_SRCDIR} \ - -v ${WORKSPACE}:/workspace \ - $port_forwarding \ - $(volume "${JARS_DIR}" /jars_dir) \ - $(volume "${RELEASEDIR}" /release) \ - $(volume "${PUBLISHDIR}" /publish) \ - $(volume "${KEYS}" /sign_keys) \ - ${image} $program + status=127 + loop_count=0 + while [ $status = 127 -a $loop_count -lt 5 ]; do + let loop_count=$loop_count+1 + docker run --cap-add=SYS_PTRACE -t $stdio --cidfile=${WORKSPACE}/${OS}_docker-cid\ + ${DOCKER_NETWORK:---network=none}\ + -u $(id -u):$(id -g) --privileged\ + -h $DISTNAME\ + -e "srcdir=${DOCKER_SRCDIR}"\ + -e "ARCH=${arch}"\ + -e "ARCHES=${ARCH}"\ + -e "BRANCH"\ + -e "COLOR"\ + -e "DISPLAY"\ + -e "DISTNAME"\ + -e "GIT_COMMIT"\ + -e "OS"\ + -e "PLATFORM"\ + -e "PUBLISH"\ + -e "RELEASE"\ + -e "RELEASE_VERSION"\ + -e "SANITIZE"\ + -e "TEST"\ + -e "TESTFORMAT"\ + -e "UPDATEPKG"\ + -e "VALGRIND_TOOLS"\ + -e "MAKE_JARS"\ + -e "CONFIGURE_PARAMS"\ + -e "mdsevent_port=$EVENT_PORT"\ + -e "HOME=/workspace"\ + -e "JARS_DIR=$jars_dir"\ + -e "TEST_TIMEUNIT"\ + -e "ALPHA_DEBUG_INFO"\ + -v ${SRCDIR}:${DOCKER_SRCDIR}\ + -v ${WORKSPACE}:/workspace\ + $port_forwarding\ + $(volume "${JARS_DIR}" /jars_dir)\ + $(volume "${RELEASEDIR}" /release)\ + $(volume "${PUBLISHDIR}" /publish)\ + $(volume "${KEYS}" /sign_keys)\ + ${image} $program status=$? - if [ -r ${WORKSPACE}/${OS}_docker-cid ] - then - sleep 3 - docker rm $(cat ${WORKSPACE}/${OS}_docker-cid) - rm -f ${WORKSPACE}/${OS}_docker-cid + if [ -r ${WORKSPACE}/${OS}_docker-cid ]; then + sleep 3 + docker rm $(cat ${WORKSPACE}/${OS}_docker-cid) + rm -f ${WORKSPACE}/${OS}_docker-cid fi - done - if [ ! "$status" = "0" ] - then - RED - cat <&2 + done + if [ ! "$status" = "0" ]; then + RED + cat <&2 ====================================================== Docker ${PLATFORM}_docker_build.sh returned failure @@ -140,34 +135,32 @@ status when exiting from ${image} ====================================================== EOF - NORMAL - exit $status + NORMAL + exit $status fi let idx=idx+1 done exit $status } -default_build(){ - if [ "${RELEASE}" = "yes" -o "${PUBLISH}" = "yes" ] - then +default_build() { + if [ "${RELEASE}" = "yes" -o "${PUBLISH}" = "yes" ]; then mkdir -p ${RELEASEDIR}/${BRANCH} else RELEASEDIR="" fi - if [ "${PUBLISH}" = "yes" ] - then + if [ "${PUBLISH}" = "yes" ]; then mkdir -p ${PUBLISHDIR}/${BRANCH} fi } -if [ "$BRANCH" = "alpha" ] -then ALPHA_DEBUG_INFO=--enable-debug=info -else ALPHA_DEBUG_INFO= +if [ "$BRANCH" = "alpha" ]; then + ALPHA_DEBUG_INFO=--enable-debug=info +else + ALPHA_DEBUG_INFO= fi set +e platform_build="${SRCDIR}/deploy/platform/${PLATFORM}/${PLATFORM}_build.sh" -if [ -f "${platform_build}" ] -then +if [ -f "${platform_build}" ]; then echo "running ${platform_build}." source ${platform_build} "$@" else From d2e5074c28cccc8dd814b4543f16e0ea4d858d44 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 17:39:05 +0200 Subject: [PATCH 15/27] Build: fixed build scripts to maintain multiarch files --- configure.ac | 4 ---- deploy/packaging/alpine/alpine_build_apks.py | 2 +- deploy/platform/alpine/alpine_build.sh | 13 ------------ deploy/platform/alpine/alpine_docker_build.sh | 9 ++++++--- deploy/platform/debian/debian_build.sh | 16 --------------- deploy/platform/debian/debian_docker_build.sh | 9 +++------ deploy/platform/platform_build.sh | 5 ++--- deploy/platform/redhat/redhat_docker_build.sh | 20 +++++++------------ 8 files changed, 19 insertions(+), 59 deletions(-) delete mode 100644 deploy/platform/alpine/alpine_build.sh delete mode 100755 deploy/platform/debian/debian_build.sh diff --git a/configure.ac b/configure.ac index 0bb01accbd..af7be6c265 100644 --- a/configure.ac +++ b/configure.ac @@ -103,10 +103,6 @@ AC_CHECK_TOOL([WINDRES], [windres], [:]) AC_PROG_YACC AM_PROG_LEX -# ln does not always provide the -r (relative) option -AS_IF([ln --help | grep -- "--relative" &>/dev/null],[AS_VAR_SET([LN_R],["ln -r"])],[AS_VAR_SET([LN_R],["ln"])]) -AC_SUBST([LN_R]) - # Always do the visibility check but don't set AM_CFLAGS on Windows. # This way things get set properly even on Windows. AC_MSG_RESULT([before VISIBILITY]) diff --git a/deploy/packaging/alpine/alpine_build_apks.py b/deploy/packaging/alpine/alpine_build_apks.py index 0c469cc9b9..4fea8f598a 100755 --- a/deploy/packaging/alpine/alpine_build_apks.py +++ b/deploy/packaging/alpine/alpine_build_apks.py @@ -217,8 +217,8 @@ def buildApks(): root = tree.getroot() apks = [] noarch = "noarch" - noarchdir = "/release/%(flavor)s/noarch" % info archdir = "/release/%(flavor)s/%(arch)s" % info + noarchdir = "/release/%(flavor)s/%(arch)s/noarch" % info os.system("rm -Rf %s/*" % archdir) if info['arch'] == noarch_builder: os.system("rm -Rf %s" % noarchdir) diff --git a/deploy/platform/alpine/alpine_build.sh b/deploy/platform/alpine/alpine_build.sh deleted file mode 100644 index ba1f2b6cc9..0000000000 --- a/deploy/platform/alpine/alpine_build.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -# -# platform/alpine/alpine_build.sh -# -# Invoked by mdsplus/deploy/platform/platform_build.sh for alpine platform. -# -# Run docker image to build mdsplus -# -# Enable arm emulation support in host kernel -#docker run --rm --privileged multiarch/qemu-user-static:register --reset -# -default_build -rundocker diff --git a/deploy/platform/alpine/alpine_docker_build.sh b/deploy/platform/alpine/alpine_docker_build.sh index 5574107548..9a19af94a0 100644 --- a/deploy/platform/alpine/alpine_docker_build.sh +++ b/deploy/platform/alpine/alpine_docker_build.sh @@ -49,14 +49,17 @@ buildrelease() { fi popd if [ -z "$NOMAKE" ]; then - rm -Rf /release/${BRANCH}/${ARCH} /release/${BRANCH}/noarch - mkdir -p /release/${BRANCH}/${ARCH} /release/${BRANCH}/noarch + # build noarch in ${ARCH}-noarch so parallel jobs wont have a race condition + mkdir -p /release/${BRANCH}/${ARCH}/noarch BUILDROOT=${BUILDROOT} \ BRANCH=${BRANCH} \ RELEASE_VERSION=${RELEASE_VERSION} \ ARCH=${ARCH} \ DISTNAME=${DISTNAME} \ - ${srcdir}/deploy/packaging/alpine/build_apks.sh + ${srcdir}/deploy/packaging/alpine/build_apks.sh && + mv -n /release/${BRANCH}/${ARCH}/noarch /release/${BRANCH}/ + # first one to get here successfully moves to /release/${BRANCH}/noarch + # others will not move and ok fi } diff --git a/deploy/platform/debian/debian_build.sh b/deploy/platform/debian/debian_build.sh deleted file mode 100755 index 83a9ec59fe..0000000000 --- a/deploy/platform/debian/debian_build.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# -# platform/debian/build.sh -# -# Invoked by mdsplus/deploy/platform/platform_build.sh for windows platform. -# -# Run docker image to build mdsplus -# -default_build -if [ "${RELEASE}" = "yes" ] -then - # clean up repobefor creating a new release - rm -Rf ${RELEASEDIR}/${BRANCH}/DEBS &>/dev/null - rm -Rf ${RELEASEDIR}/repo &>/dev/null -fi -rundocker diff --git a/deploy/platform/debian/debian_docker_build.sh b/deploy/platform/debian/debian_docker_build.sh index a47166c2df..6b95e77596 100755 --- a/deploy/platform/debian/debian_docker_build.sh +++ b/deploy/platform/debian/debian_docker_build.sh @@ -62,14 +62,13 @@ debtopkg() { buildrelease() { ### Build release version of MDSplus and then construct installer debs set -e + # ${RELEASEDIR}/${BRANCH}/DEBS will be cleaned in debian_build.sh RELEASEDEBS=/release/${BRANCH}/DEBS/${ARCH} RELEASEBLD=/workspace/releasebld BUILDROOT=${RELEASEBLD}/buildroot MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus rm -Rf ${RELEASEBLD}/${bits} mkdir -p ${RELEASEBLD}/${bits} ${BUILDROOT} ${MDSPLUS_DIR} - rm -Rf ${RELEASEDEBS} - mkdir -p ${RELEASEDEBS} pushd ${RELEASEBLD}/${bits} config ${config_param} ${ALPHA_DEBUG_INFO} if [ -z "$NOMAKE" ]; then @@ -78,6 +77,7 @@ buildrelease() { fi popd if [ -z "$NOMAKE" ]; then + mkdir -p ${RELEASEDEBS} BRANCH=${BRANCH} \ RELEASE_VERSION=${RELEASE_VERSION} \ ARCH=${ARCH} \ @@ -113,10 +113,7 @@ buildrelease() { checkstatus abort "Failure: Problem with contents of one or more debs. (see above)" $baddeb if [ -z "$abort" ] || [ "$abort" = "0" ]; then echo "Building repo" - mkdir -p /release/repo/conf - mkdir -p /release/repo/db - mkdir -p /release/repo/dists - mkdir -p /release/repo/pool + mkdir -p /release/repo/conf /release/repo/db /release/repo/dists /release/repo/pool if [ "${BRANCH}" = "alpha" -o "${BRANCH}" = "stable" ]; then component="" else diff --git a/deploy/platform/platform_build.sh b/deploy/platform/platform_build.sh index 864f69f52f..8e34f37f71 100755 --- a/deploy/platform/platform_build.sh +++ b/deploy/platform/platform_build.sh @@ -143,10 +143,9 @@ EOF exit $status } default_build() { - if [ "${RELEASE}" = "yes" -o "${PUBLISH}" = "yes" ]; then + if [ "${RELEASE}" = "yes" ]; then + rm -Rf ${RELEASEDIR}/${BRANCH} mkdir -p ${RELEASEDIR}/${BRANCH} - else - RELEASEDIR="" fi if [ "${PUBLISH}" = "yes" ]; then mkdir -p ${PUBLISHDIR}/${BRANCH} diff --git a/deploy/platform/redhat/redhat_docker_build.sh b/deploy/platform/redhat/redhat_docker_build.sh index b7b8fd23e1..2eb1b24290 100755 --- a/deploy/platform/redhat/redhat_docker_build.sh +++ b/deploy/platform/redhat/redhat_docker_build.sh @@ -58,7 +58,7 @@ buildrelease() { RELEASEBLD=/workspace/releasebld BUILDROOT=${RELEASEBLD}/buildroot MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus - rm -Rf ${RELEASEBLD} + rm -Rf ${RELEASEBLD} /release/${BRANCH} mkdir -p ${RELEASEBLD}/64 ${BUILDROOT} ${MDSPLUS_DIR} pushd ${RELEASEBLD}/64 config ${test64} ${ALPHA_DEBUG_INFO} @@ -103,19 +103,13 @@ gpgcheck=${GPGCHECK} gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-MDSplus metadata_expire=300 EOF - ### - ### Build RPMS - ### - ### Clean up release stage area - ### - rm -Rf /release/${BRANCH} mkdir -p /release/${BRANCH} - BRANCH=${BRANCH} \ - RELEASE_VERSION=${RELEASE_VERSION} \ - BNAME=${BNAME} \ - DISTNAME=${DISTNAME} \ - BUILDROOT=${BUILDROOT} \ - PLATFORM=${PLATFORM} \ + BRANCH=${BRANCH}\ + RELEASE_VERSION=${RELEASE_VERSION}\ + BNAME=${BNAME}\ + DISTNAME=${DISTNAME}\ + BUILDROOT=${BUILDROOT}\ + PLATFORM=${PLATFORM}\ ${srcdir}/deploy/platform/${PLATFORM}/${PLATFORM}_build_rpms.py do_createrepo /release badrpm=0 From a5bbf6b7a55cc63ab48563d931eafe326bd5e2a6 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 19:18:17 +0200 Subject: [PATCH 16/27] Build: network cannot be none for udp events --- deploy/platform/platform_build.sh | 265 ++++++++++++++++-------------- 1 file changed, 138 insertions(+), 127 deletions(-) diff --git a/deploy/platform/platform_build.sh b/deploy/platform/platform_build.sh index 8e34f37f71..283f52c62f 100755 --- a/deploy/platform/platform_build.sh +++ b/deploy/platform/platform_build.sh @@ -8,126 +8,137 @@ # set -e volume() { - if [ -n "$1" ]; then - echo "-v $(realpath ${1}):${2}" - fi + if [ -n "$1" ]; then + echo "-v $(realpath ${1}):${2}" + fi } RED() { - if [ "$COLOR" = "yes" ]; then - echo -e "\033[31m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[31m" + fi } GREEN() { - if [ "$COLOR" = "yes" ]; then - echo -e "\033[32m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[32m" + fi } NORMAL() { - if [ "$COLOR" = "yes" ]; then - echo -e "\033[0m" - fi + if [ "$COLOR" = "yes" ]; then + echo -e "\033[0m" + fi } spacedelim() { - if [ -n "$1" ]; then - if [ "$1" = "skip" ]; then - ans="" - else - IFS=',' read -ra ARR <<<"$1" - ans="${ARR[*]}" - fi + if [ -n "$1" ]; then + if [ "$1" = "skip" ]; then + ans="" + else + IFS=',' read -ra ARR <<<"$1" + ans="${ARR[*]}" fi - echo $ans + fi + echo $ans } rundocker() { - images=(${DOCKERIMAGE}) - ARCH="$(spacedelim ${ARCH})" - arches=(${ARCH}) - SANITIZE="$(spacedelim $SANITIZE)" - VALGRIND_TOOLS="$(spacedelim $VALGRIND_TOOLS)" - idx=0 - if [ -z "$INTERACTIVE" ]; then - stdio="-a stdout -a stderr" - program="${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" + images=(${DOCKERIMAGE}) + ARCH="$(spacedelim ${ARCH})" + arches=(${ARCH}) + SANITIZE="$(spacedelim $SANITIZE)" + VALGRIND_TOOLS="$(spacedelim $VALGRIND_TOOLS)" + idx=0 + if [ -z "$INTERACTIVE" ]; then + stdio="-a stdout -a stderr" + program="${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" + else + stdio="-i" + program="/bin/bash" + fi + while [[ $idx -lt ${#images[*]} ]]; do + image=${images[$idx]} + arch=${arches[$idx]} + echo "Building installers for ${arch} using ${image}" + if [ -n "$INTERACTIVE" ]; then + echo "env: source ${DOCKER_SRCDIR}/deploy/os/${OS}.env" + echo "run: ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" + echo "or: NOMAKE=1 ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" + fi + # + # If there are both 32-bit and 64-bit packages for the platform + # only build the deb's after both 32-bit and 64-bit builds are + # complete. Likewise only publish the release once. + # + if [ -z $JARS_DIR ]; then + jars_dir= + else + jars_dir=/jars_dir + fi + if [ -z $FORWARD_PORT ]; then + port_forwarding= else - stdio="-i" - program="/bin/bash" + port_forwarding="-p ${FORWARD_PORT}:${FORWARD_PORT}" + echo $port_forwarding fi - while [[ $idx -lt ${#images[*]} ]]; do - image=${images[$idx]} - arch=${arches[$idx]} - echo "Building installers for ${arch} using ${image}" - if [ -n "$INTERACTIVE" ]; then - echo "env: source ${DOCKER_SRCDIR}/deploy/os/${OS}.env" - echo "run: ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" - echo "or: NOMAKE=1 ${DOCKER_SRCDIR}/deploy/platform/platform_docker_build.sh" - fi - # - # If there are both 32-bit and 64-bit packages for the platform - # only build the deb's after both 32-bit and 64-bit builds are - # complete. Likewise only publish the release once. - # - if [ -z $JARS_DIR ]; then - jars_dir= - else - jars_dir=/jars_dir - fi - if [ -z $FORWARD_PORT ]; then - port_forwarding= - else - port_forwarding="-p ${FORWARD_PORT}:${FORWARD_PORT}" - echo $port_forwarding - fi - status=127 - loop_count=0 - while [ $status = 127 -a $loop_count -lt 5 ]; do - let loop_count=$loop_count+1 - docker run --cap-add=SYS_PTRACE -t $stdio --cidfile=${WORKSPACE}/${OS}_docker-cid\ - ${DOCKER_NETWORK:---network=none}\ - -u $(id -u):$(id -g) --privileged\ - -h $DISTNAME\ - -e "srcdir=${DOCKER_SRCDIR}"\ - -e "ARCH=${arch}"\ - -e "ARCHES=${ARCH}"\ - -e "BRANCH"\ - -e "COLOR"\ - -e "DISPLAY"\ - -e "DISTNAME"\ - -e "GIT_COMMIT"\ - -e "OS"\ - -e "PLATFORM"\ - -e "PUBLISH"\ - -e "RELEASE"\ - -e "RELEASE_VERSION"\ - -e "SANITIZE"\ - -e "TEST"\ - -e "TESTFORMAT"\ - -e "UPDATEPKG"\ - -e "VALGRIND_TOOLS"\ - -e "MAKE_JARS"\ - -e "CONFIGURE_PARAMS"\ - -e "mdsevent_port=$EVENT_PORT"\ - -e "HOME=/workspace"\ - -e "JARS_DIR=$jars_dir"\ - -e "TEST_TIMEUNIT"\ - -e "ALPHA_DEBUG_INFO"\ - -v ${SRCDIR}:${DOCKER_SRCDIR}\ - -v ${WORKSPACE}:/workspace\ - $port_forwarding\ - $(volume "${JARS_DIR}" /jars_dir)\ - $(volume "${RELEASEDIR}" /release)\ - $(volume "${PUBLISHDIR}" /publish)\ - $(volume "${KEYS}" /sign_keys)\ - ${image} $program - status=$? - if [ -r ${WORKSPACE}/${OS}_docker-cid ]; then - sleep 3 - docker rm $(cat ${WORKSPACE}/${OS}_docker-cid) - rm -f ${WORKSPACE}/${OS}_docker-cid - fi - done - if [ ! "$status" = "0" ]; then - RED - cat <&2 + if docker network >/dev/null 2>&1; then + #docker supports --network + if [ -z ${DOCKER_NETWORK} ]; then + docker network create ${OS} + NETWORK=--network=${OS} + else + NETWORK=--network=${DOCKER_NETWORK} + fi + else + NETWORK= + fi + status=127 + loop_count=0 + while [ $status = 127 -a $loop_count -lt 5 ]; do + let loop_count=$loop_count+1 + docker run --cap-add=SYS_PTRACE -t $stdio \ + --cidfile=${WORKSPACE}/${OS}_docker-cid \ + ${NETWORK} \ + -u $(id -u):$(id -g) --privileged -h $DISTNAME -e "srcdir=${DOCKER_SRCDIR}" \ + -e "ARCH=${arch}" \ + -e "ARCHES=${ARCH}" \ + -e "BRANCH" \ + -e "COLOR" \ + -e "DISPLAY" \ + -e "DISTNAME" \ + -e "GIT_COMMIT" \ + -e "OS" \ + -e "PLATFORM" \ + -e "PUBLISH" \ + -e "RELEASE" \ + -e "RELEASE_VERSION" \ + -e "SANITIZE" \ + -e "TEST" \ + -e "TESTFORMAT" \ + -e "UPDATEPKG" \ + -e "VALGRIND_TOOLS" \ + -e "MAKE_JARS" \ + -e "CONFIGURE_PARAMS" \ + -e "mdsevent_port=$EVENT_PORT" \ + -e "HOME=/workspace" \ + -e "JARS_DIR=$jars_dir" \ + -e "TEST_TIMEUNIT" \ + -e "ALPHA_DEBUG_INFO" \ + -v ${SRCDIR}:${DOCKER_SRCDIR} \ + -v ${WORKSPACE}:/workspace $port_forwarding $(volume "${JARS_DIR}" /jars_dir) \ + $(volume "${RELEASEDIR}" /release) \ + $(volume "${PUBLISHDIR}" /publish) \ + $(volume "${KEYS}" /sign_keys) \ + ${image} $program + status=$? + if [ -r ${WORKSPACE}/${OS}_docker-cid ]; then + sleep 3 + docker rm $(cat ${WORKSPACE}/${OS}_docker-cid) + rm -f ${WORKSPACE}/${OS}_docker-cid + fi + done + if [ -z "${DOCKER_NETWORK}" ]; then + docker network rm ${OS} + fi + if [ ! "$status" = "0" ]; then + RED + cat <&2 ====================================================== Docker ${PLATFORM}_docker_build.sh returned failure @@ -135,35 +146,35 @@ status when exiting from ${image} ====================================================== EOF - NORMAL - exit $status - fi - let idx=idx+1 - done - exit $status + NORMAL + exit $status + fi + let idx=idx+1 + done + exit $status } default_build() { - if [ "${RELEASE}" = "yes" ]; then - rm -Rf ${RELEASEDIR}/${BRANCH} - mkdir -p ${RELEASEDIR}/${BRANCH} - fi - if [ "${PUBLISH}" = "yes" ]; then - mkdir -p ${PUBLISHDIR}/${BRANCH} - fi + if [ "${RELEASE}" = "yes" ]; then + rm -Rf ${RELEASEDIR}/${BRANCH} + mkdir -p ${RELEASEDIR}/${BRANCH} + fi + if [ "${PUBLISH}" = "yes" ]; then + mkdir -p ${PUBLISHDIR}/${BRANCH} + fi } if [ "$BRANCH" = "alpha" ]; then - ALPHA_DEBUG_INFO=--enable-debug=info + ALPHA_DEBUG_INFO=--enable-debug=info else - ALPHA_DEBUG_INFO= + ALPHA_DEBUG_INFO= fi set +e platform_build="${SRCDIR}/deploy/platform/${PLATFORM}/${PLATFORM}_build.sh" if [ -f "${platform_build}" ]; then - echo "running ${platform_build}." - source ${platform_build} "$@" + echo "running ${platform_build}." + source ${platform_build} "$@" else - echo "Using default script." - default_build - rundocker + echo "Using default script." + default_build + rundocker fi From 6499134d2dd112a64fde7061ca69ce9700c56886 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 20:01:54 +0200 Subject: [PATCH 17/27] Build: fixed Docker_NETWORK cleanup if not supported --- deploy/platform/platform_build.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/deploy/platform/platform_build.sh b/deploy/platform/platform_build.sh index 283f52c62f..d085c60cb5 100755 --- a/deploy/platform/platform_build.sh +++ b/deploy/platform/platform_build.sh @@ -86,6 +86,7 @@ rundocker() { NETWORK=--network=${DOCKER_NETWORK} fi else + DOCKER_NETWORK=bridge NETWORK= fi status=127 @@ -133,7 +134,7 @@ rundocker() { rm -f ${WORKSPACE}/${OS}_docker-cid fi done - if [ -z "${DOCKER_NETWORK}" ]; then + if [ -z ${DOCKER_NETWORK} ]; then docker network rm ${OS} fi if [ ! "$status" = "0" ]; then From db4b70cfbd85b9135f20153215c43300149d4428 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 20:10:50 +0200 Subject: [PATCH 18/27] Build: cleanup buildroot for debian --- deploy/platform/debian/debian_docker_build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy/platform/debian/debian_docker_build.sh b/deploy/platform/debian/debian_docker_build.sh index 6b95e77596..86478a457f 100755 --- a/deploy/platform/debian/debian_docker_build.sh +++ b/deploy/platform/debian/debian_docker_build.sh @@ -67,7 +67,7 @@ buildrelease() { RELEASEBLD=/workspace/releasebld BUILDROOT=${RELEASEBLD}/buildroot MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus - rm -Rf ${RELEASEBLD}/${bits} + rm -Rf ${RELEASEBLD}/${bits} ${BUILDROOT} mkdir -p ${RELEASEBLD}/${bits} ${BUILDROOT} ${MDSPLUS_DIR} pushd ${RELEASEBLD}/${bits} config ${config_param} ${ALPHA_DEBUG_INFO} From 75f799a45fdf32a7f8a4a8b6b3431e7e28a1a7a5 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 20:45:26 +0200 Subject: [PATCH 19/27] Build: alpine fixed noarch --- deploy/packaging/alpine/alpine_build_apks.py | 2 +- deploy/platform/alpine/alpine_docker_build.sh | 12 ++++-------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/deploy/packaging/alpine/alpine_build_apks.py b/deploy/packaging/alpine/alpine_build_apks.py index 4fea8f598a..3b02f73099 100755 --- a/deploy/packaging/alpine/alpine_build_apks.py +++ b/deploy/packaging/alpine/alpine_build_apks.py @@ -218,7 +218,7 @@ def buildApks(): apks = [] noarch = "noarch" archdir = "/release/%(flavor)s/%(arch)s" % info - noarchdir = "/release/%(flavor)s/%(arch)s/noarch" % info + noarchdir = "/release/%(flavor)s/noarch" % info os.system("rm -Rf %s/*" % archdir) if info['arch'] == noarch_builder: os.system("rm -Rf %s" % noarchdir) diff --git a/deploy/platform/alpine/alpine_docker_build.sh b/deploy/platform/alpine/alpine_docker_build.sh index 9a19af94a0..17b087a11a 100644 --- a/deploy/platform/alpine/alpine_docker_build.sh +++ b/deploy/platform/alpine/alpine_docker_build.sh @@ -49,17 +49,12 @@ buildrelease() { fi popd if [ -z "$NOMAKE" ]; then - # build noarch in ${ARCH}-noarch so parallel jobs wont have a race condition - mkdir -p /release/${BRANCH}/${ARCH}/noarch BUILDROOT=${BUILDROOT} \ BRANCH=${BRANCH} \ RELEASE_VERSION=${RELEASE_VERSION} \ ARCH=${ARCH} \ DISTNAME=${DISTNAME} \ - ${srcdir}/deploy/packaging/alpine/build_apks.sh && - mv -n /release/${BRANCH}/${ARCH}/noarch /release/${BRANCH}/ - # first one to get here successfully moves to /release/${BRANCH}/noarch - # others will not move and ok + ${srcdir}/deploy/packaging/alpine/build_apks.sh fi } @@ -74,8 +69,9 @@ publish() { cd $P rsync -a $R/${ARCH}/*.apk $P/${ARCH}/ && : checkstatus abort "Failure: Problem copying arch apks to publish area!" $? - rsync -a $R/noarch/*.apk $P/noarch/ && : - checkstatus abort "Failure: Problem copying noarch apks to publish area!" $? + if ! rsync -a $R/noarch/*.apk $P/noarch/; then + echo "Problem copying noarch apks to publish area, maybe they are there already." + fi if [ -r $P/${ARCH}/APKINDEX.tar.gz -a ! -r $P/${ARCH}/NEW.tar.gz ]; then apk index -x $P/${ARCH}/APKINDEX.tar.gz -o $P/${ARCH}/NEW.tar.gz $P/${ARCH}/*.apk noarch/*.apk else From 4c97802f7d153586740d536557ea5d7a83d31b64 Mon Sep 17 00:00:00 2001 From: cloud Date: Tue, 4 May 2021 20:56:06 +0200 Subject: [PATCH 20/27] Build: debian cleanup repo --- deploy/platform/debian/debian_build.sh | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 deploy/platform/debian/debian_build.sh diff --git a/deploy/platform/debian/debian_build.sh b/deploy/platform/debian/debian_build.sh new file mode 100644 index 0000000000..4e05297962 --- /dev/null +++ b/deploy/platform/debian/debian_build.sh @@ -0,0 +1,8 @@ +# Sourced by mdsplus/deploy/platform/platform_build.sh +default_build +if [ "${RELEASE}" = "yes" ] +then + # clean up repo before creating a new release + rm -Rf ${RELEASEDIR}/repo +fi +rundocker From 9d0f62faa8d5dafd21e1330c67b1895d88185eb1 Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Wed, 5 May 2021 15:14:32 +0200 Subject: [PATCH 21/27] Fix:changed event API (#2306) Co-authored-by: mdsplus --- device_support/national/AsyncStoreManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/device_support/national/AsyncStoreManager.cpp b/device_support/national/AsyncStoreManager.cpp index 3e2a947d8a..fda0374a8c 100644 --- a/device_support/national/AsyncStoreManager.cpp +++ b/device_support/national/AsyncStoreManager.cpp @@ -178,7 +178,7 @@ void SaveItem::save() } // printf("STREAM %d %s %d %f %f\n", shot, streamName, actSamples, // times[0], samples[0]); - EventStream::send(shot, streamName, actSamples, times, samples, false); + EventStream::send(shot, streamName, false, actSamples, times, 1, &actSamples, samples); // EventStream::send(shot, streamName, (float)(period * counter + // timeIdx0), sample); delete[] samples; From cf0829f6ab51afb5bdbad21f56ce65ba6a402a76 Mon Sep 17 00:00:00 2001 From: Josh Stillerman Date: Wed, 12 May 2021 08:37:47 -0400 Subject: [PATCH 22/27] Build: ub20 does not have python_numpy (#2309) * build: ub20 does not have python_numpy The dependecies in linux.xml Only distinguish on 'platform'. UB20 has different dependencies than UB<20. Added new section to linux.xml for specifying DIST dependencies and logic to debian_build_debs.py to find and use this. Eventually this should be refactored so that the 'DIST' section is inside of the 'PLATFORM' section. the RHEL8 hack (its own XML) can probably leverage this same thing. * Build: fixed linux.xml parser for platforms and dists and use it for el8 and Ubuntu20 * Build: onset for a uniform linux_build_package * uniform flavor and bname aka rflavor * use /release/ with flavor in stable, alpha, other * build scrips shall use envs * build windows in flavor * fixed BUILDROOT env for redhat and cleanup for alpine * move rpmspec into pyhton script * cleanup redhat scriptand use bname for rflavor to match env * centos8 should default to python3 * ensure fresh network * redhat text=True does not help Co-authored-by: cloud Co-authored-by: Timo Schroeder --- deploy/packaging/alpine/alpine_build_apks.py | 74 +- deploy/packaging/alpine/build_apks.sh | 10 +- .../debian/debian_build_debs.py | 72 +- deploy/packaging/debian/kernel.noarch | 3 +- deploy/packaging/linux-rhel8.xml | 1022 ----------------- deploy/packaging/linux.xml | 302 ++--- deploy/packaging/linux_build_packages.py | 62 + deploy/packaging/redhat/kernel.noarch | 3 +- .../redhat/redhat_build_rpms.py | 172 ++- deploy/packaging/windows/create_installer.sh | 18 +- deploy/packaging/windows/mdsplus.nsi | 10 +- deploy/platform/alpine/alpine_docker_build.sh | 10 +- deploy/platform/debian/debian_docker_build.sh | 39 +- deploy/platform/macosx/macosx_build.sh | 4 +- deploy/platform/platform_build.sh | 34 +- deploy/platform/platform_docker_build.sh | 5 - deploy/platform/redhat/redhat_docker_build.sh | 35 +- .../platform/windows/windows_docker_build.sh | 16 +- rpm/Makefile.am | 3 +- rpm/python_module_install.sh | 28 + rpm/python_module_remove.sh | 49 + rpm/removePythonModule.sh | 48 - 22 files changed, 404 insertions(+), 1615 deletions(-) rename deploy/{platform => packaging}/debian/debian_build_debs.py (78%) delete mode 100644 deploy/packaging/linux-rhel8.xml create mode 100644 deploy/packaging/linux_build_packages.py rename deploy/{platform => packaging}/redhat/redhat_build_rpms.py (67%) create mode 100755 rpm/python_module_install.sh create mode 100755 rpm/python_module_remove.sh delete mode 100755 rpm/removePythonModule.sh diff --git a/deploy/packaging/alpine/alpine_build_apks.py b/deploy/packaging/alpine/alpine_build_apks.py index 3b02f73099..3eab0d2a3f 100755 --- a/deploy/packaging/alpine/alpine_build_apks.py +++ b/deploy/packaging/alpine/alpine_build_apks.py @@ -26,13 +26,13 @@ import subprocess import os import sys -import xml.etree.ElementTree as ET import fnmatch -import tempfile -import shutil -linux_xml = "%s/linux.xml" % (os.path.dirname( - os.path.dirname(os.path.realpath(__file__))),) + +srcdir = os.path.realpath(os.path.dirname(__file__)+'/../../..') +sys.path.insert(0, os.path.join(srcdir, 'deploy', 'packaging')) +import linux_build_packages as common + pkg_exclusions = ('repo', 'gsi', 'gsi_bin', 'idl', 'idl_bin', 'labview', 'labview_bin', 'php', 'd3d', 'matlab') noarch_builder = "x86_64" @@ -94,7 +94,7 @@ def getPackageFiles(buildroot, includes, excludes): hasuid = True excludefiles = getPackageFiles(buildroot, excludes, []) if hasuid: - print "Found %d" % len(excludefiles) + print("Found %d" % len(excludefiles)) for exclude in excludefiles: print("excluding: %s" % exclude) for exclude in excludefiles: @@ -103,43 +103,15 @@ def getPackageFiles(buildroot, includes, excludes): return files -def externalPackage(info, root, package): - ans = None - for extpackages in root.getiterator('external_packages'): - platform = extpackages.attrib['platform'] - if platform == "alpine": - pkg = extpackages.find(package) - if pkg is not None: - if 'package' in pkg.attrib: - ans = pkg.attrib['package'] - break - return ans - - def doRequire(info, out, root, require): if 'external' in require.attrib: - pkg = externalPackage(info, root, require.attrib['package']) - if pkg is not None: - os.write(out, "Requires: %s\n" % pkg) + pkg = common.external_package(info, root, require.attrib['package']) + if pkg: + os.write(out, "Depends: %s\n" % pkg) else: info['reqpkg'] = require.attrib['package'] os.write( - out, "Depends: mdsplus%(rflavor)s-%(reqpkg)s (>= %(major)d.%(minor)d.%(release)d\n" % info) - - -def getInfo(): - version = os.environ['RELEASE_VERSION'].split('.') - branch = os.environ['BRANCH'] - return { - 'major': int(version[0]), - 'minor': int(version[1]), - 'release': int(version[2]), - 'buildroot': os.environ['BUILDROOT'], - 'dist': os.environ['DISTNAME'], - 'arch': os.environ['ARCH'], - 'flavor': branch, - 'rflavor': "-%s" % branch if not branch == "stable" else "", - } + out, "Depends: mdsplus%(bname)s-%(reqpkg)s (>= %(major)d.%(minor)d.%(release)d\n" % info) def run_cmd(cmd, quiet=False): @@ -187,21 +159,21 @@ def getDependencies(info, root, package): depends = [] for require in package.getiterator("requires"): if 'external' in require.attrib: - pkg = externalPackage(info, root, require.attrib['package']) - if pkg is not None: + pkg = common.external_package(info, root, require.attrib['package']) + if pkg: depends.append(pkg) else: depends.append( - "mdsplus%s-%s" % (info['rflavor'], require.attrib['package'].replace('_', '-'))) + "mdsplus%s-%s" % (info['bname'], require.attrib['package'].replace('_', '-'))) return ' '.join(depends) def getScripts(info, package): - scriptname = "mdsplus%(rflavor)s%(name)s.%%s" % info + scriptname = "mdsplus%(bname)s%(name)s.%%s" % info scripts = [] for s in ("pre-install", "post-install", "pre-deinstall", "post-deinstall", "pre-upgrade", "post-upgrade"): scriptcls = package.find(s) - if scriptcls is not None and ("type" not in scriptcls.attrib or scriptcls.attrib["type"] != "rpm"): + if scriptcls and ("type" not in scriptcls.attrib or scriptcls.attrib["type"] != "rpm"): script = scriptname % s scripts.append(script) with open("/workspace/%s" % script, "w+") as f: @@ -211,11 +183,9 @@ def getScripts(info, package): return 'install="%s"' % " ".join(scripts) -def buildApks(): - info = getInfo() - tree = ET.parse(linux_xml) - root = tree.getroot() - apks = [] +def build(): + info = common.get_info() + root = common.get_root() noarch = "noarch" archdir = "/release/%(flavor)s/%(arch)s" % info noarchdir = "/release/%(flavor)s/noarch" % info @@ -244,7 +214,7 @@ def buildApks(): with open("/workspace/APKBUILD", "w+") as f: f.write("# Contributor: MDSplus Developer Team\n") f.write("#Maintainer: Tom Fredian \n") - f.write("pkgname=mdsplus%(rflavor)s%(name)s\n" % info) + f.write("pkgname=mdsplus%(bname)s%(name)s\n" % info) f.write("pkgver=%(major)d.%(minor)d\n" % info) f.write("pkgrel=%(release)d\n" % info) f.write('pkgdesc="%(description)s"\n' % info) @@ -272,9 +242,9 @@ def buildApks(): if not run_cmd("abuild checksum && abuild -cqdP /release/%(flavor)s" % info): raise Exception("Problem building package") if info['pkg_arch'] == noarch: - fnm = "mdsplus%(rflavor)s%(name)s-%(major)d.%(minor)d-r%(release)d.apk" % info + fnm = "mdsplus%(bname)s%(name)s-%(major)d.%(minor)d-r%(release)d.apk" % info os.rename("%s/%s" % (archdir, fnm), "%s/%s" % (noarchdir, fnm)) clean_ws() - -buildApks() +if __name__ == "__main__": + build() diff --git a/deploy/packaging/alpine/build_apks.sh b/deploy/packaging/alpine/build_apks.sh index 2c752256cc..2e0877dcff 100755 --- a/deploy/packaging/alpine/build_apks.sh +++ b/deploy/packaging/alpine/build_apks.sh @@ -1,9 +1,5 @@ #!/bin/bash [ -z "${BUILDROOT}" ] && exit 1 -[ -z "${BRANCH}" ] && exit 1 -[ -z "${RELEASE_VERSION}" ] && exit 1 -[ -z "${ARCH}" ] && exit 1 -[ -z "${DISTNAME}" ] && exit 1 pckdir=$(dirname $(realpath $0)) export HOME=/workspace cd /workspace @@ -18,9 +14,5 @@ fi # we have to unset srcdir as it is a reserved name in abuild # in the process of building the apks it will wipe $srcdir srcdir= \ - BUILDROOT=${BUILDROOT} \ - BRANCH=${BRANCH} \ - RELEASE_VERSION=${RELEASE_VERSION} \ - ARCH=${ARCH} \ - DISTNAME=${DISTNAME} \ + BUILDROOT=${BUILDROOT}\ ${pckdir}/alpine_build_apks.py diff --git a/deploy/platform/debian/debian_build_debs.py b/deploy/packaging/debian/debian_build_debs.py similarity index 78% rename from deploy/platform/debian/debian_build_debs.py rename to deploy/packaging/debian/debian_build_debs.py index 851057f705..1312de2f67 100755 --- a/deploy/platform/debian/debian_build_debs.py +++ b/deploy/packaging/debian/debian_build_debs.py @@ -23,16 +23,16 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -import subprocess +import fnmatch import os +import shutil +import subprocess import sys -import xml.etree.ElementTree as ET -import fnmatch import tempfile -import shutil -srcdir = os.path.realpath(os.path.dirname( - os.path.realpath(__file__))+'/../../..') +srcdir = os.path.realpath(os.path.dirname(__file__)+'/../../..') +sys.path.insert(0, os.path.join(srcdir, 'deploy', 'packaging')) +import linux_build_packages as common def getPackageFiles(buildroot, includes, excludes): @@ -80,49 +80,23 @@ def getPackageFiles(buildroot, includes, excludes): return files -def externalPackage(info, root, package): - ans = None - for extpackages in root.getiterator('external_packages'): - platform = extpackages.attrib['platform'] - if info['platform'] == platform: - pkg = extpackages.find(package) - if pkg is not None: - if 'package' in pkg.attrib: - ans = pkg.attrib['package'] - else: - ans = package - return ans - def doRequire(info, out, root, require): if 'external' in require.attrib: - pkg = externalPackage(info, root, require.attrib['package']) - if pkg is not None: - os.write(out, "Requires: %s\n" % pkg) + pkg = common.external_package(info, root, require.attrib['package']) + if pkg: + os.write(out, "Depends: %s\n" % pkg) else: info['reqpkg'] = require.attrib['package'] os.write( - out, "Depends: mdsplus%(BNAME)s-%(reqpkg)s (>= %(major)d.%(minor)d.%(release)d\n" % info) + out, "Depends: mdsplus%(bname)s-%(reqpkg)s (>= %(major)d.%(minor)d.%(release)d\n" % info) -def buildDebs(): - info = dict() - info['buildroot'] = os.environ['BUILDROOT'] - info['BRANCH'] = os.environ['BRANCH'] - version = os.environ['RELEASE_VERSION'].split('.') - info['dist'] = os.environ['DISTNAME'] - info['platform'] = os.environ['PLATFORM'] - info['arch'] = os.environ['ARCH'] - info['flavor'] = info['BRANCH'] - info['major'] = int(version[0]) - info['minor'] = int(version[1]) - info['release'] = int(version[2]) - info['BNAME'] = os.environ['BNAME'] - info['rflavor'] = info['BNAME'] - tree = ET.parse(srcdir+'/deploy/packaging/linux.xml') - root = tree.getroot() +def build(): + info = common.get_info() + root = common.get_root() debs = list() - for package in root.getiterator('package'): + for package in root.iter('package'): pkg = package.attrib['name'] if pkg == 'MDSplus': info['packagename'] = "" @@ -133,13 +107,13 @@ def buildDebs(): try: os.mkdir("%(tmpdir)s/DEBIAN" % info) includes = list() - for inc in package.getiterator('include'): + for inc in package.iter('include'): for inctype in inc.attrib: include = inc.attrib[inctype] if inctype != "dironly": includes.append(include) excludes = list() - for exc in package.getiterator('exclude'): + for exc in package.iter('exclude'): for exctype in exc.attrib: excludes.append(exc.attrib[exctype]) if package.find("exclude_staticlibs") is not None: @@ -159,22 +133,22 @@ def buildDebs(): raise Exception("Error building deb") sys.stdout.flush() depends = list() - for require in package.getiterator("requires"): + for require in package.iter("requires"): if 'external' in require.attrib: - pkg = externalPackage( + pkg = common.external_package( info, root, require.attrib['package']) if pkg is not None: depends.append(pkg) else: depends.append( - "mdsplus%s-%s" % (info['rflavor'], require.attrib['package'].replace('_', '-'))) + "mdsplus%s-%s" % (info['bname'], require.attrib['package'].replace('_', '-'))) if len(depends) == 0: info['depends'] = '' else: info['depends'] = "\nDepends: %s" % ','.join(depends) info['name'] = info['packagename'].replace('_', '-') f = open("%(tmpdir)s/DEBIAN/control" % info, "w") - f.write("""Package: mdsplus%(rflavor)s%(name)s + f.write("""Package: mdsplus%(bname)s%(name)s Version: %(major)d.%(minor)d.%(release)d Section: admin Priority: optional @@ -193,7 +167,7 @@ def buildDebs(): "__INSTALL_PREFIX__", "/usr/local"))) f.close() os.chmod("%(tmpdir)s/DEBIAN/%(script)s" % info, 0o775) - info['debfile'] = "/release/%(flavor)s/DEBS/%(arch)s/mdsplus%(rflavor)s%(packagename)s_%(major)d.%(minor)d.%(release)d_%(arch)s.deb" % info + info['debfile'] = "/release/%(flavor)s/DEBS/%(arch)s/mdsplus%(bname)s%(packagename)s_%(major)d.%(minor)d.%(release)d_%(arch)s.deb" % info if subprocess.Popen("dpkg-deb --build %(tmpdir)s %(debfile)s" % info, shell=True).wait() != 0: for k, v in info.items(): print("%s=%s" % (k, v)) @@ -203,5 +177,5 @@ def buildDebs(): finally: shutil.rmtree("%(tmpdir)s" % info) - -buildDebs() +if __name__ == "__main__": + build() diff --git a/deploy/packaging/debian/kernel.noarch b/deploy/packaging/debian/kernel.noarch index 8f3cd759cc..a972662fd8 100644 --- a/deploy/packaging/debian/kernel.noarch +++ b/deploy/packaging/debian/kernel.noarch @@ -35,7 +35,8 @@ ./usr/local/mdsplus/rpm/mdsipsd.xinetd ./usr/local/mdsplus/rpm/post_install_script ./usr/local/mdsplus/rpm/post_uninstall_script -./usr/local/mdsplus/rpm/removePythonModule.sh +./usr/local/mdsplus/rpm/python_module_install.sh +./usr/local/mdsplus/rpm/python_module_remove.sh ./usr/local/mdsplus/setup.csh ./usr/local/mdsplus/setup.sh ./usr/local/mdsplus/share/man/man1/mdsplus.1 diff --git a/deploy/packaging/linux-rhel8.xml b/deploy/packaging/linux-rhel8.xml deleted file mode 100644 index 16fbd7dfd9..0000000000 --- a/deploy/packaging/linux-rhel8.xml +++ /dev/null @@ -1,1022 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - -if [ -d /usr/share/applications/mdsplus ] -then - ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/java /usr/share/applications/mdsplus/ -fi - - - -if [ "$1" == "0" ] -then - rm -f /usr/share/applications/mdsplus/java 2>&1 -fi - - - - - -if [ -d /usr/share/applications/mdsplus ] -then - ln -sf /usr/local/mdsplus/desktop/java /usr/share/applications/mdsplus/ -fi - - -rm -f /usr/share/applications/mdsplus/java 2>&1 - - - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - -if [ "$1" == "0" ] -then - rm -f /usr/share/applications/mdsplus/java 2>/dev/null - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -fi - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - -rm -f /usr/share/applications/mdsplus/java 2>/dev/null -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - - -
-      $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MitDevices
-    
- - -python2 -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - - if [ "$1" == "0" ] - then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/MitDevices - fi - - - - - - /usr/local/mdsplus/rpm/removePythonModule.sh MitDevices - - - -python2 -m compileall -q /usr/local/mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - rm -Rf /usr/local/mdsplus/pydevices/MitDevices - - - - - /mdsplus/rpm/removePythonModule.sh MitDevices - - - -python2 -m compileall -q /mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - rm -Rf /mdsplus/pydevices/MitDevices - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - - - - -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -if [ ! -r /etc/xinetd.d/mdsips ] -then - cp $RPM_INSTALL_PREFIX/mdsplus/rpm/mdsipsd.xinetd /etc/xinetd.d/mdsips - if ( ! grep '^mdsips[[:space:]]' /etc/services >/dev/null 2>&1) - then - echo 'mdsips 8200/tcp # MDSplus mdsip service' >> /etc/services - fi -fi - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -if [ ! -r /etc/xinetd.d/mdsips ] -then - cp /usr/local/mdsplus/rpm/mdsipsd.xinetd /etc/xinetd.d/mdsips - if ( ! grep '^mdsips[[:space:]]' /etc/services >/dev/null 2>&1) - then - echo 'mdsips 8200/tcp # MDSplus mdsip service' >> /etc/services - fi -fi - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - -if [ -d /usr/share/applications/mdsplus ] -then - ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/motif /usr/share/applications/mdsplus/ -fi - - - - -if [ "$1" == "0" ] -then - rm -f /usr/share/applications/mdsplus/motif 2>/dev/null -fi - - - - - - - -if [ -d /usr/share/applications/mdsplus ] -then - ln -sf /usr/local/mdsplus/desktop/motif /usr/share/applications/mdsplus/ -fi - - - -rm -f /usr/share/applications/mdsplus/motif 2>/dev/null - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if [ ! -d $RPM_INSTALL_PREFIX/mdsplus/uid ] -then - if [ -d $RPM_INSTALL_PREFIX/mdsplus/uid64 ] - then - ln -sf uid64 $RPM_INSTALL_PREFIX/mdsplus/uid - else - ln -sf uid32 $RPM_INSTALL_PREFIX/mdsplus/uid - fi -fi -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - -if [ "$1" == "0" -a -h $RPM_INSTALL_PREFIX/mdsplus/uid ] -then - rm -f $RPM_INSTALL_PREFIX/mdsplus/uid -fi - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - -if [ ! -d /usr/local/mdsplus/uid ] -then - if [ -d /usr/local/mdsplus/uid64 ] - then - ln -sf uid64 /usr/local/mdsplus/uid - else - ln -sf uid32 /usr/local/mdsplus/uid - fi -fi -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - -if [ -h /usr/local/mdsplus/uid ] -then - rm -f /usr/local/mdsplus/uid -fi - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if [ -d /etc/profile.d ] -then - ln -sf $RPM_INSTALL_PREFIX/mdsplus/setup.sh /etc/profile.d/mdsplus.sh - ln -sf $RPM_INSTALL_PREFIX/mdsplus/setup.csh /etc/profile.d/mdsplus.csh -fi -if [ -d /etc/xdg/menus/applications-merged ] -then - ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/mdsplus.menu /etc/xdg/menus/applications-merged/ -fi -if [ -d /usr/share/desktop-directories ] -then - ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/mdsplus.directory /usr/share/desktop-directories/ -fi -if [ -d /usr/share/applications ] -then - mkdir -p /usr/share/applications/mdsplus - ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/kernel /usr/share/applications/mdsplus/ -fi -if [ ! -r /etc/xinetd.d/mdsip ] -then - cp $RPM_INSTALL_PREFIX/mdsplus/rpm/mdsipd.xinetd /etc/xinetd.d/mdsip - if ( ! grep '^mdsip[[:space:]]' /etc/services >/dev/null 2>&1) - then - echo 'mdsip 8000/tcp # MDSplus mdsip service' >> /etc/services - fi -fi - - - -if [ "$1" == "0" ] -then - rm -f /etc/profile.d/mdsplus.sh 2>/dev/null - rm -f /etc/profile.d/mdsplus.csh 2>/dev/null - rm -f /etc/.mdsplus_dir 2>/dev/null - rm -f /etc/xdg/menus/applications-merged/mdsplus.menu - rm -f /usr/share/desktop-directories/mdsplus.directory - rm -Rf /usr/share/applications/mdsplus - if [ -r /etc/xinetd.d/mdsip ] - then - if ( diff -q /etc/xinetd.d/mdsip $RPM_INSTALL_PREFIX/mdsplus/rpm/mdsipd.xinetd > /dev/null ) - then - rm -f /etc/xinetd.d/mdsip - if [ -x /sbin/service ] - then - /sbin/service xinetd reload - fi - fi - fi - if ( grep '^mdsip[[:space::]]' /etc/services >/dev/null 2>&1 ) - then - tmpfile=$(mktemp) - if ( grep -v '^mdsip[[:space::]]' /etc/services > $tmpfile ) - then - mv /etc/services /etc/services.rpmsave - mv $tmpfile /etc/services - fi - fi -fi - - - - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/{desktop,pixmaps} -fi - - - - - - - -if [ -d /etc/profile.d ] -then - ln -sf /usr/local/mdsplus/setup.sh /etc/profile.d/mdsplus.sh - ln -sf /usr/local/mdsplus/setup.csh /etc/profile.d/mdsplus.csh -fi -if [ -d /etc/xdg/menus/applications-merged ] -then - ln -sf /usr/local/mdsplus/desktop/mdsplus.menu /etc/xdg/menus/applications-merged/ -fi -if [ -d /usr/share/desktop-directories ] -then - ln -sf /usr/local/mdsplus/desktop/mdsplus.directory /usr/share/desktop-directories/ -fi -if [ -d /usr/share/applications ] -then - mkdir -p /usr/share/applications/mdsplus - ln -sf /usr/local/mdsplus/desktop/kernel /usr/share/applications/mdsplus/ -fi -if [ ! -r /etc/xinetd.d/mdsip ] -then - cp /usr/local/mdsplus/rpm/mdsipd.xinetd /etc/xinetd.d/mdsip - if ( ! grep '^mdsip[[:space:]]' /etc/services >/dev/null 2>&1) - then - echo 'mdsip 8000/tcp # MDSplus mdsip service' >> /etc/services - fi -fi - - - -rm -f /etc/profile.d/mdsplus.sh 2>/dev/null -rm -f /etc/profile.d/mdsplus.csh 2>/dev/null -rm -f /etc/.mdsplus_dir 2>/dev/null -rm -f /etc/xdg/menus/applications-merged/mdsplus.menu -rm -f /usr/share/desktop-directories/mdsplus.directory -rm -Rf /usr/share/applications/mdsplus -rm -Rf /usr/local/mdsplus/{desktop,pixmaps} -if [ -r /etc/xinetd.d/mdsip ] -then - if ( diff -q /etc/xinetd.d/mdsip /usr/local/mdsplus/rpm/mdsipd.xinetd > /dev/null ) - then - rm -f /etc/xinetd.d/mdsip - if [ -x /sbin/service ] - then - /sbin/service xinetd reload - fi - fi -fi -if ( grep '^mdsip[[:space::]]' /etc/services >/dev/null 2>&1 ) -then - tmpfile=$(mktemp) - if ( grep -v '^mdsip[[:space::]]' /etc/services > $tmpfile ) - then - mv /etc/services /etc/services.save - mv $tmpfile /etc/services - fi -fi - - - - - - - -ln -sf /mdsplus /usr/local/ -ln -sf /usr/local/mdsplus/setup.sh /etc/profile.d/mdsplus.sh -ln -sf /usr/local/mdsplus/setup.csh /etc/profile.d/mdsplus.csh - - -rm -f /usr/local/mdsplus -rm -f /etc/profile.d/mdsplus.sh -rm -f /etc/profile.d/mdsplus.csh - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if [ -d /etc/ld.so.conf.d ] -then - rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - touch /etc/ld.so.conf.d/mdsplus.conf - for l in lib lib32 lib64 - do - if [ ! -h $RPM_INSTALL_PREFIX/mdsplus/$l -a -d $RPM_INSTALL_PREFIX/mdsplus/$l ] - then - echo "$RPM_INSTALL_PREFIX/mdsplus/$l" >> /etc/ld.so.conf.d/mdsplus.conf - fi - done - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -fi -if [ -d $RPM_INSTALL_PREFIX/mdsplus/bin64 ] -then - bits=64 -else - bits=32 -fi -if [ -d $RPM_INSTALL_PREFIX/mdsplus/bin${bits} ] -then - if [ ! -h $RPM_INSTALL_PREFIX/mdsplus/bin ] - then - ln -sf bin${bits} $RPM_INSTALL_PREFIX/mdsplus/bin - fi -fi -if [ -d $RPM_INSTALL_PREFIX/mdsplus/lib${bits} ] -then - if [ ! -h $RPM_INSTALL_PREFIX/mdsplus/lib ] - then - ln -sf lib${bits} $RPM_INSTALL_PREFIX/mdsplus/lib - fi -fi - - - - -if [ "$1" == "0" ] -then - rm -f $RPM_INSTALL_PREFIX/mdsplus/bin - rm -f $RPM_INSTALL_PREFIX/mdsplus/lib -fi - - - - -if [ "$1" == "0" ] -then - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null -fi - - - - - - - -if [ -d /etc/ld.so.conf.d ] -then - rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - touch /etc/ld.so.conf.d/mdsplus.conf - for l in lib lib32 lib64 - do - if [ ! -h /usr/local/mdsplus/$l -a -d /usr/local/mdsplus/$l ] - then - echo "/usr/local/mdsplus/$l" >> /etc/ld.so.conf.d/mdsplus.conf - fi - done - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -fi -if [ -d /usr/local/mdsplus/bin64 ] -then - bits=64 -else - bits=32 -fi -if [ -d /usr/local/mdsplus/bin${bits} ] -then - if [ ! -h /usr/local/mdsplus/bin ] - then - ln -sf bin${bits} /usr/local/mdsplus/bin - fi -fi -if [ -d /usr/local/mdsplus/lib${bits} ] -then - if [ ! -h /usr/local/mdsplus/lib ] - then - ln -sf lib${bits} /usr/local/mdsplus/lib - fi -fi - - - - -for d in bin lib -do - if [ -h /usr/local/mdsplus/$d ] - then - rm -f /usr/local/mdsplus/$d - fi -done -ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - - - - - - - - - - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - - - - - - - - - - - - - - -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh RfxDevices
- python2 -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/RfxDevices -fi - - - - - /usr/local/mdsplus/rpm/removePythonModule.sh RfxDevices - python2 -m compileall -q /usr/local/mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/RfxDevices - - - - /mdsplus/rpm/removePythonModule.sh RfxDevices - python2 -m compileall -q /mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/RfxDevices - - -
- - - - - -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh W7xDevices
- python2 -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7Devices -fi - - - - - - /usr/local/mdsplus/rpm/removePythonModule.sh W7xDevices - python2 -m compileall -q /usr/local/mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/W7xDevices - - - - /mdsplus/rpm/removePythonModule.sh W7xDevices - python2 -m compileall -q /mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/W7xDevices - -
- - - - - -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh HtsDevices
- python2 -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7Devices -fi - - - - - /usr/local/mdsplus/rpm/removePythonModule.sh HtsDevices - python2 -m compileall -q /usr/local/mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/HtsDevices - - - - /mdsplus/rpm/removePythonModule.sh HtsDevices - python2 -m compileall -q /mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/HtsDevices - -
- - - - - - - - - - - - - - - - - - - - - - $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MDSplus - find $RPM_INSTALL_PREFIX/mdsplus/python -name '*egg-info' -delete - for py in python2 python3 - do - if ( ${py} -c exit\(\) >/dev/null 2>&1 ) - then - ${py} -m compileall -q -f $RPM_INSTALL_PREFIX/mdsplus/python >/dev/null 2>&1 - ${py} $RPM_INSTALL_PREFIX/mdsplus/python/MDSplus/setup.py -q install >/dev/null 2>&1 - fi - done - - - if [ "$1" == "0" ] - then - $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/python - fi - - - - - - if test ! -z $(/usr/local/mdsplus/rpm/removePythonModule.sh MDSplus y) - then setup_install=y - elif echo $PYTHONPATH|grep /usr/local/mdsplus/python>/dev/null - then setup_install=n - else read -t 10 -p "Do you wish to run setup.py install? (y/N) " setup_install - fi - find /usr/local/mdsplus/python -name '*egg-info' -delete - - for py in python2 python3 - do - if ( ${py} -c exit\(\) >/dev/null 2>&1 ) - then - ${py} -m compileall -q -f /usr/local/mdsplus/python >/dev/null 2>&1 - if test "$setup_install" = "y" - then - if ! ${py} /usr/local/mdsplus/python/MDSplus/setup.py -q install >/dev/null - then echo "Could not 'setup.py install' MDSplus for ${py}" - fi - fi - fi - done - - - /usr/local/mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf /usr/local/mdsplus/python - - - - - - python2 -m compileall -q -f /mdsplus/python >/dev/null 2>&1 - python2 /mdsplus/python/MDSplus/setup.py -q install - rm -Rf build dist MDSplus.egg-info - - - /mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf /mdsplus/python - - - /mdsplus/rpm/removePythonModule.sh MDSplus - - - - - - - - - - - - - - - - - - rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-MDSplus >/dev/null 2>/dev/null || true - - - if [ "$1" == "0" ] - then - nohup rpm -e gpg-pubkey-b09cb563 >/dev/null 2>&1 & - fi - - - -
- - - -%%define debug_package %%{nil} -%%global _missing_build_ids_terminate_build 0 -%%global _unpackaged_files_terminate_build 0 -Name: mdsplus%(bname)s%(packagename)s -Version: %(major)d.%(minor)d -Release: %(release)s.%(distname)s -License: BSD Open Source - Copyright (c) 2010, Massachusetts Institute of Technology All rights reserved. -Source: https://github.com/MDSplus/mdsplus/archive/%(branch)s_release-%(major)d-%(minor)d-%(release)d.tar.gz -URL: http://www.mdsplus.org -Vendor: Massachusetts Institute of Technology -Packager: Plasma Science and Fusion Center <mdsplus@www.mdsplus.org> -Summary: %(summary)s -Group: Applications/Archiving -Prefix: /usr/local -AutoReqProv: yes - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/deploy/packaging/linux.xml b/deploy/packaging/linux.xml index 49ef859f7f..5d5b323a3b 100644 --- a/deploy/packaging/linux.xml +++ b/deploy/packaging/linux.xml @@ -29,23 +29,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - + - - - @@ -121,44 +117,16 @@ ldconfig -n /etc/ld.so.conf.d/mdsplus.conf -
-      $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MitDevices
-    
- - -python -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - - if [ "$1" == "0" ] - then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/MitDevices - fi - + $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_install.sh MitDevices + if test "$1" = "0" ; then $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_remove.sh MitDevices; fi - - - /usr/local/mdsplus/rpm/removePythonModule.sh MitDevices - - - -python -m compileall -q /usr/local/mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - rm -Rf /usr/local/mdsplus/pydevices/MitDevices + /usr/local/mdsplus/rpm/python_module_install.sh MitDevices + /usr/local/mdsplus/rpm/python_module_remove.sh MitDevices - - - /mdsplus/rpm/removePythonModule.sh MitDevices - - - -python -m compileall -q /mdsplus/pydevices/MitDevices >/dev/null 2>&1 - - - rm -Rf /mdsplus/pydevices/MitDevices + /mdsplus/rpm/python_module_install.sh MitDevices + /mdsplus/rpm/python_module_remove.sh MitDevices
@@ -222,7 +190,6 @@ python -m compileall -q /mdsplus/pydevices/MitDevices >/dev/null 2>&1 - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf if [ ! -r /etc/xinetd.d/mdsips ] then @@ -238,7 +205,6 @@ fi - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf if [ ! -r /etc/xinetd.d/mdsips ] then @@ -278,38 +244,28 @@ fi - if [ -d /usr/share/applications/mdsplus ] then ln -sf $RPM_INSTALL_PREFIX/mdsplus/desktop/motif /usr/share/applications/mdsplus/ fi - - if [ "$1" == "0" ] then rm -f /usr/share/applications/mdsplus/motif 2>/dev/null fi - - if [ -d /usr/share/applications/mdsplus ] then ln -sf /usr/local/mdsplus/desktop/motif /usr/share/applications/mdsplus/ fi - - -rm -f /usr/share/applications/mdsplus/motif 2>/dev/null - - + rm -f /usr/share/applications/mdsplus/motif 2>/dev/null - @@ -340,7 +296,6 @@ rm -f /usr/share/applications/mdsplus/motif 2>/dev/null - if [ ! -d $RPM_INSTALL_PREFIX/mdsplus/uid ] then if [ -d $RPM_INSTALL_PREFIX/mdsplus/uid64 ] @@ -351,22 +306,18 @@ then fi fi ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - if [ "$1" == "0" -a -h $RPM_INSTALL_PREFIX/mdsplus/uid ] then rm -f $RPM_INSTALL_PREFIX/mdsplus/uid fi - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - if [ ! -d /usr/local/mdsplus/uid ] then if [ -d /usr/local/mdsplus/uid64 ] @@ -377,15 +328,12 @@ then fi fi ldconfig -n /etc/ld.so.conf.d/mdsplus.conf - - if [ -h /usr/local/mdsplus/uid ] then rm -f /usr/local/mdsplus/uid fi - ldconfig -n /etc/ld.so.conf.d/mdsplus.conf @@ -437,10 +385,9 @@ fi - + - @@ -466,7 +413,6 @@ fi - if [ -d /etc/profile.d ] then ln -sf $RPM_INSTALL_PREFIX/mdsplus/setup.sh /etc/profile.d/mdsplus.sh @@ -495,7 +441,6 @@ then fi - if [ "$1" == "0" ] then rm -f /etc/profile.d/mdsplus.sh 2>/dev/null @@ -525,21 +470,17 @@ then fi fi fi - - if [ "$1" == "0" ] then rm -Rf $RPM_INSTALL_PREFIX/mdsplus/{desktop,pixmaps} fi - - if [ -d /etc/profile.d ] then ln -sf /usr/local/mdsplus/setup.sh /etc/profile.d/mdsplus.sh @@ -568,7 +509,6 @@ then fi - rm -f /etc/profile.d/mdsplus.sh 2>/dev/null rm -f /etc/profile.d/mdsplus.csh 2>/dev/null rm -f /etc/.mdsplus_dir 2>/dev/null @@ -596,8 +536,6 @@ then mv $tmpfile /etc/services fi fi - - @@ -612,7 +550,6 @@ rm -f /usr/local/mdsplus rm -f /etc/profile.d/mdsplus.sh rm -f /etc/profile.d/mdsplus.csh - @@ -660,7 +597,6 @@ rm -f /etc/profile.d/mdsplus.csh - if [ -d /etc/ld.so.conf.d ] then rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null @@ -694,31 +630,24 @@ then ln -sf lib${bits} $RPM_INSTALL_PREFIX/mdsplus/lib fi fi - - if [ "$1" == "0" ] then rm -f $RPM_INSTALL_PREFIX/mdsplus/bin rm -f $RPM_INSTALL_PREFIX/mdsplus/lib fi - - if [ "$1" == "0" ] then ldconfig -n /etc/ld.so.conf.d/mdsplus.conf rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null fi - - - if [ -d /etc/ld.so.conf.d ] then rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null @@ -752,10 +681,8 @@ then ln -sf lib${bits} /usr/local/mdsplus/lib fi fi - - for d in bin lib do if [ -h /usr/local/mdsplus/$d ] @@ -766,8 +693,7 @@ done ldconfig -n /etc/ld.so.conf.d/mdsplus.conf rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - - + @@ -791,84 +717,52 @@ rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh RfxDevices
- python -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/RfxDevices -fi - + $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_install.sh RfxDevices + if test "$1" = "0" ; then $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_remove.sh RfxDevices; fi - - /usr/local/mdsplus/rpm/removePythonModule.sh RfxDevices - python -m compileall -q /usr/local/mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/RfxDevices - - + /usr/local/mdsplus/rpm/python_module_install.sh RfxDevices + /usr/local/mdsplus/rpm/python_module_remove.sh RfxDevices + - /mdsplus/rpm/removePythonModule.sh RfxDevices - python -m compileall -q /mdsplus/pydevices/RfxDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/RfxDevices + /mdsplus/rpm/python_module_install.sh RfxDevices + /mdsplus/rpm/python_module_remove.sh RfxDevices -
+ -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh W7xDevices
- python -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7Devices -fi - - + $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_install.sh W7xDevices + if test "$1" = "0" ; then $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_remove.sh W7xDevices; fi - - /usr/local/mdsplus/rpm/removePythonModule.sh W7xDevices - python -m compileall -q /usr/local/mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/W7xDevices - - + /usr/local/mdsplus/rpm/python_module_install.sh W7xDevices + /usr/local/mdsplus/rpm/python_module_remove.sh W7xDevices + - /mdsplus/rpm/removePythonModule.sh W7xDevices - python -m compileall -q /mdsplus/pydevices/W7xDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/W7xDevices + /mdsplus/rpm/python_module_install.sh W7xDevices + /mdsplus/rpm/python_module_remove.sh W7xDevices
- -
$RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh HtsDevices
- python -m compileall -q $RPM_INSTALL_PREFIX/mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - -if [ "$1" == "0" ] -then - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/pydevices/W7Devices -fi - + + $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_install.sh HtsDevices + if test "$1" = "0" ; then $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_remove.sh HtsDevices; fi - - /usr/local/mdsplus/rpm/removePythonModule.sh HtsDevices - python -m compileall -q /usr/local/mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - rm -Rf /usr/local/mdsplus/pydevices/HtsDevices - - + /usr/local/mdsplus/rpm/python_module_install.sh HtsDevices + /usr/local/mdsplus/rpm/python_module_remove.sh HtsDevices + - /mdsplus/rpm/removePythonModule.sh HtsDevices - python -m compileall -q /mdsplus/pydevices/HtsDevices >/dev/null 2>&1 - rm -Rf /mdsplus/pydevices/HtsDevices + /mdsplus/rpm/python_module_install.sh HtsDevices + /mdsplus/rpm/python_module_remove.sh HtsDevices
@@ -884,79 +778,23 @@ fi - - - + + - - $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MDSplus - find $RPM_INSTALL_PREFIX/mdsplus/python -name '*egg-info' -delete - for py in python python3 - do - if ( ${py} -c exit\(\) >/dev/null 2>&1 ) - then - ${py} -m compileall -q -f $RPM_INSTALL_PREFIX/mdsplus/python >/dev/null 2>&1 - ${py} $RPM_INSTALL_PREFIX/mdsplus/python/MDSplus/setup.py -q install >/dev/null 2>&1 - fi - done - - - if [ "$1" == "0" ] - then - $RPM_INSTALL_PREFIX/mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf $RPM_INSTALL_PREFIX/mdsplus/python - fi - + $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_install.sh MDSplus + if test "$1" = "0" ; then $RPM_INSTALL_PREFIX/mdsplus/rpm/python_module_remove.sh MDSplus; fi - - - if test ! -z $(/usr/local/mdsplus/rpm/removePythonModule.sh MDSplus y) - then setup_install=y - elif echo $PYTHONPATH|grep /usr/local/mdsplus/python>/dev/null - then setup_install=n - else read -t 10 -p "Do you wish to run setup.py install? (y/N) " setup_install - fi - find /usr/local/mdsplus/python -name '*egg-info' -delete - - for py in python python3 - do - if ( ${py} -c exit\(\) >/dev/null 2>&1 ) - then - ${py} -m compileall -q -f /usr/local/mdsplus/python >/dev/null 2>&1 - if test "$setup_install" = "y" - then - if ! ${py} /usr/local/mdsplus/python/MDSplus/setup.py -q install >/dev/null - then echo "Could not 'setup.py install' MDSplus for ${py}" - fi - fi - fi - done - - - /usr/local/mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf /usr/local/mdsplus/python - - - + /usr/local/mdsplus/rpm/python_module_install.sh MDSplus + /usr/local/mdsplus/rpm/python_module_remove.sh MDSplus + - - python -m compileall -q -f /mdsplus/python >/dev/null 2>&1 - python /mdsplus/python/MDSplus/setup.py -q install - rm -Rf build dist MDSplus.egg-info - - - /mdsplus/rpm/removePythonModule.sh MDSplus - rm -Rf /mdsplus/python - - - /mdsplus/rpm/removePythonModule.sh MDSplus - + /mdsplus/rpm/python_module_install.sh MDSplus + /mdsplus/rpm/python_module_remove.sh MDSplus - @@ -982,44 +820,42 @@ fi - - - -%%define debug_package %%{nil} -%%global _missing_build_ids_terminate_build 0 -%%global _unpackaged_files_terminate_build 0 -Name: mdsplus%(bname)s%(packagename)s -Version: %(major)d.%(minor)d -Release: %(release)s.%(distname)s -License: BSD Open Source - Copyright (c) 2010, Massachusetts Institute of Technology All rights reserved. -Source: https://github.com/MDSplus/mdsplus/archive/%(branch)s_release-%(major)d-%(minor)d-%(release)d.tar.gz -URL: http://www.mdsplus.org -Vendor: Massachusetts Institute of Technology -Packager: Plasma Science and Fusion Center <mdsplus@www.mdsplus.org> -Summary: %(summary)s -Group: Applications/Archiving -Prefix: /usr/local -AutoReqProv: yes - - - - - + + + + + + + + + + + + + + + + + - - + + + - - + + + + - - + + + diff --git a/deploy/packaging/linux_build_packages.py b/deploy/packaging/linux_build_packages.py new file mode 100644 index 0000000000..7024a0db5f --- /dev/null +++ b/deploy/packaging/linux_build_packages.py @@ -0,0 +1,62 @@ +import os +import sys +import xml.etree.ElementTree as ET + +srcdir = os.path.realpath(os.path.dirname(__file__)+'/../..') + +if sys.version_info < (3,): + def b(s): return s + def s(b): return b + def writeb(f, string): os.write(f, string) + def writes(f, string): os.write(f, string) +else: + def b(s): return s.encode() if isinstance(s, str) else s + def s(b): return b if isinstance(b, str) else b.decode() + def writeb(f, string): os.write(f, b(string)) + def writes(f, string): os.write(f, s(string)) + +def get_info(): + info = dict() + info['buildroot'] = os.environ['BUILDROOT'] + info['branch'] = os.environ['BRANCH'] + info['flavor'] = os.environ['FLAVOR'] + info['bname'] = os.environ['BNAME'] + info['dist'] = os.environ['DISTNAME'] + info['platform'] = os.environ['PLATFORM'] + info['arch'] = os.environ['ARCH'] + version = os.environ['RELEASE_VERSION'].split('.') + info['major'] = int(version[0]) + info['minor'] = int(version[1]) + info['release'] = int(version[2]) + return info + + +def get_root(): + return ET.parse(srcdir+'/deploy/packaging/linux.xml').getroot() + + +def external_package(info, root, package): + for extpackages in root.getiterator('external_packages'): + dist = extpackages.attrib.get('dist', None) + if dist: + if info['dist'] != dist: + continue + selected = dist + else: + platform = extpackages.attrib.get('platform', None) + if platform: + if info['platform'] != platform: + continue + selected = platform + else: + continue + pkg = extpackages.find(package) + if pkg is not None: # found and include dependency + pkg = pkg.attrib.get('package', package) + print('REQUIRES: %s' % (pkg,)) + return pkg + print('REQUIRES: %s but skipped in %s.' % (package, selected)) + return None + # not found so dont include dependency + print('REQUIRES: %s but no fitting external_packages found.' % (package,)) + return None diff --git a/deploy/packaging/redhat/kernel.noarch b/deploy/packaging/redhat/kernel.noarch index 45bf74bc5f..5c37684743 100644 --- a/deploy/packaging/redhat/kernel.noarch +++ b/deploy/packaging/redhat/kernel.noarch @@ -43,7 +43,8 @@ ./usr/local/mdsplus/rpm/mdsipsd.xinetd ./usr/local/mdsplus/rpm/post_install_script ./usr/local/mdsplus/rpm/post_uninstall_script -./usr/local/mdsplus/rpm/removePythonModule.sh +./usr/local/mdsplus/rpm/python_module_install.sh +./usr/local/mdsplus/rpm/python_module_remove.sh ./usr/local/mdsplus/setup.csh ./usr/local/mdsplus/setup.sh ./usr/local/mdsplus/share diff --git a/deploy/platform/redhat/redhat_build_rpms.py b/deploy/packaging/redhat/redhat_build_rpms.py similarity index 67% rename from deploy/platform/redhat/redhat_build_rpms.py rename to deploy/packaging/redhat/redhat_build_rpms.py index eec423e868..d10d4809e2 100755 --- a/deploy/platform/redhat/redhat_build_rpms.py +++ b/deploy/packaging/redhat/redhat_build_rpms.py @@ -28,34 +28,37 @@ import os import sys import pexpect -import xml.etree.ElementTree as ET -import fnmatch import tempfile -srcdir = os.path.realpath(os.path.dirname( - os.path.realpath(__file__))+'/../../..') - - -def doWrite(out, string): - try: - os.write(out, string.encode()) - except Exception: - os.write(out, string) - - -def externalPackage(info, root, package): - ans = None - for extpackages in root.getiterator('external_packages'): - platform = extpackages.attrib['platform'] - if platform == info['platform']: - pkg = extpackages.find(package) - if pkg is not None: - if 'package' in pkg.attrib: - ans = pkg.attrib['package'] - else: - ans = package - return ans - +srcdir = os.path.realpath(os.path.dirname(__file__)+'/../../..') +sys.path.insert(0, os.path.join(srcdir, 'deploy', 'packaging')) +import linux_build_packages as common + +rpmspec = """ +%%define debug_package %%{nil} +%%global _missing_build_ids_terminate_build 0 +%%global _unpackaged_files_terminate_build 0 +Name: mdsplus%(bname)s%(packagename)s +Version: %(major)d.%(minor)d +Release: %(release)s.%(dist)s +License: BSD Open Source - Copyright (c) 2010, Massachusetts Institute of Technology All rights reserved. +Source: https://github.com/MDSplus/mdsplus/archive/%(branch)s_release-%(major)d-%(minor)d-%(release)d.tar.gz +URL: http://www.mdsplus.org +Vendor: Massachusetts Institute of Technology +Packager: Plasma Science and Fusion Center +Summary: %(summary)s +Group: Applications/Archiving +Prefix: /usr/local +AutoReqProv: yes +""" + +pckspec = """ +%%description +%(description)s +%%clean +%%files +%%defattr(-,root,root) +""" def fixFilename(info, filename): """For binary packages we need to refer to /libnn, /binnn and /uidnn where nn is 32 or 64. For @@ -81,40 +84,17 @@ def fixFilename(info, filename): def doRequire(info, out, root, require): if 'external' in require.attrib: - pkg = externalPackage(info, root, require.attrib['package']) - if pkg is not None: - print('***************** REQUIRES ***********', - pkg, '*******************') - doWrite(out, "Requires: %s\n" % pkg) + pkg = common.external_package(info, root, require.attrib['package']) + if pkg: + common.writeb(out, "Requires: %s\n" % pkg) else: info['reqpkg'] = require.attrib['package'] - doWrite(out, "Requires: mdsplus%(bname)s-%(reqpkg)s = %(major)d.%(minor)d-%(release)d.%(distname)s\n" % info) + common.writeb(out, "Requires: mdsplus%(bname)s-%(reqpkg)s = %(major)d.%(minor)d-%(release)d.%(dist)s\n" % info) -def buildRpms(): - info = dict() - info['branch'] = os.environ['BRANCH'] - version = os.environ['RELEASE_VERSION'].split('.') - info['major'] = int(version[0]) - info['minor'] = int(version[1]) - info['release'] = int(version[2]) - info['distname'] = os.environ['DISTNAME'] - info['buildroot'] = os.environ['BUILDROOT'] - info['bname'] = os.environ['BNAME'] - info['platform'] = os.environ['PLATFORM'] - print('******** DISTNAME is *************', info['distname']) - if info['distname'] != 'el8': - tree = ET.parse(srcdir+'/deploy/packaging/linux.xml') - else: - tree = ET.parse(srcdir+'/deploy/packaging/linux-rhel8.xml') - root = tree.getroot() - rpmspec = root.find('rpm').find('spec_start').text - s = rpmspec.split('\n') - for idx in range(len(s)): - if len(s[idx].strip()) == 0: - s[idx] = "" - rpmspec = '\n'.join(s) - +def build(): + info = common.get_info() + root = common.get_root() bin_packages = list() noarch_packages = list() for package in root.getiterator('package'): @@ -125,7 +105,7 @@ def buildRpms(): bin_packages.append(package) architectures = [{"target": "x86_64-linux", "bits": 64, "arch_t": ".x86_64"}] - if os.environ['DISTNAME'] != 'el8': + if info['dist'] != 'el8': architectures.append( {"target": "i686-linux", "bits": 32, "arch_t": ".i686"}) @@ -142,36 +122,29 @@ def buildRpms(): info['summary'] = package.attrib['summary'] info['description'] = package.attrib['description'] out, specfilename = tempfile.mkstemp() - print (info, rpmspec) - doWrite(out, rpmspec % info) + common.writeb(out, rpmspec % info) for require in package.getiterator("requires"): doRequire(info, out, root, require) - doWrite(out, """ -%%description -%(description)s -%%clean -%%files -%%defattr(-,root,root) -""" % info) + common.writeb(out, pckspec % info) for inc in package.getiterator('include'): for inctype in inc.attrib: include = fixFilename(info, inc.attrib[inctype]) if inctype == "dironly": - doWrite(out, "%%dir %s\n" % include) + common.writeb(out, "%%dir %s\n" % include) else: - doWrite(out, "%s\n" % include) + common.writeb(out, "%s\n" % include) for exc in package.getiterator('exclude'): for exctype in exc.attrib: exclude = fixFilename(info, exc.attrib[exctype]) - doWrite(out, "%%exclude %s\n" % exclude) + common.writeb(out, "%%exclude %s\n" % exclude) if package.find("exclude_staticlibs") is not None: - doWrite(out, "%%exclude /usr/local/mdsplus/lib%(bits)d/*.a\n" % info) + common.writeb(out, "%%exclude /usr/local/mdsplus/lib%(bits)d/*.a\n" % info) if package.find("include_staticlibs") is not None: - doWrite(out, "/usr/local/mdsplus/lib%(bits)d/*.a\n" % info) - for s in ("pre", "post", "preun", "postun"): - script = package.find(s) + common.writeb(out, "/usr/local/mdsplus/lib%(bits)d/*.a\n" % info) + for phase in ("pre", "post", "preun", "postun"): + script = package.find(phase) if script is not None: - doWrite(out, "%%%s\n%s\n" % (s, script.text)) + common.writeb(out, "%%%s\n%s\n" % (phase, script.text)) os.close(out) info['specfilename'] = specfilename print("Building rpm for mdsplus%(bname)s%(packagename)s%(arch_t)s" % info) @@ -179,27 +152,22 @@ def buildRpms(): sys.stdout.flush() subprocess.Popen("/bin/cat %(specfilename)s" % info, shell=True).wait() - for s in ('BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'): + for dir in ('BUILD', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'): try: - os.mkdir('/release/%(branch)s/' % info + s) + os.mkdir(('/release/%(flavor)s/' % info) + dir) except OSError: pass # if exists - p = subprocess.Popen("rpmbuild -bb --define '_topdir /release/%(branch)s' --buildroot=%(buildroot)s --target=%(target)s %(specfilename)s 2>&1" % + p = subprocess.Popen("rpmbuild -bb --define '_topdir /release/%(flavor)s' --buildroot=%(buildroot)s --target=%(target)s %(specfilename)s 2>&1" % info, stdout=subprocess.PIPE, shell=True) - messages = p.stdout.readlines() + message = p.stdout.read() status = p.wait() os.remove(specfilename) if status != 0: - for msg in messages: - if isinstance(msg, str): - sys.stdout.write(msg) - else: - sys.stdout.write(msg.decode()) + sys.stdout.write(common.s(message)) sys.stdout.flush() raise Exception( "Error building rpm for package mdsplus%(bname)s%(packagename)s%(arch_t)s" % info) - print( - "Done building rpm for mdsplus%(bname)s%(packagename)s%(arch_t)s" % info) + print("Done building rpm for mdsplus%(bname)s%(packagename)s%(arch_t)s" % info) sys.stdout.flush() for package in noarch_packages: info['arch'] = "noarch" @@ -210,46 +178,40 @@ def buildRpms(): info['summary'] = package.attrib['summary'] info['description'] = package.attrib['description'] out, specfilename = tempfile.mkstemp() - doWrite(out, rpmspec % info) + common.writeb(out, rpmspec % info) for require in package.getiterator("requires"): doRequire(info, out, root, require) - doWrite(out, """ -Buildarch: noarch -%%description -%(description)s -%%clean -%%files -%%defattr(-,root,root) -""" % info) + common.writeb(out, "Buildarch: noarch\n") + common.writeb(out, pckspec % info) for inc in package.getiterator('include'): for inctype in inc.attrib: include = fixFilename(info, inc.attrib[inctype]) if inctype == "dironly": - doWrite(out, "%%dir %s\n" % include) + common.writeb(out, "%%dir %s\n" % include) else: - doWrite(out, "%s\n" % include) + common.writeb(out, "%s\n" % include) for exc in package.getiterator('exclude'): for exctype in exc.attrib: exclude = fixFilename(info, exc.attrib[exctype]) - doWrite(out, "%%exclude %s\n" % exclude) + common.writeb(out, "%%exclude %s\n" % exclude) if package.find("exclude_staticlibs") is not None: - doWrite(out, "%%exclude /usr/local/mdsplus/lib??/*.a\n" % info) + common.writeb(out, "%%exclude /usr/local/mdsplus/lib??/*.a\n" % info) for s in ("pre", "post", "preun", "postun"): script = package.find(s) if script is not None: - doWrite(out, "%%%s\n%s\n" % (s, script.text)) + common.writeb(out, "%%%s\n%s\n" % (s, script.text)) os.close(out) info['specfilename'] = specfilename print("Building rpm for mdsplus%(bname)s%(packagename)s.noarch" % info) sys.stdout.flush() subprocess.Popen("/bin/cat %(specfilename)s" % info, shell=True).wait() - p = subprocess.Popen("rpmbuild -bb --define '_topdir /release/%(branch)s' --buildroot=%(buildroot)s %(specfilename)s 2>&1" % + p = subprocess.Popen("rpmbuild -bb --define '_topdir /release/%(flavor)s' --buildroot=%(buildroot)s %(specfilename)s 2>&1" % info, stdout=subprocess.PIPE, shell=True) - messages = p.stdout.readlines() + message = p.stdout.read() status = p.wait() os.remove(specfilename) if status != 0: - print(''.join(messages)) + print(common.s(message)) raise Exception( "Error building rpm for package mdsplus%(bname)s%(packagename)s.noarch" % info) print("Done building rpm for mdsplus%(bname)s%(packagename)s.noarch" % info) @@ -257,7 +219,7 @@ def buildRpms(): try: os.stat('/sign_keys/.gnupg') try: - cmd = "/bin/sh -c 'rsync -a /sign_keys /tmp/; HOME=/tmp/sign_keys rpmsign --addsign /release/%(branch)s/RPMS/*/*%(major)d.%(minor)d-%(release)d*.rpm'" % info + cmd = "/bin/sh -c 'rsync -a /sign_keys /tmp/; HOME=/tmp/sign_keys rpmsign --addsign /release/%(flavor)s/RPMS/*/*%(major)d.%(minor)d-%(release)d*.rpm'" % info try: if sys.version_info < (3,): bout = sys.stdout @@ -281,5 +243,5 @@ def buildRpms(): except: print("Sign keys unavailable. Not signing packages.") - -buildRpms() +if __name__ == "__main__": + build() diff --git a/deploy/packaging/windows/create_installer.sh b/deploy/packaging/windows/create_installer.sh index 9788cfa433..f76c40ed1a 100755 --- a/deploy/packaging/windows/create_installer.sh +++ b/deploy/packaging/windows/create_installer.sh @@ -9,16 +9,10 @@ major=$(echo ${RELEASE_VERSION} | cut -d. -f1) minor=$(echo ${RELEASE_VERSION} | cut -d. -f2) release=$(echo ${RELEASE_VERSION} | cut -d. -f3) -if [ "${BRANCH}" = "stable" ]; then - bname="" -else - bname="-${BRANCH}" -fi - pushd ${MDSPLUS_DIR} -makensis -V4 -DMAJOR=${major} -DMINOR=${minor} -DRELEASE=${release} -DFLAVOR=${bname} -NOCD -DBRANCH=${BRANCH} \ +makensis -V4 -DMAJOR=${major} -DMINOR=${minor} -DRELEASE=${release} -DBNAME=${BNAME} -NOCD -DBRANCH=${BRANCH} \ -DINCLUDE=${srcdir}/deploy/packaging/${PLATFORM} \ - -DOUTDIR=/release/${BRANCH} -Dsrcdir=${srcdir} ${vs} ${srcdir}/deploy/packaging/${PLATFORM}/mdsplus.nsi + -DOUTDIR=/release/${FLAVOR} -Dsrcdir=${srcdir} ${vs} ${srcdir}/deploy/packaging/${PLATFORM}/mdsplus.nsi popd if [ -d /sign_keys ]; then echo "Signing installer" @@ -26,11 +20,11 @@ if [ -d /sign_keys ]; then osslsigncode sign -certs /sign_keys/mdsplus.spc \ -key /sign_keys/mdsplus.pvk -pass mdsplus \ -n "MDSplus" -i http://www.mdsplus.org/ \ - -in /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe \ - -out /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe + -in /release/${FLAVOR}/MDSplus${BNAME}-${major}.${minor}-${release}.exe \ + -out /release/${FLAVOR}/MDSplus${BNAME}-${major}.${minor}-${release}-signed.exe ); then - mv -v /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}-signed.exe \ - /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe + mv -v /release/${FLAVOR}/MDSplus${BNAME}-${major}.${minor}-${release}-signed.exe \ + /release/${FLAVOR}/MDSplus${BNAME}-${major}.${minor}-${release}.exe echo "Installer successfully signed" else echo "Failed to sign installer" diff --git a/deploy/packaging/windows/mdsplus.nsi b/deploy/packaging/windows/mdsplus.nsi index 958484d50c..d3a50d907a 100644 --- a/deploy/packaging/windows/mdsplus.nsi +++ b/deploy/packaging/windows/mdsplus.nsi @@ -1,9 +1,9 @@ -Name "MDSplus${FLAVOR} ${MAJOR}.${MINOR}-${RELEASE}" -OutFile ${OUTDIR}/MDSplus${FLAVOR}-${MAJOR}.${MINOR}-${RELEASE}.exe +Name "MDSplus${BNAME} ${MAJOR}.${MINOR}-${RELEASE}" +OutFile ${OUTDIR}/MDSplus${BNAME}-${MAJOR}.${MINOR}-${RELEASE}.exe ;SetCompress off SetCompressor /FINAL LZMA ShowInstDetails show -InstType "Typical" +InstType "Typical" InstType "Full" InstType "Minimal" @@ -153,7 +153,7 @@ Function install_core_pre File MDSplus-License.rtf # Registry information for add/remove programs - ${WriteKeyStr} "${UNINSTALL_KEY}" "DisplayName" "MDSplus${FLAVOR}" + ${WriteKeyStr} "${UNINSTALL_KEY}" "DisplayName" "MDSplus${BNAME}" ${WriteKeyStr} "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\uninstall.exe" /$MultiUser.InstallMode' ${WriteKeyStr} "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S /$MultiUser.InstallMode' ${WriteKeyStr} "${UNINSTALL_KEY}" "Uninstaller" "$INSTDIR\uninstall.exe" @@ -691,7 +691,7 @@ functionEnd ; un.onInit Function un.onGUIEnd SendMessage ${HWND_BROADCAST} ${WM_SETTINGCHANGE} 0 "STR:Environment" /TIMEOUT=5000 FunctionEnd - + Section uninstall Push $R0 Push $R1 diff --git a/deploy/platform/alpine/alpine_docker_build.sh b/deploy/platform/alpine/alpine_docker_build.sh index 17b087a11a..a46d806803 100644 --- a/deploy/platform/alpine/alpine_docker_build.sh +++ b/deploy/platform/alpine/alpine_docker_build.sh @@ -42,7 +42,7 @@ buildrelease() { rm -Rf ${RELEASEBLD} mkdir -p ${RELEASEBLD} ${BUILDROOT} ${MDSPLUS_DIR} pushd ${RELEASEBLD} - config ${ARCH} ${host} bin lib ${ALPHA_DEBUG_INFO} + config ${ARCH} ${host} bin lib ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -50,10 +50,6 @@ buildrelease() { popd if [ -z "$NOMAKE" ]; then BUILDROOT=${BUILDROOT} \ - BRANCH=${BRANCH} \ - RELEASE_VERSION=${RELEASE_VERSION} \ - ARCH=${ARCH} \ - DISTNAME=${DISTNAME} \ ${srcdir}/deploy/packaging/alpine/build_apks.sh fi } @@ -63,8 +59,8 @@ publish() { ## this will move new files into publish and update APKINDEX.tar.gz # if NEW.tar.gz exists or if an old APKINDEX.tar.gz does not yet exist, # it will create a new repository (takes longer, exspecially on a remote fs) - R=/release/${BRANCH} - P=/publish/${BRANCH} + R=/release/${FLAVOR} + P=/publish/${FLAVOR} mkdir -p $P/${ARCH} $P/noarch cd $P rsync -a $R/${ARCH}/*.apk $P/${ARCH}/ && : diff --git a/deploy/platform/debian/debian_docker_build.sh b/deploy/platform/debian/debian_docker_build.sh index 86478a457f..065109d021 100755 --- a/deploy/platform/debian/debian_docker_build.sh +++ b/deploy/platform/debian/debian_docker_build.sh @@ -62,15 +62,15 @@ debtopkg() { buildrelease() { ### Build release version of MDSplus and then construct installer debs set -e - # ${RELEASEDIR}/${BRANCH}/DEBS will be cleaned in debian_build.sh - RELEASEDEBS=/release/${BRANCH}/DEBS/${ARCH} + # ${RELEASEDIR}/${FLAVOR}/DEBS will be cleaned in debian_build.sh + RELEASEDEBS=/release/${FLAVOR}/DEBS/${ARCH} RELEASEBLD=/workspace/releasebld BUILDROOT=${RELEASEBLD}/buildroot MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus rm -Rf ${RELEASEBLD}/${bits} ${BUILDROOT} mkdir -p ${RELEASEBLD}/${bits} ${BUILDROOT} ${MDSPLUS_DIR} pushd ${RELEASEBLD}/${bits} - config ${config_param} ${ALPHA_DEBUG_INFO} + config ${config_param} ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -78,15 +78,10 @@ buildrelease() { popd if [ -z "$NOMAKE" ]; then mkdir -p ${RELEASEDEBS} - BRANCH=${BRANCH} \ - RELEASE_VERSION=${RELEASE_VERSION} \ - ARCH=${ARCH} \ - DISTNAME=${DISTNAME} \ - BUILDROOT=${BUILDROOT} \ - PLATFORM=${PLATFORM} \ - ${srcdir}/deploy/platform/debian/debian_build_debs.py + BUILDROOT=${BUILDROOT} \ + ${srcdir}/deploy/packaging/debian/debian_build_debs.py baddeb=0 - for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*${RELEASE_VERSION}_*\.deb"); do + for deb in $(find ${RELEASEDEBS} -name "*${RELEASE_VERSION}_*\.deb"); do pkg=$(debtopkg $(basename $deb) "${BNAME}" ${RELEASE_VERSION} ${ARCH}) if [ "${#pkg}" = "0" ]; then continue @@ -114,10 +109,10 @@ buildrelease() { if [ -z "$abort" ] || [ "$abort" = "0" ]; then echo "Building repo" mkdir -p /release/repo/conf /release/repo/db /release/repo/dists /release/repo/pool - if [ "${BRANCH}" = "alpha" -o "${BRANCH}" = "stable" ]; then + if [ "${FLAVOR}" = "alpha" -o "${FLAVOR}" = "stable" ]; then component="" else - component=" ${BRANCH}" + component=" ${FLAVOR}" fi GPG_HOME="" if [ -d /sign_keys/${OS}/.gnupg ]; then @@ -148,9 +143,9 @@ ${SIGN_WITH} EOF pushd /release/repo reprepro clearvanished - for deb in $(find /release/${BRANCH}/DEBS/${ARCH} -name "*${RELEASE_VERSION}_*\.deb"); do + for deb in $(find /release/${FLAVOR}/DEBS/${ARCH} -name "*${RELEASE_VERSION}_*\.deb"); do if [ -z "$abort" ] || [ "$abort" = "0" ]; then - : && HOME=/tmp reprepro -V -C ${BRANCH} includedeb MDSplus $deb + : && HOME=/tmp reprepro -V -C ${FLAVOR} includedeb MDSplus $deb checkstatus abort "Failure: Problem installing $deb into repository." $? else break @@ -163,9 +158,9 @@ EOF publish() { ### DO NOT CLEAN /publish as it may contain valid older release packages - mkdir -p /publish/${BRANCH}/DEBS - rsync -a /release/${BRANCH}/DEBS/${ARCH} /publish/${BRANCH}/DEBS/ - LAST_RELEASE_INFO=/publish/${BRANCH}_${OS} + mkdir -p /publish/${FLAVOR}/DEBS + rsync -a /release/${FLAVOR}/DEBS/${ARCH} /publish/${FLAVOR}/DEBS/ + LAST_RELEASE_INFO=/publish/${FLAVOR}_${OS} if [ ! -r /publish/repo ]; then : && rsync -a /release/repo /publish/ checkstatus abort "Failure: Problem copying repo into publish area." $? @@ -173,9 +168,9 @@ publish() { pushd /publish/repo rsync -a /release/repo/conf/distributions /publish/repo/conf/ reprepro clearvanished - : && env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus ../${BRANCH}/DEBS/${ARCH}/*${RELEASE_VERSION}_*.deb || + : && env HOME=/sign_keys reprepro -V --keepunused -C ${FLAVOR} includedeb MDSplus ../${FLAVOR}/DEBS/${ARCH}/*${RELEASE_VERSION}_*.deb || env HOME=/sign_keys reprepro export MDSplus - checkstatus abort "Failure: Problem installing ${BRANCH} into debian repository." $? + checkstatus abort "Failure: Problem installing ${FLAVOR} into debian repository." $? if [ -f ${LAST_RELEASE_INFO} ]; then PREVIOUS_VERSION="$(cat ${LAST_RELEASE_INFO})" else @@ -183,9 +178,9 @@ publish() { fi echo "PREVIOUS_VERSION=${PREVIOUS_VERSION}" if [ -n $PREVIOUS_VERSION ]; then - : && env HOME=/sign_keys reprepro -V --keepunused -C ${BRANCH} includedeb MDSplus-previous ../${BRANCH}/DEBS/${ARCH}/*${PREVIOUS_VERSION}_*.deb || + : && env HOME=/sign_keys reprepro -V --keepunused -C ${FLAVOR} includedeb MDSplus-previous ../${FLAVOR}/DEBS/${ARCH}/*${PREVIOUS_VERSION}_*.deb || env HOME=/sign_keys reprepro export MDSplus-previous - checkstatus abort "Failure: Problem installing previous ${BRANCH} into debian repository." $? + checkstatus abort "Failure: Problem installing previous ${FLAVOR} into debian repository." $? fi popd fi diff --git a/deploy/platform/macosx/macosx_build.sh b/deploy/platform/macosx/macosx_build.sh index f50fe7d5c8..740fb96927 100755 --- a/deploy/platform/macosx/macosx_build.sh +++ b/deploy/platform/macosx/macosx_build.sh @@ -85,7 +85,7 @@ then ${SRCDIR}/configure \ --prefix=${MDSPLUS_DIR} \ --exec_prefix=${MDSPLUS_DIR} \ - ${JAVA_OPTS} ${ALPHA_DEBUG_INFO} + ${JAVA_OPTS} ${CONFIGURE_EXTRA} $MAKE $MAKE install popd @@ -99,7 +99,7 @@ then /usr/local/bin/packagesbuild -v -F ${SRCDIR} ${WORKSPACE}/releasebld/MDSplus.pkgproj if [ "$?" == "0" ] then - mv ${WORKSPACE}/releasebld/buildroot/MDSplus.pkg ${RELEASEDIR}/${BRANCH}/MDSplus${BNAME}-${VERS[0]}-${VERS[1]}-${VERS[2]}-osx.pkg + mv ${WORKSPACE}/releasebld/buildroot/MDSplus.pkg ${RELEASEDIR}/${BRANCH}/MDSplus${BNAME}-${VERS[0]}-${VERS[1]}-${VERS[2]}-osx.pkg fi # /Developer/usr/bin/packagemaker \ # --title "MDSplus%(pkgflavor)s" \ diff --git a/deploy/platform/platform_build.sh b/deploy/platform/platform_build.sh index d085c60cb5..99ab8cc642 100755 --- a/deploy/platform/platform_build.sh +++ b/deploy/platform/platform_build.sh @@ -80,6 +80,7 @@ rundocker() { if docker network >/dev/null 2>&1; then #docker supports --network if [ -z ${DOCKER_NETWORK} ]; then + docker network rm ${OS} || : docker network create ${OS} NETWORK=--network=${OS} else @@ -100,6 +101,8 @@ rundocker() { -e "ARCH=${arch}" \ -e "ARCHES=${ARCH}" \ -e "BRANCH" \ + -e "BNAME" \ + -e "FLAVOR" \ -e "COLOR" \ -e "DISPLAY" \ -e "DISTNAME" \ @@ -120,7 +123,7 @@ rundocker() { -e "HOME=/workspace" \ -e "JARS_DIR=$jars_dir" \ -e "TEST_TIMEUNIT" \ - -e "ALPHA_DEBUG_INFO" \ + -e "CONFIGURE_EXTRA" \ -v ${SRCDIR}:${DOCKER_SRCDIR} \ -v ${WORKSPACE}:/workspace $port_forwarding $(volume "${JARS_DIR}" /jars_dir) \ $(volume "${RELEASEDIR}" /release) \ @@ -156,19 +159,32 @@ EOF } default_build() { if [ "${RELEASE}" = "yes" ]; then - rm -Rf ${RELEASEDIR}/${BRANCH} - mkdir -p ${RELEASEDIR}/${BRANCH} + rm -Rf ${RELEASEDIR}/${FLAVOR} + mkdir -p ${RELEASEDIR}/${FLAVOR} fi if [ "${PUBLISH}" = "yes" ]; then - mkdir -p ${PUBLISHDIR}/${BRANCH} + mkdir -p ${PUBLISHDIR}/${FLAVOR} fi } -if [ "$BRANCH" = "alpha" ]; then - ALPHA_DEBUG_INFO=--enable-debug=info -else - ALPHA_DEBUG_INFO= -fi +case "$BRANCH" in + stable) + export CONFIGURE_EXTRA= + export FLAVOR="stable" + export BNAME="" + ;; + alpha) + export CONFIGURE_EXTRA=--enable-debug=info + export FLAVOR="alpha" + export BNAME="-alpha" + ;; + *) + export CONFIGURE_EXTRA=--enable-debug=info + export FLAVOR="other" + export BNAME="-other" + ;; +esac + set +e platform_build="${SRCDIR}/deploy/platform/${PLATFORM}/${PLATFORM}_build.sh" if [ -f "${platform_build}" ]; then diff --git a/deploy/platform/platform_docker_build.sh b/deploy/platform/platform_docker_build.sh index d8760ed53b..ba60ff1c1d 100755 --- a/deploy/platform/platform_docker_build.sh +++ b/deploy/platform/platform_docker_build.sh @@ -205,11 +205,6 @@ main(){ set +e make_jars fi - case "$BRANCH" in - stable) export BNAME="";; - alpha) export BNAME="-alpha";; - *) export BNAME="-other";; - esac if [ "$RELEASE" = "yes" ] then set +e diff --git a/deploy/platform/redhat/redhat_docker_build.sh b/deploy/platform/redhat/redhat_docker_build.sh index 2eb1b24290..eebb801195 100755 --- a/deploy/platform/redhat/redhat_docker_build.sh +++ b/deploy/platform/redhat/redhat_docker_build.sh @@ -17,13 +17,13 @@ do_createrepo() { repodir=$1 tmpdir=$(mktemp -d) trap 'rm -Rf ${tmpdir}' EXIT - if [ -d ${repodir}/${BRANCH}/RPMS/repodata ]; then - rsync -a ${repodir}/${BRANCH}/RPMS/repodata ${tmpdir} - update_args="--update --cachedir ${repodir}/${BRANCH}/cache ${use_deltas}" + if [ -d ${repodir}/${FLAVOR}/RPMS/repodata ]; then + rsync -a ${repodir}/${FLAVOR}/RPMS/repodata ${tmpdir} + update_args="--update --cachedir ${repodir}/${FLAVOR}/cache ${use_deltas}" fi - : && createrepo -q $update_args -o ${tmpdir} ${repodir}/${BRANCH}/RPMS + : && createrepo -q $update_args -o ${tmpdir} ${repodir}/${FLAVOR}/RPMS checkstatus abort "Failure: Problem creating rpm repository in ${repodir}!" $? - : && rsync -a ${tmpdir}/repodata ${repodir}/${BRANCH}/RPMS/ + : && rsync -a ${tmpdir}/repodata ${repodir}/${FLAVOR}/RPMS/ } srcdir=$(readlink -e $(dirname ${0})/../..) @@ -58,10 +58,10 @@ buildrelease() { RELEASEBLD=/workspace/releasebld BUILDROOT=${RELEASEBLD}/buildroot MDSPLUS_DIR=${BUILDROOT}/usr/local/mdsplus - rm -Rf ${RELEASEBLD} /release/${BRANCH} + rm -Rf ${RELEASEBLD} /release/${FLAVOR} mkdir -p ${RELEASEBLD}/64 ${BUILDROOT} ${MDSPLUS_DIR} pushd ${RELEASEBLD}/64 - config ${test64} ${ALPHA_DEBUG_INFO} + config ${test64} ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -70,7 +70,7 @@ buildrelease() { if [ "${ARCHES}" != "amd64" ]; then mkdir -p ${RELEASEBLD}/32 pushd ${RELEASEBLD}/32 - config ${test32} ${ALPHA_DEBUG_INFO} + config ${test32} ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -97,23 +97,18 @@ buildrelease() { cat - >${BUILDROOT}/etc/yum.repos.d/mdsplus${BNAME}.repo </dev/null); then use_deltas="--deltas" diff --git a/deploy/platform/windows/windows_docker_build.sh b/deploy/platform/windows/windows_docker_build.sh index 62e0351436..40b935ca1a 100755 --- a/deploy/platform/windows/windows_docker_build.sh +++ b/deploy/platform/windows/windows_docker_build.sh @@ -3,10 +3,10 @@ # windows_docker_build.sh - build windows installer # # release: -# /release/$branch/MDSplus-*.exe +# /release/$flavor/MDSplus-*.exe # # publish: -# /publish/$branch/MDSplus-*.exe +# /publish/$flavor/MDSplus-*.exe # srcdir=$(readlink -e $(dirname ${0})/../..) @@ -35,7 +35,7 @@ buildrelease() { mkdir -p ${MDSPLUS_DIR}; mkdir -p /workspace/releasebld/64; pushd /workspace/releasebld/64; - config ${test64} ${ALPHA_DEBUG_INFO} + config ${test64} ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -43,7 +43,7 @@ buildrelease() { popd; mkdir -p /workspace/releasebld/32; pushd /workspace/releasebld/32; - config ${test32} ${ALPHA_DEBUG_INFO} + config ${test32} ${CONFIGURE_EXTRA} if [ -z "$NOMAKE" ]; then $MAKE $MAKE install @@ -71,11 +71,5 @@ publish() { major=$(echo ${RELEASE_VERSION} | cut -d. -f1) minor=$(echo ${RELEASE_VERSION} | cut -d. -f2) release=$(echo ${RELEASE_VERSION} | cut -d. -f3) - if [ "${BRANCH}" = "stable" ] - then - bname="" - else - bname="-${BRANCH}" - fi - rsync -a /release/${BRANCH}/MDSplus${bname}-${major}.${minor}-${release}.exe /publish/${BRANCH} + rsync -a /release/${FLAVOR}/MDSplus${BNAME}-${major}.${minor}-${release}.exe /publish/${FLAVOR} } diff --git a/rpm/Makefile.am b/rpm/Makefile.am index 3d9d27a4b6..34ecbd69c9 100644 --- a/rpm/Makefile.am +++ b/rpm/Makefile.am @@ -4,11 +4,10 @@ dist_etc_DATA = mdsplus.conf.template rpmdir = $(exec_prefix)/rpm rpm_SCRIPTS = post_uninstall_script -dist_rpm_SCRIPTS = post_install_script removePythonModule.sh +dist_rpm_SCRIPTS = post_install_script python_module_install.sh python_module_remove.sh if GLOBUSLICENSE dist_rpm_DATA = fusiongrid-mdsip.xinetd fusiongrid-mdsips.xinetd globus-gatekeeper.xinetd globus-gridftp.xinetd else dist_rpm_DATA = mdsipd.xinetd mdsipsd.xinetd endif - diff --git a/rpm/python_module_install.sh b/rpm/python_module_install.sh new file mode 100755 index 0000000000..5a2aef59a5 --- /dev/null +++ b/rpm/python_module_install.sh @@ -0,0 +1,28 @@ +#!/bin/sh +mdsplus_dir=$(readlink -f $(dirname ${0})/..) +module=${1} + +if test "${module}" = "MDSplus"; then + srcdir=${mdsplus_dir}/python + if test -n "$(${mdsplus_dir}/rpm/python_module_remove.sh ${module} y)"; then + setup_install=y + elif ( echo ${PYTHONPATH} | grep ${mdsplus_dir}/python >/dev/null ); then + setup_install=n + else + read -t 10 -p "Do you wish to run setup.py install? (y/N) " setup_install + fi +else + srcdir=${mdsplus_dir}/pydevices + setup_install=n +fi + +for python in python2 python3; do + if ( ${python} -c pass >/dev/null 2>&1 ); then + ${python} -m compileall -q -f ${srcdir}/${module} >/dev/null 2>&1 + if test "${setup_install}" = "y"; then + if ! ${python} ${mdsplus_dir}/python/MDSplus/setup.py -q install >/dev/null; then + echo "Could not 'setup.py install' MDSplus for ${python}" + fi + fi + fi +done diff --git a/rpm/python_module_remove.sh b/rpm/python_module_remove.sh new file mode 100755 index 0000000000..bf8304aa1d --- /dev/null +++ b/rpm/python_module_remove.sh @@ -0,0 +1,49 @@ +#!/bin/sh +mdsplus_dir=$(readlink -f $(dirname ${0})/..) +module=${1} + +get_mod_dir() { + python=$1 + if ( ${python} -s -c 'import site' >/dev/null 2>&1 ); then + opt='-s' + fi + mdir=$(realpath $(${python} -E $opt -c 'import pkgutil;print(pkgutil.get_loader("'${module}'").filename)')) 2>/dev/null + if (echo $mdir | grep "${mdsplus_dir}" >/dev/null); then + echo $mdir >&2 + return # imported form MDSPLUS_DIR + fi + echo $mdir +} + +removed=n +for python in python2 python3; do + mdir=$(get_mod_dir ${python}) + while [ ! -z "$mdir" ]; do + if ( echo $mdir | grep -i ${module}} >/dev/null ); then + if [ -L $mdir ]; then + rm -f $mdir + else + rm -Rf $mdir + fi + echo $mdir >&2 + if [ $? -eq 0 ]; then + removed=y + mdir=$(get_mod_dir ${python}) + continue # check if there is more + fi + fi + break # out of while loop + done +done + +rm -Rf ${mdsplus_dir}/python/${module}*egg-info +if test -n "$2"; then + echo $removed +else + rm -Rf ${mdsplus_dir}/python/${module} + if test "${module}" != "MDSplus"; then + ${mdsplus_dir}/pydevices/${module} + fi + rmdir ${mdsplus_dir}/python 2>/dev/null || : + rmdir ${mdsplus_dir}/pydevices 2>/dev/null || : +fi diff --git a/rpm/removePythonModule.sh b/rpm/removePythonModule.sh deleted file mode 100755 index 7c888d617b..0000000000 --- a/rpm/removePythonModule.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/sh - -getModDir() { - if ( $2 -s -c 'import site' 2>/dev/null ) - then - opt='-s' - fi - mdir=$(dirname $($2 -E $opt -c 'import '$1';print('$1'.__file__)' 2>/dev/null) 2>/dev/null) - if ( echo $mdir | grep "$3" >/dev/null) - then - return - fi - if ( dirname $mdir 2>/dev/null | grep -i mdsplus > /dev/null ) - then - mdir=$(dirname $mdir 2>/dev/null) - fi - echo $mdir -} - -removed= -mdsplus_dir=$(readlink -f $(dirname ${0})/..) -for py in python2 python3 -do - mdir=$(getModDir $1 ${py} $mdsplus_dir) - while [ ! -z "$mdir" ] - do - if ( echo $mdir | grep -i $1 >/dev/null ) - then - if [ -L $mdir ] - then - rm -f $mdir - else - rm -Rf $mdir - fi - if [ "$?" = 0 ] - then - removed=y - mdir=$(getModDir $1 ${py} $mdsplus_dir) - continue # check if there is more - fi - fi - break # out of while loop - done -done - -if test ! -z $2 -then echo $removed -fi From c0a2365dc17708bafe47dc683e34ee50829f46c0 Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Wed, 12 May 2021 15:12:32 +0200 Subject: [PATCH 23/27] Fix:jTraverer and jScope fixezs (#2310) jTraverser: avoid reading conglomerate nodes for gettin number of conglomerate elements jScope: avoid reprating Signal.setXLimits if the limits passed are the same as before. Avoid possible loops triggered by detDataAsync() calls Co-authored-by: GabrieleManduchi --- java/jscope/src/main/java/mds/wave/Signal.java | 13 ++++++++++++- .../src/main/java/mds/jtraverser/Node.java | 5 +++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/java/jscope/src/main/java/mds/wave/Signal.java b/java/jscope/src/main/java/mds/wave/Signal.java index 443a849461..1a1c25f27c 100644 --- a/java/jscope/src/main/java/mds/wave/Signal.java +++ b/java/jscope/src/main/java/mds/wave/Signal.java @@ -501,6 +501,8 @@ static String toStringTime(long time) private int x2D_points = 0; private int y2D_points = 0; private int z2D_points = 0; + + double prevSetXMin, prevSetXMax; /** * Constructs a zero Signal with 100 points. @@ -2767,7 +2769,14 @@ public void setXinYZplot(float curr_x_yz_plot) public void setXLimits(double xmin, double xmax, int mode) { - xLimitsInitialized = true; + if(xLimitsInitialized && prevSetXMin == xmin && prevSetXMax == xmax) + { + return; + } + xLimitsInitialized = true; + prevSetXMin = xmin; + prevSetXMax = xmax; + if (xmin != -Double.MAX_VALUE) { this.xmin = xmin; @@ -2817,7 +2826,9 @@ public void setXLimits(double xmin, double xmax, int mode) } if (((mode & DO_NOT_UPDATE) == 0) && (currLower != saved_xmin || currUpper != saved_xmax || (mode & AT_CREATION) == 0)) + { data.getDataAsync(currLower, currUpper, NUM_POINTS); + } } // fireSignalUpdated(); } diff --git a/java/jtraverser/src/main/java/mds/jtraverser/Node.java b/java/jtraverser/src/main/java/mds/jtraverser/Node.java index 3708e76433..1419c0c72e 100644 --- a/java/jtraverser/src/main/java/mds/jtraverser/Node.java +++ b/java/jtraverser/src/main/java/mds/jtraverser/Node.java @@ -461,9 +461,10 @@ public NodeInfo getInfo() throws MDSplus.MdsException cal.setTimeInMillis(time); final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"); final String dateStr = sdf.format(cal.getTime()); - return new NodeInfo(nid.getDclass(), nid.getDtype(), nid.getUsage(), nid.getNciFlags(), nid.getOwnerId(), - nid.getLength(), nid.getConglomerateNodes().size(), nid.getConglomerateElt(), dateStr, + NodeInfo info = new NodeInfo(nid.getDclass(), nid.getDtype(), nid.getUsage(), nid.getNciFlags(), nid.getOwnerId(), + nid.getLength(), nid.getNumElts(), nid.getConglomerateElt(), dateStr, nid.getNodeName(), nid.getFullPath(), nid.getMinPath(), nid.getPath(), nid.getNumSegments()); + return info; } public final int getLength() From 6b024897a54f992473062be8778f2810674486f5 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Fri, 14 May 2021 14:41:57 +0200 Subject: [PATCH 24/27] Build: fixed alpine externals, removed python dependency if numpy is required --- deploy/packaging/linux.xml | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/deploy/packaging/linux.xml b/deploy/packaging/linux.xml index 5d5b323a3b..31c3568b3d 100644 --- a/deploy/packaging/linux.xml +++ b/deploy/packaging/linux.xml @@ -778,7 +778,6 @@ rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - @@ -823,39 +822,33 @@ rm -f /etc/ld.so.conf.d/mdsplus.conf 2>/dev/null - - + - - + - - + - - - - + + - - + From 4d5dc4982c70270e09ccefbca94cc6767ba55ff2 Mon Sep 17 00:00:00 2001 From: GabrieleManduchi Date: Mon, 17 May 2021 10:28:46 +0200 Subject: [PATCH 25/27] Gm beans (#2312) * Feature:new Device Bean for MARTe2 Parameter list * Fix Help, Unis for TreeNode data * New support beans for MARTe2 Simulink devices * New device beans * New devices * rempve prints * Fix nid changes * Changed NIDs * Changed NIDs * Changed stream API * Avoid useless simulink initialization * other forms * Minor fixes * New Redpitaya ref_stream support * MARTE2_SIMULINK_RABBIT Ddevice * Delete data first and check trigger * new form * workaround find node failure * new devices added Co-authored-by: GabrieleManduchi Co-authored-by: mdsplus --- deploy/packaging/debian/htsdevices.noarch | 2 +- deploy/packaging/debian/python.noarch | 2 +- deploy/packaging/debian/rfxdevices.noarch | 2 + deploy/packaging/redhat/htsdevices.noarch | 2 +- deploy/packaging/redhat/python.noarch | 2 +- deploy/packaging/redhat/rfxdevices.noarch | 2 + .../redpitaya/AsyncStoreManager.cpp | 160 + device_support/redpitaya/AsyncStoreManager.h | 86 + device_support/redpitaya/Makefile | 4 +- device_support/redpitaya/redpitaya.cpp | 105 +- device_support/redpitaya/rfx_stream.h | 194 +- java/devicebeans/DeviceBeansManifest.mf | 6 + .../src/main/java/DeviceComponent.java | 6 +- .../src/main/java/DeviceInputs.java | 145 + .../src/main/java/DeviceInputsBeanInfo.java | 38 + .../src/main/java/DeviceInputsCustomizer.java | 82 + .../src/main/java/DeviceOutputs.java | 172 + .../src/main/java/DeviceOutputsBeanInfo.java | 38 + .../main/java/DeviceOutputsCustomizer.java | 82 + .../src/main/java/DeviceParameters.java | 82 + .../main/java/DeviceParametersBeanInfo.java | 40 + .../main/java/DeviceParametersCustomizer.java | 98 + .../src/main/java/MARTE2_CONVERSIONSetup.java | 81 +- .../src/main/java/MARTE2_EXPRSetup.java | 1428 ++-- .../src/main/java/MARTE2_FFTSetup.java | 190 +- .../src/main/java/MARTE2_GAMSetup.java | 3756 ++++++----- .../src/main/java/MARTE2_NI6259_DACSetup.java | 391 +- .../src/main/java/MARTE2_NI6259_DISetup.java | 149 +- .../src/main/java/MARTE2_NI6259_DOSetup.java | 198 +- .../main/java/MARTE2_PYTHON_GENERICSetup.java | 120 +- .../src/main/java/MARTE2_PYTHON_PIDSetup.java | 235 +- .../src/main/java/MARTE2_RESAMPLERSetup.java | 32 +- .../src/main/java/MARTE2_RTSMSetup.java | 30 +- .../java/MARTE2_SIMULINK_FLUXMAPSetup.java | 75 + .../java/MARTE2_SIMULINK_GENERICSetup.java | 131 +- .../java/MARTE2_SIMULINK_RABBITSetup.java | 76 + .../java/MARTE2_SIMULINK_RAPTORSetup.java | 4935 +------------- .../main/java/MARTE2_SIMULINK_TANKSetup.java | 10 +- .../src/main/java/MARTE2_SPIDER_CALSetup.java | 1574 +---- .../src/main/java/MARTE2_STREAM_INSetup.java | 442 +- .../src/main/java/MARTE2_SWTRIGSetup.java | 64 +- .../resources/MARTE2_CONVERSIONSetup.form | 101 +- .../src/main/resources/MARTE2_EXPRSetup.form | 108 +- .../src/main/resources/MARTE2_FFTSetup.form | 4 +- .../src/main/resources/MARTE2_GAMSetup.form | 2 +- .../main/resources/MARTE2_NI6259Setup.form | 2 +- .../resources/MARTE2_NI6259_DACSetup.form | 2 +- .../main/resources/MARTE2_NI6259_DISetup.form | 2 +- .../main/resources/MARTE2_NI6259_DOSetup.form | 2 +- .../resources/MARTE2_PYTHON_GENERICSetup.form | 120 +- .../resources/MARTE2_PYTHON_PIDSetup.form | 2 +- .../main/resources/MARTE2_RESAMPLERSetup.form | 32 +- .../src/main/resources/MARTE2_RTSMSetup.form | 30 +- .../MARTE2_SIMULINK_FLUXMAPSetup.form | 110 + .../MARTE2_SIMULINK_GENERICSetup.form | 120 +- .../MARTE2_SIMULINK_RABBITSetup.form | 111 + .../MARTE2_SIMULINK_RAPTORSetup.form | 5770 +---------------- .../resources/MARTE2_SIMULINK_TANKSetup.form | 10 +- .../main/resources/MARTE2_STREAM_INSetup.form | 32 +- .../main/resources/MARTE2_SWTRIGSetup.form | 66 +- .../main/java/mds/jdispatcher/jServer.java | 3 +- javamds/mdsobjects.c | 5 +- mdsmisc/ScopeUtilities.c | 2 +- pydevices/RfxDevices/MARTE2_COMPONENT.py | 171 +- pydevices/RfxDevices/MARTE2_SIMULINK.py | 28 +- .../RfxDevices/MARTE2_SIMULINK_FLUXMAP.py | 31 + .../RfxDevices/MARTE2_SIMULINK_RABBIT.py | 31 + pydevices/RfxDevices/RFX_RPADC.py | 15 +- 68 files changed, 6327 insertions(+), 15852 deletions(-) create mode 100644 device_support/redpitaya/AsyncStoreManager.cpp create mode 100644 device_support/redpitaya/AsyncStoreManager.h create mode 100644 java/devicebeans/src/main/java/DeviceInputs.java create mode 100644 java/devicebeans/src/main/java/DeviceInputsBeanInfo.java create mode 100644 java/devicebeans/src/main/java/DeviceInputsCustomizer.java create mode 100644 java/devicebeans/src/main/java/DeviceOutputs.java create mode 100644 java/devicebeans/src/main/java/DeviceOutputsBeanInfo.java create mode 100644 java/devicebeans/src/main/java/DeviceOutputsCustomizer.java create mode 100644 java/devicebeans/src/main/java/DeviceParameters.java create mode 100644 java/devicebeans/src/main/java/DeviceParametersBeanInfo.java create mode 100644 java/devicebeans/src/main/java/DeviceParametersCustomizer.java create mode 100644 java/jdevices/src/main/java/MARTE2_SIMULINK_FLUXMAPSetup.java create mode 100644 java/jdevices/src/main/java/MARTE2_SIMULINK_RABBITSetup.java create mode 100644 java/jdevices/src/main/resources/MARTE2_SIMULINK_FLUXMAPSetup.form create mode 100644 java/jdevices/src/main/resources/MARTE2_SIMULINK_RABBITSetup.form create mode 100644 pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py create mode 100644 pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py diff --git a/deploy/packaging/debian/htsdevices.noarch b/deploy/packaging/debian/htsdevices.noarch index 6d2df03f37..d27beb9c1e 100644 --- a/deploy/packaging/debian/htsdevices.noarch +++ b/deploy/packaging/debian/htsdevices.noarch @@ -1,8 +1,8 @@ ./usr/local/mdsplus/pydevices/HtsDevices/_version.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_423st.py +./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435sc.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435st.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_WRPG.py -./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435sc.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_WRTD.py ./usr/local/mdsplus/pydevices/HtsDevices/cryocon18i.py ./usr/local/mdsplus/pydevices/HtsDevices/cryocon24c.py diff --git a/deploy/packaging/debian/python.noarch b/deploy/packaging/debian/python.noarch index 54b5779491..0366910800 100644 --- a/deploy/packaging/debian/python.noarch +++ b/deploy/packaging/debian/python.noarch @@ -20,8 +20,8 @@ ./usr/local/mdsplus/python/MDSplus/tests/connection_case.py ./usr/local/mdsplus/python/MDSplus/tests/data_case.py ./usr/local/mdsplus/python/MDSplus/tests/dcl_case.py -./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices/TestDevice.py +./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/exception_case.py ./usr/local/mdsplus/python/MDSplus/tests/images/test.gif ./usr/local/mdsplus/python/MDSplus/tests/images/test.jpg diff --git a/deploy/packaging/debian/rfxdevices.noarch b/deploy/packaging/debian/rfxdevices.noarch index 00e21f1a95..69486b3fed 100644 --- a/deploy/packaging/debian/rfxdevices.noarch +++ b/deploy/packaging/debian/rfxdevices.noarch @@ -52,9 +52,11 @@ ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_RFXMODEL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_RTSM.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_GENERIC.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_LEV_CTRLR.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_MAGNET.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_RAPTOR.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_TANK.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SPIDER_CAL.py diff --git a/deploy/packaging/redhat/htsdevices.noarch b/deploy/packaging/redhat/htsdevices.noarch index 4841cfa2da..8009e7e3b9 100644 --- a/deploy/packaging/redhat/htsdevices.noarch +++ b/deploy/packaging/redhat/htsdevices.noarch @@ -1,9 +1,9 @@ ./usr/local/mdsplus/pydevices/HtsDevices ./usr/local/mdsplus/pydevices/HtsDevices/_version.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_423st.py +./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435sc.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435st.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_WRPG.py -./usr/local/mdsplus/pydevices/HtsDevices/acq2106_435sc.py ./usr/local/mdsplus/pydevices/HtsDevices/acq2106_WRTD.py ./usr/local/mdsplus/pydevices/HtsDevices/cryocon18i.py ./usr/local/mdsplus/pydevices/HtsDevices/cryocon24c.py diff --git a/deploy/packaging/redhat/python.noarch b/deploy/packaging/redhat/python.noarch index fdb78b2d6a..078a82b4d2 100644 --- a/deploy/packaging/redhat/python.noarch +++ b/deploy/packaging/redhat/python.noarch @@ -23,8 +23,8 @@ ./usr/local/mdsplus/python/MDSplus/tests/data_case.py ./usr/local/mdsplus/python/MDSplus/tests/dcl_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices -./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/devices/TestDevice.py +./usr/local/mdsplus/python/MDSplus/tests/devices_case.py ./usr/local/mdsplus/python/MDSplus/tests/exception_case.py ./usr/local/mdsplus/python/MDSplus/tests/images ./usr/local/mdsplus/python/MDSplus/tests/images/test.gif diff --git a/deploy/packaging/redhat/rfxdevices.noarch b/deploy/packaging/redhat/rfxdevices.noarch index e7b3aafc34..c96775bf77 100644 --- a/deploy/packaging/redhat/rfxdevices.noarch +++ b/deploy/packaging/redhat/rfxdevices.noarch @@ -53,9 +53,11 @@ ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_RFXMODEL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_RTSM.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_GENERIC.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_LEV_CTRLR.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_MAGNET.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_RAPTOR.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SIMULINK_TANK.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE2_SPIDER_CAL.py diff --git a/device_support/redpitaya/AsyncStoreManager.cpp b/device_support/redpitaya/AsyncStoreManager.cpp new file mode 100644 index 0000000000..c4274cf1b5 --- /dev/null +++ b/device_support/redpitaya/AsyncStoreManager.cpp @@ -0,0 +1,160 @@ +#include "AsyncStoreManager.h" + +pthread_mutex_t globalMutex = PTHREAD_MUTEX_INITIALIZER; +pthread_mutex_t segmentMutex = PTHREAD_MUTEX_INITIALIZER; + + +SaveItem::SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode) +{ + this->buffer = buffer; + this->segmentSamples = segmentSamples; + this->dataNode = dataNode; + this->triggerTime = triggerTime; + this->treePtr = (MDSplus::Tree *)treePtr; + this->blocksInSegment = blocksInSegment; + this->startTimes = new double[blocksInSegment]; + this->endTimes = new double[blocksInSegment]; + for(int i = 0; i < blocksInSegment; i++) + { + this->startTimes[i] = startTimes[i]; + this->endTimes[i] = endTimes[i]; + } + this->freq = freq; + this->resampledNode = resampledNode; + nxt = 0; +} + + +void SaveItem::save() +{ + MDSplus::Array *chanData = + new MDSplus::Int16Array(buffer, segmentSamples); + + MDSplus::Data *timebase; + MDSplus::Data *startTimeData; + MDSplus::Data *endTimeData; + MDSplus::Data *deltaData = new MDSplus::Float64(1. / freq); + if (blocksInSegment == 1) + { + startTimeData = new MDSplus::Float64(startTimes[0]); + endTimeData = new MDSplus::Float64(endTimes[0]); + } + else + { + startTimeData = new MDSplus::Float64Array(startTimes, blocksInSegment); + endTimeData = new MDSplus::Float64Array(endTimes, blocksInSegment); + } + timebase = MDSplus::compileWithArgs( + "make_range($1+$2, $3+$4-$5/2., $6)", treePtr, 6, startTimeData, triggerTime, + endTimeData, triggerTime, deltaData, deltaData); + deleteData(startTimeData); + deleteData(endTimeData); + deleteData(deltaData); + + MDSplus::Data *startData = new MDSplus::Float64(startTimes[0]); + MDSplus::Data *endData = new MDSplus::Float64(endTimes[blocksInSegment - 1]); + MDSplus::Data *startSegData = + MDSplus::compileWithArgs("$1+$2", treePtr, 2, startData, triggerTime); + MDSplus::Data *endSegData = + MDSplus::compileWithArgs("$1+$2", treePtr, 2, endData, triggerTime); + try + { + std::cout << "MAKE SEGMENT SAMPLES:"<< segmentSamples << std::endl; + dataNode->makeSegment(startSegData, endSegData, timebase, chanData); + } + catch (MDSplus::MdsException &exc) + { + std::cout << "Error writing segment: " << exc.what() << std::endl; + } + MDSplus::deleteData(chanData); + MDSplus::deleteData(timebase); + MDSplus::deleteData(startData); + MDSplus::deleteData(endData); + MDSplus::deleteData(startSegData); + MDSplus::deleteData(endSegData); + delete[] buffer; + delete [] startTimes; + delete [] endTimes; +} + +SaveList::SaveList() +{ + int status = pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&itemAvailable, NULL); + saveHead = saveTail = NULL; + stopReq = false; + threadCreated = false; +} + +void SaveList::addItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode) + +{ + SaveItem *newItem = new SaveItem( + buffer, segmentSamples, dataNode, triggerTime, treePtr, startTimes, endTimes, freq, blocksInSegment, resampledNode); + pthread_mutex_lock(&mutex); + + if (saveHead == NULL) + saveHead = saveTail = newItem; + else + { + saveTail->setNext(newItem); + saveTail = newItem; + } + pthread_cond_signal(&itemAvailable); + pthread_mutex_unlock(&mutex); +} +void SaveList::executeItems() +{ + while (true) + { + pthread_mutex_lock(&mutex); + if (stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + + while (saveHead == NULL) + { + pthread_cond_wait(&itemAvailable, &mutex); + if (stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + } + SaveItem *currItem = saveHead; + saveHead = saveHead->getNext(); + pthread_mutex_unlock(&mutex); + currItem->save(); + delete currItem; + } +} +void SaveList::start() +{ + pthread_create(&thread, NULL, handleSave, (void *)this); + threadCreated = true; +} +void SaveList::stop() +{ + stopReq = true; + pthread_cond_signal(&itemAvailable); + if (threadCreated) + { + pthread_join(thread, NULL); + printf("SAVE THREAD TERMINATED\n"); + } +} + +void *handleSave(void *listPtr) +{ + SaveList *list = (SaveList *)listPtr; + list->executeItems(); + return NULL; +} diff --git a/device_support/redpitaya/AsyncStoreManager.h b/device_support/redpitaya/AsyncStoreManager.h new file mode 100644 index 0000000000..529912d3ee --- /dev/null +++ b/device_support/redpitaya/AsyncStoreManager.h @@ -0,0 +1,86 @@ +#ifndef ASYNC_STORE_MANAGER +#define ASYNC_STORE_MANAGER + +#define SHORT 1 +#define FLOAT 2 + +#include +#include +#include +#include +#include +#include +#include + +class SaveItem +{ + +private: + short *buffer; + int segmentSamples; + MDSplus::Tree *treePtr; + SaveItem *nxt; + MDSplus::Data *triggerTime; + MDSplus::TreeNode *dataNode; + MDSplus::TreeNode *resampledNode; + double *startTimes, *endTimes; + double freq; + int blocksInSegment; + +public: + + SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode = NULL); + + void setNext(SaveItem *itm) { nxt = itm; } + SaveItem *getNext() { return nxt; } + + MDSplus::Tree *getTree() { return (MDSplus::Tree *)treePtr; } + void save(); +}; + +class SaveList +{ +public: + pthread_cond_t itemAvailable; + pthread_t thread; + bool threadCreated; + SaveItem *saveHead, *saveTail; + bool stopReq; + pthread_mutex_t mutex; + +private: + int getQueueLen() + { + pthread_mutex_lock(&mutex); + int len = 0; + SaveItem *currItem = saveHead; + while (currItem) + { + len++; + currItem = currItem->getNext(); + } + pthread_mutex_unlock(&mutex); + return len; + } + +public: + SaveList(); + + void addItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode = NULL); + + void executeItems(); + void start(); + void stop(); +}; + +extern "C" void *handleSave(void *listPtr); +extern "C" void startSave(void **retList); +extern "C" void stopSave(void *listPtr); + +#endif diff --git a/device_support/redpitaya/Makefile b/device_support/redpitaya/Makefile index 75f1c8dee0..4b6e68d0e9 100755 --- a/device_support/redpitaya/Makefile +++ b/device_support/redpitaya/Makefile @@ -1,11 +1,11 @@ CC=g++ -CFLAGS = -fPIC -o2 -Wall -DLINUX -I${MDSPLUS_DIR}/include -I. +CFLAGS = -fPIC -std=c++11 -o2 -Wall -DLINUX -I${MDSPLUS_DIR}/include -I. LDFLAGS = -L${MDSPLUS_DIR}/lib -lpthread -lMdsObjectsCppShr -SOURCES=redpitaya.cpp +SOURCES=redpitaya.cpp AsyncStoreManager.cpp OBJECTS=$(SOURCES:.cpp=.o) SHAREDLIB=libredpitaya.so EXE=test diff --git a/device_support/redpitaya/redpitaya.cpp b/device_support/redpitaya/redpitaya.cpp index 8fea10f673..522ab8287b 100644 --- a/device_support/redpitaya/redpitaya.cpp +++ b/device_support/redpitaya/redpitaya.cpp @@ -7,6 +7,8 @@ #include #include #include +#include + extern "C" { @@ -104,6 +106,9 @@ static void writeConfig(int fd, struct rpadc_configuration *config) // Decimator IP seems not to work properly is decimation set the firsttime to // 1 regs.decimator_register = 10; + + regs.lev_trig_count = 1; // set first count higher than init in VHDL + ioctl(fd, RFX_STREAM_SET_REGISTERS, ®s); usleep(10000); @@ -220,8 +225,8 @@ static void adcTrigger(int fd) command = 0; ioctl(fd, RFX_STREAM_SET_COMMAND_REGISTER, &command); - // ioctl(fd, RFX_STREAM_GET_DATA_FIFO_LEN, &command); - + ioctl(fd, RFX_STREAM_GET_DRIVER_BUFLEN, &command); + std::cout<<"DATA FIFO LEN: " << command << std::endl; // ioctl(fd, RFX_STREAM_GET_DATA_FIFO_VAL, &command); // ioctl(fd, RFX_STREAM_GET_TIME_FIFO_LEN, &command); // ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &command); @@ -254,11 +259,12 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, MDSplus::TreeNode *chan2, MDSplus::Data *triggerTime, unsigned int *dataSamples, double *startTimes, double *endTimes, int segmentSamples, - int blocksInSegment, double freq) + int blocksInSegment, double freq, SaveList *saveList) { - +std::cout << "WRITE SEGMENT " << segmentSamples; +if(segmentSamples == 0) return; short *chan1Samples, *chan2Samples; - std::cout << "WRITE SEGMENT SAMPLES: " << segmentSamples << std::endl; + //std::cout << "WRITE SEGMENT SAMPLES: " << segmentSamples << std::endl; chan1Samples = new short[segmentSamples]; chan2Samples = new short[segmentSamples]; @@ -267,60 +273,12 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, chan1Samples[i] = dataSamples[i] & 0x0000ffff; chan2Samples[i] = (dataSamples[i] >> 16) & 0x0000ffff; } + + saveList->addItem(chan1Samples, segmentSamples, chan1, triggerTime, t, + startTimes, endTimes, freq, blocksInSegment); - MDSplus::Array *chan1Data = - new MDSplus::Int16Array(chan1Samples, segmentSamples); - MDSplus::Array *chan2Data = - new MDSplus::Int16Array(chan2Samples, segmentSamples); - - MDSplus::Data *timebase; - - MDSplus::Data *startTimeData; - MDSplus::Data *endTimeData; - MDSplus::Data *deltaData = new MDSplus::Float64(1 / freq); - if (blocksInSegment == 1) - { - startTimeData = new MDSplus::Float64(startTimes[0]); - endTimeData = new MDSplus::Float64(endTimes[0]); - } - else - { - startTimeData = new MDSplus::Float64Array(startTimes, blocksInSegment); - endTimeData = new MDSplus::Float64Array(endTimes, blocksInSegment); - } - timebase = MDSplus::compileWithArgs( - "make_range($1+$2, $3+$4-$5/2., $6)", t, 6, startTimeData, triggerTime, - endTimeData, triggerTime, deltaData, deltaData); - deleteData(startTimeData); - deleteData(endTimeData); - deleteData(deltaData); - - MDSplus::Data *startData = new MDSplus::Float64(startTimes[0]); - MDSplus::Data *endData = new MDSplus::Float64(endTimes[blocksInSegment - 1]); - MDSplus::Data *startSegData = - MDSplus::compileWithArgs("$1+$2", t, 2, startData, triggerTime); - MDSplus::Data *endSegData = - MDSplus::compileWithArgs("$1+$2", t, 2, endData, triggerTime); - try - { - // std::cout << "MAKE SEGMENT "<< chan1 << chan1Data << std::endl; - chan1->makeSegment(startSegData, endSegData, timebase, chan1Data); - chan2->makeSegment(startSegData, endSegData, timebase, chan2Data); - } - catch (MDSplus::MdsException &exc) - { - std::cout << "Error writing segment: " << exc.what() << std::endl; - } - MDSplus::deleteData(chan1Data); - MDSplus::deleteData(chan2Data); - MDSplus::deleteData(timebase); - MDSplus::deleteData(startData); - MDSplus::deleteData(endData); - MDSplus::deleteData(startSegData); - MDSplus::deleteData(endSegData); - delete[] chan1Samples; - delete[] chan2Samples; - // std::cout << "WRITESEGMENT END" << std::endl; + saveList->addItem(chan2Samples, segmentSamples, chan2, triggerTime, t, + startTimes, endTimes, freq, blocksInSegment); } // Stop void rpadcStop(int fd) @@ -329,6 +287,7 @@ void rpadcStop(int fd) usleep(100000); fifoFlush(fd); stopped = true; + std::cout << "TIRATO SU STOP\n"; usleep(100000); usleep(100000); // dmaStop(fd); @@ -336,7 +295,9 @@ void rpadcStop(int fd) usleep(100000); stopRead(fd); usleep(100000); + std::cout << "CLOSE "; close(fd); + std::cout << "CLOSED\n"; } void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, @@ -351,6 +312,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, double *startTimes, *endTimes; unsigned long long prevTime = 0; stopped = false; + unsigned int trig_lev_count = 0; MDSplus::Tree *tree = new MDSplus::Tree(treeName, shot); MDSplus::TreeNode *chan1 = new MDSplus::TreeNode(chan1Nid, tree); MDSplus::TreeNode *chan2 = new MDSplus::TreeNode(chan2Nid, tree); @@ -404,6 +366,13 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, usleep(1000); int segmentIdx = 0; prevTime = 0; + SaveList *saveList = new SaveList; + saveList->start(); + // START WITH A INITIAL VALUE FOR TRIG_LEV_COUNT + ioctl(fd, RFX_STREAM_GET_LEV_TRIG_COUNT, &trig_lev_count); + trig_lev_count++; + ioctl(fd, RFX_STREAM_SET_LEV_TRIG_COUNT, &trig_lev_count); + while (true) { for (int currBlock = 0; currBlock < blocksInSegment; currBlock++) @@ -413,7 +382,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, { int rb = read(fd, &dataSamples[currBlock * blockSamples + currSample], (blockSamples - currSample) * sizeof(int)); - +//std::cout << "READ " << rb << std::endl; currSample += rb / sizeof(int); if (stopped) // May happen when block readout has terminated or in the @@ -444,16 +413,18 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, ((segmentIdx + 1) * segmentSamples - preSamples) / freq1; writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, - currBlock * blockSamples + currSample, 1, freq1); + currBlock * blockSamples + currSample, 1, freq1, saveList); } else // Some data for new window have been read { + std::cout << "MULTIPLE 1\n"; unsigned long long currTime; unsigned int time1, time2; ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &time1); ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &time2); currTime = (unsigned long long)time1 | (((unsigned long long)time2) << 32); + std::cout << "MULTIPLE 2 "<< currBlock << std::endl; startTimes[currBlock] = (currTime - preSamples) / freq; endTimes[currBlock] = (currTime + postSamples - 1) / freq; // include last sample @@ -462,7 +433,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, currBlock * blockSamples + currSample, - currBlock + 1, freq1); + currBlock + 1, freq1, saveList); } } else // Some windows have been read before and the segment is @@ -470,7 +441,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, { writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, currBlock * blockSamples + currSample, - currBlock, freq1); + currBlock, freq1, saveList); } } // adcStop(fd); @@ -479,6 +450,9 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, // usleep(100000); // close(fd); deviceFd = 0; + std::cout << "CHIAMO STOP\n"; + saveList->stop(); + std::cout << "CHIAMATO\n"; delete chan1; delete chan2; delete trigger; @@ -490,6 +464,10 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, return; } } + // signal to FPGA that block has been read + ioctl(fd, RFX_STREAM_GET_LEV_TRIG_COUNT, &trig_lev_count); + trig_lev_count++; + ioctl(fd, RFX_STREAM_SET_LEV_TRIG_COUNT, &trig_lev_count); // Here the block been filled. It may refer to the same window // (isSingle)or to a different time window if (preSamples != 0 || postSamples != 0) // not continuous @@ -531,8 +509,9 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, segmentIdx++; writeSegment(tree, chan1, chan2, trigger, dataSamples, startTimes, endTimes, - segmentSamples, blocksInSegment, freq1); + segmentSamples, blocksInSegment, freq1, saveList); } + std::cout << "ULTIMAO RPADCSTREAM\n"; } static void printConfig(struct rpadc_configuration *config) { diff --git a/device_support/redpitaya/rfx_stream.h b/device_support/redpitaya/rfx_stream.h index bd1a71997a..2df3cf6f4b 100644 --- a/device_support/redpitaya/rfx_stream.h +++ b/device_support/redpitaya/rfx_stream.h @@ -1,91 +1,95 @@ #ifndef RFX_STREAM_H #define RFX_STREAM_H -#include + #include +#include + + #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif -// Temporaneo +//Temporaneo #define DMA_SOURCE 1 - //////////////// +//////////////// + -#define DEVICE_NAME "rfx_stream" /* Dev name as it appears in /proc/devices */ +#define DEVICE_NAME "rfx_stream" /* Dev name as it appears in /proc/devices */ #define MODULE_NAME "rfx_stream" - // Generic IOCTL commands - -#define RFX_STREAM_IOCTL_BASE 'W' -#define RFX_STREAM_ARM_DMA _IO(RFX_STREAM_IOCTL_BASE, 1) -#define RFX_STREAM_START_DMA _IO(RFX_STREAM_IOCTL_BASE, 2) -#define RFX_STREAM_STOP_DMA _IO(RFX_STREAM_IOCTL_BASE, 3) -#define RFX_STREAM_SET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 4) -#define RFX_STREAM_GET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 5) -#define RFX_STREAM_IS_DMA_RUNNING _IO(RFX_STREAM_IOCTL_BASE, 6) -#define RFX_STREAM_GET_DMA_DATA _IO(RFX_STREAM_IOCTL_BASE, 7) -#define RFX_STREAM_SET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 8) -#define RFX_STREAM_GET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 9) -#define RFX_STREAM_GET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 10) -#define RFX_STREAM_SET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 11) -#define RFX_STREAM_FIFO_INT_HALF_SIZE _IO(RFX_STREAM_IOCTL_BASE, 12) -#define RFX_STREAM_FIFO_INT_FIRST_SAMPLE _IO(RFX_STREAM_IOCTL_BASE, 13) -#define RFX_STREAM_FIFO_FLUSH _IO(RFX_STREAM_IOCTL_BASE, 14) -#define RFX_STREAM_START_READ _IO(RFX_STREAM_IOCTL_BASE, 15) -#define RFX_STREAM_STOP_READ _IO(RFX_STREAM_IOCTL_BASE, 16) -#define RFX_STREAM_GET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 20) -#define RFX_STREAM_SET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 21) -#define RFX_STREAM_GET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 22) -#define RFX_STREAM_SET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 23) -#define RFX_STREAM_GET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 24) -#define RFX_STREAM_SET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 25) -#define RFX_STREAM_GET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 26) -#define RFX_STREAM_SET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 27) -#define RFX_STREAM_GET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 28) -#define RFX_STREAM_SET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 29) -#define RFX_STREAM_GET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 30) -#define RFX_STREAM_SET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 31) -#define RFX_STREAM_GET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 32) -#define RFX_STREAM_SET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 33) -#define RFX_STREAM_GET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 34) -#define RFX_STREAM_SET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 35) -#define RFX_STREAM_GET_DATA_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 36) -#define RFX_STREAM_GET_DATA_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 37) -#define RFX_STREAM_CLEAR_DATA_FIFO _IO(RFX_STREAM_IOCTL_BASE, 38) -#define RFX_STREAM_GET_TIME_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 39) -#define RFX_STREAM_GET_TIME_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 40) -#define RFX_STREAM_CLEAR_TIME_FIFO _IO(RFX_STREAM_IOCTL_BASE, 41) +//Generic IOCTL commands + +#define RFX_STREAM_IOCTL_BASE 'W' +#define RFX_STREAM_ARM_DMA _IO(RFX_STREAM_IOCTL_BASE, 1) +#define RFX_STREAM_START_DMA _IO(RFX_STREAM_IOCTL_BASE, 2) +#define RFX_STREAM_STOP_DMA _IO(RFX_STREAM_IOCTL_BASE, 3) +#define RFX_STREAM_SET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 4) +#define RFX_STREAM_GET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 5) +#define RFX_STREAM_IS_DMA_RUNNING _IO(RFX_STREAM_IOCTL_BASE, 6) +#define RFX_STREAM_GET_DMA_DATA _IO(RFX_STREAM_IOCTL_BASE, 7) +#define RFX_STREAM_SET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 8) +#define RFX_STREAM_GET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 9) +#define RFX_STREAM_GET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 10) +#define RFX_STREAM_SET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 11) +#define RFX_STREAM_FIFO_INT_HALF_SIZE _IO(RFX_STREAM_IOCTL_BASE, 12) +#define RFX_STREAM_FIFO_INT_FIRST_SAMPLE _IO(RFX_STREAM_IOCTL_BASE, 13) +#define RFX_STREAM_FIFO_FLUSH _IO(RFX_STREAM_IOCTL_BASE, 14) +#define RFX_STREAM_START_READ _IO(RFX_STREAM_IOCTL_BASE, 15) +#define RFX_STREAM_STOP_READ _IO(RFX_STREAM_IOCTL_BASE, 16) +#define RFX_STREAM_GET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 20) +#define RFX_STREAM_SET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 21) +#define RFX_STREAM_GET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 22) +#define RFX_STREAM_SET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 23) +#define RFX_STREAM_GET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 24) +#define RFX_STREAM_SET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 25) +#define RFX_STREAM_GET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 26) +#define RFX_STREAM_SET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 27) +#define RFX_STREAM_GET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 28) +#define RFX_STREAM_SET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 29) +#define RFX_STREAM_GET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 30) +#define RFX_STREAM_SET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 31) +#define RFX_STREAM_GET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 32) +#define RFX_STREAM_SET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 33) +#define RFX_STREAM_GET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 34) +#define RFX_STREAM_SET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 35) +#define RFX_STREAM_GET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 36) +#define RFX_STREAM_SET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 37) +#define RFX_STREAM_GET_DATA_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 38) +#define RFX_STREAM_GET_DATA_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 39) +#define RFX_STREAM_CLEAR_DATA_FIFO _IO(RFX_STREAM_IOCTL_BASE, 40) +#define RFX_STREAM_GET_TIME_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 41) +#define RFX_STREAM_GET_TIME_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 42) +#define RFX_STREAM_CLEAR_TIME_FIFO _IO(RFX_STREAM_IOCTL_BASE, 43) + #ifndef AXI_ENUMS_DEFINED #define AXI_ENUMS_DEFINED - enum AxiStreamFifo_Register - { - ISR = 0x00, ///< Interrupt Status Register (ISR) - IER = 0x04, ///< Interrupt Enable Register (IER) - TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) - TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) - TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port +enum AxiStreamFifo_Register { + ISR = 0x00, ///< Interrupt Status Register (ISR) + IER = 0x04, ///< Interrupt Enable Register (IER) + TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) + TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) + TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port TDFD4 = 0x1000, ///< Transmit Data FIFO for AXI4 Data Write Port - TLR = 0x14, ///< Transmit Length Register (TLR) - RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) - RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) - RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) + TLR = 0x14, ///< Transmit Length Register (TLR) + RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) + RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) + RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) RDFD4 = 0x1000, ///< Receive Data FIFO for AXI4 Data Read Port (RDFD) - RLR = 0x24, ///< Receive Length Register (RLR) - SRR = 0x28, ///< AXI4-Stream Reset (SRR) - TDR = 0x2c, ///< Transmit Destination Register (TDR) - RDR = 0x30, ///< Receive Destination Register (RDR) + RLR = 0x24, ///< Receive Length Register (RLR) + SRR = 0x28, ///< AXI4-Stream Reset (SRR) + TDR = 0x2c, ///< Transmit Destination Register (TDR) + RDR = 0x30, ///< Receive Destination Register (RDR) /// not supported yet .. /// - TID = 0x34, ///< Transmit ID Register - TUSER = 0x38, ///< Transmit USER Register - RID = 0x3c, ///< Receive ID Register - RUSER = 0x40 ///< Receive USER Register - }; - - enum AxiStreamFifo_ISREnum - { + TID = 0x34, ///< Transmit ID Register + TUSER = 0x38, ///< Transmit USER Register + RID = 0x3c, ///< Receive ID Register + RUSER = 0x40 ///< Receive USER Register +}; + +enum AxiStreamFifo_ISREnum { ISR_RFPE = 1 << 19, ///< Receive FIFO Programmable Empty ISR_RFPF = 1 << 20, ///< Receive FIFO Programmable Full ISR_TFPE = 1 << 21, ///< Transmit FIFO Programmable Empty @@ -99,10 +103,9 @@ extern "C" ISR_RPUE = 1 << 29, ///< Receive Packet Underrun Error ISR_RPORE = 1 << 30, ///< Receive Packet Overrun Read Error ISR_RPURE = 1 << 31, ///< Receive Packet Underrun Read Error - }; +}; - enum RegisterIdx - { +enum RegisterIdx { FIFO_00_IDX = 0, FIFO_01_IDX = 1, FIFO_10_IDX = 2, @@ -111,30 +114,35 @@ extern "C" PRE_POST_REG_IDX = 5, DEC_REG_IDX = 6, MODE_REG_IDX = 8 - }; +}; #endif #pragma pack(1) - struct rfx_stream_registers - { - char command_register_enable; - unsigned int command_register; - char decimator_register_enable; - unsigned int decimator_register; - char mode_register_enable; - unsigned int mode_register; - char packetizer_enable; - unsigned int packetizer; - char post_register_enable; - unsigned int post_register; - char pre_register_enable; - unsigned int pre_register; - char trig_event_code_enable; - unsigned int trig_event_code; - char event_code_enable; - unsigned int event_code; - }; +struct rfx_stream_registers +{ + char command_register_enable; + unsigned int command_register; + char decimator_register_enable; + unsigned int decimator_register; + char lev_trig_count_enable; + unsigned int lev_trig_count; + char mode_register_enable; + unsigned int mode_register; + char packetizer_enable; + unsigned int packetizer; + char post_register_enable; + unsigned int post_register; + char pre_register_enable; + unsigned int pre_register; + char trig_event_code_enable; + unsigned int trig_event_code; + char event_code_enable; + unsigned int event_code; + +}; + + #ifdef __cplusplus } diff --git a/java/devicebeans/DeviceBeansManifest.mf b/java/devicebeans/DeviceBeansManifest.mf index b928accf0f..b461728a66 100644 --- a/java/devicebeans/DeviceBeansManifest.mf +++ b/java/devicebeans/DeviceBeansManifest.mf @@ -33,6 +33,12 @@ Java-Bean: True Name: DeviceParameters.class Java-Bean: True +Name: DeviceInputs.class +Java-Bean: True + +Name: DeviceOutputs.class +Java-Bean: True + Name: DeviceWaveParameters.class Java-Bean: True diff --git a/java/devicebeans/src/main/java/DeviceComponent.java b/java/devicebeans/src/main/java/DeviceComponent.java index ee2787aa12..d7585068fd 100644 --- a/java/devicebeans/src/main/java/DeviceComponent.java +++ b/java/devicebeans/src/main/java/DeviceComponent.java @@ -10,11 +10,11 @@ public abstract class DeviceComponent extends JPanel * */ private static final long serialVersionUID = 1L; - public static final int DATA = 0, STATE = 1, DISPATCH = 2; + public static final int DATA = 0, STATE = 1, DISPATCH = 2, STRUCTURE = 3; Interface subtree; public int mode = DATA; public int baseNid = 0, offsetNid = 0; - protected String curr_data, init_data; + protected String curr_data = null, init_data; protected boolean curr_on, init_on; protected int nidData; protected int baseNidData; @@ -53,6 +53,7 @@ public void apply() throws Exception throw e; } } + checkRefShot(); } if (mode != DISPATCH && supportsState()) { @@ -66,7 +67,6 @@ public void apply() throws Exception System.out.println("Error writing device state: " + e); } } - checkRefShot(); } public void apply(int currBaseNid) throws Exception diff --git a/java/devicebeans/src/main/java/DeviceInputs.java b/java/devicebeans/src/main/java/DeviceInputs.java new file mode 100644 index 0000000000..ecd2b51385 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceInputs.java @@ -0,0 +1,145 @@ +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +import javax.swing.*; +import javax.swing.border.LineBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class DeviceInputs extends DeviceComponent +{ + + private JScrollPane scrollP; + private int numInputs; + private JTextField valuesTF[], fieldsTF[][]; + private JLabel labels[]; + int numParameters[], numFields[]; + private int numInputChildren = 0; + public DeviceInputs() + { + } + @Override + protected void initializeData(String data, boolean is_on) + { + mode = STRUCTURE; + int currNid = baseNid + offsetNid; + try { + numInputs = subtree.getInt("GETNCI("+subtree.getFullPath(currNid)+",\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc){numInputs = 0;} + valuesTF = new JTextField[numInputs]; + labels = new JLabel[numInputs]; + fieldsTF = new JTextField[numInputs][]; + numParameters = new int[numInputs]; + numFields = new int[numInputs]; + JPanel jp = new JPanel(); + jp.setLayout(new GridLayout(numInputs, 1)); + int currInputNid = currNid + 1; + try { + int children = subtree.getInt("GETNCI("+subtree.getFullPath(currInputNid)+",\'NUMBER_OF_CHILDREN\')"); + int members = subtree.getInt("GETNCI("+subtree.getFullPath(currInputNid)+",\'NUMBER_OF_MEMBERS\')"); + numInputChildren = children + members; + }catch(Exception exc) + { + System.out.println("Error getting number of input children"); + } + for(int i = 0; i < numInputs; i++) + { + try { + numParameters[i] = subtree.getInt("GETNCI("+subtree.getFullPath(currInputNid+6)+",\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + numParameters[i] = 0; + } + if(numInputChildren == 6) //Old version without fields + numFields[i] = 0; + else + { + try { + numFields[i] = subtree.getInt("GETNCI("+subtree.getFullPath(currInputNid+7+numParameters[i])+",\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + numFields[i] = 0; + } + } + fieldsTF[i] = new JTextField[numFields[i]]; + String inputName; + try { + inputName = subtree.getString(subtree.getDataExpr(currInputNid + 5)); + }catch(Exception exc) + { + inputName = ""; + } + JPanel jp1 = new JPanel(); + jp1.setBorder(new TitledBorder(inputName)); + jp1.setLayout(new GridLayout(1 + numFields[i],1)); + JPanel jp2 = new JPanel(); + jp2.setLayout(new BorderLayout()); + jp2.add(valuesTF[i] = new JTextField(), "Center"); + jp1.add(jp2); + for (int fieldIdx = 0; fieldIdx < numFields[i]; fieldIdx++) + { + String fieldName; + try { + fieldName = subtree.getString(subtree.getDataExpr(currInputNid + 8 + 2 * numParameters[i] + 6 * fieldIdx + 4)); + }catch(Exception exc) + { + fieldName = ""; + } + jp2 = new JPanel(); + jp2.setLayout(new BorderLayout()); + jp2.setBorder(new TitledBorder(inputName+"."+fieldName)); + jp2.add(fieldsTF[i][fieldIdx] = new JTextField(), "Center"); + jp1.add(jp2); + } + currInputNid += numInputChildren + 1 + 2 * numParameters[i] + 6 * numFields[i]; + jp.add(jp1); + } + scrollP = new JScrollPane(jp); + setLayout(new BorderLayout()); + add(scrollP, "Center"); + displayData(data, is_on); + } + protected void displayData(String data, boolean is_on) + { + int currInputNid = baseNid + offsetNid + 1; + for(int inputIdx = 0; inputIdx < numInputs; inputIdx++) + { + try { + valuesTF[inputIdx].setText(subtree.getDataExpr(currInputNid + 4)); + }catch(Exception exc) + { + valuesTF[inputIdx].setText(""); + } + for(int fieldIdx = 0; fieldIdx < numFields[inputIdx]; fieldIdx++) + { + try { + fieldsTF[inputIdx][fieldIdx].setText(subtree.getDataExpr(currInputNid + 8 + 2 * numParameters[inputIdx] + 6 * fieldIdx + 5)); + }catch(Exception exc){fieldsTF[inputIdx][fieldIdx].setText("");} + } + currInputNid += numInputChildren + 1 + 2 * numParameters[inputIdx] + 6 * numFields[inputIdx]; + } + } + + protected String getData() {return null;} + protected boolean getState(){return true;} + + public void apply() throws Exception + { + int currInputNid = baseNid + offsetNid + 1; + for(int inputIdx = 0; inputIdx < numInputs; inputIdx++) + { + try { + subtree.putDataExpr(currInputNid + 4, valuesTF[inputIdx].getText()); + }catch(Exception exc){} + for(int fieldIdx = 0; fieldIdx < numFields[inputIdx]; fieldIdx++) + { + try { + subtree.putDataExpr(currInputNid + 8 + 2 * numParameters[inputIdx] + 6 * fieldIdx + 5, fieldsTF[inputIdx][fieldIdx].getText()); + }catch(Exception exc){} + } + currInputNid += numInputChildren + 1 + 2 * numParameters[inputIdx] + 6 * numFields[inputIdx]; + } + } +} diff --git a/java/devicebeans/src/main/java/DeviceInputsBeanInfo.java b/java/devicebeans/src/main/java/DeviceInputsBeanInfo.java new file mode 100644 index 0000000000..843f357c90 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceInputsBeanInfo.java @@ -0,0 +1,38 @@ +import java.beans.*; +import java.awt.*; + +public class DeviceInputsBeanInfo extends SimpleBeanInfo +{ + @Override + public BeanDescriptor getBeanDescriptor() + { return new BeanDescriptor(DeviceInputs.class, DeviceInputsCustomizer.class); } + + @Override + public Image getIcon(int kind) + { + return loadImage("DeviceChannel.gif"); + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors() + { + try + { + final PropertyDescriptor[] props = + { property("offsetNid", "Offset nid")}; + return props; + } + catch (final IntrospectionException e) + { + System.out.println("DeviceInputs: property exception " + e); + return super.getPropertyDescriptors(); + } + } + + public PropertyDescriptor property(String name, String description) throws IntrospectionException + { + final PropertyDescriptor p = new PropertyDescriptor(name, DeviceInputs.class); + p.setShortDescription(description); + return p; + } +} diff --git a/java/devicebeans/src/main/java/DeviceInputsCustomizer.java b/java/devicebeans/src/main/java/DeviceInputsCustomizer.java new file mode 100644 index 0000000000..60e5598d7d --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceInputsCustomizer.java @@ -0,0 +1,82 @@ +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.beans.Customizer; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; + +public class DeviceInputsCustomizer extends DeviceCustomizer implements Customizer +{ + /** + * + */ + private static final long serialVersionUID = 1L; + DeviceInputs bean = null; + Object obj; + PropertyChangeSupport listeners = new PropertyChangeSupport(this); + TextField parameterOffsetTF, numParametersTF; + Choice nids; + Button doneButton; + public DeviceInputsCustomizer() + {} + + @Override + public void addPropertyChangeListener(PropertyChangeListener l) + { + listeners.addPropertyChangeListener(l); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener l) + { + listeners.removePropertyChangeListener(l); + } + + @Override + public void setObject(Object o) + { + bean = (DeviceInputs) o; + setLayout(new BorderLayout()); + Panel jp = new Panel(); + jp.setLayout(new GridLayout(1, 1)); + Panel jp1 = new Panel(); + jp.add(jp1); + jp1 = new Panel(); + jp1.add(new Label("Offset nid: ")); + jp1.add(nids = new Choice()); + final String names[] = getDeviceFields(); + if (names != null) + for (int i = 0; i < names.length; i++) + nids.addItem(names[i]); + int offsetNid = bean.getOffsetNid(); + if (offsetNid > 0) + offsetNid--; + nids.select(offsetNid); + jp.add(jp1); + add(jp, "Center"); + jp = new Panel(); + jp.add(doneButton = new Button("Apply")); + doneButton.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + if (bean == null) + return; + final int oldOffsetNid = bean.getOffsetNid(); + bean.setOffsetNid(nids.getSelectedIndex() + 1); + listeners.firePropertyChange("offsetNid", oldOffsetNid, bean.getOffsetNid()); + final String oldIdentifier = bean.getIdentifier(); + DeviceInputsCustomizer.this.repaint(); + } + }); + add(jp, "South"); + } +} diff --git a/java/devicebeans/src/main/java/DeviceOutputs.java b/java/devicebeans/src/main/java/DeviceOutputs.java new file mode 100644 index 0000000000..47b231bd04 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceOutputs.java @@ -0,0 +1,172 @@ +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +import javax.swing.*; +import javax.swing.border.LineBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class DeviceOutputs extends DeviceComponent +{ + + private JScrollPane scrollP; + private int numOutputs; + private JTextField segLensTF[], streamNamesTF[]; + private int segLenNids[], streamNameNids[]; + private int numOutputChildren = 0; + private int numItems; + public DeviceOutputs() + { + } + @Override + protected void initializeData(String data, boolean is_on) + { + mode = STRUCTURE; + int currNid = baseNid + offsetNid; + try { + numOutputs = subtree.getInt("GETNCI("+subtree.getFullPath(currNid)+",\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc){numOutputs = 0;} + int currOutNid = currNid + 7; + //Count number of actual outputs (i.e. for which nSamomes and streamName make sense + numItems = 0; + for(int outIdx = 0; outIdx < numOutputs; outIdx++) + { + int numChildren, numMembers, numPars, numFields; + try { + numChildren = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+",\'NUMBER_OF_CHILDREN\')"); + numMembers = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+",\'NUMBER_OF_MEMBERS\')"); + numPars = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+":PARAMETERS,\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + System.out.println("Error getting Output fields"); + numOutputs = 0; + break; + } + try{ + numFields = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+":FIELDS,\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + numFields = 0; //node FIELDS missing + } + if(numFields == 0) + numItems += 1; //no structure + else + numItems += numFields; + currOutNid += 1 + numChildren + numMembers + 2 * numPars + 8 * numFields; + } + segLensTF = new JTextField[numItems]; + streamNamesTF = new JTextField[numItems]; + segLenNids = new int[numItems]; + streamNameNids = new int[numItems]; + JPanel jp = new JPanel(); + jp.setLayout(new GridLayout(numItems, 1)); + currOutNid = currNid + 7; + int currItem = 0; + for(int outIdx = 0; outIdx < numOutputs; outIdx++) + { + int numChildren, numMembers, numPars, numFields; + try { + numChildren = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+",\'NUMBER_OF_CHILDREN\')"); + numMembers = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+",\'NUMBER_OF_MEMBERS\')"); + numPars = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+":PARAMETERS,\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + System.out.println("Error getting Output fields"); + numOutputs = 0; + break; + } + try{ + numFields = subtree.getInt("GETNCI("+subtree.getFullPath(currOutNid)+":FIELDS,\'NUMBER_OF_CHILDREN\')"); + }catch(Exception exc) + { + numFields = 0; //node FIELDS missing + } + String outName = ""; + try { + outName = subtree.getString(subtree.getDataExpr(currOutNid + 1)); + }catch(Exception exc){} + if(numFields == 0) + { + JPanel jp1 = new JPanel(); + jp1.setBorder(new TitledBorder(outName)); + jp1.setLayout(new GridLayout(1,2)); + jp1.add(new JLabel("Segment len.: ")); + jp1.add(segLensTF[currItem] = new JTextField(10)); + jp1.add(new JLabel("Stream name: ")); + jp1.add(streamNamesTF[currItem] = new JTextField(10)); + jp.add(jp1); + segLenNids[currItem] = currOutNid + 5; + streamNameNids[currItem] = currOutNid + 6; + currItem++; + } + else + { + for(int fieldIdx = 0; fieldIdx < numFields; fieldIdx++) + { + int fieldNid = currOutNid + numChildren +numMembers +1 + 2 * numPars + 8 * fieldIdx; + segLenNids[currItem] = fieldNid + 5; + streamNameNids[currItem] = fieldNid + 6; + String fieldName = ""; + try { + fieldName = subtree.getString(subtree.getDataExpr(fieldNid + 1)); + }catch(Exception exc){} + JPanel jp1 = new JPanel(); + jp1.setBorder(new TitledBorder(outName+'.'+fieldName)); + jp1.setLayout(new GridLayout(1,2)); + jp1.add(new JLabel("Segment len.: ")); + jp1.add(segLensTF[currItem] = new JTextField(10)); + jp1.add(new JLabel("Stream name: ")); + jp1.add(streamNamesTF[currItem] = new JTextField(10)); + jp.add(jp1); + currItem++; + } + } + currOutNid += 1 + numChildren + numMembers + 2 * numPars + 8 * numFields; + + } + scrollP = new JScrollPane(jp); + setLayout(new BorderLayout()); + add(scrollP, "Center"); + displayData(data, is_on); + } + protected void displayData(String data, boolean is_on) + { + for(int idx = 0; idx < numItems; idx++) + { + try { + segLensTF[idx].setText(subtree.getDataExpr(segLenNids[idx])); + }catch(Exception exc) + { + segLensTF[idx].setText(""); + } + try { + streamNamesTF[idx].setText(subtree.getString(subtree.getDataExpr(streamNameNids[idx]))); + }catch(Exception exc) + { + streamNamesTF[idx].setText(""); + } + } + } + + protected String getData() {return null;} + protected boolean getState(){return true;} + + public void apply() throws Exception + { + for(int idx = 0; idx < numItems; idx++) + { + try { + subtree.putDataExpr(segLenNids[idx], segLensTF[idx].getText()); + }catch(Exception exc) + {} + try { + String name = streamNamesTF[idx].getText(); + subtree.putDataExpr(streamNameNids[idx], "\""+streamNamesTF[idx].getText()+"\""); + }catch(Exception exc) + {} + } + } + + } diff --git a/java/devicebeans/src/main/java/DeviceOutputsBeanInfo.java b/java/devicebeans/src/main/java/DeviceOutputsBeanInfo.java new file mode 100644 index 0000000000..65e0125c87 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceOutputsBeanInfo.java @@ -0,0 +1,38 @@ +import java.beans.*; +import java.awt.*; + +public class DeviceOutputsBeanInfo extends SimpleBeanInfo +{ + @Override + public BeanDescriptor getBeanDescriptor() + { return new BeanDescriptor(DeviceOutputs.class, DeviceOutputsCustomizer.class); } + + @Override + public Image getIcon(int kind) + { + return loadImage("DeviceChannel.gif"); + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors() + { + try + { + final PropertyDescriptor[] props = + { property("offsetNid", "Offset nid")}; + return props; + } + catch (final IntrospectionException e) + { + System.out.println("DeviceOutputs: property exception " + e); + return super.getPropertyDescriptors(); + } + } + + public PropertyDescriptor property(String name, String description) throws IntrospectionException + { + final PropertyDescriptor p = new PropertyDescriptor(name, DeviceOutputs.class); + p.setShortDescription(description); + return p; + } +} diff --git a/java/devicebeans/src/main/java/DeviceOutputsCustomizer.java b/java/devicebeans/src/main/java/DeviceOutputsCustomizer.java new file mode 100644 index 0000000000..3d46ad2091 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceOutputsCustomizer.java @@ -0,0 +1,82 @@ +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.beans.Customizer; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; + +public class DeviceOutputsCustomizer extends DeviceCustomizer implements Customizer +{ + /** + * + */ + private static final long serialVersionUID = 1L; + DeviceOutputs bean = null; + Object obj; + PropertyChangeSupport listeners = new PropertyChangeSupport(this); + TextField parameterOffsetTF, numParametersTF; + Choice nids; + Button doneButton; + public DeviceOutputsCustomizer() + {} + + @Override + public void addPropertyChangeListener(PropertyChangeListener l) + { + listeners.addPropertyChangeListener(l); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener l) + { + listeners.removePropertyChangeListener(l); + } + + @Override + public void setObject(Object o) + { + bean = (DeviceOutputs) o; + setLayout(new BorderLayout()); + Panel jp = new Panel(); + jp.setLayout(new GridLayout(1, 1)); + Panel jp1 = new Panel(); + jp.add(jp1); + jp1 = new Panel(); + jp1.add(new Label("Offset nid: ")); + jp1.add(nids = new Choice()); + final String names[] = getDeviceFields(); + if (names != null) + for (int i = 0; i < names.length; i++) + nids.addItem(names[i]); + int offsetNid = bean.getOffsetNid(); + if (offsetNid > 0) + offsetNid--; + nids.select(offsetNid); + jp.add(jp1); + add(jp, "Center"); + jp = new Panel(); + jp.add(doneButton = new Button("Apply")); + doneButton.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + if (bean == null) + return; + final int oldOffsetNid = bean.getOffsetNid(); + bean.setOffsetNid(nids.getSelectedIndex() + 1); + listeners.firePropertyChange("offsetNid", oldOffsetNid, bean.getOffsetNid()); + final String oldIdentifier = bean.getIdentifier(); + DeviceOutputsCustomizer.this.repaint(); + } + }); + add(jp, "South"); + } +} diff --git a/java/devicebeans/src/main/java/DeviceParameters.java b/java/devicebeans/src/main/java/DeviceParameters.java new file mode 100644 index 0000000000..b67c277754 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceParameters.java @@ -0,0 +1,82 @@ +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +import javax.swing.*; +import javax.swing.border.LineBorder; +import javax.swing.border.TitledBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class DeviceParameters extends DeviceComponent +{ + + private JScrollPane scrollP; + private int parameterOffset; + private int numParameters; + private JTextField valuesTF[]; + private JLabel labels[]; + public DeviceParameters() + { + } + @Override + protected void initializeData(String data, boolean is_on) + { + mode = STRUCTURE; + valuesTF = new JTextField[numParameters]; + labels = new JLabel[numParameters]; + JPanel jp = new JPanel(); + jp.setLayout(new GridLayout(numParameters, 1)); + int currNid = baseNid + offsetNid + 2 + 3 * parameterOffset; + for(int i = 0; i < numParameters; i++) + { + JPanel jp1 = new JPanel(); + String parName = ""; + try { + parName = subtree.getString(subtree.getDataExpr(currNid)); + parName = parName.substring(11); + }catch(Exception exc){System.out.println("Cannot read parameter name");} + + jp1.setBorder(new TitledBorder(parName)); + jp1.setLayout(new BorderLayout()); + jp1.add(valuesTF[i] = new JTextField(), "Center"); + jp.add(jp1); + currNid += 3; + } + scrollP = new JScrollPane(jp); + setLayout(new BorderLayout()); + add(scrollP, "Center"); + displayData(data, is_on); + + } + protected void displayData(String data, boolean is_on) + { + int currNid = baseNid + offsetNid + 3 + 3 * parameterOffset; + for(int parIdx = 0; parIdx < numParameters; parIdx++) + { + try { + valuesTF[parIdx].setText(subtree.getDataExpr(currNid)); + }catch(Exception exc){System.out.println("Cannot read parameter value");} + currNid += 3; + } + } + + protected String getData() {return null;} + protected boolean getState(){return true;} + + public void apply() throws Exception + { + int currNid = baseNid + offsetNid + 3 + 3 * parameterOffset; + for(int parIdx = 0; parIdx < numParameters; parIdx++) + { + try { + subtree.putDataExpr(currNid, valuesTF[parIdx].getText()); + }catch(Exception exc){System.out.println("Cannot write parameter "+labels[parIdx]+": "+exc);} + currNid += 3; + } + } + public int getNumParameters() {return numParameters;} + public void setNumParameters(int numParameters) {this.numParameters = numParameters;} + public int getParameterOffset() {return parameterOffset;} + public void setParameterOffset(int parameterOffset) {this.parameterOffset = parameterOffset;} +} diff --git a/java/devicebeans/src/main/java/DeviceParametersBeanInfo.java b/java/devicebeans/src/main/java/DeviceParametersBeanInfo.java new file mode 100644 index 0000000000..c65cdc8d22 --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceParametersBeanInfo.java @@ -0,0 +1,40 @@ +import java.beans.*; +import java.awt.*; + +public class DeviceParametersBeanInfo extends SimpleBeanInfo +{ + @Override + public BeanDescriptor getBeanDescriptor() + { return new BeanDescriptor(DeviceParameters.class, DeviceParametersCustomizer.class); } + + @Override + public Image getIcon(int kind) + { + return loadImage("DeviceLabel.gif"); + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors() + { + try + { + final PropertyDescriptor[] props = + { property("offsetNid", "Offset nid"), + property("parameterOffset", "Parameter offset"), + property("numParameters", "Number of parameters")}; + return props; + } + catch (final IntrospectionException e) + { + System.out.println("DeviceField: property exception " + e); + return super.getPropertyDescriptors(); + } + } + + public PropertyDescriptor property(String name, String description) throws IntrospectionException + { + final PropertyDescriptor p = new PropertyDescriptor(name, DeviceParameters.class); + p.setShortDescription(description); + return p; + } +} diff --git a/java/devicebeans/src/main/java/DeviceParametersCustomizer.java b/java/devicebeans/src/main/java/DeviceParametersCustomizer.java new file mode 100644 index 0000000000..b1f4d4aeea --- /dev/null +++ b/java/devicebeans/src/main/java/DeviceParametersCustomizer.java @@ -0,0 +1,98 @@ +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.beans.Customizer; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; + +public class DeviceParametersCustomizer extends DeviceCustomizer implements Customizer +{ + /** + * + */ + private static final long serialVersionUID = 1L; + DeviceParameters bean = null; + Object obj; + PropertyChangeSupport listeners = new PropertyChangeSupport(this); + TextField parameterOffsetTF, numParametersTF; + Choice nids; + Button doneButton; + public DeviceParametersCustomizer() + {} + + @Override + public void addPropertyChangeListener(PropertyChangeListener l) + { + listeners.addPropertyChangeListener(l); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener l) + { + listeners.removePropertyChangeListener(l); + } + + @Override + public void setObject(Object o) + { + bean = (DeviceParameters) o; + setLayout(new BorderLayout()); + Panel jp = new Panel(); + jp.setLayout(new GridLayout(2, 1)); + Panel jp1 = new Panel(); + jp1.add(new Label("Parameter Offset: ")); + jp1.add(parameterOffsetTF = new TextField(4)); + final int parameterOffset = bean.getParameterOffset(); + parameterOffsetTF.setText((new Integer(parameterOffset)).toString()); + jp1.add(new Label("Num. Parameters: ")); + jp1.add(numParametersTF = new TextField(4)); + final int numParameters = bean.getNumParameters(); + numParametersTF.setText((new Integer(numParameters)).toString()); + jp.add(jp1); + jp1 = new Panel(); + jp1.add(new Label("Offset nid: ")); + jp1.add(nids = new Choice()); + final String names[] = getDeviceFields(); + if (names != null) + for (int i = 0; i < names.length; i++) + nids.addItem(names[i]); + int offsetNid = bean.getOffsetNid(); + if (offsetNid > 0) + offsetNid--; + nids.select(offsetNid); + jp.add(jp1); + add(jp, "Center"); + jp = new Panel(); + jp.add(doneButton = new Button("Apply")); + doneButton.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + if (bean == null) + return; + final String parameterOffsetStr = parameterOffsetTF.getText(); + final int oldParameterOffset = bean.getParameterOffset(); + bean.setParameterOffset(Integer.parseInt(parameterOffsetStr)); + listeners.firePropertyChange("parameterOffset", oldParameterOffset, bean.getParameterOffset()); + final String numParametersStr = numParametersTF.getText(); + final int oldNumParameters = bean.getNumParameters(); + bean.setNumParameters(Integer.parseInt(numParametersStr)); + listeners.firePropertyChange("numParameters", oldNumParameters, bean.getNumParameters()); + final int oldOffsetNid = bean.getOffsetNid(); + bean.setOffsetNid(nids.getSelectedIndex() + 1); + listeners.firePropertyChange("offsetNid", oldOffsetNid, bean.getOffsetNid()); + final String oldIdentifier = bean.getIdentifier(); + DeviceParametersCustomizer.this.repaint(); + } + }); + add(jp, "South"); + } +} diff --git a/java/jdevices/src/main/java/MARTE2_CONVERSIONSetup.java b/java/jdevices/src/main/java/MARTE2_CONVERSIONSetup.java index 492a07609e..192ba41bb2 100644 --- a/java/jdevices/src/main/java/MARTE2_CONVERSIONSetup.java +++ b/java/jdevices/src/main/java/MARTE2_CONVERSIONSetup.java @@ -145,8 +145,11 @@ private void initComponents() { jPanel34 = new javax.swing.JPanel(); deviceChoice31 = new DeviceChoice(); deviceField49 = new DeviceField(); + jPanel35 = new javax.swing.JPanel(); + deviceChoice32 = new DeviceChoice(); + deviceField51 = new DeviceField(); - setDeviceProvider("scdevail:8100"); + setDeviceProvider("spilds:8100"); setDeviceTitle("MARTe2 Type Conversion GAM"); setDeviceType("MARTE2_CONVERSION"); setHeight(400); @@ -571,14 +574,14 @@ private void initComponents() { deviceChoice18.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice18.setIdentifier(""); deviceChoice18.setLabelString("Type: "); - deviceChoice18.setOffsetNid(135); + deviceChoice18.setOffsetNid(136); deviceChoice18.setUpdateIdentifier(""); jPanel21.add(deviceChoice18); deviceField36.setIdentifier(""); deviceField36.setLabelString("Segment Len.(0 to disable write): "); deviceField36.setNumCols(4); - deviceField36.setOffsetNid(138); + deviceField36.setOffsetNid(139); jPanel21.add(deviceField36); jPanel19.add(jPanel21); @@ -588,14 +591,14 @@ private void initComponents() { deviceChoice19.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice19.setIdentifier(""); deviceChoice19.setLabelString("Type: "); - deviceChoice19.setOffsetNid(143); + deviceChoice19.setOffsetNid(145); deviceChoice19.setUpdateIdentifier(""); jPanel22.add(deviceChoice19); deviceField37.setIdentifier(""); deviceField37.setLabelString("Segment Len.(0 to disable write): "); deviceField37.setNumCols(4); - deviceField37.setOffsetNid(146); + deviceField37.setOffsetNid(148); jPanel22.add(deviceField37); jPanel19.add(jPanel22); @@ -605,14 +608,14 @@ private void initComponents() { deviceChoice20.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice20.setIdentifier(""); deviceChoice20.setLabelString("Type: "); - deviceChoice20.setOffsetNid(151); + deviceChoice20.setOffsetNid(154); deviceChoice20.setUpdateIdentifier(""); jPanel23.add(deviceChoice20); deviceField38.setIdentifier(""); deviceField38.setLabelString("Segment Len.(0 to disable write): "); deviceField38.setNumCols(4); - deviceField38.setOffsetNid(154); + deviceField38.setOffsetNid(157); jPanel23.add(deviceField38); jPanel19.add(jPanel23); @@ -622,14 +625,14 @@ private void initComponents() { deviceChoice21.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice21.setIdentifier(""); deviceChoice21.setLabelString("Type: "); - deviceChoice21.setOffsetNid(159); + deviceChoice21.setOffsetNid(163); deviceChoice21.setUpdateIdentifier(""); jPanel24.add(deviceChoice21); deviceField39.setIdentifier(""); deviceField39.setLabelString("Segment Len.(0 to disable write): "); deviceField39.setNumCols(4); - deviceField39.setOffsetNid(162); + deviceField39.setOffsetNid(166); jPanel24.add(deviceField39); jPanel19.add(jPanel24); @@ -639,14 +642,14 @@ private void initComponents() { deviceChoice22.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice22.setIdentifier(""); deviceChoice22.setLabelString("Type: "); - deviceChoice22.setOffsetNid(167); + deviceChoice22.setOffsetNid(172); deviceChoice22.setUpdateIdentifier(""); jPanel25.add(deviceChoice22); deviceField40.setIdentifier(""); deviceField40.setLabelString("Segment Len.(0 to disable write): "); deviceField40.setNumCols(4); - deviceField40.setOffsetNid(170); + deviceField40.setOffsetNid(175); jPanel25.add(deviceField40); jPanel19.add(jPanel25); @@ -656,14 +659,14 @@ private void initComponents() { deviceChoice23.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice23.setIdentifier(""); deviceChoice23.setLabelString("Type: "); - deviceChoice23.setOffsetNid(175); + deviceChoice23.setOffsetNid(181); deviceChoice23.setUpdateIdentifier(""); jPanel26.add(deviceChoice23); deviceField41.setIdentifier(""); deviceField41.setLabelString("Segment Len.(0 to disable write): "); deviceField41.setNumCols(4); - deviceField41.setOffsetNid(178); + deviceField41.setOffsetNid(184); jPanel26.add(deviceField41); jPanel19.add(jPanel26); @@ -673,14 +676,14 @@ private void initComponents() { deviceChoice24.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice24.setIdentifier(""); deviceChoice24.setLabelString("Type: "); - deviceChoice24.setOffsetNid(183); + deviceChoice24.setOffsetNid(190); deviceChoice24.setUpdateIdentifier(""); jPanel27.add(deviceChoice24); deviceField42.setIdentifier(""); deviceField42.setLabelString("Segment Len.(0 to disable write): "); deviceField42.setNumCols(4); - deviceField42.setOffsetNid(186); + deviceField42.setOffsetNid(193); jPanel27.add(deviceField42); jPanel19.add(jPanel27); @@ -690,14 +693,14 @@ private void initComponents() { deviceChoice25.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice25.setIdentifier(""); deviceChoice25.setLabelString("Type: "); - deviceChoice25.setOffsetNid(191); + deviceChoice25.setOffsetNid(199); deviceChoice25.setUpdateIdentifier(""); jPanel28.add(deviceChoice25); deviceField43.setIdentifier(""); deviceField43.setLabelString("Segment Len.(0 to disable write): "); deviceField43.setNumCols(4); - deviceField43.setOffsetNid(194); + deviceField43.setOffsetNid(202); jPanel28.add(deviceField43); jPanel19.add(jPanel28); @@ -707,14 +710,14 @@ private void initComponents() { deviceChoice26.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice26.setIdentifier(""); deviceChoice26.setLabelString("Type: "); - deviceChoice26.setOffsetNid(199); + deviceChoice26.setOffsetNid(208); deviceChoice26.setUpdateIdentifier(""); jPanel29.add(deviceChoice26); deviceField44.setIdentifier(""); deviceField44.setLabelString("Segment Len.(0 to disable write): "); deviceField44.setNumCols(4); - deviceField44.setOffsetNid(202); + deviceField44.setOffsetNid(211); jPanel29.add(deviceField44); jPanel19.add(jPanel29); @@ -724,14 +727,14 @@ private void initComponents() { deviceChoice27.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice27.setIdentifier(""); deviceChoice27.setLabelString("Type: "); - deviceChoice27.setOffsetNid(207); + deviceChoice27.setOffsetNid(217); deviceChoice27.setUpdateIdentifier(""); jPanel30.add(deviceChoice27); deviceField45.setIdentifier(""); deviceField45.setLabelString("Segment Len.(0 to disable write): "); deviceField45.setNumCols(4); - deviceField45.setOffsetNid(210); + deviceField45.setOffsetNid(220); jPanel30.add(deviceField45); jPanel19.add(jPanel30); @@ -741,14 +744,14 @@ private void initComponents() { deviceChoice28.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice28.setIdentifier(""); deviceChoice28.setLabelString("Type: "); - deviceChoice28.setOffsetNid(215); + deviceChoice28.setOffsetNid(227); deviceChoice28.setUpdateIdentifier(""); jPanel31.add(deviceChoice28); deviceField46.setIdentifier(""); deviceField46.setLabelString("Segment Len.(0 to disable write): "); deviceField46.setNumCols(4); - deviceField46.setOffsetNid(218); + deviceField46.setOffsetNid(229); jPanel31.add(deviceField46); jPanel19.add(jPanel31); @@ -758,14 +761,14 @@ private void initComponents() { deviceChoice29.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice29.setIdentifier(""); deviceChoice29.setLabelString("Type: "); - deviceChoice29.setOffsetNid(223); + deviceChoice29.setOffsetNid(235); deviceChoice29.setUpdateIdentifier(""); jPanel32.add(deviceChoice29); deviceField47.setIdentifier(""); deviceField47.setLabelString("Segment Len.(0 to disable write): "); deviceField47.setNumCols(4); - deviceField47.setOffsetNid(226); + deviceField47.setOffsetNid(238); jPanel32.add(deviceField47); jPanel19.add(jPanel32); @@ -775,14 +778,14 @@ private void initComponents() { deviceChoice30.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice30.setIdentifier(""); deviceChoice30.setLabelString("Type: "); - deviceChoice30.setOffsetNid(239); + deviceChoice30.setOffsetNid(244); deviceChoice30.setUpdateIdentifier(""); jPanel33.add(deviceChoice30); deviceField48.setIdentifier(""); deviceField48.setLabelString("Segment Len.(0 to disable write): "); deviceField48.setNumCols(4); - deviceField48.setOffsetNid(242); + deviceField48.setOffsetNid(247); jPanel33.add(deviceField48); jPanel19.add(jPanel33); @@ -792,18 +795,35 @@ private void initComponents() { deviceChoice31.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); deviceChoice31.setIdentifier(""); deviceChoice31.setLabelString("Type: "); - deviceChoice31.setOffsetNid(247); + deviceChoice31.setOffsetNid(253); deviceChoice31.setUpdateIdentifier(""); jPanel34.add(deviceChoice31); deviceField49.setIdentifier(""); deviceField49.setLabelString("Segment Len.(0 to disable write): "); deviceField49.setNumCols(4); - deviceField49.setOffsetNid(250); + deviceField49.setOffsetNid(256); jPanel34.add(deviceField49); jPanel19.add(jPanel34); + jPanel35.setBorder(javax.swing.BorderFactory.createTitledBorder("Out16")); + + deviceChoice32.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice32.setIdentifier(""); + deviceChoice32.setLabelString("Type: "); + deviceChoice32.setOffsetNid(262); + deviceChoice32.setUpdateIdentifier(""); + jPanel35.add(deviceChoice32); + + deviceField51.setIdentifier(""); + deviceField51.setLabelString("Segment Len.(0 to disable write): "); + deviceField51.setNumCols(4); + deviceField51.setOffsetNid(265); + jPanel35.add(deviceField51); + + jPanel19.add(jPanel35); + jScrollPane2.setViewportView(jPanel19); jTabbedPane1.addTab("Outputs", jScrollPane2); @@ -839,6 +859,7 @@ private void initComponents() { private DeviceChoice deviceChoice3; private DeviceChoice deviceChoice30; private DeviceChoice deviceChoice31; + private DeviceChoice deviceChoice32; private DeviceChoice deviceChoice4; private DeviceChoice deviceChoice5; private DeviceChoice deviceChoice6; @@ -891,6 +912,7 @@ private void initComponents() { private DeviceField deviceField49; private DeviceField deviceField5; private DeviceField deviceField50; + private DeviceField deviceField51; private DeviceField deviceField6; private DeviceField deviceField7; private DeviceField deviceField8; @@ -923,6 +945,7 @@ private void initComponents() { private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel33; private javax.swing.JPanel jPanel34; + private javax.swing.JPanel jPanel35; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; diff --git a/java/jdevices/src/main/java/MARTE2_EXPRSetup.java b/java/jdevices/src/main/java/MARTE2_EXPRSetup.java index 80799c4a9b..fe2c424534 100644 --- a/java/jdevices/src/main/java/MARTE2_EXPRSetup.java +++ b/java/jdevices/src/main/java/MARTE2_EXPRSetup.java @@ -29,629 +29,807 @@ public MARTE2_EXPRSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceButtons1 = new DeviceButtons(); - jPanel1 = new javax.swing.JPanel(); - jTabbedPane1 = new javax.swing.JTabbedPane(); - jPanel2 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceChoice1 = new DeviceChoice(); - jPanel4 = new javax.swing.JPanel(); - deviceField2 = new DeviceField(); - jPanel5 = new javax.swing.JPanel(); - jPanel6 = new javax.swing.JPanel(); - deviceField3 = new DeviceField(); - deviceChoice2 = new DeviceChoice(); - jPanel7 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - jPanel9 = new javax.swing.JPanel(); - deviceField5 = new DeviceField(); - deviceChoice3 = new DeviceChoice(); - jPanel10 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - jPanel11 = new javax.swing.JPanel(); - jPanel12 = new javax.swing.JPanel(); - deviceField7 = new DeviceField(); - deviceChoice4 = new DeviceChoice(); - jPanel13 = new javax.swing.JPanel(); - deviceField8 = new DeviceField(); - jPanel14 = new javax.swing.JPanel(); - jPanel15 = new javax.swing.JPanel(); - deviceField9 = new DeviceField(); - deviceChoice5 = new DeviceChoice(); - jPanel16 = new javax.swing.JPanel(); - deviceField10 = new DeviceField(); - jPanel17 = new javax.swing.JPanel(); - jPanel18 = new javax.swing.JPanel(); - deviceField11 = new DeviceField(); - deviceChoice6 = new DeviceChoice(); - jPanel19 = new javax.swing.JPanel(); - deviceField12 = new DeviceField(); - jPanel20 = new javax.swing.JPanel(); - jPanel21 = new javax.swing.JPanel(); - deviceField13 = new DeviceField(); - deviceChoice7 = new DeviceChoice(); - jPanel22 = new javax.swing.JPanel(); - deviceField14 = new DeviceField(); - jPanel23 = new javax.swing.JPanel(); - jPanel24 = new javax.swing.JPanel(); - deviceField15 = new DeviceField(); - deviceChoice8 = new DeviceChoice(); - jPanel25 = new javax.swing.JPanel(); - deviceField16 = new DeviceField(); - jTabbedPane2 = new javax.swing.JTabbedPane(); - jPanel26 = new javax.swing.JPanel(); - jPanel27 = new javax.swing.JPanel(); - deviceField17 = new DeviceField(); - deviceChoice9 = new DeviceChoice(); - deviceField33 = new DeviceField(); - jPanel28 = new javax.swing.JPanel(); - deviceField18 = new DeviceField(); - jPanel29 = new javax.swing.JPanel(); - jPanel30 = new javax.swing.JPanel(); - deviceField19 = new DeviceField(); - deviceChoice10 = new DeviceChoice(); - deviceField34 = new DeviceField(); - jPanel31 = new javax.swing.JPanel(); - deviceField20 = new DeviceField(); - jPanel32 = new javax.swing.JPanel(); - jPanel33 = new javax.swing.JPanel(); - deviceField21 = new DeviceField(); - deviceChoice11 = new DeviceChoice(); - deviceField35 = new DeviceField(); - jPanel34 = new javax.swing.JPanel(); - deviceField22 = new DeviceField(); - jPanel35 = new javax.swing.JPanel(); - jPanel36 = new javax.swing.JPanel(); - deviceField23 = new DeviceField(); - deviceChoice12 = new DeviceChoice(); - deviceField36 = new DeviceField(); - jPanel37 = new javax.swing.JPanel(); - deviceField24 = new DeviceField(); - jPanel38 = new javax.swing.JPanel(); - jPanel39 = new javax.swing.JPanel(); - deviceField25 = new DeviceField(); - deviceChoice13 = new DeviceChoice(); - deviceField37 = new DeviceField(); - jPanel40 = new javax.swing.JPanel(); - deviceField26 = new DeviceField(); - jPanel41 = new javax.swing.JPanel(); - jPanel42 = new javax.swing.JPanel(); - deviceField27 = new DeviceField(); - deviceChoice14 = new DeviceChoice(); - deviceField38 = new DeviceField(); - jPanel43 = new javax.swing.JPanel(); - deviceField28 = new DeviceField(); - jPanel44 = new javax.swing.JPanel(); - jPanel45 = new javax.swing.JPanel(); - deviceField29 = new DeviceField(); - deviceChoice15 = new DeviceChoice(); - deviceField39 = new DeviceField(); - jPanel46 = new javax.swing.JPanel(); - deviceField30 = new DeviceField(); - jPanel47 = new javax.swing.JPanel(); - jPanel48 = new javax.swing.JPanel(); - deviceField31 = new DeviceField(); - deviceChoice16 = new DeviceChoice(); - deviceField40 = new DeviceField(); - jPanel49 = new javax.swing.JPanel(); - deviceField32 = new DeviceField(); - jPanel50 = new javax.swing.JPanel(); - deviceField41 = new DeviceField(); - deviceField43 = new DeviceField(); - deviceField42 = new DeviceField(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceType("MARTE2_EXPR"); - setHeight(400); - setWidth(900); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - jPanel1.setLayout(new java.awt.GridLayout(2, 1)); - jPanel2.setLayout(new java.awt.GridLayout(2, 1)); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField1.setOffsetNid(32); - jPanel3.add(deviceField1); - deviceChoice1.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice1.setIdentifier(""); - deviceChoice1.setLabelString(""); - deviceChoice1.setOffsetNid(31); - deviceChoice1.setUpdateIdentifier(""); - jPanel3.add(deviceChoice1); - jPanel2.add(jPanel3); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Value:"); - deviceField2.setNumCols(25); - deviceField2.setOffsetNid(34); - jPanel4.add(deviceField2); - jPanel2.add(jPanel4); - jTabbedPane1.addTab("In1", jPanel2); - jPanel5.setLayout(new java.awt.GridLayout(2, 1)); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField3.setOffsetNid(39); - jPanel6.add(deviceField3); - deviceChoice2.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice2.setIdentifier(""); - deviceChoice2.setLabelString(""); - deviceChoice2.setOffsetNid(38); - deviceChoice2.setUpdateIdentifier(""); - jPanel6.add(deviceChoice2); - jPanel5.add(jPanel6); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Value:"); - deviceField4.setNumCols(25); - deviceField4.setOffsetNid(41); - jPanel7.add(deviceField4); - jPanel5.add(jPanel7); - jTabbedPane1.addTab("In2", jPanel5); - jPanel8.setLayout(new java.awt.GridLayout(2, 1)); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField5.setOffsetNid(46); - jPanel9.add(deviceField5); - deviceChoice3.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice3.setIdentifier(""); - deviceChoice3.setLabelString(""); - deviceChoice3.setOffsetNid(45); - deviceChoice3.setUpdateIdentifier(""); - jPanel9.add(deviceChoice3); - jPanel8.add(jPanel9); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Value:"); - deviceField6.setNumCols(25); - deviceField6.setOffsetNid(48); - jPanel10.add(deviceField6); - jPanel8.add(jPanel10); - jTabbedPane1.addTab("In3", jPanel8); - jPanel11.setLayout(new java.awt.GridLayout(2, 1)); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField7.setOffsetNid(53); - jPanel12.add(deviceField7); - deviceChoice4.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice4.setIdentifier(""); - deviceChoice4.setLabelString(""); - deviceChoice4.setOffsetNid(52); - deviceChoice4.setUpdateIdentifier(""); - jPanel12.add(deviceChoice4); - jPanel11.add(jPanel12); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Value:"); - deviceField8.setNumCols(25); - deviceField8.setOffsetNid(55); - jPanel13.add(deviceField8); - jPanel11.add(jPanel13); - jTabbedPane1.addTab("In4", jPanel11); - jPanel14.setLayout(new java.awt.GridLayout(2, 1)); - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField9.setOffsetNid(60); - jPanel15.add(deviceField9); - deviceChoice5.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice5.setIdentifier(""); - deviceChoice5.setLabelString(""); - deviceChoice5.setOffsetNid(59); - deviceChoice5.setUpdateIdentifier(""); - jPanel15.add(deviceChoice5); - jPanel14.add(jPanel15); - deviceField10.setIdentifier(""); - deviceField10.setLabelString("Value:"); - deviceField10.setNumCols(25); - deviceField10.setOffsetNid(62); - jPanel16.add(deviceField10); - jPanel14.add(jPanel16); - jTabbedPane1.addTab("In5", jPanel14); - jPanel17.setLayout(new java.awt.GridLayout(2, 1)); - deviceField11.setIdentifier(""); - deviceField11.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField11.setOffsetNid(67); - jPanel18.add(deviceField11); - deviceChoice6.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice6.setIdentifier(""); - deviceChoice6.setLabelString(""); - deviceChoice6.setOffsetNid(66); - deviceChoice6.setUpdateIdentifier(""); - jPanel18.add(deviceChoice6); - jPanel17.add(jPanel18); - deviceField12.setIdentifier(""); - deviceField12.setLabelString("Value:"); - deviceField12.setNumCols(25); - deviceField12.setOffsetNid(69); - jPanel19.add(deviceField12); - jPanel17.add(jPanel19); - jTabbedPane1.addTab("In6", jPanel17); - jPanel20.setLayout(new java.awt.GridLayout(2, 1)); - deviceField13.setIdentifier(""); - deviceField13.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField13.setOffsetNid(74); - jPanel21.add(deviceField13); - deviceChoice7.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice7.setIdentifier(""); - deviceChoice7.setLabelString(""); - deviceChoice7.setOffsetNid(73); - deviceChoice7.setUpdateIdentifier(""); - jPanel21.add(deviceChoice7); - jPanel20.add(jPanel21); - deviceField14.setIdentifier(""); - deviceField14.setLabelString("Value:"); - deviceField14.setNumCols(25); - deviceField14.setOffsetNid(76); - jPanel22.add(deviceField14); - jPanel20.add(jPanel22); - jTabbedPane1.addTab("In7", jPanel20); - jPanel23.setLayout(new java.awt.GridLayout(2, 1)); - deviceField15.setIdentifier(""); - deviceField15.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField15.setOffsetNid(81); - jPanel24.add(deviceField15); - deviceChoice8.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice8.setIdentifier(""); - deviceChoice8.setLabelString(""); - deviceChoice8.setOffsetNid(80); - deviceChoice8.setUpdateIdentifier(""); - jPanel24.add(deviceChoice8); - jPanel23.add(jPanel24); - deviceField16.setIdentifier(""); - deviceField16.setLabelString("Value:"); - deviceField16.setNumCols(25); - deviceField16.setOffsetNid(83); - jPanel25.add(deviceField16); - jPanel23.add(jPanel25); - jTabbedPane1.addTab("In8", jPanel23); - jPanel1.add(jTabbedPane1); - jPanel26.setLayout(new java.awt.GridLayout(2, 1)); - deviceField17.setIdentifier(""); - deviceField17.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField17.setOffsetNid(97); - jPanel27.add(deviceField17); - deviceChoice9.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice9.setIdentifier(""); - deviceChoice9.setLabelString("Type: "); - deviceChoice9.setOffsetNid(95); - deviceChoice9.setUpdateIdentifier(""); - jPanel27.add(deviceChoice9); - deviceField33.setIdentifier(""); - deviceField33.setLabelString("Seg. Len (0 to disable writing):"); - deviceField33.setNumCols(4); - deviceField33.setOffsetNid(98); - jPanel27.add(deviceField33); - jPanel26.add(jPanel27); - deviceField18.setIdentifier(""); - deviceField18.setLabelString("Expression:"); - deviceField18.setNumCols(35); - deviceField18.setOffsetNid(103); - deviceField18.setTextOnly(true); - jPanel28.add(deviceField18); - jPanel26.add(jPanel28); - jTabbedPane2.addTab("Out1", jPanel26); - jPanel29.setLayout(new java.awt.GridLayout(2, 1)); - deviceField19.setIdentifier(""); - deviceField19.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField19.setOffsetNid(108); - jPanel30.add(deviceField19); - deviceChoice10.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice10.setIdentifier(""); - deviceChoice10.setLabelString("Type: "); - deviceChoice10.setOffsetNid(106); - deviceChoice10.setUpdateIdentifier(""); - jPanel30.add(deviceChoice10); - deviceField34.setIdentifier(""); - deviceField34.setLabelString("Seg. Len (0 to disable writing):"); - deviceField34.setNumCols(4); - deviceField34.setOffsetNid(109); - jPanel30.add(deviceField34); - jPanel29.add(jPanel30); - deviceField20.setIdentifier(""); - deviceField20.setLabelString("Expression:"); - deviceField20.setNumCols(35); - deviceField20.setOffsetNid(114); - deviceField20.setTextOnly(true); - jPanel31.add(deviceField20); - jPanel29.add(jPanel31); - jTabbedPane2.addTab("Out2", jPanel29); - jPanel32.setLayout(new java.awt.GridLayout(2, 1)); - deviceField21.setIdentifier(""); - deviceField21.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField21.setOffsetNid(119); - jPanel33.add(deviceField21); - deviceChoice11.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice11.setIdentifier(""); - deviceChoice11.setLabelString("Type: "); - deviceChoice11.setOffsetNid(117); - deviceChoice11.setUpdateIdentifier(""); - jPanel33.add(deviceChoice11); - deviceField35.setIdentifier(""); - deviceField35.setLabelString("Seg. Len (0 to disable writing):"); - deviceField35.setNumCols(4); - deviceField35.setOffsetNid(120); - jPanel33.add(deviceField35); - jPanel32.add(jPanel33); - deviceField22.setIdentifier(""); - deviceField22.setLabelString("Expression:"); - deviceField22.setNumCols(35); - deviceField22.setOffsetNid(125); - deviceField22.setTextOnly(true); - jPanel34.add(deviceField22); - jPanel32.add(jPanel34); - jTabbedPane2.addTab("Out3", jPanel32); - jPanel35.setLayout(new java.awt.GridLayout(2, 1)); - deviceField23.setIdentifier(""); - deviceField23.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField23.setOffsetNid(130); - jPanel36.add(deviceField23); - deviceChoice12.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice12.setIdentifier(""); - deviceChoice12.setLabelString("Type: "); - deviceChoice12.setOffsetNid(128); - deviceChoice12.setUpdateIdentifier(""); - jPanel36.add(deviceChoice12); - deviceField36.setIdentifier(""); - deviceField36.setLabelString("Seg. Len (0 to disable writing):"); - deviceField36.setNumCols(4); - deviceField36.setOffsetNid(131); - jPanel36.add(deviceField36); - jPanel35.add(jPanel36); - deviceField24.setIdentifier(""); - deviceField24.setLabelString("Expression:"); - deviceField24.setNumCols(35); - deviceField24.setOffsetNid(136); - deviceField24.setTextOnly(true); - jPanel37.add(deviceField24); - jPanel35.add(jPanel37); - jTabbedPane2.addTab("Out4", jPanel35); - jPanel38.setLayout(new java.awt.GridLayout(2, 1)); - deviceField25.setIdentifier(""); - deviceField25.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField25.setOffsetNid(141); - jPanel39.add(deviceField25); - deviceChoice13.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice13.setIdentifier(""); - deviceChoice13.setLabelString("Type: "); - deviceChoice13.setOffsetNid(139); - deviceChoice13.setUpdateIdentifier(""); - jPanel39.add(deviceChoice13); - deviceField37.setIdentifier(""); - deviceField37.setLabelString("Seg. Len (0 to disable writing):"); - deviceField37.setNumCols(4); - deviceField37.setOffsetNid(142); - jPanel39.add(deviceField37); - jPanel38.add(jPanel39); - deviceField26.setIdentifier(""); - deviceField26.setLabelString("Expression:"); - deviceField26.setNumCols(35); - deviceField26.setOffsetNid(147); - deviceField26.setTextOnly(true); - jPanel40.add(deviceField26); - jPanel38.add(jPanel40); - jTabbedPane2.addTab("Out5", jPanel38); - jPanel41.setLayout(new java.awt.GridLayout(2, 1)); - deviceField27.setIdentifier(""); - deviceField27.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField27.setOffsetNid(152); - jPanel42.add(deviceField27); - deviceChoice14.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice14.setIdentifier(""); - deviceChoice14.setLabelString("Type: "); - deviceChoice14.setOffsetNid(150); - deviceChoice14.setUpdateIdentifier(""); - jPanel42.add(deviceChoice14); - deviceField38.setIdentifier(""); - deviceField38.setLabelString("Seg. Len (0 to disable writing):"); - deviceField38.setNumCols(4); - deviceField38.setOffsetNid(153); - jPanel42.add(deviceField38); - jPanel41.add(jPanel42); - deviceField28.setIdentifier(""); - deviceField28.setLabelString("Expression:"); - deviceField28.setNumCols(35); - deviceField28.setOffsetNid(158); - deviceField28.setTextOnly(true); - jPanel43.add(deviceField28); - jPanel41.add(jPanel43); - jTabbedPane2.addTab("Out6", jPanel41); - jPanel44.setLayout(new java.awt.GridLayout(2, 1)); - deviceField29.setIdentifier(""); - deviceField29.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField29.setOffsetNid(163); - jPanel45.add(deviceField29); - deviceChoice15.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice15.setIdentifier(""); - deviceChoice15.setLabelString("Type: "); - deviceChoice15.setOffsetNid(161); - deviceChoice15.setUpdateIdentifier(""); - jPanel45.add(deviceChoice15); - deviceField39.setIdentifier(""); - deviceField39.setLabelString("Seg. Len (0 to disable writing):"); - deviceField39.setNumCols(4); - deviceField39.setOffsetNid(164); - jPanel45.add(deviceField39); - jPanel44.add(jPanel45); - deviceField30.setIdentifier(""); - deviceField30.setLabelString("Expression:"); - deviceField30.setNumCols(35); - deviceField30.setOffsetNid(169); - deviceField30.setTextOnly(true); - jPanel46.add(deviceField30); - jPanel44.add(jPanel46); - jTabbedPane2.addTab("Out7", jPanel44); - jPanel47.setLayout(new java.awt.GridLayout(2, 1)); - deviceField31.setIdentifier(""); - deviceField31.setLabelString("Dimensions (0 for scalar, array otherwise):"); - deviceField31.setOffsetNid(174); - jPanel48.add(deviceField31); - deviceChoice16.setChoiceItems(new String[] - { "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64" }); - deviceChoice16.setIdentifier(""); - deviceChoice16.setLabelString("Type: "); - deviceChoice16.setOffsetNid(172); - deviceChoice16.setUpdateIdentifier(""); - jPanel48.add(deviceChoice16); - deviceField40.setIdentifier(""); - deviceField40.setLabelString("Seg. Len (0 to disable writing):"); - deviceField40.setNumCols(4); - deviceField40.setOffsetNid(175); - jPanel48.add(deviceField40); - jPanel47.add(jPanel48); - deviceField32.setIdentifier(""); - deviceField32.setLabelString("Expression:"); - deviceField32.setNumCols(35); - deviceField32.setOffsetNid(180); - deviceField32.setTextOnly(true); - jPanel49.add(deviceField32); - jPanel47.add(jPanel49); - jTabbedPane2.addTab("Out8", jPanel47); - jPanel1.add(jTabbedPane2); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - deviceField41.setIdentifier(""); - deviceField41.setLabelString("Timebase:"); - deviceField41.setNumCols(25); - deviceField41.setOffsetNid(3); - jPanel50.add(deviceField41); - deviceField43.setIdentifier(""); - deviceField43.setLabelString("Timebase Division (Valid if timebase on another thread):"); - deviceField43.setNumCols(4); - deviceField43.setOffsetNid(181); - jPanel50.add(deviceField43); - deviceField42.setIdentifier(""); - deviceField42.setLabelString("Storage CPUs: "); - deviceField42.setNumCols(4); - deviceField42.setOffsetNid(92); - jPanel50.add(deviceField42); - getContentPane().add(jPanel50, java.awt.BorderLayout.PAGE_START); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice1; - private DeviceChoice deviceChoice10; - private DeviceChoice deviceChoice11; - private DeviceChoice deviceChoice12; - private DeviceChoice deviceChoice13; - private DeviceChoice deviceChoice14; - private DeviceChoice deviceChoice15; - private DeviceChoice deviceChoice16; - private DeviceChoice deviceChoice2; - private DeviceChoice deviceChoice3; - private DeviceChoice deviceChoice4; - private DeviceChoice deviceChoice5; - private DeviceChoice deviceChoice6; - private DeviceChoice deviceChoice7; - private DeviceChoice deviceChoice8; - private DeviceChoice deviceChoice9; - private DeviceField deviceField1; - private DeviceField deviceField10; - private DeviceField deviceField11; - private DeviceField deviceField12; - private DeviceField deviceField13; - private DeviceField deviceField14; - private DeviceField deviceField15; - private DeviceField deviceField16; - private DeviceField deviceField17; - private DeviceField deviceField18; - private DeviceField deviceField19; - private DeviceField deviceField2; - private DeviceField deviceField20; - private DeviceField deviceField21; - private DeviceField deviceField22; - private DeviceField deviceField23; - private DeviceField deviceField24; - private DeviceField deviceField25; - private DeviceField deviceField26; - private DeviceField deviceField27; - private DeviceField deviceField28; - private DeviceField deviceField29; - private DeviceField deviceField3; - private DeviceField deviceField30; - private DeviceField deviceField31; - private DeviceField deviceField32; - private DeviceField deviceField33; - private DeviceField deviceField34; - private DeviceField deviceField35; - private DeviceField deviceField36; - private DeviceField deviceField37; - private DeviceField deviceField38; - private DeviceField deviceField39; - private DeviceField deviceField4; - private DeviceField deviceField40; - private DeviceField deviceField41; - private DeviceField deviceField42; - private DeviceField deviceField43; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private DeviceField deviceField8; - private DeviceField deviceField9; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel10; - private javax.swing.JPanel jPanel11; - private javax.swing.JPanel jPanel12; - private javax.swing.JPanel jPanel13; - private javax.swing.JPanel jPanel14; - private javax.swing.JPanel jPanel15; - private javax.swing.JPanel jPanel16; - private javax.swing.JPanel jPanel17; - private javax.swing.JPanel jPanel18; - private javax.swing.JPanel jPanel19; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel20; - private javax.swing.JPanel jPanel21; - private javax.swing.JPanel jPanel22; - private javax.swing.JPanel jPanel23; - private javax.swing.JPanel jPanel24; - private javax.swing.JPanel jPanel25; - private javax.swing.JPanel jPanel26; - private javax.swing.JPanel jPanel27; - private javax.swing.JPanel jPanel28; - private javax.swing.JPanel jPanel29; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel30; - private javax.swing.JPanel jPanel31; - private javax.swing.JPanel jPanel32; - private javax.swing.JPanel jPanel33; - private javax.swing.JPanel jPanel34; - private javax.swing.JPanel jPanel35; - private javax.swing.JPanel jPanel36; - private javax.swing.JPanel jPanel37; - private javax.swing.JPanel jPanel38; - private javax.swing.JPanel jPanel39; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel40; - private javax.swing.JPanel jPanel41; - private javax.swing.JPanel jPanel42; - private javax.swing.JPanel jPanel43; - private javax.swing.JPanel jPanel44; - private javax.swing.JPanel jPanel45; - private javax.swing.JPanel jPanel46; - private javax.swing.JPanel jPanel47; - private javax.swing.JPanel jPanel48; - private javax.swing.JPanel jPanel49; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel50; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel9; - private javax.swing.JTabbedPane jTabbedPane1; - private javax.swing.JTabbedPane jTabbedPane2; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel1 = new javax.swing.JPanel(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel2 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceChoice1 = new DeviceChoice(); + jPanel4 = new javax.swing.JPanel(); + deviceField2 = new DeviceField(); + jPanel5 = new javax.swing.JPanel(); + jPanel6 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); + deviceChoice2 = new DeviceChoice(); + jPanel7 = new javax.swing.JPanel(); + deviceField4 = new DeviceField(); + jPanel8 = new javax.swing.JPanel(); + jPanel9 = new javax.swing.JPanel(); + deviceField5 = new DeviceField(); + deviceChoice3 = new DeviceChoice(); + jPanel10 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + jPanel11 = new javax.swing.JPanel(); + jPanel12 = new javax.swing.JPanel(); + deviceField7 = new DeviceField(); + deviceChoice4 = new DeviceChoice(); + jPanel13 = new javax.swing.JPanel(); + deviceField8 = new DeviceField(); + jPanel14 = new javax.swing.JPanel(); + jPanel15 = new javax.swing.JPanel(); + deviceField9 = new DeviceField(); + deviceChoice5 = new DeviceChoice(); + jPanel16 = new javax.swing.JPanel(); + deviceField10 = new DeviceField(); + jPanel17 = new javax.swing.JPanel(); + jPanel18 = new javax.swing.JPanel(); + deviceField11 = new DeviceField(); + deviceChoice6 = new DeviceChoice(); + jPanel19 = new javax.swing.JPanel(); + deviceField12 = new DeviceField(); + jPanel20 = new javax.swing.JPanel(); + jPanel21 = new javax.swing.JPanel(); + deviceField13 = new DeviceField(); + deviceChoice7 = new DeviceChoice(); + jPanel22 = new javax.swing.JPanel(); + deviceField14 = new DeviceField(); + jPanel23 = new javax.swing.JPanel(); + jPanel24 = new javax.swing.JPanel(); + deviceField15 = new DeviceField(); + deviceChoice8 = new DeviceChoice(); + jPanel25 = new javax.swing.JPanel(); + deviceField16 = new DeviceField(); + jTabbedPane2 = new javax.swing.JTabbedPane(); + jPanel26 = new javax.swing.JPanel(); + jPanel27 = new javax.swing.JPanel(); + deviceField17 = new DeviceField(); + deviceChoice9 = new DeviceChoice(); + deviceField33 = new DeviceField(); + jPanel28 = new javax.swing.JPanel(); + deviceField18 = new DeviceField(); + deviceField44 = new DeviceField(); + jPanel29 = new javax.swing.JPanel(); + jPanel30 = new javax.swing.JPanel(); + deviceField19 = new DeviceField(); + deviceChoice10 = new DeviceChoice(); + deviceField34 = new DeviceField(); + jPanel31 = new javax.swing.JPanel(); + deviceField20 = new DeviceField(); + deviceField45 = new DeviceField(); + jPanel32 = new javax.swing.JPanel(); + jPanel33 = new javax.swing.JPanel(); + deviceField21 = new DeviceField(); + deviceChoice11 = new DeviceChoice(); + deviceField35 = new DeviceField(); + jPanel34 = new javax.swing.JPanel(); + deviceField22 = new DeviceField(); + deviceField46 = new DeviceField(); + jPanel35 = new javax.swing.JPanel(); + jPanel36 = new javax.swing.JPanel(); + deviceField23 = new DeviceField(); + deviceChoice12 = new DeviceChoice(); + deviceField36 = new DeviceField(); + jPanel37 = new javax.swing.JPanel(); + deviceField24 = new DeviceField(); + deviceField47 = new DeviceField(); + jPanel38 = new javax.swing.JPanel(); + jPanel39 = new javax.swing.JPanel(); + deviceField25 = new DeviceField(); + deviceChoice13 = new DeviceChoice(); + deviceField37 = new DeviceField(); + jPanel40 = new javax.swing.JPanel(); + deviceField26 = new DeviceField(); + deviceField48 = new DeviceField(); + jPanel41 = new javax.swing.JPanel(); + jPanel42 = new javax.swing.JPanel(); + deviceField27 = new DeviceField(); + deviceChoice14 = new DeviceChoice(); + deviceField38 = new DeviceField(); + jPanel43 = new javax.swing.JPanel(); + deviceField28 = new DeviceField(); + deviceField49 = new DeviceField(); + jPanel44 = new javax.swing.JPanel(); + jPanel45 = new javax.swing.JPanel(); + deviceField29 = new DeviceField(); + deviceChoice15 = new DeviceChoice(); + deviceField39 = new DeviceField(); + jPanel46 = new javax.swing.JPanel(); + deviceField30 = new DeviceField(); + deviceField50 = new DeviceField(); + jPanel47 = new javax.swing.JPanel(); + jPanel48 = new javax.swing.JPanel(); + deviceField31 = new DeviceField(); + deviceChoice16 = new DeviceChoice(); + deviceField40 = new DeviceField(); + jPanel49 = new javax.swing.JPanel(); + deviceField32 = new DeviceField(); + deviceField51 = new DeviceField(); + jPanel50 = new javax.swing.JPanel(); + deviceField41 = new DeviceField(); + deviceField43 = new DeviceField(); + deviceField42 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceType("MARTE2_EXPR"); + setHeight(400); + setWidth(900); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + jPanel1.setLayout(new java.awt.GridLayout(2, 1)); + + jPanel2.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField1.setOffsetNid(32); + jPanel3.add(deviceField1); + + deviceChoice1.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString(""); + deviceChoice1.setOffsetNid(31); + deviceChoice1.setUpdateIdentifier(""); + jPanel3.add(deviceChoice1); + + jPanel2.add(jPanel3); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Value:"); + deviceField2.setNumCols(25); + deviceField2.setOffsetNid(34); + jPanel4.add(deviceField2); + + jPanel2.add(jPanel4); + + jTabbedPane1.addTab("In1", jPanel2); + + jPanel5.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField3.setOffsetNid(39); + jPanel6.add(deviceField3); + + deviceChoice2.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString(""); + deviceChoice2.setOffsetNid(38); + deviceChoice2.setUpdateIdentifier(""); + jPanel6.add(deviceChoice2); + + jPanel5.add(jPanel6); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Value:"); + deviceField4.setNumCols(25); + deviceField4.setOffsetNid(41); + jPanel7.add(deviceField4); + + jPanel5.add(jPanel7); + + jTabbedPane1.addTab("In2", jPanel5); + + jPanel8.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField5.setOffsetNid(46); + jPanel9.add(deviceField5); + + deviceChoice3.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString(""); + deviceChoice3.setOffsetNid(45); + deviceChoice3.setUpdateIdentifier(""); + jPanel9.add(deviceChoice3); + + jPanel8.add(jPanel9); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Value:"); + deviceField6.setNumCols(25); + deviceField6.setOffsetNid(48); + jPanel10.add(deviceField6); + + jPanel8.add(jPanel10); + + jTabbedPane1.addTab("In3", jPanel8); + + jPanel11.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField7.setOffsetNid(53); + jPanel12.add(deviceField7); + + deviceChoice4.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice4.setIdentifier(""); + deviceChoice4.setLabelString(""); + deviceChoice4.setOffsetNid(52); + deviceChoice4.setUpdateIdentifier(""); + jPanel12.add(deviceChoice4); + + jPanel11.add(jPanel12); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Value:"); + deviceField8.setNumCols(25); + deviceField8.setOffsetNid(55); + jPanel13.add(deviceField8); + + jPanel11.add(jPanel13); + + jTabbedPane1.addTab("In4", jPanel11); + + jPanel14.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField9.setOffsetNid(60); + jPanel15.add(deviceField9); + + deviceChoice5.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice5.setIdentifier(""); + deviceChoice5.setLabelString(""); + deviceChoice5.setOffsetNid(59); + deviceChoice5.setUpdateIdentifier(""); + jPanel15.add(deviceChoice5); + + jPanel14.add(jPanel15); + + deviceField10.setIdentifier(""); + deviceField10.setLabelString("Value:"); + deviceField10.setNumCols(25); + deviceField10.setOffsetNid(62); + jPanel16.add(deviceField10); + + jPanel14.add(jPanel16); + + jTabbedPane1.addTab("In5", jPanel14); + + jPanel17.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField11.setIdentifier(""); + deviceField11.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField11.setOffsetNid(67); + jPanel18.add(deviceField11); + + deviceChoice6.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice6.setIdentifier(""); + deviceChoice6.setLabelString(""); + deviceChoice6.setOffsetNid(66); + deviceChoice6.setUpdateIdentifier(""); + jPanel18.add(deviceChoice6); + + jPanel17.add(jPanel18); + + deviceField12.setIdentifier(""); + deviceField12.setLabelString("Value:"); + deviceField12.setNumCols(25); + deviceField12.setOffsetNid(69); + jPanel19.add(deviceField12); + + jPanel17.add(jPanel19); + + jTabbedPane1.addTab("In6", jPanel17); + + jPanel20.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField13.setIdentifier(""); + deviceField13.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField13.setOffsetNid(74); + jPanel21.add(deviceField13); + + deviceChoice7.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice7.setIdentifier(""); + deviceChoice7.setLabelString(""); + deviceChoice7.setOffsetNid(73); + deviceChoice7.setUpdateIdentifier(""); + jPanel21.add(deviceChoice7); + + jPanel20.add(jPanel21); + + deviceField14.setIdentifier(""); + deviceField14.setLabelString("Value:"); + deviceField14.setNumCols(25); + deviceField14.setOffsetNid(76); + jPanel22.add(deviceField14); + + jPanel20.add(jPanel22); + + jTabbedPane1.addTab("In7", jPanel20); + + jPanel23.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField15.setIdentifier(""); + deviceField15.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField15.setOffsetNid(81); + jPanel24.add(deviceField15); + + deviceChoice8.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice8.setIdentifier(""); + deviceChoice8.setLabelString(""); + deviceChoice8.setOffsetNid(80); + deviceChoice8.setUpdateIdentifier(""); + jPanel24.add(deviceChoice8); + + jPanel23.add(jPanel24); + + deviceField16.setIdentifier(""); + deviceField16.setLabelString("Value:"); + deviceField16.setNumCols(25); + deviceField16.setOffsetNid(83); + jPanel25.add(deviceField16); + + jPanel23.add(jPanel25); + + jTabbedPane1.addTab("In8", jPanel23); + + jPanel1.add(jTabbedPane1); + + jPanel26.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField17.setIdentifier(""); + deviceField17.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField17.setOffsetNid(97); + jPanel27.add(deviceField17); + + deviceChoice9.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice9.setIdentifier(""); + deviceChoice9.setLabelString("Type: "); + deviceChoice9.setOffsetNid(95); + deviceChoice9.setUpdateIdentifier(""); + jPanel27.add(deviceChoice9); + + deviceField33.setIdentifier(""); + deviceField33.setLabelString("Seg. Len (0 to disable writing):"); + deviceField33.setNumCols(4); + deviceField33.setOffsetNid(98); + jPanel27.add(deviceField33); + + jPanel26.add(jPanel27); + + deviceField18.setIdentifier(""); + deviceField18.setLabelString("Expression:"); + deviceField18.setNumCols(35); + deviceField18.setOffsetNid(104); + deviceField18.setTextOnly(true); + jPanel28.add(deviceField18); + + deviceField44.setIdentifier(""); + deviceField44.setLabelString("Stream Name: "); + deviceField44.setOffsetNid(99); + deviceField44.setTextOnly(true); + jPanel28.add(deviceField44); + + jPanel26.add(jPanel28); + + jTabbedPane2.addTab("Out1", jPanel26); + + jPanel29.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField19.setIdentifier(""); + deviceField19.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField19.setOffsetNid(109); + jPanel30.add(deviceField19); + + deviceChoice10.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice10.setIdentifier(""); + deviceChoice10.setLabelString("Type: "); + deviceChoice10.setOffsetNid(107); + deviceChoice10.setUpdateIdentifier(""); + jPanel30.add(deviceChoice10); + + deviceField34.setIdentifier(""); + deviceField34.setLabelString("Seg. Len (0 to disable writing):"); + deviceField34.setNumCols(4); + deviceField34.setOffsetNid(109); + jPanel30.add(deviceField34); + + jPanel29.add(jPanel30); + + deviceField20.setIdentifier(""); + deviceField20.setLabelString("Expression:"); + deviceField20.setNumCols(35); + deviceField20.setOffsetNid(116); + deviceField20.setTextOnly(true); + jPanel31.add(deviceField20); + + deviceField45.setIdentifier(""); + deviceField45.setLabelString("Stream Name: "); + deviceField45.setOffsetNid(111); + deviceField45.setTextOnly(true); + jPanel31.add(deviceField45); + + jPanel29.add(jPanel31); + + jTabbedPane2.addTab("Out2", jPanel29); + + jPanel32.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField21.setIdentifier(""); + deviceField21.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField21.setOffsetNid(121); + jPanel33.add(deviceField21); + + deviceChoice11.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice11.setIdentifier(""); + deviceChoice11.setLabelString("Type: "); + deviceChoice11.setOffsetNid(119); + deviceChoice11.setUpdateIdentifier(""); + jPanel33.add(deviceChoice11); + + deviceField35.setIdentifier(""); + deviceField35.setLabelString("Seg. Len (0 to disable writing):"); + deviceField35.setNumCols(4); + deviceField35.setOffsetNid(120); + jPanel33.add(deviceField35); + + jPanel32.add(jPanel33); + + deviceField22.setIdentifier(""); + deviceField22.setLabelString("Expression:"); + deviceField22.setNumCols(35); + deviceField22.setOffsetNid(128); + deviceField22.setTextOnly(true); + jPanel34.add(deviceField22); + + deviceField46.setIdentifier(""); + deviceField46.setLabelString("Stream Name: "); + deviceField46.setOffsetNid(123); + deviceField46.setTextOnly(true); + jPanel34.add(deviceField46); + + jPanel32.add(jPanel34); + + jTabbedPane2.addTab("Out3", jPanel32); + + jPanel35.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField23.setIdentifier(""); + deviceField23.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField23.setOffsetNid(133); + jPanel36.add(deviceField23); + + deviceChoice12.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice12.setIdentifier(""); + deviceChoice12.setLabelString("Type: "); + deviceChoice12.setOffsetNid(131); + deviceChoice12.setUpdateIdentifier(""); + jPanel36.add(deviceChoice12); + + deviceField36.setIdentifier(""); + deviceField36.setLabelString("Seg. Len (0 to disable writing):"); + deviceField36.setNumCols(4); + deviceField36.setOffsetNid(131); + jPanel36.add(deviceField36); + + jPanel35.add(jPanel36); + + deviceField24.setIdentifier(""); + deviceField24.setLabelString("Expression:"); + deviceField24.setNumCols(35); + deviceField24.setOffsetNid(140); + deviceField24.setTextOnly(true); + jPanel37.add(deviceField24); + + deviceField47.setIdentifier(""); + deviceField47.setLabelString("Stream Name: "); + deviceField47.setOffsetNid(135); + deviceField47.setTextOnly(true); + jPanel37.add(deviceField47); + + jPanel35.add(jPanel37); + + jTabbedPane2.addTab("Out4", jPanel35); + + jPanel38.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField25.setIdentifier(""); + deviceField25.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField25.setOffsetNid(145); + jPanel39.add(deviceField25); + + deviceChoice13.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice13.setIdentifier(""); + deviceChoice13.setLabelString("Type: "); + deviceChoice13.setOffsetNid(143); + deviceChoice13.setUpdateIdentifier(""); + jPanel39.add(deviceChoice13); + + deviceField37.setIdentifier(""); + deviceField37.setLabelString("Seg. Len (0 to disable writing):"); + deviceField37.setNumCols(4); + deviceField37.setOffsetNid(142); + jPanel39.add(deviceField37); + + jPanel38.add(jPanel39); + + deviceField26.setIdentifier(""); + deviceField26.setLabelString("Expression:"); + deviceField26.setNumCols(35); + deviceField26.setOffsetNid(152); + deviceField26.setTextOnly(true); + jPanel40.add(deviceField26); + + deviceField48.setIdentifier(""); + deviceField48.setLabelString("Stream Name: "); + deviceField48.setOffsetNid(147); + deviceField48.setTextOnly(true); + jPanel40.add(deviceField48); + + jPanel38.add(jPanel40); + + jTabbedPane2.addTab("Out5", jPanel38); + + jPanel41.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField27.setIdentifier(""); + deviceField27.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField27.setOffsetNid(157); + jPanel42.add(deviceField27); + + deviceChoice14.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice14.setIdentifier(""); + deviceChoice14.setLabelString("Type: "); + deviceChoice14.setOffsetNid(155); + deviceChoice14.setUpdateIdentifier(""); + jPanel42.add(deviceChoice14); + + deviceField38.setIdentifier(""); + deviceField38.setLabelString("Seg. Len (0 to disable writing):"); + deviceField38.setNumCols(4); + deviceField38.setOffsetNid(153); + jPanel42.add(deviceField38); + + jPanel41.add(jPanel42); + + deviceField28.setIdentifier(""); + deviceField28.setLabelString("Expression:"); + deviceField28.setNumCols(35); + deviceField28.setOffsetNid(164); + deviceField28.setTextOnly(true); + jPanel43.add(deviceField28); + + deviceField49.setIdentifier(""); + deviceField49.setLabelString("Stream Name: "); + deviceField49.setOffsetNid(159); + deviceField49.setTextOnly(true); + jPanel43.add(deviceField49); + + jPanel41.add(jPanel43); + + jTabbedPane2.addTab("Out6", jPanel41); + + jPanel44.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField29.setIdentifier(""); + deviceField29.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField29.setOffsetNid(169); + jPanel45.add(deviceField29); + + deviceChoice15.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice15.setIdentifier(""); + deviceChoice15.setLabelString("Type: "); + deviceChoice15.setOffsetNid(167); + deviceChoice15.setUpdateIdentifier(""); + jPanel45.add(deviceChoice15); + + deviceField39.setIdentifier(""); + deviceField39.setLabelString("Seg. Len (0 to disable writing):"); + deviceField39.setNumCols(4); + deviceField39.setOffsetNid(164); + jPanel45.add(deviceField39); + + jPanel44.add(jPanel45); + + deviceField30.setIdentifier(""); + deviceField30.setLabelString("Expression:"); + deviceField30.setNumCols(35); + deviceField30.setOffsetNid(176); + deviceField30.setTextOnly(true); + jPanel46.add(deviceField30); + + deviceField50.setIdentifier(""); + deviceField50.setLabelString("Stream Name: "); + deviceField50.setOffsetNid(171); + deviceField50.setTextOnly(true); + jPanel46.add(deviceField50); + + jPanel44.add(jPanel46); + + jTabbedPane2.addTab("Out7", jPanel44); + + jPanel47.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField31.setIdentifier(""); + deviceField31.setLabelString("Dimensions (0 for scalar, array otherwise):"); + deviceField31.setOffsetNid(181); + jPanel48.add(deviceField31); + + deviceChoice16.setChoiceItems(new String[] {"int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float32", "float64"}); + deviceChoice16.setIdentifier(""); + deviceChoice16.setLabelString("Type: "); + deviceChoice16.setOffsetNid(179); + deviceChoice16.setUpdateIdentifier(""); + jPanel48.add(deviceChoice16); + + deviceField40.setIdentifier(""); + deviceField40.setLabelString("Seg. Len (0 to disable writing):"); + deviceField40.setNumCols(4); + deviceField40.setOffsetNid(175); + jPanel48.add(deviceField40); + + jPanel47.add(jPanel48); + + deviceField32.setIdentifier(""); + deviceField32.setLabelString("Expression:"); + deviceField32.setNumCols(35); + deviceField32.setOffsetNid(188); + deviceField32.setTextOnly(true); + jPanel49.add(deviceField32); + + deviceField51.setIdentifier(""); + deviceField51.setLabelString("Stream Name: "); + deviceField51.setOffsetNid(183); + deviceField51.setTextOnly(true); + jPanel49.add(deviceField51); + + jPanel47.add(jPanel49); + + jTabbedPane2.addTab("Out8", jPanel47); + + jPanel1.add(jTabbedPane2); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + deviceField41.setIdentifier(""); + deviceField41.setLabelString("Timebase:"); + deviceField41.setNumCols(25); + deviceField41.setOffsetNid(3); + jPanel50.add(deviceField41); + + deviceField43.setIdentifier(""); + deviceField43.setLabelString("Timebase Division (Valid if timebase on another thread):"); + deviceField43.setNumCols(4); + deviceField43.setOffsetNid(181); + jPanel50.add(deviceField43); + + deviceField42.setIdentifier(""); + deviceField42.setLabelString("Storage CPUs: "); + deviceField42.setNumCols(4); + deviceField42.setOffsetNid(92); + jPanel50.add(deviceField42); + + getContentPane().add(jPanel50, java.awt.BorderLayout.PAGE_START); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceChoice deviceChoice10; + private DeviceChoice deviceChoice11; + private DeviceChoice deviceChoice12; + private DeviceChoice deviceChoice13; + private DeviceChoice deviceChoice14; + private DeviceChoice deviceChoice15; + private DeviceChoice deviceChoice16; + private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice3; + private DeviceChoice deviceChoice4; + private DeviceChoice deviceChoice5; + private DeviceChoice deviceChoice6; + private DeviceChoice deviceChoice7; + private DeviceChoice deviceChoice8; + private DeviceChoice deviceChoice9; + private DeviceField deviceField1; + private DeviceField deviceField10; + private DeviceField deviceField11; + private DeviceField deviceField12; + private DeviceField deviceField13; + private DeviceField deviceField14; + private DeviceField deviceField15; + private DeviceField deviceField16; + private DeviceField deviceField17; + private DeviceField deviceField18; + private DeviceField deviceField19; + private DeviceField deviceField2; + private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; + private DeviceField deviceField23; + private DeviceField deviceField24; + private DeviceField deviceField25; + private DeviceField deviceField26; + private DeviceField deviceField27; + private DeviceField deviceField28; + private DeviceField deviceField29; + private DeviceField deviceField3; + private DeviceField deviceField30; + private DeviceField deviceField31; + private DeviceField deviceField32; + private DeviceField deviceField33; + private DeviceField deviceField34; + private DeviceField deviceField35; + private DeviceField deviceField36; + private DeviceField deviceField37; + private DeviceField deviceField38; + private DeviceField deviceField39; + private DeviceField deviceField4; + private DeviceField deviceField40; + private DeviceField deviceField41; + private DeviceField deviceField42; + private DeviceField deviceField43; + private DeviceField deviceField44; + private DeviceField deviceField45; + private DeviceField deviceField46; + private DeviceField deviceField47; + private DeviceField deviceField48; + private DeviceField deviceField49; + private DeviceField deviceField5; + private DeviceField deviceField50; + private DeviceField deviceField51; + private DeviceField deviceField6; + private DeviceField deviceField7; + private DeviceField deviceField8; + private DeviceField deviceField9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel10; + private javax.swing.JPanel jPanel11; + private javax.swing.JPanel jPanel12; + private javax.swing.JPanel jPanel13; + private javax.swing.JPanel jPanel14; + private javax.swing.JPanel jPanel15; + private javax.swing.JPanel jPanel16; + private javax.swing.JPanel jPanel17; + private javax.swing.JPanel jPanel18; + private javax.swing.JPanel jPanel19; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel20; + private javax.swing.JPanel jPanel21; + private javax.swing.JPanel jPanel22; + private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; + private javax.swing.JPanel jPanel25; + private javax.swing.JPanel jPanel26; + private javax.swing.JPanel jPanel27; + private javax.swing.JPanel jPanel28; + private javax.swing.JPanel jPanel29; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel30; + private javax.swing.JPanel jPanel31; + private javax.swing.JPanel jPanel32; + private javax.swing.JPanel jPanel33; + private javax.swing.JPanel jPanel34; + private javax.swing.JPanel jPanel35; + private javax.swing.JPanel jPanel36; + private javax.swing.JPanel jPanel37; + private javax.swing.JPanel jPanel38; + private javax.swing.JPanel jPanel39; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel40; + private javax.swing.JPanel jPanel41; + private javax.swing.JPanel jPanel42; + private javax.swing.JPanel jPanel43; + private javax.swing.JPanel jPanel44; + private javax.swing.JPanel jPanel45; + private javax.swing.JPanel jPanel46; + private javax.swing.JPanel jPanel47; + private javax.swing.JPanel jPanel48; + private javax.swing.JPanel jPanel49; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel50; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel9; + private javax.swing.JTabbedPane jTabbedPane1; + private javax.swing.JTabbedPane jTabbedPane2; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_FFTSetup.java b/java/jdevices/src/main/java/MARTE2_FFTSetup.java index 8a23f994c2..031121bdc0 100644 --- a/java/jdevices/src/main/java/MARTE2_FFTSetup.java +++ b/java/jdevices/src/main/java/MARTE2_FFTSetup.java @@ -29,91 +29,107 @@ public MARTE2_FFTSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceButtons1 = new DeviceButtons(); - jPanel2 = new javax.swing.JPanel(); - jPanel5 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField5 = new DeviceField(); - jPanel6 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - deviceChoice2 = new DeviceChoice(); - jPanel1 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceField2 = new DeviceField(); - deviceField6 = new DeviceField(); - jPanel4 = new javax.swing.JPanel(); - deviceField3 = new DeviceField(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("MARTe2 FFT GAM"); - setDeviceType("MARTE2_FFT"); - setHeight(300); - setWidth(800); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - jPanel2.setLayout(new java.awt.GridLayout(2, 1)); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Num. Samples"); - deviceField1.setNumCols(4); - deviceField1.setOffsetNid(7); - jPanel5.add(deviceField1); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("MdsWriter CPU Mask: "); - deviceField5.setNumCols(4); - deviceField5.setOffsetNid(22); - jPanel5.add(deviceField5); - jPanel2.add(jPanel5); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Out Segment len (0 to disable writing in tree):"); - deviceField4.setNumCols(5); - deviceField4.setOffsetNid(28); - jPanel6.add(deviceField4); - deviceChoice2.setChoiceItems(new String[] - { "int16", "int32", "float32", "float64" }); - deviceChoice2.setIdentifier(""); - deviceChoice2.setLabelString("Input type: "); - deviceChoice2.setOffsetNid(10); - deviceChoice2.setUpdateIdentifier(""); - jPanel6.add(deviceChoice2); - jPanel2.add(jPanel6); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - jPanel1.setLayout(new java.awt.GridLayout(2, 1)); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Timebase: "); - deviceField2.setNumCols(35); - deviceField2.setOffsetNid(3); - jPanel3.add(deviceField2); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Timebase div:"); - deviceField6.setNumCols(4); - deviceField6.setOffsetNid(39); - jPanel3.add(deviceField6); - jPanel1.add(jPanel3); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Input"); - deviceField3.setNumCols(35); - deviceField3.setOffsetNid(13); - jPanel4.add(deviceField3); - jPanel1.add(jPanel4); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice2; - private DeviceField deviceField1; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel6; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel2 = new javax.swing.JPanel(); + jPanel5 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField5 = new DeviceField(); + jPanel6 = new javax.swing.JPanel(); + deviceField4 = new DeviceField(); + deviceChoice2 = new DeviceChoice(); + jPanel1 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + deviceField2 = new DeviceField(); + deviceField6 = new DeviceField(); + jPanel4 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 FFT GAM"); + setDeviceType("MARTE2_FFT"); + setHeight(300); + setWidth(800); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + jPanel2.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Num. Samples"); + deviceField1.setNumCols(4); + deviceField1.setOffsetNid(7); + jPanel5.add(deviceField1); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("MdsWriter CPU Mask: "); + deviceField5.setNumCols(4); + deviceField5.setOffsetNid(22); + jPanel5.add(deviceField5); + + jPanel2.add(jPanel5); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Out Segment len (0 to disable writing in tree):"); + deviceField4.setNumCols(5); + deviceField4.setOffsetNid(28); + jPanel6.add(deviceField4); + + deviceChoice2.setChoiceItems(new String[] {"int16", "int32", "float32", "float64"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString("Input type: "); + deviceChoice2.setOffsetNid(10); + deviceChoice2.setUpdateIdentifier(""); + jPanel6.add(deviceChoice2); + + jPanel2.add(jPanel6); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + jPanel1.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Timebase: "); + deviceField2.setNumCols(35); + deviceField2.setOffsetNid(3); + jPanel3.add(deviceField2); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Timebase div:"); + deviceField6.setNumCols(4); + deviceField6.setOffsetNid(41); + jPanel3.add(deviceField6); + + jPanel1.add(jPanel3); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Input"); + deviceField3.setNumCols(35); + deviceField3.setOffsetNid(13); + jPanel4.add(deviceField3); + + jPanel1.add(jPanel4); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice2; + private DeviceField deviceField1; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_GAMSetup.java b/java/jdevices/src/main/java/MARTE2_GAMSetup.java index 8c4bf0088d..4e96f3c1f2 100644 --- a/java/jdevices/src/main/java/MARTE2_GAMSetup.java +++ b/java/jdevices/src/main/java/MARTE2_GAMSetup.java @@ -29,1737 +29,2027 @@ public MARTE2_GAMSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceButtons1 = new DeviceButtons(); - jPanel1 = new javax.swing.JPanel(); - jPanel2 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField2 = new DeviceField(); - deviceField67 = new DeviceField(); - jTabbedPane1 = new javax.swing.JTabbedPane(); - jScrollPane1 = new javax.swing.JScrollPane(); - jPanel4 = new javax.swing.JPanel(); - jPanel14 = new javax.swing.JPanel(); - jPanel15 = new javax.swing.JPanel(); - deviceField7 = new DeviceField(); - jPanel16 = new javax.swing.JPanel(); - deviceField8 = new DeviceField(); - jPanel17 = new javax.swing.JPanel(); - jPanel18 = new javax.swing.JPanel(); - deviceField9 = new DeviceField(); - jPanel19 = new javax.swing.JPanel(); - deviceField10 = new DeviceField(); - jPanel20 = new javax.swing.JPanel(); - jPanel21 = new javax.swing.JPanel(); - deviceField11 = new DeviceField(); - jPanel22 = new javax.swing.JPanel(); - deviceField12 = new DeviceField(); - jPanel23 = new javax.swing.JPanel(); - jPanel24 = new javax.swing.JPanel(); - deviceField13 = new DeviceField(); - jPanel25 = new javax.swing.JPanel(); - deviceField14 = new DeviceField(); - jPanel26 = new javax.swing.JPanel(); - jPanel27 = new javax.swing.JPanel(); - deviceField15 = new DeviceField(); - jPanel28 = new javax.swing.JPanel(); - deviceField16 = new DeviceField(); - jPanel29 = new javax.swing.JPanel(); - jPanel30 = new javax.swing.JPanel(); - deviceField17 = new DeviceField(); - jPanel31 = new javax.swing.JPanel(); - deviceField18 = new DeviceField(); - jPanel32 = new javax.swing.JPanel(); - jPanel33 = new javax.swing.JPanel(); - deviceField19 = new DeviceField(); - jPanel34 = new javax.swing.JPanel(); - deviceField20 = new DeviceField(); - jPanel35 = new javax.swing.JPanel(); - jPanel36 = new javax.swing.JPanel(); - deviceField21 = new DeviceField(); - jPanel37 = new javax.swing.JPanel(); - deviceField22 = new DeviceField(); - jPanel38 = new javax.swing.JPanel(); - jPanel39 = new javax.swing.JPanel(); - deviceField23 = new DeviceField(); - jPanel40 = new javax.swing.JPanel(); - deviceField24 = new DeviceField(); - jPanel41 = new javax.swing.JPanel(); - jPanel42 = new javax.swing.JPanel(); - deviceField25 = new DeviceField(); - jPanel43 = new javax.swing.JPanel(); - deviceField26 = new DeviceField(); - jPanel44 = new javax.swing.JPanel(); - jPanel45 = new javax.swing.JPanel(); - deviceField27 = new DeviceField(); - jPanel46 = new javax.swing.JPanel(); - deviceField28 = new DeviceField(); - jPanel47 = new javax.swing.JPanel(); - jPanel48 = new javax.swing.JPanel(); - deviceField29 = new DeviceField(); - jPanel49 = new javax.swing.JPanel(); - deviceField30 = new DeviceField(); - jPanel50 = new javax.swing.JPanel(); - jPanel51 = new javax.swing.JPanel(); - deviceField31 = new DeviceField(); - jPanel52 = new javax.swing.JPanel(); - deviceField32 = new DeviceField(); - jPanel53 = new javax.swing.JPanel(); - jPanel54 = new javax.swing.JPanel(); - deviceField33 = new DeviceField(); - jPanel55 = new javax.swing.JPanel(); - deviceField34 = new DeviceField(); - jPanel56 = new javax.swing.JPanel(); - jPanel57 = new javax.swing.JPanel(); - deviceField35 = new DeviceField(); - jPanel58 = new javax.swing.JPanel(); - deviceField36 = new DeviceField(); - jPanel59 = new javax.swing.JPanel(); - jPanel60 = new javax.swing.JPanel(); - deviceField37 = new DeviceField(); - jPanel61 = new javax.swing.JPanel(); - deviceField38 = new DeviceField(); - jScrollPane2 = new javax.swing.JScrollPane(); - jPanel3 = new javax.swing.JPanel(); - jPanel5 = new javax.swing.JPanel(); - jPanel6 = new javax.swing.JPanel(); - deviceChoice1 = new DeviceChoice(); - deviceField3 = new DeviceField(); - deviceChoice2 = new DeviceChoice(); - jPanel7 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - jPanel9 = new javax.swing.JPanel(); - deviceChoice3 = new DeviceChoice(); - deviceField5 = new DeviceField(); - deviceChoice4 = new DeviceChoice(); - jPanel10 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - jPanel11 = new javax.swing.JPanel(); - jPanel12 = new javax.swing.JPanel(); - deviceChoice5 = new DeviceChoice(); - deviceField39 = new DeviceField(); - deviceChoice6 = new DeviceChoice(); - jPanel13 = new javax.swing.JPanel(); - deviceField40 = new DeviceField(); - jPanel62 = new javax.swing.JPanel(); - jPanel63 = new javax.swing.JPanel(); - deviceChoice7 = new DeviceChoice(); - deviceField41 = new DeviceField(); - deviceChoice8 = new DeviceChoice(); - jPanel64 = new javax.swing.JPanel(); - deviceField42 = new DeviceField(); - jPanel65 = new javax.swing.JPanel(); - jPanel66 = new javax.swing.JPanel(); - deviceChoice9 = new DeviceChoice(); - deviceField43 = new DeviceField(); - deviceChoice10 = new DeviceChoice(); - jPanel67 = new javax.swing.JPanel(); - deviceField44 = new DeviceField(); - jPanel68 = new javax.swing.JPanel(); - jPanel69 = new javax.swing.JPanel(); - deviceChoice11 = new DeviceChoice(); - deviceField45 = new DeviceField(); - deviceChoice12 = new DeviceChoice(); - jPanel70 = new javax.swing.JPanel(); - deviceField46 = new DeviceField(); - jPanel71 = new javax.swing.JPanel(); - jPanel72 = new javax.swing.JPanel(); - deviceChoice13 = new DeviceChoice(); - deviceField47 = new DeviceField(); - deviceChoice14 = new DeviceChoice(); - jPanel73 = new javax.swing.JPanel(); - deviceField48 = new DeviceField(); - jPanel74 = new javax.swing.JPanel(); - jPanel75 = new javax.swing.JPanel(); - deviceChoice15 = new DeviceChoice(); - deviceField49 = new DeviceField(); - deviceChoice16 = new DeviceChoice(); - jPanel76 = new javax.swing.JPanel(); - deviceField50 = new DeviceField(); - jPanel77 = new javax.swing.JPanel(); - jPanel78 = new javax.swing.JPanel(); - deviceChoice17 = new DeviceChoice(); - deviceField51 = new DeviceField(); - deviceChoice18 = new DeviceChoice(); - jPanel79 = new javax.swing.JPanel(); - deviceField52 = new DeviceField(); - jPanel80 = new javax.swing.JPanel(); - jPanel81 = new javax.swing.JPanel(); - deviceChoice19 = new DeviceChoice(); - deviceField53 = new DeviceField(); - deviceChoice20 = new DeviceChoice(); - jPanel82 = new javax.swing.JPanel(); - deviceField54 = new DeviceField(); - jPanel83 = new javax.swing.JPanel(); - jPanel84 = new javax.swing.JPanel(); - deviceChoice21 = new DeviceChoice(); - deviceField55 = new DeviceField(); - deviceChoice22 = new DeviceChoice(); - jPanel85 = new javax.swing.JPanel(); - deviceField56 = new DeviceField(); - jPanel86 = new javax.swing.JPanel(); - jPanel87 = new javax.swing.JPanel(); - deviceChoice23 = new DeviceChoice(); - deviceField57 = new DeviceField(); - deviceChoice24 = new DeviceChoice(); - jPanel88 = new javax.swing.JPanel(); - deviceField58 = new DeviceField(); - jPanel89 = new javax.swing.JPanel(); - jPanel90 = new javax.swing.JPanel(); - deviceChoice25 = new DeviceChoice(); - deviceField59 = new DeviceField(); - deviceChoice26 = new DeviceChoice(); - jPanel91 = new javax.swing.JPanel(); - deviceField60 = new DeviceField(); - jPanel92 = new javax.swing.JPanel(); - jPanel93 = new javax.swing.JPanel(); - deviceChoice27 = new DeviceChoice(); - deviceField61 = new DeviceField(); - deviceChoice28 = new DeviceChoice(); - jPanel94 = new javax.swing.JPanel(); - deviceField62 = new DeviceField(); - jPanel95 = new javax.swing.JPanel(); - jPanel96 = new javax.swing.JPanel(); - deviceChoice29 = new DeviceChoice(); - deviceField63 = new DeviceField(); - deviceChoice30 = new DeviceChoice(); - jPanel97 = new javax.swing.JPanel(); - deviceField64 = new DeviceField(); - jPanel98 = new javax.swing.JPanel(); - jPanel99 = new javax.swing.JPanel(); - deviceChoice31 = new DeviceChoice(); - deviceField65 = new DeviceField(); - deviceChoice32 = new DeviceChoice(); - jPanel100 = new javax.swing.JPanel(); - deviceField66 = new DeviceField(); - jScrollPane3 = new javax.swing.JScrollPane(); - jPanel101 = new javax.swing.JPanel(); - jPanel102 = new javax.swing.JPanel(); - deviceField69 = new DeviceField(); - deviceField68 = new DeviceField(); - deviceChoice34 = new DeviceChoice(); - deviceField70 = new DeviceField(); - jPanel103 = new javax.swing.JPanel(); - deviceField71 = new DeviceField(); - deviceField72 = new DeviceField(); - deviceChoice35 = new DeviceChoice(); - deviceField73 = new DeviceField(); - jPanel104 = new javax.swing.JPanel(); - deviceField74 = new DeviceField(); - deviceField75 = new DeviceField(); - deviceChoice36 = new DeviceChoice(); - deviceField76 = new DeviceField(); - jPanel105 = new javax.swing.JPanel(); - deviceField77 = new DeviceField(); - deviceField78 = new DeviceField(); - deviceChoice37 = new DeviceChoice(); - deviceField79 = new DeviceField(); - jPanel106 = new javax.swing.JPanel(); - deviceField80 = new DeviceField(); - deviceField81 = new DeviceField(); - deviceChoice38 = new DeviceChoice(); - deviceField82 = new DeviceField(); - jPanel107 = new javax.swing.JPanel(); - deviceField83 = new DeviceField(); - deviceField84 = new DeviceField(); - deviceChoice39 = new DeviceChoice(); - deviceField85 = new DeviceField(); - jPanel108 = new javax.swing.JPanel(); - deviceField86 = new DeviceField(); - deviceField87 = new DeviceField(); - deviceChoice40 = new DeviceChoice(); - deviceField88 = new DeviceField(); - jPanel109 = new javax.swing.JPanel(); - deviceField89 = new DeviceField(); - deviceField90 = new DeviceField(); - deviceChoice41 = new DeviceChoice(); - deviceField91 = new DeviceField(); - jPanel110 = new javax.swing.JPanel(); - deviceField92 = new DeviceField(); - deviceField93 = new DeviceField(); - deviceChoice42 = new DeviceChoice(); - deviceField94 = new DeviceField(); - jPanel111 = new javax.swing.JPanel(); - deviceField95 = new DeviceField(); - deviceField96 = new DeviceField(); - deviceChoice43 = new DeviceChoice(); - deviceField97 = new DeviceField(); - jPanel112 = new javax.swing.JPanel(); - deviceField98 = new DeviceField(); - deviceField99 = new DeviceField(); - deviceChoice44 = new DeviceChoice(); - deviceField100 = new DeviceField(); - jPanel113 = new javax.swing.JPanel(); - deviceField101 = new DeviceField(); - deviceField102 = new DeviceField(); - deviceChoice45 = new DeviceChoice(); - deviceField103 = new DeviceField(); - jPanel114 = new javax.swing.JPanel(); - deviceField104 = new DeviceField(); - deviceField105 = new DeviceField(); - deviceChoice46 = new DeviceChoice(); - deviceField106 = new DeviceField(); - jPanel115 = new javax.swing.JPanel(); - deviceField107 = new DeviceField(); - deviceField108 = new DeviceField(); - deviceChoice47 = new DeviceChoice(); - deviceField109 = new DeviceField(); - jPanel116 = new javax.swing.JPanel(); - deviceField110 = new DeviceField(); - deviceField111 = new DeviceField(); - deviceChoice48 = new DeviceChoice(); - deviceField112 = new DeviceField(); - jPanel117 = new javax.swing.JPanel(); - deviceField113 = new DeviceField(); - deviceField114 = new DeviceField(); - deviceChoice49 = new DeviceChoice(); - deviceField115 = new DeviceField(); - setDeviceProvider("scdev6vl.nbtf:8100"); - setDeviceTitle("MARTe2 Generic GAM"); - setDeviceType("MARTE2_GAM"); - setHeight(500); - setWidth(750); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - jPanel1.setLayout(new java.awt.BorderLayout()); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("GAM Class: "); - deviceField1.setNumCols(15); - deviceField1.setOffsetNid(1); - deviceField1.setTextOnly(true); - jPanel2.add(deviceField1); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Timebase: "); - deviceField2.setNumCols(25); - deviceField2.setOffsetNid(3); - jPanel2.add(deviceField2); - deviceField67.setIdentifier(""); - deviceField67.setLabelString("Trigger: "); - deviceField67.setNumCols(15); - deviceField67.setOffsetNid(151); - jPanel2.add(deviceField67); - jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH); - jPanel4.setLayout(new java.awt.GridLayout(16, 1)); - jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 1")); - jPanel14.setLayout(new java.awt.GridLayout(1, 2)); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Name: "); - deviceField7.setNumCols(15); - deviceField7.setOffsetNid(6); - deviceField7.setTextOnly(true); - jPanel15.add(deviceField7); - jPanel14.add(jPanel15); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Value: "); - deviceField8.setNumCols(25); - deviceField8.setOffsetNid(7); - jPanel16.add(deviceField8); - jPanel14.add(jPanel16); - jPanel4.add(jPanel14); - jPanel17.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 2")); - jPanel17.setLayout(new java.awt.GridLayout(1, 2)); - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Name: "); - deviceField9.setNumCols(15); - deviceField9.setOffsetNid(9); - deviceField9.setTextOnly(true); - jPanel18.add(deviceField9); - jPanel17.add(jPanel18); - deviceField10.setIdentifier(""); - deviceField10.setLabelString("Value: "); - deviceField10.setNumCols(25); - deviceField10.setOffsetNid(10); - jPanel19.add(deviceField10); - jPanel17.add(jPanel19); - jPanel4.add(jPanel17); - jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 3")); - jPanel20.setLayout(new java.awt.GridLayout(1, 2)); - deviceField11.setIdentifier(""); - deviceField11.setLabelString("Name: "); - deviceField11.setNumCols(15); - deviceField11.setOffsetNid(12); - deviceField11.setTextOnly(true); - jPanel21.add(deviceField11); - jPanel20.add(jPanel21); - deviceField12.setIdentifier(""); - deviceField12.setLabelString("Value: "); - deviceField12.setNumCols(25); - deviceField12.setOffsetNid(13); - jPanel22.add(deviceField12); - jPanel20.add(jPanel22); - jPanel4.add(jPanel20); - jPanel23.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 4")); - jPanel23.setLayout(new java.awt.GridLayout(1, 2)); - deviceField13.setIdentifier(""); - deviceField13.setLabelString("Name: "); - deviceField13.setNumCols(15); - deviceField13.setOffsetNid(15); - deviceField13.setTextOnly(true); - jPanel24.add(deviceField13); - jPanel23.add(jPanel24); - deviceField14.setIdentifier(""); - deviceField14.setLabelString("Value: "); - deviceField14.setNumCols(25); - deviceField14.setOffsetNid(16); - jPanel25.add(deviceField14); - jPanel23.add(jPanel25); - jPanel4.add(jPanel23); - jPanel26.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 5")); - jPanel26.setLayout(new java.awt.GridLayout(1, 2)); - deviceField15.setIdentifier(""); - deviceField15.setLabelString("Name: "); - deviceField15.setNumCols(15); - deviceField15.setOffsetNid(18); - deviceField15.setTextOnly(true); - jPanel27.add(deviceField15); - jPanel26.add(jPanel27); - deviceField16.setIdentifier(""); - deviceField16.setLabelString("Value: "); - deviceField16.setNumCols(25); - deviceField16.setOffsetNid(19); - jPanel28.add(deviceField16); - jPanel26.add(jPanel28); - jPanel4.add(jPanel26); - jPanel29.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 6")); - jPanel29.setLayout(new java.awt.GridLayout(1, 2)); - deviceField17.setIdentifier(""); - deviceField17.setLabelString("Name: "); - deviceField17.setNumCols(15); - deviceField17.setOffsetNid(21); - deviceField17.setTextOnly(true); - jPanel30.add(deviceField17); - jPanel29.add(jPanel30); - deviceField18.setIdentifier(""); - deviceField18.setLabelString("Value: "); - deviceField18.setNumCols(25); - deviceField18.setOffsetNid(22); - jPanel31.add(deviceField18); - jPanel29.add(jPanel31); - jPanel4.add(jPanel29); - jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 7")); - jPanel32.setLayout(new java.awt.GridLayout(1, 2)); - deviceField19.setIdentifier(""); - deviceField19.setLabelString("Name: "); - deviceField19.setNumCols(15); - deviceField19.setOffsetNid(24); - deviceField19.setTextOnly(true); - jPanel33.add(deviceField19); - jPanel32.add(jPanel33); - deviceField20.setIdentifier(""); - deviceField20.setLabelString("Value: "); - deviceField20.setNumCols(25); - deviceField20.setOffsetNid(25); - jPanel34.add(deviceField20); - jPanel32.add(jPanel34); - jPanel4.add(jPanel32); - jPanel35.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 8")); - jPanel35.setLayout(new java.awt.GridLayout(1, 2)); - deviceField21.setIdentifier(""); - deviceField21.setLabelString("Name: "); - deviceField21.setNumCols(15); - deviceField21.setOffsetNid(27); - deviceField21.setTextOnly(true); - jPanel36.add(deviceField21); - jPanel35.add(jPanel36); - deviceField22.setIdentifier(""); - deviceField22.setLabelString("Value: "); - deviceField22.setNumCols(25); - deviceField22.setOffsetNid(28); - jPanel37.add(deviceField22); - jPanel35.add(jPanel37); - jPanel4.add(jPanel35); - jPanel38.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 9")); - jPanel38.setLayout(new java.awt.GridLayout(1, 2)); - deviceField23.setIdentifier(""); - deviceField23.setLabelString("Name: "); - deviceField23.setNumCols(15); - deviceField23.setOffsetNid(30); - deviceField23.setTextOnly(true); - jPanel39.add(deviceField23); - jPanel38.add(jPanel39); - deviceField24.setIdentifier(""); - deviceField24.setLabelString("Value: "); - deviceField24.setNumCols(25); - deviceField24.setOffsetNid(31); - jPanel40.add(deviceField24); - jPanel38.add(jPanel40); - jPanel4.add(jPanel38); - jPanel41.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 10")); - jPanel41.setLayout(new java.awt.GridLayout(1, 2)); - deviceField25.setIdentifier(""); - deviceField25.setLabelString("Name: "); - deviceField25.setNumCols(15); - deviceField25.setOffsetNid(33); - deviceField25.setTextOnly(true); - jPanel42.add(deviceField25); - jPanel41.add(jPanel42); - deviceField26.setIdentifier(""); - deviceField26.setLabelString("Value: "); - deviceField26.setNumCols(25); - deviceField26.setOffsetNid(34); - jPanel43.add(deviceField26); - jPanel41.add(jPanel43); - jPanel4.add(jPanel41); - jPanel44.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 11")); - jPanel44.setLayout(new java.awt.GridLayout(1, 2)); - deviceField27.setIdentifier(""); - deviceField27.setLabelString("Name: "); - deviceField27.setNumCols(15); - deviceField27.setOffsetNid(36); - deviceField27.setTextOnly(true); - jPanel45.add(deviceField27); - jPanel44.add(jPanel45); - deviceField28.setIdentifier(""); - deviceField28.setLabelString("Value: "); - deviceField28.setNumCols(25); - deviceField28.setOffsetNid(37); - jPanel46.add(deviceField28); - jPanel44.add(jPanel46); - jPanel4.add(jPanel44); - jPanel47.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 12")); - jPanel47.setLayout(new java.awt.GridLayout(1, 2)); - deviceField29.setIdentifier(""); - deviceField29.setLabelString("Name: "); - deviceField29.setNumCols(15); - deviceField29.setOffsetNid(39); - deviceField29.setTextOnly(true); - jPanel48.add(deviceField29); - jPanel47.add(jPanel48); - deviceField30.setIdentifier(""); - deviceField30.setLabelString("Value: "); - deviceField30.setNumCols(25); - deviceField30.setOffsetNid(40); - jPanel49.add(deviceField30); - jPanel47.add(jPanel49); - jPanel4.add(jPanel47); - jPanel50.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 13")); - jPanel50.setLayout(new java.awt.GridLayout(1, 2)); - deviceField31.setIdentifier(""); - deviceField31.setLabelString("Name: "); - deviceField31.setNumCols(15); - deviceField31.setOffsetNid(42); - deviceField31.setTextOnly(true); - jPanel51.add(deviceField31); - jPanel50.add(jPanel51); - deviceField32.setIdentifier(""); - deviceField32.setLabelString("Value: "); - deviceField32.setNumCols(25); - deviceField32.setOffsetNid(43); - jPanel52.add(deviceField32); - jPanel50.add(jPanel52); - jPanel4.add(jPanel50); - jPanel53.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 14")); - jPanel53.setLayout(new java.awt.GridLayout(1, 2)); - deviceField33.setIdentifier(""); - deviceField33.setLabelString("Name: "); - deviceField33.setNumCols(15); - deviceField33.setOffsetNid(45); - deviceField33.setTextOnly(true); - jPanel54.add(deviceField33); - jPanel53.add(jPanel54); - deviceField34.setIdentifier(""); - deviceField34.setLabelString("Value: "); - deviceField34.setNumCols(25); - deviceField34.setOffsetNid(46); - jPanel55.add(deviceField34); - jPanel53.add(jPanel55); - jPanel4.add(jPanel53); - jPanel56.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 15")); - jPanel56.setLayout(new java.awt.GridLayout(1, 2)); - deviceField35.setIdentifier(""); - deviceField35.setLabelString("Name: "); - deviceField35.setNumCols(15); - deviceField35.setOffsetNid(48); - deviceField35.setTextOnly(true); - jPanel57.add(deviceField35); - jPanel56.add(jPanel57); - deviceField36.setIdentifier(""); - deviceField36.setLabelString("Value: "); - deviceField36.setNumCols(25); - deviceField36.setOffsetNid(49); - jPanel58.add(deviceField36); - jPanel56.add(jPanel58); - jPanel4.add(jPanel56); - jPanel59.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 16")); - jPanel59.setLayout(new java.awt.GridLayout(1, 2)); - deviceField37.setIdentifier(""); - deviceField37.setLabelString("Name: "); - deviceField37.setNumCols(15); - deviceField37.setOffsetNid(51); - deviceField37.setTextOnly(true); - jPanel60.add(deviceField37); - jPanel59.add(jPanel60); - deviceField38.setIdentifier(""); - deviceField38.setLabelString("Value: "); - deviceField38.setNumCols(25); - deviceField38.setOffsetNid(52); - jPanel61.add(deviceField38); - jPanel59.add(jPanel61); - jPanel4.add(jPanel59); - jScrollPane1.setViewportView(jPanel4); - jTabbedPane1.addTab("Parameters", jScrollPane1); - jPanel3.setLayout(new java.awt.GridLayout(16, 1)); - jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 1")); - jPanel5.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice1.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice1.setIdentifier(""); - deviceChoice1.setLabelString("Column First order:"); - deviceChoice1.setOffsetNid(57); - deviceChoice1.setUpdateIdentifier(""); - jPanel6.add(deviceChoice1); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Dimensions (-1 to disable input):"); - deviceField3.setNumCols(5); - deviceField3.setOffsetNid(56); - jPanel6.add(deviceField3); - deviceChoice2.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice2.setIdentifier(""); - deviceChoice2.setLabelString("Type"); - deviceChoice2.setOffsetNid(55); - deviceChoice2.setUpdateIdentifier(""); - jPanel6.add(deviceChoice2); - jPanel5.add(jPanel6); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Value: "); - deviceField4.setNumCols(35); - deviceField4.setOffsetNid(58); - jPanel7.add(deviceField4); - jPanel5.add(jPanel7); - jPanel3.add(jPanel5); - jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 2")); - jPanel8.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice3.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice3.setIdentifier(""); - deviceChoice3.setLabelString("Column First order:"); - deviceChoice3.setOffsetNid(63); - deviceChoice3.setUpdateIdentifier(""); - jPanel9.add(deviceChoice3); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Dimensions (-1 to disable input):"); - deviceField5.setNumCols(5); - deviceField5.setOffsetNid(62); - jPanel9.add(deviceField5); - deviceChoice4.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice4.setIdentifier(""); - deviceChoice4.setLabelString("Type"); - deviceChoice4.setOffsetNid(61); - deviceChoice4.setUpdateIdentifier(""); - jPanel9.add(deviceChoice4); - jPanel8.add(jPanel9); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Value: "); - deviceField6.setNumCols(35); - deviceField6.setOffsetNid(64); - jPanel10.add(deviceField6); - jPanel8.add(jPanel10); - jPanel3.add(jPanel8); - jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 3")); - jPanel11.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice5.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice5.setIdentifier(""); - deviceChoice5.setLabelString("Column First order:"); - deviceChoice5.setOffsetNid(69); - deviceChoice5.setUpdateIdentifier(""); - jPanel12.add(deviceChoice5); - deviceField39.setIdentifier(""); - deviceField39.setLabelString("Dimensions (-1 to disable input):"); - deviceField39.setNumCols(5); - deviceField39.setOffsetNid(68); - jPanel12.add(deviceField39); - deviceChoice6.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice6.setIdentifier(""); - deviceChoice6.setLabelString("Type"); - deviceChoice6.setOffsetNid(67); - deviceChoice6.setUpdateIdentifier(""); - jPanel12.add(deviceChoice6); - jPanel11.add(jPanel12); - deviceField40.setIdentifier(""); - deviceField40.setLabelString("Value: "); - deviceField40.setNumCols(35); - deviceField40.setOffsetNid(70); - jPanel13.add(deviceField40); - jPanel11.add(jPanel13); - jPanel3.add(jPanel11); - jPanel62.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 4")); - jPanel62.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice7.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice7.setIdentifier(""); - deviceChoice7.setLabelString("Column First order:"); - deviceChoice7.setOffsetNid(75); - deviceChoice7.setUpdateIdentifier(""); - jPanel63.add(deviceChoice7); - deviceField41.setIdentifier(""); - deviceField41.setLabelString("Dimensions (-1 to disable input):"); - deviceField41.setNumCols(5); - deviceField41.setOffsetNid(74); - jPanel63.add(deviceField41); - deviceChoice8.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice8.setIdentifier(""); - deviceChoice8.setLabelString("Type"); - deviceChoice8.setOffsetNid(73); - deviceChoice8.setUpdateIdentifier(""); - jPanel63.add(deviceChoice8); - jPanel62.add(jPanel63); - deviceField42.setIdentifier(""); - deviceField42.setLabelString("Value: "); - deviceField42.setNumCols(35); - deviceField42.setOffsetNid(76); - jPanel64.add(deviceField42); - jPanel62.add(jPanel64); - jPanel3.add(jPanel62); - jPanel65.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 5")); - jPanel65.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice9.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice9.setIdentifier(""); - deviceChoice9.setLabelString("Column First order:"); - deviceChoice9.setOffsetNid(81); - deviceChoice9.setUpdateIdentifier(""); - jPanel66.add(deviceChoice9); - deviceField43.setIdentifier(""); - deviceField43.setLabelString("Dimensions (-1 to disable input):"); - deviceField43.setNumCols(5); - deviceField43.setOffsetNid(80); - jPanel66.add(deviceField43); - deviceChoice10.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice10.setIdentifier(""); - deviceChoice10.setLabelString("Type"); - deviceChoice10.setOffsetNid(79); - deviceChoice10.setUpdateIdentifier(""); - jPanel66.add(deviceChoice10); - jPanel65.add(jPanel66); - deviceField44.setIdentifier(""); - deviceField44.setLabelString("Value: "); - deviceField44.setNumCols(35); - deviceField44.setOffsetNid(82); - jPanel67.add(deviceField44); - jPanel65.add(jPanel67); - jPanel3.add(jPanel65); - jPanel68.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 6")); - jPanel68.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice11.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice11.setIdentifier(""); - deviceChoice11.setLabelString("Column First order:"); - deviceChoice11.setOffsetNid(87); - deviceChoice11.setUpdateIdentifier(""); - jPanel69.add(deviceChoice11); - deviceField45.setIdentifier(""); - deviceField45.setLabelString("Dimensions (-1 to disable input):"); - deviceField45.setNumCols(5); - deviceField45.setOffsetNid(86); - jPanel69.add(deviceField45); - deviceChoice12.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice12.setIdentifier(""); - deviceChoice12.setLabelString("Type"); - deviceChoice12.setOffsetNid(85); - deviceChoice12.setUpdateIdentifier(""); - jPanel69.add(deviceChoice12); - jPanel68.add(jPanel69); - deviceField46.setIdentifier(""); - deviceField46.setLabelString("Value: "); - deviceField46.setNumCols(35); - deviceField46.setOffsetNid(88); - jPanel70.add(deviceField46); - jPanel68.add(jPanel70); - jPanel3.add(jPanel68); - jPanel71.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 7")); - jPanel71.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice13.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice13.setIdentifier(""); - deviceChoice13.setLabelString("Column First order:"); - deviceChoice13.setOffsetNid(93); - deviceChoice13.setUpdateIdentifier(""); - jPanel72.add(deviceChoice13); - deviceField47.setIdentifier(""); - deviceField47.setLabelString("Dimensions (-1 to disable input):"); - deviceField47.setNumCols(5); - deviceField47.setOffsetNid(86); - jPanel72.add(deviceField47); - deviceChoice14.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice14.setIdentifier(""); - deviceChoice14.setLabelString("Type"); - deviceChoice14.setOffsetNid(91); - deviceChoice14.setUpdateIdentifier(""); - jPanel72.add(deviceChoice14); - jPanel71.add(jPanel72); - deviceField48.setIdentifier(""); - deviceField48.setLabelString("Value: "); - deviceField48.setNumCols(35); - deviceField48.setOffsetNid(94); - jPanel73.add(deviceField48); - jPanel71.add(jPanel73); - jPanel3.add(jPanel71); - jPanel74.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 8")); - jPanel74.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice15.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice15.setIdentifier(""); - deviceChoice15.setLabelString("Column First order:"); - deviceChoice15.setOffsetNid(99); - deviceChoice15.setUpdateIdentifier(""); - jPanel75.add(deviceChoice15); - deviceField49.setIdentifier(""); - deviceField49.setLabelString("Dimensions (-1 to disable input):"); - deviceField49.setNumCols(5); - deviceField49.setOffsetNid(98); - jPanel75.add(deviceField49); - deviceChoice16.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice16.setIdentifier(""); - deviceChoice16.setLabelString("Type"); - deviceChoice16.setOffsetNid(97); - deviceChoice16.setUpdateIdentifier(""); - jPanel75.add(deviceChoice16); - jPanel74.add(jPanel75); - deviceField50.setIdentifier(""); - deviceField50.setLabelString("Value: "); - deviceField50.setNumCols(35); - deviceField50.setOffsetNid(100); - jPanel76.add(deviceField50); - jPanel74.add(jPanel76); - jPanel3.add(jPanel74); - jPanel77.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 9")); - jPanel77.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice17.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice17.setIdentifier(""); - deviceChoice17.setLabelString("Column First order:"); - deviceChoice17.setOffsetNid(105); - deviceChoice17.setUpdateIdentifier(""); - jPanel78.add(deviceChoice17); - deviceField51.setIdentifier(""); - deviceField51.setLabelString("Dimensions (-1 to disable input):"); - deviceField51.setNumCols(5); - deviceField51.setOffsetNid(104); - jPanel78.add(deviceField51); - deviceChoice18.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice18.setIdentifier(""); - deviceChoice18.setLabelString("Type"); - deviceChoice18.setOffsetNid(103); - deviceChoice18.setUpdateIdentifier(""); - jPanel78.add(deviceChoice18); - jPanel77.add(jPanel78); - deviceField52.setIdentifier(""); - deviceField52.setLabelString("Value: "); - deviceField52.setNumCols(35); - deviceField52.setOffsetNid(106); - jPanel79.add(deviceField52); - jPanel77.add(jPanel79); - jPanel3.add(jPanel77); - jPanel80.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 10")); - jPanel80.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice19.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice19.setIdentifier(""); - deviceChoice19.setLabelString("Column First order:"); - deviceChoice19.setOffsetNid(111); - deviceChoice19.setUpdateIdentifier(""); - jPanel81.add(deviceChoice19); - deviceField53.setIdentifier(""); - deviceField53.setLabelString("Dimensions (-1 to disable input):"); - deviceField53.setNumCols(5); - deviceField53.setOffsetNid(110); - jPanel81.add(deviceField53); - deviceChoice20.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice20.setIdentifier(""); - deviceChoice20.setLabelString("Type"); - deviceChoice20.setOffsetNid(109); - deviceChoice20.setUpdateIdentifier(""); - jPanel81.add(deviceChoice20); - jPanel80.add(jPanel81); - deviceField54.setIdentifier(""); - deviceField54.setLabelString("Value: "); - deviceField54.setNumCols(35); - deviceField54.setOffsetNid(112); - jPanel82.add(deviceField54); - jPanel80.add(jPanel82); - jPanel3.add(jPanel80); - jPanel83.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 11")); - jPanel83.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice21.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice21.setIdentifier(""); - deviceChoice21.setLabelString("Column First order:"); - deviceChoice21.setOffsetNid(117); - deviceChoice21.setUpdateIdentifier(""); - jPanel84.add(deviceChoice21); - deviceField55.setIdentifier(""); - deviceField55.setLabelString("Dimensions (-1 to disable input):"); - deviceField55.setNumCols(5); - deviceField55.setOffsetNid(116); - jPanel84.add(deviceField55); - deviceChoice22.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice22.setIdentifier(""); - deviceChoice22.setLabelString("Type"); - deviceChoice22.setOffsetNid(115); - deviceChoice22.setUpdateIdentifier(""); - jPanel84.add(deviceChoice22); - jPanel83.add(jPanel84); - deviceField56.setIdentifier(""); - deviceField56.setLabelString("Value: "); - deviceField56.setNumCols(35); - deviceField56.setOffsetNid(118); - jPanel85.add(deviceField56); - jPanel83.add(jPanel85); - jPanel3.add(jPanel83); - jPanel86.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 12")); - jPanel86.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice23.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice23.setIdentifier(""); - deviceChoice23.setLabelString("Column First order:"); - deviceChoice23.setOffsetNid(123); - deviceChoice23.setUpdateIdentifier(""); - jPanel87.add(deviceChoice23); - deviceField57.setIdentifier(""); - deviceField57.setLabelString("Dimensions (-1 to disable input):"); - deviceField57.setNumCols(5); - deviceField57.setOffsetNid(122); - jPanel87.add(deviceField57); - deviceChoice24.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice24.setIdentifier(""); - deviceChoice24.setLabelString("Type"); - deviceChoice24.setOffsetNid(121); - deviceChoice24.setUpdateIdentifier(""); - jPanel87.add(deviceChoice24); - jPanel86.add(jPanel87); - deviceField58.setIdentifier(""); - deviceField58.setLabelString("Value: "); - deviceField58.setNumCols(35); - deviceField58.setOffsetNid(124); - jPanel88.add(deviceField58); - jPanel86.add(jPanel88); - jPanel3.add(jPanel86); - jPanel89.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 13")); - jPanel89.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice25.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice25.setIdentifier(""); - deviceChoice25.setLabelString("Column First order:"); - deviceChoice25.setOffsetNid(129); - deviceChoice25.setUpdateIdentifier(""); - jPanel90.add(deviceChoice25); - deviceField59.setIdentifier(""); - deviceField59.setLabelString("Dimensions (-1 to disable input):"); - deviceField59.setNumCols(5); - deviceField59.setOffsetNid(128); - jPanel90.add(deviceField59); - deviceChoice26.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice26.setIdentifier(""); - deviceChoice26.setLabelString("Type"); - deviceChoice26.setOffsetNid(127); - deviceChoice26.setUpdateIdentifier(""); - jPanel90.add(deviceChoice26); - jPanel89.add(jPanel90); - deviceField60.setIdentifier(""); - deviceField60.setLabelString("Value: "); - deviceField60.setNumCols(35); - deviceField60.setOffsetNid(130); - jPanel91.add(deviceField60); - jPanel89.add(jPanel91); - jPanel3.add(jPanel89); - jPanel92.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 14")); - jPanel92.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice27.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice27.setIdentifier(""); - deviceChoice27.setLabelString("Column First order:"); - deviceChoice27.setOffsetNid(135); - deviceChoice27.setUpdateIdentifier(""); - jPanel93.add(deviceChoice27); - deviceField61.setIdentifier(""); - deviceField61.setLabelString("Dimensions (-1 to disable input):"); - deviceField61.setNumCols(5); - deviceField61.setOffsetNid(134); - jPanel93.add(deviceField61); - deviceChoice28.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice28.setIdentifier(""); - deviceChoice28.setLabelString("Type"); - deviceChoice28.setOffsetNid(133); - deviceChoice28.setUpdateIdentifier(""); - jPanel93.add(deviceChoice28); - jPanel92.add(jPanel93); - deviceField62.setIdentifier(""); - deviceField62.setLabelString("Value: "); - deviceField62.setNumCols(35); - deviceField62.setOffsetNid(136); - jPanel94.add(deviceField62); - jPanel92.add(jPanel94); - jPanel3.add(jPanel92); - jPanel95.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 15")); - jPanel95.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice29.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice29.setIdentifier(""); - deviceChoice29.setLabelString("Column First order:"); - deviceChoice29.setOffsetNid(141); - deviceChoice29.setUpdateIdentifier(""); - jPanel96.add(deviceChoice29); - deviceField63.setIdentifier(""); - deviceField63.setLabelString("Dimensions (-1 to disable input):"); - deviceField63.setNumCols(5); - deviceField63.setOffsetNid(140); - jPanel96.add(deviceField63); - deviceChoice30.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice30.setIdentifier(""); - deviceChoice30.setLabelString("Type"); - deviceChoice30.setOffsetNid(139); - deviceChoice30.setUpdateIdentifier(""); - jPanel96.add(deviceChoice30); - jPanel95.add(jPanel96); - deviceField64.setIdentifier(""); - deviceField64.setLabelString("Value: "); - deviceField64.setNumCols(35); - deviceField64.setOffsetNid(142); - jPanel97.add(deviceField64); - jPanel95.add(jPanel97); - jPanel3.add(jPanel95); - jPanel98.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 16")); - jPanel98.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice31.setChoiceItems(new String[] - { "NO", "YES" }); - deviceChoice31.setIdentifier(""); - deviceChoice31.setLabelString("Column First order:"); - deviceChoice31.setOffsetNid(147); - deviceChoice31.setUpdateIdentifier(""); - jPanel99.add(deviceChoice31); - deviceField65.setIdentifier(""); - deviceField65.setLabelString("Dimensions (-1 to disable input):"); - deviceField65.setNumCols(5); - deviceField65.setOffsetNid(146); - jPanel99.add(deviceField65); - deviceChoice32.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice32.setIdentifier(""); - deviceChoice32.setLabelString("Type"); - deviceChoice32.setOffsetNid(145); - deviceChoice32.setUpdateIdentifier(""); - jPanel99.add(deviceChoice32); - jPanel98.add(jPanel99); - deviceField66.setIdentifier(""); - deviceField66.setLabelString("Value: "); - deviceField66.setNumCols(35); - deviceField66.setOffsetNid(148); - jPanel100.add(deviceField66); - jPanel98.add(jPanel100); - jPanel3.add(jPanel98); - jScrollPane2.setViewportView(jPanel3); - jTabbedPane1.addTab("Inputs", jScrollPane2); - jPanel101.setLayout(new java.awt.GridLayout(16, 1)); - jPanel102.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 1")); - deviceField69.setIdentifier(""); - deviceField69.setLabelString("Name"); - deviceField69.setNumCols(15); - deviceField69.setOffsetNid(153); - deviceField69.setTextOnly(true); - jPanel102.add(deviceField69); - deviceField68.setIdentifier(""); - deviceField68.setLabelString("Dimensions (-1 to disable output):"); - deviceField68.setNumCols(5); - deviceField68.setOffsetNid(155); - jPanel102.add(deviceField68); - deviceChoice34.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice34.setIdentifier(""); - deviceChoice34.setLabelString("Type"); - deviceChoice34.setOffsetNid(154); - deviceChoice34.setUpdateIdentifier(""); - jPanel102.add(deviceChoice34); - deviceField70.setIdentifier(""); - deviceField70.setLabelString("Seg. Len: "); - deviceField70.setNumCols(5); - deviceField70.setOffsetNid(156); - jPanel102.add(deviceField70); - jPanel101.add(jPanel102); - jPanel103.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 2")); - deviceField71.setIdentifier(""); - deviceField71.setLabelString("Name"); - deviceField71.setNumCols(15); - deviceField71.setOffsetNid(160); - deviceField71.setTextOnly(true); - jPanel103.add(deviceField71); - deviceField72.setIdentifier(""); - deviceField72.setLabelString("Dimensions (-1 to disable output):"); - deviceField72.setNumCols(5); - deviceField72.setOffsetNid(162); - jPanel103.add(deviceField72); - deviceChoice35.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice35.setIdentifier(""); - deviceChoice35.setLabelString("Type"); - deviceChoice35.setOffsetNid(161); - deviceChoice35.setUpdateIdentifier(""); - jPanel103.add(deviceChoice35); - deviceField73.setIdentifier(""); - deviceField73.setLabelString("Seg. Len: "); - deviceField73.setNumCols(5); - deviceField73.setOffsetNid(163); - jPanel103.add(deviceField73); - jPanel101.add(jPanel103); - jPanel104.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 3")); - deviceField74.setIdentifier(""); - deviceField74.setLabelString("Name"); - deviceField74.setNumCols(15); - deviceField74.setOffsetNid(167); - deviceField74.setTextOnly(true); - jPanel104.add(deviceField74); - deviceField75.setIdentifier(""); - deviceField75.setLabelString("Dimensions (-1 to disable output):"); - deviceField75.setNumCols(5); - deviceField75.setOffsetNid(169); - jPanel104.add(deviceField75); - deviceChoice36.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice36.setIdentifier(""); - deviceChoice36.setLabelString("Type"); - deviceChoice36.setOffsetNid(168); - deviceChoice36.setUpdateIdentifier(""); - jPanel104.add(deviceChoice36); - deviceField76.setIdentifier(""); - deviceField76.setLabelString("Seg. Len: "); - deviceField76.setNumCols(5); - deviceField76.setOffsetNid(170); - jPanel104.add(deviceField76); - jPanel101.add(jPanel104); - jPanel105.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 4")); - deviceField77.setIdentifier(""); - deviceField77.setLabelString("Name"); - deviceField77.setNumCols(15); - deviceField77.setOffsetNid(174); - deviceField77.setTextOnly(true); - jPanel105.add(deviceField77); - deviceField78.setIdentifier(""); - deviceField78.setLabelString("Dimensions (-1 to disable output):"); - deviceField78.setNumCols(5); - deviceField78.setOffsetNid(176); - jPanel105.add(deviceField78); - deviceChoice37.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice37.setIdentifier(""); - deviceChoice37.setLabelString("Type"); - deviceChoice37.setOffsetNid(175); - deviceChoice37.setUpdateIdentifier(""); - jPanel105.add(deviceChoice37); - deviceField79.setIdentifier(""); - deviceField79.setLabelString("Seg. Len: "); - deviceField79.setNumCols(5); - deviceField79.setOffsetNid(177); - jPanel105.add(deviceField79); - jPanel101.add(jPanel105); - jPanel106.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 5")); - deviceField80.setIdentifier(""); - deviceField80.setLabelString("Name"); - deviceField80.setNumCols(15); - deviceField80.setOffsetNid(181); - deviceField80.setTextOnly(true); - jPanel106.add(deviceField80); - deviceField81.setIdentifier(""); - deviceField81.setLabelString("Dimensions (-1 to disable output):"); - deviceField81.setNumCols(5); - deviceField81.setOffsetNid(183); - jPanel106.add(deviceField81); - deviceChoice38.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice38.setIdentifier(""); - deviceChoice38.setLabelString("Type"); - deviceChoice38.setOffsetNid(182); - deviceChoice38.setUpdateIdentifier(""); - jPanel106.add(deviceChoice38); - deviceField82.setIdentifier(""); - deviceField82.setLabelString("Seg. Len: "); - deviceField82.setNumCols(5); - deviceField82.setOffsetNid(184); - jPanel106.add(deviceField82); - jPanel101.add(jPanel106); - jPanel107.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 6")); - deviceField83.setIdentifier(""); - deviceField83.setLabelString("Name"); - deviceField83.setNumCols(15); - deviceField83.setOffsetNid(188); - deviceField83.setTextOnly(true); - jPanel107.add(deviceField83); - deviceField84.setIdentifier(""); - deviceField84.setLabelString("Dimensions (-1 to disable output):"); - deviceField84.setNumCols(5); - deviceField84.setOffsetNid(190); - jPanel107.add(deviceField84); - deviceChoice39.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice39.setIdentifier(""); - deviceChoice39.setLabelString("Type"); - deviceChoice39.setOffsetNid(189); - deviceChoice39.setUpdateIdentifier(""); - jPanel107.add(deviceChoice39); - deviceField85.setIdentifier(""); - deviceField85.setLabelString("Seg. Len: "); - deviceField85.setNumCols(5); - deviceField85.setOffsetNid(191); - jPanel107.add(deviceField85); - jPanel101.add(jPanel107); - jPanel108.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 7")); - deviceField86.setIdentifier(""); - deviceField86.setLabelString("Name"); - deviceField86.setNumCols(15); - deviceField86.setOffsetNid(195); - deviceField86.setTextOnly(true); - jPanel108.add(deviceField86); - deviceField87.setIdentifier(""); - deviceField87.setLabelString("Dimensions (-1 to disable output):"); - deviceField87.setNumCols(5); - deviceField87.setOffsetNid(197); - jPanel108.add(deviceField87); - deviceChoice40.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice40.setIdentifier(""); - deviceChoice40.setLabelString("Type"); - deviceChoice40.setOffsetNid(196); - deviceChoice40.setUpdateIdentifier(""); - jPanel108.add(deviceChoice40); - deviceField88.setIdentifier(""); - deviceField88.setLabelString("Seg. Len: "); - deviceField88.setNumCols(5); - deviceField88.setOffsetNid(198); - jPanel108.add(deviceField88); - jPanel101.add(jPanel108); - jPanel109.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 8")); - deviceField89.setIdentifier(""); - deviceField89.setLabelString("Name"); - deviceField89.setNumCols(15); - deviceField89.setOffsetNid(202); - deviceField89.setTextOnly(true); - jPanel109.add(deviceField89); - deviceField90.setIdentifier(""); - deviceField90.setLabelString("Dimensions (-1 to disable output):"); - deviceField90.setNumCols(5); - deviceField90.setOffsetNid(204); - jPanel109.add(deviceField90); - deviceChoice41.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice41.setIdentifier(""); - deviceChoice41.setLabelString("Type"); - deviceChoice41.setOffsetNid(203); - deviceChoice41.setUpdateIdentifier(""); - jPanel109.add(deviceChoice41); - deviceField91.setIdentifier(""); - deviceField91.setLabelString("Seg. Len: "); - deviceField91.setNumCols(5); - deviceField91.setOffsetNid(205); - jPanel109.add(deviceField91); - jPanel101.add(jPanel109); - jPanel110.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 9")); - deviceField92.setIdentifier(""); - deviceField92.setLabelString("Name"); - deviceField92.setNumCols(15); - deviceField92.setOffsetNid(209); - deviceField92.setTextOnly(true); - jPanel110.add(deviceField92); - deviceField93.setIdentifier(""); - deviceField93.setLabelString("Dimensions (-1 to disable output):"); - deviceField93.setNumCols(5); - deviceField93.setOffsetNid(211); - jPanel110.add(deviceField93); - deviceChoice42.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice42.setIdentifier(""); - deviceChoice42.setLabelString("Type"); - deviceChoice42.setOffsetNid(210); - deviceChoice42.setUpdateIdentifier(""); - jPanel110.add(deviceChoice42); - deviceField94.setIdentifier(""); - deviceField94.setLabelString("Seg. Len: "); - deviceField94.setNumCols(5); - deviceField94.setOffsetNid(212); - jPanel110.add(deviceField94); - jPanel101.add(jPanel110); - jPanel111.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 10")); - deviceField95.setIdentifier(""); - deviceField95.setLabelString("Name"); - deviceField95.setNumCols(15); - deviceField95.setOffsetNid(216); - deviceField95.setTextOnly(true); - jPanel111.add(deviceField95); - deviceField96.setIdentifier(""); - deviceField96.setLabelString("Dimensions (-1 to disable output):"); - deviceField96.setNumCols(5); - deviceField96.setOffsetNid(218); - jPanel111.add(deviceField96); - deviceChoice43.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice43.setIdentifier(""); - deviceChoice43.setLabelString("Type"); - deviceChoice43.setOffsetNid(217); - deviceChoice43.setUpdateIdentifier(""); - jPanel111.add(deviceChoice43); - deviceField97.setIdentifier(""); - deviceField97.setLabelString("Seg. Len: "); - deviceField97.setNumCols(5); - deviceField97.setOffsetNid(219); - jPanel111.add(deviceField97); - jPanel101.add(jPanel111); - jPanel112.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 11")); - deviceField98.setIdentifier(""); - deviceField98.setLabelString("Name"); - deviceField98.setNumCols(15); - deviceField98.setOffsetNid(223); - deviceField98.setTextOnly(true); - jPanel112.add(deviceField98); - deviceField99.setIdentifier(""); - deviceField99.setLabelString("Dimensions (-1 to disable output):"); - deviceField99.setNumCols(5); - deviceField99.setOffsetNid(225); - jPanel112.add(deviceField99); - deviceChoice44.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice44.setIdentifier(""); - deviceChoice44.setLabelString("Type"); - deviceChoice44.setOffsetNid(224); - deviceChoice44.setUpdateIdentifier(""); - jPanel112.add(deviceChoice44); - deviceField100.setIdentifier(""); - deviceField100.setLabelString("Seg. Len: "); - deviceField100.setNumCols(5); - deviceField100.setOffsetNid(226); - jPanel112.add(deviceField100); - jPanel101.add(jPanel112); - jPanel113.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 12")); - deviceField101.setIdentifier(""); - deviceField101.setLabelString("Name"); - deviceField101.setNumCols(15); - deviceField101.setOffsetNid(230); - deviceField101.setTextOnly(true); - jPanel113.add(deviceField101); - deviceField102.setIdentifier(""); - deviceField102.setLabelString("Dimensions (-1 to disable output):"); - deviceField102.setNumCols(5); - deviceField102.setOffsetNid(232); - jPanel113.add(deviceField102); - deviceChoice45.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice45.setIdentifier(""); - deviceChoice45.setLabelString("Type"); - deviceChoice45.setOffsetNid(231); - deviceChoice45.setUpdateIdentifier(""); - jPanel113.add(deviceChoice45); - deviceField103.setIdentifier(""); - deviceField103.setLabelString("Seg. Len: "); - deviceField103.setNumCols(5); - deviceField103.setOffsetNid(233); - jPanel113.add(deviceField103); - jPanel101.add(jPanel113); - jPanel114.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 13")); - deviceField104.setIdentifier(""); - deviceField104.setLabelString("Name"); - deviceField104.setNumCols(15); - deviceField104.setOffsetNid(237); - deviceField104.setTextOnly(true); - jPanel114.add(deviceField104); - deviceField105.setIdentifier(""); - deviceField105.setLabelString("Dimensions (-1 to disable output):"); - deviceField105.setNumCols(5); - deviceField105.setOffsetNid(239); - jPanel114.add(deviceField105); - deviceChoice46.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice46.setIdentifier(""); - deviceChoice46.setLabelString("Type"); - deviceChoice46.setOffsetNid(238); - deviceChoice46.setUpdateIdentifier(""); - jPanel114.add(deviceChoice46); - deviceField106.setIdentifier(""); - deviceField106.setLabelString("Seg. Len: "); - deviceField106.setNumCols(5); - deviceField106.setOffsetNid(240); - jPanel114.add(deviceField106); - jPanel101.add(jPanel114); - jPanel115.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 14")); - deviceField107.setIdentifier(""); - deviceField107.setLabelString("Name"); - deviceField107.setNumCols(15); - deviceField107.setOffsetNid(244); - deviceField107.setTextOnly(true); - jPanel115.add(deviceField107); - deviceField108.setIdentifier(""); - deviceField108.setLabelString("Dimensions (-1 to disable output):"); - deviceField108.setNumCols(5); - deviceField108.setOffsetNid(246); - jPanel115.add(deviceField108); - deviceChoice47.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice47.setIdentifier(""); - deviceChoice47.setLabelString("Type"); - deviceChoice47.setOffsetNid(245); - deviceChoice47.setUpdateIdentifier(""); - jPanel115.add(deviceChoice47); - deviceField109.setIdentifier(""); - deviceField109.setLabelString("Seg. Len: "); - deviceField109.setNumCols(5); - deviceField109.setOffsetNid(247); - jPanel115.add(deviceField109); - jPanel101.add(jPanel115); - jPanel116.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 15")); - deviceField110.setIdentifier(""); - deviceField110.setLabelString("Name"); - deviceField110.setNumCols(15); - deviceField110.setOffsetNid(251); - deviceField110.setTextOnly(true); - jPanel116.add(deviceField110); - deviceField111.setIdentifier(""); - deviceField111.setLabelString("Dimensions (-1 to disable output):"); - deviceField111.setNumCols(5); - deviceField111.setOffsetNid(253); - jPanel116.add(deviceField111); - deviceChoice48.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice48.setIdentifier(""); - deviceChoice48.setLabelString("Type"); - deviceChoice48.setOffsetNid(252); - deviceChoice48.setUpdateIdentifier(""); - jPanel116.add(deviceChoice48); - deviceField112.setIdentifier(""); - deviceField112.setLabelString("Seg. Len: "); - deviceField112.setNumCols(5); - deviceField112.setOffsetNid(254); - jPanel116.add(deviceField112); - jPanel101.add(jPanel116); - jPanel117.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 16")); - deviceField113.setIdentifier(""); - deviceField113.setLabelString("Name"); - deviceField113.setNumCols(15); - deviceField113.setOffsetNid(258); - deviceField113.setTextOnly(true); - jPanel117.add(deviceField113); - deviceField114.setIdentifier(""); - deviceField114.setLabelString("Dimensions (-1 to disable output):"); - deviceField114.setNumCols(5); - deviceField114.setOffsetNid(260); - jPanel117.add(deviceField114); - deviceChoice49.setChoiceItems(new String[] - { "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64" }); - deviceChoice49.setIdentifier(""); - deviceChoice49.setLabelString("Type"); - deviceChoice49.setOffsetNid(259); - deviceChoice49.setUpdateIdentifier(""); - jPanel117.add(deviceChoice49); - deviceField115.setIdentifier(""); - deviceField115.setLabelString("Seg. Len: "); - deviceField115.setNumCols(5); - deviceField115.setOffsetNid(261); - jPanel117.add(deviceField115); - jPanel101.add(jPanel117); - jScrollPane3.setViewportView(jPanel101); - jTabbedPane1.addTab("Outputs", jScrollPane3); - jPanel1.add(jTabbedPane1, java.awt.BorderLayout.CENTER); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice1; - private DeviceChoice deviceChoice10; - private DeviceChoice deviceChoice11; - private DeviceChoice deviceChoice12; - private DeviceChoice deviceChoice13; - private DeviceChoice deviceChoice14; - private DeviceChoice deviceChoice15; - private DeviceChoice deviceChoice16; - private DeviceChoice deviceChoice17; - private DeviceChoice deviceChoice18; - private DeviceChoice deviceChoice19; - private DeviceChoice deviceChoice2; - private DeviceChoice deviceChoice20; - private DeviceChoice deviceChoice21; - private DeviceChoice deviceChoice22; - private DeviceChoice deviceChoice23; - private DeviceChoice deviceChoice24; - private DeviceChoice deviceChoice25; - private DeviceChoice deviceChoice26; - private DeviceChoice deviceChoice27; - private DeviceChoice deviceChoice28; - private DeviceChoice deviceChoice29; - private DeviceChoice deviceChoice3; - private DeviceChoice deviceChoice30; - private DeviceChoice deviceChoice31; - private DeviceChoice deviceChoice32; - private DeviceChoice deviceChoice34; - private DeviceChoice deviceChoice35; - private DeviceChoice deviceChoice36; - private DeviceChoice deviceChoice37; - private DeviceChoice deviceChoice38; - private DeviceChoice deviceChoice39; - private DeviceChoice deviceChoice4; - private DeviceChoice deviceChoice40; - private DeviceChoice deviceChoice41; - private DeviceChoice deviceChoice42; - private DeviceChoice deviceChoice43; - private DeviceChoice deviceChoice44; - private DeviceChoice deviceChoice45; - private DeviceChoice deviceChoice46; - private DeviceChoice deviceChoice47; - private DeviceChoice deviceChoice48; - private DeviceChoice deviceChoice49; - private DeviceChoice deviceChoice5; - private DeviceChoice deviceChoice6; - private DeviceChoice deviceChoice7; - private DeviceChoice deviceChoice8; - private DeviceChoice deviceChoice9; - private DeviceField deviceField1; - private DeviceField deviceField10; - private DeviceField deviceField100; - private DeviceField deviceField101; - private DeviceField deviceField102; - private DeviceField deviceField103; - private DeviceField deviceField104; - private DeviceField deviceField105; - private DeviceField deviceField106; - private DeviceField deviceField107; - private DeviceField deviceField108; - private DeviceField deviceField109; - private DeviceField deviceField11; - private DeviceField deviceField110; - private DeviceField deviceField111; - private DeviceField deviceField112; - private DeviceField deviceField113; - private DeviceField deviceField114; - private DeviceField deviceField115; - private DeviceField deviceField12; - private DeviceField deviceField13; - private DeviceField deviceField14; - private DeviceField deviceField15; - private DeviceField deviceField16; - private DeviceField deviceField17; - private DeviceField deviceField18; - private DeviceField deviceField19; - private DeviceField deviceField2; - private DeviceField deviceField20; - private DeviceField deviceField21; - private DeviceField deviceField22; - private DeviceField deviceField23; - private DeviceField deviceField24; - private DeviceField deviceField25; - private DeviceField deviceField26; - private DeviceField deviceField27; - private DeviceField deviceField28; - private DeviceField deviceField29; - private DeviceField deviceField3; - private DeviceField deviceField30; - private DeviceField deviceField31; - private DeviceField deviceField32; - private DeviceField deviceField33; - private DeviceField deviceField34; - private DeviceField deviceField35; - private DeviceField deviceField36; - private DeviceField deviceField37; - private DeviceField deviceField38; - private DeviceField deviceField39; - private DeviceField deviceField4; - private DeviceField deviceField40; - private DeviceField deviceField41; - private DeviceField deviceField42; - private DeviceField deviceField43; - private DeviceField deviceField44; - private DeviceField deviceField45; - private DeviceField deviceField46; - private DeviceField deviceField47; - private DeviceField deviceField48; - private DeviceField deviceField49; - private DeviceField deviceField5; - private DeviceField deviceField50; - private DeviceField deviceField51; - private DeviceField deviceField52; - private DeviceField deviceField53; - private DeviceField deviceField54; - private DeviceField deviceField55; - private DeviceField deviceField56; - private DeviceField deviceField57; - private DeviceField deviceField58; - private DeviceField deviceField59; - private DeviceField deviceField6; - private DeviceField deviceField60; - private DeviceField deviceField61; - private DeviceField deviceField62; - private DeviceField deviceField63; - private DeviceField deviceField64; - private DeviceField deviceField65; - private DeviceField deviceField66; - private DeviceField deviceField67; - private DeviceField deviceField68; - private DeviceField deviceField69; - private DeviceField deviceField7; - private DeviceField deviceField70; - private DeviceField deviceField71; - private DeviceField deviceField72; - private DeviceField deviceField73; - private DeviceField deviceField74; - private DeviceField deviceField75; - private DeviceField deviceField76; - private DeviceField deviceField77; - private DeviceField deviceField78; - private DeviceField deviceField79; - private DeviceField deviceField8; - private DeviceField deviceField80; - private DeviceField deviceField81; - private DeviceField deviceField82; - private DeviceField deviceField83; - private DeviceField deviceField84; - private DeviceField deviceField85; - private DeviceField deviceField86; - private DeviceField deviceField87; - private DeviceField deviceField88; - private DeviceField deviceField89; - private DeviceField deviceField9; - private DeviceField deviceField90; - private DeviceField deviceField91; - private DeviceField deviceField92; - private DeviceField deviceField93; - private DeviceField deviceField94; - private DeviceField deviceField95; - private DeviceField deviceField96; - private DeviceField deviceField97; - private DeviceField deviceField98; - private DeviceField deviceField99; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel10; - private javax.swing.JPanel jPanel100; - private javax.swing.JPanel jPanel101; - private javax.swing.JPanel jPanel102; - private javax.swing.JPanel jPanel103; - private javax.swing.JPanel jPanel104; - private javax.swing.JPanel jPanel105; - private javax.swing.JPanel jPanel106; - private javax.swing.JPanel jPanel107; - private javax.swing.JPanel jPanel108; - private javax.swing.JPanel jPanel109; - private javax.swing.JPanel jPanel11; - private javax.swing.JPanel jPanel110; - private javax.swing.JPanel jPanel111; - private javax.swing.JPanel jPanel112; - private javax.swing.JPanel jPanel113; - private javax.swing.JPanel jPanel114; - private javax.swing.JPanel jPanel115; - private javax.swing.JPanel jPanel116; - private javax.swing.JPanel jPanel117; - private javax.swing.JPanel jPanel12; - private javax.swing.JPanel jPanel13; - private javax.swing.JPanel jPanel14; - private javax.swing.JPanel jPanel15; - private javax.swing.JPanel jPanel16; - private javax.swing.JPanel jPanel17; - private javax.swing.JPanel jPanel18; - private javax.swing.JPanel jPanel19; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel20; - private javax.swing.JPanel jPanel21; - private javax.swing.JPanel jPanel22; - private javax.swing.JPanel jPanel23; - private javax.swing.JPanel jPanel24; - private javax.swing.JPanel jPanel25; - private javax.swing.JPanel jPanel26; - private javax.swing.JPanel jPanel27; - private javax.swing.JPanel jPanel28; - private javax.swing.JPanel jPanel29; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel30; - private javax.swing.JPanel jPanel31; - private javax.swing.JPanel jPanel32; - private javax.swing.JPanel jPanel33; - private javax.swing.JPanel jPanel34; - private javax.swing.JPanel jPanel35; - private javax.swing.JPanel jPanel36; - private javax.swing.JPanel jPanel37; - private javax.swing.JPanel jPanel38; - private javax.swing.JPanel jPanel39; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel40; - private javax.swing.JPanel jPanel41; - private javax.swing.JPanel jPanel42; - private javax.swing.JPanel jPanel43; - private javax.swing.JPanel jPanel44; - private javax.swing.JPanel jPanel45; - private javax.swing.JPanel jPanel46; - private javax.swing.JPanel jPanel47; - private javax.swing.JPanel jPanel48; - private javax.swing.JPanel jPanel49; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel50; - private javax.swing.JPanel jPanel51; - private javax.swing.JPanel jPanel52; - private javax.swing.JPanel jPanel53; - private javax.swing.JPanel jPanel54; - private javax.swing.JPanel jPanel55; - private javax.swing.JPanel jPanel56; - private javax.swing.JPanel jPanel57; - private javax.swing.JPanel jPanel58; - private javax.swing.JPanel jPanel59; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel60; - private javax.swing.JPanel jPanel61; - private javax.swing.JPanel jPanel62; - private javax.swing.JPanel jPanel63; - private javax.swing.JPanel jPanel64; - private javax.swing.JPanel jPanel65; - private javax.swing.JPanel jPanel66; - private javax.swing.JPanel jPanel67; - private javax.swing.JPanel jPanel68; - private javax.swing.JPanel jPanel69; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel70; - private javax.swing.JPanel jPanel71; - private javax.swing.JPanel jPanel72; - private javax.swing.JPanel jPanel73; - private javax.swing.JPanel jPanel74; - private javax.swing.JPanel jPanel75; - private javax.swing.JPanel jPanel76; - private javax.swing.JPanel jPanel77; - private javax.swing.JPanel jPanel78; - private javax.swing.JPanel jPanel79; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel80; - private javax.swing.JPanel jPanel81; - private javax.swing.JPanel jPanel82; - private javax.swing.JPanel jPanel83; - private javax.swing.JPanel jPanel84; - private javax.swing.JPanel jPanel85; - private javax.swing.JPanel jPanel86; - private javax.swing.JPanel jPanel87; - private javax.swing.JPanel jPanel88; - private javax.swing.JPanel jPanel89; - private javax.swing.JPanel jPanel9; - private javax.swing.JPanel jPanel90; - private javax.swing.JPanel jPanel91; - private javax.swing.JPanel jPanel92; - private javax.swing.JPanel jPanel93; - private javax.swing.JPanel jPanel94; - private javax.swing.JPanel jPanel95; - private javax.swing.JPanel jPanel96; - private javax.swing.JPanel jPanel97; - private javax.swing.JPanel jPanel98; - private javax.swing.JPanel jPanel99; - private javax.swing.JScrollPane jScrollPane1; - private javax.swing.JScrollPane jScrollPane2; - private javax.swing.JScrollPane jScrollPane3; - private javax.swing.JTabbedPane jTabbedPane1; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel1 = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField2 = new DeviceField(); + deviceField67 = new DeviceField(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jScrollPane1 = new javax.swing.JScrollPane(); + jPanel4 = new javax.swing.JPanel(); + jPanel14 = new javax.swing.JPanel(); + jPanel15 = new javax.swing.JPanel(); + deviceField7 = new DeviceField(); + jPanel16 = new javax.swing.JPanel(); + deviceField8 = new DeviceField(); + jPanel17 = new javax.swing.JPanel(); + jPanel18 = new javax.swing.JPanel(); + deviceField9 = new DeviceField(); + jPanel19 = new javax.swing.JPanel(); + deviceField10 = new DeviceField(); + jPanel20 = new javax.swing.JPanel(); + jPanel21 = new javax.swing.JPanel(); + deviceField11 = new DeviceField(); + jPanel22 = new javax.swing.JPanel(); + deviceField12 = new DeviceField(); + jPanel23 = new javax.swing.JPanel(); + jPanel24 = new javax.swing.JPanel(); + deviceField13 = new DeviceField(); + jPanel25 = new javax.swing.JPanel(); + deviceField14 = new DeviceField(); + jPanel26 = new javax.swing.JPanel(); + jPanel27 = new javax.swing.JPanel(); + deviceField15 = new DeviceField(); + jPanel28 = new javax.swing.JPanel(); + deviceField16 = new DeviceField(); + jPanel29 = new javax.swing.JPanel(); + jPanel30 = new javax.swing.JPanel(); + deviceField17 = new DeviceField(); + jPanel31 = new javax.swing.JPanel(); + deviceField18 = new DeviceField(); + jPanel32 = new javax.swing.JPanel(); + jPanel33 = new javax.swing.JPanel(); + deviceField19 = new DeviceField(); + jPanel34 = new javax.swing.JPanel(); + deviceField20 = new DeviceField(); + jPanel35 = new javax.swing.JPanel(); + jPanel36 = new javax.swing.JPanel(); + deviceField21 = new DeviceField(); + jPanel37 = new javax.swing.JPanel(); + deviceField22 = new DeviceField(); + jPanel38 = new javax.swing.JPanel(); + jPanel39 = new javax.swing.JPanel(); + deviceField23 = new DeviceField(); + jPanel40 = new javax.swing.JPanel(); + deviceField24 = new DeviceField(); + jPanel41 = new javax.swing.JPanel(); + jPanel42 = new javax.swing.JPanel(); + deviceField25 = new DeviceField(); + jPanel43 = new javax.swing.JPanel(); + deviceField26 = new DeviceField(); + jPanel44 = new javax.swing.JPanel(); + jPanel45 = new javax.swing.JPanel(); + deviceField27 = new DeviceField(); + jPanel46 = new javax.swing.JPanel(); + deviceField28 = new DeviceField(); + jPanel47 = new javax.swing.JPanel(); + jPanel48 = new javax.swing.JPanel(); + deviceField29 = new DeviceField(); + jPanel49 = new javax.swing.JPanel(); + deviceField30 = new DeviceField(); + jPanel50 = new javax.swing.JPanel(); + jPanel51 = new javax.swing.JPanel(); + deviceField31 = new DeviceField(); + jPanel52 = new javax.swing.JPanel(); + deviceField32 = new DeviceField(); + jPanel53 = new javax.swing.JPanel(); + jPanel54 = new javax.swing.JPanel(); + deviceField33 = new DeviceField(); + jPanel55 = new javax.swing.JPanel(); + deviceField34 = new DeviceField(); + jPanel56 = new javax.swing.JPanel(); + jPanel57 = new javax.swing.JPanel(); + deviceField35 = new DeviceField(); + jPanel58 = new javax.swing.JPanel(); + deviceField36 = new DeviceField(); + jPanel59 = new javax.swing.JPanel(); + jPanel60 = new javax.swing.JPanel(); + deviceField37 = new DeviceField(); + jPanel61 = new javax.swing.JPanel(); + deviceField38 = new DeviceField(); + jScrollPane2 = new javax.swing.JScrollPane(); + jPanel3 = new javax.swing.JPanel(); + jPanel5 = new javax.swing.JPanel(); + jPanel6 = new javax.swing.JPanel(); + deviceChoice1 = new DeviceChoice(); + deviceField3 = new DeviceField(); + deviceChoice2 = new DeviceChoice(); + jPanel7 = new javax.swing.JPanel(); + deviceField4 = new DeviceField(); + jPanel8 = new javax.swing.JPanel(); + jPanel9 = new javax.swing.JPanel(); + deviceChoice3 = new DeviceChoice(); + deviceField5 = new DeviceField(); + deviceChoice4 = new DeviceChoice(); + jPanel10 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + jPanel11 = new javax.swing.JPanel(); + jPanel12 = new javax.swing.JPanel(); + deviceChoice5 = new DeviceChoice(); + deviceField39 = new DeviceField(); + deviceChoice6 = new DeviceChoice(); + jPanel13 = new javax.swing.JPanel(); + deviceField40 = new DeviceField(); + jPanel62 = new javax.swing.JPanel(); + jPanel63 = new javax.swing.JPanel(); + deviceChoice7 = new DeviceChoice(); + deviceField41 = new DeviceField(); + deviceChoice8 = new DeviceChoice(); + jPanel64 = new javax.swing.JPanel(); + deviceField42 = new DeviceField(); + jPanel65 = new javax.swing.JPanel(); + jPanel66 = new javax.swing.JPanel(); + deviceChoice9 = new DeviceChoice(); + deviceField43 = new DeviceField(); + deviceChoice10 = new DeviceChoice(); + jPanel67 = new javax.swing.JPanel(); + deviceField44 = new DeviceField(); + jPanel68 = new javax.swing.JPanel(); + jPanel69 = new javax.swing.JPanel(); + deviceChoice11 = new DeviceChoice(); + deviceField45 = new DeviceField(); + deviceChoice12 = new DeviceChoice(); + jPanel70 = new javax.swing.JPanel(); + deviceField46 = new DeviceField(); + jPanel71 = new javax.swing.JPanel(); + jPanel72 = new javax.swing.JPanel(); + deviceChoice13 = new DeviceChoice(); + deviceField47 = new DeviceField(); + deviceChoice14 = new DeviceChoice(); + jPanel73 = new javax.swing.JPanel(); + deviceField48 = new DeviceField(); + jPanel74 = new javax.swing.JPanel(); + jPanel75 = new javax.swing.JPanel(); + deviceChoice15 = new DeviceChoice(); + deviceField49 = new DeviceField(); + deviceChoice16 = new DeviceChoice(); + jPanel76 = new javax.swing.JPanel(); + deviceField50 = new DeviceField(); + jPanel77 = new javax.swing.JPanel(); + jPanel78 = new javax.swing.JPanel(); + deviceChoice17 = new DeviceChoice(); + deviceField51 = new DeviceField(); + deviceChoice18 = new DeviceChoice(); + jPanel79 = new javax.swing.JPanel(); + deviceField52 = new DeviceField(); + jPanel80 = new javax.swing.JPanel(); + jPanel81 = new javax.swing.JPanel(); + deviceChoice19 = new DeviceChoice(); + deviceField53 = new DeviceField(); + deviceChoice20 = new DeviceChoice(); + jPanel82 = new javax.swing.JPanel(); + deviceField54 = new DeviceField(); + jPanel83 = new javax.swing.JPanel(); + jPanel84 = new javax.swing.JPanel(); + deviceChoice21 = new DeviceChoice(); + deviceField55 = new DeviceField(); + deviceChoice22 = new DeviceChoice(); + jPanel85 = new javax.swing.JPanel(); + deviceField56 = new DeviceField(); + jPanel86 = new javax.swing.JPanel(); + jPanel87 = new javax.swing.JPanel(); + deviceChoice23 = new DeviceChoice(); + deviceField57 = new DeviceField(); + deviceChoice24 = new DeviceChoice(); + jPanel88 = new javax.swing.JPanel(); + deviceField58 = new DeviceField(); + jPanel89 = new javax.swing.JPanel(); + jPanel90 = new javax.swing.JPanel(); + deviceChoice25 = new DeviceChoice(); + deviceField59 = new DeviceField(); + deviceChoice26 = new DeviceChoice(); + jPanel91 = new javax.swing.JPanel(); + deviceField60 = new DeviceField(); + jPanel92 = new javax.swing.JPanel(); + jPanel93 = new javax.swing.JPanel(); + deviceChoice27 = new DeviceChoice(); + deviceField61 = new DeviceField(); + deviceChoice28 = new DeviceChoice(); + jPanel94 = new javax.swing.JPanel(); + deviceField62 = new DeviceField(); + jPanel95 = new javax.swing.JPanel(); + jPanel96 = new javax.swing.JPanel(); + deviceChoice29 = new DeviceChoice(); + deviceField63 = new DeviceField(); + deviceChoice30 = new DeviceChoice(); + jPanel97 = new javax.swing.JPanel(); + deviceField64 = new DeviceField(); + jPanel98 = new javax.swing.JPanel(); + jPanel99 = new javax.swing.JPanel(); + deviceChoice31 = new DeviceChoice(); + deviceField65 = new DeviceField(); + deviceChoice32 = new DeviceChoice(); + jPanel100 = new javax.swing.JPanel(); + deviceField66 = new DeviceField(); + jScrollPane3 = new javax.swing.JScrollPane(); + jPanel101 = new javax.swing.JPanel(); + jPanel102 = new javax.swing.JPanel(); + deviceField69 = new DeviceField(); + deviceField68 = new DeviceField(); + deviceChoice34 = new DeviceChoice(); + deviceField70 = new DeviceField(); + jPanel103 = new javax.swing.JPanel(); + deviceField71 = new DeviceField(); + deviceField72 = new DeviceField(); + deviceChoice35 = new DeviceChoice(); + deviceField73 = new DeviceField(); + jPanel104 = new javax.swing.JPanel(); + deviceField74 = new DeviceField(); + deviceField75 = new DeviceField(); + deviceChoice36 = new DeviceChoice(); + deviceField76 = new DeviceField(); + jPanel105 = new javax.swing.JPanel(); + deviceField77 = new DeviceField(); + deviceField78 = new DeviceField(); + deviceChoice37 = new DeviceChoice(); + deviceField79 = new DeviceField(); + jPanel106 = new javax.swing.JPanel(); + deviceField80 = new DeviceField(); + deviceField81 = new DeviceField(); + deviceChoice38 = new DeviceChoice(); + deviceField82 = new DeviceField(); + jPanel107 = new javax.swing.JPanel(); + deviceField83 = new DeviceField(); + deviceField84 = new DeviceField(); + deviceChoice39 = new DeviceChoice(); + deviceField85 = new DeviceField(); + jPanel108 = new javax.swing.JPanel(); + deviceField86 = new DeviceField(); + deviceField87 = new DeviceField(); + deviceChoice40 = new DeviceChoice(); + deviceField88 = new DeviceField(); + jPanel109 = new javax.swing.JPanel(); + deviceField89 = new DeviceField(); + deviceField90 = new DeviceField(); + deviceChoice41 = new DeviceChoice(); + deviceField91 = new DeviceField(); + jPanel110 = new javax.swing.JPanel(); + deviceField92 = new DeviceField(); + deviceField93 = new DeviceField(); + deviceChoice42 = new DeviceChoice(); + deviceField94 = new DeviceField(); + jPanel111 = new javax.swing.JPanel(); + deviceField95 = new DeviceField(); + deviceField96 = new DeviceField(); + deviceChoice43 = new DeviceChoice(); + deviceField97 = new DeviceField(); + jPanel112 = new javax.swing.JPanel(); + deviceField98 = new DeviceField(); + deviceField99 = new DeviceField(); + deviceChoice44 = new DeviceChoice(); + deviceField100 = new DeviceField(); + jPanel113 = new javax.swing.JPanel(); + deviceField101 = new DeviceField(); + deviceField102 = new DeviceField(); + deviceChoice45 = new DeviceChoice(); + deviceField103 = new DeviceField(); + jPanel114 = new javax.swing.JPanel(); + deviceField104 = new DeviceField(); + deviceField105 = new DeviceField(); + deviceChoice46 = new DeviceChoice(); + deviceField106 = new DeviceField(); + jPanel115 = new javax.swing.JPanel(); + deviceField107 = new DeviceField(); + deviceField108 = new DeviceField(); + deviceChoice47 = new DeviceChoice(); + deviceField109 = new DeviceField(); + jPanel116 = new javax.swing.JPanel(); + deviceField110 = new DeviceField(); + deviceField111 = new DeviceField(); + deviceChoice48 = new DeviceChoice(); + deviceField112 = new DeviceField(); + jPanel117 = new javax.swing.JPanel(); + deviceField113 = new DeviceField(); + deviceField114 = new DeviceField(); + deviceChoice49 = new DeviceChoice(); + deviceField115 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 Generic GAM"); + setDeviceType("MARTE2_GAM"); + setHeight(500); + setWidth(750); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + jPanel1.setLayout(new java.awt.BorderLayout()); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("GAM Class: "); + deviceField1.setNumCols(15); + deviceField1.setOffsetNid(1); + deviceField1.setTextOnly(true); + jPanel2.add(deviceField1); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Timebase: "); + deviceField2.setNumCols(25); + deviceField2.setOffsetNid(3); + jPanel2.add(deviceField2); + + deviceField67.setIdentifier(""); + deviceField67.setLabelString("Trigger: "); + deviceField67.setNumCols(15); + deviceField67.setOffsetNid(151); + jPanel2.add(deviceField67); + + jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH); + + jPanel4.setLayout(new java.awt.GridLayout(16, 1)); + + jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 1")); + jPanel14.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Name: "); + deviceField7.setNumCols(15); + deviceField7.setOffsetNid(6); + deviceField7.setTextOnly(true); + jPanel15.add(deviceField7); + + jPanel14.add(jPanel15); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Value: "); + deviceField8.setNumCols(25); + deviceField8.setOffsetNid(7); + jPanel16.add(deviceField8); + + jPanel14.add(jPanel16); + + jPanel4.add(jPanel14); + + jPanel17.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 2")); + jPanel17.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Name: "); + deviceField9.setNumCols(15); + deviceField9.setOffsetNid(9); + deviceField9.setTextOnly(true); + jPanel18.add(deviceField9); + + jPanel17.add(jPanel18); + + deviceField10.setIdentifier(""); + deviceField10.setLabelString("Value: "); + deviceField10.setNumCols(25); + deviceField10.setOffsetNid(10); + jPanel19.add(deviceField10); + + jPanel17.add(jPanel19); + + jPanel4.add(jPanel17); + + jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 3")); + jPanel20.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField11.setIdentifier(""); + deviceField11.setLabelString("Name: "); + deviceField11.setNumCols(15); + deviceField11.setOffsetNid(12); + deviceField11.setTextOnly(true); + jPanel21.add(deviceField11); + + jPanel20.add(jPanel21); + + deviceField12.setIdentifier(""); + deviceField12.setLabelString("Value: "); + deviceField12.setNumCols(25); + deviceField12.setOffsetNid(13); + jPanel22.add(deviceField12); + + jPanel20.add(jPanel22); + + jPanel4.add(jPanel20); + + jPanel23.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 4")); + jPanel23.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField13.setIdentifier(""); + deviceField13.setLabelString("Name: "); + deviceField13.setNumCols(15); + deviceField13.setOffsetNid(15); + deviceField13.setTextOnly(true); + jPanel24.add(deviceField13); + + jPanel23.add(jPanel24); + + deviceField14.setIdentifier(""); + deviceField14.setLabelString("Value: "); + deviceField14.setNumCols(25); + deviceField14.setOffsetNid(16); + jPanel25.add(deviceField14); + + jPanel23.add(jPanel25); + + jPanel4.add(jPanel23); + + jPanel26.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 5")); + jPanel26.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField15.setIdentifier(""); + deviceField15.setLabelString("Name: "); + deviceField15.setNumCols(15); + deviceField15.setOffsetNid(18); + deviceField15.setTextOnly(true); + jPanel27.add(deviceField15); + + jPanel26.add(jPanel27); + + deviceField16.setIdentifier(""); + deviceField16.setLabelString("Value: "); + deviceField16.setNumCols(25); + deviceField16.setOffsetNid(19); + jPanel28.add(deviceField16); + + jPanel26.add(jPanel28); + + jPanel4.add(jPanel26); + + jPanel29.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 6")); + jPanel29.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField17.setIdentifier(""); + deviceField17.setLabelString("Name: "); + deviceField17.setNumCols(15); + deviceField17.setOffsetNid(21); + deviceField17.setTextOnly(true); + jPanel30.add(deviceField17); + + jPanel29.add(jPanel30); + + deviceField18.setIdentifier(""); + deviceField18.setLabelString("Value: "); + deviceField18.setNumCols(25); + deviceField18.setOffsetNid(22); + jPanel31.add(deviceField18); + + jPanel29.add(jPanel31); + + jPanel4.add(jPanel29); + + jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 7")); + jPanel32.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField19.setIdentifier(""); + deviceField19.setLabelString("Name: "); + deviceField19.setNumCols(15); + deviceField19.setOffsetNid(24); + deviceField19.setTextOnly(true); + jPanel33.add(deviceField19); + + jPanel32.add(jPanel33); + + deviceField20.setIdentifier(""); + deviceField20.setLabelString("Value: "); + deviceField20.setNumCols(25); + deviceField20.setOffsetNid(25); + jPanel34.add(deviceField20); + + jPanel32.add(jPanel34); + + jPanel4.add(jPanel32); + + jPanel35.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 8")); + jPanel35.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField21.setIdentifier(""); + deviceField21.setLabelString("Name: "); + deviceField21.setNumCols(15); + deviceField21.setOffsetNid(27); + deviceField21.setTextOnly(true); + jPanel36.add(deviceField21); + + jPanel35.add(jPanel36); + + deviceField22.setIdentifier(""); + deviceField22.setLabelString("Value: "); + deviceField22.setNumCols(25); + deviceField22.setOffsetNid(28); + jPanel37.add(deviceField22); + + jPanel35.add(jPanel37); + + jPanel4.add(jPanel35); + + jPanel38.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 9")); + jPanel38.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField23.setIdentifier(""); + deviceField23.setLabelString("Name: "); + deviceField23.setNumCols(15); + deviceField23.setOffsetNid(30); + deviceField23.setTextOnly(true); + jPanel39.add(deviceField23); + + jPanel38.add(jPanel39); + + deviceField24.setIdentifier(""); + deviceField24.setLabelString("Value: "); + deviceField24.setNumCols(25); + deviceField24.setOffsetNid(31); + jPanel40.add(deviceField24); + + jPanel38.add(jPanel40); + + jPanel4.add(jPanel38); + + jPanel41.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 10")); + jPanel41.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField25.setIdentifier(""); + deviceField25.setLabelString("Name: "); + deviceField25.setNumCols(15); + deviceField25.setOffsetNid(33); + deviceField25.setTextOnly(true); + jPanel42.add(deviceField25); + + jPanel41.add(jPanel42); + + deviceField26.setIdentifier(""); + deviceField26.setLabelString("Value: "); + deviceField26.setNumCols(25); + deviceField26.setOffsetNid(34); + jPanel43.add(deviceField26); + + jPanel41.add(jPanel43); + + jPanel4.add(jPanel41); + + jPanel44.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 11")); + jPanel44.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField27.setIdentifier(""); + deviceField27.setLabelString("Name: "); + deviceField27.setNumCols(15); + deviceField27.setOffsetNid(36); + deviceField27.setTextOnly(true); + jPanel45.add(deviceField27); + + jPanel44.add(jPanel45); + + deviceField28.setIdentifier(""); + deviceField28.setLabelString("Value: "); + deviceField28.setNumCols(25); + deviceField28.setOffsetNid(37); + jPanel46.add(deviceField28); + + jPanel44.add(jPanel46); + + jPanel4.add(jPanel44); + + jPanel47.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 12")); + jPanel47.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField29.setIdentifier(""); + deviceField29.setLabelString("Name: "); + deviceField29.setNumCols(15); + deviceField29.setOffsetNid(39); + deviceField29.setTextOnly(true); + jPanel48.add(deviceField29); + + jPanel47.add(jPanel48); + + deviceField30.setIdentifier(""); + deviceField30.setLabelString("Value: "); + deviceField30.setNumCols(25); + deviceField30.setOffsetNid(40); + jPanel49.add(deviceField30); + + jPanel47.add(jPanel49); + + jPanel4.add(jPanel47); + + jPanel50.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 13")); + jPanel50.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField31.setIdentifier(""); + deviceField31.setLabelString("Name: "); + deviceField31.setNumCols(15); + deviceField31.setOffsetNid(42); + deviceField31.setTextOnly(true); + jPanel51.add(deviceField31); + + jPanel50.add(jPanel51); + + deviceField32.setIdentifier(""); + deviceField32.setLabelString("Value: "); + deviceField32.setNumCols(25); + deviceField32.setOffsetNid(43); + jPanel52.add(deviceField32); + + jPanel50.add(jPanel52); + + jPanel4.add(jPanel50); + + jPanel53.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 14")); + jPanel53.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField33.setIdentifier(""); + deviceField33.setLabelString("Name: "); + deviceField33.setNumCols(15); + deviceField33.setOffsetNid(45); + deviceField33.setTextOnly(true); + jPanel54.add(deviceField33); + + jPanel53.add(jPanel54); + + deviceField34.setIdentifier(""); + deviceField34.setLabelString("Value: "); + deviceField34.setNumCols(25); + deviceField34.setOffsetNid(46); + jPanel55.add(deviceField34); + + jPanel53.add(jPanel55); + + jPanel4.add(jPanel53); + + jPanel56.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 15")); + jPanel56.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField35.setIdentifier(""); + deviceField35.setLabelString("Name: "); + deviceField35.setNumCols(15); + deviceField35.setOffsetNid(48); + deviceField35.setTextOnly(true); + jPanel57.add(deviceField35); + + jPanel56.add(jPanel57); + + deviceField36.setIdentifier(""); + deviceField36.setLabelString("Value: "); + deviceField36.setNumCols(25); + deviceField36.setOffsetNid(49); + jPanel58.add(deviceField36); + + jPanel56.add(jPanel58); + + jPanel4.add(jPanel56); + + jPanel59.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter 16")); + jPanel59.setLayout(new java.awt.GridLayout(1, 2)); + + deviceField37.setIdentifier(""); + deviceField37.setLabelString("Name: "); + deviceField37.setNumCols(15); + deviceField37.setOffsetNid(51); + deviceField37.setTextOnly(true); + jPanel60.add(deviceField37); + + jPanel59.add(jPanel60); + + deviceField38.setIdentifier(""); + deviceField38.setLabelString("Value: "); + deviceField38.setNumCols(25); + deviceField38.setOffsetNid(52); + jPanel61.add(deviceField38); + + jPanel59.add(jPanel61); + + jPanel4.add(jPanel59); + + jScrollPane1.setViewportView(jPanel4); + + jTabbedPane1.addTab("Parameters", jScrollPane1); + + jPanel3.setLayout(new java.awt.GridLayout(16, 1)); + + jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 1")); + jPanel5.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice1.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString("Column First order:"); + deviceChoice1.setOffsetNid(57); + deviceChoice1.setUpdateIdentifier(""); + jPanel6.add(deviceChoice1); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Dimensions (-1 to disable input):"); + deviceField3.setNumCols(5); + deviceField3.setOffsetNid(56); + jPanel6.add(deviceField3); + + deviceChoice2.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString("Type"); + deviceChoice2.setOffsetNid(55); + deviceChoice2.setUpdateIdentifier(""); + jPanel6.add(deviceChoice2); + + jPanel5.add(jPanel6); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Value: "); + deviceField4.setNumCols(35); + deviceField4.setOffsetNid(58); + jPanel7.add(deviceField4); + + jPanel5.add(jPanel7); + + jPanel3.add(jPanel5); + + jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 2")); + jPanel8.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice3.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString("Column First order:"); + deviceChoice3.setOffsetNid(63); + deviceChoice3.setUpdateIdentifier(""); + jPanel9.add(deviceChoice3); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Dimensions (-1 to disable input):"); + deviceField5.setNumCols(5); + deviceField5.setOffsetNid(62); + jPanel9.add(deviceField5); + + deviceChoice4.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice4.setIdentifier(""); + deviceChoice4.setLabelString("Type"); + deviceChoice4.setOffsetNid(61); + deviceChoice4.setUpdateIdentifier(""); + jPanel9.add(deviceChoice4); + + jPanel8.add(jPanel9); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Value: "); + deviceField6.setNumCols(35); + deviceField6.setOffsetNid(64); + jPanel10.add(deviceField6); + + jPanel8.add(jPanel10); + + jPanel3.add(jPanel8); + + jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 3")); + jPanel11.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice5.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice5.setIdentifier(""); + deviceChoice5.setLabelString("Column First order:"); + deviceChoice5.setOffsetNid(69); + deviceChoice5.setUpdateIdentifier(""); + jPanel12.add(deviceChoice5); + + deviceField39.setIdentifier(""); + deviceField39.setLabelString("Dimensions (-1 to disable input):"); + deviceField39.setNumCols(5); + deviceField39.setOffsetNid(68); + jPanel12.add(deviceField39); + + deviceChoice6.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice6.setIdentifier(""); + deviceChoice6.setLabelString("Type"); + deviceChoice6.setOffsetNid(67); + deviceChoice6.setUpdateIdentifier(""); + jPanel12.add(deviceChoice6); + + jPanel11.add(jPanel12); + + deviceField40.setIdentifier(""); + deviceField40.setLabelString("Value: "); + deviceField40.setNumCols(35); + deviceField40.setOffsetNid(70); + jPanel13.add(deviceField40); + + jPanel11.add(jPanel13); + + jPanel3.add(jPanel11); + + jPanel62.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 4")); + jPanel62.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice7.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice7.setIdentifier(""); + deviceChoice7.setLabelString("Column First order:"); + deviceChoice7.setOffsetNid(75); + deviceChoice7.setUpdateIdentifier(""); + jPanel63.add(deviceChoice7); + + deviceField41.setIdentifier(""); + deviceField41.setLabelString("Dimensions (-1 to disable input):"); + deviceField41.setNumCols(5); + deviceField41.setOffsetNid(74); + jPanel63.add(deviceField41); + + deviceChoice8.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice8.setIdentifier(""); + deviceChoice8.setLabelString("Type"); + deviceChoice8.setOffsetNid(73); + deviceChoice8.setUpdateIdentifier(""); + jPanel63.add(deviceChoice8); + + jPanel62.add(jPanel63); + + deviceField42.setIdentifier(""); + deviceField42.setLabelString("Value: "); + deviceField42.setNumCols(35); + deviceField42.setOffsetNid(76); + jPanel64.add(deviceField42); + + jPanel62.add(jPanel64); + + jPanel3.add(jPanel62); + + jPanel65.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 5")); + jPanel65.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice9.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice9.setIdentifier(""); + deviceChoice9.setLabelString("Column First order:"); + deviceChoice9.setOffsetNid(81); + deviceChoice9.setUpdateIdentifier(""); + jPanel66.add(deviceChoice9); + + deviceField43.setIdentifier(""); + deviceField43.setLabelString("Dimensions (-1 to disable input):"); + deviceField43.setNumCols(5); + deviceField43.setOffsetNid(80); + jPanel66.add(deviceField43); + + deviceChoice10.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice10.setIdentifier(""); + deviceChoice10.setLabelString("Type"); + deviceChoice10.setOffsetNid(79); + deviceChoice10.setUpdateIdentifier(""); + jPanel66.add(deviceChoice10); + + jPanel65.add(jPanel66); + + deviceField44.setIdentifier(""); + deviceField44.setLabelString("Value: "); + deviceField44.setNumCols(35); + deviceField44.setOffsetNid(82); + jPanel67.add(deviceField44); + + jPanel65.add(jPanel67); + + jPanel3.add(jPanel65); + + jPanel68.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 6")); + jPanel68.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice11.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice11.setIdentifier(""); + deviceChoice11.setLabelString("Column First order:"); + deviceChoice11.setOffsetNid(87); + deviceChoice11.setUpdateIdentifier(""); + jPanel69.add(deviceChoice11); + + deviceField45.setIdentifier(""); + deviceField45.setLabelString("Dimensions (-1 to disable input):"); + deviceField45.setNumCols(5); + deviceField45.setOffsetNid(86); + jPanel69.add(deviceField45); + + deviceChoice12.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice12.setIdentifier(""); + deviceChoice12.setLabelString("Type"); + deviceChoice12.setOffsetNid(85); + deviceChoice12.setUpdateIdentifier(""); + jPanel69.add(deviceChoice12); + + jPanel68.add(jPanel69); + + deviceField46.setIdentifier(""); + deviceField46.setLabelString("Value: "); + deviceField46.setNumCols(35); + deviceField46.setOffsetNid(88); + jPanel70.add(deviceField46); + + jPanel68.add(jPanel70); + + jPanel3.add(jPanel68); + + jPanel71.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 7")); + jPanel71.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice13.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice13.setIdentifier(""); + deviceChoice13.setLabelString("Column First order:"); + deviceChoice13.setOffsetNid(93); + deviceChoice13.setUpdateIdentifier(""); + jPanel72.add(deviceChoice13); + + deviceField47.setIdentifier(""); + deviceField47.setLabelString("Dimensions (-1 to disable input):"); + deviceField47.setNumCols(5); + deviceField47.setOffsetNid(86); + jPanel72.add(deviceField47); + + deviceChoice14.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice14.setIdentifier(""); + deviceChoice14.setLabelString("Type"); + deviceChoice14.setOffsetNid(91); + deviceChoice14.setUpdateIdentifier(""); + jPanel72.add(deviceChoice14); + + jPanel71.add(jPanel72); + + deviceField48.setIdentifier(""); + deviceField48.setLabelString("Value: "); + deviceField48.setNumCols(35); + deviceField48.setOffsetNid(94); + jPanel73.add(deviceField48); + + jPanel71.add(jPanel73); + + jPanel3.add(jPanel71); + + jPanel74.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 8")); + jPanel74.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice15.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice15.setIdentifier(""); + deviceChoice15.setLabelString("Column First order:"); + deviceChoice15.setOffsetNid(99); + deviceChoice15.setUpdateIdentifier(""); + jPanel75.add(deviceChoice15); + + deviceField49.setIdentifier(""); + deviceField49.setLabelString("Dimensions (-1 to disable input):"); + deviceField49.setNumCols(5); + deviceField49.setOffsetNid(98); + jPanel75.add(deviceField49); + + deviceChoice16.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice16.setIdentifier(""); + deviceChoice16.setLabelString("Type"); + deviceChoice16.setOffsetNid(97); + deviceChoice16.setUpdateIdentifier(""); + jPanel75.add(deviceChoice16); + + jPanel74.add(jPanel75); + + deviceField50.setIdentifier(""); + deviceField50.setLabelString("Value: "); + deviceField50.setNumCols(35); + deviceField50.setOffsetNid(100); + jPanel76.add(deviceField50); + + jPanel74.add(jPanel76); + + jPanel3.add(jPanel74); + + jPanel77.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 9")); + jPanel77.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice17.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice17.setIdentifier(""); + deviceChoice17.setLabelString("Column First order:"); + deviceChoice17.setOffsetNid(105); + deviceChoice17.setUpdateIdentifier(""); + jPanel78.add(deviceChoice17); + + deviceField51.setIdentifier(""); + deviceField51.setLabelString("Dimensions (-1 to disable input):"); + deviceField51.setNumCols(5); + deviceField51.setOffsetNid(104); + jPanel78.add(deviceField51); + + deviceChoice18.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice18.setIdentifier(""); + deviceChoice18.setLabelString("Type"); + deviceChoice18.setOffsetNid(103); + deviceChoice18.setUpdateIdentifier(""); + jPanel78.add(deviceChoice18); + + jPanel77.add(jPanel78); + + deviceField52.setIdentifier(""); + deviceField52.setLabelString("Value: "); + deviceField52.setNumCols(35); + deviceField52.setOffsetNid(106); + jPanel79.add(deviceField52); + + jPanel77.add(jPanel79); + + jPanel3.add(jPanel77); + + jPanel80.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 10")); + jPanel80.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice19.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice19.setIdentifier(""); + deviceChoice19.setLabelString("Column First order:"); + deviceChoice19.setOffsetNid(111); + deviceChoice19.setUpdateIdentifier(""); + jPanel81.add(deviceChoice19); + + deviceField53.setIdentifier(""); + deviceField53.setLabelString("Dimensions (-1 to disable input):"); + deviceField53.setNumCols(5); + deviceField53.setOffsetNid(110); + jPanel81.add(deviceField53); + + deviceChoice20.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice20.setIdentifier(""); + deviceChoice20.setLabelString("Type"); + deviceChoice20.setOffsetNid(109); + deviceChoice20.setUpdateIdentifier(""); + jPanel81.add(deviceChoice20); + + jPanel80.add(jPanel81); + + deviceField54.setIdentifier(""); + deviceField54.setLabelString("Value: "); + deviceField54.setNumCols(35); + deviceField54.setOffsetNid(112); + jPanel82.add(deviceField54); + + jPanel80.add(jPanel82); + + jPanel3.add(jPanel80); + + jPanel83.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 11")); + jPanel83.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice21.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice21.setIdentifier(""); + deviceChoice21.setLabelString("Column First order:"); + deviceChoice21.setOffsetNid(117); + deviceChoice21.setUpdateIdentifier(""); + jPanel84.add(deviceChoice21); + + deviceField55.setIdentifier(""); + deviceField55.setLabelString("Dimensions (-1 to disable input):"); + deviceField55.setNumCols(5); + deviceField55.setOffsetNid(116); + jPanel84.add(deviceField55); + + deviceChoice22.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice22.setIdentifier(""); + deviceChoice22.setLabelString("Type"); + deviceChoice22.setOffsetNid(115); + deviceChoice22.setUpdateIdentifier(""); + jPanel84.add(deviceChoice22); + + jPanel83.add(jPanel84); + + deviceField56.setIdentifier(""); + deviceField56.setLabelString("Value: "); + deviceField56.setNumCols(35); + deviceField56.setOffsetNid(118); + jPanel85.add(deviceField56); + + jPanel83.add(jPanel85); + + jPanel3.add(jPanel83); + + jPanel86.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 12")); + jPanel86.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice23.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice23.setIdentifier(""); + deviceChoice23.setLabelString("Column First order:"); + deviceChoice23.setOffsetNid(123); + deviceChoice23.setUpdateIdentifier(""); + jPanel87.add(deviceChoice23); + + deviceField57.setIdentifier(""); + deviceField57.setLabelString("Dimensions (-1 to disable input):"); + deviceField57.setNumCols(5); + deviceField57.setOffsetNid(122); + jPanel87.add(deviceField57); + + deviceChoice24.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice24.setIdentifier(""); + deviceChoice24.setLabelString("Type"); + deviceChoice24.setOffsetNid(121); + deviceChoice24.setUpdateIdentifier(""); + jPanel87.add(deviceChoice24); + + jPanel86.add(jPanel87); + + deviceField58.setIdentifier(""); + deviceField58.setLabelString("Value: "); + deviceField58.setNumCols(35); + deviceField58.setOffsetNid(124); + jPanel88.add(deviceField58); + + jPanel86.add(jPanel88); + + jPanel3.add(jPanel86); + + jPanel89.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 13")); + jPanel89.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice25.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice25.setIdentifier(""); + deviceChoice25.setLabelString("Column First order:"); + deviceChoice25.setOffsetNid(129); + deviceChoice25.setUpdateIdentifier(""); + jPanel90.add(deviceChoice25); + + deviceField59.setIdentifier(""); + deviceField59.setLabelString("Dimensions (-1 to disable input):"); + deviceField59.setNumCols(5); + deviceField59.setOffsetNid(128); + jPanel90.add(deviceField59); + + deviceChoice26.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice26.setIdentifier(""); + deviceChoice26.setLabelString("Type"); + deviceChoice26.setOffsetNid(127); + deviceChoice26.setUpdateIdentifier(""); + jPanel90.add(deviceChoice26); + + jPanel89.add(jPanel90); + + deviceField60.setIdentifier(""); + deviceField60.setLabelString("Value: "); + deviceField60.setNumCols(35); + deviceField60.setOffsetNid(130); + jPanel91.add(deviceField60); + + jPanel89.add(jPanel91); + + jPanel3.add(jPanel89); + + jPanel92.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 14")); + jPanel92.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice27.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice27.setIdentifier(""); + deviceChoice27.setLabelString("Column First order:"); + deviceChoice27.setOffsetNid(135); + deviceChoice27.setUpdateIdentifier(""); + jPanel93.add(deviceChoice27); + + deviceField61.setIdentifier(""); + deviceField61.setLabelString("Dimensions (-1 to disable input):"); + deviceField61.setNumCols(5); + deviceField61.setOffsetNid(134); + jPanel93.add(deviceField61); + + deviceChoice28.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice28.setIdentifier(""); + deviceChoice28.setLabelString("Type"); + deviceChoice28.setOffsetNid(133); + deviceChoice28.setUpdateIdentifier(""); + jPanel93.add(deviceChoice28); + + jPanel92.add(jPanel93); + + deviceField62.setIdentifier(""); + deviceField62.setLabelString("Value: "); + deviceField62.setNumCols(35); + deviceField62.setOffsetNid(136); + jPanel94.add(deviceField62); + + jPanel92.add(jPanel94); + + jPanel3.add(jPanel92); + + jPanel95.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 15")); + jPanel95.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice29.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice29.setIdentifier(""); + deviceChoice29.setLabelString("Column First order:"); + deviceChoice29.setOffsetNid(141); + deviceChoice29.setUpdateIdentifier(""); + jPanel96.add(deviceChoice29); + + deviceField63.setIdentifier(""); + deviceField63.setLabelString("Dimensions (-1 to disable input):"); + deviceField63.setNumCols(5); + deviceField63.setOffsetNid(140); + jPanel96.add(deviceField63); + + deviceChoice30.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice30.setIdentifier(""); + deviceChoice30.setLabelString("Type"); + deviceChoice30.setOffsetNid(139); + deviceChoice30.setUpdateIdentifier(""); + jPanel96.add(deviceChoice30); + + jPanel95.add(jPanel96); + + deviceField64.setIdentifier(""); + deviceField64.setLabelString("Value: "); + deviceField64.setNumCols(35); + deviceField64.setOffsetNid(142); + jPanel97.add(deviceField64); + + jPanel95.add(jPanel97); + + jPanel3.add(jPanel95); + + jPanel98.setBorder(javax.swing.BorderFactory.createTitledBorder("Input 16")); + jPanel98.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice31.setChoiceItems(new String[] {"NO", "YES"}); + deviceChoice31.setIdentifier(""); + deviceChoice31.setLabelString("Column First order:"); + deviceChoice31.setOffsetNid(147); + deviceChoice31.setUpdateIdentifier(""); + jPanel99.add(deviceChoice31); + + deviceField65.setIdentifier(""); + deviceField65.setLabelString("Dimensions (-1 to disable input):"); + deviceField65.setNumCols(5); + deviceField65.setOffsetNid(146); + jPanel99.add(deviceField65); + + deviceChoice32.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice32.setIdentifier(""); + deviceChoice32.setLabelString("Type"); + deviceChoice32.setOffsetNid(145); + deviceChoice32.setUpdateIdentifier(""); + jPanel99.add(deviceChoice32); + + jPanel98.add(jPanel99); + + deviceField66.setIdentifier(""); + deviceField66.setLabelString("Value: "); + deviceField66.setNumCols(35); + deviceField66.setOffsetNid(148); + jPanel100.add(deviceField66); + + jPanel98.add(jPanel100); + + jPanel3.add(jPanel98); + + jScrollPane2.setViewportView(jPanel3); + + jTabbedPane1.addTab("Inputs", jScrollPane2); + + jPanel101.setLayout(new java.awt.GridLayout(16, 1)); + + jPanel102.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 1")); + + deviceField69.setIdentifier(""); + deviceField69.setLabelString("Name"); + deviceField69.setNumCols(15); + deviceField69.setOffsetNid(153); + deviceField69.setTextOnly(true); + jPanel102.add(deviceField69); + + deviceField68.setIdentifier(""); + deviceField68.setLabelString("Dimensions (-1 to disable output):"); + deviceField68.setNumCols(5); + deviceField68.setOffsetNid(155); + jPanel102.add(deviceField68); + + deviceChoice34.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice34.setIdentifier(""); + deviceChoice34.setLabelString("Type"); + deviceChoice34.setOffsetNid(154); + deviceChoice34.setUpdateIdentifier(""); + jPanel102.add(deviceChoice34); + + deviceField70.setIdentifier(""); + deviceField70.setLabelString("Seg. Len: "); + deviceField70.setNumCols(5); + deviceField70.setOffsetNid(156); + jPanel102.add(deviceField70); + + jPanel101.add(jPanel102); + + jPanel103.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 2")); + + deviceField71.setIdentifier(""); + deviceField71.setLabelString("Name"); + deviceField71.setNumCols(15); + deviceField71.setOffsetNid(160); + deviceField71.setTextOnly(true); + jPanel103.add(deviceField71); + + deviceField72.setIdentifier(""); + deviceField72.setLabelString("Dimensions (-1 to disable output):"); + deviceField72.setNumCols(5); + deviceField72.setOffsetNid(162); + jPanel103.add(deviceField72); + + deviceChoice35.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice35.setIdentifier(""); + deviceChoice35.setLabelString("Type"); + deviceChoice35.setOffsetNid(161); + deviceChoice35.setUpdateIdentifier(""); + jPanel103.add(deviceChoice35); + + deviceField73.setIdentifier(""); + deviceField73.setLabelString("Seg. Len: "); + deviceField73.setNumCols(5); + deviceField73.setOffsetNid(163); + jPanel103.add(deviceField73); + + jPanel101.add(jPanel103); + + jPanel104.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 3")); + + deviceField74.setIdentifier(""); + deviceField74.setLabelString("Name"); + deviceField74.setNumCols(15); + deviceField74.setOffsetNid(167); + deviceField74.setTextOnly(true); + jPanel104.add(deviceField74); + + deviceField75.setIdentifier(""); + deviceField75.setLabelString("Dimensions (-1 to disable output):"); + deviceField75.setNumCols(5); + deviceField75.setOffsetNid(169); + jPanel104.add(deviceField75); + + deviceChoice36.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice36.setIdentifier(""); + deviceChoice36.setLabelString("Type"); + deviceChoice36.setOffsetNid(168); + deviceChoice36.setUpdateIdentifier(""); + jPanel104.add(deviceChoice36); + + deviceField76.setIdentifier(""); + deviceField76.setLabelString("Seg. Len: "); + deviceField76.setNumCols(5); + deviceField76.setOffsetNid(170); + jPanel104.add(deviceField76); + + jPanel101.add(jPanel104); + + jPanel105.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 4")); + + deviceField77.setIdentifier(""); + deviceField77.setLabelString("Name"); + deviceField77.setNumCols(15); + deviceField77.setOffsetNid(174); + deviceField77.setTextOnly(true); + jPanel105.add(deviceField77); + + deviceField78.setIdentifier(""); + deviceField78.setLabelString("Dimensions (-1 to disable output):"); + deviceField78.setNumCols(5); + deviceField78.setOffsetNid(176); + jPanel105.add(deviceField78); + + deviceChoice37.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice37.setIdentifier(""); + deviceChoice37.setLabelString("Type"); + deviceChoice37.setOffsetNid(175); + deviceChoice37.setUpdateIdentifier(""); + jPanel105.add(deviceChoice37); + + deviceField79.setIdentifier(""); + deviceField79.setLabelString("Seg. Len: "); + deviceField79.setNumCols(5); + deviceField79.setOffsetNid(177); + jPanel105.add(deviceField79); + + jPanel101.add(jPanel105); + + jPanel106.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 5")); + + deviceField80.setIdentifier(""); + deviceField80.setLabelString("Name"); + deviceField80.setNumCols(15); + deviceField80.setOffsetNid(181); + deviceField80.setTextOnly(true); + jPanel106.add(deviceField80); + + deviceField81.setIdentifier(""); + deviceField81.setLabelString("Dimensions (-1 to disable output):"); + deviceField81.setNumCols(5); + deviceField81.setOffsetNid(183); + jPanel106.add(deviceField81); + + deviceChoice38.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice38.setIdentifier(""); + deviceChoice38.setLabelString("Type"); + deviceChoice38.setOffsetNid(182); + deviceChoice38.setUpdateIdentifier(""); + jPanel106.add(deviceChoice38); + + deviceField82.setIdentifier(""); + deviceField82.setLabelString("Seg. Len: "); + deviceField82.setNumCols(5); + deviceField82.setOffsetNid(184); + jPanel106.add(deviceField82); + + jPanel101.add(jPanel106); + + jPanel107.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 6")); + + deviceField83.setIdentifier(""); + deviceField83.setLabelString("Name"); + deviceField83.setNumCols(15); + deviceField83.setOffsetNid(188); + deviceField83.setTextOnly(true); + jPanel107.add(deviceField83); + + deviceField84.setIdentifier(""); + deviceField84.setLabelString("Dimensions (-1 to disable output):"); + deviceField84.setNumCols(5); + deviceField84.setOffsetNid(190); + jPanel107.add(deviceField84); + + deviceChoice39.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice39.setIdentifier(""); + deviceChoice39.setLabelString("Type"); + deviceChoice39.setOffsetNid(189); + deviceChoice39.setUpdateIdentifier(""); + jPanel107.add(deviceChoice39); + + deviceField85.setIdentifier(""); + deviceField85.setLabelString("Seg. Len: "); + deviceField85.setNumCols(5); + deviceField85.setOffsetNid(191); + jPanel107.add(deviceField85); + + jPanel101.add(jPanel107); + + jPanel108.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 7")); + + deviceField86.setIdentifier(""); + deviceField86.setLabelString("Name"); + deviceField86.setNumCols(15); + deviceField86.setOffsetNid(195); + deviceField86.setTextOnly(true); + jPanel108.add(deviceField86); + + deviceField87.setIdentifier(""); + deviceField87.setLabelString("Dimensions (-1 to disable output):"); + deviceField87.setNumCols(5); + deviceField87.setOffsetNid(197); + jPanel108.add(deviceField87); + + deviceChoice40.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice40.setIdentifier(""); + deviceChoice40.setLabelString("Type"); + deviceChoice40.setOffsetNid(196); + deviceChoice40.setUpdateIdentifier(""); + jPanel108.add(deviceChoice40); + + deviceField88.setIdentifier(""); + deviceField88.setLabelString("Seg. Len: "); + deviceField88.setNumCols(5); + deviceField88.setOffsetNid(198); + jPanel108.add(deviceField88); + + jPanel101.add(jPanel108); + + jPanel109.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 8")); + + deviceField89.setIdentifier(""); + deviceField89.setLabelString("Name"); + deviceField89.setNumCols(15); + deviceField89.setOffsetNid(202); + deviceField89.setTextOnly(true); + jPanel109.add(deviceField89); + + deviceField90.setIdentifier(""); + deviceField90.setLabelString("Dimensions (-1 to disable output):"); + deviceField90.setNumCols(5); + deviceField90.setOffsetNid(204); + jPanel109.add(deviceField90); + + deviceChoice41.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice41.setIdentifier(""); + deviceChoice41.setLabelString("Type"); + deviceChoice41.setOffsetNid(203); + deviceChoice41.setUpdateIdentifier(""); + jPanel109.add(deviceChoice41); + + deviceField91.setIdentifier(""); + deviceField91.setLabelString("Seg. Len: "); + deviceField91.setNumCols(5); + deviceField91.setOffsetNid(205); + jPanel109.add(deviceField91); + + jPanel101.add(jPanel109); + + jPanel110.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 9")); + + deviceField92.setIdentifier(""); + deviceField92.setLabelString("Name"); + deviceField92.setNumCols(15); + deviceField92.setOffsetNid(209); + deviceField92.setTextOnly(true); + jPanel110.add(deviceField92); + + deviceField93.setIdentifier(""); + deviceField93.setLabelString("Dimensions (-1 to disable output):"); + deviceField93.setNumCols(5); + deviceField93.setOffsetNid(211); + jPanel110.add(deviceField93); + + deviceChoice42.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice42.setIdentifier(""); + deviceChoice42.setLabelString("Type"); + deviceChoice42.setOffsetNid(210); + deviceChoice42.setUpdateIdentifier(""); + jPanel110.add(deviceChoice42); + + deviceField94.setIdentifier(""); + deviceField94.setLabelString("Seg. Len: "); + deviceField94.setNumCols(5); + deviceField94.setOffsetNid(212); + jPanel110.add(deviceField94); + + jPanel101.add(jPanel110); + + jPanel111.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 10")); + + deviceField95.setIdentifier(""); + deviceField95.setLabelString("Name"); + deviceField95.setNumCols(15); + deviceField95.setOffsetNid(216); + deviceField95.setTextOnly(true); + jPanel111.add(deviceField95); + + deviceField96.setIdentifier(""); + deviceField96.setLabelString("Dimensions (-1 to disable output):"); + deviceField96.setNumCols(5); + deviceField96.setOffsetNid(218); + jPanel111.add(deviceField96); + + deviceChoice43.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice43.setIdentifier(""); + deviceChoice43.setLabelString("Type"); + deviceChoice43.setOffsetNid(217); + deviceChoice43.setUpdateIdentifier(""); + jPanel111.add(deviceChoice43); + + deviceField97.setIdentifier(""); + deviceField97.setLabelString("Seg. Len: "); + deviceField97.setNumCols(5); + deviceField97.setOffsetNid(219); + jPanel111.add(deviceField97); + + jPanel101.add(jPanel111); + + jPanel112.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 11")); + + deviceField98.setIdentifier(""); + deviceField98.setLabelString("Name"); + deviceField98.setNumCols(15); + deviceField98.setOffsetNid(223); + deviceField98.setTextOnly(true); + jPanel112.add(deviceField98); + + deviceField99.setIdentifier(""); + deviceField99.setLabelString("Dimensions (-1 to disable output):"); + deviceField99.setNumCols(5); + deviceField99.setOffsetNid(225); + jPanel112.add(deviceField99); + + deviceChoice44.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice44.setIdentifier(""); + deviceChoice44.setLabelString("Type"); + deviceChoice44.setOffsetNid(224); + deviceChoice44.setUpdateIdentifier(""); + jPanel112.add(deviceChoice44); + + deviceField100.setIdentifier(""); + deviceField100.setLabelString("Seg. Len: "); + deviceField100.setNumCols(5); + deviceField100.setOffsetNid(226); + jPanel112.add(deviceField100); + + jPanel101.add(jPanel112); + + jPanel113.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 12")); + + deviceField101.setIdentifier(""); + deviceField101.setLabelString("Name"); + deviceField101.setNumCols(15); + deviceField101.setOffsetNid(230); + deviceField101.setTextOnly(true); + jPanel113.add(deviceField101); + + deviceField102.setIdentifier(""); + deviceField102.setLabelString("Dimensions (-1 to disable output):"); + deviceField102.setNumCols(5); + deviceField102.setOffsetNid(232); + jPanel113.add(deviceField102); + + deviceChoice45.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice45.setIdentifier(""); + deviceChoice45.setLabelString("Type"); + deviceChoice45.setOffsetNid(231); + deviceChoice45.setUpdateIdentifier(""); + jPanel113.add(deviceChoice45); + + deviceField103.setIdentifier(""); + deviceField103.setLabelString("Seg. Len: "); + deviceField103.setNumCols(5); + deviceField103.setOffsetNid(233); + jPanel113.add(deviceField103); + + jPanel101.add(jPanel113); + + jPanel114.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 13")); + + deviceField104.setIdentifier(""); + deviceField104.setLabelString("Name"); + deviceField104.setNumCols(15); + deviceField104.setOffsetNid(237); + deviceField104.setTextOnly(true); + jPanel114.add(deviceField104); + + deviceField105.setIdentifier(""); + deviceField105.setLabelString("Dimensions (-1 to disable output):"); + deviceField105.setNumCols(5); + deviceField105.setOffsetNid(239); + jPanel114.add(deviceField105); + + deviceChoice46.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice46.setIdentifier(""); + deviceChoice46.setLabelString("Type"); + deviceChoice46.setOffsetNid(238); + deviceChoice46.setUpdateIdentifier(""); + jPanel114.add(deviceChoice46); + + deviceField106.setIdentifier(""); + deviceField106.setLabelString("Seg. Len: "); + deviceField106.setNumCols(5); + deviceField106.setOffsetNid(240); + jPanel114.add(deviceField106); + + jPanel101.add(jPanel114); + + jPanel115.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 14")); + + deviceField107.setIdentifier(""); + deviceField107.setLabelString("Name"); + deviceField107.setNumCols(15); + deviceField107.setOffsetNid(244); + deviceField107.setTextOnly(true); + jPanel115.add(deviceField107); + + deviceField108.setIdentifier(""); + deviceField108.setLabelString("Dimensions (-1 to disable output):"); + deviceField108.setNumCols(5); + deviceField108.setOffsetNid(246); + jPanel115.add(deviceField108); + + deviceChoice47.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice47.setIdentifier(""); + deviceChoice47.setLabelString("Type"); + deviceChoice47.setOffsetNid(245); + deviceChoice47.setUpdateIdentifier(""); + jPanel115.add(deviceChoice47); + + deviceField109.setIdentifier(""); + deviceField109.setLabelString("Seg. Len: "); + deviceField109.setNumCols(5); + deviceField109.setOffsetNid(247); + jPanel115.add(deviceField109); + + jPanel101.add(jPanel115); + + jPanel116.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 15")); + + deviceField110.setIdentifier(""); + deviceField110.setLabelString("Name"); + deviceField110.setNumCols(15); + deviceField110.setOffsetNid(251); + deviceField110.setTextOnly(true); + jPanel116.add(deviceField110); + + deviceField111.setIdentifier(""); + deviceField111.setLabelString("Dimensions (-1 to disable output):"); + deviceField111.setNumCols(5); + deviceField111.setOffsetNid(253); + jPanel116.add(deviceField111); + + deviceChoice48.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice48.setIdentifier(""); + deviceChoice48.setLabelString("Type"); + deviceChoice48.setOffsetNid(252); + deviceChoice48.setUpdateIdentifier(""); + jPanel116.add(deviceChoice48); + + deviceField112.setIdentifier(""); + deviceField112.setLabelString("Seg. Len: "); + deviceField112.setNumCols(5); + deviceField112.setOffsetNid(254); + jPanel116.add(deviceField112); + + jPanel101.add(jPanel116); + + jPanel117.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 16")); + + deviceField113.setIdentifier(""); + deviceField113.setLabelString("Name"); + deviceField113.setNumCols(15); + deviceField113.setOffsetNid(258); + deviceField113.setTextOnly(true); + jPanel117.add(deviceField113); + + deviceField114.setIdentifier(""); + deviceField114.setLabelString("Dimensions (-1 to disable output):"); + deviceField114.setNumCols(5); + deviceField114.setOffsetNid(260); + jPanel117.add(deviceField114); + + deviceChoice49.setChoiceItems(new String[] {"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "char8", "float32", "float64"}); + deviceChoice49.setIdentifier(""); + deviceChoice49.setLabelString("Type"); + deviceChoice49.setOffsetNid(259); + deviceChoice49.setUpdateIdentifier(""); + jPanel117.add(deviceChoice49); + + deviceField115.setIdentifier(""); + deviceField115.setLabelString("Seg. Len: "); + deviceField115.setNumCols(5); + deviceField115.setOffsetNid(261); + jPanel117.add(deviceField115); + + jPanel101.add(jPanel117); + + jScrollPane3.setViewportView(jPanel101); + + jTabbedPane1.addTab("Outputs", jScrollPane3); + + jPanel1.add(jTabbedPane1, java.awt.BorderLayout.CENTER); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceChoice deviceChoice10; + private DeviceChoice deviceChoice11; + private DeviceChoice deviceChoice12; + private DeviceChoice deviceChoice13; + private DeviceChoice deviceChoice14; + private DeviceChoice deviceChoice15; + private DeviceChoice deviceChoice16; + private DeviceChoice deviceChoice17; + private DeviceChoice deviceChoice18; + private DeviceChoice deviceChoice19; + private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice20; + private DeviceChoice deviceChoice21; + private DeviceChoice deviceChoice22; + private DeviceChoice deviceChoice23; + private DeviceChoice deviceChoice24; + private DeviceChoice deviceChoice25; + private DeviceChoice deviceChoice26; + private DeviceChoice deviceChoice27; + private DeviceChoice deviceChoice28; + private DeviceChoice deviceChoice29; + private DeviceChoice deviceChoice3; + private DeviceChoice deviceChoice30; + private DeviceChoice deviceChoice31; + private DeviceChoice deviceChoice32; + private DeviceChoice deviceChoice34; + private DeviceChoice deviceChoice35; + private DeviceChoice deviceChoice36; + private DeviceChoice deviceChoice37; + private DeviceChoice deviceChoice38; + private DeviceChoice deviceChoice39; + private DeviceChoice deviceChoice4; + private DeviceChoice deviceChoice40; + private DeviceChoice deviceChoice41; + private DeviceChoice deviceChoice42; + private DeviceChoice deviceChoice43; + private DeviceChoice deviceChoice44; + private DeviceChoice deviceChoice45; + private DeviceChoice deviceChoice46; + private DeviceChoice deviceChoice47; + private DeviceChoice deviceChoice48; + private DeviceChoice deviceChoice49; + private DeviceChoice deviceChoice5; + private DeviceChoice deviceChoice6; + private DeviceChoice deviceChoice7; + private DeviceChoice deviceChoice8; + private DeviceChoice deviceChoice9; + private DeviceField deviceField1; + private DeviceField deviceField10; + private DeviceField deviceField100; + private DeviceField deviceField101; + private DeviceField deviceField102; + private DeviceField deviceField103; + private DeviceField deviceField104; + private DeviceField deviceField105; + private DeviceField deviceField106; + private DeviceField deviceField107; + private DeviceField deviceField108; + private DeviceField deviceField109; + private DeviceField deviceField11; + private DeviceField deviceField110; + private DeviceField deviceField111; + private DeviceField deviceField112; + private DeviceField deviceField113; + private DeviceField deviceField114; + private DeviceField deviceField115; + private DeviceField deviceField12; + private DeviceField deviceField13; + private DeviceField deviceField14; + private DeviceField deviceField15; + private DeviceField deviceField16; + private DeviceField deviceField17; + private DeviceField deviceField18; + private DeviceField deviceField19; + private DeviceField deviceField2; + private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; + private DeviceField deviceField23; + private DeviceField deviceField24; + private DeviceField deviceField25; + private DeviceField deviceField26; + private DeviceField deviceField27; + private DeviceField deviceField28; + private DeviceField deviceField29; + private DeviceField deviceField3; + private DeviceField deviceField30; + private DeviceField deviceField31; + private DeviceField deviceField32; + private DeviceField deviceField33; + private DeviceField deviceField34; + private DeviceField deviceField35; + private DeviceField deviceField36; + private DeviceField deviceField37; + private DeviceField deviceField38; + private DeviceField deviceField39; + private DeviceField deviceField4; + private DeviceField deviceField40; + private DeviceField deviceField41; + private DeviceField deviceField42; + private DeviceField deviceField43; + private DeviceField deviceField44; + private DeviceField deviceField45; + private DeviceField deviceField46; + private DeviceField deviceField47; + private DeviceField deviceField48; + private DeviceField deviceField49; + private DeviceField deviceField5; + private DeviceField deviceField50; + private DeviceField deviceField51; + private DeviceField deviceField52; + private DeviceField deviceField53; + private DeviceField deviceField54; + private DeviceField deviceField55; + private DeviceField deviceField56; + private DeviceField deviceField57; + private DeviceField deviceField58; + private DeviceField deviceField59; + private DeviceField deviceField6; + private DeviceField deviceField60; + private DeviceField deviceField61; + private DeviceField deviceField62; + private DeviceField deviceField63; + private DeviceField deviceField64; + private DeviceField deviceField65; + private DeviceField deviceField66; + private DeviceField deviceField67; + private DeviceField deviceField68; + private DeviceField deviceField69; + private DeviceField deviceField7; + private DeviceField deviceField70; + private DeviceField deviceField71; + private DeviceField deviceField72; + private DeviceField deviceField73; + private DeviceField deviceField74; + private DeviceField deviceField75; + private DeviceField deviceField76; + private DeviceField deviceField77; + private DeviceField deviceField78; + private DeviceField deviceField79; + private DeviceField deviceField8; + private DeviceField deviceField80; + private DeviceField deviceField81; + private DeviceField deviceField82; + private DeviceField deviceField83; + private DeviceField deviceField84; + private DeviceField deviceField85; + private DeviceField deviceField86; + private DeviceField deviceField87; + private DeviceField deviceField88; + private DeviceField deviceField89; + private DeviceField deviceField9; + private DeviceField deviceField90; + private DeviceField deviceField91; + private DeviceField deviceField92; + private DeviceField deviceField93; + private DeviceField deviceField94; + private DeviceField deviceField95; + private DeviceField deviceField96; + private DeviceField deviceField97; + private DeviceField deviceField98; + private DeviceField deviceField99; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel10; + private javax.swing.JPanel jPanel100; + private javax.swing.JPanel jPanel101; + private javax.swing.JPanel jPanel102; + private javax.swing.JPanel jPanel103; + private javax.swing.JPanel jPanel104; + private javax.swing.JPanel jPanel105; + private javax.swing.JPanel jPanel106; + private javax.swing.JPanel jPanel107; + private javax.swing.JPanel jPanel108; + private javax.swing.JPanel jPanel109; + private javax.swing.JPanel jPanel11; + private javax.swing.JPanel jPanel110; + private javax.swing.JPanel jPanel111; + private javax.swing.JPanel jPanel112; + private javax.swing.JPanel jPanel113; + private javax.swing.JPanel jPanel114; + private javax.swing.JPanel jPanel115; + private javax.swing.JPanel jPanel116; + private javax.swing.JPanel jPanel117; + private javax.swing.JPanel jPanel12; + private javax.swing.JPanel jPanel13; + private javax.swing.JPanel jPanel14; + private javax.swing.JPanel jPanel15; + private javax.swing.JPanel jPanel16; + private javax.swing.JPanel jPanel17; + private javax.swing.JPanel jPanel18; + private javax.swing.JPanel jPanel19; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel20; + private javax.swing.JPanel jPanel21; + private javax.swing.JPanel jPanel22; + private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; + private javax.swing.JPanel jPanel25; + private javax.swing.JPanel jPanel26; + private javax.swing.JPanel jPanel27; + private javax.swing.JPanel jPanel28; + private javax.swing.JPanel jPanel29; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel30; + private javax.swing.JPanel jPanel31; + private javax.swing.JPanel jPanel32; + private javax.swing.JPanel jPanel33; + private javax.swing.JPanel jPanel34; + private javax.swing.JPanel jPanel35; + private javax.swing.JPanel jPanel36; + private javax.swing.JPanel jPanel37; + private javax.swing.JPanel jPanel38; + private javax.swing.JPanel jPanel39; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel40; + private javax.swing.JPanel jPanel41; + private javax.swing.JPanel jPanel42; + private javax.swing.JPanel jPanel43; + private javax.swing.JPanel jPanel44; + private javax.swing.JPanel jPanel45; + private javax.swing.JPanel jPanel46; + private javax.swing.JPanel jPanel47; + private javax.swing.JPanel jPanel48; + private javax.swing.JPanel jPanel49; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel50; + private javax.swing.JPanel jPanel51; + private javax.swing.JPanel jPanel52; + private javax.swing.JPanel jPanel53; + private javax.swing.JPanel jPanel54; + private javax.swing.JPanel jPanel55; + private javax.swing.JPanel jPanel56; + private javax.swing.JPanel jPanel57; + private javax.swing.JPanel jPanel58; + private javax.swing.JPanel jPanel59; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel60; + private javax.swing.JPanel jPanel61; + private javax.swing.JPanel jPanel62; + private javax.swing.JPanel jPanel63; + private javax.swing.JPanel jPanel64; + private javax.swing.JPanel jPanel65; + private javax.swing.JPanel jPanel66; + private javax.swing.JPanel jPanel67; + private javax.swing.JPanel jPanel68; + private javax.swing.JPanel jPanel69; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel70; + private javax.swing.JPanel jPanel71; + private javax.swing.JPanel jPanel72; + private javax.swing.JPanel jPanel73; + private javax.swing.JPanel jPanel74; + private javax.swing.JPanel jPanel75; + private javax.swing.JPanel jPanel76; + private javax.swing.JPanel jPanel77; + private javax.swing.JPanel jPanel78; + private javax.swing.JPanel jPanel79; + private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel80; + private javax.swing.JPanel jPanel81; + private javax.swing.JPanel jPanel82; + private javax.swing.JPanel jPanel83; + private javax.swing.JPanel jPanel84; + private javax.swing.JPanel jPanel85; + private javax.swing.JPanel jPanel86; + private javax.swing.JPanel jPanel87; + private javax.swing.JPanel jPanel88; + private javax.swing.JPanel jPanel89; + private javax.swing.JPanel jPanel9; + private javax.swing.JPanel jPanel90; + private javax.swing.JPanel jPanel91; + private javax.swing.JPanel jPanel92; + private javax.swing.JPanel jPanel93; + private javax.swing.JPanel jPanel94; + private javax.swing.JPanel jPanel95; + private javax.swing.JPanel jPanel96; + private javax.swing.JPanel jPanel97; + private javax.swing.JPanel jPanel98; + private javax.swing.JPanel jPanel99; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JScrollPane jScrollPane3; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_NI6259_DACSetup.java b/java/jdevices/src/main/java/MARTE2_NI6259_DACSetup.java index 3cce4d2b19..64960de132 100644 --- a/java/jdevices/src/main/java/MARTE2_NI6259_DACSetup.java +++ b/java/jdevices/src/main/java/MARTE2_NI6259_DACSetup.java @@ -29,185 +29,214 @@ public MARTE2_NI6259_DACSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - jPanel2 = new javax.swing.JPanel(); - jPanel14 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField7 = new DeviceField(); - deviceField8 = new DeviceField(); - jPanel15 = new javax.swing.JPanel(); - deviceField2 = new DeviceField(); - deviceChoice2 = new DeviceChoice(); - deviceChoice1 = new DeviceChoice(); - jTabbedPane1 = new javax.swing.JTabbedPane(); - jPanel1 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceChoice3 = new DeviceChoice(); - jPanel4 = new javax.swing.JPanel(); - deviceField3 = new DeviceField(); - jPanel5 = new javax.swing.JPanel(); - jPanel6 = new javax.swing.JPanel(); - deviceChoice4 = new DeviceChoice(); - jPanel7 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - jPanel9 = new javax.swing.JPanel(); - deviceChoice5 = new DeviceChoice(); - jPanel10 = new javax.swing.JPanel(); - deviceField5 = new DeviceField(); - jPanel11 = new javax.swing.JPanel(); - jPanel12 = new javax.swing.JPanel(); - deviceChoice6 = new DeviceChoice(); - jPanel13 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceButtons1 = new DeviceButtons(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("MARTe2 NI 6250 DAC"); - setDeviceType("MARTE2_NI6259_DAC"); - setHeight(300); - setWidth(700); - jPanel2.setLayout(new java.awt.GridLayout(2, 1)); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Board Id:"); - deviceField1.setNumCols(4); - deviceField1.setOffsetNid(10); - jPanel14.add(deviceField1); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Timebase: "); - deviceField7.setNumCols(25); - deviceField7.setOffsetNid(3); - jPanel14.add(deviceField7); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Timebase div:"); - deviceField8.setNumCols(4); - deviceField8.setOffsetNid(76); - jPanel14.add(deviceField8); - jPanel2.add(jPanel14); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Clock update divisor: "); - deviceField2.setNumCols(3); - deviceField2.setOffsetNid(19); - jPanel15.add(deviceField2); - deviceChoice2.setChoiceItems(new String[] - { "RISING_EDGE", "FALLING_EDGE" }); - deviceChoice2.setIdentifier(""); - deviceChoice2.setLabelString("Clock update polarity: "); - deviceChoice2.setOffsetNid(16); - deviceChoice2.setUpdateIdentifier(""); - jPanel15.add(deviceChoice2); - deviceChoice1.setChoiceItems(new String[] - { "UI_TC", "PFI0", "PFI1", "PFI2", "PFI3", "PFI4", "PFI5", "PFI6", "PFI7", "PFI8", "PFI9", "PFI10", "PFI11", - "PFI12", "PFI13", "PFI14", "PFI15", "RTSI0", "RTSI1", "RTSI2", "RTSI3", "RTSI4", "RTSI5", "RTSI6", - "RTSI7", "GPCRT0_OUT", "GPCRT1_OUT", "START_TRIGGER", "ANALOG_TRIGGER", "LOW" }); - deviceChoice1.setIdentifier(""); - deviceChoice1.setLabelString("Clock update source: "); - deviceChoice1.setOffsetNid(13); - deviceChoice1.setUpdateIdentifier(""); - jPanel15.add(deviceChoice1); - jPanel2.add(jPanel15); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - jPanel1.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice3.setChoiceItems(new String[] - { "Unipolar", "Bipolar" }); - deviceChoice3.setIdentifier(""); - deviceChoice3.setLabelString("Polarity:"); - deviceChoice3.setOffsetNid(33); - deviceChoice3.setUpdateIdentifier(""); - jPanel3.add(deviceChoice3); - jPanel1.add(jPanel3); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Value: "); - deviceField3.setNumCols(40); - deviceField3.setOffsetNid(25); - jPanel4.add(deviceField3); - jPanel1.add(jPanel4); - jTabbedPane1.addTab("Chan 1", jPanel1); - jPanel5.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice4.setChoiceItems(new String[] - { "Unipolar", "Bipolar" }); - deviceChoice4.setIdentifier(""); - deviceChoice4.setLabelString("Polarity:"); - deviceChoice4.setOffsetNid(62); - deviceChoice4.setUpdateIdentifier(""); - jPanel6.add(deviceChoice4); - jPanel5.add(jPanel6); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Value: "); - deviceField4.setNumCols(40); - deviceField4.setOffsetNid(41); - jPanel7.add(deviceField4); - jPanel5.add(jPanel7); - jTabbedPane1.addTab("Chan 2", jPanel5); - jPanel8.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice5.setChoiceItems(new String[] - { "Unipolar", "Bipolar" }); - deviceChoice5.setIdentifier(""); - deviceChoice5.setLabelString("Polarity:"); - deviceChoice5.setOffsetNid(62); - deviceChoice5.setUpdateIdentifier(""); - jPanel9.add(deviceChoice5); - jPanel8.add(jPanel9); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Value: "); - deviceField5.setNumCols(40); - deviceField5.setOffsetNid(54); - jPanel10.add(deviceField5); - jPanel8.add(jPanel10); - jTabbedPane1.addTab("Chan 3", jPanel8); - jPanel11.setLayout(new java.awt.GridLayout(2, 1)); - deviceChoice6.setChoiceItems(new String[] - { "Unipolar", "Bipolar" }); - deviceChoice6.setIdentifier(""); - deviceChoice6.setLabelString("Polarity:"); - deviceChoice6.setOffsetNid(75); - deviceChoice6.setUpdateIdentifier(""); - jPanel12.add(deviceChoice6); - jPanel11.add(jPanel12); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Value: "); - deviceField6.setNumCols(40); - deviceField6.setOffsetNid(67); - jPanel13.add(deviceField6); - jPanel11.add(jPanel13); - jTabbedPane1.addTab("Chan 4", jPanel11); - getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice1; - private DeviceChoice deviceChoice2; - private DeviceChoice deviceChoice3; - private DeviceChoice deviceChoice4; - private DeviceChoice deviceChoice5; - private DeviceChoice deviceChoice6; - private DeviceField deviceField1; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private DeviceField deviceField8; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel10; - private javax.swing.JPanel jPanel11; - private javax.swing.JPanel jPanel12; - private javax.swing.JPanel jPanel13; - private javax.swing.JPanel jPanel14; - private javax.swing.JPanel jPanel15; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel9; - private javax.swing.JTabbedPane jTabbedPane1; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel2 = new javax.swing.JPanel(); + jPanel14 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField7 = new DeviceField(); + deviceField8 = new DeviceField(); + jPanel15 = new javax.swing.JPanel(); + deviceField2 = new DeviceField(); + deviceChoice2 = new DeviceChoice(); + deviceChoice1 = new DeviceChoice(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel1 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + deviceChoice3 = new DeviceChoice(); + jPanel4 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); + jPanel5 = new javax.swing.JPanel(); + jPanel6 = new javax.swing.JPanel(); + deviceChoice4 = new DeviceChoice(); + jPanel7 = new javax.swing.JPanel(); + deviceField4 = new DeviceField(); + jPanel8 = new javax.swing.JPanel(); + jPanel9 = new javax.swing.JPanel(); + deviceChoice5 = new DeviceChoice(); + jPanel10 = new javax.swing.JPanel(); + deviceField5 = new DeviceField(); + jPanel11 = new javax.swing.JPanel(); + jPanel12 = new javax.swing.JPanel(); + deviceChoice6 = new DeviceChoice(); + jPanel13 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + deviceButtons1 = new DeviceButtons(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 NI 6250 DAC"); + setDeviceType("MARTE2_NI6259_DAC"); + setHeight(300); + setWidth(700); + + jPanel2.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Board Id:"); + deviceField1.setNumCols(4); + deviceField1.setOffsetNid(10); + jPanel14.add(deviceField1); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Timebase: "); + deviceField7.setNumCols(25); + deviceField7.setOffsetNid(3); + jPanel14.add(deviceField7); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Timebase div:"); + deviceField8.setNumCols(4); + deviceField8.setOffsetNid(76); + jPanel14.add(deviceField8); + + jPanel2.add(jPanel14); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Clock update divisor: "); + deviceField2.setNumCols(3); + deviceField2.setOffsetNid(19); + jPanel15.add(deviceField2); + + deviceChoice2.setChoiceItems(new String[] {"RISING_EDGE", "FALLING_EDGE"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString("Clock update polarity: "); + deviceChoice2.setOffsetNid(16); + deviceChoice2.setUpdateIdentifier(""); + jPanel15.add(deviceChoice2); + + deviceChoice1.setChoiceItems(new String[] {"UI_TC", "PFI0", "PFI1", "PFI2", "PFI3", "PFI4", "PFI5", "PFI6", "PFI7", "PFI8", "PFI9", "PFI10", "PFI11", "PFI12", "PFI13", "PFI14", "PFI15", "RTSI0", "RTSI1", "RTSI2", "RTSI3", "RTSI4", "RTSI5", "RTSI6", "RTSI7", "GPCRT0_OUT", "GPCRT1_OUT", "START_TRIGGER", "ANALOG_TRIGGER", "LOW"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString("Clock update source: "); + deviceChoice1.setOffsetNid(13); + deviceChoice1.setUpdateIdentifier(""); + jPanel15.add(deviceChoice1); + + jPanel2.add(jPanel15); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + jPanel1.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice3.setChoiceItems(new String[] {"Unipolar", "Bipolar"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString("Polarity:"); + deviceChoice3.setOffsetNid(33); + deviceChoice3.setUpdateIdentifier(""); + jPanel3.add(deviceChoice3); + + jPanel1.add(jPanel3); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Value: "); + deviceField3.setNumCols(40); + deviceField3.setOffsetNid(25); + jPanel4.add(deviceField3); + + jPanel1.add(jPanel4); + + jTabbedPane1.addTab("Chan 1", jPanel1); + + jPanel5.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice4.setChoiceItems(new String[] {"Unipolar", "Bipolar"}); + deviceChoice4.setIdentifier(""); + deviceChoice4.setLabelString("Polarity:"); + deviceChoice4.setOffsetNid(62); + deviceChoice4.setUpdateIdentifier(""); + jPanel6.add(deviceChoice4); + + jPanel5.add(jPanel6); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Value: "); + deviceField4.setNumCols(40); + deviceField4.setOffsetNid(41); + jPanel7.add(deviceField4); + + jPanel5.add(jPanel7); + + jTabbedPane1.addTab("Chan 2", jPanel5); + + jPanel8.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice5.setChoiceItems(new String[] {"Unipolar", "Bipolar"}); + deviceChoice5.setIdentifier(""); + deviceChoice5.setLabelString("Polarity:"); + deviceChoice5.setOffsetNid(62); + deviceChoice5.setUpdateIdentifier(""); + jPanel9.add(deviceChoice5); + + jPanel8.add(jPanel9); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Value: "); + deviceField5.setNumCols(40); + deviceField5.setOffsetNid(54); + jPanel10.add(deviceField5); + + jPanel8.add(jPanel10); + + jTabbedPane1.addTab("Chan 3", jPanel8); + + jPanel11.setLayout(new java.awt.GridLayout(2, 1)); + + deviceChoice6.setChoiceItems(new String[] {"Unipolar", "Bipolar"}); + deviceChoice6.setIdentifier(""); + deviceChoice6.setLabelString("Polarity:"); + deviceChoice6.setOffsetNid(75); + deviceChoice6.setUpdateIdentifier(""); + jPanel12.add(deviceChoice6); + + jPanel11.add(jPanel12); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Value: "); + deviceField6.setNumCols(40); + deviceField6.setOffsetNid(67); + jPanel13.add(deviceField6); + + jPanel11.add(jPanel13); + + jTabbedPane1.addTab("Chan 4", jPanel11); + + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice3; + private DeviceChoice deviceChoice4; + private DeviceChoice deviceChoice5; + private DeviceChoice deviceChoice6; + private DeviceField deviceField1; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private DeviceField deviceField7; + private DeviceField deviceField8; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel10; + private javax.swing.JPanel jPanel11; + private javax.swing.JPanel jPanel12; + private javax.swing.JPanel jPanel13; + private javax.swing.JPanel jPanel14; + private javax.swing.JPanel jPanel15; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel9; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_NI6259_DISetup.java b/java/jdevices/src/main/java/MARTE2_NI6259_DISetup.java index 1e1c0c70e5..81bb4414a6 100644 --- a/java/jdevices/src/main/java/MARTE2_NI6259_DISetup.java +++ b/java/jdevices/src/main/java/MARTE2_NI6259_DISetup.java @@ -29,74 +29,85 @@ public MARTE2_NI6259_DISetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceButtons1 = new DeviceButtons(); - jPanel2 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceField7 = new DeviceField(); - jPanel1 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField2 = new DeviceField(); - deviceField3 = new DeviceField(); - deviceField4 = new DeviceField(); - deviceField5 = new DeviceField(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("NI6259 Digital Input"); - setDeviceType("MARTE2_NI6259_DI"); - setHeight(200); - setWidth(700); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Timebase: "); - deviceField6.setNumCols(25); - deviceField6.setOffsetNid(3); - jPanel2.add(deviceField6); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Storage CPUs: "); - deviceField7.setNumCols(4); - deviceField7.setOffsetNid(17); - jPanel2.add(deviceField7); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Board Id: "); - deviceField1.setNumCols(4); - deviceField1.setOffsetNid(10); - jPanel1.add(deviceField1); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Port 1 Mask: "); - deviceField2.setNumCols(4); - deviceField2.setOffsetNid(31); - jPanel1.add(deviceField2); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Port 2 Mask: "); - deviceField3.setNumCols(4); - deviceField3.setOffsetNid(45); - jPanel1.add(deviceField3); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Port 3 Mask: "); - deviceField4.setNumCols(4); - deviceField4.setOffsetNid(59); - jPanel1.add(deviceField4); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Segment len (0 to disable writing in tree):"); - deviceField5.setOffsetNid(23); - jPanel1.add(deviceField5); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel2 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + deviceField7 = new DeviceField(); + jPanel1 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField2 = new DeviceField(); + deviceField3 = new DeviceField(); + deviceField4 = new DeviceField(); + deviceField5 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("NI6259 Digital Input"); + setDeviceType("MARTE2_NI6259_DI"); + setHeight(200); + setWidth(700); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Timebase: "); + deviceField6.setNumCols(25); + deviceField6.setOffsetNid(3); + jPanel2.add(deviceField6); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Storage CPUs: "); + deviceField7.setNumCols(4); + deviceField7.setOffsetNid(17); + jPanel2.add(deviceField7); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Board Id: "); + deviceField1.setNumCols(4); + deviceField1.setOffsetNid(10); + jPanel1.add(deviceField1); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Port 1 Mask: "); + deviceField2.setNumCols(4); + deviceField2.setOffsetNid(31); + jPanel1.add(deviceField2); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Port 2 Mask: "); + deviceField3.setNumCols(4); + deviceField3.setOffsetNid(45); + jPanel1.add(deviceField3); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Port 3 Mask: "); + deviceField4.setNumCols(4); + deviceField4.setOffsetNid(59); + jPanel1.add(deviceField4); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Segment len (0 to disable writing in tree):"); + deviceField5.setOffsetNid(23); + jPanel1.add(deviceField5); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceField deviceField1; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - // End of variables declaration//GEN-END:variables + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceField deviceField1; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private DeviceField deviceField7; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_NI6259_DOSetup.java b/java/jdevices/src/main/java/MARTE2_NI6259_DOSetup.java index 3807fdba8f..cefb8e2083 100644 --- a/java/jdevices/src/main/java/MARTE2_NI6259_DOSetup.java +++ b/java/jdevices/src/main/java/MARTE2_NI6259_DOSetup.java @@ -29,95 +29,111 @@ public MARTE2_NI6259_DOSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceButtons1 = new DeviceButtons(); - jPanel2 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField8 = new DeviceField(); - deviceField9 = new DeviceField(); - jTabbedPane1 = new javax.swing.JTabbedPane(); - jPanel3 = new javax.swing.JPanel(); - deviceField2 = new DeviceField(); - deviceField3 = new DeviceField(); - jPanel4 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - deviceField5 = new DeviceField(); - jPanel5 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceField7 = new DeviceField(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("MARTe2 NI6259 Digital Output "); - setDeviceType("MARTE2_NI6259_DO"); - setHeight(200); - setWidth(600); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Board Id: "); - deviceField1.setNumCols(4); - deviceField1.setOffsetNid(10); - jPanel2.add(deviceField1); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Timebase: "); - deviceField8.setNumCols(20); - deviceField8.setOffsetNid(3); - jPanel2.add(deviceField8); - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Timebase div.:"); - deviceField9.setNumCols(4); - deviceField9.setOffsetNid(54); - jPanel2.add(deviceField9); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Mask: "); - deviceField2.setOffsetNid(24); - jPanel3.add(deviceField2); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Value: "); - deviceField3.setNumCols(35); - deviceField3.setOffsetNid(16); - jPanel3.add(deviceField3); - jTabbedPane1.addTab("Port 1", jPanel3); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Mask: "); - deviceField4.setOffsetNid(40); - jPanel4.add(deviceField4); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Value: "); - deviceField5.setNumCols(35); - deviceField5.setOffsetNid(32); - jPanel4.add(deviceField5); - jTabbedPane1.addTab("Port 2", jPanel4); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Mask: "); - deviceField6.setOffsetNid(53); - jPanel5.add(deviceField6); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Value: "); - deviceField7.setNumCols(35); - deviceField7.setOffsetNid(45); - jPanel5.add(deviceField7); - jTabbedPane1.addTab("Port 3", jPanel5); - getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceField deviceField1; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private DeviceField deviceField8; - private DeviceField deviceField9; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel5; - private javax.swing.JTabbedPane jTabbedPane1; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel2 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField8 = new DeviceField(); + deviceField9 = new DeviceField(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel3 = new javax.swing.JPanel(); + deviceField2 = new DeviceField(); + deviceField3 = new DeviceField(); + jPanel4 = new javax.swing.JPanel(); + deviceField4 = new DeviceField(); + deviceField5 = new DeviceField(); + jPanel5 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + deviceField7 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 NI6259 Digital Output "); + setDeviceType("MARTE2_NI6259_DO"); + setHeight(200); + setWidth(600); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Board Id: "); + deviceField1.setNumCols(4); + deviceField1.setOffsetNid(10); + jPanel2.add(deviceField1); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Timebase: "); + deviceField8.setNumCols(20); + deviceField8.setOffsetNid(3); + jPanel2.add(deviceField8); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Timebase div.:"); + deviceField9.setNumCols(4); + deviceField9.setOffsetNid(54); + jPanel2.add(deviceField9); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Mask: "); + deviceField2.setOffsetNid(24); + jPanel3.add(deviceField2); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Value: "); + deviceField3.setNumCols(35); + deviceField3.setOffsetNid(16); + jPanel3.add(deviceField3); + + jTabbedPane1.addTab("Port 1", jPanel3); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Mask: "); + deviceField4.setOffsetNid(40); + jPanel4.add(deviceField4); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Value: "); + deviceField5.setNumCols(35); + deviceField5.setOffsetNid(32); + jPanel4.add(deviceField5); + + jTabbedPane1.addTab("Port 2", jPanel4); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Mask: "); + deviceField6.setOffsetNid(53); + jPanel5.add(deviceField6); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Value: "); + deviceField7.setNumCols(35); + deviceField7.setOffsetNid(45); + jPanel5.add(deviceField7); + + jTabbedPane1.addTab("Port 3", jPanel5); + + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceField deviceField1; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private DeviceField deviceField7; + private DeviceField deviceField8; + private DeviceField deviceField9; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_PYTHON_GENERICSetup.java b/java/jdevices/src/main/java/MARTE2_PYTHON_GENERICSetup.java index be6acd6aca..08e21c9648 100644 --- a/java/jdevices/src/main/java/MARTE2_PYTHON_GENERICSetup.java +++ b/java/jdevices/src/main/java/MARTE2_PYTHON_GENERICSetup.java @@ -104,41 +104,49 @@ private void initComponents() { deviceChoice9 = new DeviceChoice(); deviceField30 = new DeviceField(); deviceField31 = new DeviceField(); + deviceField69 = new DeviceField(); jPanel31 = new javax.swing.JPanel(); deviceField32 = new DeviceField(); deviceChoice10 = new DeviceChoice(); deviceField33 = new DeviceField(); deviceField34 = new DeviceField(); + deviceField70 = new DeviceField(); jPanel32 = new javax.swing.JPanel(); deviceField35 = new DeviceField(); deviceChoice11 = new DeviceChoice(); deviceField36 = new DeviceField(); deviceField37 = new DeviceField(); + deviceField71 = new DeviceField(); jPanel33 = new javax.swing.JPanel(); deviceField38 = new DeviceField(); deviceChoice12 = new DeviceChoice(); deviceField39 = new DeviceField(); deviceField40 = new DeviceField(); + deviceField72 = new DeviceField(); jPanel34 = new javax.swing.JPanel(); deviceField41 = new DeviceField(); deviceChoice13 = new DeviceChoice(); deviceField42 = new DeviceField(); deviceField43 = new DeviceField(); + deviceField73 = new DeviceField(); jPanel35 = new javax.swing.JPanel(); deviceField44 = new DeviceField(); deviceChoice14 = new DeviceChoice(); deviceField45 = new DeviceField(); deviceField46 = new DeviceField(); + deviceField74 = new DeviceField(); jPanel36 = new javax.swing.JPanel(); deviceField47 = new DeviceField(); deviceChoice15 = new DeviceChoice(); deviceField48 = new DeviceField(); deviceField49 = new DeviceField(); + deviceField75 = new DeviceField(); jPanel37 = new javax.swing.JPanel(); deviceField50 = new DeviceField(); deviceChoice16 = new DeviceChoice(); deviceField51 = new DeviceField(); deviceField52 = new DeviceField(); + deviceField76 = new DeviceField(); jScrollPane3 = new javax.swing.JScrollPane(); jPanel38 = new javax.swing.JPanel(); jPanel39 = new javax.swing.JPanel(); @@ -520,209 +528,257 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { deviceField31.setOffsetNid(101); jPanel30.add(deviceField31); + deviceField69.setIdentifier(""); + deviceField69.setLabelString("Stream Name:"); + deviceField69.setOffsetNid(102); + deviceField69.setTextOnly(true); + jPanel30.add(deviceField69); + jPanel29.add(jPanel30); jPanel31.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 2")); deviceField32.setIdentifier(""); deviceField32.setLabelString("Name: "); - deviceField32.setOffsetNid(105); + deviceField32.setOffsetNid(106); deviceField32.setTextOnly(true); jPanel31.add(deviceField32); deviceChoice10.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice10.setIdentifier(""); deviceChoice10.setLabelString("Type: "); - deviceChoice10.setOffsetNid(106); + deviceChoice10.setOffsetNid(107); deviceChoice10.setUpdateIdentifier(""); jPanel31.add(deviceChoice10); deviceField33.setIdentifier(""); deviceField33.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField33.setNumCols(4); - deviceField33.setOffsetNid(108); + deviceField33.setOffsetNid(109); jPanel31.add(deviceField33); deviceField34.setIdentifier(""); deviceField34.setLabelString("Seg. Len (0 to disable)"); deviceField34.setNumCols(4); - deviceField34.setOffsetNid(109); + deviceField34.setOffsetNid(110); jPanel31.add(deviceField34); + deviceField70.setIdentifier(""); + deviceField70.setLabelString("Stream Name:"); + deviceField70.setOffsetNid(111); + deviceField70.setTextOnly(true); + jPanel31.add(deviceField70); + jPanel29.add(jPanel31); jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 3")); deviceField35.setIdentifier(""); deviceField35.setLabelString("Name: "); - deviceField35.setOffsetNid(113); + deviceField35.setOffsetNid(115); deviceField35.setTextOnly(true); jPanel32.add(deviceField35); deviceChoice11.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice11.setIdentifier(""); deviceChoice11.setLabelString("Type: "); - deviceChoice11.setOffsetNid(114); + deviceChoice11.setOffsetNid(116); deviceChoice11.setUpdateIdentifier(""); jPanel32.add(deviceChoice11); deviceField36.setIdentifier(""); deviceField36.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField36.setNumCols(4); - deviceField36.setOffsetNid(116); + deviceField36.setOffsetNid(118); jPanel32.add(deviceField36); deviceField37.setIdentifier(""); deviceField37.setLabelString("Seg. Len (0 to disable)"); deviceField37.setNumCols(4); - deviceField37.setOffsetNid(117); + deviceField37.setOffsetNid(119); jPanel32.add(deviceField37); + deviceField71.setIdentifier(""); + deviceField71.setLabelString("Stream Name:"); + deviceField71.setOffsetNid(120); + deviceField71.setTextOnly(true); + jPanel32.add(deviceField71); + jPanel29.add(jPanel32); jPanel33.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 4")); deviceField38.setIdentifier(""); deviceField38.setLabelString("Name: "); - deviceField38.setOffsetNid(121); + deviceField38.setOffsetNid(124); deviceField38.setTextOnly(true); jPanel33.add(deviceField38); deviceChoice12.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice12.setIdentifier(""); deviceChoice12.setLabelString("Type: "); - deviceChoice12.setOffsetNid(122); + deviceChoice12.setOffsetNid(125); deviceChoice12.setUpdateIdentifier(""); jPanel33.add(deviceChoice12); deviceField39.setIdentifier(""); deviceField39.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField39.setNumCols(4); - deviceField39.setOffsetNid(124); + deviceField39.setOffsetNid(127); jPanel33.add(deviceField39); deviceField40.setIdentifier(""); deviceField40.setLabelString("Seg. Len (0 to disable)"); deviceField40.setNumCols(4); - deviceField40.setOffsetNid(125); + deviceField40.setOffsetNid(128); jPanel33.add(deviceField40); + deviceField72.setIdentifier(""); + deviceField72.setLabelString("Stream Name:"); + deviceField72.setOffsetNid(129); + deviceField72.setTextOnly(true); + jPanel33.add(deviceField72); + jPanel29.add(jPanel33); jPanel34.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 5")); deviceField41.setIdentifier(""); deviceField41.setLabelString("Name: "); - deviceField41.setOffsetNid(129); + deviceField41.setOffsetNid(133); deviceField41.setTextOnly(true); jPanel34.add(deviceField41); deviceChoice13.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice13.setIdentifier(""); deviceChoice13.setLabelString("Type: "); - deviceChoice13.setOffsetNid(130); + deviceChoice13.setOffsetNid(134); deviceChoice13.setUpdateIdentifier(""); jPanel34.add(deviceChoice13); deviceField42.setIdentifier(""); deviceField42.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField42.setNumCols(4); - deviceField42.setOffsetNid(132); + deviceField42.setOffsetNid(136); jPanel34.add(deviceField42); deviceField43.setIdentifier(""); deviceField43.setLabelString("Seg. Len (0 to disable)"); deviceField43.setNumCols(4); - deviceField43.setOffsetNid(133); + deviceField43.setOffsetNid(137); jPanel34.add(deviceField43); + deviceField73.setIdentifier(""); + deviceField73.setLabelString("Stream Name:"); + deviceField73.setOffsetNid(138); + deviceField73.setTextOnly(true); + jPanel34.add(deviceField73); + jPanel29.add(jPanel34); jPanel35.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 6")); deviceField44.setIdentifier(""); deviceField44.setLabelString("Name: "); - deviceField44.setOffsetNid(137); + deviceField44.setOffsetNid(142); deviceField44.setTextOnly(true); jPanel35.add(deviceField44); deviceChoice14.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice14.setIdentifier(""); deviceChoice14.setLabelString("Type: "); - deviceChoice14.setOffsetNid(138); + deviceChoice14.setOffsetNid(143); deviceChoice14.setUpdateIdentifier(""); jPanel35.add(deviceChoice14); deviceField45.setIdentifier(""); deviceField45.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField45.setNumCols(4); - deviceField45.setOffsetNid(140); + deviceField45.setOffsetNid(145); jPanel35.add(deviceField45); deviceField46.setIdentifier(""); deviceField46.setLabelString("Seg. Len (0 to disable)"); deviceField46.setNumCols(4); - deviceField46.setOffsetNid(141); + deviceField46.setOffsetNid(146); jPanel35.add(deviceField46); + deviceField74.setIdentifier(""); + deviceField74.setLabelString("Stream Name:"); + deviceField74.setOffsetNid(147); + deviceField74.setTextOnly(true); + jPanel35.add(deviceField74); + jPanel29.add(jPanel35); jPanel36.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 7")); deviceField47.setIdentifier(""); deviceField47.setLabelString("Name: "); - deviceField47.setOffsetNid(145); + deviceField47.setOffsetNid(151); deviceField47.setTextOnly(true); jPanel36.add(deviceField47); deviceChoice15.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice15.setIdentifier(""); deviceChoice15.setLabelString("Type: "); - deviceChoice15.setOffsetNid(146); + deviceChoice15.setOffsetNid(152); deviceChoice15.setUpdateIdentifier(""); jPanel36.add(deviceChoice15); deviceField48.setIdentifier(""); deviceField48.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField48.setNumCols(4); - deviceField48.setOffsetNid(148); + deviceField48.setOffsetNid(154); jPanel36.add(deviceField48); deviceField49.setIdentifier(""); deviceField49.setLabelString("Seg. Len (0 to disable)"); deviceField49.setNumCols(4); - deviceField49.setOffsetNid(149); + deviceField49.setOffsetNid(155); jPanel36.add(deviceField49); + deviceField75.setIdentifier(""); + deviceField75.setLabelString("Stream Name:"); + deviceField75.setOffsetNid(156); + deviceField75.setTextOnly(true); + jPanel36.add(deviceField75); + jPanel29.add(jPanel36); jPanel37.setBorder(javax.swing.BorderFactory.createTitledBorder("Output 8")); deviceField50.setIdentifier(""); deviceField50.setLabelString("Name: "); - deviceField50.setOffsetNid(153); + deviceField50.setOffsetNid(160); deviceField50.setTextOnly(true); jPanel37.add(deviceField50); deviceChoice16.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice16.setIdentifier(""); deviceChoice16.setLabelString("Type: "); - deviceChoice16.setOffsetNid(154); + deviceChoice16.setOffsetNid(161); deviceChoice16.setUpdateIdentifier(""); jPanel37.add(deviceChoice16); deviceField51.setIdentifier(""); deviceField51.setLabelString("Dimensions (0 for scalar, -1 to disable):"); deviceField51.setNumCols(4); - deviceField51.setOffsetNid(156); + deviceField51.setOffsetNid(163); jPanel37.add(deviceField51); deviceField52.setIdentifier(""); deviceField52.setLabelString("Seg. Len (0 to disable)"); deviceField52.setNumCols(4); - deviceField52.setOffsetNid(157); + deviceField52.setOffsetNid(164); jPanel37.add(deviceField52); + deviceField76.setIdentifier(""); + deviceField76.setLabelString("Stream Name:"); + deviceField76.setOffsetNid(165); + deviceField76.setTextOnly(true); + jPanel37.add(deviceField76); + jPanel29.add(jPanel37); jScrollPane2.setViewportView(jPanel29); @@ -965,7 +1021,15 @@ private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRS private DeviceField deviceField66; private DeviceField deviceField67; private DeviceField deviceField68; + private DeviceField deviceField69; private DeviceField deviceField7; + private DeviceField deviceField70; + private DeviceField deviceField71; + private DeviceField deviceField72; + private DeviceField deviceField73; + private DeviceField deviceField74; + private DeviceField deviceField75; + private DeviceField deviceField76; private DeviceField deviceField8; private DeviceField deviceField9; private javax.swing.JButton jButton2; diff --git a/java/jdevices/src/main/java/MARTE2_PYTHON_PIDSetup.java b/java/jdevices/src/main/java/MARTE2_PYTHON_PIDSetup.java index 10c69cab76..98ab267398 100644 --- a/java/jdevices/src/main/java/MARTE2_PYTHON_PIDSetup.java +++ b/java/jdevices/src/main/java/MARTE2_PYTHON_PIDSetup.java @@ -29,112 +29,131 @@ public MARTE2_PYTHON_PIDSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - jPanel2 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField2 = new DeviceField(); - jPanel1 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceField3 = new DeviceField(); - deviceField4 = new DeviceField(); - deviceField5 = new DeviceField(); - deviceField8 = new DeviceField(); - jPanel4 = new javax.swing.JPanel(); - jPanel5 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceChoice1 = new DeviceChoice(); - jPanel6 = new javax.swing.JPanel(); - deviceField7 = new DeviceField(); - deviceField9 = new DeviceField(); - deviceButtons1 = new DeviceButtons(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("Python PID"); - setDeviceType("MARTE2_PYTHON_PID"); - setHeight(250); - setWidth(800); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Timebase"); - deviceField1.setNumCols(20); - deviceField1.setOffsetNid(3); - jPanel2.add(deviceField1); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Timebase Div:"); - deviceField2.setNumCols(4); - deviceField2.setOffsetNid(40); - jPanel2.add(deviceField2); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - jPanel1.setLayout(new java.awt.GridLayout(2, 1)); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Kp:"); - deviceField3.setNumCols(6); - deviceField3.setOffsetNid(10); - jPanel3.add(deviceField3); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Ki:"); - deviceField4.setNumCols(6); - deviceField4.setOffsetNid(13); - jPanel3.add(deviceField4); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Kd:"); - deviceField5.setNumCols(6); - deviceField5.setOffsetNid(16); - jPanel3.add(deviceField5); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Period:"); - deviceField8.setNumCols(4); - deviceField8.setOffsetNid(19); - jPanel3.add(deviceField8); - jPanel1.add(jPanel3); - jPanel4.setLayout(new java.awt.GridLayout(2, 0)); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Input"); - deviceField6.setNumCols(35); - deviceField6.setOffsetNid(25); - jPanel5.add(deviceField6); - deviceChoice1.setChoiceItems(new String[] - { "int16", "int32", "float32", "float64" }); - deviceChoice1.setIdentifier(""); - deviceChoice1.setLabelString("Output type: "); - deviceChoice1.setOffsetNid(37); - deviceChoice1.setUpdateIdentifier(""); - jPanel5.add(deviceChoice1); - jPanel4.add(jPanel5); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Seg. len (0 to disable writing)"); - deviceField7.setNumCols(4); - deviceField7.setOffsetNid(40); - jPanel6.add(deviceField7); - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Out CPUs:"); - deviceField9.setNumCols(4); - deviceField9.setOffsetNid(34); - jPanel6.add(deviceField9); - jPanel4.add(jPanel6); - jPanel1.add(jPanel4); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice1; - private DeviceField deviceField1; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private DeviceField deviceField8; - private DeviceField deviceField9; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel6; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel2 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField2 = new DeviceField(); + jPanel1 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); + deviceField4 = new DeviceField(); + deviceField5 = new DeviceField(); + deviceField8 = new DeviceField(); + jPanel4 = new javax.swing.JPanel(); + jPanel5 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + deviceChoice1 = new DeviceChoice(); + jPanel6 = new javax.swing.JPanel(); + deviceField7 = new DeviceField(); + deviceField9 = new DeviceField(); + deviceButtons1 = new DeviceButtons(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("Python PID"); + setDeviceType("MARTE2_PYTHON_PID"); + setHeight(250); + setWidth(800); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Timebase"); + deviceField1.setNumCols(20); + deviceField1.setOffsetNid(3); + jPanel2.add(deviceField1); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Timebase Div:"); + deviceField2.setNumCols(4); + deviceField2.setOffsetNid(40); + jPanel2.add(deviceField2); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + jPanel1.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Kp:"); + deviceField3.setNumCols(6); + deviceField3.setOffsetNid(10); + jPanel3.add(deviceField3); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Ki:"); + deviceField4.setNumCols(6); + deviceField4.setOffsetNid(13); + jPanel3.add(deviceField4); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Kd:"); + deviceField5.setNumCols(6); + deviceField5.setOffsetNid(16); + jPanel3.add(deviceField5); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Period:"); + deviceField8.setNumCols(4); + deviceField8.setOffsetNid(19); + jPanel3.add(deviceField8); + + jPanel1.add(jPanel3); + + jPanel4.setLayout(new java.awt.GridLayout(2, 0)); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Input"); + deviceField6.setNumCols(35); + deviceField6.setOffsetNid(25); + jPanel5.add(deviceField6); + + deviceChoice1.setChoiceItems(new String[] {"int16", "int32", "float32", "float64"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString("Output type: "); + deviceChoice1.setOffsetNid(37); + deviceChoice1.setUpdateIdentifier(""); + jPanel5.add(deviceChoice1); + + jPanel4.add(jPanel5); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Seg. len (0 to disable writing)"); + deviceField7.setNumCols(4); + deviceField7.setOffsetNid(40); + jPanel6.add(deviceField7); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Out CPUs:"); + deviceField9.setNumCols(4); + deviceField9.setOffsetNid(34); + jPanel6.add(deviceField9); + + jPanel4.add(jPanel6); + + jPanel1.add(jPanel4); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceField deviceField1; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private DeviceField deviceField7; + private DeviceField deviceField8; + private DeviceField deviceField9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_RESAMPLERSetup.java b/java/jdevices/src/main/java/MARTE2_RESAMPLERSetup.java index 2a738e56d3..95f0d42142 100644 --- a/java/jdevices/src/main/java/MARTE2_RESAMPLERSetup.java +++ b/java/jdevices/src/main/java/MARTE2_RESAMPLERSetup.java @@ -137,7 +137,7 @@ private void initComponents() { jPanel37 = new javax.swing.JPanel(); deviceField52 = new DeviceField(); - setDeviceProvider("scdevail:8100"); + setDeviceProvider("spilds:8100"); setDeviceTitle("MARTe2 Resampler "); setDeviceType("MARTE2_RESAMPLER"); setHeight(400); @@ -576,7 +576,7 @@ private void initComponents() { deviceField38.setIdentifier(""); deviceField38.setLabelString("Segment Len (0 to disable write):"); deviceField38.setNumCols(6); - deviceField38.setOffsetNid(147); + deviceField38.setOffsetNid(148); jPanel23.add(deviceField38); jPanel21.add(jPanel23); @@ -586,7 +586,7 @@ private void initComponents() { deviceField39.setIdentifier(""); deviceField39.setLabelString("Segment Len (0 to disable write):"); deviceField39.setNumCols(6); - deviceField39.setOffsetNid(155); + deviceField39.setOffsetNid(157); jPanel24.add(deviceField39); jPanel21.add(jPanel24); @@ -596,7 +596,7 @@ private void initComponents() { deviceField40.setIdentifier(""); deviceField40.setLabelString("Segment Len (0 to disable write):"); deviceField40.setNumCols(6); - deviceField40.setOffsetNid(163); + deviceField40.setOffsetNid(166); jPanel25.add(deviceField40); jPanel21.add(jPanel25); @@ -606,7 +606,7 @@ private void initComponents() { deviceField41.setIdentifier(""); deviceField41.setLabelString("Segment Len (0 to disable write):"); deviceField41.setNumCols(6); - deviceField41.setOffsetNid(171); + deviceField41.setOffsetNid(175); jPanel26.add(deviceField41); jPanel21.add(jPanel26); @@ -616,7 +616,7 @@ private void initComponents() { deviceField42.setIdentifier(""); deviceField42.setLabelString("Segment Len (0 to disable write):"); deviceField42.setNumCols(6); - deviceField42.setOffsetNid(179); + deviceField42.setOffsetNid(184); jPanel27.add(deviceField42); jPanel21.add(jPanel27); @@ -626,7 +626,7 @@ private void initComponents() { deviceField43.setIdentifier(""); deviceField43.setLabelString("Segment Len (0 to disable write):"); deviceField43.setNumCols(6); - deviceField43.setOffsetNid(187); + deviceField43.setOffsetNid(193); jPanel28.add(deviceField43); jPanel21.add(jPanel28); @@ -636,7 +636,7 @@ private void initComponents() { deviceField44.setIdentifier(""); deviceField44.setLabelString("Segment Len (0 to disable write):"); deviceField44.setNumCols(6); - deviceField44.setOffsetNid(195); + deviceField44.setOffsetNid(202); jPanel29.add(deviceField44); jPanel21.add(jPanel29); @@ -646,7 +646,7 @@ private void initComponents() { deviceField45.setIdentifier(""); deviceField45.setLabelString("Segment Len (0 to disable write):"); deviceField45.setNumCols(6); - deviceField45.setOffsetNid(203); + deviceField45.setOffsetNid(211); jPanel30.add(deviceField45); jPanel21.add(jPanel30); @@ -656,7 +656,7 @@ private void initComponents() { deviceField46.setIdentifier(""); deviceField46.setLabelString("Segment Len (0 to disable write):"); deviceField46.setNumCols(6); - deviceField46.setOffsetNid(211); + deviceField46.setOffsetNid(220); jPanel31.add(deviceField46); jPanel21.add(jPanel31); @@ -666,7 +666,7 @@ private void initComponents() { deviceField47.setIdentifier(""); deviceField47.setLabelString("Segment Len (0 to disable write):"); deviceField47.setNumCols(6); - deviceField47.setOffsetNid(219); + deviceField47.setOffsetNid(229); jPanel32.add(deviceField47); jPanel21.add(jPanel32); @@ -676,7 +676,7 @@ private void initComponents() { deviceField48.setIdentifier(""); deviceField48.setLabelString("Segment Len (0 to disable write):"); deviceField48.setNumCols(6); - deviceField48.setOffsetNid(227); + deviceField48.setOffsetNid(238); jPanel33.add(deviceField48); jPanel21.add(jPanel33); @@ -686,7 +686,7 @@ private void initComponents() { deviceField49.setIdentifier(""); deviceField49.setLabelString("Segment Len (0 to disable write):"); deviceField49.setNumCols(6); - deviceField49.setOffsetNid(235); + deviceField49.setOffsetNid(247); jPanel34.add(deviceField49); jPanel21.add(jPanel34); @@ -696,7 +696,7 @@ private void initComponents() { deviceField50.setIdentifier(""); deviceField50.setLabelString("Segment Len (0 to disable write):"); deviceField50.setNumCols(6); - deviceField50.setOffsetNid(243); + deviceField50.setOffsetNid(256); jPanel35.add(deviceField50); jPanel21.add(jPanel35); @@ -706,7 +706,7 @@ private void initComponents() { deviceField51.setIdentifier(""); deviceField51.setLabelString("Segment Len (0 to disable write):"); deviceField51.setNumCols(6); - deviceField51.setOffsetNid(251); + deviceField51.setOffsetNid(265); jPanel36.add(deviceField51); jPanel21.add(jPanel36); @@ -716,7 +716,7 @@ private void initComponents() { deviceField52.setIdentifier(""); deviceField52.setLabelString("Segment Len (0 to disable write):"); deviceField52.setNumCols(6); - deviceField52.setOffsetNid(259); + deviceField52.setOffsetNid(274); jPanel37.add(deviceField52); jPanel21.add(jPanel37); diff --git a/java/jdevices/src/main/java/MARTE2_RTSMSetup.java b/java/jdevices/src/main/java/MARTE2_RTSMSetup.java index 1116df063f..7c8a0f1453 100644 --- a/java/jdevices/src/main/java/MARTE2_RTSMSetup.java +++ b/java/jdevices/src/main/java/MARTE2_RTSMSetup.java @@ -4739,7 +4739,7 @@ private void initComponents() { deviceField42.setIdentifier(""); deviceField42.setLabelString("Segment Len.:"); deviceField42.setNumCols(6); - deviceField42.setOffsetNid(3648); + deviceField42.setOffsetNid(3649); jPanel220.add(deviceField42); deviceChoice9.setChoiceIntValues(new int[] {0, -1}); @@ -4758,7 +4758,7 @@ private void initComponents() { deviceField43.setIdentifier(""); deviceField43.setLabelString("Segment Len.:"); deviceField43.setNumCols(6); - deviceField43.setOffsetNid(3657); + deviceField43.setOffsetNid(3658); jPanel222.add(deviceField43); deviceChoice10.setChoiceIntValues(new int[] {0, -1}); @@ -4766,7 +4766,7 @@ private void initComponents() { deviceChoice10.setConvert(true); deviceChoice10.setIdentifier(""); deviceChoice10.setLabelString("Output: "); - deviceChoice10.setOffsetNid(3655); + deviceChoice10.setOffsetNid(3657); deviceChoice10.setUpdateIdentifier(""); jPanel222.add(deviceChoice10); @@ -4777,7 +4777,7 @@ private void initComponents() { deviceField44.setIdentifier(""); deviceField44.setLabelString("Segment Len.:"); deviceField44.setNumCols(6); - deviceField44.setOffsetNid(3664); + deviceField44.setOffsetNid(3667); jPanel223.add(deviceField44); deviceChoice11.setChoiceIntValues(new int[] {0, -1}); @@ -4785,7 +4785,7 @@ private void initComponents() { deviceChoice11.setConvert(true); deviceChoice11.setIdentifier(""); deviceChoice11.setLabelString("Output: "); - deviceChoice11.setOffsetNid(3663); + deviceChoice11.setOffsetNid(3666); deviceChoice11.setUpdateIdentifier(""); jPanel223.add(deviceChoice11); @@ -4796,7 +4796,7 @@ private void initComponents() { deviceField45.setIdentifier(""); deviceField45.setLabelString("Segment Len.:"); deviceField45.setNumCols(6); - deviceField45.setOffsetNid(3672); + deviceField45.setOffsetNid(3676); jPanel224.add(deviceField45); deviceChoice12.setChoiceIntValues(new int[] {0, -1}); @@ -4804,7 +4804,7 @@ private void initComponents() { deviceChoice12.setConvert(true); deviceChoice12.setIdentifier(""); deviceChoice12.setLabelString("Output: "); - deviceChoice12.setOffsetNid(3671); + deviceChoice12.setOffsetNid(3675); deviceChoice12.setUpdateIdentifier(""); jPanel224.add(deviceChoice12); @@ -4815,7 +4815,7 @@ private void initComponents() { deviceField46.setIdentifier(""); deviceField46.setLabelString("Segment Len.:"); deviceField46.setNumCols(6); - deviceField46.setOffsetNid(3680); + deviceField46.setOffsetNid(3685); jPanel225.add(deviceField46); deviceChoice13.setChoiceIntValues(new int[] {0, -1}); @@ -4823,7 +4823,7 @@ private void initComponents() { deviceChoice13.setConvert(true); deviceChoice13.setIdentifier(""); deviceChoice13.setLabelString("Output: "); - deviceChoice13.setOffsetNid(3679); + deviceChoice13.setOffsetNid(3684); deviceChoice13.setUpdateIdentifier(""); jPanel225.add(deviceChoice13); @@ -4834,7 +4834,7 @@ private void initComponents() { deviceField47.setIdentifier(""); deviceField47.setLabelString("Segment Len.:"); deviceField47.setNumCols(6); - deviceField47.setOffsetNid(3688); + deviceField47.setOffsetNid(3694); jPanel226.add(deviceField47); deviceChoice14.setChoiceIntValues(new int[] {0, -1}); @@ -4842,7 +4842,7 @@ private void initComponents() { deviceChoice14.setConvert(true); deviceChoice14.setIdentifier(""); deviceChoice14.setLabelString("Output: "); - deviceChoice14.setOffsetNid(3687); + deviceChoice14.setOffsetNid(3693); deviceChoice14.setUpdateIdentifier(""); jPanel226.add(deviceChoice14); @@ -4853,7 +4853,7 @@ private void initComponents() { deviceField48.setIdentifier(""); deviceField48.setLabelString("Segment Len.:"); deviceField48.setNumCols(6); - deviceField48.setOffsetNid(3696); + deviceField48.setOffsetNid(3703); jPanel227.add(deviceField48); deviceChoice15.setChoiceIntValues(new int[] {0, -1}); @@ -4861,7 +4861,7 @@ private void initComponents() { deviceChoice15.setConvert(true); deviceChoice15.setIdentifier(""); deviceChoice15.setLabelString("Output: "); - deviceChoice15.setOffsetNid(3695); + deviceChoice15.setOffsetNid(3702); deviceChoice15.setUpdateIdentifier(""); jPanel227.add(deviceChoice15); @@ -4872,7 +4872,7 @@ private void initComponents() { deviceField49.setIdentifier(""); deviceField49.setLabelString("Segment Len.:"); deviceField49.setNumCols(6); - deviceField49.setOffsetNid(3704); + deviceField49.setOffsetNid(3712); jPanel228.add(deviceField49); deviceChoice16.setChoiceIntValues(new int[] {0, -1}); @@ -4880,7 +4880,7 @@ private void initComponents() { deviceChoice16.setConvert(true); deviceChoice16.setIdentifier(""); deviceChoice16.setLabelString("Output: "); - deviceChoice16.setOffsetNid(3703); + deviceChoice16.setOffsetNid(3711); deviceChoice16.setUpdateIdentifier(""); jPanel228.add(deviceChoice16); diff --git a/java/jdevices/src/main/java/MARTE2_SIMULINK_FLUXMAPSetup.java b/java/jdevices/src/main/java/MARTE2_SIMULINK_FLUXMAPSetup.java new file mode 100644 index 0000000000..5a63f1e8eb --- /dev/null +++ b/java/jdevices/src/main/java/MARTE2_SIMULINK_FLUXMAPSetup.java @@ -0,0 +1,75 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author mdsplus + */ +public class MARTE2_SIMULINK_FLUXMAPSetup extends DeviceSetup { + + /** + * Creates new form MARTE2_SIMULINK_FLUXMAPSetup + */ + public MARTE2_SIMULINK_FLUXMAPSetup() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + deviceInputs1 = new DeviceInputs(); + deviceOutputs1 = new DeviceOutputs(); + deviceParameters1 = new DeviceParameters(); + jPanel1 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("Fluxmap"); + setDeviceType("MARTE2_SIMULINK_FLUXMAP"); + setHeight(400); + setUpdateEvent(""); + setWidth(500); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + deviceInputs1.setOffsetNid(50); + jTabbedPane1.addTab("Inputs", deviceInputs1); + + deviceOutputs1.setOffsetNid(171); + jTabbedPane1.addTab("Outputs", deviceOutputs1); + + deviceParameters1.setNumParameters(10); + deviceParameters1.setOffsetNid(4); + deviceParameters1.setParameterOffset(5); + jTabbedPane1.addTab("Parameters", deviceParameters1); + + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); + + deviceField1.setIdentifier(""); + deviceField1.setOffsetNid(3); + jPanel1.add(deviceField1); + + getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceField deviceField1; + private DeviceInputs deviceInputs1; + private DeviceOutputs deviceOutputs1; + private DeviceParameters deviceParameters1; + private javax.swing.JPanel jPanel1; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/java/jdevices/src/main/java/MARTE2_SIMULINK_GENERICSetup.java b/java/jdevices/src/main/java/MARTE2_SIMULINK_GENERICSetup.java index 721036b64c..5afc18761b 100644 --- a/java/jdevices/src/main/java/MARTE2_SIMULINK_GENERICSetup.java +++ b/java/jdevices/src/main/java/MARTE2_SIMULINK_GENERICSetup.java @@ -96,41 +96,49 @@ private void initComponents() { deviceChoice9 = new DeviceChoice(); deviceField30 = new DeviceField(); deviceField31 = new DeviceField(); + deviceField69 = new DeviceField(); jPanel31 = new javax.swing.JPanel(); deviceField32 = new DeviceField(); deviceChoice10 = new DeviceChoice(); deviceField33 = new DeviceField(); deviceField34 = new DeviceField(); + deviceField70 = new DeviceField(); jPanel32 = new javax.swing.JPanel(); deviceField35 = new DeviceField(); deviceChoice11 = new DeviceChoice(); deviceField36 = new DeviceField(); deviceField37 = new DeviceField(); + deviceField71 = new DeviceField(); jPanel33 = new javax.swing.JPanel(); deviceField38 = new DeviceField(); deviceChoice12 = new DeviceChoice(); deviceField39 = new DeviceField(); deviceField40 = new DeviceField(); + deviceField72 = new DeviceField(); jPanel34 = new javax.swing.JPanel(); deviceField41 = new DeviceField(); deviceChoice13 = new DeviceChoice(); deviceField42 = new DeviceField(); deviceField43 = new DeviceField(); + deviceField73 = new DeviceField(); jPanel35 = new javax.swing.JPanel(); deviceField44 = new DeviceField(); deviceChoice14 = new DeviceChoice(); deviceField45 = new DeviceField(); deviceField46 = new DeviceField(); + deviceField74 = new DeviceField(); jPanel36 = new javax.swing.JPanel(); deviceField47 = new DeviceField(); deviceChoice15 = new DeviceChoice(); deviceField48 = new DeviceField(); deviceField49 = new DeviceField(); + deviceField75 = new DeviceField(); jPanel37 = new javax.swing.JPanel(); deviceField50 = new DeviceField(); deviceChoice16 = new DeviceChoice(); deviceField51 = new DeviceField(); deviceField52 = new DeviceField(); + deviceField76 = new DeviceField(); jScrollPane3 = new javax.swing.JScrollPane(); jPanel38 = new javax.swing.JPanel(); jPanel39 = new javax.swing.JPanel(); @@ -161,7 +169,6 @@ private void initComponents() { jPanel2 = new javax.swing.JPanel(); deviceField1 = new DeviceField(); deviceField2 = new DeviceField(); - deviceChoice18 = new DeviceChoice(); jPanel3 = new javax.swing.JPanel(); deviceField3 = new DeviceField(); deviceField4 = new DeviceField(); @@ -482,209 +489,257 @@ private void initComponents() { deviceField31.setOffsetNid(107); jPanel30.add(deviceField31); + deviceField69.setIdentifier(""); + deviceField69.setLabelString("Stream: "); + deviceField69.setOffsetNid(108); + deviceField69.setTextOnly(true); + jPanel30.add(deviceField69); + jPanel29.add(jPanel30); jPanel31.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 2")); deviceField32.setIdentifier(""); deviceField32.setLabelString("Name:"); - deviceField32.setOffsetNid(111); + deviceField32.setOffsetNid(112); deviceField32.setTextOnly(true); jPanel31.add(deviceField32); deviceChoice10.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice10.setIdentifier(""); deviceChoice10.setLabelString("Type:"); - deviceChoice10.setOffsetNid(112); + deviceChoice10.setOffsetNid(113); deviceChoice10.setUpdateIdentifier(""); jPanel31.add(deviceChoice10); deviceField33.setIdentifier(""); deviceField33.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField33.setNumCols(8); - deviceField33.setOffsetNid(114); + deviceField33.setOffsetNid(115); jPanel31.add(deviceField33); deviceField34.setIdentifier(""); deviceField34.setLabelString("Seg. Len (0 to disable):"); deviceField34.setNumCols(14); - deviceField34.setOffsetNid(115); + deviceField34.setOffsetNid(116); jPanel31.add(deviceField34); + deviceField70.setIdentifier(""); + deviceField70.setLabelString("Stream: "); + deviceField70.setOffsetNid(117); + deviceField70.setTextOnly(true); + jPanel31.add(deviceField70); + jPanel29.add(jPanel31); jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 3")); deviceField35.setIdentifier(""); deviceField35.setLabelString("Name:"); - deviceField35.setOffsetNid(119); + deviceField35.setOffsetNid(121); deviceField35.setTextOnly(true); jPanel32.add(deviceField35); deviceChoice11.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice11.setIdentifier(""); deviceChoice11.setLabelString("Type:"); - deviceChoice11.setOffsetNid(120); + deviceChoice11.setOffsetNid(122); deviceChoice11.setUpdateIdentifier(""); jPanel32.add(deviceChoice11); deviceField36.setIdentifier(""); deviceField36.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField36.setNumCols(8); - deviceField36.setOffsetNid(122); + deviceField36.setOffsetNid(124); jPanel32.add(deviceField36); deviceField37.setIdentifier(""); deviceField37.setLabelString("Seg. Len (0 to disable):"); deviceField37.setNumCols(14); - deviceField37.setOffsetNid(123); + deviceField37.setOffsetNid(125); jPanel32.add(deviceField37); + deviceField71.setIdentifier(""); + deviceField71.setLabelString("Stream: "); + deviceField71.setOffsetNid(126); + deviceField71.setTextOnly(true); + jPanel32.add(deviceField71); + jPanel29.add(jPanel32); jPanel33.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 4")); deviceField38.setIdentifier(""); deviceField38.setLabelString("Name:"); - deviceField38.setOffsetNid(127); + deviceField38.setOffsetNid(130); deviceField38.setTextOnly(true); jPanel33.add(deviceField38); deviceChoice12.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice12.setIdentifier(""); deviceChoice12.setLabelString("Type:"); - deviceChoice12.setOffsetNid(128); + deviceChoice12.setOffsetNid(131); deviceChoice12.setUpdateIdentifier(""); jPanel33.add(deviceChoice12); deviceField39.setIdentifier(""); deviceField39.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField39.setNumCols(8); - deviceField39.setOffsetNid(130); + deviceField39.setOffsetNid(133); jPanel33.add(deviceField39); deviceField40.setIdentifier(""); deviceField40.setLabelString("Seg. Len (0 to disable):"); deviceField40.setNumCols(14); - deviceField40.setOffsetNid(131); + deviceField40.setOffsetNid(134); jPanel33.add(deviceField40); + deviceField72.setIdentifier(""); + deviceField72.setLabelString("Stream: "); + deviceField72.setOffsetNid(135); + deviceField72.setTextOnly(true); + jPanel33.add(deviceField72); + jPanel29.add(jPanel33); jPanel34.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 5")); deviceField41.setIdentifier(""); deviceField41.setLabelString("Name:"); - deviceField41.setOffsetNid(135); + deviceField41.setOffsetNid(139); deviceField41.setTextOnly(true); jPanel34.add(deviceField41); deviceChoice13.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice13.setIdentifier(""); deviceChoice13.setLabelString("Type:"); - deviceChoice13.setOffsetNid(136); + deviceChoice13.setOffsetNid(140); deviceChoice13.setUpdateIdentifier(""); jPanel34.add(deviceChoice13); deviceField42.setIdentifier(""); deviceField42.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField42.setNumCols(8); - deviceField42.setOffsetNid(138); + deviceField42.setOffsetNid(142); jPanel34.add(deviceField42); deviceField43.setIdentifier(""); deviceField43.setLabelString("Seg. Len (0 to disable):"); deviceField43.setNumCols(14); - deviceField43.setOffsetNid(139); + deviceField43.setOffsetNid(143); jPanel34.add(deviceField43); + deviceField73.setIdentifier(""); + deviceField73.setLabelString("Stream: "); + deviceField73.setOffsetNid(144); + deviceField73.setTextOnly(true); + jPanel34.add(deviceField73); + jPanel29.add(jPanel34); jPanel35.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 6")); deviceField44.setIdentifier(""); deviceField44.setLabelString("Name:"); - deviceField44.setOffsetNid(143); + deviceField44.setOffsetNid(148); deviceField44.setTextOnly(true); jPanel35.add(deviceField44); deviceChoice14.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice14.setIdentifier(""); deviceChoice14.setLabelString("Type:"); - deviceChoice14.setOffsetNid(144); + deviceChoice14.setOffsetNid(149); deviceChoice14.setUpdateIdentifier(""); jPanel35.add(deviceChoice14); deviceField45.setIdentifier(""); deviceField45.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField45.setNumCols(8); - deviceField45.setOffsetNid(146); + deviceField45.setOffsetNid(151); jPanel35.add(deviceField45); deviceField46.setIdentifier(""); deviceField46.setLabelString("Seg. Len (0 to disable):"); deviceField46.setNumCols(14); - deviceField46.setOffsetNid(147); + deviceField46.setOffsetNid(152); jPanel35.add(deviceField46); + deviceField74.setIdentifier(""); + deviceField74.setLabelString("Stream: "); + deviceField74.setOffsetNid(153); + deviceField74.setTextOnly(true); + jPanel35.add(deviceField74); + jPanel29.add(jPanel35); jPanel36.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 7")); deviceField47.setIdentifier(""); deviceField47.setLabelString("Name:"); - deviceField47.setOffsetNid(151); + deviceField47.setOffsetNid(157); deviceField47.setTextOnly(true); jPanel36.add(deviceField47); deviceChoice15.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice15.setIdentifier(""); deviceChoice15.setLabelString("Type:"); - deviceChoice15.setOffsetNid(152); + deviceChoice15.setOffsetNid(158); deviceChoice15.setUpdateIdentifier(""); jPanel36.add(deviceChoice15); deviceField48.setIdentifier(""); deviceField48.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField48.setNumCols(8); - deviceField48.setOffsetNid(154); + deviceField48.setOffsetNid(160); jPanel36.add(deviceField48); deviceField49.setIdentifier(""); deviceField49.setLabelString("Seg. Len (0 to disable):"); deviceField49.setNumCols(14); - deviceField49.setOffsetNid(155); + deviceField49.setOffsetNid(161); jPanel36.add(deviceField49); + deviceField75.setIdentifier(""); + deviceField75.setLabelString("Stream: "); + deviceField75.setOffsetNid(162); + deviceField75.setTextOnly(true); + jPanel36.add(deviceField75); + jPanel29.add(jPanel36); jPanel37.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Output 1"), "Output 8")); deviceField50.setIdentifier(""); deviceField50.setLabelString("Name:"); - deviceField50.setOffsetNid(159); + deviceField50.setOffsetNid(166); deviceField50.setTextOnly(true); jPanel37.add(deviceField50); deviceChoice16.setChoiceItems(new String[] {"int8", "int16", "int32", "int64", "float32", "float64"}); deviceChoice16.setIdentifier(""); deviceChoice16.setLabelString("Type:"); - deviceChoice16.setOffsetNid(160); + deviceChoice16.setOffsetNid(167); deviceChoice16.setUpdateIdentifier(""); jPanel37.add(deviceChoice16); deviceField51.setIdentifier(""); deviceField51.setLabelString("Dimension (0 for scalar, -1 to disable)"); deviceField51.setNumCols(8); - deviceField51.setOffsetNid(162); + deviceField51.setOffsetNid(169); jPanel37.add(deviceField51); deviceField52.setIdentifier(""); deviceField52.setLabelString("Seg. Len (0 to disable):"); deviceField52.setNumCols(14); - deviceField52.setOffsetNid(163); + deviceField52.setOffsetNid(170); jPanel37.add(deviceField52); + deviceField76.setIdentifier(""); + deviceField76.setLabelString("Stream: "); + deviceField76.setOffsetNid(171); + deviceField76.setTextOnly(true); + jPanel37.add(deviceField76); + jPanel29.add(jPanel37); jScrollPane2.setViewportView(jPanel29); @@ -828,18 +883,11 @@ private void initComponents() { jPanel2.add(deviceField1); deviceField2.setIdentifier(""); - deviceField2.setLabelString("Timebase div.:"); + deviceField2.setLabelString("Timebase div. (if from another thread):"); deviceField2.setNumCols(4); deviceField2.setOffsetNid(166); jPanel2.add(deviceField2); - deviceChoice18.setChoiceItems(new String[] {"ENABLED", "DISABLED"}); - deviceChoice18.setIdentifier(""); - deviceChoice18.setLabelString("Logging:"); - deviceChoice18.setOffsetNid(167); - deviceChoice18.setUpdateIdentifier(""); - jPanel2.add(deviceChoice18); - jPanel1.add(jPanel2); deviceField3.setIdentifier(""); @@ -903,7 +951,6 @@ private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRS private DeviceChoice deviceChoice15; private DeviceChoice deviceChoice16; private DeviceChoice deviceChoice17; - private DeviceChoice deviceChoice18; private DeviceChoice deviceChoice2; private DeviceChoice deviceChoice3; private DeviceChoice deviceChoice4; @@ -977,7 +1024,15 @@ private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRS private DeviceField deviceField66; private DeviceField deviceField67; private DeviceField deviceField68; + private DeviceField deviceField69; private DeviceField deviceField7; + private DeviceField deviceField70; + private DeviceField deviceField71; + private DeviceField deviceField72; + private DeviceField deviceField73; + private DeviceField deviceField74; + private DeviceField deviceField75; + private DeviceField deviceField76; private DeviceField deviceField8; private DeviceField deviceField9; private javax.swing.JButton jButton1; diff --git a/java/jdevices/src/main/java/MARTE2_SIMULINK_RABBITSetup.java b/java/jdevices/src/main/java/MARTE2_SIMULINK_RABBITSetup.java new file mode 100644 index 0000000000..674253bc93 --- /dev/null +++ b/java/jdevices/src/main/java/MARTE2_SIMULINK_RABBITSetup.java @@ -0,0 +1,76 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author mdsplus + */ +public class MARTE2_SIMULINK_RABBITSetup extends DeviceSetup { + + /** + * Creates new form MARTE2_SIMULINK_RABBITSetup + */ + public MARTE2_SIMULINK_RABBITSetup() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceButtons1 = new DeviceButtons(); + jPanel2 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + deviceInputs1 = new DeviceInputs(); + deviceOutputs1 = new DeviceOutputs(); + deviceParameters1 = new DeviceParameters(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("Rabbit Setup"); + setDeviceType("MARTE2_SIMULINK_RABBIT"); + setHeight(400); + setUpdateEvent(""); + setWidth(500); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Timebase: "); + deviceField1.setOffsetNid(3); + jPanel2.add(deviceField1); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + deviceInputs1.setOffsetNid(32); + jTabbedPane1.addTab("Inputs", deviceInputs1); + + deviceOutputs1.setOffsetNid(353); + jTabbedPane1.addTab("Outputs", deviceOutputs1); + + deviceParameters1.setNumParameters(5); + deviceParameters1.setOffsetNid(4); + deviceParameters1.setParameterOffset(4); + jTabbedPane1.addTab("Parameters", deviceParameters1); + + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceField deviceField1; + private DeviceInputs deviceInputs1; + private DeviceOutputs deviceOutputs1; + private DeviceParameters deviceParameters1; + private javax.swing.JPanel jPanel2; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/java/jdevices/src/main/java/MARTE2_SIMULINK_RAPTORSetup.java b/java/jdevices/src/main/java/MARTE2_SIMULINK_RAPTORSetup.java index 4beea63acd..6911f3b539 100644 --- a/java/jdevices/src/main/java/MARTE2_SIMULINK_RAPTORSetup.java +++ b/java/jdevices/src/main/java/MARTE2_SIMULINK_RAPTORSetup.java @@ -30,722 +30,9 @@ private void initComponents() { jPanel2 = new javax.swing.JPanel(); deviceField1 = new DeviceField(); jTabbedPane1 = new javax.swing.JTabbedPane(); - jScrollPane1 = new javax.swing.JScrollPane(); - jPanel1 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceField2 = new DeviceField(); - deviceField3 = new DeviceField(); - jPanel4 = new javax.swing.JPanel(); - deviceField4 = new DeviceField(); - deviceField5 = new DeviceField(); - jPanel5 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceField7 = new DeviceField(); - jPanel6 = new javax.swing.JPanel(); - deviceField8 = new DeviceField(); - deviceField9 = new DeviceField(); - jPanel7 = new javax.swing.JPanel(); - deviceField10 = new DeviceField(); - deviceField11 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - deviceField12 = new DeviceField(); - deviceField13 = new DeviceField(); - jPanel9 = new javax.swing.JPanel(); - deviceField14 = new DeviceField(); - deviceField15 = new DeviceField(); - jPanel10 = new javax.swing.JPanel(); - deviceField16 = new DeviceField(); - deviceField17 = new DeviceField(); - jPanel11 = new javax.swing.JPanel(); - deviceField18 = new DeviceField(); - deviceField19 = new DeviceField(); - jPanel12 = new javax.swing.JPanel(); - deviceField20 = new DeviceField(); - deviceField21 = new DeviceField(); - jPanel13 = new javax.swing.JPanel(); - deviceField22 = new DeviceField(); - deviceField23 = new DeviceField(); - jPanel14 = new javax.swing.JPanel(); - deviceField24 = new DeviceField(); - deviceField25 = new DeviceField(); - jPanel15 = new javax.swing.JPanel(); - deviceField26 = new DeviceField(); - deviceField27 = new DeviceField(); - jPanel16 = new javax.swing.JPanel(); - deviceField28 = new DeviceField(); - deviceField29 = new DeviceField(); - jPanel17 = new javax.swing.JPanel(); - deviceField30 = new DeviceField(); - deviceField31 = new DeviceField(); - jPanel18 = new javax.swing.JPanel(); - deviceField32 = new DeviceField(); - deviceField33 = new DeviceField(); - jPanel19 = new javax.swing.JPanel(); - deviceField34 = new DeviceField(); - deviceField35 = new DeviceField(); - jPanel20 = new javax.swing.JPanel(); - deviceField36 = new DeviceField(); - deviceField37 = new DeviceField(); - jPanel21 = new javax.swing.JPanel(); - deviceField38 = new DeviceField(); - deviceField39 = new DeviceField(); - jPanel22 = new javax.swing.JPanel(); - deviceField40 = new DeviceField(); - deviceField41 = new DeviceField(); - jPanel23 = new javax.swing.JPanel(); - deviceField42 = new DeviceField(); - deviceField43 = new DeviceField(); - jPanel24 = new javax.swing.JPanel(); - deviceField44 = new DeviceField(); - deviceField45 = new DeviceField(); - jPanel25 = new javax.swing.JPanel(); - deviceField46 = new DeviceField(); - deviceField47 = new DeviceField(); - jPanel26 = new javax.swing.JPanel(); - deviceField48 = new DeviceField(); - deviceField49 = new DeviceField(); - jPanel27 = new javax.swing.JPanel(); - deviceField50 = new DeviceField(); - deviceField51 = new DeviceField(); - jPanel28 = new javax.swing.JPanel(); - deviceField52 = new DeviceField(); - deviceField53 = new DeviceField(); - jPanel29 = new javax.swing.JPanel(); - deviceField54 = new DeviceField(); - deviceField55 = new DeviceField(); - jPanel30 = new javax.swing.JPanel(); - deviceField56 = new DeviceField(); - deviceField57 = new DeviceField(); - jPanel31 = new javax.swing.JPanel(); - deviceField58 = new DeviceField(); - deviceField59 = new DeviceField(); - jPanel32 = new javax.swing.JPanel(); - deviceField60 = new DeviceField(); - deviceField61 = new DeviceField(); - jPanel33 = new javax.swing.JPanel(); - deviceField62 = new DeviceField(); - deviceField63 = new DeviceField(); - jPanel34 = new javax.swing.JPanel(); - deviceField64 = new DeviceField(); - deviceField65 = new DeviceField(); - jPanel35 = new javax.swing.JPanel(); - deviceField66 = new DeviceField(); - deviceField67 = new DeviceField(); - jPanel36 = new javax.swing.JPanel(); - deviceField68 = new DeviceField(); - deviceField69 = new DeviceField(); - jPanel37 = new javax.swing.JPanel(); - deviceField70 = new DeviceField(); - deviceField71 = new DeviceField(); - jPanel38 = new javax.swing.JPanel(); - deviceField72 = new DeviceField(); - deviceField73 = new DeviceField(); - jPanel39 = new javax.swing.JPanel(); - deviceField74 = new DeviceField(); - deviceField75 = new DeviceField(); - jPanel40 = new javax.swing.JPanel(); - deviceField76 = new DeviceField(); - deviceField77 = new DeviceField(); - jPanel41 = new javax.swing.JPanel(); - deviceField78 = new DeviceField(); - deviceField79 = new DeviceField(); - jPanel42 = new javax.swing.JPanel(); - deviceField80 = new DeviceField(); - deviceField81 = new DeviceField(); - jPanel43 = new javax.swing.JPanel(); - deviceField82 = new DeviceField(); - deviceField83 = new DeviceField(); - jPanel44 = new javax.swing.JPanel(); - deviceField84 = new DeviceField(); - deviceField85 = new DeviceField(); - jPanel45 = new javax.swing.JPanel(); - deviceField86 = new DeviceField(); - deviceField87 = new DeviceField(); - jPanel46 = new javax.swing.JPanel(); - deviceField88 = new DeviceField(); - deviceField89 = new DeviceField(); - jPanel47 = new javax.swing.JPanel(); - deviceField90 = new DeviceField(); - deviceField91 = new DeviceField(); - jPanel48 = new javax.swing.JPanel(); - deviceField92 = new DeviceField(); - deviceField93 = new DeviceField(); - jPanel49 = new javax.swing.JPanel(); - deviceField94 = new DeviceField(); - deviceField95 = new DeviceField(); - jPanel50 = new javax.swing.JPanel(); - deviceField96 = new DeviceField(); - deviceField97 = new DeviceField(); - jPanel51 = new javax.swing.JPanel(); - deviceField98 = new DeviceField(); - deviceField99 = new DeviceField(); - jPanel52 = new javax.swing.JPanel(); - deviceField100 = new DeviceField(); - deviceField101 = new DeviceField(); - jPanel53 = new javax.swing.JPanel(); - deviceField102 = new DeviceField(); - deviceField103 = new DeviceField(); - jPanel54 = new javax.swing.JPanel(); - deviceField104 = new DeviceField(); - deviceField105 = new DeviceField(); - jPanel55 = new javax.swing.JPanel(); - deviceField106 = new DeviceField(); - deviceField107 = new DeviceField(); - jPanel56 = new javax.swing.JPanel(); - deviceField108 = new DeviceField(); - deviceField109 = new DeviceField(); - jPanel57 = new javax.swing.JPanel(); - deviceField110 = new DeviceField(); - deviceField111 = new DeviceField(); - jPanel58 = new javax.swing.JPanel(); - deviceField112 = new DeviceField(); - deviceField113 = new DeviceField(); - jPanel59 = new javax.swing.JPanel(); - deviceField114 = new DeviceField(); - deviceField115 = new DeviceField(); - jPanel60 = new javax.swing.JPanel(); - deviceField116 = new DeviceField(); - deviceField117 = new DeviceField(); - jPanel61 = new javax.swing.JPanel(); - deviceField118 = new DeviceField(); - deviceField119 = new DeviceField(); - jPanel62 = new javax.swing.JPanel(); - deviceField120 = new DeviceField(); - deviceField121 = new DeviceField(); - jPanel63 = new javax.swing.JPanel(); - deviceField122 = new DeviceField(); - deviceField123 = new DeviceField(); - jPanel64 = new javax.swing.JPanel(); - deviceField124 = new DeviceField(); - deviceField125 = new DeviceField(); - jPanel65 = new javax.swing.JPanel(); - deviceField126 = new DeviceField(); - deviceField127 = new DeviceField(); - jPanel66 = new javax.swing.JPanel(); - deviceField128 = new DeviceField(); - deviceField129 = new DeviceField(); - jPanel67 = new javax.swing.JPanel(); - deviceField130 = new DeviceField(); - deviceField131 = new DeviceField(); - jPanel68 = new javax.swing.JPanel(); - deviceField132 = new DeviceField(); - deviceField133 = new DeviceField(); - jPanel69 = new javax.swing.JPanel(); - deviceField134 = new DeviceField(); - deviceField135 = new DeviceField(); - jPanel70 = new javax.swing.JPanel(); - deviceField136 = new DeviceField(); - deviceField137 = new DeviceField(); - jPanel71 = new javax.swing.JPanel(); - deviceField138 = new DeviceField(); - deviceField139 = new DeviceField(); - jPanel72 = new javax.swing.JPanel(); - deviceField140 = new DeviceField(); - deviceField141 = new DeviceField(); - jPanel73 = new javax.swing.JPanel(); - deviceField142 = new DeviceField(); - deviceField143 = new DeviceField(); - jPanel74 = new javax.swing.JPanel(); - deviceField144 = new DeviceField(); - deviceField145 = new DeviceField(); - jPanel75 = new javax.swing.JPanel(); - deviceField146 = new DeviceField(); - deviceField147 = new DeviceField(); - jPanel76 = new javax.swing.JPanel(); - deviceField148 = new DeviceField(); - deviceField149 = new DeviceField(); - jPanel77 = new javax.swing.JPanel(); - deviceField150 = new DeviceField(); - deviceField151 = new DeviceField(); - jPanel78 = new javax.swing.JPanel(); - deviceField152 = new DeviceField(); - deviceField153 = new DeviceField(); - jPanel79 = new javax.swing.JPanel(); - deviceField154 = new DeviceField(); - deviceField155 = new DeviceField(); - jPanel80 = new javax.swing.JPanel(); - deviceField156 = new DeviceField(); - deviceField157 = new DeviceField(); - jPanel81 = new javax.swing.JPanel(); - deviceField158 = new DeviceField(); - deviceField159 = new DeviceField(); - jPanel82 = new javax.swing.JPanel(); - deviceField160 = new DeviceField(); - deviceField161 = new DeviceField(); - jPanel83 = new javax.swing.JPanel(); - deviceField162 = new DeviceField(); - deviceField163 = new DeviceField(); - jPanel84 = new javax.swing.JPanel(); - deviceField164 = new DeviceField(); - deviceField165 = new DeviceField(); - jPanel85 = new javax.swing.JPanel(); - deviceField166 = new DeviceField(); - deviceField167 = new DeviceField(); - jPanel86 = new javax.swing.JPanel(); - deviceField168 = new DeviceField(); - deviceField169 = new DeviceField(); - jPanel87 = new javax.swing.JPanel(); - deviceField170 = new DeviceField(); - deviceField171 = new DeviceField(); - jPanel88 = new javax.swing.JPanel(); - deviceField172 = new DeviceField(); - deviceField173 = new DeviceField(); - jPanel89 = new javax.swing.JPanel(); - deviceField174 = new DeviceField(); - deviceField175 = new DeviceField(); - jPanel90 = new javax.swing.JPanel(); - deviceField176 = new DeviceField(); - deviceField177 = new DeviceField(); - jPanel91 = new javax.swing.JPanel(); - deviceField178 = new DeviceField(); - deviceField179 = new DeviceField(); - jPanel92 = new javax.swing.JPanel(); - deviceField180 = new DeviceField(); - deviceField181 = new DeviceField(); - jPanel93 = new javax.swing.JPanel(); - deviceField182 = new DeviceField(); - deviceField183 = new DeviceField(); - jPanel94 = new javax.swing.JPanel(); - deviceField184 = new DeviceField(); - deviceField185 = new DeviceField(); - jPanel95 = new javax.swing.JPanel(); - deviceField186 = new DeviceField(); - deviceField187 = new DeviceField(); - jPanel96 = new javax.swing.JPanel(); - deviceField188 = new DeviceField(); - deviceField189 = new DeviceField(); - jPanel97 = new javax.swing.JPanel(); - deviceField190 = new DeviceField(); - deviceField191 = new DeviceField(); - jPanel98 = new javax.swing.JPanel(); - deviceField192 = new DeviceField(); - deviceField193 = new DeviceField(); - jPanel99 = new javax.swing.JPanel(); - deviceField194 = new DeviceField(); - deviceField195 = new DeviceField(); - jPanel100 = new javax.swing.JPanel(); - deviceField196 = new DeviceField(); - deviceField197 = new DeviceField(); - jPanel101 = new javax.swing.JPanel(); - deviceField198 = new DeviceField(); - deviceField199 = new DeviceField(); - jPanel102 = new javax.swing.JPanel(); - deviceField200 = new DeviceField(); - deviceField201 = new DeviceField(); - jPanel103 = new javax.swing.JPanel(); - deviceField202 = new DeviceField(); - deviceField203 = new DeviceField(); - jPanel104 = new javax.swing.JPanel(); - deviceField204 = new DeviceField(); - deviceField205 = new DeviceField(); - jPanel105 = new javax.swing.JPanel(); - deviceField206 = new DeviceField(); - deviceField207 = new DeviceField(); - jPanel106 = new javax.swing.JPanel(); - deviceField208 = new DeviceField(); - deviceField209 = new DeviceField(); - jPanel107 = new javax.swing.JPanel(); - deviceField210 = new DeviceField(); - deviceField211 = new DeviceField(); - jPanel108 = new javax.swing.JPanel(); - deviceField212 = new DeviceField(); - deviceField213 = new DeviceField(); - jPanel109 = new javax.swing.JPanel(); - deviceField214 = new DeviceField(); - deviceField215 = new DeviceField(); - jPanel110 = new javax.swing.JPanel(); - deviceField216 = new DeviceField(); - deviceField217 = new DeviceField(); - jPanel111 = new javax.swing.JPanel(); - deviceField218 = new DeviceField(); - deviceField219 = new DeviceField(); - jPanel112 = new javax.swing.JPanel(); - deviceField220 = new DeviceField(); - deviceField221 = new DeviceField(); - jPanel113 = new javax.swing.JPanel(); - deviceField222 = new DeviceField(); - deviceField223 = new DeviceField(); - jPanel114 = new javax.swing.JPanel(); - deviceField224 = new DeviceField(); - deviceField225 = new DeviceField(); - jPanel115 = new javax.swing.JPanel(); - deviceField226 = new DeviceField(); - deviceField227 = new DeviceField(); - jPanel116 = new javax.swing.JPanel(); - deviceField228 = new DeviceField(); - deviceField229 = new DeviceField(); - jPanel117 = new javax.swing.JPanel(); - deviceField230 = new DeviceField(); - deviceField231 = new DeviceField(); - jPanel118 = new javax.swing.JPanel(); - deviceField232 = new DeviceField(); - deviceField233 = new DeviceField(); - jPanel119 = new javax.swing.JPanel(); - deviceField234 = new DeviceField(); - deviceField235 = new DeviceField(); - jPanel120 = new javax.swing.JPanel(); - deviceField236 = new DeviceField(); - deviceField237 = new DeviceField(); - jPanel121 = new javax.swing.JPanel(); - deviceField238 = new DeviceField(); - deviceField239 = new DeviceField(); - jPanel122 = new javax.swing.JPanel(); - deviceField240 = new DeviceField(); - deviceField241 = new DeviceField(); - jPanel123 = new javax.swing.JPanel(); - deviceField242 = new DeviceField(); - deviceField243 = new DeviceField(); - jPanel124 = new javax.swing.JPanel(); - deviceField244 = new DeviceField(); - deviceField245 = new DeviceField(); - jPanel125 = new javax.swing.JPanel(); - deviceField246 = new DeviceField(); - deviceField247 = new DeviceField(); - jPanel126 = new javax.swing.JPanel(); - deviceField248 = new DeviceField(); - deviceField249 = new DeviceField(); - jPanel127 = new javax.swing.JPanel(); - deviceField250 = new DeviceField(); - deviceField251 = new DeviceField(); - jPanel128 = new javax.swing.JPanel(); - deviceField252 = new DeviceField(); - deviceField253 = new DeviceField(); - jPanel129 = new javax.swing.JPanel(); - deviceField254 = new DeviceField(); - deviceField255 = new DeviceField(); - jPanel130 = new javax.swing.JPanel(); - deviceField256 = new DeviceField(); - deviceField257 = new DeviceField(); - jPanel131 = new javax.swing.JPanel(); - deviceField258 = new DeviceField(); - deviceField259 = new DeviceField(); - jPanel132 = new javax.swing.JPanel(); - deviceField260 = new DeviceField(); - deviceField261 = new DeviceField(); - jPanel133 = new javax.swing.JPanel(); - deviceField262 = new DeviceField(); - deviceField263 = new DeviceField(); - jPanel134 = new javax.swing.JPanel(); - deviceField264 = new DeviceField(); - deviceField265 = new DeviceField(); - jPanel135 = new javax.swing.JPanel(); - deviceField266 = new DeviceField(); - deviceField267 = new DeviceField(); - jPanel136 = new javax.swing.JPanel(); - deviceField268 = new DeviceField(); - deviceField269 = new DeviceField(); - jPanel137 = new javax.swing.JPanel(); - deviceField270 = new DeviceField(); - deviceField271 = new DeviceField(); - jPanel138 = new javax.swing.JPanel(); - deviceField272 = new DeviceField(); - deviceField273 = new DeviceField(); - jPanel139 = new javax.swing.JPanel(); - deviceField274 = new DeviceField(); - deviceField275 = new DeviceField(); - jPanel140 = new javax.swing.JPanel(); - deviceField276 = new DeviceField(); - deviceField277 = new DeviceField(); - jPanel141 = new javax.swing.JPanel(); - deviceField278 = new DeviceField(); - deviceField279 = new DeviceField(); - jPanel142 = new javax.swing.JPanel(); - deviceField280 = new DeviceField(); - deviceField281 = new DeviceField(); - jPanel143 = new javax.swing.JPanel(); - deviceField282 = new DeviceField(); - deviceField283 = new DeviceField(); - jPanel144 = new javax.swing.JPanel(); - deviceField284 = new DeviceField(); - deviceField285 = new DeviceField(); - jPanel145 = new javax.swing.JPanel(); - deviceField286 = new DeviceField(); - deviceField287 = new DeviceField(); - jPanel146 = new javax.swing.JPanel(); - deviceField288 = new DeviceField(); - deviceField289 = new DeviceField(); - jScrollPane2 = new javax.swing.JScrollPane(); - jPanel147 = new javax.swing.JPanel(); - jPanel148 = new javax.swing.JPanel(); - jPanel149 = new javax.swing.JPanel(); - deviceLabel1 = new DeviceLabel(); - deviceField290 = new DeviceField(); - jPanel150 = new javax.swing.JPanel(); - deviceField291 = new DeviceField(); - deviceField292 = new DeviceField(); - jPanel151 = new javax.swing.JPanel(); - jPanel152 = new javax.swing.JPanel(); - deviceLabel2 = new DeviceLabel(); - deviceField293 = new DeviceField(); - jPanel153 = new javax.swing.JPanel(); - deviceField294 = new DeviceField(); - deviceField295 = new DeviceField(); - jPanel154 = new javax.swing.JPanel(); - jPanel155 = new javax.swing.JPanel(); - deviceLabel3 = new DeviceLabel(); - deviceField296 = new DeviceField(); - jPanel156 = new javax.swing.JPanel(); - deviceField297 = new DeviceField(); - deviceField298 = new DeviceField(); - jPanel157 = new javax.swing.JPanel(); - jPanel158 = new javax.swing.JPanel(); - deviceLabel4 = new DeviceLabel(); - deviceField299 = new DeviceField(); - jPanel159 = new javax.swing.JPanel(); - deviceField300 = new DeviceField(); - deviceField301 = new DeviceField(); - jPanel160 = new javax.swing.JPanel(); - jPanel161 = new javax.swing.JPanel(); - deviceLabel5 = new DeviceLabel(); - deviceField302 = new DeviceField(); - jPanel162 = new javax.swing.JPanel(); - deviceField303 = new DeviceField(); - deviceField304 = new DeviceField(); - jPanel163 = new javax.swing.JPanel(); - jPanel164 = new javax.swing.JPanel(); - deviceLabel6 = new DeviceLabel(); - deviceField305 = new DeviceField(); - jPanel165 = new javax.swing.JPanel(); - deviceField306 = new DeviceField(); - deviceField307 = new DeviceField(); - jPanel166 = new javax.swing.JPanel(); - jPanel167 = new javax.swing.JPanel(); - deviceLabel7 = new DeviceLabel(); - deviceField308 = new DeviceField(); - jPanel168 = new javax.swing.JPanel(); - deviceField309 = new DeviceField(); - deviceField310 = new DeviceField(); - jPanel169 = new javax.swing.JPanel(); - jPanel170 = new javax.swing.JPanel(); - deviceLabel8 = new DeviceLabel(); - deviceField311 = new DeviceField(); - jPanel171 = new javax.swing.JPanel(); - deviceField312 = new DeviceField(); - deviceField313 = new DeviceField(); - jPanel172 = new javax.swing.JPanel(); - jPanel173 = new javax.swing.JPanel(); - deviceLabel9 = new DeviceLabel(); - deviceField314 = new DeviceField(); - jPanel174 = new javax.swing.JPanel(); - deviceField315 = new DeviceField(); - deviceField316 = new DeviceField(); - jPanel175 = new javax.swing.JPanel(); - jPanel176 = new javax.swing.JPanel(); - deviceLabel10 = new DeviceLabel(); - deviceField317 = new DeviceField(); - jPanel177 = new javax.swing.JPanel(); - deviceField318 = new DeviceField(); - deviceField319 = new DeviceField(); - jPanel178 = new javax.swing.JPanel(); - jPanel179 = new javax.swing.JPanel(); - deviceLabel11 = new DeviceLabel(); - deviceField320 = new DeviceField(); - jPanel180 = new javax.swing.JPanel(); - deviceField321 = new DeviceField(); - deviceField322 = new DeviceField(); - jPanel181 = new javax.swing.JPanel(); - jPanel182 = new javax.swing.JPanel(); - deviceLabel12 = new DeviceLabel(); - deviceField323 = new DeviceField(); - jPanel183 = new javax.swing.JPanel(); - deviceField324 = new DeviceField(); - deviceField325 = new DeviceField(); - jPanel184 = new javax.swing.JPanel(); - jPanel185 = new javax.swing.JPanel(); - deviceLabel13 = new DeviceLabel(); - deviceField326 = new DeviceField(); - jPanel186 = new javax.swing.JPanel(); - deviceField327 = new DeviceField(); - deviceField328 = new DeviceField(); - jPanel187 = new javax.swing.JPanel(); - jPanel188 = new javax.swing.JPanel(); - deviceLabel14 = new DeviceLabel(); - deviceField329 = new DeviceField(); - jPanel189 = new javax.swing.JPanel(); - deviceField330 = new DeviceField(); - deviceField331 = new DeviceField(); - jPanel190 = new javax.swing.JPanel(); - jPanel191 = new javax.swing.JPanel(); - deviceLabel15 = new DeviceLabel(); - deviceField332 = new DeviceField(); - jPanel192 = new javax.swing.JPanel(); - deviceField333 = new DeviceField(); - deviceField334 = new DeviceField(); - jPanel193 = new javax.swing.JPanel(); - jPanel194 = new javax.swing.JPanel(); - deviceLabel16 = new DeviceLabel(); - deviceField335 = new DeviceField(); - jPanel195 = new javax.swing.JPanel(); - deviceField336 = new DeviceField(); - deviceField337 = new DeviceField(); - jPanel196 = new javax.swing.JPanel(); - jPanel197 = new javax.swing.JPanel(); - deviceLabel17 = new DeviceLabel(); - deviceField338 = new DeviceField(); - jPanel198 = new javax.swing.JPanel(); - deviceField339 = new DeviceField(); - deviceField340 = new DeviceField(); - jPanel199 = new javax.swing.JPanel(); - jPanel200 = new javax.swing.JPanel(); - deviceLabel18 = new DeviceLabel(); - deviceField341 = new DeviceField(); - jPanel201 = new javax.swing.JPanel(); - deviceField342 = new DeviceField(); - deviceField343 = new DeviceField(); - jPanel202 = new javax.swing.JPanel(); - jPanel203 = new javax.swing.JPanel(); - deviceLabel19 = new DeviceLabel(); - deviceField344 = new DeviceField(); - jPanel204 = new javax.swing.JPanel(); - deviceField345 = new DeviceField(); - deviceField346 = new DeviceField(); - jPanel205 = new javax.swing.JPanel(); - jPanel206 = new javax.swing.JPanel(); - deviceLabel20 = new DeviceLabel(); - deviceField347 = new DeviceField(); - jPanel207 = new javax.swing.JPanel(); - deviceField348 = new DeviceField(); - deviceField349 = new DeviceField(); - jPanel208 = new javax.swing.JPanel(); - jPanel209 = new javax.swing.JPanel(); - deviceLabel21 = new DeviceLabel(); - deviceField350 = new DeviceField(); - jPanel210 = new javax.swing.JPanel(); - deviceField351 = new DeviceField(); - deviceField352 = new DeviceField(); - jPanel211 = new javax.swing.JPanel(); - jPanel212 = new javax.swing.JPanel(); - deviceLabel22 = new DeviceLabel(); - deviceField353 = new DeviceField(); - jPanel213 = new javax.swing.JPanel(); - deviceField354 = new DeviceField(); - deviceField355 = new DeviceField(); - jPanel214 = new javax.swing.JPanel(); - jPanel215 = new javax.swing.JPanel(); - deviceLabel23 = new DeviceLabel(); - deviceField356 = new DeviceField(); - jPanel216 = new javax.swing.JPanel(); - deviceField357 = new DeviceField(); - deviceField358 = new DeviceField(); - jPanel217 = new javax.swing.JPanel(); - jPanel218 = new javax.swing.JPanel(); - deviceLabel24 = new DeviceLabel(); - deviceField359 = new DeviceField(); - jPanel219 = new javax.swing.JPanel(); - deviceField360 = new DeviceField(); - deviceField361 = new DeviceField(); - jPanel220 = new javax.swing.JPanel(); - jPanel221 = new javax.swing.JPanel(); - deviceLabel25 = new DeviceLabel(); - deviceField362 = new DeviceField(); - jPanel222 = new javax.swing.JPanel(); - deviceField363 = new DeviceField(); - deviceField364 = new DeviceField(); - jPanel223 = new javax.swing.JPanel(); - jPanel224 = new javax.swing.JPanel(); - deviceLabel26 = new DeviceLabel(); - deviceField365 = new DeviceField(); - jPanel225 = new javax.swing.JPanel(); - deviceField366 = new DeviceField(); - deviceField367 = new DeviceField(); - jPanel226 = new javax.swing.JPanel(); - jPanel227 = new javax.swing.JPanel(); - deviceLabel27 = new DeviceLabel(); - deviceField368 = new DeviceField(); - jPanel228 = new javax.swing.JPanel(); - deviceField369 = new DeviceField(); - deviceField370 = new DeviceField(); - jPanel229 = new javax.swing.JPanel(); - jPanel230 = new javax.swing.JPanel(); - deviceLabel28 = new DeviceLabel(); - deviceField371 = new DeviceField(); - jPanel231 = new javax.swing.JPanel(); - deviceField372 = new DeviceField(); - deviceField373 = new DeviceField(); - jPanel232 = new javax.swing.JPanel(); - jPanel233 = new javax.swing.JPanel(); - deviceLabel29 = new DeviceLabel(); - deviceField374 = new DeviceField(); - jPanel234 = new javax.swing.JPanel(); - deviceField375 = new DeviceField(); - deviceField376 = new DeviceField(); - jPanel235 = new javax.swing.JPanel(); - jPanel236 = new javax.swing.JPanel(); - deviceLabel30 = new DeviceLabel(); - deviceField377 = new DeviceField(); - jPanel237 = new javax.swing.JPanel(); - deviceField378 = new DeviceField(); - deviceField379 = new DeviceField(); - jPanel238 = new javax.swing.JPanel(); - jPanel239 = new javax.swing.JPanel(); - deviceLabel31 = new DeviceLabel(); - deviceField380 = new DeviceField(); - jPanel240 = new javax.swing.JPanel(); - deviceField381 = new DeviceField(); - deviceField382 = new DeviceField(); - jPanel241 = new javax.swing.JPanel(); - jPanel242 = new javax.swing.JPanel(); - deviceLabel32 = new DeviceLabel(); - deviceField383 = new DeviceField(); - jPanel243 = new javax.swing.JPanel(); - deviceField384 = new DeviceField(); - deviceField385 = new DeviceField(); - jPanel244 = new javax.swing.JPanel(); - jPanel245 = new javax.swing.JPanel(); - deviceLabel33 = new DeviceLabel(); - deviceField386 = new DeviceField(); - jPanel246 = new javax.swing.JPanel(); - deviceField387 = new DeviceField(); - deviceField388 = new DeviceField(); - jPanel247 = new javax.swing.JPanel(); - jPanel248 = new javax.swing.JPanel(); - deviceLabel34 = new DeviceLabel(); - deviceField389 = new DeviceField(); - jPanel249 = new javax.swing.JPanel(); - deviceField390 = new DeviceField(); - deviceField391 = new DeviceField(); - jPanel250 = new javax.swing.JPanel(); - jPanel251 = new javax.swing.JPanel(); - deviceLabel35 = new DeviceLabel(); - deviceField392 = new DeviceField(); - jPanel252 = new javax.swing.JPanel(); - deviceField393 = new DeviceField(); - deviceField394 = new DeviceField(); - jPanel253 = new javax.swing.JPanel(); - jPanel254 = new javax.swing.JPanel(); - deviceLabel36 = new DeviceLabel(); - deviceField395 = new DeviceField(); - jPanel255 = new javax.swing.JPanel(); - deviceField396 = new DeviceField(); - deviceField397 = new DeviceField(); - jPanel256 = new javax.swing.JPanel(); - jPanel257 = new javax.swing.JPanel(); - deviceLabel37 = new DeviceLabel(); - deviceField398 = new DeviceField(); - jPanel258 = new javax.swing.JPanel(); - deviceField399 = new DeviceField(); - deviceField400 = new DeviceField(); - jPanel259 = new javax.swing.JPanel(); - jPanel260 = new javax.swing.JPanel(); - deviceLabel38 = new DeviceLabel(); - deviceField401 = new DeviceField(); - jPanel261 = new javax.swing.JPanel(); - deviceField402 = new DeviceField(); - deviceField403 = new DeviceField(); - jPanel262 = new javax.swing.JPanel(); - jPanel263 = new javax.swing.JPanel(); - deviceLabel39 = new DeviceLabel(); - deviceField404 = new DeviceField(); - jPanel264 = new javax.swing.JPanel(); - deviceField405 = new DeviceField(); - deviceField406 = new DeviceField(); - jPanel265 = new javax.swing.JPanel(); - jPanel266 = new javax.swing.JPanel(); - deviceLabel40 = new DeviceLabel(); - deviceField407 = new DeviceField(); - jPanel267 = new javax.swing.JPanel(); - deviceField408 = new DeviceField(); - deviceField409 = new DeviceField(); + deviceInputs1 = new DeviceInputs(); + deviceOutputs1 = new DeviceOutputs(); + deviceParameters1 = new DeviceParameters(); setDeviceProvider("spilds:8100"); setDeviceTitle("MARTe2 RAPTOR"); @@ -763,3497 +50,16 @@ private void initComponents() { getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - jPanel1.setLayout(new java.awt.GridLayout(145, 1)); + deviceInputs1.setOffsetNid(449); + jTabbedPane1.addTab("Inputs", deviceInputs1); - deviceField2.setEditable(false); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("Name: "); - deviceField2.setNumCols(15); - deviceField2.setOffsetNid(18); - deviceField2.setTextOnly(true); - jPanel3.add(deviceField2); + deviceOutputs1.setOffsetNid(1250); + jTabbedPane1.addTab("Outputs", deviceOutputs1); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Value: "); - deviceField3.setOffsetNid(19); - jPanel3.add(deviceField3); - - jPanel1.add(jPanel3); - - deviceField4.setEditable(false); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Name: "); - deviceField4.setNumCols(15); - deviceField4.setOffsetNid(21); - deviceField4.setTextOnly(true); - jPanel4.add(deviceField4); - - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Value: "); - deviceField5.setOffsetNid(22); - jPanel4.add(deviceField5); - - jPanel1.add(jPanel4); - - deviceField6.setEditable(false); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Name: "); - deviceField6.setNumCols(15); - deviceField6.setOffsetNid(24); - deviceField6.setTextOnly(true); - jPanel5.add(deviceField6); - - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Value: "); - deviceField7.setOffsetNid(25); - jPanel5.add(deviceField7); - - jPanel1.add(jPanel5); - - deviceField8.setEditable(false); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Name: "); - deviceField8.setNumCols(15); - deviceField8.setOffsetNid(27); - deviceField8.setTextOnly(true); - jPanel6.add(deviceField8); - - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Value: "); - deviceField9.setOffsetNid(28); - jPanel6.add(deviceField9); - - jPanel1.add(jPanel6); - - deviceField10.setEditable(false); - deviceField10.setIdentifier(""); - deviceField10.setLabelString("Name: "); - deviceField10.setNumCols(15); - deviceField10.setOffsetNid(30); - deviceField10.setTextOnly(true); - jPanel7.add(deviceField10); - - deviceField11.setIdentifier(""); - deviceField11.setLabelString("Value: "); - deviceField11.setOffsetNid(31); - jPanel7.add(deviceField11); - - jPanel1.add(jPanel7); - - deviceField12.setEditable(false); - deviceField12.setIdentifier(""); - deviceField12.setLabelString("Name: "); - deviceField12.setNumCols(15); - deviceField12.setOffsetNid(33); - deviceField12.setTextOnly(true); - jPanel8.add(deviceField12); - - deviceField13.setIdentifier(""); - deviceField13.setLabelString("Value: "); - deviceField13.setOffsetNid(34); - jPanel8.add(deviceField13); - - jPanel1.add(jPanel8); - - deviceField14.setEditable(false); - deviceField14.setIdentifier(""); - deviceField14.setLabelString("Name: "); - deviceField14.setNumCols(15); - deviceField14.setOffsetNid(36); - deviceField14.setTextOnly(true); - jPanel9.add(deviceField14); - - deviceField15.setIdentifier(""); - deviceField15.setLabelString("Value: "); - deviceField15.setOffsetNid(37); - jPanel9.add(deviceField15); - - jPanel1.add(jPanel9); - - deviceField16.setEditable(false); - deviceField16.setIdentifier(""); - deviceField16.setLabelString("Name: "); - deviceField16.setNumCols(15); - deviceField16.setOffsetNid(39); - deviceField16.setTextOnly(true); - jPanel10.add(deviceField16); - - deviceField17.setIdentifier(""); - deviceField17.setLabelString("Value: "); - deviceField17.setOffsetNid(40); - jPanel10.add(deviceField17); - - jPanel1.add(jPanel10); - - deviceField18.setEditable(false); - deviceField18.setIdentifier(""); - deviceField18.setLabelString("Name: "); - deviceField18.setNumCols(15); - deviceField18.setOffsetNid(42); - deviceField18.setTextOnly(true); - jPanel11.add(deviceField18); - - deviceField19.setIdentifier(""); - deviceField19.setLabelString("Value: "); - deviceField19.setOffsetNid(43); - jPanel11.add(deviceField19); - - jPanel1.add(jPanel11); - - deviceField20.setEditable(false); - deviceField20.setIdentifier(""); - deviceField20.setLabelString("Name: "); - deviceField20.setNumCols(15); - deviceField20.setOffsetNid(45); - deviceField20.setTextOnly(true); - jPanel12.add(deviceField20); - - deviceField21.setIdentifier(""); - deviceField21.setLabelString("Value: "); - deviceField21.setOffsetNid(46); - jPanel12.add(deviceField21); - - jPanel1.add(jPanel12); - - deviceField22.setEditable(false); - deviceField22.setIdentifier(""); - deviceField22.setLabelString("Name: "); - deviceField22.setNumCols(15); - deviceField22.setOffsetNid(48); - deviceField22.setTextOnly(true); - jPanel13.add(deviceField22); - - deviceField23.setIdentifier(""); - deviceField23.setLabelString("Value: "); - deviceField23.setOffsetNid(49); - jPanel13.add(deviceField23); - - jPanel1.add(jPanel13); - - deviceField24.setEditable(false); - deviceField24.setIdentifier(""); - deviceField24.setLabelString("Name: "); - deviceField24.setNumCols(15); - deviceField24.setOffsetNid(51); - deviceField24.setTextOnly(true); - jPanel14.add(deviceField24); - - deviceField25.setIdentifier(""); - deviceField25.setLabelString("Value: "); - deviceField25.setOffsetNid(52); - jPanel14.add(deviceField25); - - jPanel1.add(jPanel14); - - deviceField26.setEditable(false); - deviceField26.setIdentifier(""); - deviceField26.setLabelString("Name: "); - deviceField26.setNumCols(15); - deviceField26.setOffsetNid(54); - deviceField26.setTextOnly(true); - jPanel15.add(deviceField26); - - deviceField27.setIdentifier(""); - deviceField27.setLabelString("Value: "); - deviceField27.setOffsetNid(55); - jPanel15.add(deviceField27); - - jPanel1.add(jPanel15); - - deviceField28.setEditable(false); - deviceField28.setIdentifier(""); - deviceField28.setLabelString("Name: "); - deviceField28.setNumCols(15); - deviceField28.setOffsetNid(57); - deviceField28.setTextOnly(true); - jPanel16.add(deviceField28); - - deviceField29.setIdentifier(""); - deviceField29.setLabelString("Value: "); - deviceField29.setOffsetNid(58); - jPanel16.add(deviceField29); - - jPanel1.add(jPanel16); - - deviceField30.setEditable(false); - deviceField30.setIdentifier(""); - deviceField30.setLabelString("Name: "); - deviceField30.setNumCols(15); - deviceField30.setOffsetNid(60); - deviceField30.setTextOnly(true); - jPanel17.add(deviceField30); - - deviceField31.setIdentifier(""); - deviceField31.setLabelString("Value: "); - deviceField31.setOffsetNid(61); - jPanel17.add(deviceField31); - - jPanel1.add(jPanel17); - - deviceField32.setEditable(false); - deviceField32.setIdentifier(""); - deviceField32.setLabelString("Name: "); - deviceField32.setNumCols(15); - deviceField32.setOffsetNid(63); - deviceField32.setTextOnly(true); - jPanel18.add(deviceField32); - - deviceField33.setIdentifier(""); - deviceField33.setLabelString("Value: "); - deviceField33.setOffsetNid(64); - jPanel18.add(deviceField33); - - jPanel1.add(jPanel18); - - deviceField34.setEditable(false); - deviceField34.setIdentifier(""); - deviceField34.setLabelString("Name: "); - deviceField34.setNumCols(15); - deviceField34.setOffsetNid(66); - deviceField34.setTextOnly(true); - jPanel19.add(deviceField34); - - deviceField35.setIdentifier(""); - deviceField35.setLabelString("Value: "); - deviceField35.setOffsetNid(67); - jPanel19.add(deviceField35); - - jPanel1.add(jPanel19); - - deviceField36.setEditable(false); - deviceField36.setIdentifier(""); - deviceField36.setLabelString("Name: "); - deviceField36.setNumCols(15); - deviceField36.setOffsetNid(69); - deviceField36.setTextOnly(true); - jPanel20.add(deviceField36); - - deviceField37.setIdentifier(""); - deviceField37.setLabelString("Value: "); - deviceField37.setOffsetNid(70); - jPanel20.add(deviceField37); - - jPanel1.add(jPanel20); - - deviceField38.setEditable(false); - deviceField38.setIdentifier(""); - deviceField38.setLabelString("Name: "); - deviceField38.setNumCols(15); - deviceField38.setOffsetNid(72); - deviceField38.setTextOnly(true); - jPanel21.add(deviceField38); - - deviceField39.setIdentifier(""); - deviceField39.setLabelString("Value: "); - deviceField39.setOffsetNid(73); - jPanel21.add(deviceField39); - - jPanel1.add(jPanel21); - - deviceField40.setEditable(false); - deviceField40.setIdentifier(""); - deviceField40.setLabelString("Name: "); - deviceField40.setNumCols(15); - deviceField40.setOffsetNid(75); - deviceField40.setTextOnly(true); - jPanel22.add(deviceField40); - - deviceField41.setIdentifier(""); - deviceField41.setLabelString("Value: "); - deviceField41.setOffsetNid(76); - jPanel22.add(deviceField41); - - jPanel1.add(jPanel22); - - deviceField42.setEditable(false); - deviceField42.setIdentifier(""); - deviceField42.setLabelString("Name: "); - deviceField42.setNumCols(15); - deviceField42.setOffsetNid(78); - deviceField42.setTextOnly(true); - jPanel23.add(deviceField42); - - deviceField43.setIdentifier(""); - deviceField43.setLabelString("Value: "); - deviceField43.setOffsetNid(79); - jPanel23.add(deviceField43); - - jPanel1.add(jPanel23); - - deviceField44.setEditable(false); - deviceField44.setIdentifier(""); - deviceField44.setLabelString("Name: "); - deviceField44.setNumCols(15); - deviceField44.setOffsetNid(81); - deviceField44.setTextOnly(true); - jPanel24.add(deviceField44); - - deviceField45.setIdentifier(""); - deviceField45.setLabelString("Value: "); - deviceField45.setOffsetNid(82); - jPanel24.add(deviceField45); - - jPanel1.add(jPanel24); - - deviceField46.setEditable(false); - deviceField46.setIdentifier(""); - deviceField46.setLabelString("Name: "); - deviceField46.setNumCols(15); - deviceField46.setOffsetNid(84); - deviceField46.setTextOnly(true); - jPanel25.add(deviceField46); - - deviceField47.setIdentifier(""); - deviceField47.setLabelString("Value: "); - deviceField47.setOffsetNid(85); - jPanel25.add(deviceField47); - - jPanel1.add(jPanel25); - - deviceField48.setEditable(false); - deviceField48.setIdentifier(""); - deviceField48.setLabelString("Name: "); - deviceField48.setNumCols(15); - deviceField48.setOffsetNid(87); - deviceField48.setTextOnly(true); - jPanel26.add(deviceField48); - - deviceField49.setIdentifier(""); - deviceField49.setLabelString("Value: "); - deviceField49.setOffsetNid(88); - jPanel26.add(deviceField49); - - jPanel1.add(jPanel26); - - deviceField50.setEditable(false); - deviceField50.setIdentifier(""); - deviceField50.setLabelString("Name: "); - deviceField50.setNumCols(15); - deviceField50.setOffsetNid(90); - deviceField50.setTextOnly(true); - jPanel27.add(deviceField50); - - deviceField51.setIdentifier(""); - deviceField51.setLabelString("Value: "); - deviceField51.setOffsetNid(91); - jPanel27.add(deviceField51); - - jPanel1.add(jPanel27); - - deviceField52.setEditable(false); - deviceField52.setIdentifier(""); - deviceField52.setLabelString("Name: "); - deviceField52.setNumCols(15); - deviceField52.setOffsetNid(93); - deviceField52.setTextOnly(true); - jPanel28.add(deviceField52); - - deviceField53.setIdentifier(""); - deviceField53.setLabelString("Value: "); - deviceField53.setOffsetNid(94); - jPanel28.add(deviceField53); - - jPanel1.add(jPanel28); - - deviceField54.setEditable(false); - deviceField54.setIdentifier(""); - deviceField54.setLabelString("Name: "); - deviceField54.setNumCols(15); - deviceField54.setOffsetNid(96); - deviceField54.setTextOnly(true); - jPanel29.add(deviceField54); - - deviceField55.setIdentifier(""); - deviceField55.setLabelString("Value: "); - deviceField55.setOffsetNid(97); - jPanel29.add(deviceField55); - - jPanel1.add(jPanel29); - - deviceField56.setEditable(false); - deviceField56.setIdentifier(""); - deviceField56.setLabelString("Name: "); - deviceField56.setNumCols(15); - deviceField56.setOffsetNid(99); - deviceField56.setTextOnly(true); - jPanel30.add(deviceField56); - - deviceField57.setIdentifier(""); - deviceField57.setLabelString("Value: "); - deviceField57.setOffsetNid(100); - jPanel30.add(deviceField57); - - jPanel1.add(jPanel30); - - deviceField58.setEditable(false); - deviceField58.setIdentifier(""); - deviceField58.setLabelString("Name: "); - deviceField58.setNumCols(15); - deviceField58.setOffsetNid(102); - deviceField58.setTextOnly(true); - jPanel31.add(deviceField58); - - deviceField59.setIdentifier(""); - deviceField59.setLabelString("Value: "); - deviceField59.setOffsetNid(103); - jPanel31.add(deviceField59); - - jPanel1.add(jPanel31); - - deviceField60.setEditable(false); - deviceField60.setIdentifier(""); - deviceField60.setLabelString("Name: "); - deviceField60.setNumCols(15); - deviceField60.setOffsetNid(105); - deviceField60.setTextOnly(true); - jPanel32.add(deviceField60); - - deviceField61.setIdentifier(""); - deviceField61.setLabelString("Value: "); - deviceField61.setOffsetNid(106); - jPanel32.add(deviceField61); - - jPanel1.add(jPanel32); - - deviceField62.setEditable(false); - deviceField62.setIdentifier(""); - deviceField62.setLabelString("Name: "); - deviceField62.setNumCols(15); - deviceField62.setOffsetNid(108); - deviceField62.setTextOnly(true); - jPanel33.add(deviceField62); - - deviceField63.setIdentifier(""); - deviceField63.setLabelString("Value: "); - deviceField63.setOffsetNid(109); - jPanel33.add(deviceField63); - - jPanel1.add(jPanel33); - - deviceField64.setEditable(false); - deviceField64.setIdentifier(""); - deviceField64.setLabelString("Name: "); - deviceField64.setNumCols(15); - deviceField64.setOffsetNid(111); - deviceField64.setTextOnly(true); - jPanel34.add(deviceField64); - - deviceField65.setIdentifier(""); - deviceField65.setLabelString("Value: "); - deviceField65.setOffsetNid(112); - jPanel34.add(deviceField65); - - jPanel1.add(jPanel34); - - deviceField66.setEditable(false); - deviceField66.setIdentifier(""); - deviceField66.setLabelString("Name: "); - deviceField66.setNumCols(15); - deviceField66.setOffsetNid(114); - deviceField66.setTextOnly(true); - jPanel35.add(deviceField66); - - deviceField67.setIdentifier(""); - deviceField67.setLabelString("Value: "); - deviceField67.setOffsetNid(115); - jPanel35.add(deviceField67); - - jPanel1.add(jPanel35); - - deviceField68.setEditable(false); - deviceField68.setIdentifier(""); - deviceField68.setLabelString("Name: "); - deviceField68.setNumCols(15); - deviceField68.setOffsetNid(117); - deviceField68.setTextOnly(true); - jPanel36.add(deviceField68); - - deviceField69.setIdentifier(""); - deviceField69.setLabelString("Value: "); - deviceField69.setOffsetNid(118); - jPanel36.add(deviceField69); - - jPanel1.add(jPanel36); - - deviceField70.setEditable(false); - deviceField70.setIdentifier(""); - deviceField70.setLabelString("Name: "); - deviceField70.setNumCols(15); - deviceField70.setOffsetNid(120); - deviceField70.setTextOnly(true); - jPanel37.add(deviceField70); - - deviceField71.setIdentifier(""); - deviceField71.setLabelString("Value: "); - deviceField71.setOffsetNid(121); - jPanel37.add(deviceField71); - - jPanel1.add(jPanel37); - - deviceField72.setEditable(false); - deviceField72.setIdentifier(""); - deviceField72.setLabelString("Name: "); - deviceField72.setNumCols(15); - deviceField72.setOffsetNid(123); - deviceField72.setTextOnly(true); - jPanel38.add(deviceField72); - - deviceField73.setIdentifier(""); - deviceField73.setLabelString("Value: "); - deviceField73.setOffsetNid(124); - jPanel38.add(deviceField73); - - jPanel1.add(jPanel38); - - deviceField74.setEditable(false); - deviceField74.setIdentifier(""); - deviceField74.setLabelString("Name: "); - deviceField74.setNumCols(15); - deviceField74.setOffsetNid(126); - deviceField74.setTextOnly(true); - jPanel39.add(deviceField74); - - deviceField75.setIdentifier(""); - deviceField75.setLabelString("Value: "); - deviceField75.setOffsetNid(127); - jPanel39.add(deviceField75); - - jPanel1.add(jPanel39); - - deviceField76.setEditable(false); - deviceField76.setIdentifier(""); - deviceField76.setLabelString("Name: "); - deviceField76.setNumCols(15); - deviceField76.setOffsetNid(129); - deviceField76.setTextOnly(true); - jPanel40.add(deviceField76); - - deviceField77.setIdentifier(""); - deviceField77.setLabelString("Value: "); - deviceField77.setOffsetNid(130); - jPanel40.add(deviceField77); - - jPanel1.add(jPanel40); - - deviceField78.setEditable(false); - deviceField78.setIdentifier(""); - deviceField78.setLabelString("Name: "); - deviceField78.setNumCols(15); - deviceField78.setOffsetNid(132); - deviceField78.setTextOnly(true); - jPanel41.add(deviceField78); - - deviceField79.setIdentifier(""); - deviceField79.setLabelString("Value: "); - deviceField79.setOffsetNid(133); - jPanel41.add(deviceField79); - - jPanel1.add(jPanel41); - - deviceField80.setEditable(false); - deviceField80.setIdentifier(""); - deviceField80.setLabelString("Name: "); - deviceField80.setNumCols(15); - deviceField80.setOffsetNid(135); - deviceField80.setTextOnly(true); - jPanel42.add(deviceField80); - - deviceField81.setIdentifier(""); - deviceField81.setLabelString("Value: "); - deviceField81.setOffsetNid(136); - jPanel42.add(deviceField81); - - jPanel1.add(jPanel42); - - deviceField82.setEditable(false); - deviceField82.setIdentifier(""); - deviceField82.setLabelString("Name: "); - deviceField82.setNumCols(15); - deviceField82.setOffsetNid(138); - deviceField82.setTextOnly(true); - jPanel43.add(deviceField82); - - deviceField83.setIdentifier(""); - deviceField83.setLabelString("Value: "); - deviceField83.setOffsetNid(139); - jPanel43.add(deviceField83); - - jPanel1.add(jPanel43); - - deviceField84.setEditable(false); - deviceField84.setIdentifier(""); - deviceField84.setLabelString("Name: "); - deviceField84.setNumCols(15); - deviceField84.setOffsetNid(141); - deviceField84.setTextOnly(true); - jPanel44.add(deviceField84); - - deviceField85.setIdentifier(""); - deviceField85.setLabelString("Value: "); - deviceField85.setOffsetNid(142); - jPanel44.add(deviceField85); - - jPanel1.add(jPanel44); - - deviceField86.setEditable(false); - deviceField86.setIdentifier(""); - deviceField86.setLabelString("Name: "); - deviceField86.setNumCols(15); - deviceField86.setOffsetNid(144); - deviceField86.setTextOnly(true); - jPanel45.add(deviceField86); - - deviceField87.setIdentifier(""); - deviceField87.setLabelString("Value: "); - deviceField87.setOffsetNid(145); - jPanel45.add(deviceField87); - - jPanel1.add(jPanel45); - - deviceField88.setEditable(false); - deviceField88.setIdentifier(""); - deviceField88.setLabelString("Name: "); - deviceField88.setNumCols(15); - deviceField88.setOffsetNid(147); - deviceField88.setTextOnly(true); - jPanel46.add(deviceField88); - - deviceField89.setIdentifier(""); - deviceField89.setLabelString("Value: "); - deviceField89.setOffsetNid(148); - jPanel46.add(deviceField89); - - jPanel1.add(jPanel46); - - deviceField90.setEditable(false); - deviceField90.setIdentifier(""); - deviceField90.setLabelString("Name: "); - deviceField90.setNumCols(15); - deviceField90.setOffsetNid(150); - deviceField90.setTextOnly(true); - jPanel47.add(deviceField90); - - deviceField91.setIdentifier(""); - deviceField91.setLabelString("Value: "); - deviceField91.setOffsetNid(151); - jPanel47.add(deviceField91); - - jPanel1.add(jPanel47); - - deviceField92.setEditable(false); - deviceField92.setIdentifier(""); - deviceField92.setLabelString("Name: "); - deviceField92.setNumCols(15); - deviceField92.setOffsetNid(153); - deviceField92.setTextOnly(true); - jPanel48.add(deviceField92); - - deviceField93.setIdentifier(""); - deviceField93.setLabelString("Value: "); - deviceField93.setOffsetNid(154); - jPanel48.add(deviceField93); - - jPanel1.add(jPanel48); - - deviceField94.setEditable(false); - deviceField94.setIdentifier(""); - deviceField94.setLabelString("Name: "); - deviceField94.setNumCols(15); - deviceField94.setOffsetNid(156); - deviceField94.setTextOnly(true); - jPanel49.add(deviceField94); - - deviceField95.setIdentifier(""); - deviceField95.setLabelString("Value: "); - deviceField95.setOffsetNid(157); - jPanel49.add(deviceField95); - - jPanel1.add(jPanel49); - - deviceField96.setEditable(false); - deviceField96.setIdentifier(""); - deviceField96.setLabelString("Name: "); - deviceField96.setNumCols(15); - deviceField96.setOffsetNid(159); - deviceField96.setTextOnly(true); - jPanel50.add(deviceField96); - - deviceField97.setIdentifier(""); - deviceField97.setLabelString("Value: "); - deviceField97.setOffsetNid(160); - jPanel50.add(deviceField97); - - jPanel1.add(jPanel50); - - deviceField98.setEditable(false); - deviceField98.setIdentifier(""); - deviceField98.setLabelString("Name: "); - deviceField98.setNumCols(15); - deviceField98.setOffsetNid(162); - deviceField98.setTextOnly(true); - jPanel51.add(deviceField98); - - deviceField99.setIdentifier(""); - deviceField99.setLabelString("Value: "); - deviceField99.setOffsetNid(163); - jPanel51.add(deviceField99); - - jPanel1.add(jPanel51); - - deviceField100.setEditable(false); - deviceField100.setIdentifier(""); - deviceField100.setLabelString("Name: "); - deviceField100.setNumCols(15); - deviceField100.setOffsetNid(165); - deviceField100.setTextOnly(true); - jPanel52.add(deviceField100); - - deviceField101.setIdentifier(""); - deviceField101.setLabelString("Value: "); - deviceField101.setOffsetNid(166); - jPanel52.add(deviceField101); - - jPanel1.add(jPanel52); - - deviceField102.setEditable(false); - deviceField102.setIdentifier(""); - deviceField102.setLabelString("Name: "); - deviceField102.setNumCols(15); - deviceField102.setOffsetNid(168); - deviceField102.setTextOnly(true); - jPanel53.add(deviceField102); - - deviceField103.setIdentifier(""); - deviceField103.setLabelString("Value: "); - deviceField103.setOffsetNid(169); - jPanel53.add(deviceField103); - - jPanel1.add(jPanel53); - - deviceField104.setEditable(false); - deviceField104.setIdentifier(""); - deviceField104.setLabelString("Name: "); - deviceField104.setNumCols(15); - deviceField104.setOffsetNid(171); - deviceField104.setTextOnly(true); - jPanel54.add(deviceField104); - - deviceField105.setIdentifier(""); - deviceField105.setLabelString("Value: "); - deviceField105.setOffsetNid(172); - jPanel54.add(deviceField105); - - jPanel1.add(jPanel54); - - deviceField106.setEditable(false); - deviceField106.setIdentifier(""); - deviceField106.setLabelString("Name: "); - deviceField106.setNumCols(15); - deviceField106.setOffsetNid(174); - deviceField106.setTextOnly(true); - jPanel55.add(deviceField106); - - deviceField107.setIdentifier(""); - deviceField107.setLabelString("Value: "); - deviceField107.setOffsetNid(175); - jPanel55.add(deviceField107); - - jPanel1.add(jPanel55); - - deviceField108.setEditable(false); - deviceField108.setIdentifier(""); - deviceField108.setLabelString("Name: "); - deviceField108.setNumCols(15); - deviceField108.setOffsetNid(177); - deviceField108.setTextOnly(true); - jPanel56.add(deviceField108); - - deviceField109.setIdentifier(""); - deviceField109.setLabelString("Value: "); - deviceField109.setOffsetNid(178); - jPanel56.add(deviceField109); - - jPanel1.add(jPanel56); - - deviceField110.setEditable(false); - deviceField110.setIdentifier(""); - deviceField110.setLabelString("Name: "); - deviceField110.setNumCols(15); - deviceField110.setOffsetNid(180); - deviceField110.setTextOnly(true); - jPanel57.add(deviceField110); - - deviceField111.setIdentifier(""); - deviceField111.setLabelString("Value: "); - deviceField111.setOffsetNid(181); - jPanel57.add(deviceField111); - - jPanel1.add(jPanel57); - - deviceField112.setEditable(false); - deviceField112.setIdentifier(""); - deviceField112.setLabelString("Name: "); - deviceField112.setNumCols(15); - deviceField112.setOffsetNid(183); - deviceField112.setTextOnly(true); - jPanel58.add(deviceField112); - - deviceField113.setIdentifier(""); - deviceField113.setLabelString("Value: "); - deviceField113.setOffsetNid(184); - jPanel58.add(deviceField113); - - jPanel1.add(jPanel58); - - deviceField114.setEditable(false); - deviceField114.setIdentifier(""); - deviceField114.setLabelString("Name: "); - deviceField114.setNumCols(15); - deviceField114.setOffsetNid(186); - deviceField114.setTextOnly(true); - jPanel59.add(deviceField114); - - deviceField115.setIdentifier(""); - deviceField115.setLabelString("Value: "); - deviceField115.setOffsetNid(187); - jPanel59.add(deviceField115); - - jPanel1.add(jPanel59); - - deviceField116.setEditable(false); - deviceField116.setIdentifier(""); - deviceField116.setLabelString("Name: "); - deviceField116.setNumCols(15); - deviceField116.setOffsetNid(189); - deviceField116.setTextOnly(true); - jPanel60.add(deviceField116); - - deviceField117.setIdentifier(""); - deviceField117.setLabelString("Value: "); - deviceField117.setOffsetNid(190); - jPanel60.add(deviceField117); - - jPanel1.add(jPanel60); - - deviceField118.setEditable(false); - deviceField118.setIdentifier(""); - deviceField118.setLabelString("Name: "); - deviceField118.setNumCols(15); - deviceField118.setOffsetNid(192); - deviceField118.setTextOnly(true); - jPanel61.add(deviceField118); - - deviceField119.setIdentifier(""); - deviceField119.setLabelString("Value: "); - deviceField119.setOffsetNid(193); - jPanel61.add(deviceField119); - - jPanel1.add(jPanel61); - - deviceField120.setEditable(false); - deviceField120.setIdentifier(""); - deviceField120.setLabelString("Name: "); - deviceField120.setNumCols(15); - deviceField120.setOffsetNid(195); - deviceField120.setTextOnly(true); - jPanel62.add(deviceField120); - - deviceField121.setIdentifier(""); - deviceField121.setLabelString("Value: "); - deviceField121.setOffsetNid(196); - jPanel62.add(deviceField121); - - jPanel1.add(jPanel62); - - deviceField122.setEditable(false); - deviceField122.setIdentifier(""); - deviceField122.setLabelString("Name: "); - deviceField122.setNumCols(15); - deviceField122.setOffsetNid(198); - deviceField122.setTextOnly(true); - jPanel63.add(deviceField122); - - deviceField123.setIdentifier(""); - deviceField123.setLabelString("Value: "); - deviceField123.setOffsetNid(199); - jPanel63.add(deviceField123); - - jPanel1.add(jPanel63); - - deviceField124.setEditable(false); - deviceField124.setIdentifier(""); - deviceField124.setLabelString("Name: "); - deviceField124.setNumCols(15); - deviceField124.setOffsetNid(201); - deviceField124.setTextOnly(true); - jPanel64.add(deviceField124); - - deviceField125.setIdentifier(""); - deviceField125.setLabelString("Value: "); - deviceField125.setOffsetNid(202); - jPanel64.add(deviceField125); - - jPanel1.add(jPanel64); - - deviceField126.setEditable(false); - deviceField126.setIdentifier(""); - deviceField126.setLabelString("Name: "); - deviceField126.setNumCols(15); - deviceField126.setOffsetNid(204); - deviceField126.setTextOnly(true); - jPanel65.add(deviceField126); - - deviceField127.setIdentifier(""); - deviceField127.setLabelString("Value: "); - deviceField127.setOffsetNid(205); - jPanel65.add(deviceField127); - - jPanel1.add(jPanel65); - - deviceField128.setEditable(false); - deviceField128.setIdentifier(""); - deviceField128.setLabelString("Name: "); - deviceField128.setNumCols(15); - deviceField128.setOffsetNid(207); - deviceField128.setTextOnly(true); - jPanel66.add(deviceField128); - - deviceField129.setIdentifier(""); - deviceField129.setLabelString("Value: "); - deviceField129.setOffsetNid(208); - jPanel66.add(deviceField129); - - jPanel1.add(jPanel66); - - deviceField130.setEditable(false); - deviceField130.setIdentifier(""); - deviceField130.setLabelString("Name: "); - deviceField130.setNumCols(15); - deviceField130.setOffsetNid(210); - deviceField130.setTextOnly(true); - jPanel67.add(deviceField130); - - deviceField131.setIdentifier(""); - deviceField131.setLabelString("Value: "); - deviceField131.setOffsetNid(211); - jPanel67.add(deviceField131); - - jPanel1.add(jPanel67); - - deviceField132.setEditable(false); - deviceField132.setIdentifier(""); - deviceField132.setLabelString("Name: "); - deviceField132.setNumCols(15); - deviceField132.setOffsetNid(213); - deviceField132.setTextOnly(true); - jPanel68.add(deviceField132); - - deviceField133.setIdentifier(""); - deviceField133.setLabelString("Value: "); - deviceField133.setOffsetNid(214); - jPanel68.add(deviceField133); - - jPanel1.add(jPanel68); - - deviceField134.setEditable(false); - deviceField134.setIdentifier(""); - deviceField134.setLabelString("Name: "); - deviceField134.setNumCols(15); - deviceField134.setOffsetNid(216); - deviceField134.setTextOnly(true); - jPanel69.add(deviceField134); - - deviceField135.setIdentifier(""); - deviceField135.setLabelString("Value: "); - deviceField135.setOffsetNid(217); - jPanel69.add(deviceField135); - - jPanel1.add(jPanel69); - - deviceField136.setEditable(false); - deviceField136.setIdentifier(""); - deviceField136.setLabelString("Name: "); - deviceField136.setNumCols(15); - deviceField136.setOffsetNid(219); - deviceField136.setTextOnly(true); - jPanel70.add(deviceField136); - - deviceField137.setIdentifier(""); - deviceField137.setLabelString("Value: "); - deviceField137.setOffsetNid(220); - jPanel70.add(deviceField137); - - jPanel1.add(jPanel70); - - deviceField138.setEditable(false); - deviceField138.setIdentifier(""); - deviceField138.setLabelString("Name: "); - deviceField138.setNumCols(15); - deviceField138.setOffsetNid(222); - deviceField138.setTextOnly(true); - jPanel71.add(deviceField138); - - deviceField139.setIdentifier(""); - deviceField139.setLabelString("Value: "); - deviceField139.setOffsetNid(223); - jPanel71.add(deviceField139); - - jPanel1.add(jPanel71); - - deviceField140.setEditable(false); - deviceField140.setIdentifier(""); - deviceField140.setLabelString("Name: "); - deviceField140.setNumCols(15); - deviceField140.setOffsetNid(225); - deviceField140.setTextOnly(true); - jPanel72.add(deviceField140); - - deviceField141.setIdentifier(""); - deviceField141.setLabelString("Value: "); - deviceField141.setOffsetNid(226); - jPanel72.add(deviceField141); - - jPanel1.add(jPanel72); - - deviceField142.setEditable(false); - deviceField142.setIdentifier(""); - deviceField142.setLabelString("Name: "); - deviceField142.setNumCols(15); - deviceField142.setOffsetNid(228); - deviceField142.setTextOnly(true); - jPanel73.add(deviceField142); - - deviceField143.setIdentifier(""); - deviceField143.setLabelString("Value: "); - deviceField143.setOffsetNid(229); - jPanel73.add(deviceField143); - - jPanel1.add(jPanel73); - - deviceField144.setEditable(false); - deviceField144.setIdentifier(""); - deviceField144.setLabelString("Name: "); - deviceField144.setNumCols(15); - deviceField144.setOffsetNid(231); - deviceField144.setTextOnly(true); - jPanel74.add(deviceField144); - - deviceField145.setIdentifier(""); - deviceField145.setLabelString("Value: "); - deviceField145.setOffsetNid(232); - jPanel74.add(deviceField145); - - jPanel1.add(jPanel74); - - deviceField146.setEditable(false); - deviceField146.setIdentifier(""); - deviceField146.setLabelString("Name: "); - deviceField146.setNumCols(15); - deviceField146.setOffsetNid(234); - deviceField146.setTextOnly(true); - jPanel75.add(deviceField146); - - deviceField147.setIdentifier(""); - deviceField147.setLabelString("Value: "); - deviceField147.setOffsetNid(235); - jPanel75.add(deviceField147); - - jPanel1.add(jPanel75); - - deviceField148.setEditable(false); - deviceField148.setIdentifier(""); - deviceField148.setLabelString("Name: "); - deviceField148.setNumCols(15); - deviceField148.setOffsetNid(237); - deviceField148.setTextOnly(true); - jPanel76.add(deviceField148); - - deviceField149.setIdentifier(""); - deviceField149.setLabelString("Value: "); - deviceField149.setOffsetNid(238); - jPanel76.add(deviceField149); - - jPanel1.add(jPanel76); - - deviceField150.setEditable(false); - deviceField150.setIdentifier(""); - deviceField150.setLabelString("Name: "); - deviceField150.setNumCols(15); - deviceField150.setOffsetNid(240); - deviceField150.setTextOnly(true); - jPanel77.add(deviceField150); - - deviceField151.setIdentifier(""); - deviceField151.setLabelString("Value: "); - deviceField151.setOffsetNid(241); - jPanel77.add(deviceField151); - - jPanel1.add(jPanel77); - - deviceField152.setEditable(false); - deviceField152.setIdentifier(""); - deviceField152.setLabelString("Name: "); - deviceField152.setNumCols(15); - deviceField152.setOffsetNid(243); - deviceField152.setTextOnly(true); - jPanel78.add(deviceField152); - - deviceField153.setIdentifier(""); - deviceField153.setLabelString("Value: "); - deviceField153.setOffsetNid(244); - jPanel78.add(deviceField153); - - jPanel1.add(jPanel78); - - deviceField154.setEditable(false); - deviceField154.setIdentifier(""); - deviceField154.setLabelString("Name: "); - deviceField154.setNumCols(15); - deviceField154.setOffsetNid(246); - deviceField154.setTextOnly(true); - jPanel79.add(deviceField154); - - deviceField155.setIdentifier(""); - deviceField155.setLabelString("Value: "); - deviceField155.setOffsetNid(247); - jPanel79.add(deviceField155); - - jPanel1.add(jPanel79); - - deviceField156.setEditable(false); - deviceField156.setIdentifier(""); - deviceField156.setLabelString("Name: "); - deviceField156.setNumCols(15); - deviceField156.setOffsetNid(249); - deviceField156.setTextOnly(true); - jPanel80.add(deviceField156); - - deviceField157.setIdentifier(""); - deviceField157.setLabelString("Value: "); - deviceField157.setOffsetNid(250); - jPanel80.add(deviceField157); - - jPanel1.add(jPanel80); - - deviceField158.setEditable(false); - deviceField158.setIdentifier(""); - deviceField158.setLabelString("Name: "); - deviceField158.setNumCols(15); - deviceField158.setOffsetNid(252); - deviceField158.setTextOnly(true); - jPanel81.add(deviceField158); - - deviceField159.setIdentifier(""); - deviceField159.setLabelString("Value: "); - deviceField159.setOffsetNid(253); - jPanel81.add(deviceField159); - - jPanel1.add(jPanel81); - - deviceField160.setEditable(false); - deviceField160.setIdentifier(""); - deviceField160.setLabelString("Name: "); - deviceField160.setNumCols(15); - deviceField160.setOffsetNid(255); - deviceField160.setTextOnly(true); - jPanel82.add(deviceField160); - - deviceField161.setIdentifier(""); - deviceField161.setLabelString("Value: "); - deviceField161.setOffsetNid(256); - jPanel82.add(deviceField161); - - jPanel1.add(jPanel82); - - deviceField162.setEditable(false); - deviceField162.setIdentifier(""); - deviceField162.setLabelString("Name: "); - deviceField162.setNumCols(15); - deviceField162.setOffsetNid(258); - deviceField162.setTextOnly(true); - jPanel83.add(deviceField162); - - deviceField163.setIdentifier(""); - deviceField163.setLabelString("Value: "); - deviceField163.setOffsetNid(259); - jPanel83.add(deviceField163); - - jPanel1.add(jPanel83); - - deviceField164.setEditable(false); - deviceField164.setIdentifier(""); - deviceField164.setLabelString("Name: "); - deviceField164.setNumCols(15); - deviceField164.setOffsetNid(261); - deviceField164.setTextOnly(true); - jPanel84.add(deviceField164); - - deviceField165.setIdentifier(""); - deviceField165.setLabelString("Value: "); - deviceField165.setOffsetNid(262); - jPanel84.add(deviceField165); - - jPanel1.add(jPanel84); - - deviceField166.setEditable(false); - deviceField166.setIdentifier(""); - deviceField166.setLabelString("Name: "); - deviceField166.setNumCols(15); - deviceField166.setOffsetNid(264); - deviceField166.setTextOnly(true); - jPanel85.add(deviceField166); - - deviceField167.setIdentifier(""); - deviceField167.setLabelString("Value: "); - deviceField167.setOffsetNid(265); - jPanel85.add(deviceField167); - - jPanel1.add(jPanel85); - - deviceField168.setEditable(false); - deviceField168.setIdentifier(""); - deviceField168.setLabelString("Name: "); - deviceField168.setNumCols(15); - deviceField168.setOffsetNid(267); - deviceField168.setTextOnly(true); - jPanel86.add(deviceField168); - - deviceField169.setIdentifier(""); - deviceField169.setLabelString("Value: "); - deviceField169.setOffsetNid(268); - jPanel86.add(deviceField169); - - jPanel1.add(jPanel86); - - deviceField170.setEditable(false); - deviceField170.setIdentifier(""); - deviceField170.setLabelString("Name: "); - deviceField170.setNumCols(15); - deviceField170.setOffsetNid(270); - deviceField170.setTextOnly(true); - jPanel87.add(deviceField170); - - deviceField171.setIdentifier(""); - deviceField171.setLabelString("Value: "); - deviceField171.setOffsetNid(271); - jPanel87.add(deviceField171); - - jPanel1.add(jPanel87); - - deviceField172.setEditable(false); - deviceField172.setIdentifier(""); - deviceField172.setLabelString("Name: "); - deviceField172.setNumCols(15); - deviceField172.setOffsetNid(273); - deviceField172.setTextOnly(true); - jPanel88.add(deviceField172); - - deviceField173.setIdentifier(""); - deviceField173.setLabelString("Value: "); - deviceField173.setOffsetNid(274); - jPanel88.add(deviceField173); - - jPanel1.add(jPanel88); - - deviceField174.setEditable(false); - deviceField174.setIdentifier(""); - deviceField174.setLabelString("Name: "); - deviceField174.setNumCols(15); - deviceField174.setOffsetNid(276); - deviceField174.setTextOnly(true); - jPanel89.add(deviceField174); - - deviceField175.setIdentifier(""); - deviceField175.setLabelString("Value: "); - deviceField175.setOffsetNid(277); - jPanel89.add(deviceField175); - - jPanel1.add(jPanel89); - - deviceField176.setEditable(false); - deviceField176.setIdentifier(""); - deviceField176.setLabelString("Name: "); - deviceField176.setNumCols(15); - deviceField176.setOffsetNid(279); - deviceField176.setTextOnly(true); - jPanel90.add(deviceField176); - - deviceField177.setIdentifier(""); - deviceField177.setLabelString("Value: "); - deviceField177.setOffsetNid(280); - jPanel90.add(deviceField177); - - jPanel1.add(jPanel90); - - deviceField178.setEditable(false); - deviceField178.setIdentifier(""); - deviceField178.setLabelString("Name: "); - deviceField178.setNumCols(15); - deviceField178.setOffsetNid(282); - deviceField178.setTextOnly(true); - jPanel91.add(deviceField178); - - deviceField179.setIdentifier(""); - deviceField179.setLabelString("Value: "); - deviceField179.setOffsetNid(283); - jPanel91.add(deviceField179); - - jPanel1.add(jPanel91); - - deviceField180.setEditable(false); - deviceField180.setIdentifier(""); - deviceField180.setLabelString("Name: "); - deviceField180.setNumCols(15); - deviceField180.setOffsetNid(285); - deviceField180.setTextOnly(true); - jPanel92.add(deviceField180); - - deviceField181.setIdentifier(""); - deviceField181.setLabelString("Value: "); - deviceField181.setOffsetNid(286); - jPanel92.add(deviceField181); - - jPanel1.add(jPanel92); - - deviceField182.setEditable(false); - deviceField182.setIdentifier(""); - deviceField182.setLabelString("Name: "); - deviceField182.setNumCols(15); - deviceField182.setOffsetNid(288); - deviceField182.setTextOnly(true); - jPanel93.add(deviceField182); - - deviceField183.setIdentifier(""); - deviceField183.setLabelString("Value: "); - deviceField183.setOffsetNid(289); - jPanel93.add(deviceField183); - - jPanel1.add(jPanel93); - - deviceField184.setEditable(false); - deviceField184.setIdentifier(""); - deviceField184.setLabelString("Name: "); - deviceField184.setNumCols(15); - deviceField184.setOffsetNid(291); - deviceField184.setTextOnly(true); - jPanel94.add(deviceField184); - - deviceField185.setIdentifier(""); - deviceField185.setLabelString("Value: "); - deviceField185.setOffsetNid(292); - jPanel94.add(deviceField185); - - jPanel1.add(jPanel94); - - deviceField186.setEditable(false); - deviceField186.setIdentifier(""); - deviceField186.setLabelString("Name: "); - deviceField186.setNumCols(15); - deviceField186.setOffsetNid(294); - deviceField186.setTextOnly(true); - jPanel95.add(deviceField186); - - deviceField187.setIdentifier(""); - deviceField187.setLabelString("Value: "); - deviceField187.setOffsetNid(295); - jPanel95.add(deviceField187); - - jPanel1.add(jPanel95); - - deviceField188.setEditable(false); - deviceField188.setIdentifier(""); - deviceField188.setLabelString("Name: "); - deviceField188.setNumCols(15); - deviceField188.setOffsetNid(297); - deviceField188.setTextOnly(true); - jPanel96.add(deviceField188); - - deviceField189.setIdentifier(""); - deviceField189.setLabelString("Value: "); - deviceField189.setOffsetNid(298); - jPanel96.add(deviceField189); - - jPanel1.add(jPanel96); - - deviceField190.setEditable(false); - deviceField190.setIdentifier(""); - deviceField190.setLabelString("Name: "); - deviceField190.setNumCols(15); - deviceField190.setOffsetNid(300); - deviceField190.setTextOnly(true); - jPanel97.add(deviceField190); - - deviceField191.setIdentifier(""); - deviceField191.setLabelString("Value: "); - deviceField191.setOffsetNid(301); - jPanel97.add(deviceField191); - - jPanel1.add(jPanel97); - - deviceField192.setEditable(false); - deviceField192.setIdentifier(""); - deviceField192.setLabelString("Name: "); - deviceField192.setNumCols(15); - deviceField192.setOffsetNid(303); - deviceField192.setTextOnly(true); - jPanel98.add(deviceField192); - - deviceField193.setIdentifier(""); - deviceField193.setLabelString("Value: "); - deviceField193.setOffsetNid(304); - jPanel98.add(deviceField193); - - jPanel1.add(jPanel98); - - deviceField194.setEditable(false); - deviceField194.setIdentifier(""); - deviceField194.setLabelString("Name: "); - deviceField194.setNumCols(15); - deviceField194.setOffsetNid(306); - deviceField194.setTextOnly(true); - jPanel99.add(deviceField194); - - deviceField195.setIdentifier(""); - deviceField195.setLabelString("Value: "); - deviceField195.setOffsetNid(307); - jPanel99.add(deviceField195); - - jPanel1.add(jPanel99); - - deviceField196.setEditable(false); - deviceField196.setIdentifier(""); - deviceField196.setLabelString("Name: "); - deviceField196.setNumCols(15); - deviceField196.setOffsetNid(309); - deviceField196.setTextOnly(true); - jPanel100.add(deviceField196); - - deviceField197.setIdentifier(""); - deviceField197.setLabelString("Value: "); - deviceField197.setOffsetNid(310); - jPanel100.add(deviceField197); - - jPanel1.add(jPanel100); - - deviceField198.setEditable(false); - deviceField198.setIdentifier(""); - deviceField198.setLabelString("Name: "); - deviceField198.setNumCols(15); - deviceField198.setOffsetNid(312); - deviceField198.setTextOnly(true); - jPanel101.add(deviceField198); - - deviceField199.setIdentifier(""); - deviceField199.setLabelString("Value: "); - deviceField199.setOffsetNid(313); - jPanel101.add(deviceField199); - - jPanel1.add(jPanel101); - - deviceField200.setEditable(false); - deviceField200.setIdentifier(""); - deviceField200.setLabelString("Name: "); - deviceField200.setNumCols(15); - deviceField200.setOffsetNid(315); - deviceField200.setTextOnly(true); - jPanel102.add(deviceField200); - - deviceField201.setIdentifier(""); - deviceField201.setLabelString("Value: "); - deviceField201.setOffsetNid(316); - jPanel102.add(deviceField201); - - jPanel1.add(jPanel102); - - deviceField202.setEditable(false); - deviceField202.setIdentifier(""); - deviceField202.setLabelString("Name: "); - deviceField202.setNumCols(15); - deviceField202.setOffsetNid(318); - deviceField202.setTextOnly(true); - jPanel103.add(deviceField202); - - deviceField203.setIdentifier(""); - deviceField203.setLabelString("Value: "); - deviceField203.setOffsetNid(319); - jPanel103.add(deviceField203); - - jPanel1.add(jPanel103); - - deviceField204.setEditable(false); - deviceField204.setIdentifier(""); - deviceField204.setLabelString("Name: "); - deviceField204.setNumCols(15); - deviceField204.setOffsetNid(321); - deviceField204.setTextOnly(true); - jPanel104.add(deviceField204); - - deviceField205.setIdentifier(""); - deviceField205.setLabelString("Value: "); - deviceField205.setOffsetNid(322); - jPanel104.add(deviceField205); - - jPanel1.add(jPanel104); - - deviceField206.setEditable(false); - deviceField206.setIdentifier(""); - deviceField206.setLabelString("Name: "); - deviceField206.setNumCols(15); - deviceField206.setOffsetNid(324); - deviceField206.setTextOnly(true); - jPanel105.add(deviceField206); - - deviceField207.setIdentifier(""); - deviceField207.setLabelString("Value: "); - deviceField207.setOffsetNid(325); - jPanel105.add(deviceField207); - - jPanel1.add(jPanel105); - - deviceField208.setEditable(false); - deviceField208.setIdentifier(""); - deviceField208.setLabelString("Name: "); - deviceField208.setNumCols(15); - deviceField208.setOffsetNid(327); - deviceField208.setTextOnly(true); - jPanel106.add(deviceField208); - - deviceField209.setIdentifier(""); - deviceField209.setLabelString("Value: "); - deviceField209.setOffsetNid(328); - jPanel106.add(deviceField209); - - jPanel1.add(jPanel106); - - deviceField210.setEditable(false); - deviceField210.setIdentifier(""); - deviceField210.setLabelString("Name: "); - deviceField210.setNumCols(15); - deviceField210.setOffsetNid(330); - deviceField210.setTextOnly(true); - jPanel107.add(deviceField210); - - deviceField211.setIdentifier(""); - deviceField211.setLabelString("Value: "); - deviceField211.setOffsetNid(331); - jPanel107.add(deviceField211); - - jPanel1.add(jPanel107); - - deviceField212.setEditable(false); - deviceField212.setIdentifier(""); - deviceField212.setLabelString("Name: "); - deviceField212.setNumCols(15); - deviceField212.setOffsetNid(333); - deviceField212.setTextOnly(true); - jPanel108.add(deviceField212); - - deviceField213.setIdentifier(""); - deviceField213.setLabelString("Value: "); - deviceField213.setOffsetNid(334); - jPanel108.add(deviceField213); - - jPanel1.add(jPanel108); - - deviceField214.setEditable(false); - deviceField214.setIdentifier(""); - deviceField214.setLabelString("Name: "); - deviceField214.setNumCols(15); - deviceField214.setOffsetNid(336); - deviceField214.setTextOnly(true); - jPanel109.add(deviceField214); - - deviceField215.setIdentifier(""); - deviceField215.setLabelString("Value: "); - deviceField215.setOffsetNid(337); - jPanel109.add(deviceField215); - - jPanel1.add(jPanel109); - - deviceField216.setEditable(false); - deviceField216.setIdentifier(""); - deviceField216.setLabelString("Name: "); - deviceField216.setNumCols(15); - deviceField216.setOffsetNid(339); - deviceField216.setTextOnly(true); - jPanel110.add(deviceField216); - - deviceField217.setIdentifier(""); - deviceField217.setLabelString("Value: "); - deviceField217.setOffsetNid(340); - jPanel110.add(deviceField217); - - jPanel1.add(jPanel110); - - deviceField218.setEditable(false); - deviceField218.setIdentifier(""); - deviceField218.setLabelString("Name: "); - deviceField218.setNumCols(15); - deviceField218.setOffsetNid(342); - deviceField218.setTextOnly(true); - jPanel111.add(deviceField218); - - deviceField219.setIdentifier(""); - deviceField219.setLabelString("Value: "); - deviceField219.setOffsetNid(343); - jPanel111.add(deviceField219); - - jPanel1.add(jPanel111); - - deviceField220.setEditable(false); - deviceField220.setIdentifier(""); - deviceField220.setLabelString("Name: "); - deviceField220.setNumCols(15); - deviceField220.setOffsetNid(345); - deviceField220.setTextOnly(true); - jPanel112.add(deviceField220); - - deviceField221.setIdentifier(""); - deviceField221.setLabelString("Value: "); - deviceField221.setOffsetNid(346); - jPanel112.add(deviceField221); - - jPanel1.add(jPanel112); - - deviceField222.setEditable(false); - deviceField222.setIdentifier(""); - deviceField222.setLabelString("Name: "); - deviceField222.setNumCols(15); - deviceField222.setOffsetNid(348); - deviceField222.setTextOnly(true); - jPanel113.add(deviceField222); - - deviceField223.setIdentifier(""); - deviceField223.setLabelString("Value: "); - deviceField223.setOffsetNid(349); - jPanel113.add(deviceField223); - - jPanel1.add(jPanel113); - - deviceField224.setEditable(false); - deviceField224.setIdentifier(""); - deviceField224.setLabelString("Name: "); - deviceField224.setNumCols(15); - deviceField224.setOffsetNid(351); - deviceField224.setTextOnly(true); - jPanel114.add(deviceField224); - - deviceField225.setIdentifier(""); - deviceField225.setLabelString("Value: "); - deviceField225.setOffsetNid(352); - jPanel114.add(deviceField225); - - jPanel1.add(jPanel114); - - deviceField226.setEditable(false); - deviceField226.setIdentifier(""); - deviceField226.setLabelString("Name: "); - deviceField226.setNumCols(15); - deviceField226.setOffsetNid(354); - deviceField226.setTextOnly(true); - jPanel115.add(deviceField226); - - deviceField227.setIdentifier(""); - deviceField227.setLabelString("Value: "); - deviceField227.setOffsetNid(355); - jPanel115.add(deviceField227); - - jPanel1.add(jPanel115); - - deviceField228.setEditable(false); - deviceField228.setIdentifier(""); - deviceField228.setLabelString("Name: "); - deviceField228.setNumCols(15); - deviceField228.setOffsetNid(357); - deviceField228.setTextOnly(true); - jPanel116.add(deviceField228); - - deviceField229.setIdentifier(""); - deviceField229.setLabelString("Value: "); - deviceField229.setOffsetNid(358); - jPanel116.add(deviceField229); - - jPanel1.add(jPanel116); - - deviceField230.setEditable(false); - deviceField230.setIdentifier(""); - deviceField230.setLabelString("Name: "); - deviceField230.setNumCols(15); - deviceField230.setOffsetNid(360); - deviceField230.setTextOnly(true); - jPanel117.add(deviceField230); - - deviceField231.setIdentifier(""); - deviceField231.setLabelString("Value: "); - deviceField231.setOffsetNid(361); - jPanel117.add(deviceField231); - - jPanel1.add(jPanel117); - - deviceField232.setEditable(false); - deviceField232.setIdentifier(""); - deviceField232.setLabelString("Name: "); - deviceField232.setNumCols(15); - deviceField232.setOffsetNid(363); - deviceField232.setTextOnly(true); - jPanel118.add(deviceField232); - - deviceField233.setIdentifier(""); - deviceField233.setLabelString("Value: "); - deviceField233.setOffsetNid(364); - jPanel118.add(deviceField233); - - jPanel1.add(jPanel118); - - deviceField234.setEditable(false); - deviceField234.setIdentifier(""); - deviceField234.setLabelString("Name: "); - deviceField234.setNumCols(15); - deviceField234.setOffsetNid(366); - deviceField234.setTextOnly(true); - jPanel119.add(deviceField234); - - deviceField235.setIdentifier(""); - deviceField235.setLabelString("Value: "); - deviceField235.setOffsetNid(367); - jPanel119.add(deviceField235); - - jPanel1.add(jPanel119); - - deviceField236.setEditable(false); - deviceField236.setIdentifier(""); - deviceField236.setLabelString("Name: "); - deviceField236.setNumCols(15); - deviceField236.setOffsetNid(369); - deviceField236.setTextOnly(true); - jPanel120.add(deviceField236); - - deviceField237.setIdentifier(""); - deviceField237.setLabelString("Value: "); - deviceField237.setOffsetNid(370); - jPanel120.add(deviceField237); - - jPanel1.add(jPanel120); - - deviceField238.setEditable(false); - deviceField238.setIdentifier(""); - deviceField238.setLabelString("Name: "); - deviceField238.setNumCols(15); - deviceField238.setOffsetNid(372); - deviceField238.setTextOnly(true); - jPanel121.add(deviceField238); - - deviceField239.setIdentifier(""); - deviceField239.setLabelString("Value: "); - deviceField239.setOffsetNid(373); - jPanel121.add(deviceField239); - - jPanel1.add(jPanel121); - - deviceField240.setEditable(false); - deviceField240.setIdentifier(""); - deviceField240.setLabelString("Name: "); - deviceField240.setNumCols(15); - deviceField240.setOffsetNid(375); - deviceField240.setTextOnly(true); - jPanel122.add(deviceField240); - - deviceField241.setIdentifier(""); - deviceField241.setLabelString("Value: "); - deviceField241.setOffsetNid(376); - jPanel122.add(deviceField241); - - jPanel1.add(jPanel122); - - deviceField242.setEditable(false); - deviceField242.setIdentifier(""); - deviceField242.setLabelString("Name: "); - deviceField242.setNumCols(15); - deviceField242.setOffsetNid(378); - deviceField242.setTextOnly(true); - jPanel123.add(deviceField242); - - deviceField243.setIdentifier(""); - deviceField243.setLabelString("Value: "); - deviceField243.setOffsetNid(379); - jPanel123.add(deviceField243); - - jPanel1.add(jPanel123); - - deviceField244.setEditable(false); - deviceField244.setIdentifier(""); - deviceField244.setLabelString("Name: "); - deviceField244.setNumCols(15); - deviceField244.setOffsetNid(381); - deviceField244.setTextOnly(true); - jPanel124.add(deviceField244); - - deviceField245.setIdentifier(""); - deviceField245.setLabelString("Value: "); - deviceField245.setOffsetNid(382); - jPanel124.add(deviceField245); - - jPanel1.add(jPanel124); - - deviceField246.setEditable(false); - deviceField246.setIdentifier(""); - deviceField246.setLabelString("Name: "); - deviceField246.setNumCols(15); - deviceField246.setOffsetNid(384); - deviceField246.setTextOnly(true); - jPanel125.add(deviceField246); - - deviceField247.setIdentifier(""); - deviceField247.setLabelString("Value: "); - deviceField247.setOffsetNid(385); - jPanel125.add(deviceField247); - - jPanel1.add(jPanel125); - - deviceField248.setEditable(false); - deviceField248.setIdentifier(""); - deviceField248.setLabelString("Name: "); - deviceField248.setNumCols(15); - deviceField248.setOffsetNid(387); - deviceField248.setTextOnly(true); - jPanel126.add(deviceField248); - - deviceField249.setIdentifier(""); - deviceField249.setLabelString("Value: "); - deviceField249.setOffsetNid(388); - jPanel126.add(deviceField249); - - jPanel1.add(jPanel126); - - deviceField250.setEditable(false); - deviceField250.setIdentifier(""); - deviceField250.setLabelString("Name: "); - deviceField250.setNumCols(15); - deviceField250.setOffsetNid(390); - deviceField250.setTextOnly(true); - jPanel127.add(deviceField250); - - deviceField251.setIdentifier(""); - deviceField251.setLabelString("Value: "); - deviceField251.setOffsetNid(391); - jPanel127.add(deviceField251); - - jPanel1.add(jPanel127); - - deviceField252.setEditable(false); - deviceField252.setIdentifier(""); - deviceField252.setLabelString("Name: "); - deviceField252.setNumCols(15); - deviceField252.setOffsetNid(393); - deviceField252.setTextOnly(true); - jPanel128.add(deviceField252); - - deviceField253.setIdentifier(""); - deviceField253.setLabelString("Value: "); - deviceField253.setOffsetNid(394); - jPanel128.add(deviceField253); - - jPanel1.add(jPanel128); - - deviceField254.setEditable(false); - deviceField254.setIdentifier(""); - deviceField254.setLabelString("Name: "); - deviceField254.setNumCols(15); - deviceField254.setOffsetNid(396); - deviceField254.setTextOnly(true); - jPanel129.add(deviceField254); - - deviceField255.setIdentifier(""); - deviceField255.setLabelString("Value: "); - deviceField255.setOffsetNid(397); - jPanel129.add(deviceField255); - - jPanel1.add(jPanel129); - - deviceField256.setEditable(false); - deviceField256.setIdentifier(""); - deviceField256.setLabelString("Name: "); - deviceField256.setNumCols(15); - deviceField256.setOffsetNid(399); - deviceField256.setTextOnly(true); - jPanel130.add(deviceField256); - - deviceField257.setIdentifier(""); - deviceField257.setLabelString("Value: "); - deviceField257.setOffsetNid(400); - jPanel130.add(deviceField257); - - jPanel1.add(jPanel130); - - deviceField258.setEditable(false); - deviceField258.setIdentifier(""); - deviceField258.setLabelString("Name: "); - deviceField258.setNumCols(15); - deviceField258.setOffsetNid(402); - deviceField258.setTextOnly(true); - jPanel131.add(deviceField258); - - deviceField259.setIdentifier(""); - deviceField259.setLabelString("Value: "); - deviceField259.setOffsetNid(403); - jPanel131.add(deviceField259); - - jPanel1.add(jPanel131); - - deviceField260.setEditable(false); - deviceField260.setIdentifier(""); - deviceField260.setLabelString("Name: "); - deviceField260.setNumCols(15); - deviceField260.setOffsetNid(405); - deviceField260.setTextOnly(true); - jPanel132.add(deviceField260); - - deviceField261.setIdentifier(""); - deviceField261.setLabelString("Value: "); - deviceField261.setOffsetNid(406); - jPanel132.add(deviceField261); - - jPanel1.add(jPanel132); - - deviceField262.setEditable(false); - deviceField262.setIdentifier(""); - deviceField262.setLabelString("Name: "); - deviceField262.setNumCols(15); - deviceField262.setOffsetNid(408); - deviceField262.setTextOnly(true); - jPanel133.add(deviceField262); - - deviceField263.setIdentifier(""); - deviceField263.setLabelString("Value: "); - deviceField263.setOffsetNid(409); - jPanel133.add(deviceField263); - - jPanel1.add(jPanel133); - - deviceField264.setEditable(false); - deviceField264.setIdentifier(""); - deviceField264.setLabelString("Name: "); - deviceField264.setNumCols(15); - deviceField264.setOffsetNid(411); - deviceField264.setTextOnly(true); - jPanel134.add(deviceField264); - - deviceField265.setIdentifier(""); - deviceField265.setLabelString("Value: "); - deviceField265.setOffsetNid(412); - jPanel134.add(deviceField265); - - jPanel1.add(jPanel134); - - deviceField266.setEditable(false); - deviceField266.setIdentifier(""); - deviceField266.setLabelString("Name: "); - deviceField266.setNumCols(15); - deviceField266.setOffsetNid(414); - deviceField266.setTextOnly(true); - jPanel135.add(deviceField266); - - deviceField267.setIdentifier(""); - deviceField267.setLabelString("Value: "); - deviceField267.setOffsetNid(415); - jPanel135.add(deviceField267); - - jPanel1.add(jPanel135); - - deviceField268.setEditable(false); - deviceField268.setIdentifier(""); - deviceField268.setLabelString("Name: "); - deviceField268.setNumCols(15); - deviceField268.setOffsetNid(417); - deviceField268.setTextOnly(true); - jPanel136.add(deviceField268); - - deviceField269.setIdentifier(""); - deviceField269.setLabelString("Value: "); - deviceField269.setOffsetNid(418); - jPanel136.add(deviceField269); - - jPanel1.add(jPanel136); - - deviceField270.setEditable(false); - deviceField270.setIdentifier(""); - deviceField270.setLabelString("Name: "); - deviceField270.setNumCols(15); - deviceField270.setOffsetNid(420); - deviceField270.setTextOnly(true); - jPanel137.add(deviceField270); - - deviceField271.setIdentifier(""); - deviceField271.setLabelString("Value: "); - deviceField271.setOffsetNid(421); - jPanel137.add(deviceField271); - - jPanel1.add(jPanel137); - - deviceField272.setEditable(false); - deviceField272.setIdentifier(""); - deviceField272.setLabelString("Name: "); - deviceField272.setNumCols(15); - deviceField272.setOffsetNid(423); - deviceField272.setTextOnly(true); - jPanel138.add(deviceField272); - - deviceField273.setIdentifier(""); - deviceField273.setLabelString("Value: "); - deviceField273.setOffsetNid(424); - jPanel138.add(deviceField273); - - jPanel1.add(jPanel138); - - deviceField274.setEditable(false); - deviceField274.setIdentifier(""); - deviceField274.setLabelString("Name: "); - deviceField274.setNumCols(15); - deviceField274.setOffsetNid(426); - deviceField274.setTextOnly(true); - jPanel139.add(deviceField274); - - deviceField275.setIdentifier(""); - deviceField275.setLabelString("Value: "); - deviceField275.setOffsetNid(427); - jPanel139.add(deviceField275); - - jPanel1.add(jPanel139); - - deviceField276.setEditable(false); - deviceField276.setIdentifier(""); - deviceField276.setLabelString("Name: "); - deviceField276.setNumCols(15); - deviceField276.setOffsetNid(429); - deviceField276.setTextOnly(true); - jPanel140.add(deviceField276); - - deviceField277.setIdentifier(""); - deviceField277.setLabelString("Value: "); - deviceField277.setOffsetNid(430); - jPanel140.add(deviceField277); - - jPanel1.add(jPanel140); - - deviceField278.setEditable(false); - deviceField278.setIdentifier(""); - deviceField278.setLabelString("Name: "); - deviceField278.setNumCols(15); - deviceField278.setOffsetNid(432); - deviceField278.setTextOnly(true); - jPanel141.add(deviceField278); - - deviceField279.setIdentifier(""); - deviceField279.setLabelString("Value: "); - deviceField279.setOffsetNid(433); - jPanel141.add(deviceField279); - - jPanel1.add(jPanel141); - - deviceField280.setEditable(false); - deviceField280.setIdentifier(""); - deviceField280.setLabelString("Name: "); - deviceField280.setNumCols(15); - deviceField280.setOffsetNid(435); - deviceField280.setTextOnly(true); - jPanel142.add(deviceField280); - - deviceField281.setIdentifier(""); - deviceField281.setLabelString("Value: "); - deviceField281.setOffsetNid(436); - jPanel142.add(deviceField281); - - jPanel1.add(jPanel142); - - deviceField282.setEditable(false); - deviceField282.setIdentifier(""); - deviceField282.setLabelString("Name: "); - deviceField282.setNumCols(15); - deviceField282.setOffsetNid(438); - deviceField282.setTextOnly(true); - jPanel143.add(deviceField282); - - deviceField283.setIdentifier(""); - deviceField283.setLabelString("Value: "); - deviceField283.setOffsetNid(439); - jPanel143.add(deviceField283); - - jPanel1.add(jPanel143); - - deviceField284.setEditable(false); - deviceField284.setIdentifier(""); - deviceField284.setLabelString("Name: "); - deviceField284.setNumCols(15); - deviceField284.setOffsetNid(441); - deviceField284.setTextOnly(true); - jPanel144.add(deviceField284); - - deviceField285.setIdentifier(""); - deviceField285.setLabelString("Value: "); - deviceField285.setOffsetNid(442); - jPanel144.add(deviceField285); - - jPanel1.add(jPanel144); - - deviceField286.setEditable(false); - deviceField286.setIdentifier(""); - deviceField286.setLabelString("Name: "); - deviceField286.setNumCols(15); - deviceField286.setOffsetNid(444); - deviceField286.setTextOnly(true); - jPanel145.add(deviceField286); - - deviceField287.setIdentifier(""); - deviceField287.setLabelString("Value: "); - deviceField287.setOffsetNid(445); - jPanel145.add(deviceField287); - - jPanel1.add(jPanel145); - - deviceField288.setEditable(false); - deviceField288.setIdentifier(""); - deviceField288.setLabelString("Name: "); - deviceField288.setNumCols(15); - deviceField288.setOffsetNid(447); - deviceField288.setTextOnly(true); - jPanel146.add(deviceField288); - - deviceField289.setIdentifier(""); - deviceField289.setLabelString("Value: "); - deviceField289.setOffsetNid(448); - jPanel146.add(deviceField289); - - jPanel1.add(jPanel146); - - jScrollPane1.setViewportView(jPanel1); - - jTabbedPane1.addTab("Parameters", jScrollPane1); - - jPanel147.setLayout(new java.awt.GridLayout(40, 1)); - - jPanel148.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel148.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel1.setIdentifier(""); - deviceLabel1.setNumCols(15); - deviceLabel1.setOffsetNid(455); - deviceLabel1.setTextOnly(true); - jPanel149.add(deviceLabel1); - - deviceField290.setIdentifier(""); - deviceField290.setLabelString("Struct Value: "); - deviceField290.setNumCols(30); - deviceField290.setOffsetNid(454); - jPanel149.add(deviceField290); - - jPanel148.add(jPanel149); - - deviceField291.setIdentifier(""); - deviceField291.setLabelString("Flag:"); - deviceField291.setNumCols(20); - deviceField291.setOffsetNid(469); - jPanel150.add(deviceField291); - - deviceField292.setIdentifier(""); - deviceField292.setLabelString("Value: "); - deviceField292.setNumCols(20); - deviceField292.setOffsetNid(463); - jPanel150.add(deviceField292); - - jPanel148.add(jPanel150); - - jPanel147.add(jPanel148); - - jPanel151.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel151.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel2.setIdentifier(""); - deviceLabel2.setNumCols(15); - deviceLabel2.setOffsetNid(475); - deviceLabel2.setTextOnly(true); - jPanel152.add(deviceLabel2); - - deviceField293.setIdentifier(""); - deviceField293.setLabelString("Struct Value: "); - deviceField293.setNumCols(30); - deviceField293.setOffsetNid(474); - jPanel152.add(deviceField293); - - jPanel151.add(jPanel152); - - deviceField294.setIdentifier(""); - deviceField294.setLabelString("Flag:"); - deviceField294.setNumCols(20); - deviceField294.setOffsetNid(489); - jPanel153.add(deviceField294); - - deviceField295.setIdentifier(""); - deviceField295.setLabelString("Value: "); - deviceField295.setNumCols(20); - deviceField295.setOffsetNid(483); - jPanel153.add(deviceField295); - - jPanel151.add(jPanel153); - - jPanel147.add(jPanel151); - - jPanel154.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel154.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel3.setIdentifier(""); - deviceLabel3.setNumCols(15); - deviceLabel3.setOffsetNid(495); - deviceLabel3.setTextOnly(true); - jPanel155.add(deviceLabel3); - - deviceField296.setIdentifier(""); - deviceField296.setLabelString("Struct Value: "); - deviceField296.setNumCols(30); - deviceField296.setOffsetNid(494); - jPanel155.add(deviceField296); - - jPanel154.add(jPanel155); - - deviceField297.setIdentifier(""); - deviceField297.setLabelString("Flag:"); - deviceField297.setNumCols(20); - deviceField297.setOffsetNid(509); - jPanel156.add(deviceField297); - - deviceField298.setIdentifier(""); - deviceField298.setLabelString("Value: "); - deviceField298.setNumCols(20); - deviceField298.setOffsetNid(503); - jPanel156.add(deviceField298); - - jPanel154.add(jPanel156); - - jPanel147.add(jPanel154); - - jPanel157.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel157.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel4.setIdentifier(""); - deviceLabel4.setNumCols(15); - deviceLabel4.setOffsetNid(515); - deviceLabel4.setTextOnly(true); - jPanel158.add(deviceLabel4); - - deviceField299.setIdentifier(""); - deviceField299.setLabelString("Struct Value: "); - deviceField299.setNumCols(30); - deviceField299.setOffsetNid(514); - jPanel158.add(deviceField299); - - jPanel157.add(jPanel158); - - deviceField300.setIdentifier(""); - deviceField300.setLabelString("Flag:"); - deviceField300.setNumCols(20); - deviceField300.setOffsetNid(529); - jPanel159.add(deviceField300); - - deviceField301.setIdentifier(""); - deviceField301.setLabelString("Value: "); - deviceField301.setNumCols(20); - deviceField301.setOffsetNid(523); - jPanel159.add(deviceField301); - - jPanel157.add(jPanel159); - - jPanel147.add(jPanel157); - - jPanel160.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel160.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel5.setIdentifier(""); - deviceLabel5.setNumCols(15); - deviceLabel5.setOffsetNid(535); - deviceLabel5.setTextOnly(true); - jPanel161.add(deviceLabel5); - - deviceField302.setIdentifier(""); - deviceField302.setLabelString("Struct Value: "); - deviceField302.setNumCols(30); - deviceField302.setOffsetNid(534); - jPanel161.add(deviceField302); - - jPanel160.add(jPanel161); - - deviceField303.setIdentifier(""); - deviceField303.setLabelString("Flag:"); - deviceField303.setNumCols(20); - deviceField303.setOffsetNid(549); - jPanel162.add(deviceField303); - - deviceField304.setIdentifier(""); - deviceField304.setLabelString("Value: "); - deviceField304.setNumCols(20); - deviceField304.setOffsetNid(543); - jPanel162.add(deviceField304); - - jPanel160.add(jPanel162); - - jPanel147.add(jPanel160); - - jPanel163.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel163.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel6.setIdentifier(""); - deviceLabel6.setNumCols(15); - deviceLabel6.setOffsetNid(555); - deviceLabel6.setTextOnly(true); - jPanel164.add(deviceLabel6); - - deviceField305.setIdentifier(""); - deviceField305.setLabelString("Struct Value: "); - deviceField305.setNumCols(30); - deviceField305.setOffsetNid(554); - jPanel164.add(deviceField305); - - jPanel163.add(jPanel164); - - deviceField306.setIdentifier(""); - deviceField306.setLabelString("Flag:"); - deviceField306.setNumCols(20); - deviceField306.setOffsetNid(569); - jPanel165.add(deviceField306); - - deviceField307.setIdentifier(""); - deviceField307.setLabelString("Value: "); - deviceField307.setNumCols(20); - deviceField307.setOffsetNid(563); - jPanel165.add(deviceField307); - - jPanel163.add(jPanel165); - - jPanel147.add(jPanel163); - - jPanel166.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel166.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel7.setIdentifier(""); - deviceLabel7.setNumCols(15); - deviceLabel7.setOffsetNid(575); - deviceLabel7.setTextOnly(true); - jPanel167.add(deviceLabel7); - - deviceField308.setIdentifier(""); - deviceField308.setLabelString("Struct Value: "); - deviceField308.setNumCols(30); - deviceField308.setOffsetNid(574); - jPanel167.add(deviceField308); - - jPanel166.add(jPanel167); - - deviceField309.setIdentifier(""); - deviceField309.setLabelString("Flag:"); - deviceField309.setNumCols(20); - deviceField309.setOffsetNid(589); - jPanel168.add(deviceField309); - - deviceField310.setIdentifier(""); - deviceField310.setLabelString("Value: "); - deviceField310.setNumCols(20); - deviceField310.setOffsetNid(583); - jPanel168.add(deviceField310); - - jPanel166.add(jPanel168); - - jPanel147.add(jPanel166); - - jPanel169.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel169.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel8.setIdentifier(""); - deviceLabel8.setNumCols(15); - deviceLabel8.setOffsetNid(595); - deviceLabel8.setTextOnly(true); - jPanel170.add(deviceLabel8); - - deviceField311.setIdentifier(""); - deviceField311.setLabelString("Struct Value: "); - deviceField311.setNumCols(30); - deviceField311.setOffsetNid(594); - jPanel170.add(deviceField311); - - jPanel169.add(jPanel170); - - deviceField312.setIdentifier(""); - deviceField312.setLabelString("Flag:"); - deviceField312.setNumCols(20); - deviceField312.setOffsetNid(609); - jPanel171.add(deviceField312); - - deviceField313.setIdentifier(""); - deviceField313.setLabelString("Value: "); - deviceField313.setNumCols(20); - deviceField313.setOffsetNid(603); - jPanel171.add(deviceField313); - - jPanel169.add(jPanel171); - - jPanel147.add(jPanel169); - - jPanel172.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel172.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel9.setIdentifier(""); - deviceLabel9.setNumCols(15); - deviceLabel9.setOffsetNid(615); - deviceLabel9.setTextOnly(true); - jPanel173.add(deviceLabel9); - - deviceField314.setIdentifier(""); - deviceField314.setLabelString("Struct Value: "); - deviceField314.setNumCols(30); - deviceField314.setOffsetNid(614); - jPanel173.add(deviceField314); - - jPanel172.add(jPanel173); - - deviceField315.setIdentifier(""); - deviceField315.setLabelString("Flag:"); - deviceField315.setNumCols(20); - deviceField315.setOffsetNid(629); - jPanel174.add(deviceField315); - - deviceField316.setIdentifier(""); - deviceField316.setLabelString("Value: "); - deviceField316.setNumCols(20); - deviceField316.setOffsetNid(623); - jPanel174.add(deviceField316); - - jPanel172.add(jPanel174); - - jPanel147.add(jPanel172); - - jPanel175.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel175.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel10.setIdentifier(""); - deviceLabel10.setNumCols(15); - deviceLabel10.setOffsetNid(635); - deviceLabel10.setTextOnly(true); - jPanel176.add(deviceLabel10); - - deviceField317.setIdentifier(""); - deviceField317.setLabelString("Struct Value: "); - deviceField317.setNumCols(30); - deviceField317.setOffsetNid(634); - jPanel176.add(deviceField317); - - jPanel175.add(jPanel176); - - deviceField318.setIdentifier(""); - deviceField318.setLabelString("Flag:"); - deviceField318.setNumCols(20); - deviceField318.setOffsetNid(649); - jPanel177.add(deviceField318); - - deviceField319.setIdentifier(""); - deviceField319.setLabelString("Value: "); - deviceField319.setNumCols(20); - deviceField319.setOffsetNid(643); - jPanel177.add(deviceField319); - - jPanel175.add(jPanel177); - - jPanel147.add(jPanel175); - - jPanel178.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel178.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel11.setIdentifier(""); - deviceLabel11.setNumCols(15); - deviceLabel11.setOffsetNid(655); - deviceLabel11.setTextOnly(true); - jPanel179.add(deviceLabel11); - - deviceField320.setIdentifier(""); - deviceField320.setLabelString("Struct Value: "); - deviceField320.setNumCols(30); - deviceField320.setOffsetNid(654); - jPanel179.add(deviceField320); - - jPanel178.add(jPanel179); - - deviceField321.setIdentifier(""); - deviceField321.setLabelString("Flag:"); - deviceField321.setNumCols(20); - deviceField321.setOffsetNid(669); - jPanel180.add(deviceField321); - - deviceField322.setIdentifier(""); - deviceField322.setLabelString("Value: "); - deviceField322.setNumCols(20); - deviceField322.setOffsetNid(663); - jPanel180.add(deviceField322); - - jPanel178.add(jPanel180); - - jPanel147.add(jPanel178); - - jPanel181.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel181.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel12.setIdentifier(""); - deviceLabel12.setNumCols(15); - deviceLabel12.setOffsetNid(675); - deviceLabel12.setTextOnly(true); - jPanel182.add(deviceLabel12); - - deviceField323.setIdentifier(""); - deviceField323.setLabelString("Struct Value: "); - deviceField323.setNumCols(30); - deviceField323.setOffsetNid(674); - jPanel182.add(deviceField323); - - jPanel181.add(jPanel182); - - deviceField324.setIdentifier(""); - deviceField324.setLabelString("Flag:"); - deviceField324.setNumCols(20); - deviceField324.setOffsetNid(689); - jPanel183.add(deviceField324); - - deviceField325.setIdentifier(""); - deviceField325.setLabelString("Value: "); - deviceField325.setNumCols(20); - deviceField325.setOffsetNid(683); - jPanel183.add(deviceField325); - - jPanel181.add(jPanel183); - - jPanel147.add(jPanel181); - - jPanel184.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel184.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel13.setIdentifier(""); - deviceLabel13.setNumCols(15); - deviceLabel13.setOffsetNid(695); - deviceLabel13.setTextOnly(true); - jPanel185.add(deviceLabel13); - - deviceField326.setIdentifier(""); - deviceField326.setLabelString("Struct Value: "); - deviceField326.setNumCols(30); - deviceField326.setOffsetNid(694); - jPanel185.add(deviceField326); - - jPanel184.add(jPanel185); - - deviceField327.setIdentifier(""); - deviceField327.setLabelString("Flag:"); - deviceField327.setNumCols(20); - deviceField327.setOffsetNid(709); - jPanel186.add(deviceField327); - - deviceField328.setIdentifier(""); - deviceField328.setLabelString("Value: "); - deviceField328.setNumCols(20); - deviceField328.setOffsetNid(703); - jPanel186.add(deviceField328); - - jPanel184.add(jPanel186); - - jPanel147.add(jPanel184); - - jPanel187.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel187.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel14.setIdentifier(""); - deviceLabel14.setNumCols(15); - deviceLabel14.setOffsetNid(715); - deviceLabel14.setTextOnly(true); - jPanel188.add(deviceLabel14); - - deviceField329.setIdentifier(""); - deviceField329.setLabelString("Struct Value: "); - deviceField329.setNumCols(30); - deviceField329.setOffsetNid(714); - jPanel188.add(deviceField329); - - jPanel187.add(jPanel188); - - deviceField330.setIdentifier(""); - deviceField330.setLabelString("Flag:"); - deviceField330.setNumCols(20); - deviceField330.setOffsetNid(729); - jPanel189.add(deviceField330); - - deviceField331.setIdentifier(""); - deviceField331.setLabelString("Value: "); - deviceField331.setNumCols(20); - deviceField331.setOffsetNid(723); - jPanel189.add(deviceField331); - - jPanel187.add(jPanel189); - - jPanel147.add(jPanel187); - - jPanel190.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel190.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel15.setIdentifier(""); - deviceLabel15.setNumCols(15); - deviceLabel15.setOffsetNid(735); - deviceLabel15.setTextOnly(true); - jPanel191.add(deviceLabel15); - - deviceField332.setIdentifier(""); - deviceField332.setLabelString("Struct Value: "); - deviceField332.setNumCols(30); - deviceField332.setOffsetNid(734); - jPanel191.add(deviceField332); - - jPanel190.add(jPanel191); - - deviceField333.setIdentifier(""); - deviceField333.setLabelString("Flag:"); - deviceField333.setNumCols(20); - deviceField333.setOffsetNid(749); - jPanel192.add(deviceField333); - - deviceField334.setIdentifier(""); - deviceField334.setLabelString("Value: "); - deviceField334.setNumCols(20); - deviceField334.setOffsetNid(743); - jPanel192.add(deviceField334); - - jPanel190.add(jPanel192); - - jPanel147.add(jPanel190); - - jPanel193.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel193.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel16.setIdentifier(""); - deviceLabel16.setNumCols(15); - deviceLabel16.setOffsetNid(755); - deviceLabel16.setTextOnly(true); - jPanel194.add(deviceLabel16); - - deviceField335.setIdentifier(""); - deviceField335.setLabelString("Struct Value: "); - deviceField335.setNumCols(30); - deviceField335.setOffsetNid(754); - jPanel194.add(deviceField335); - - jPanel193.add(jPanel194); - - deviceField336.setIdentifier(""); - deviceField336.setLabelString("Flag:"); - deviceField336.setNumCols(20); - deviceField336.setOffsetNid(769); - jPanel195.add(deviceField336); - - deviceField337.setIdentifier(""); - deviceField337.setLabelString("Value: "); - deviceField337.setNumCols(20); - deviceField337.setOffsetNid(763); - jPanel195.add(deviceField337); - - jPanel193.add(jPanel195); - - jPanel147.add(jPanel193); - - jPanel196.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel196.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel17.setIdentifier(""); - deviceLabel17.setNumCols(15); - deviceLabel17.setOffsetNid(775); - deviceLabel17.setTextOnly(true); - jPanel197.add(deviceLabel17); - - deviceField338.setIdentifier(""); - deviceField338.setLabelString("Struct Value: "); - deviceField338.setNumCols(30); - deviceField338.setOffsetNid(774); - jPanel197.add(deviceField338); - - jPanel196.add(jPanel197); - - deviceField339.setIdentifier(""); - deviceField339.setLabelString("Flag:"); - deviceField339.setNumCols(20); - deviceField339.setOffsetNid(789); - jPanel198.add(deviceField339); - - deviceField340.setIdentifier(""); - deviceField340.setLabelString("Value: "); - deviceField340.setNumCols(20); - deviceField340.setOffsetNid(783); - jPanel198.add(deviceField340); - - jPanel196.add(jPanel198); - - jPanel147.add(jPanel196); - - jPanel199.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel199.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel18.setIdentifier(""); - deviceLabel18.setNumCols(15); - deviceLabel18.setOffsetNid(795); - deviceLabel18.setTextOnly(true); - jPanel200.add(deviceLabel18); - - deviceField341.setIdentifier(""); - deviceField341.setLabelString("Struct Value: "); - deviceField341.setNumCols(30); - deviceField341.setOffsetNid(794); - jPanel200.add(deviceField341); - - jPanel199.add(jPanel200); - - deviceField342.setIdentifier(""); - deviceField342.setLabelString("Flag:"); - deviceField342.setNumCols(20); - deviceField342.setOffsetNid(809); - jPanel201.add(deviceField342); - - deviceField343.setIdentifier(""); - deviceField343.setLabelString("Value: "); - deviceField343.setNumCols(20); - deviceField343.setOffsetNid(803); - jPanel201.add(deviceField343); - - jPanel199.add(jPanel201); - - jPanel147.add(jPanel199); - - jPanel202.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel202.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel19.setIdentifier(""); - deviceLabel19.setNumCols(15); - deviceLabel19.setOffsetNid(815); - deviceLabel19.setTextOnly(true); - jPanel203.add(deviceLabel19); - - deviceField344.setIdentifier(""); - deviceField344.setLabelString("Struct Value: "); - deviceField344.setNumCols(30); - deviceField344.setOffsetNid(814); - jPanel203.add(deviceField344); - - jPanel202.add(jPanel203); - - deviceField345.setIdentifier(""); - deviceField345.setLabelString("Flag:"); - deviceField345.setNumCols(20); - deviceField345.setOffsetNid(829); - jPanel204.add(deviceField345); - - deviceField346.setIdentifier(""); - deviceField346.setLabelString("Value: "); - deviceField346.setNumCols(20); - deviceField346.setOffsetNid(823); - jPanel204.add(deviceField346); - - jPanel202.add(jPanel204); - - jPanel147.add(jPanel202); - - jPanel205.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel205.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel20.setIdentifier(""); - deviceLabel20.setNumCols(15); - deviceLabel20.setOffsetNid(835); - deviceLabel20.setTextOnly(true); - jPanel206.add(deviceLabel20); - - deviceField347.setIdentifier(""); - deviceField347.setLabelString("Struct Value: "); - deviceField347.setNumCols(30); - deviceField347.setOffsetNid(834); - jPanel206.add(deviceField347); - - jPanel205.add(jPanel206); - - deviceField348.setIdentifier(""); - deviceField348.setLabelString("Flag:"); - deviceField348.setNumCols(20); - deviceField348.setOffsetNid(849); - jPanel207.add(deviceField348); - - deviceField349.setIdentifier(""); - deviceField349.setLabelString("Value: "); - deviceField349.setNumCols(20); - deviceField349.setOffsetNid(843); - jPanel207.add(deviceField349); - - jPanel205.add(jPanel207); - - jPanel147.add(jPanel205); - - jPanel208.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel208.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel21.setIdentifier(""); - deviceLabel21.setNumCols(15); - deviceLabel21.setOffsetNid(855); - deviceLabel21.setTextOnly(true); - jPanel209.add(deviceLabel21); - - deviceField350.setIdentifier(""); - deviceField350.setLabelString("Struct Value: "); - deviceField350.setNumCols(30); - deviceField350.setOffsetNid(854); - jPanel209.add(deviceField350); - - jPanel208.add(jPanel209); - - deviceField351.setIdentifier(""); - deviceField351.setLabelString("Flag:"); - deviceField351.setNumCols(20); - deviceField351.setOffsetNid(869); - jPanel210.add(deviceField351); - - deviceField352.setIdentifier(""); - deviceField352.setLabelString("Value: "); - deviceField352.setNumCols(20); - deviceField352.setOffsetNid(863); - jPanel210.add(deviceField352); - - jPanel208.add(jPanel210); - - jPanel147.add(jPanel208); - - jPanel211.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel211.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel22.setIdentifier(""); - deviceLabel22.setNumCols(15); - deviceLabel22.setOffsetNid(875); - deviceLabel22.setTextOnly(true); - jPanel212.add(deviceLabel22); - - deviceField353.setIdentifier(""); - deviceField353.setLabelString("Struct Value: "); - deviceField353.setNumCols(30); - deviceField353.setOffsetNid(874); - jPanel212.add(deviceField353); - - jPanel211.add(jPanel212); - - deviceField354.setIdentifier(""); - deviceField354.setLabelString("Flag:"); - deviceField354.setNumCols(20); - deviceField354.setOffsetNid(889); - jPanel213.add(deviceField354); - - deviceField355.setIdentifier(""); - deviceField355.setLabelString("Value: "); - deviceField355.setNumCols(20); - deviceField355.setOffsetNid(883); - jPanel213.add(deviceField355); - - jPanel211.add(jPanel213); - - jPanel147.add(jPanel211); - - jPanel214.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel214.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel23.setIdentifier(""); - deviceLabel23.setNumCols(15); - deviceLabel23.setOffsetNid(895); - deviceLabel23.setTextOnly(true); - jPanel215.add(deviceLabel23); - - deviceField356.setIdentifier(""); - deviceField356.setLabelString("Struct Value: "); - deviceField356.setNumCols(30); - deviceField356.setOffsetNid(894); - jPanel215.add(deviceField356); - - jPanel214.add(jPanel215); - - deviceField357.setIdentifier(""); - deviceField357.setLabelString("Flag:"); - deviceField357.setNumCols(20); - deviceField357.setOffsetNid(909); - jPanel216.add(deviceField357); - - deviceField358.setIdentifier(""); - deviceField358.setLabelString("Value: "); - deviceField358.setNumCols(20); - deviceField358.setOffsetNid(903); - jPanel216.add(deviceField358); - - jPanel214.add(jPanel216); - - jPanel147.add(jPanel214); - - jPanel217.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel217.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel24.setIdentifier(""); - deviceLabel24.setNumCols(15); - deviceLabel24.setOffsetNid(915); - deviceLabel24.setTextOnly(true); - jPanel218.add(deviceLabel24); - - deviceField359.setIdentifier(""); - deviceField359.setLabelString("Struct Value: "); - deviceField359.setNumCols(30); - deviceField359.setOffsetNid(914); - jPanel218.add(deviceField359); - - jPanel217.add(jPanel218); - - deviceField360.setIdentifier(""); - deviceField360.setLabelString("Flag:"); - deviceField360.setNumCols(20); - deviceField360.setOffsetNid(929); - jPanel219.add(deviceField360); - - deviceField361.setIdentifier(""); - deviceField361.setLabelString("Value: "); - deviceField361.setNumCols(20); - deviceField361.setOffsetNid(923); - jPanel219.add(deviceField361); - - jPanel217.add(jPanel219); - - jPanel147.add(jPanel217); - - jPanel220.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel220.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel25.setIdentifier(""); - deviceLabel25.setNumCols(15); - deviceLabel25.setOffsetNid(935); - deviceLabel25.setTextOnly(true); - jPanel221.add(deviceLabel25); - - deviceField362.setIdentifier(""); - deviceField362.setLabelString("Struct Value: "); - deviceField362.setNumCols(30); - deviceField362.setOffsetNid(934); - jPanel221.add(deviceField362); - - jPanel220.add(jPanel221); - - deviceField363.setIdentifier(""); - deviceField363.setLabelString("Flag:"); - deviceField363.setNumCols(20); - deviceField363.setOffsetNid(949); - jPanel222.add(deviceField363); - - deviceField364.setIdentifier(""); - deviceField364.setLabelString("Value: "); - deviceField364.setNumCols(20); - deviceField364.setOffsetNid(943); - jPanel222.add(deviceField364); - - jPanel220.add(jPanel222); - - jPanel147.add(jPanel220); - - jPanel223.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel223.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel26.setIdentifier(""); - deviceLabel26.setNumCols(15); - deviceLabel26.setOffsetNid(955); - deviceLabel26.setTextOnly(true); - jPanel224.add(deviceLabel26); - - deviceField365.setIdentifier(""); - deviceField365.setLabelString("Struct Value: "); - deviceField365.setNumCols(30); - deviceField365.setOffsetNid(954); - jPanel224.add(deviceField365); - - jPanel223.add(jPanel224); - - deviceField366.setIdentifier(""); - deviceField366.setLabelString("Flag:"); - deviceField366.setNumCols(20); - deviceField366.setOffsetNid(969); - jPanel225.add(deviceField366); - - deviceField367.setIdentifier(""); - deviceField367.setLabelString("Value: "); - deviceField367.setNumCols(20); - deviceField367.setOffsetNid(963); - jPanel225.add(deviceField367); - - jPanel223.add(jPanel225); - - jPanel147.add(jPanel223); - - jPanel226.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel226.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel27.setIdentifier(""); - deviceLabel27.setNumCols(15); - deviceLabel27.setOffsetNid(975); - deviceLabel27.setTextOnly(true); - jPanel227.add(deviceLabel27); - - deviceField368.setIdentifier(""); - deviceField368.setLabelString("Struct Value: "); - deviceField368.setNumCols(30); - deviceField368.setOffsetNid(974); - jPanel227.add(deviceField368); - - jPanel226.add(jPanel227); - - deviceField369.setIdentifier(""); - deviceField369.setLabelString("Flag:"); - deviceField369.setNumCols(20); - deviceField369.setOffsetNid(989); - jPanel228.add(deviceField369); - - deviceField370.setIdentifier(""); - deviceField370.setLabelString("Value: "); - deviceField370.setNumCols(20); - deviceField370.setOffsetNid(983); - jPanel228.add(deviceField370); - - jPanel226.add(jPanel228); - - jPanel147.add(jPanel226); - - jPanel229.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel229.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel28.setIdentifier(""); - deviceLabel28.setNumCols(15); - deviceLabel28.setOffsetNid(995); - deviceLabel28.setTextOnly(true); - jPanel230.add(deviceLabel28); - - deviceField371.setIdentifier(""); - deviceField371.setLabelString("Struct Value: "); - deviceField371.setNumCols(30); - deviceField371.setOffsetNid(994); - jPanel230.add(deviceField371); - - jPanel229.add(jPanel230); - - deviceField372.setIdentifier(""); - deviceField372.setLabelString("Flag:"); - deviceField372.setNumCols(20); - deviceField372.setOffsetNid(1009); - jPanel231.add(deviceField372); - - deviceField373.setIdentifier(""); - deviceField373.setLabelString("Value: "); - deviceField373.setNumCols(20); - deviceField373.setOffsetNid(1003); - jPanel231.add(deviceField373); - - jPanel229.add(jPanel231); - - jPanel147.add(jPanel229); - - jPanel232.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel232.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel29.setIdentifier(""); - deviceLabel29.setNumCols(15); - deviceLabel29.setOffsetNid(995); - deviceLabel29.setTextOnly(true); - jPanel233.add(deviceLabel29); - - deviceField374.setIdentifier(""); - deviceField374.setLabelString("Struct Value: "); - deviceField374.setNumCols(30); - deviceField374.setOffsetNid(994); - jPanel233.add(deviceField374); - - jPanel232.add(jPanel233); - - deviceField375.setIdentifier(""); - deviceField375.setLabelString("Flag:"); - deviceField375.setNumCols(20); - deviceField375.setOffsetNid(1009); - jPanel234.add(deviceField375); - - deviceField376.setIdentifier(""); - deviceField376.setLabelString("Value: "); - deviceField376.setNumCols(20); - deviceField376.setOffsetNid(1003); - jPanel234.add(deviceField376); - - jPanel232.add(jPanel234); - - jPanel147.add(jPanel232); - - jPanel235.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel235.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel30.setIdentifier(""); - deviceLabel30.setNumCols(15); - deviceLabel30.setOffsetNid(1015); - deviceLabel30.setTextOnly(true); - jPanel236.add(deviceLabel30); - - deviceField377.setIdentifier(""); - deviceField377.setLabelString("Struct Value: "); - deviceField377.setNumCols(30); - deviceField377.setOffsetNid(1014); - jPanel236.add(deviceField377); - - jPanel235.add(jPanel236); - - deviceField378.setIdentifier(""); - deviceField378.setLabelString("Flag:"); - deviceField378.setNumCols(20); - deviceField378.setOffsetNid(1029); - jPanel237.add(deviceField378); - - deviceField379.setIdentifier(""); - deviceField379.setLabelString("Value: "); - deviceField379.setNumCols(20); - deviceField379.setOffsetNid(1023); - jPanel237.add(deviceField379); - - jPanel235.add(jPanel237); - - jPanel147.add(jPanel235); - - jPanel238.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel238.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel31.setIdentifier(""); - deviceLabel31.setNumCols(15); - deviceLabel31.setOffsetNid(1035); - deviceLabel31.setTextOnly(true); - jPanel239.add(deviceLabel31); - - deviceField380.setIdentifier(""); - deviceField380.setLabelString("Struct Value: "); - deviceField380.setNumCols(30); - deviceField380.setOffsetNid(1034); - jPanel239.add(deviceField380); - - jPanel238.add(jPanel239); - - deviceField381.setIdentifier(""); - deviceField381.setLabelString("Flag:"); - deviceField381.setNumCols(20); - deviceField381.setOffsetNid(1049); - jPanel240.add(deviceField381); - - deviceField382.setIdentifier(""); - deviceField382.setLabelString("Value: "); - deviceField382.setNumCols(20); - deviceField382.setOffsetNid(1043); - jPanel240.add(deviceField382); - - jPanel238.add(jPanel240); - - jPanel147.add(jPanel238); - - jPanel241.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel241.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel32.setIdentifier(""); - deviceLabel32.setNumCols(15); - deviceLabel32.setOffsetNid(1055); - deviceLabel32.setTextOnly(true); - jPanel242.add(deviceLabel32); - - deviceField383.setIdentifier(""); - deviceField383.setLabelString("Struct Value: "); - deviceField383.setNumCols(30); - deviceField383.setOffsetNid(1054); - jPanel242.add(deviceField383); - - jPanel241.add(jPanel242); - - deviceField384.setIdentifier(""); - deviceField384.setLabelString("Flag:"); - deviceField384.setNumCols(20); - deviceField384.setOffsetNid(1069); - jPanel243.add(deviceField384); - - deviceField385.setIdentifier(""); - deviceField385.setLabelString("Value: "); - deviceField385.setNumCols(20); - deviceField385.setOffsetNid(1063); - jPanel243.add(deviceField385); - - jPanel241.add(jPanel243); - - jPanel147.add(jPanel241); - - jPanel244.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel244.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel33.setIdentifier(""); - deviceLabel33.setNumCols(15); - deviceLabel33.setOffsetNid(1075); - deviceLabel33.setTextOnly(true); - jPanel245.add(deviceLabel33); - - deviceField386.setIdentifier(""); - deviceField386.setLabelString("Struct Value: "); - deviceField386.setNumCols(30); - deviceField386.setOffsetNid(1074); - jPanel245.add(deviceField386); - - jPanel244.add(jPanel245); - - deviceField387.setIdentifier(""); - deviceField387.setLabelString("Flag:"); - deviceField387.setNumCols(20); - deviceField387.setOffsetNid(1089); - jPanel246.add(deviceField387); - - deviceField388.setIdentifier(""); - deviceField388.setLabelString("Value: "); - deviceField388.setNumCols(20); - deviceField388.setOffsetNid(1083); - jPanel246.add(deviceField388); - - jPanel244.add(jPanel246); - - jPanel147.add(jPanel244); - - jPanel247.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel247.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel34.setIdentifier(""); - deviceLabel34.setNumCols(15); - deviceLabel34.setOffsetNid(1095); - deviceLabel34.setTextOnly(true); - jPanel248.add(deviceLabel34); - - deviceField389.setIdentifier(""); - deviceField389.setLabelString("Struct Value: "); - deviceField389.setNumCols(30); - deviceField389.setOffsetNid(1094); - jPanel248.add(deviceField389); - - jPanel247.add(jPanel248); - - deviceField390.setIdentifier(""); - deviceField390.setLabelString("Flag:"); - deviceField390.setNumCols(20); - deviceField390.setOffsetNid(1109); - jPanel249.add(deviceField390); - - deviceField391.setIdentifier(""); - deviceField391.setLabelString("Value: "); - deviceField391.setNumCols(20); - deviceField391.setOffsetNid(1103); - jPanel249.add(deviceField391); - - jPanel247.add(jPanel249); - - jPanel147.add(jPanel247); - - jPanel250.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel250.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel35.setIdentifier(""); - deviceLabel35.setNumCols(15); - deviceLabel35.setOffsetNid(1115); - deviceLabel35.setTextOnly(true); - jPanel251.add(deviceLabel35); - - deviceField392.setIdentifier(""); - deviceField392.setLabelString("Struct Value: "); - deviceField392.setNumCols(30); - deviceField392.setOffsetNid(1114); - jPanel251.add(deviceField392); - - jPanel250.add(jPanel251); - - deviceField393.setIdentifier(""); - deviceField393.setLabelString("Flag:"); - deviceField393.setNumCols(20); - deviceField393.setOffsetNid(1129); - jPanel252.add(deviceField393); - - deviceField394.setIdentifier(""); - deviceField394.setLabelString("Value: "); - deviceField394.setNumCols(20); - deviceField394.setOffsetNid(1123); - jPanel252.add(deviceField394); - - jPanel250.add(jPanel252); - - jPanel147.add(jPanel250); - - jPanel253.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel253.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel36.setIdentifier(""); - deviceLabel36.setNumCols(15); - deviceLabel36.setOffsetNid(1135); - deviceLabel36.setTextOnly(true); - jPanel254.add(deviceLabel36); - - deviceField395.setIdentifier(""); - deviceField395.setLabelString("Struct Value: "); - deviceField395.setNumCols(30); - deviceField395.setOffsetNid(1134); - jPanel254.add(deviceField395); - - jPanel253.add(jPanel254); - - deviceField396.setIdentifier(""); - deviceField396.setLabelString("Flag:"); - deviceField396.setNumCols(20); - deviceField396.setOffsetNid(1149); - jPanel255.add(deviceField396); - - deviceField397.setIdentifier(""); - deviceField397.setLabelString("Value: "); - deviceField397.setNumCols(20); - deviceField397.setOffsetNid(1143); - jPanel255.add(deviceField397); - - jPanel253.add(jPanel255); - - jPanel147.add(jPanel253); - - jPanel256.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel256.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel37.setIdentifier(""); - deviceLabel37.setNumCols(15); - deviceLabel37.setOffsetNid(1155); - deviceLabel37.setTextOnly(true); - jPanel257.add(deviceLabel37); - - deviceField398.setIdentifier(""); - deviceField398.setLabelString("Struct Value: "); - deviceField398.setNumCols(30); - deviceField398.setOffsetNid(1154); - jPanel257.add(deviceField398); - - jPanel256.add(jPanel257); - - deviceField399.setIdentifier(""); - deviceField399.setLabelString("Flag:"); - deviceField399.setNumCols(20); - deviceField399.setOffsetNid(1169); - jPanel258.add(deviceField399); - - deviceField400.setIdentifier(""); - deviceField400.setLabelString("Value: "); - deviceField400.setNumCols(20); - deviceField400.setOffsetNid(1163); - jPanel258.add(deviceField400); - - jPanel256.add(jPanel258); - - jPanel147.add(jPanel256); - - jPanel259.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel259.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel38.setIdentifier(""); - deviceLabel38.setNumCols(15); - deviceLabel38.setOffsetNid(1175); - deviceLabel38.setTextOnly(true); - jPanel260.add(deviceLabel38); - - deviceField401.setIdentifier(""); - deviceField401.setLabelString("Struct Value: "); - deviceField401.setNumCols(30); - deviceField401.setOffsetNid(1174); - jPanel260.add(deviceField401); - - jPanel259.add(jPanel260); - - deviceField402.setIdentifier(""); - deviceField402.setLabelString("Flag:"); - deviceField402.setNumCols(20); - deviceField402.setOffsetNid(1189); - jPanel261.add(deviceField402); - - deviceField403.setIdentifier(""); - deviceField403.setLabelString("Value: "); - deviceField403.setNumCols(20); - deviceField403.setOffsetNid(1183); - jPanel261.add(deviceField403); - - jPanel259.add(jPanel261); - - jPanel147.add(jPanel259); - - jPanel262.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel262.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel39.setIdentifier(""); - deviceLabel39.setNumCols(15); - deviceLabel39.setOffsetNid(1195); - deviceLabel39.setTextOnly(true); - jPanel263.add(deviceLabel39); - - deviceField404.setIdentifier(""); - deviceField404.setLabelString("Struct Value: "); - deviceField404.setNumCols(30); - deviceField404.setOffsetNid(1194); - jPanel263.add(deviceField404); - - jPanel262.add(jPanel263); - - deviceField405.setIdentifier(""); - deviceField405.setLabelString("Flag:"); - deviceField405.setNumCols(20); - deviceField405.setOffsetNid(1209); - jPanel264.add(deviceField405); - - deviceField406.setIdentifier(""); - deviceField406.setLabelString("Value: "); - deviceField406.setNumCols(20); - deviceField406.setOffsetNid(1203); - jPanel264.add(deviceField406); - - jPanel262.add(jPanel264); - - jPanel147.add(jPanel262); - - jPanel265.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); - jPanel265.setLayout(new java.awt.GridLayout(2, 1)); - - deviceLabel40.setIdentifier(""); - deviceLabel40.setNumCols(15); - deviceLabel40.setOffsetNid(1215); - deviceLabel40.setTextOnly(true); - jPanel266.add(deviceLabel40); - - deviceField407.setIdentifier(""); - deviceField407.setLabelString("Struct Value: "); - deviceField407.setNumCols(30); - deviceField407.setOffsetNid(1214); - jPanel266.add(deviceField407); - - jPanel265.add(jPanel266); - - deviceField408.setIdentifier(""); - deviceField408.setLabelString("Flag:"); - deviceField408.setNumCols(20); - deviceField408.setOffsetNid(1229); - jPanel267.add(deviceField408); - - deviceField409.setIdentifier(""); - deviceField409.setLabelString("Value: "); - deviceField409.setNumCols(20); - deviceField409.setOffsetNid(1223); - jPanel267.add(deviceField409); - - jPanel265.add(jPanel267); - - jPanel147.add(jPanel265); - - jScrollPane2.setViewportView(jPanel147); - - jTabbedPane1.addTab("Inputs", jScrollPane2); + deviceParameters1.setNumParameters(144); + deviceParameters1.setOffsetNid(4); + deviceParameters1.setParameterOffset(4); + jTabbedPane1.addTab("Parameters", deviceParameters1); getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); }// //GEN-END:initComponents @@ -4262,723 +68,10 @@ private void initComponents() { // Variables declaration - do not modify//GEN-BEGIN:variables private DeviceButtons deviceButtons1; private DeviceField deviceField1; - private DeviceField deviceField10; - private DeviceField deviceField100; - private DeviceField deviceField101; - private DeviceField deviceField102; - private DeviceField deviceField103; - private DeviceField deviceField104; - private DeviceField deviceField105; - private DeviceField deviceField106; - private DeviceField deviceField107; - private DeviceField deviceField108; - private DeviceField deviceField109; - private DeviceField deviceField11; - private DeviceField deviceField110; - private DeviceField deviceField111; - private DeviceField deviceField112; - private DeviceField deviceField113; - private DeviceField deviceField114; - private DeviceField deviceField115; - private DeviceField deviceField116; - private DeviceField deviceField117; - private DeviceField deviceField118; - private DeviceField deviceField119; - private DeviceField deviceField12; - private DeviceField deviceField120; - private DeviceField deviceField121; - private DeviceField deviceField122; - private DeviceField deviceField123; - private DeviceField deviceField124; - private DeviceField deviceField125; - private DeviceField deviceField126; - private DeviceField deviceField127; - private DeviceField deviceField128; - private DeviceField deviceField129; - private DeviceField deviceField13; - private DeviceField deviceField130; - private DeviceField deviceField131; - private DeviceField deviceField132; - private DeviceField deviceField133; - private DeviceField deviceField134; - private DeviceField deviceField135; - private DeviceField deviceField136; - private DeviceField deviceField137; - private DeviceField deviceField138; - private DeviceField deviceField139; - private DeviceField deviceField14; - private DeviceField deviceField140; - private DeviceField deviceField141; - private DeviceField deviceField142; - private DeviceField deviceField143; - private DeviceField deviceField144; - private DeviceField deviceField145; - private DeviceField deviceField146; - private DeviceField deviceField147; - private DeviceField deviceField148; - private DeviceField deviceField149; - private DeviceField deviceField15; - private DeviceField deviceField150; - private DeviceField deviceField151; - private DeviceField deviceField152; - private DeviceField deviceField153; - private DeviceField deviceField154; - private DeviceField deviceField155; - private DeviceField deviceField156; - private DeviceField deviceField157; - private DeviceField deviceField158; - private DeviceField deviceField159; - private DeviceField deviceField16; - private DeviceField deviceField160; - private DeviceField deviceField161; - private DeviceField deviceField162; - private DeviceField deviceField163; - private DeviceField deviceField164; - private DeviceField deviceField165; - private DeviceField deviceField166; - private DeviceField deviceField167; - private DeviceField deviceField168; - private DeviceField deviceField169; - private DeviceField deviceField17; - private DeviceField deviceField170; - private DeviceField deviceField171; - private DeviceField deviceField172; - private DeviceField deviceField173; - private DeviceField deviceField174; - private DeviceField deviceField175; - private DeviceField deviceField176; - private DeviceField deviceField177; - private DeviceField deviceField178; - private DeviceField deviceField179; - private DeviceField deviceField18; - private DeviceField deviceField180; - private DeviceField deviceField181; - private DeviceField deviceField182; - private DeviceField deviceField183; - private DeviceField deviceField184; - private DeviceField deviceField185; - private DeviceField deviceField186; - private DeviceField deviceField187; - private DeviceField deviceField188; - private DeviceField deviceField189; - private DeviceField deviceField19; - private DeviceField deviceField190; - private DeviceField deviceField191; - private DeviceField deviceField192; - private DeviceField deviceField193; - private DeviceField deviceField194; - private DeviceField deviceField195; - private DeviceField deviceField196; - private DeviceField deviceField197; - private DeviceField deviceField198; - private DeviceField deviceField199; - private DeviceField deviceField2; - private DeviceField deviceField20; - private DeviceField deviceField200; - private DeviceField deviceField201; - private DeviceField deviceField202; - private DeviceField deviceField203; - private DeviceField deviceField204; - private DeviceField deviceField205; - private DeviceField deviceField206; - private DeviceField deviceField207; - private DeviceField deviceField208; - private DeviceField deviceField209; - private DeviceField deviceField21; - private DeviceField deviceField210; - private DeviceField deviceField211; - private DeviceField deviceField212; - private DeviceField deviceField213; - private DeviceField deviceField214; - private DeviceField deviceField215; - private DeviceField deviceField216; - private DeviceField deviceField217; - private DeviceField deviceField218; - private DeviceField deviceField219; - private DeviceField deviceField22; - private DeviceField deviceField220; - private DeviceField deviceField221; - private DeviceField deviceField222; - private DeviceField deviceField223; - private DeviceField deviceField224; - private DeviceField deviceField225; - private DeviceField deviceField226; - private DeviceField deviceField227; - private DeviceField deviceField228; - private DeviceField deviceField229; - private DeviceField deviceField23; - private DeviceField deviceField230; - private DeviceField deviceField231; - private DeviceField deviceField232; - private DeviceField deviceField233; - private DeviceField deviceField234; - private DeviceField deviceField235; - private DeviceField deviceField236; - private DeviceField deviceField237; - private DeviceField deviceField238; - private DeviceField deviceField239; - private DeviceField deviceField24; - private DeviceField deviceField240; - private DeviceField deviceField241; - private DeviceField deviceField242; - private DeviceField deviceField243; - private DeviceField deviceField244; - private DeviceField deviceField245; - private DeviceField deviceField246; - private DeviceField deviceField247; - private DeviceField deviceField248; - private DeviceField deviceField249; - private DeviceField deviceField25; - private DeviceField deviceField250; - private DeviceField deviceField251; - private DeviceField deviceField252; - private DeviceField deviceField253; - private DeviceField deviceField254; - private DeviceField deviceField255; - private DeviceField deviceField256; - private DeviceField deviceField257; - private DeviceField deviceField258; - private DeviceField deviceField259; - private DeviceField deviceField26; - private DeviceField deviceField260; - private DeviceField deviceField261; - private DeviceField deviceField262; - private DeviceField deviceField263; - private DeviceField deviceField264; - private DeviceField deviceField265; - private DeviceField deviceField266; - private DeviceField deviceField267; - private DeviceField deviceField268; - private DeviceField deviceField269; - private DeviceField deviceField27; - private DeviceField deviceField270; - private DeviceField deviceField271; - private DeviceField deviceField272; - private DeviceField deviceField273; - private DeviceField deviceField274; - private DeviceField deviceField275; - private DeviceField deviceField276; - private DeviceField deviceField277; - private DeviceField deviceField278; - private DeviceField deviceField279; - private DeviceField deviceField28; - private DeviceField deviceField280; - private DeviceField deviceField281; - private DeviceField deviceField282; - private DeviceField deviceField283; - private DeviceField deviceField284; - private DeviceField deviceField285; - private DeviceField deviceField286; - private DeviceField deviceField287; - private DeviceField deviceField288; - private DeviceField deviceField289; - private DeviceField deviceField29; - private DeviceField deviceField290; - private DeviceField deviceField291; - private DeviceField deviceField292; - private DeviceField deviceField293; - private DeviceField deviceField294; - private DeviceField deviceField295; - private DeviceField deviceField296; - private DeviceField deviceField297; - private DeviceField deviceField298; - private DeviceField deviceField299; - private DeviceField deviceField3; - private DeviceField deviceField30; - private DeviceField deviceField300; - private DeviceField deviceField301; - private DeviceField deviceField302; - private DeviceField deviceField303; - private DeviceField deviceField304; - private DeviceField deviceField305; - private DeviceField deviceField306; - private DeviceField deviceField307; - private DeviceField deviceField308; - private DeviceField deviceField309; - private DeviceField deviceField31; - private DeviceField deviceField310; - private DeviceField deviceField311; - private DeviceField deviceField312; - private DeviceField deviceField313; - private DeviceField deviceField314; - private DeviceField deviceField315; - private DeviceField deviceField316; - private DeviceField deviceField317; - private DeviceField deviceField318; - private DeviceField deviceField319; - private DeviceField deviceField32; - private DeviceField deviceField320; - private DeviceField deviceField321; - private DeviceField deviceField322; - private DeviceField deviceField323; - private DeviceField deviceField324; - private DeviceField deviceField325; - private DeviceField deviceField326; - private DeviceField deviceField327; - private DeviceField deviceField328; - private DeviceField deviceField329; - private DeviceField deviceField33; - private DeviceField deviceField330; - private DeviceField deviceField331; - private DeviceField deviceField332; - private DeviceField deviceField333; - private DeviceField deviceField334; - private DeviceField deviceField335; - private DeviceField deviceField336; - private DeviceField deviceField337; - private DeviceField deviceField338; - private DeviceField deviceField339; - private DeviceField deviceField34; - private DeviceField deviceField340; - private DeviceField deviceField341; - private DeviceField deviceField342; - private DeviceField deviceField343; - private DeviceField deviceField344; - private DeviceField deviceField345; - private DeviceField deviceField346; - private DeviceField deviceField347; - private DeviceField deviceField348; - private DeviceField deviceField349; - private DeviceField deviceField35; - private DeviceField deviceField350; - private DeviceField deviceField351; - private DeviceField deviceField352; - private DeviceField deviceField353; - private DeviceField deviceField354; - private DeviceField deviceField355; - private DeviceField deviceField356; - private DeviceField deviceField357; - private DeviceField deviceField358; - private DeviceField deviceField359; - private DeviceField deviceField36; - private DeviceField deviceField360; - private DeviceField deviceField361; - private DeviceField deviceField362; - private DeviceField deviceField363; - private DeviceField deviceField364; - private DeviceField deviceField365; - private DeviceField deviceField366; - private DeviceField deviceField367; - private DeviceField deviceField368; - private DeviceField deviceField369; - private DeviceField deviceField37; - private DeviceField deviceField370; - private DeviceField deviceField371; - private DeviceField deviceField372; - private DeviceField deviceField373; - private DeviceField deviceField374; - private DeviceField deviceField375; - private DeviceField deviceField376; - private DeviceField deviceField377; - private DeviceField deviceField378; - private DeviceField deviceField379; - private DeviceField deviceField38; - private DeviceField deviceField380; - private DeviceField deviceField381; - private DeviceField deviceField382; - private DeviceField deviceField383; - private DeviceField deviceField384; - private DeviceField deviceField385; - private DeviceField deviceField386; - private DeviceField deviceField387; - private DeviceField deviceField388; - private DeviceField deviceField389; - private DeviceField deviceField39; - private DeviceField deviceField390; - private DeviceField deviceField391; - private DeviceField deviceField392; - private DeviceField deviceField393; - private DeviceField deviceField394; - private DeviceField deviceField395; - private DeviceField deviceField396; - private DeviceField deviceField397; - private DeviceField deviceField398; - private DeviceField deviceField399; - private DeviceField deviceField4; - private DeviceField deviceField40; - private DeviceField deviceField400; - private DeviceField deviceField401; - private DeviceField deviceField402; - private DeviceField deviceField403; - private DeviceField deviceField404; - private DeviceField deviceField405; - private DeviceField deviceField406; - private DeviceField deviceField407; - private DeviceField deviceField408; - private DeviceField deviceField409; - private DeviceField deviceField41; - private DeviceField deviceField42; - private DeviceField deviceField43; - private DeviceField deviceField44; - private DeviceField deviceField45; - private DeviceField deviceField46; - private DeviceField deviceField47; - private DeviceField deviceField48; - private DeviceField deviceField49; - private DeviceField deviceField5; - private DeviceField deviceField50; - private DeviceField deviceField51; - private DeviceField deviceField52; - private DeviceField deviceField53; - private DeviceField deviceField54; - private DeviceField deviceField55; - private DeviceField deviceField56; - private DeviceField deviceField57; - private DeviceField deviceField58; - private DeviceField deviceField59; - private DeviceField deviceField6; - private DeviceField deviceField60; - private DeviceField deviceField61; - private DeviceField deviceField62; - private DeviceField deviceField63; - private DeviceField deviceField64; - private DeviceField deviceField65; - private DeviceField deviceField66; - private DeviceField deviceField67; - private DeviceField deviceField68; - private DeviceField deviceField69; - private DeviceField deviceField7; - private DeviceField deviceField70; - private DeviceField deviceField71; - private DeviceField deviceField72; - private DeviceField deviceField73; - private DeviceField deviceField74; - private DeviceField deviceField75; - private DeviceField deviceField76; - private DeviceField deviceField77; - private DeviceField deviceField78; - private DeviceField deviceField79; - private DeviceField deviceField8; - private DeviceField deviceField80; - private DeviceField deviceField81; - private DeviceField deviceField82; - private DeviceField deviceField83; - private DeviceField deviceField84; - private DeviceField deviceField85; - private DeviceField deviceField86; - private DeviceField deviceField87; - private DeviceField deviceField88; - private DeviceField deviceField89; - private DeviceField deviceField9; - private DeviceField deviceField90; - private DeviceField deviceField91; - private DeviceField deviceField92; - private DeviceField deviceField93; - private DeviceField deviceField94; - private DeviceField deviceField95; - private DeviceField deviceField96; - private DeviceField deviceField97; - private DeviceField deviceField98; - private DeviceField deviceField99; - private DeviceLabel deviceLabel1; - private DeviceLabel deviceLabel10; - private DeviceLabel deviceLabel11; - private DeviceLabel deviceLabel12; - private DeviceLabel deviceLabel13; - private DeviceLabel deviceLabel14; - private DeviceLabel deviceLabel15; - private DeviceLabel deviceLabel16; - private DeviceLabel deviceLabel17; - private DeviceLabel deviceLabel18; - private DeviceLabel deviceLabel19; - private DeviceLabel deviceLabel2; - private DeviceLabel deviceLabel20; - private DeviceLabel deviceLabel21; - private DeviceLabel deviceLabel22; - private DeviceLabel deviceLabel23; - private DeviceLabel deviceLabel24; - private DeviceLabel deviceLabel25; - private DeviceLabel deviceLabel26; - private DeviceLabel deviceLabel27; - private DeviceLabel deviceLabel28; - private DeviceLabel deviceLabel29; - private DeviceLabel deviceLabel3; - private DeviceLabel deviceLabel30; - private DeviceLabel deviceLabel31; - private DeviceLabel deviceLabel32; - private DeviceLabel deviceLabel33; - private DeviceLabel deviceLabel34; - private DeviceLabel deviceLabel35; - private DeviceLabel deviceLabel36; - private DeviceLabel deviceLabel37; - private DeviceLabel deviceLabel38; - private DeviceLabel deviceLabel39; - private DeviceLabel deviceLabel4; - private DeviceLabel deviceLabel40; - private DeviceLabel deviceLabel5; - private DeviceLabel deviceLabel6; - private DeviceLabel deviceLabel7; - private DeviceLabel deviceLabel8; - private DeviceLabel deviceLabel9; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel10; - private javax.swing.JPanel jPanel100; - private javax.swing.JPanel jPanel101; - private javax.swing.JPanel jPanel102; - private javax.swing.JPanel jPanel103; - private javax.swing.JPanel jPanel104; - private javax.swing.JPanel jPanel105; - private javax.swing.JPanel jPanel106; - private javax.swing.JPanel jPanel107; - private javax.swing.JPanel jPanel108; - private javax.swing.JPanel jPanel109; - private javax.swing.JPanel jPanel11; - private javax.swing.JPanel jPanel110; - private javax.swing.JPanel jPanel111; - private javax.swing.JPanel jPanel112; - private javax.swing.JPanel jPanel113; - private javax.swing.JPanel jPanel114; - private javax.swing.JPanel jPanel115; - private javax.swing.JPanel jPanel116; - private javax.swing.JPanel jPanel117; - private javax.swing.JPanel jPanel118; - private javax.swing.JPanel jPanel119; - private javax.swing.JPanel jPanel12; - private javax.swing.JPanel jPanel120; - private javax.swing.JPanel jPanel121; - private javax.swing.JPanel jPanel122; - private javax.swing.JPanel jPanel123; - private javax.swing.JPanel jPanel124; - private javax.swing.JPanel jPanel125; - private javax.swing.JPanel jPanel126; - private javax.swing.JPanel jPanel127; - private javax.swing.JPanel jPanel128; - private javax.swing.JPanel jPanel129; - private javax.swing.JPanel jPanel13; - private javax.swing.JPanel jPanel130; - private javax.swing.JPanel jPanel131; - private javax.swing.JPanel jPanel132; - private javax.swing.JPanel jPanel133; - private javax.swing.JPanel jPanel134; - private javax.swing.JPanel jPanel135; - private javax.swing.JPanel jPanel136; - private javax.swing.JPanel jPanel137; - private javax.swing.JPanel jPanel138; - private javax.swing.JPanel jPanel139; - private javax.swing.JPanel jPanel14; - private javax.swing.JPanel jPanel140; - private javax.swing.JPanel jPanel141; - private javax.swing.JPanel jPanel142; - private javax.swing.JPanel jPanel143; - private javax.swing.JPanel jPanel144; - private javax.swing.JPanel jPanel145; - private javax.swing.JPanel jPanel146; - private javax.swing.JPanel jPanel147; - private javax.swing.JPanel jPanel148; - private javax.swing.JPanel jPanel149; - private javax.swing.JPanel jPanel15; - private javax.swing.JPanel jPanel150; - private javax.swing.JPanel jPanel151; - private javax.swing.JPanel jPanel152; - private javax.swing.JPanel jPanel153; - private javax.swing.JPanel jPanel154; - private javax.swing.JPanel jPanel155; - private javax.swing.JPanel jPanel156; - private javax.swing.JPanel jPanel157; - private javax.swing.JPanel jPanel158; - private javax.swing.JPanel jPanel159; - private javax.swing.JPanel jPanel16; - private javax.swing.JPanel jPanel160; - private javax.swing.JPanel jPanel161; - private javax.swing.JPanel jPanel162; - private javax.swing.JPanel jPanel163; - private javax.swing.JPanel jPanel164; - private javax.swing.JPanel jPanel165; - private javax.swing.JPanel jPanel166; - private javax.swing.JPanel jPanel167; - private javax.swing.JPanel jPanel168; - private javax.swing.JPanel jPanel169; - private javax.swing.JPanel jPanel17; - private javax.swing.JPanel jPanel170; - private javax.swing.JPanel jPanel171; - private javax.swing.JPanel jPanel172; - private javax.swing.JPanel jPanel173; - private javax.swing.JPanel jPanel174; - private javax.swing.JPanel jPanel175; - private javax.swing.JPanel jPanel176; - private javax.swing.JPanel jPanel177; - private javax.swing.JPanel jPanel178; - private javax.swing.JPanel jPanel179; - private javax.swing.JPanel jPanel18; - private javax.swing.JPanel jPanel180; - private javax.swing.JPanel jPanel181; - private javax.swing.JPanel jPanel182; - private javax.swing.JPanel jPanel183; - private javax.swing.JPanel jPanel184; - private javax.swing.JPanel jPanel185; - private javax.swing.JPanel jPanel186; - private javax.swing.JPanel jPanel187; - private javax.swing.JPanel jPanel188; - private javax.swing.JPanel jPanel189; - private javax.swing.JPanel jPanel19; - private javax.swing.JPanel jPanel190; - private javax.swing.JPanel jPanel191; - private javax.swing.JPanel jPanel192; - private javax.swing.JPanel jPanel193; - private javax.swing.JPanel jPanel194; - private javax.swing.JPanel jPanel195; - private javax.swing.JPanel jPanel196; - private javax.swing.JPanel jPanel197; - private javax.swing.JPanel jPanel198; - private javax.swing.JPanel jPanel199; + private DeviceInputs deviceInputs1; + private DeviceOutputs deviceOutputs1; + private DeviceParameters deviceParameters1; private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel20; - private javax.swing.JPanel jPanel200; - private javax.swing.JPanel jPanel201; - private javax.swing.JPanel jPanel202; - private javax.swing.JPanel jPanel203; - private javax.swing.JPanel jPanel204; - private javax.swing.JPanel jPanel205; - private javax.swing.JPanel jPanel206; - private javax.swing.JPanel jPanel207; - private javax.swing.JPanel jPanel208; - private javax.swing.JPanel jPanel209; - private javax.swing.JPanel jPanel21; - private javax.swing.JPanel jPanel210; - private javax.swing.JPanel jPanel211; - private javax.swing.JPanel jPanel212; - private javax.swing.JPanel jPanel213; - private javax.swing.JPanel jPanel214; - private javax.swing.JPanel jPanel215; - private javax.swing.JPanel jPanel216; - private javax.swing.JPanel jPanel217; - private javax.swing.JPanel jPanel218; - private javax.swing.JPanel jPanel219; - private javax.swing.JPanel jPanel22; - private javax.swing.JPanel jPanel220; - private javax.swing.JPanel jPanel221; - private javax.swing.JPanel jPanel222; - private javax.swing.JPanel jPanel223; - private javax.swing.JPanel jPanel224; - private javax.swing.JPanel jPanel225; - private javax.swing.JPanel jPanel226; - private javax.swing.JPanel jPanel227; - private javax.swing.JPanel jPanel228; - private javax.swing.JPanel jPanel229; - private javax.swing.JPanel jPanel23; - private javax.swing.JPanel jPanel230; - private javax.swing.JPanel jPanel231; - private javax.swing.JPanel jPanel232; - private javax.swing.JPanel jPanel233; - private javax.swing.JPanel jPanel234; - private javax.swing.JPanel jPanel235; - private javax.swing.JPanel jPanel236; - private javax.swing.JPanel jPanel237; - private javax.swing.JPanel jPanel238; - private javax.swing.JPanel jPanel239; - private javax.swing.JPanel jPanel24; - private javax.swing.JPanel jPanel240; - private javax.swing.JPanel jPanel241; - private javax.swing.JPanel jPanel242; - private javax.swing.JPanel jPanel243; - private javax.swing.JPanel jPanel244; - private javax.swing.JPanel jPanel245; - private javax.swing.JPanel jPanel246; - private javax.swing.JPanel jPanel247; - private javax.swing.JPanel jPanel248; - private javax.swing.JPanel jPanel249; - private javax.swing.JPanel jPanel25; - private javax.swing.JPanel jPanel250; - private javax.swing.JPanel jPanel251; - private javax.swing.JPanel jPanel252; - private javax.swing.JPanel jPanel253; - private javax.swing.JPanel jPanel254; - private javax.swing.JPanel jPanel255; - private javax.swing.JPanel jPanel256; - private javax.swing.JPanel jPanel257; - private javax.swing.JPanel jPanel258; - private javax.swing.JPanel jPanel259; - private javax.swing.JPanel jPanel26; - private javax.swing.JPanel jPanel260; - private javax.swing.JPanel jPanel261; - private javax.swing.JPanel jPanel262; - private javax.swing.JPanel jPanel263; - private javax.swing.JPanel jPanel264; - private javax.swing.JPanel jPanel265; - private javax.swing.JPanel jPanel266; - private javax.swing.JPanel jPanel267; - private javax.swing.JPanel jPanel27; - private javax.swing.JPanel jPanel28; - private javax.swing.JPanel jPanel29; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel30; - private javax.swing.JPanel jPanel31; - private javax.swing.JPanel jPanel32; - private javax.swing.JPanel jPanel33; - private javax.swing.JPanel jPanel34; - private javax.swing.JPanel jPanel35; - private javax.swing.JPanel jPanel36; - private javax.swing.JPanel jPanel37; - private javax.swing.JPanel jPanel38; - private javax.swing.JPanel jPanel39; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel40; - private javax.swing.JPanel jPanel41; - private javax.swing.JPanel jPanel42; - private javax.swing.JPanel jPanel43; - private javax.swing.JPanel jPanel44; - private javax.swing.JPanel jPanel45; - private javax.swing.JPanel jPanel46; - private javax.swing.JPanel jPanel47; - private javax.swing.JPanel jPanel48; - private javax.swing.JPanel jPanel49; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel50; - private javax.swing.JPanel jPanel51; - private javax.swing.JPanel jPanel52; - private javax.swing.JPanel jPanel53; - private javax.swing.JPanel jPanel54; - private javax.swing.JPanel jPanel55; - private javax.swing.JPanel jPanel56; - private javax.swing.JPanel jPanel57; - private javax.swing.JPanel jPanel58; - private javax.swing.JPanel jPanel59; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel60; - private javax.swing.JPanel jPanel61; - private javax.swing.JPanel jPanel62; - private javax.swing.JPanel jPanel63; - private javax.swing.JPanel jPanel64; - private javax.swing.JPanel jPanel65; - private javax.swing.JPanel jPanel66; - private javax.swing.JPanel jPanel67; - private javax.swing.JPanel jPanel68; - private javax.swing.JPanel jPanel69; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel70; - private javax.swing.JPanel jPanel71; - private javax.swing.JPanel jPanel72; - private javax.swing.JPanel jPanel73; - private javax.swing.JPanel jPanel74; - private javax.swing.JPanel jPanel75; - private javax.swing.JPanel jPanel76; - private javax.swing.JPanel jPanel77; - private javax.swing.JPanel jPanel78; - private javax.swing.JPanel jPanel79; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel80; - private javax.swing.JPanel jPanel81; - private javax.swing.JPanel jPanel82; - private javax.swing.JPanel jPanel83; - private javax.swing.JPanel jPanel84; - private javax.swing.JPanel jPanel85; - private javax.swing.JPanel jPanel86; - private javax.swing.JPanel jPanel87; - private javax.swing.JPanel jPanel88; - private javax.swing.JPanel jPanel89; - private javax.swing.JPanel jPanel9; - private javax.swing.JPanel jPanel90; - private javax.swing.JPanel jPanel91; - private javax.swing.JPanel jPanel92; - private javax.swing.JPanel jPanel93; - private javax.swing.JPanel jPanel94; - private javax.swing.JPanel jPanel95; - private javax.swing.JPanel jPanel96; - private javax.swing.JPanel jPanel97; - private javax.swing.JPanel jPanel98; - private javax.swing.JPanel jPanel99; - private javax.swing.JScrollPane jScrollPane1; - private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_SIMULINK_TANKSetup.java b/java/jdevices/src/main/java/MARTE2_SIMULINK_TANKSetup.java index d45534aa7a..bdd721a983 100644 --- a/java/jdevices/src/main/java/MARTE2_SIMULINK_TANKSetup.java +++ b/java/jdevices/src/main/java/MARTE2_SIMULINK_TANKSetup.java @@ -42,6 +42,7 @@ private void initComponents() { jPanel4 = new javax.swing.JPanel(); deviceField4 = new DeviceField(); deviceField5 = new DeviceField(); + deviceField6 = new DeviceField(); setDeviceProvider("spilds:8100"); setDeviceTitle("MARTe2 Simulink Tank"); @@ -61,7 +62,7 @@ private void initComponents() { deviceField2.setIdentifier(""); deviceField2.setLabelString("Timebase Div: "); deviceField2.setNumCols(4); - deviceField2.setOffsetNid(43); + deviceField2.setOffsetNid(44); jPanel2.add(deviceField2); jPanel1.add(jPanel2); @@ -86,6 +87,12 @@ private void initComponents() { deviceField5.setOffsetNid(34); jPanel4.add(deviceField5); + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Stream:"); + deviceField6.setOffsetNid(41); + deviceField6.setTextOnly(true); + jPanel4.add(deviceField6); + jPanel1.add(jPanel4); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); @@ -98,6 +105,7 @@ private void initComponents() { private DeviceField deviceField3; private DeviceField deviceField4; private DeviceField deviceField5; + private DeviceField deviceField6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; diff --git a/java/jdevices/src/main/java/MARTE2_SPIDER_CALSetup.java b/java/jdevices/src/main/java/MARTE2_SPIDER_CALSetup.java index 9d5a63876a..c0a82711d3 100644 --- a/java/jdevices/src/main/java/MARTE2_SPIDER_CALSetup.java +++ b/java/jdevices/src/main/java/MARTE2_SPIDER_CALSetup.java @@ -28,1591 +28,73 @@ private void initComponents() { deviceButtons1 = new DeviceButtons(); jPanel2 = new javax.swing.JPanel(); - jPanel87 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField170 = new DeviceField(); - jPanel88 = new javax.swing.JPanel(); - deviceField171 = new DeviceField(); - deviceField172 = new DeviceField(); - deviceField173 = new DeviceField(); - jScrollPane1 = new javax.swing.JScrollPane(); - jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); deviceField2 = new DeviceField(); - deviceField3 = new DeviceField(); jPanel4 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); deviceField4 = new DeviceField(); deviceField5 = new DeviceField(); - jPanel5 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceField7 = new DeviceField(); - jPanel6 = new javax.swing.JPanel(); - deviceField8 = new DeviceField(); - deviceField9 = new DeviceField(); - jPanel7 = new javax.swing.JPanel(); - deviceField10 = new DeviceField(); - deviceField11 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - deviceField12 = new DeviceField(); - deviceField13 = new DeviceField(); - jPanel9 = new javax.swing.JPanel(); - deviceField14 = new DeviceField(); - deviceField15 = new DeviceField(); - jPanel10 = new javax.swing.JPanel(); - deviceField16 = new DeviceField(); - deviceField17 = new DeviceField(); - jPanel11 = new javax.swing.JPanel(); - deviceField18 = new DeviceField(); - deviceField19 = new DeviceField(); - jPanel12 = new javax.swing.JPanel(); - deviceField20 = new DeviceField(); - deviceField21 = new DeviceField(); - jPanel13 = new javax.swing.JPanel(); - deviceField22 = new DeviceField(); - deviceField23 = new DeviceField(); - jPanel14 = new javax.swing.JPanel(); - deviceField24 = new DeviceField(); - deviceField25 = new DeviceField(); - jPanel15 = new javax.swing.JPanel(); - deviceField26 = new DeviceField(); - deviceField27 = new DeviceField(); - jPanel16 = new javax.swing.JPanel(); - deviceField28 = new DeviceField(); - deviceField29 = new DeviceField(); - jPanel17 = new javax.swing.JPanel(); - deviceField30 = new DeviceField(); - deviceField31 = new DeviceField(); - jPanel18 = new javax.swing.JPanel(); - deviceField32 = new DeviceField(); - deviceField33 = new DeviceField(); - jPanel19 = new javax.swing.JPanel(); - deviceField34 = new DeviceField(); - deviceField35 = new DeviceField(); - jPanel20 = new javax.swing.JPanel(); - deviceField36 = new DeviceField(); - deviceField37 = new DeviceField(); - jPanel21 = new javax.swing.JPanel(); - deviceField38 = new DeviceField(); - deviceField39 = new DeviceField(); - jPanel22 = new javax.swing.JPanel(); - deviceField40 = new DeviceField(); - deviceField41 = new DeviceField(); - jPanel23 = new javax.swing.JPanel(); - deviceField42 = new DeviceField(); - deviceField43 = new DeviceField(); - jPanel24 = new javax.swing.JPanel(); - deviceField44 = new DeviceField(); - deviceField45 = new DeviceField(); - jPanel25 = new javax.swing.JPanel(); - deviceField46 = new DeviceField(); - deviceField47 = new DeviceField(); - jPanel26 = new javax.swing.JPanel(); - deviceField48 = new DeviceField(); - deviceField49 = new DeviceField(); - jPanel27 = new javax.swing.JPanel(); - deviceField50 = new DeviceField(); - deviceField51 = new DeviceField(); - jPanel28 = new javax.swing.JPanel(); - deviceField52 = new DeviceField(); - deviceField53 = new DeviceField(); - jPanel29 = new javax.swing.JPanel(); - deviceField54 = new DeviceField(); - deviceField55 = new DeviceField(); - jPanel30 = new javax.swing.JPanel(); - deviceField56 = new DeviceField(); - deviceField57 = new DeviceField(); - jPanel31 = new javax.swing.JPanel(); - deviceField58 = new DeviceField(); - deviceField59 = new DeviceField(); - jPanel32 = new javax.swing.JPanel(); - deviceField60 = new DeviceField(); - deviceField61 = new DeviceField(); - jPanel33 = new javax.swing.JPanel(); - deviceField62 = new DeviceField(); - deviceField63 = new DeviceField(); - jPanel34 = new javax.swing.JPanel(); - deviceField64 = new DeviceField(); - deviceField65 = new DeviceField(); - jPanel35 = new javax.swing.JPanel(); - deviceField66 = new DeviceField(); - deviceField67 = new DeviceField(); - jPanel36 = new javax.swing.JPanel(); - deviceField68 = new DeviceField(); - deviceField69 = new DeviceField(); - jPanel37 = new javax.swing.JPanel(); - deviceField70 = new DeviceField(); - deviceField71 = new DeviceField(); - jPanel38 = new javax.swing.JPanel(); - deviceField72 = new DeviceField(); - deviceField73 = new DeviceField(); - jPanel39 = new javax.swing.JPanel(); - deviceField74 = new DeviceField(); - deviceField75 = new DeviceField(); - jPanel40 = new javax.swing.JPanel(); - deviceField76 = new DeviceField(); - deviceField77 = new DeviceField(); - jPanel41 = new javax.swing.JPanel(); - deviceField78 = new DeviceField(); - deviceField79 = new DeviceField(); - jPanel42 = new javax.swing.JPanel(); - deviceField80 = new DeviceField(); - deviceField81 = new DeviceField(); - jPanel43 = new javax.swing.JPanel(); - deviceField82 = new DeviceField(); - deviceField83 = new DeviceField(); - jPanel44 = new javax.swing.JPanel(); - deviceField84 = new DeviceField(); - deviceField85 = new DeviceField(); - jPanel45 = new javax.swing.JPanel(); - deviceField86 = new DeviceField(); - deviceField87 = new DeviceField(); - jPanel46 = new javax.swing.JPanel(); - deviceField88 = new DeviceField(); - deviceField89 = new DeviceField(); - jPanel47 = new javax.swing.JPanel(); - deviceField90 = new DeviceField(); - deviceField91 = new DeviceField(); - jPanel48 = new javax.swing.JPanel(); - deviceField92 = new DeviceField(); - deviceField93 = new DeviceField(); - jPanel49 = new javax.swing.JPanel(); - deviceField94 = new DeviceField(); - deviceField95 = new DeviceField(); - jPanel50 = new javax.swing.JPanel(); - deviceField96 = new DeviceField(); - deviceField97 = new DeviceField(); - jPanel51 = new javax.swing.JPanel(); - deviceField98 = new DeviceField(); - deviceField99 = new DeviceField(); - jPanel52 = new javax.swing.JPanel(); - deviceField100 = new DeviceField(); - deviceField101 = new DeviceField(); - jPanel53 = new javax.swing.JPanel(); - deviceField102 = new DeviceField(); - deviceField103 = new DeviceField(); - jPanel54 = new javax.swing.JPanel(); - deviceField104 = new DeviceField(); - deviceField105 = new DeviceField(); - jPanel55 = new javax.swing.JPanel(); - deviceField106 = new DeviceField(); - deviceField107 = new DeviceField(); - jPanel56 = new javax.swing.JPanel(); - deviceField108 = new DeviceField(); - deviceField109 = new DeviceField(); - jPanel57 = new javax.swing.JPanel(); - deviceField110 = new DeviceField(); - deviceField111 = new DeviceField(); - jPanel58 = new javax.swing.JPanel(); - deviceField112 = new DeviceField(); - deviceField113 = new DeviceField(); - jPanel59 = new javax.swing.JPanel(); - deviceField114 = new DeviceField(); - deviceField115 = new DeviceField(); - jPanel60 = new javax.swing.JPanel(); - deviceField116 = new DeviceField(); - deviceField117 = new DeviceField(); - jPanel61 = new javax.swing.JPanel(); - deviceField118 = new DeviceField(); - deviceField119 = new DeviceField(); - jPanel62 = new javax.swing.JPanel(); - deviceField120 = new DeviceField(); - deviceField121 = new DeviceField(); - jPanel63 = new javax.swing.JPanel(); - deviceField122 = new DeviceField(); - deviceField123 = new DeviceField(); - jPanel64 = new javax.swing.JPanel(); - deviceField124 = new DeviceField(); - deviceField125 = new DeviceField(); - jPanel65 = new javax.swing.JPanel(); - deviceField126 = new DeviceField(); - deviceField127 = new DeviceField(); - jPanel66 = new javax.swing.JPanel(); - deviceField128 = new DeviceField(); - deviceField129 = new DeviceField(); - jPanel67 = new javax.swing.JPanel(); - deviceField130 = new DeviceField(); - deviceField131 = new DeviceField(); - jPanel68 = new javax.swing.JPanel(); - deviceField132 = new DeviceField(); - deviceField133 = new DeviceField(); - jPanel69 = new javax.swing.JPanel(); - deviceField134 = new DeviceField(); - deviceField135 = new DeviceField(); - jPanel70 = new javax.swing.JPanel(); - deviceField136 = new DeviceField(); - deviceField137 = new DeviceField(); - jPanel71 = new javax.swing.JPanel(); - deviceField138 = new DeviceField(); - deviceField139 = new DeviceField(); - jPanel72 = new javax.swing.JPanel(); - deviceField140 = new DeviceField(); - deviceField141 = new DeviceField(); - jPanel73 = new javax.swing.JPanel(); - deviceField142 = new DeviceField(); - deviceField143 = new DeviceField(); - jPanel74 = new javax.swing.JPanel(); - deviceField144 = new DeviceField(); - deviceField145 = new DeviceField(); - jPanel75 = new javax.swing.JPanel(); - deviceField146 = new DeviceField(); - deviceField147 = new DeviceField(); - jPanel76 = new javax.swing.JPanel(); - deviceField148 = new DeviceField(); - deviceField149 = new DeviceField(); - jPanel77 = new javax.swing.JPanel(); - deviceField150 = new DeviceField(); - deviceField151 = new DeviceField(); - jPanel78 = new javax.swing.JPanel(); - deviceField152 = new DeviceField(); - deviceField153 = new DeviceField(); - jPanel79 = new javax.swing.JPanel(); - deviceField154 = new DeviceField(); - deviceField155 = new DeviceField(); - jPanel80 = new javax.swing.JPanel(); - deviceField156 = new DeviceField(); - deviceField157 = new DeviceField(); - jPanel81 = new javax.swing.JPanel(); - deviceField158 = new DeviceField(); - deviceField159 = new DeviceField(); - jPanel82 = new javax.swing.JPanel(); - deviceField160 = new DeviceField(); - deviceField161 = new DeviceField(); - jPanel83 = new javax.swing.JPanel(); - deviceField162 = new DeviceField(); - deviceField163 = new DeviceField(); - jPanel84 = new javax.swing.JPanel(); - deviceField164 = new DeviceField(); - deviceField165 = new DeviceField(); - jPanel85 = new javax.swing.JPanel(); - deviceField166 = new DeviceField(); - deviceField167 = new DeviceField(); - jPanel86 = new javax.swing.JPanel(); - deviceField168 = new DeviceField(); - deviceField169 = new DeviceField(); + deviceInputs1 = new DeviceInputs(); - setDeviceProvider("spilds.rfx.local:8100"); - setDeviceTitle("\"MARTe2 Spider Calorimetric measurements"); + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 Spider Calorimeter"); setDeviceType("MARTE2_SPIDER_CAL"); - setHeight(500); - setWidth(800); + setHeight(300); + setUpdateEvent(""); + setWidth(500); getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); jPanel2.setLayout(new java.awt.GridLayout(2, 1)); deviceField1.setIdentifier(""); - deviceField1.setLabelString("Period:"); + deviceField1.setLabelString("Period"); deviceField1.setOffsetNid(7); - jPanel87.add(deviceField1); - - deviceField170.setIdentifier(""); - deviceField170.setLabelString("Timebase"); - deviceField170.setNumCols(15); - deviceField170.setOffsetNid(3); - jPanel87.add(deviceField170); - - jPanel2.add(jPanel87); - - deviceField171.setIdentifier(""); - deviceField171.setLabelString("Out Trigger:"); - deviceField171.setNumCols(25); - deviceField171.setOffsetNid(598); - jPanel88.add(deviceField171); - - deviceField172.setIdentifier(""); - deviceField172.setLabelString("Pre Samples: "); - deviceField172.setNumCols(5); - deviceField172.setOffsetNid(599); - jPanel88.add(deviceField172); - - deviceField173.setIdentifier(""); - deviceField173.setLabelString("Post Samples: "); - deviceField173.setNumCols(5); - deviceField173.setOffsetNid(600); - jPanel88.add(deviceField173); + jPanel3.add(deviceField1); - jPanel2.add(jPanel88); - - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - - jPanel1.setLayout(new java.awt.GridLayout(84, 1)); - - deviceField2.setEditable(false); deviceField2.setIdentifier(""); - deviceField2.setOffsetNid(14); + deviceField2.setLabelString("Timebase: "); + deviceField2.setNumCols(25); + deviceField2.setOffsetNid(3); jPanel3.add(deviceField2); - deviceField3.setIdentifier(""); - deviceField3.setNumCols(30); - deviceField3.setOffsetNid(13); - jPanel3.add(deviceField3); + jPanel2.add(jPanel3); - jPanel1.add(jPanel3); + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Out trigger: "); + deviceField3.setNumCols(25); + deviceField3.setOffsetNid(598); + jPanel4.add(deviceField3); - deviceField4.setEditable(false); deviceField4.setIdentifier(""); - deviceField4.setOffsetNid(21); + deviceField4.setLabelString("Pre samples: "); + deviceField4.setOffsetNid(599); jPanel4.add(deviceField4); deviceField5.setIdentifier(""); - deviceField5.setNumCols(30); - deviceField5.setOffsetNid(20); + deviceField5.setLabelString("Post samples: "); + deviceField5.setOffsetNid(600); jPanel4.add(deviceField5); - jPanel1.add(jPanel4); - - deviceField6.setEditable(false); - deviceField6.setIdentifier(""); - deviceField6.setOffsetNid(28); - jPanel5.add(deviceField6); - - deviceField7.setIdentifier(""); - deviceField7.setNumCols(30); - deviceField7.setOffsetNid(27); - jPanel5.add(deviceField7); - - jPanel1.add(jPanel5); - - deviceField8.setEditable(false); - deviceField8.setIdentifier(""); - deviceField8.setOffsetNid(35); - jPanel6.add(deviceField8); - - deviceField9.setIdentifier(""); - deviceField9.setNumCols(30); - deviceField9.setOffsetNid(34); - jPanel6.add(deviceField9); - - jPanel1.add(jPanel6); - - deviceField10.setEditable(false); - deviceField10.setIdentifier(""); - deviceField10.setOffsetNid(42); - jPanel7.add(deviceField10); - - deviceField11.setIdentifier(""); - deviceField11.setNumCols(30); - deviceField11.setOffsetNid(41); - jPanel7.add(deviceField11); - - jPanel1.add(jPanel7); - - deviceField12.setEditable(false); - deviceField12.setIdentifier(""); - deviceField12.setOffsetNid(49); - jPanel8.add(deviceField12); - - deviceField13.setIdentifier(""); - deviceField13.setNumCols(30); - deviceField13.setOffsetNid(48); - jPanel8.add(deviceField13); - - jPanel1.add(jPanel8); - - deviceField14.setEditable(false); - deviceField14.setIdentifier(""); - deviceField14.setOffsetNid(56); - jPanel9.add(deviceField14); - - deviceField15.setIdentifier(""); - deviceField15.setNumCols(30); - deviceField15.setOffsetNid(55); - jPanel9.add(deviceField15); - - jPanel1.add(jPanel9); - - deviceField16.setEditable(false); - deviceField16.setIdentifier(""); - deviceField16.setOffsetNid(63); - jPanel10.add(deviceField16); - - deviceField17.setIdentifier(""); - deviceField17.setNumCols(30); - deviceField17.setOffsetNid(62); - jPanel10.add(deviceField17); - - jPanel1.add(jPanel10); - - deviceField18.setEditable(false); - deviceField18.setIdentifier(""); - deviceField18.setOffsetNid(70); - jPanel11.add(deviceField18); - - deviceField19.setIdentifier(""); - deviceField19.setNumCols(30); - deviceField19.setOffsetNid(69); - jPanel11.add(deviceField19); - - jPanel1.add(jPanel11); - - deviceField20.setEditable(false); - deviceField20.setIdentifier(""); - deviceField20.setOffsetNid(77); - jPanel12.add(deviceField20); - - deviceField21.setIdentifier(""); - deviceField21.setNumCols(30); - deviceField21.setOffsetNid(76); - jPanel12.add(deviceField21); - - jPanel1.add(jPanel12); - - deviceField22.setEditable(false); - deviceField22.setIdentifier(""); - deviceField22.setOffsetNid(84); - jPanel13.add(deviceField22); - - deviceField23.setIdentifier(""); - deviceField23.setNumCols(30); - deviceField23.setOffsetNid(83); - jPanel13.add(deviceField23); - - jPanel1.add(jPanel13); - - deviceField24.setEditable(false); - deviceField24.setIdentifier(""); - deviceField24.setOffsetNid(91); - jPanel14.add(deviceField24); - - deviceField25.setIdentifier(""); - deviceField25.setNumCols(30); - deviceField25.setOffsetNid(90); - jPanel14.add(deviceField25); - - jPanel1.add(jPanel14); - - deviceField26.setEditable(false); - deviceField26.setIdentifier(""); - deviceField26.setOffsetNid(98); - jPanel15.add(deviceField26); - - deviceField27.setIdentifier(""); - deviceField27.setNumCols(30); - deviceField27.setOffsetNid(97); - jPanel15.add(deviceField27); - - jPanel1.add(jPanel15); - - deviceField28.setEditable(false); - deviceField28.setIdentifier(""); - deviceField28.setOffsetNid(105); - jPanel16.add(deviceField28); - - deviceField29.setIdentifier(""); - deviceField29.setNumCols(30); - deviceField29.setOffsetNid(104); - jPanel16.add(deviceField29); - - jPanel1.add(jPanel16); - - deviceField30.setEditable(false); - deviceField30.setIdentifier(""); - deviceField30.setOffsetNid(112); - jPanel17.add(deviceField30); - - deviceField31.setIdentifier(""); - deviceField31.setNumCols(30); - deviceField31.setOffsetNid(111); - jPanel17.add(deviceField31); - - jPanel1.add(jPanel17); - - deviceField32.setEditable(false); - deviceField32.setIdentifier(""); - deviceField32.setOffsetNid(119); - jPanel18.add(deviceField32); - - deviceField33.setIdentifier(""); - deviceField33.setNumCols(30); - deviceField33.setOffsetNid(118); - jPanel18.add(deviceField33); - - jPanel1.add(jPanel18); - - deviceField34.setEditable(false); - deviceField34.setIdentifier(""); - deviceField34.setOffsetNid(126); - jPanel19.add(deviceField34); - - deviceField35.setIdentifier(""); - deviceField35.setNumCols(30); - deviceField35.setOffsetNid(125); - jPanel19.add(deviceField35); - - jPanel1.add(jPanel19); - - deviceField36.setEditable(false); - deviceField36.setIdentifier(""); - deviceField36.setOffsetNid(133); - jPanel20.add(deviceField36); - - deviceField37.setIdentifier(""); - deviceField37.setNumCols(30); - deviceField37.setOffsetNid(132); - jPanel20.add(deviceField37); - - jPanel1.add(jPanel20); - - deviceField38.setEditable(false); - deviceField38.setIdentifier(""); - deviceField38.setOffsetNid(140); - jPanel21.add(deviceField38); - - deviceField39.setIdentifier(""); - deviceField39.setNumCols(30); - deviceField39.setOffsetNid(139); - jPanel21.add(deviceField39); - - jPanel1.add(jPanel21); - - deviceField40.setEditable(false); - deviceField40.setIdentifier(""); - deviceField40.setOffsetNid(147); - jPanel22.add(deviceField40); - - deviceField41.setIdentifier(""); - deviceField41.setNumCols(30); - deviceField41.setOffsetNid(146); - jPanel22.add(deviceField41); - - jPanel1.add(jPanel22); - - deviceField42.setEditable(false); - deviceField42.setIdentifier(""); - deviceField42.setOffsetNid(154); - jPanel23.add(deviceField42); - - deviceField43.setIdentifier(""); - deviceField43.setNumCols(30); - deviceField43.setOffsetNid(153); - jPanel23.add(deviceField43); - - jPanel1.add(jPanel23); - - deviceField44.setEditable(false); - deviceField44.setIdentifier(""); - deviceField44.setOffsetNid(161); - jPanel24.add(deviceField44); - - deviceField45.setIdentifier(""); - deviceField45.setNumCols(30); - deviceField45.setOffsetNid(160); - jPanel24.add(deviceField45); - - jPanel1.add(jPanel24); - - deviceField46.setEditable(false); - deviceField46.setIdentifier(""); - deviceField46.setOffsetNid(168); - jPanel25.add(deviceField46); - - deviceField47.setIdentifier(""); - deviceField47.setNumCols(30); - deviceField47.setOffsetNid(167); - jPanel25.add(deviceField47); - - jPanel1.add(jPanel25); - - deviceField48.setEditable(false); - deviceField48.setIdentifier(""); - deviceField48.setOffsetNid(175); - jPanel26.add(deviceField48); - - deviceField49.setIdentifier(""); - deviceField49.setNumCols(30); - deviceField49.setOffsetNid(174); - jPanel26.add(deviceField49); - - jPanel1.add(jPanel26); - - deviceField50.setEditable(false); - deviceField50.setIdentifier(""); - deviceField50.setOffsetNid(182); - jPanel27.add(deviceField50); - - deviceField51.setIdentifier(""); - deviceField51.setNumCols(30); - deviceField51.setOffsetNid(181); - jPanel27.add(deviceField51); - - jPanel1.add(jPanel27); - - deviceField52.setEditable(false); - deviceField52.setIdentifier(""); - deviceField52.setOffsetNid(189); - jPanel28.add(deviceField52); - - deviceField53.setIdentifier(""); - deviceField53.setNumCols(30); - deviceField53.setOffsetNid(188); - jPanel28.add(deviceField53); - - jPanel1.add(jPanel28); - - deviceField54.setEditable(false); - deviceField54.setIdentifier(""); - deviceField54.setOffsetNid(196); - jPanel29.add(deviceField54); - - deviceField55.setIdentifier(""); - deviceField55.setNumCols(30); - deviceField55.setOffsetNid(195); - jPanel29.add(deviceField55); - - jPanel1.add(jPanel29); - - deviceField56.setEditable(false); - deviceField56.setIdentifier(""); - deviceField56.setOffsetNid(203); - jPanel30.add(deviceField56); - - deviceField57.setIdentifier(""); - deviceField57.setNumCols(30); - deviceField57.setOffsetNid(202); - jPanel30.add(deviceField57); - - jPanel1.add(jPanel30); - - deviceField58.setEditable(false); - deviceField58.setIdentifier(""); - deviceField58.setOffsetNid(210); - jPanel31.add(deviceField58); - - deviceField59.setIdentifier(""); - deviceField59.setNumCols(30); - deviceField59.setOffsetNid(209); - jPanel31.add(deviceField59); - - jPanel1.add(jPanel31); - - deviceField60.setEditable(false); - deviceField60.setIdentifier(""); - deviceField60.setOffsetNid(217); - jPanel32.add(deviceField60); - - deviceField61.setIdentifier(""); - deviceField61.setNumCols(30); - deviceField61.setOffsetNid(216); - jPanel32.add(deviceField61); - - jPanel1.add(jPanel32); - - deviceField62.setEditable(false); - deviceField62.setIdentifier(""); - deviceField62.setOffsetNid(224); - jPanel33.add(deviceField62); - - deviceField63.setIdentifier(""); - deviceField63.setNumCols(30); - deviceField63.setOffsetNid(223); - jPanel33.add(deviceField63); - - jPanel1.add(jPanel33); - - deviceField64.setEditable(false); - deviceField64.setIdentifier(""); - deviceField64.setOffsetNid(231); - jPanel34.add(deviceField64); - - deviceField65.setIdentifier(""); - deviceField65.setNumCols(30); - deviceField65.setOffsetNid(230); - jPanel34.add(deviceField65); - - jPanel1.add(jPanel34); - - deviceField66.setEditable(false); - deviceField66.setIdentifier(""); - deviceField66.setOffsetNid(238); - jPanel35.add(deviceField66); - - deviceField67.setIdentifier(""); - deviceField67.setNumCols(30); - deviceField67.setOffsetNid(237); - jPanel35.add(deviceField67); - - jPanel1.add(jPanel35); - - deviceField68.setEditable(false); - deviceField68.setIdentifier(""); - deviceField68.setOffsetNid(245); - jPanel36.add(deviceField68); - - deviceField69.setIdentifier(""); - deviceField69.setNumCols(30); - deviceField69.setOffsetNid(244); - jPanel36.add(deviceField69); - - jPanel1.add(jPanel36); - - deviceField70.setEditable(false); - deviceField70.setIdentifier(""); - deviceField70.setOffsetNid(252); - jPanel37.add(deviceField70); - - deviceField71.setIdentifier(""); - deviceField71.setNumCols(30); - deviceField71.setOffsetNid(251); - jPanel37.add(deviceField71); - - jPanel1.add(jPanel37); - - deviceField72.setEditable(false); - deviceField72.setIdentifier(""); - deviceField72.setOffsetNid(259); - jPanel38.add(deviceField72); - - deviceField73.setIdentifier(""); - deviceField73.setNumCols(30); - deviceField73.setOffsetNid(258); - jPanel38.add(deviceField73); - - jPanel1.add(jPanel38); - - deviceField74.setEditable(false); - deviceField74.setIdentifier(""); - deviceField74.setOffsetNid(266); - jPanel39.add(deviceField74); - - deviceField75.setIdentifier(""); - deviceField75.setNumCols(30); - deviceField75.setOffsetNid(265); - jPanel39.add(deviceField75); - - jPanel1.add(jPanel39); - - deviceField76.setEditable(false); - deviceField76.setIdentifier(""); - deviceField76.setOffsetNid(273); - jPanel40.add(deviceField76); - - deviceField77.setIdentifier(""); - deviceField77.setNumCols(30); - deviceField77.setOffsetNid(272); - jPanel40.add(deviceField77); - - jPanel1.add(jPanel40); - - deviceField78.setEditable(false); - deviceField78.setIdentifier(""); - deviceField78.setOffsetNid(280); - jPanel41.add(deviceField78); - - deviceField79.setIdentifier(""); - deviceField79.setNumCols(30); - deviceField79.setOffsetNid(279); - jPanel41.add(deviceField79); - - jPanel1.add(jPanel41); - - deviceField80.setEditable(false); - deviceField80.setIdentifier(""); - deviceField80.setOffsetNid(287); - jPanel42.add(deviceField80); - - deviceField81.setIdentifier(""); - deviceField81.setNumCols(30); - deviceField81.setOffsetNid(286); - jPanel42.add(deviceField81); - - jPanel1.add(jPanel42); - - deviceField82.setEditable(false); - deviceField82.setIdentifier(""); - deviceField82.setOffsetNid(294); - jPanel43.add(deviceField82); - - deviceField83.setIdentifier(""); - deviceField83.setNumCols(30); - deviceField83.setOffsetNid(293); - jPanel43.add(deviceField83); + jPanel2.add(jPanel4); - jPanel1.add(jPanel43); - - deviceField84.setEditable(false); - deviceField84.setIdentifier(""); - deviceField84.setOffsetNid(301); - jPanel44.add(deviceField84); - - deviceField85.setIdentifier(""); - deviceField85.setNumCols(30); - deviceField85.setOffsetNid(300); - jPanel44.add(deviceField85); - - jPanel1.add(jPanel44); - - deviceField86.setEditable(false); - deviceField86.setIdentifier(""); - deviceField86.setOffsetNid(308); - jPanel45.add(deviceField86); - - deviceField87.setIdentifier(""); - deviceField87.setNumCols(30); - deviceField87.setOffsetNid(307); - jPanel45.add(deviceField87); - - jPanel1.add(jPanel45); - - deviceField88.setEditable(false); - deviceField88.setIdentifier(""); - deviceField88.setOffsetNid(315); - jPanel46.add(deviceField88); - - deviceField89.setIdentifier(""); - deviceField89.setNumCols(30); - deviceField89.setOffsetNid(314); - jPanel46.add(deviceField89); - - jPanel1.add(jPanel46); - - deviceField90.setEditable(false); - deviceField90.setIdentifier(""); - deviceField90.setOffsetNid(322); - jPanel47.add(deviceField90); - - deviceField91.setIdentifier(""); - deviceField91.setNumCols(30); - deviceField91.setOffsetNid(321); - jPanel47.add(deviceField91); - - jPanel1.add(jPanel47); - - deviceField92.setEditable(false); - deviceField92.setIdentifier(""); - deviceField92.setOffsetNid(329); - jPanel48.add(deviceField92); - - deviceField93.setIdentifier(""); - deviceField93.setNumCols(30); - deviceField93.setOffsetNid(328); - jPanel48.add(deviceField93); - - jPanel1.add(jPanel48); - - deviceField94.setEditable(false); - deviceField94.setIdentifier(""); - deviceField94.setOffsetNid(336); - jPanel49.add(deviceField94); - - deviceField95.setIdentifier(""); - deviceField95.setNumCols(30); - deviceField95.setOffsetNid(335); - jPanel49.add(deviceField95); - - jPanel1.add(jPanel49); - - deviceField96.setEditable(false); - deviceField96.setIdentifier(""); - deviceField96.setOffsetNid(343); - jPanel50.add(deviceField96); - - deviceField97.setIdentifier(""); - deviceField97.setNumCols(30); - deviceField97.setOffsetNid(342); - jPanel50.add(deviceField97); - - jPanel1.add(jPanel50); - - deviceField98.setEditable(false); - deviceField98.setIdentifier(""); - deviceField98.setOffsetNid(350); - jPanel51.add(deviceField98); - - deviceField99.setIdentifier(""); - deviceField99.setNumCols(30); - deviceField99.setOffsetNid(349); - jPanel51.add(deviceField99); - - jPanel1.add(jPanel51); - - deviceField100.setEditable(false); - deviceField100.setIdentifier(""); - deviceField100.setOffsetNid(357); - jPanel52.add(deviceField100); - - deviceField101.setIdentifier(""); - deviceField101.setNumCols(30); - deviceField101.setOffsetNid(356); - jPanel52.add(deviceField101); - - jPanel1.add(jPanel52); - - deviceField102.setEditable(false); - deviceField102.setIdentifier(""); - deviceField102.setOffsetNid(364); - jPanel53.add(deviceField102); - - deviceField103.setIdentifier(""); - deviceField103.setNumCols(30); - deviceField103.setOffsetNid(363); - jPanel53.add(deviceField103); - - jPanel1.add(jPanel53); - - deviceField104.setEditable(false); - deviceField104.setIdentifier(""); - deviceField104.setOffsetNid(371); - jPanel54.add(deviceField104); - - deviceField105.setIdentifier(""); - deviceField105.setNumCols(30); - deviceField105.setOffsetNid(370); - jPanel54.add(deviceField105); - - jPanel1.add(jPanel54); - - deviceField106.setEditable(false); - deviceField106.setIdentifier(""); - deviceField106.setOffsetNid(378); - jPanel55.add(deviceField106); - - deviceField107.setIdentifier(""); - deviceField107.setNumCols(30); - deviceField107.setOffsetNid(377); - jPanel55.add(deviceField107); - - jPanel1.add(jPanel55); - - deviceField108.setEditable(false); - deviceField108.setIdentifier(""); - deviceField108.setOffsetNid(385); - jPanel56.add(deviceField108); - - deviceField109.setIdentifier(""); - deviceField109.setNumCols(30); - deviceField109.setOffsetNid(384); - jPanel56.add(deviceField109); - - jPanel1.add(jPanel56); - - deviceField110.setEditable(false); - deviceField110.setIdentifier(""); - deviceField110.setOffsetNid(392); - jPanel57.add(deviceField110); - - deviceField111.setIdentifier(""); - deviceField111.setNumCols(30); - deviceField111.setOffsetNid(391); - jPanel57.add(deviceField111); - - jPanel1.add(jPanel57); - - deviceField112.setEditable(false); - deviceField112.setIdentifier(""); - deviceField112.setOffsetNid(399); - jPanel58.add(deviceField112); - - deviceField113.setIdentifier(""); - deviceField113.setNumCols(30); - deviceField113.setOffsetNid(398); - jPanel58.add(deviceField113); - - jPanel1.add(jPanel58); - - deviceField114.setEditable(false); - deviceField114.setIdentifier(""); - deviceField114.setOffsetNid(406); - jPanel59.add(deviceField114); - - deviceField115.setIdentifier(""); - deviceField115.setNumCols(30); - deviceField115.setOffsetNid(405); - jPanel59.add(deviceField115); - - jPanel1.add(jPanel59); - - deviceField116.setEditable(false); - deviceField116.setIdentifier(""); - deviceField116.setOffsetNid(413); - jPanel60.add(deviceField116); - - deviceField117.setIdentifier(""); - deviceField117.setNumCols(30); - deviceField117.setOffsetNid(412); - jPanel60.add(deviceField117); - - jPanel1.add(jPanel60); - - deviceField118.setEditable(false); - deviceField118.setIdentifier(""); - deviceField118.setOffsetNid(420); - jPanel61.add(deviceField118); - - deviceField119.setIdentifier(""); - deviceField119.setNumCols(30); - deviceField119.setOffsetNid(419); - jPanel61.add(deviceField119); - - jPanel1.add(jPanel61); - - deviceField120.setEditable(false); - deviceField120.setIdentifier(""); - deviceField120.setOffsetNid(427); - jPanel62.add(deviceField120); - - deviceField121.setIdentifier(""); - deviceField121.setNumCols(30); - deviceField121.setOffsetNid(426); - jPanel62.add(deviceField121); - - jPanel1.add(jPanel62); - - deviceField122.setEditable(false); - deviceField122.setIdentifier(""); - deviceField122.setOffsetNid(434); - jPanel63.add(deviceField122); - - deviceField123.setIdentifier(""); - deviceField123.setNumCols(30); - deviceField123.setOffsetNid(433); - jPanel63.add(deviceField123); - - jPanel1.add(jPanel63); - - deviceField124.setEditable(false); - deviceField124.setIdentifier(""); - deviceField124.setOffsetNid(441); - jPanel64.add(deviceField124); - - deviceField125.setIdentifier(""); - deviceField125.setNumCols(30); - deviceField125.setOffsetNid(440); - jPanel64.add(deviceField125); - - jPanel1.add(jPanel64); - - deviceField126.setEditable(false); - deviceField126.setIdentifier(""); - deviceField126.setOffsetNid(448); - jPanel65.add(deviceField126); - - deviceField127.setIdentifier(""); - deviceField127.setNumCols(30); - deviceField127.setOffsetNid(447); - jPanel65.add(deviceField127); - - jPanel1.add(jPanel65); - - deviceField128.setEditable(false); - deviceField128.setIdentifier(""); - deviceField128.setOffsetNid(455); - jPanel66.add(deviceField128); - - deviceField129.setIdentifier(""); - deviceField129.setNumCols(30); - deviceField129.setOffsetNid(454); - jPanel66.add(deviceField129); - - jPanel1.add(jPanel66); - - deviceField130.setEditable(false); - deviceField130.setIdentifier(""); - deviceField130.setOffsetNid(462); - jPanel67.add(deviceField130); - - deviceField131.setIdentifier(""); - deviceField131.setNumCols(30); - deviceField131.setOffsetNid(461); - jPanel67.add(deviceField131); - - jPanel1.add(jPanel67); - - deviceField132.setEditable(false); - deviceField132.setIdentifier(""); - deviceField132.setOffsetNid(469); - jPanel68.add(deviceField132); - - deviceField133.setIdentifier(""); - deviceField133.setNumCols(30); - deviceField133.setOffsetNid(468); - jPanel68.add(deviceField133); - - jPanel1.add(jPanel68); - - deviceField134.setEditable(false); - deviceField134.setIdentifier(""); - deviceField134.setOffsetNid(476); - jPanel69.add(deviceField134); - - deviceField135.setIdentifier(""); - deviceField135.setNumCols(30); - deviceField135.setOffsetNid(475); - jPanel69.add(deviceField135); - - jPanel1.add(jPanel69); - - deviceField136.setEditable(false); - deviceField136.setIdentifier(""); - deviceField136.setOffsetNid(483); - jPanel70.add(deviceField136); - - deviceField137.setIdentifier(""); - deviceField137.setNumCols(30); - deviceField137.setOffsetNid(482); - jPanel70.add(deviceField137); - - jPanel1.add(jPanel70); - - deviceField138.setEditable(false); - deviceField138.setIdentifier(""); - deviceField138.setOffsetNid(490); - jPanel71.add(deviceField138); - - deviceField139.setIdentifier(""); - deviceField139.setNumCols(30); - deviceField139.setOffsetNid(489); - jPanel71.add(deviceField139); - - jPanel1.add(jPanel71); - - deviceField140.setEditable(false); - deviceField140.setIdentifier(""); - deviceField140.setOffsetNid(497); - jPanel72.add(deviceField140); - - deviceField141.setIdentifier(""); - deviceField141.setNumCols(30); - deviceField141.setOffsetNid(496); - jPanel72.add(deviceField141); - - jPanel1.add(jPanel72); - - deviceField142.setEditable(false); - deviceField142.setIdentifier(""); - deviceField142.setOffsetNid(504); - jPanel73.add(deviceField142); - - deviceField143.setIdentifier(""); - deviceField143.setNumCols(30); - deviceField143.setOffsetNid(503); - jPanel73.add(deviceField143); - - jPanel1.add(jPanel73); - - deviceField144.setEditable(false); - deviceField144.setIdentifier(""); - deviceField144.setOffsetNid(511); - jPanel74.add(deviceField144); - - deviceField145.setIdentifier(""); - deviceField145.setNumCols(30); - deviceField145.setOffsetNid(510); - jPanel74.add(deviceField145); - - jPanel1.add(jPanel74); - - deviceField146.setEditable(false); - deviceField146.setIdentifier(""); - deviceField146.setOffsetNid(518); - jPanel75.add(deviceField146); - - deviceField147.setIdentifier(""); - deviceField147.setNumCols(30); - deviceField147.setOffsetNid(517); - jPanel75.add(deviceField147); - - jPanel1.add(jPanel75); - - deviceField148.setEditable(false); - deviceField148.setIdentifier(""); - deviceField148.setOffsetNid(525); - jPanel76.add(deviceField148); - - deviceField149.setIdentifier(""); - deviceField149.setNumCols(30); - deviceField149.setOffsetNid(524); - jPanel76.add(deviceField149); - - jPanel1.add(jPanel76); - - deviceField150.setEditable(false); - deviceField150.setIdentifier(""); - deviceField150.setOffsetNid(532); - jPanel77.add(deviceField150); - - deviceField151.setIdentifier(""); - deviceField151.setNumCols(30); - deviceField151.setOffsetNid(531); - jPanel77.add(deviceField151); - - jPanel1.add(jPanel77); - - deviceField152.setEditable(false); - deviceField152.setIdentifier(""); - deviceField152.setOffsetNid(539); - jPanel78.add(deviceField152); - - deviceField153.setIdentifier(""); - deviceField153.setNumCols(30); - deviceField153.setOffsetNid(538); - jPanel78.add(deviceField153); - - jPanel1.add(jPanel78); - - deviceField154.setEditable(false); - deviceField154.setIdentifier(""); - deviceField154.setOffsetNid(546); - jPanel79.add(deviceField154); - - deviceField155.setIdentifier(""); - deviceField155.setNumCols(30); - deviceField155.setOffsetNid(545); - jPanel79.add(deviceField155); - - jPanel1.add(jPanel79); - - deviceField156.setEditable(false); - deviceField156.setIdentifier(""); - deviceField156.setOffsetNid(553); - jPanel80.add(deviceField156); - - deviceField157.setIdentifier(""); - deviceField157.setNumCols(30); - deviceField157.setOffsetNid(552); - jPanel80.add(deviceField157); - - jPanel1.add(jPanel80); - - deviceField158.setEditable(false); - deviceField158.setIdentifier(""); - deviceField158.setOffsetNid(560); - jPanel81.add(deviceField158); - - deviceField159.setIdentifier(""); - deviceField159.setNumCols(30); - deviceField159.setOffsetNid(559); - jPanel81.add(deviceField159); - - jPanel1.add(jPanel81); - - deviceField160.setEditable(false); - deviceField160.setIdentifier(""); - deviceField160.setOffsetNid(567); - jPanel82.add(deviceField160); - - deviceField161.setIdentifier(""); - deviceField161.setNumCols(30); - deviceField161.setOffsetNid(566); - jPanel82.add(deviceField161); - - jPanel1.add(jPanel82); - - deviceField162.setEditable(false); - deviceField162.setIdentifier(""); - deviceField162.setOffsetNid(574); - jPanel83.add(deviceField162); - - deviceField163.setIdentifier(""); - deviceField163.setNumCols(30); - deviceField163.setOffsetNid(573); - jPanel83.add(deviceField163); - - jPanel1.add(jPanel83); - - deviceField164.setEditable(false); - deviceField164.setIdentifier(""); - deviceField164.setOffsetNid(581); - jPanel84.add(deviceField164); - - deviceField165.setIdentifier(""); - deviceField165.setNumCols(30); - deviceField165.setOffsetNid(580); - jPanel84.add(deviceField165); - - jPanel1.add(jPanel84); - - deviceField166.setEditable(false); - deviceField166.setIdentifier(""); - deviceField166.setOffsetNid(588); - jPanel85.add(deviceField166); - - deviceField167.setIdentifier(""); - deviceField167.setNumCols(30); - deviceField167.setOffsetNid(587); - jPanel85.add(deviceField167); - - jPanel1.add(jPanel85); - - deviceField168.setEditable(false); - deviceField168.setIdentifier(""); - deviceField168.setOffsetNid(595); - jPanel86.add(deviceField168); - - deviceField169.setIdentifier(""); - deviceField169.setNumCols(30); - deviceField169.setOffsetNid(594); - jPanel86.add(deviceField169); - - jPanel1.add(jPanel86); - - jScrollPane1.setViewportView(jPanel1); + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); + deviceInputs1.setOffsetNid(8); + getContentPane().add(deviceInputs1, java.awt.BorderLayout.CENTER); }// //GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private DeviceButtons deviceButtons1; private DeviceField deviceField1; - private DeviceField deviceField10; - private DeviceField deviceField100; - private DeviceField deviceField101; - private DeviceField deviceField102; - private DeviceField deviceField103; - private DeviceField deviceField104; - private DeviceField deviceField105; - private DeviceField deviceField106; - private DeviceField deviceField107; - private DeviceField deviceField108; - private DeviceField deviceField109; - private DeviceField deviceField11; - private DeviceField deviceField110; - private DeviceField deviceField111; - private DeviceField deviceField112; - private DeviceField deviceField113; - private DeviceField deviceField114; - private DeviceField deviceField115; - private DeviceField deviceField116; - private DeviceField deviceField117; - private DeviceField deviceField118; - private DeviceField deviceField119; - private DeviceField deviceField12; - private DeviceField deviceField120; - private DeviceField deviceField121; - private DeviceField deviceField122; - private DeviceField deviceField123; - private DeviceField deviceField124; - private DeviceField deviceField125; - private DeviceField deviceField126; - private DeviceField deviceField127; - private DeviceField deviceField128; - private DeviceField deviceField129; - private DeviceField deviceField13; - private DeviceField deviceField130; - private DeviceField deviceField131; - private DeviceField deviceField132; - private DeviceField deviceField133; - private DeviceField deviceField134; - private DeviceField deviceField135; - private DeviceField deviceField136; - private DeviceField deviceField137; - private DeviceField deviceField138; - private DeviceField deviceField139; - private DeviceField deviceField14; - private DeviceField deviceField140; - private DeviceField deviceField141; - private DeviceField deviceField142; - private DeviceField deviceField143; - private DeviceField deviceField144; - private DeviceField deviceField145; - private DeviceField deviceField146; - private DeviceField deviceField147; - private DeviceField deviceField148; - private DeviceField deviceField149; - private DeviceField deviceField15; - private DeviceField deviceField150; - private DeviceField deviceField151; - private DeviceField deviceField152; - private DeviceField deviceField153; - private DeviceField deviceField154; - private DeviceField deviceField155; - private DeviceField deviceField156; - private DeviceField deviceField157; - private DeviceField deviceField158; - private DeviceField deviceField159; - private DeviceField deviceField16; - private DeviceField deviceField160; - private DeviceField deviceField161; - private DeviceField deviceField162; - private DeviceField deviceField163; - private DeviceField deviceField164; - private DeviceField deviceField165; - private DeviceField deviceField166; - private DeviceField deviceField167; - private DeviceField deviceField168; - private DeviceField deviceField169; - private DeviceField deviceField17; - private DeviceField deviceField170; - private DeviceField deviceField171; - private DeviceField deviceField172; - private DeviceField deviceField173; - private DeviceField deviceField18; - private DeviceField deviceField19; private DeviceField deviceField2; - private DeviceField deviceField20; - private DeviceField deviceField21; - private DeviceField deviceField22; - private DeviceField deviceField23; - private DeviceField deviceField24; - private DeviceField deviceField25; - private DeviceField deviceField26; - private DeviceField deviceField27; - private DeviceField deviceField28; - private DeviceField deviceField29; private DeviceField deviceField3; - private DeviceField deviceField30; - private DeviceField deviceField31; - private DeviceField deviceField32; - private DeviceField deviceField33; - private DeviceField deviceField34; - private DeviceField deviceField35; - private DeviceField deviceField36; - private DeviceField deviceField37; - private DeviceField deviceField38; - private DeviceField deviceField39; private DeviceField deviceField4; - private DeviceField deviceField40; - private DeviceField deviceField41; - private DeviceField deviceField42; - private DeviceField deviceField43; - private DeviceField deviceField44; - private DeviceField deviceField45; - private DeviceField deviceField46; - private DeviceField deviceField47; - private DeviceField deviceField48; - private DeviceField deviceField49; private DeviceField deviceField5; - private DeviceField deviceField50; - private DeviceField deviceField51; - private DeviceField deviceField52; - private DeviceField deviceField53; - private DeviceField deviceField54; - private DeviceField deviceField55; - private DeviceField deviceField56; - private DeviceField deviceField57; - private DeviceField deviceField58; - private DeviceField deviceField59; - private DeviceField deviceField6; - private DeviceField deviceField60; - private DeviceField deviceField61; - private DeviceField deviceField62; - private DeviceField deviceField63; - private DeviceField deviceField64; - private DeviceField deviceField65; - private DeviceField deviceField66; - private DeviceField deviceField67; - private DeviceField deviceField68; - private DeviceField deviceField69; - private DeviceField deviceField7; - private DeviceField deviceField70; - private DeviceField deviceField71; - private DeviceField deviceField72; - private DeviceField deviceField73; - private DeviceField deviceField74; - private DeviceField deviceField75; - private DeviceField deviceField76; - private DeviceField deviceField77; - private DeviceField deviceField78; - private DeviceField deviceField79; - private DeviceField deviceField8; - private DeviceField deviceField80; - private DeviceField deviceField81; - private DeviceField deviceField82; - private DeviceField deviceField83; - private DeviceField deviceField84; - private DeviceField deviceField85; - private DeviceField deviceField86; - private DeviceField deviceField87; - private DeviceField deviceField88; - private DeviceField deviceField89; - private DeviceField deviceField9; - private DeviceField deviceField90; - private DeviceField deviceField91; - private DeviceField deviceField92; - private DeviceField deviceField93; - private DeviceField deviceField94; - private DeviceField deviceField95; - private DeviceField deviceField96; - private DeviceField deviceField97; - private DeviceField deviceField98; - private DeviceField deviceField99; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel10; - private javax.swing.JPanel jPanel11; - private javax.swing.JPanel jPanel12; - private javax.swing.JPanel jPanel13; - private javax.swing.JPanel jPanel14; - private javax.swing.JPanel jPanel15; - private javax.swing.JPanel jPanel16; - private javax.swing.JPanel jPanel17; - private javax.swing.JPanel jPanel18; - private javax.swing.JPanel jPanel19; + private DeviceInputs deviceInputs1; private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel20; - private javax.swing.JPanel jPanel21; - private javax.swing.JPanel jPanel22; - private javax.swing.JPanel jPanel23; - private javax.swing.JPanel jPanel24; - private javax.swing.JPanel jPanel25; - private javax.swing.JPanel jPanel26; - private javax.swing.JPanel jPanel27; - private javax.swing.JPanel jPanel28; - private javax.swing.JPanel jPanel29; private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel30; - private javax.swing.JPanel jPanel31; - private javax.swing.JPanel jPanel32; - private javax.swing.JPanel jPanel33; - private javax.swing.JPanel jPanel34; - private javax.swing.JPanel jPanel35; - private javax.swing.JPanel jPanel36; - private javax.swing.JPanel jPanel37; - private javax.swing.JPanel jPanel38; - private javax.swing.JPanel jPanel39; private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel40; - private javax.swing.JPanel jPanel41; - private javax.swing.JPanel jPanel42; - private javax.swing.JPanel jPanel43; - private javax.swing.JPanel jPanel44; - private javax.swing.JPanel jPanel45; - private javax.swing.JPanel jPanel46; - private javax.swing.JPanel jPanel47; - private javax.swing.JPanel jPanel48; - private javax.swing.JPanel jPanel49; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel50; - private javax.swing.JPanel jPanel51; - private javax.swing.JPanel jPanel52; - private javax.swing.JPanel jPanel53; - private javax.swing.JPanel jPanel54; - private javax.swing.JPanel jPanel55; - private javax.swing.JPanel jPanel56; - private javax.swing.JPanel jPanel57; - private javax.swing.JPanel jPanel58; - private javax.swing.JPanel jPanel59; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel60; - private javax.swing.JPanel jPanel61; - private javax.swing.JPanel jPanel62; - private javax.swing.JPanel jPanel63; - private javax.swing.JPanel jPanel64; - private javax.swing.JPanel jPanel65; - private javax.swing.JPanel jPanel66; - private javax.swing.JPanel jPanel67; - private javax.swing.JPanel jPanel68; - private javax.swing.JPanel jPanel69; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel70; - private javax.swing.JPanel jPanel71; - private javax.swing.JPanel jPanel72; - private javax.swing.JPanel jPanel73; - private javax.swing.JPanel jPanel74; - private javax.swing.JPanel jPanel75; - private javax.swing.JPanel jPanel76; - private javax.swing.JPanel jPanel77; - private javax.swing.JPanel jPanel78; - private javax.swing.JPanel jPanel79; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel80; - private javax.swing.JPanel jPanel81; - private javax.swing.JPanel jPanel82; - private javax.swing.JPanel jPanel83; - private javax.swing.JPanel jPanel84; - private javax.swing.JPanel jPanel85; - private javax.swing.JPanel jPanel86; - private javax.swing.JPanel jPanel87; - private javax.swing.JPanel jPanel88; - private javax.swing.JPanel jPanel9; - private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_STREAM_INSetup.java b/java/jdevices/src/main/java/MARTE2_STREAM_INSetup.java index e1c89c338d..6b971ae3f5 100644 --- a/java/jdevices/src/main/java/MARTE2_STREAM_INSetup.java +++ b/java/jdevices/src/main/java/MARTE2_STREAM_INSetup.java @@ -29,209 +29,241 @@ public MARTE2_STREAM_INSetup() */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents - private void initComponents() - { - deviceSetup1 = new DeviceSetup(); - deviceButtons1 = new DeviceButtons(); - jPanel2 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - deviceField1 = new DeviceField(); - deviceField2 = new DeviceField(); - jPanel4 = new javax.swing.JPanel(); - deviceField3 = new DeviceField(); - deviceField4 = new DeviceField(); - deviceField5 = new DeviceField(); - jPanel1 = new javax.swing.JPanel(); - jScrollPane1 = new javax.swing.JScrollPane(); - jPanel5 = new javax.swing.JPanel(); - jPanel6 = new javax.swing.JPanel(); - deviceField6 = new DeviceField(); - deviceChoice1 = new DeviceChoice(); - deviceField7 = new DeviceField(); - deviceField8 = new DeviceField(); - jPanel7 = new javax.swing.JPanel(); - deviceField9 = new DeviceField(); - deviceChoice2 = new DeviceChoice(); - deviceField10 = new DeviceField(); - deviceField11 = new DeviceField(); - jPanel8 = new javax.swing.JPanel(); - deviceField12 = new DeviceField(); - deviceChoice3 = new DeviceChoice(); - deviceField13 = new DeviceField(); - deviceField14 = new DeviceField(); - jPanel9 = new javax.swing.JPanel(); - deviceField15 = new DeviceField(); - deviceChoice4 = new DeviceChoice(); - deviceField16 = new DeviceField(); - deviceField17 = new DeviceField(); - setDeviceProvider("scdevail.rfx.local:8200"); - setDeviceTitle("MARTe2 Input Stream"); - setDeviceType("MARTE2_STREAM:IN"); - setHeight(400); - setWidth(700); - getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); - jPanel2.setLayout(new java.awt.GridLayout(2, 1)); - deviceField1.setIdentifier(""); - deviceField1.setLabelString("Buffer queue len:"); - deviceField1.setNumCols(4); - deviceField1.setOffsetNid(7); - jPanel3.add(deviceField1); - deviceField2.setIdentifier(""); - deviceField2.setLabelString("CPU Mask"); - deviceField2.setNumCols(4); - deviceField2.setOffsetNid(10); - jPanel3.add(deviceField2); - jPanel2.add(jPanel3); - deviceField3.setIdentifier(""); - deviceField3.setLabelString("Stack size: "); - deviceField3.setOffsetNid(13); - jPanel4.add(deviceField3); - deviceField4.setIdentifier(""); - deviceField4.setLabelString("Sinchronizing Idx: "); - deviceField4.setNumCols(4); - deviceField4.setOffsetNid(16); - jPanel4.add(deviceField4); - deviceField5.setIdentifier(""); - deviceField5.setLabelString("Period"); - deviceField5.setNumCols(6); - deviceField5.setOffsetNid(19); - jPanel4.add(deviceField5); - jPanel2.add(jPanel4); - getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); - jPanel1.setLayout(new java.awt.BorderLayout()); - jPanel5.setLayout(new java.awt.GridLayout(4, 1)); - deviceField6.setIdentifier(""); - deviceField6.setLabelString("Dimensions:"); - deviceField6.setOffsetNid(31); - jPanel6.add(deviceField6); - deviceChoice1.setChoiceItems(new String[] - { "int16", "uint16", "int32", "uint32", "float32", "float64" }); - deviceChoice1.setIdentifier(""); - deviceChoice1.setLabelString("Type:"); - deviceChoice1.setOffsetNid(29); - deviceChoice1.setUpdateIdentifier(""); - jPanel6.add(deviceChoice1); - deviceField7.setIdentifier(""); - deviceField7.setLabelString("Channel: "); - deviceField7.setNumCols(12); - deviceField7.setOffsetNid(37); - deviceField7.setTextOnly(true); - jPanel6.add(deviceField7); - deviceField8.setIdentifier(""); - deviceField8.setLabelString("Seg. len: "); - deviceField8.setNumCols(4); - deviceField8.setOffsetNid(32); - jPanel6.add(deviceField8); - jPanel5.add(jPanel6); - deviceField9.setIdentifier(""); - deviceField9.setLabelString("Dimensions:"); - deviceField9.setOffsetNid(42); - jPanel7.add(deviceField9); - deviceChoice2.setChoiceItems(new String[] - { "int16", "uint16", "int32", "uint32", "float32", "float64" }); - deviceChoice2.setIdentifier(""); - deviceChoice2.setLabelString("Type:"); - deviceChoice2.setOffsetNid(40); - deviceChoice2.setUpdateIdentifier(""); - jPanel7.add(deviceChoice2); - deviceField10.setIdentifier(""); - deviceField10.setLabelString("Channel: "); - deviceField10.setNumCols(12); - deviceField10.setOffsetNid(48); - deviceField10.setTextOnly(true); - jPanel7.add(deviceField10); - deviceField11.setIdentifier(""); - deviceField11.setLabelString("Seg. len: "); - deviceField11.setNumCols(4); - deviceField11.setOffsetNid(43); - jPanel7.add(deviceField11); - jPanel5.add(jPanel7); - deviceField12.setIdentifier(""); - deviceField12.setLabelString("Dimensions:"); - deviceField12.setOffsetNid(53); - jPanel8.add(deviceField12); - deviceChoice3.setChoiceItems(new String[] - { "int16", "uint16", "int32", "uint32", "float32", "float64" }); - deviceChoice3.setIdentifier(""); - deviceChoice3.setLabelString("Type:"); - deviceChoice3.setOffsetNid(51); - deviceChoice3.setUpdateIdentifier(""); - jPanel8.add(deviceChoice3); - deviceField13.setIdentifier(""); - deviceField13.setLabelString("Channel: "); - deviceField13.setNumCols(12); - deviceField13.setOffsetNid(59); - deviceField13.setTextOnly(true); - jPanel8.add(deviceField13); - deviceField14.setIdentifier(""); - deviceField14.setLabelString("Seg. len: "); - deviceField14.setNumCols(4); - deviceField14.setOffsetNid(54); - jPanel8.add(deviceField14); - jPanel5.add(jPanel8); - deviceField15.setIdentifier(""); - deviceField15.setLabelString("Dimensions:"); - deviceField15.setOffsetNid(64); - jPanel9.add(deviceField15); - deviceChoice4.setChoiceItems(new String[] - { "int16", "uint16", "int32", "uint32", "float32", "float64" }); - deviceChoice4.setIdentifier(""); - deviceChoice4.setLabelString("Type:"); - deviceChoice4.setOffsetNid(62); - deviceChoice4.setUpdateIdentifier(""); - jPanel9.add(deviceChoice4); - deviceField16.setIdentifier(""); - deviceField16.setLabelString("Channel: "); - deviceField16.setNumCols(12); - deviceField16.setOffsetNid(70); - deviceField16.setTextOnly(true); - jPanel9.add(deviceField16); - deviceField17.setIdentifier(""); - deviceField17.setLabelString("Seg. len: "); - deviceField17.setNumCols(4); - deviceField17.setOffsetNid(65); - jPanel9.add(deviceField17); - jPanel5.add(jPanel9); - jScrollPane1.setViewportView(jPanel5); - jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER); - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - getAccessibleContext().setAccessibleName(""); - }// //GEN-END:initComponents - - // Variables declaration - do not modify//GEN-BEGIN:variables - private DeviceButtons deviceButtons1; - private DeviceChoice deviceChoice1; - private DeviceChoice deviceChoice2; - private DeviceChoice deviceChoice3; - private DeviceChoice deviceChoice4; - private DeviceField deviceField1; - private DeviceField deviceField10; - private DeviceField deviceField11; - private DeviceField deviceField12; - private DeviceField deviceField13; - private DeviceField deviceField14; - private DeviceField deviceField15; - private DeviceField deviceField16; - private DeviceField deviceField17; - private DeviceField deviceField2; - private DeviceField deviceField3; - private DeviceField deviceField4; - private DeviceField deviceField5; - private DeviceField deviceField6; - private DeviceField deviceField7; - private DeviceField deviceField8; - private DeviceField deviceField9; - private DeviceSetup deviceSetup1; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JPanel jPanel5; - private javax.swing.JPanel jPanel6; - private javax.swing.JPanel jPanel7; - private javax.swing.JPanel jPanel8; - private javax.swing.JPanel jPanel9; - private javax.swing.JScrollPane jScrollPane1; - // End of variables declaration//GEN-END:variables + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceSetup1 = new DeviceSetup(); + deviceButtons1 = new DeviceButtons(); + jPanel2 = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceField2 = new DeviceField(); + jPanel4 = new javax.swing.JPanel(); + deviceField3 = new DeviceField(); + deviceField4 = new DeviceField(); + deviceField5 = new DeviceField(); + jPanel1 = new javax.swing.JPanel(); + jScrollPane1 = new javax.swing.JScrollPane(); + jPanel5 = new javax.swing.JPanel(); + jPanel6 = new javax.swing.JPanel(); + deviceField6 = new DeviceField(); + deviceChoice1 = new DeviceChoice(); + deviceField7 = new DeviceField(); + deviceField8 = new DeviceField(); + jPanel7 = new javax.swing.JPanel(); + deviceField9 = new DeviceField(); + deviceChoice2 = new DeviceChoice(); + deviceField10 = new DeviceField(); + deviceField11 = new DeviceField(); + jPanel8 = new javax.swing.JPanel(); + deviceField12 = new DeviceField(); + deviceChoice3 = new DeviceChoice(); + deviceField13 = new DeviceField(); + deviceField14 = new DeviceField(); + jPanel9 = new javax.swing.JPanel(); + deviceField15 = new DeviceField(); + deviceChoice4 = new DeviceChoice(); + deviceField16 = new DeviceField(); + deviceField17 = new DeviceField(); + + setDeviceProvider("spilds:8100"); + setDeviceTitle("MARTe2 Input Stream"); + setDeviceType("MARTE2_STREAM_IN"); + setHeight(400); + setWidth(700); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + jPanel2.setLayout(new java.awt.GridLayout(2, 1)); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Buffer queue len:"); + deviceField1.setNumCols(4); + deviceField1.setOffsetNid(7); + jPanel3.add(deviceField1); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("CPU Mask"); + deviceField2.setNumCols(4); + deviceField2.setOffsetNid(10); + jPanel3.add(deviceField2); + + jPanel2.add(jPanel3); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Stack size: "); + deviceField3.setOffsetNid(13); + jPanel4.add(deviceField3); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("Sinchronizing Idx: "); + deviceField4.setNumCols(4); + deviceField4.setOffsetNid(16); + jPanel4.add(deviceField4); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Period"); + deviceField5.setNumCols(6); + deviceField5.setOffsetNid(19); + jPanel4.add(deviceField5); + + jPanel2.add(jPanel4); + + getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START); + + jPanel1.setLayout(new java.awt.BorderLayout()); + + jPanel5.setLayout(new java.awt.GridLayout(4, 1)); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("Dimensions:"); + deviceField6.setOffsetNid(31); + jPanel6.add(deviceField6); + + deviceChoice1.setChoiceItems(new String[] {"int16", "uint16", "int32", "uint32", "float32", "float64"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString("Type:"); + deviceChoice1.setOffsetNid(29); + deviceChoice1.setUpdateIdentifier(""); + jPanel6.add(deviceChoice1); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Channel: "); + deviceField7.setNumCols(12); + deviceField7.setOffsetNid(38); + deviceField7.setTextOnly(true); + jPanel6.add(deviceField7); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Seg. len: "); + deviceField8.setNumCols(4); + deviceField8.setOffsetNid(32); + jPanel6.add(deviceField8); + + jPanel5.add(jPanel6); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Dimensions:"); + deviceField9.setOffsetNid(43); + jPanel7.add(deviceField9); + + deviceChoice2.setChoiceItems(new String[] {"int16", "uint16", "int32", "uint32", "float32", "float64"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString("Type:"); + deviceChoice2.setOffsetNid(41); + deviceChoice2.setUpdateIdentifier(""); + jPanel7.add(deviceChoice2); + + deviceField10.setIdentifier(""); + deviceField10.setLabelString("Channel: "); + deviceField10.setNumCols(12); + deviceField10.setOffsetNid(50); + deviceField10.setTextOnly(true); + jPanel7.add(deviceField10); + + deviceField11.setIdentifier(""); + deviceField11.setLabelString("Seg. len: "); + deviceField11.setNumCols(4); + deviceField11.setOffsetNid(44); + jPanel7.add(deviceField11); + + jPanel5.add(jPanel7); + + deviceField12.setIdentifier(""); + deviceField12.setLabelString("Dimensions:"); + deviceField12.setOffsetNid(55); + jPanel8.add(deviceField12); + + deviceChoice3.setChoiceItems(new String[] {"int16", "uint16", "int32", "uint32", "float32", "float64"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString("Type:"); + deviceChoice3.setOffsetNid(53); + deviceChoice3.setUpdateIdentifier(""); + jPanel8.add(deviceChoice3); + + deviceField13.setIdentifier(""); + deviceField13.setLabelString("Channel: "); + deviceField13.setNumCols(12); + deviceField13.setOffsetNid(62); + deviceField13.setTextOnly(true); + jPanel8.add(deviceField13); + + deviceField14.setIdentifier(""); + deviceField14.setLabelString("Seg. len: "); + deviceField14.setNumCols(4); + deviceField14.setOffsetNid(56); + jPanel8.add(deviceField14); + + jPanel5.add(jPanel8); + + deviceField15.setIdentifier(""); + deviceField15.setLabelString("Dimensions:"); + deviceField15.setOffsetNid(67); + jPanel9.add(deviceField15); + + deviceChoice4.setChoiceItems(new String[] {"int16", "uint16", "int32", "uint32", "float32", "float64"}); + deviceChoice4.setIdentifier(""); + deviceChoice4.setLabelString("Type:"); + deviceChoice4.setOffsetNid(65); + deviceChoice4.setUpdateIdentifier(""); + jPanel9.add(deviceChoice4); + + deviceField16.setIdentifier(""); + deviceField16.setLabelString("Channel: "); + deviceField16.setNumCols(12); + deviceField16.setOffsetNid(74); + deviceField16.setTextOnly(true); + jPanel9.add(deviceField16); + + deviceField17.setIdentifier(""); + deviceField17.setLabelString("Seg. len: "); + deviceField17.setNumCols(4); + deviceField17.setOffsetNid(68); + jPanel9.add(deviceField17); + + jPanel5.add(jPanel9); + + jScrollPane1.setViewportView(jPanel5); + + jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER); + + getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); + + getAccessibleContext().setAccessibleName(""); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice3; + private DeviceChoice deviceChoice4; + private DeviceField deviceField1; + private DeviceField deviceField10; + private DeviceField deviceField11; + private DeviceField deviceField12; + private DeviceField deviceField13; + private DeviceField deviceField14; + private DeviceField deviceField15; + private DeviceField deviceField16; + private DeviceField deviceField17; + private DeviceField deviceField2; + private DeviceField deviceField3; + private DeviceField deviceField4; + private DeviceField deviceField5; + private DeviceField deviceField6; + private DeviceField deviceField7; + private DeviceField deviceField8; + private DeviceField deviceField9; + private DeviceSetup deviceSetup1; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel9; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MARTE2_SWTRIGSetup.java b/java/jdevices/src/main/java/MARTE2_SWTRIGSetup.java index 7d9e9f3bbe..1642f997ed 100644 --- a/java/jdevices/src/main/java/MARTE2_SWTRIGSetup.java +++ b/java/jdevices/src/main/java/MARTE2_SWTRIGSetup.java @@ -127,26 +127,26 @@ private void initComponents() { deviceField6.setIdentifier(""); deviceField6.setLabelString("Trigger Event:"); - deviceField6.setOffsetNid(53); + deviceField6.setOffsetNid(56); deviceField6.setTextOnly(true); jPanel5.add(deviceField6); deviceField7.setIdentifier(""); deviceField7.setLabelString("Wait cycles: "); deviceField7.setNumCols(6); - deviceField7.setOffsetNid(56); + deviceField7.setOffsetNid(59); jPanel5.add(deviceField7); deviceField8.setIdentifier(""); deviceField8.setLabelString("Trigger cycles:"); deviceField8.setNumCols(6); - deviceField8.setOffsetNid(59); + deviceField8.setOffsetNid(62); jPanel5.add(deviceField8); deviceField30.setIdentifier(""); deviceField30.setLabelString("Segment len.:"); deviceField30.setNumCols(4); - deviceField30.setOffsetNid(48); + deviceField30.setOffsetNid(50); jPanel5.add(deviceField30); jPanel4.add(jPanel5); @@ -155,26 +155,26 @@ private void initComponents() { deviceField9.setIdentifier(""); deviceField9.setLabelString("Trigger Event:"); - deviceField9.setOffsetNid(70); + deviceField9.setOffsetNid(74); deviceField9.setTextOnly(true); jPanel6.add(deviceField9); deviceField10.setIdentifier(""); deviceField10.setLabelString("Wait cycles: "); deviceField10.setNumCols(6); - deviceField10.setOffsetNid(73); + deviceField10.setOffsetNid(77); jPanel6.add(deviceField10); deviceField11.setIdentifier(""); deviceField11.setLabelString("Trigger cycles:"); deviceField11.setNumCols(6); - deviceField11.setOffsetNid(76); + deviceField11.setOffsetNid(80); jPanel6.add(deviceField11); deviceField31.setIdentifier(""); deviceField31.setLabelString("Segment len.:"); deviceField31.setNumCols(4); - deviceField31.setOffsetNid(65); + deviceField31.setOffsetNid(68); jPanel6.add(deviceField31); jPanel4.add(jPanel6); @@ -183,26 +183,26 @@ private void initComponents() { deviceField12.setIdentifier(""); deviceField12.setLabelString("Trigger Event:"); - deviceField12.setOffsetNid(87); + deviceField12.setOffsetNid(92); deviceField12.setTextOnly(true); jPanel7.add(deviceField12); deviceField13.setIdentifier(""); deviceField13.setLabelString("Wait cycles: "); deviceField13.setNumCols(6); - deviceField13.setOffsetNid(90); + deviceField13.setOffsetNid(95); jPanel7.add(deviceField13); deviceField14.setIdentifier(""); deviceField14.setLabelString("Trigger cycles:"); deviceField14.setNumCols(6); - deviceField14.setOffsetNid(93); + deviceField14.setOffsetNid(98); jPanel7.add(deviceField14); deviceField32.setIdentifier(""); deviceField32.setLabelString("Segment len.:"); deviceField32.setNumCols(4); - deviceField32.setOffsetNid(82); + deviceField32.setOffsetNid(86); jPanel7.add(deviceField32); jPanel4.add(jPanel7); @@ -211,26 +211,26 @@ private void initComponents() { deviceField15.setIdentifier(""); deviceField15.setLabelString("Trigger Event:"); - deviceField15.setOffsetNid(104); + deviceField15.setOffsetNid(110); deviceField15.setTextOnly(true); jPanel8.add(deviceField15); deviceField16.setIdentifier(""); deviceField16.setLabelString("Wait cycles: "); deviceField16.setNumCols(6); - deviceField16.setOffsetNid(107); + deviceField16.setOffsetNid(113); jPanel8.add(deviceField16); deviceField17.setIdentifier(""); deviceField17.setLabelString("Trigger cycles:"); deviceField17.setNumCols(6); - deviceField17.setOffsetNid(110); + deviceField17.setOffsetNid(116); jPanel8.add(deviceField17); deviceField33.setIdentifier(""); deviceField33.setLabelString("Segment len.:"); deviceField33.setNumCols(4); - deviceField33.setOffsetNid(99); + deviceField33.setOffsetNid(104); jPanel8.add(deviceField33); jPanel4.add(jPanel8); @@ -239,26 +239,26 @@ private void initComponents() { deviceField18.setIdentifier(""); deviceField18.setLabelString("Trigger Event:"); - deviceField18.setOffsetNid(121); + deviceField18.setOffsetNid(128); deviceField18.setTextOnly(true); jPanel9.add(deviceField18); deviceField19.setIdentifier(""); deviceField19.setLabelString("Wait cycles: "); deviceField19.setNumCols(6); - deviceField19.setOffsetNid(124); + deviceField19.setOffsetNid(131); jPanel9.add(deviceField19); deviceField20.setIdentifier(""); deviceField20.setLabelString("Trigger cycles:"); deviceField20.setNumCols(6); - deviceField20.setOffsetNid(127); + deviceField20.setOffsetNid(134); jPanel9.add(deviceField20); deviceField34.setIdentifier(""); deviceField34.setLabelString("Segment len.:"); deviceField34.setNumCols(4); - deviceField34.setOffsetNid(116); + deviceField34.setOffsetNid(122); jPanel9.add(deviceField34); jPanel4.add(jPanel9); @@ -267,26 +267,26 @@ private void initComponents() { deviceField21.setIdentifier(""); deviceField21.setLabelString("Trigger Event:"); - deviceField21.setOffsetNid(138); + deviceField21.setOffsetNid(146); deviceField21.setTextOnly(true); jPanel10.add(deviceField21); deviceField22.setIdentifier(""); deviceField22.setLabelString("Wait cycles: "); deviceField22.setNumCols(6); - deviceField22.setOffsetNid(141); + deviceField22.setOffsetNid(149); jPanel10.add(deviceField22); deviceField23.setIdentifier(""); deviceField23.setLabelString("Trigger cycles:"); deviceField23.setNumCols(6); - deviceField23.setOffsetNid(144); + deviceField23.setOffsetNid(152); jPanel10.add(deviceField23); deviceField35.setIdentifier(""); deviceField35.setLabelString("Segment len.:"); deviceField35.setNumCols(4); - deviceField35.setOffsetNid(133); + deviceField35.setOffsetNid(140); jPanel10.add(deviceField35); jPanel4.add(jPanel10); @@ -295,26 +295,26 @@ private void initComponents() { deviceField24.setIdentifier(""); deviceField24.setLabelString("Trigger Event:"); - deviceField24.setOffsetNid(155); + deviceField24.setOffsetNid(164); deviceField24.setTextOnly(true); jPanel11.add(deviceField24); deviceField25.setIdentifier(""); deviceField25.setLabelString("Wait cycles: "); deviceField25.setNumCols(6); - deviceField25.setOffsetNid(158); + deviceField25.setOffsetNid(167); jPanel11.add(deviceField25); deviceField26.setIdentifier(""); deviceField26.setLabelString("Trigger cycles:"); deviceField26.setNumCols(6); - deviceField26.setOffsetNid(161); + deviceField26.setOffsetNid(170); jPanel11.add(deviceField26); deviceField36.setIdentifier(""); deviceField36.setLabelString("Segment len.:"); deviceField36.setNumCols(4); - deviceField36.setOffsetNid(150); + deviceField36.setOffsetNid(158); jPanel11.add(deviceField36); jPanel4.add(jPanel11); @@ -323,26 +323,26 @@ private void initComponents() { deviceField27.setIdentifier(""); deviceField27.setLabelString("Trigger Event:"); - deviceField27.setOffsetNid(172); + deviceField27.setOffsetNid(182); deviceField27.setTextOnly(true); jPanel12.add(deviceField27); deviceField28.setIdentifier(""); deviceField28.setLabelString("Wait cycles: "); deviceField28.setNumCols(6); - deviceField28.setOffsetNid(175); + deviceField28.setOffsetNid(185); jPanel12.add(deviceField28); deviceField29.setIdentifier(""); deviceField29.setLabelString("Trigger cycles:"); deviceField29.setNumCols(6); - deviceField29.setOffsetNid(178); + deviceField29.setOffsetNid(188); jPanel12.add(deviceField29); deviceField37.setIdentifier(""); deviceField37.setLabelString("Segment len.:"); deviceField37.setNumCols(4); - deviceField37.setOffsetNid(167); + deviceField37.setOffsetNid(176); jPanel12.add(deviceField37); jPanel4.add(jPanel12); diff --git a/java/jdevices/src/main/resources/MARTE2_CONVERSIONSetup.form b/java/jdevices/src/main/resources/MARTE2_CONVERSIONSetup.form index 1cbf8c1cb5..dc1f20ba66 100644 --- a/java/jdevices/src/main/resources/MARTE2_CONVERSIONSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_CONVERSIONSetup.form @@ -2,7 +2,7 @@
- + @@ -1005,7 +1005,7 @@ - + @@ -1014,7 +1014,7 @@ - + @@ -1048,7 +1048,7 @@ - + @@ -1057,7 +1057,7 @@ - + @@ -1091,7 +1091,7 @@ - + @@ -1100,7 +1100,7 @@ - + @@ -1134,7 +1134,7 @@ - + @@ -1143,7 +1143,7 @@ - + @@ -1177,7 +1177,7 @@ - + @@ -1186,7 +1186,7 @@ - + @@ -1220,7 +1220,7 @@ - + @@ -1229,7 +1229,7 @@ - + @@ -1263,7 +1263,7 @@ - + @@ -1272,7 +1272,7 @@ - + @@ -1306,7 +1306,7 @@ - + @@ -1315,7 +1315,7 @@ - + @@ -1349,7 +1349,7 @@ - + @@ -1358,7 +1358,7 @@ - + @@ -1392,7 +1392,7 @@ - + @@ -1401,7 +1401,7 @@ - + @@ -1435,7 +1435,7 @@ - + @@ -1444,7 +1444,7 @@ - + @@ -1478,7 +1478,7 @@ - + @@ -1487,7 +1487,7 @@ - + @@ -1521,7 +1521,7 @@ - + @@ -1530,7 +1530,7 @@ - + @@ -1564,7 +1564,7 @@ - + @@ -1573,7 +1573,50 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_EXPRSetup.form b/java/jdevices/src/main/resources/MARTE2_EXPRSetup.form index e48fa0752a..ca56c06297 100644 --- a/java/jdevices/src/main/resources/MARTE2_EXPRSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_EXPRSetup.form @@ -2,7 +2,7 @@ - + @@ -643,7 +643,15 @@ - + + + + + + + + + @@ -673,7 +681,7 @@ - + @@ -694,7 +702,7 @@ - + @@ -717,7 +725,15 @@ - + + + + + + + + + @@ -747,7 +763,7 @@ - + @@ -768,7 +784,7 @@ - + @@ -791,7 +807,15 @@ - + + + + + + + + + @@ -821,7 +845,7 @@ - + @@ -842,7 +866,7 @@ - + @@ -865,7 +889,15 @@ - + + + + + + + + + @@ -895,7 +927,7 @@ - + @@ -916,7 +948,7 @@ - + @@ -939,6 +971,14 @@ + + + + + + + + @@ -969,7 +1009,7 @@ - + @@ -990,7 +1030,7 @@ - + @@ -1013,7 +1053,15 @@ - + + + + + + + + + @@ -1043,7 +1091,7 @@ - + @@ -1064,7 +1112,7 @@ - + @@ -1087,7 +1135,15 @@ - + + + + + + + + + @@ -1117,7 +1173,7 @@ - + @@ -1138,7 +1194,7 @@ - + @@ -1161,7 +1217,15 @@ - + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_FFTSetup.form b/java/jdevices/src/main/resources/MARTE2_FFTSetup.form index ae3fe8312e..88e02e07c1 100644 --- a/java/jdevices/src/main/resources/MARTE2_FFTSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_FFTSetup.form @@ -2,7 +2,7 @@ - + @@ -131,7 +131,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_GAMSetup.form b/java/jdevices/src/main/resources/MARTE2_GAMSetup.form index f17dbf4519..fcb8a9c9b8 100644 --- a/java/jdevices/src/main/resources/MARTE2_GAMSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_GAMSetup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_NI6259Setup.form b/java/jdevices/src/main/resources/MARTE2_NI6259Setup.form index 02eb0186a0..7366e91b8e 100644 --- a/java/jdevices/src/main/resources/MARTE2_NI6259Setup.form +++ b/java/jdevices/src/main/resources/MARTE2_NI6259Setup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_NI6259_DACSetup.form b/java/jdevices/src/main/resources/MARTE2_NI6259_DACSetup.form index 004ef9c5c0..14516d81fd 100644 --- a/java/jdevices/src/main/resources/MARTE2_NI6259_DACSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_NI6259_DACSetup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_NI6259_DISetup.form b/java/jdevices/src/main/resources/MARTE2_NI6259_DISetup.form index f42b8f092c..117b0cfd3c 100644 --- a/java/jdevices/src/main/resources/MARTE2_NI6259_DISetup.form +++ b/java/jdevices/src/main/resources/MARTE2_NI6259_DISetup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_NI6259_DOSetup.form b/java/jdevices/src/main/resources/MARTE2_NI6259_DOSetup.form index fe6ff1605b..31c68c6cc7 100644 --- a/java/jdevices/src/main/resources/MARTE2_NI6259_DOSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_NI6259_DOSetup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_PYTHON_GENERICSetup.form b/java/jdevices/src/main/resources/MARTE2_PYTHON_GENERICSetup.form index fb92185c4a..98712ec7e8 100644 --- a/java/jdevices/src/main/resources/MARTE2_PYTHON_GENERICSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_PYTHON_GENERICSetup.form @@ -761,6 +761,14 @@ + + + + + + + + @@ -778,7 +786,7 @@ - + @@ -796,7 +804,7 @@ - + @@ -805,7 +813,7 @@ - + @@ -813,7 +821,15 @@ - + + + + + + + + + @@ -833,7 +849,7 @@ - + @@ -851,7 +867,7 @@ - + @@ -860,7 +876,7 @@ - + @@ -868,7 +884,15 @@ - + + + + + + + + + @@ -888,7 +912,7 @@ - + @@ -906,7 +930,7 @@ - + @@ -915,7 +939,7 @@ - + @@ -923,7 +947,15 @@ - + + + + + + + + + @@ -943,7 +975,7 @@ - + @@ -961,7 +993,7 @@ - + @@ -970,7 +1002,7 @@ - + @@ -978,7 +1010,15 @@ - + + + + + + + + + @@ -998,7 +1038,7 @@ - + @@ -1016,7 +1056,7 @@ - + @@ -1025,7 +1065,7 @@ - + @@ -1033,7 +1073,15 @@ - + + + + + + + + + @@ -1053,7 +1101,7 @@ - + @@ -1071,7 +1119,7 @@ - + @@ -1080,7 +1128,7 @@ - + @@ -1088,7 +1136,15 @@ - + + + + + + + + + @@ -1108,7 +1164,7 @@ - + @@ -1126,7 +1182,7 @@ - + @@ -1135,7 +1191,7 @@ - + @@ -1143,7 +1199,15 @@ - + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_PYTHON_PIDSetup.form b/java/jdevices/src/main/resources/MARTE2_PYTHON_PIDSetup.form index d5ec313274..e551e89056 100644 --- a/java/jdevices/src/main/resources/MARTE2_PYTHON_PIDSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_PYTHON_PIDSetup.form @@ -2,7 +2,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_RESAMPLERSetup.form b/java/jdevices/src/main/resources/MARTE2_RESAMPLERSetup.form index 8cfca26d48..439b355436 100644 --- a/java/jdevices/src/main/resources/MARTE2_RESAMPLERSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_RESAMPLERSetup.form @@ -2,7 +2,7 @@ - + @@ -1011,7 +1011,7 @@ - + @@ -1032,7 +1032,7 @@ - + @@ -1053,7 +1053,7 @@ - + @@ -1074,7 +1074,7 @@ - + @@ -1095,7 +1095,7 @@ - + @@ -1116,7 +1116,7 @@ - + @@ -1137,7 +1137,7 @@ - + @@ -1158,7 +1158,7 @@ - + @@ -1179,7 +1179,7 @@ - + @@ -1200,7 +1200,7 @@ - + @@ -1221,7 +1221,7 @@ - + @@ -1242,7 +1242,7 @@ - + @@ -1263,7 +1263,7 @@ - + @@ -1284,7 +1284,7 @@ - + @@ -1305,7 +1305,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_RTSMSetup.form b/java/jdevices/src/main/resources/MARTE2_RTSMSetup.form index 1e5a892fb4..3b59c58b24 100644 --- a/java/jdevices/src/main/resources/MARTE2_RTSMSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_RTSMSetup.form @@ -8799,7 +8799,7 @@ - + @@ -8838,7 +8838,7 @@ - + @@ -8855,7 +8855,7 @@ - + @@ -8877,7 +8877,7 @@ - + @@ -8894,7 +8894,7 @@ - + @@ -8916,7 +8916,7 @@ - + @@ -8933,7 +8933,7 @@ - + @@ -8955,7 +8955,7 @@ - + @@ -8972,7 +8972,7 @@ - + @@ -8994,7 +8994,7 @@ - + @@ -9011,7 +9011,7 @@ - + @@ -9033,7 +9033,7 @@ - + @@ -9050,7 +9050,7 @@ - + @@ -9072,7 +9072,7 @@ - + @@ -9089,7 +9089,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_SIMULINK_FLUXMAPSetup.form b/java/jdevices/src/main/resources/MARTE2_SIMULINK_FLUXMAPSetup.form new file mode 100644 index 0000000000..b8f43a595f --- /dev/null +++ b/java/jdevices/src/main/resources/MARTE2_SIMULINK_FLUXMAPSetup.form @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_SIMULINK_GENERICSetup.form b/java/jdevices/src/main/resources/MARTE2_SIMULINK_GENERICSetup.form index 43cf0c0bfd..17980c104d 100644 --- a/java/jdevices/src/main/resources/MARTE2_SIMULINK_GENERICSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_SIMULINK_GENERICSetup.form @@ -699,6 +699,14 @@ + + + + + + + + @@ -720,7 +728,7 @@ - + @@ -738,7 +746,7 @@ - + @@ -747,7 +755,7 @@ - + @@ -755,7 +763,15 @@ - + + + + + + + + + @@ -779,7 +795,7 @@ - + @@ -797,7 +813,7 @@ - + @@ -806,7 +822,7 @@ - + @@ -814,7 +830,15 @@ - + + + + + + + + + @@ -838,7 +862,7 @@ - + @@ -856,7 +880,7 @@ - + @@ -865,7 +889,7 @@ - + @@ -873,7 +897,15 @@ - + + + + + + + + + @@ -897,7 +929,7 @@ - + @@ -915,7 +947,7 @@ - + @@ -924,7 +956,7 @@ - + @@ -932,7 +964,15 @@ - + + + + + + + + + @@ -956,7 +996,7 @@ - + @@ -974,7 +1014,7 @@ - + @@ -983,7 +1023,7 @@ - + @@ -991,7 +1031,15 @@ - + + + + + + + + + @@ -1015,7 +1063,7 @@ - + @@ -1033,7 +1081,7 @@ - + @@ -1042,7 +1090,7 @@ - + @@ -1050,7 +1098,15 @@ - + + + + + + + + + @@ -1074,7 +1130,7 @@ - + @@ -1092,7 +1148,7 @@ - + @@ -1101,7 +1157,7 @@ - + @@ -1109,7 +1165,15 @@ - + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_SIMULINK_RABBITSetup.form b/java/jdevices/src/main/resources/MARTE2_SIMULINK_RABBITSetup.form new file mode 100644 index 0000000000..cd3837f0ac --- /dev/null +++ b/java/jdevices/src/main/resources/MARTE2_SIMULINK_RABBITSetup.form @@ -0,0 +1,111 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_SIMULINK_RAPTORSetup.form b/java/jdevices/src/main/resources/MARTE2_SIMULINK_RAPTORSetup.form index 595b30d9c8..1805a4efac 100644 --- a/java/jdevices/src/main/resources/MARTE2_SIMULINK_RAPTORSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_SIMULINK_RAPTORSetup.form @@ -62,5761 +62,49 @@ - + + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/java/jdevices/src/main/resources/MARTE2_SIMULINK_TANKSetup.form b/java/jdevices/src/main/resources/MARTE2_SIMULINK_TANKSetup.form index e75914f475..43b984acce 100644 --- a/java/jdevices/src/main/resources/MARTE2_SIMULINK_TANKSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_SIMULINK_TANKSetup.form @@ -62,7 +62,7 @@ - + @@ -101,6 +101,14 @@ + + + + + + + + diff --git a/java/jdevices/src/main/resources/MARTE2_STREAM_INSetup.form b/java/jdevices/src/main/resources/MARTE2_STREAM_INSetup.form index 9e2c586002..f9ba7ae94c 100644 --- a/java/jdevices/src/main/resources/MARTE2_STREAM_INSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_STREAM_INSetup.form @@ -8,9 +8,9 @@ - + - + @@ -30,7 +30,7 @@ - + @@ -166,7 +166,7 @@ - + @@ -188,7 +188,7 @@ - + @@ -205,7 +205,7 @@ - + @@ -214,7 +214,7 @@ - + @@ -223,7 +223,7 @@ - + @@ -236,7 +236,7 @@ - + @@ -253,7 +253,7 @@ - + @@ -262,7 +262,7 @@ - + @@ -271,7 +271,7 @@ - + @@ -284,7 +284,7 @@ - + @@ -301,7 +301,7 @@ - + @@ -310,7 +310,7 @@ - + @@ -319,7 +319,7 @@ - + diff --git a/java/jdevices/src/main/resources/MARTE2_SWTRIGSetup.form b/java/jdevices/src/main/resources/MARTE2_SWTRIGSetup.form index 1a2b15e942..331db46bb3 100644 --- a/java/jdevices/src/main/resources/MARTE2_SWTRIGSetup.form +++ b/java/jdevices/src/main/resources/MARTE2_SWTRIGSetup.form @@ -22,7 +22,7 @@ - + @@ -122,7 +122,7 @@ - + @@ -131,7 +131,7 @@ - + @@ -139,7 +139,7 @@ - + @@ -147,7 +147,7 @@ - + @@ -167,7 +167,7 @@ - + @@ -176,7 +176,7 @@ - + @@ -184,7 +184,7 @@ - + @@ -192,7 +192,7 @@ - + @@ -212,7 +212,7 @@ - + @@ -221,7 +221,7 @@ - + @@ -229,7 +229,7 @@ - + @@ -237,7 +237,7 @@ - + @@ -257,7 +257,7 @@ - + @@ -266,7 +266,7 @@ - + @@ -274,7 +274,7 @@ - + @@ -282,7 +282,7 @@ - + @@ -302,7 +302,7 @@ - + @@ -311,7 +311,7 @@ - + @@ -319,7 +319,7 @@ - + @@ -327,7 +327,7 @@ - + @@ -347,7 +347,7 @@ - + @@ -356,7 +356,7 @@ - + @@ -364,7 +364,7 @@ - + @@ -372,7 +372,7 @@ - + @@ -392,7 +392,7 @@ - + @@ -401,7 +401,7 @@ - + @@ -409,7 +409,7 @@ - + @@ -417,7 +417,7 @@ - + @@ -437,7 +437,7 @@ - + @@ -446,7 +446,7 @@ - + @@ -454,7 +454,7 @@ - + @@ -462,7 +462,7 @@ - + diff --git a/java/jdispatcher/src/main/java/mds/jdispatcher/jServer.java b/java/jdispatcher/src/main/java/mds/jdispatcher/jServer.java index dacea15af9..b1f3070fd2 100644 --- a/java/jdispatcher/src/main/java/mds/jdispatcher/jServer.java +++ b/java/jdispatcher/src/main/java/mds/jdispatcher/jServer.java @@ -351,7 +351,7 @@ int doSimpleAction(String name, final String tree, final int shot) int status = 0; try { - if (mdsTree == null || !tree.equals(lastTree) || shot != lastShot) + if (mdsTree == null || !tree.equals(lastTree) || shot != lastShot || !mdsTree.isOpen()) { if (mdsTree != null) mdsTree.close(); @@ -367,6 +367,7 @@ int doSimpleAction(String name, final String tree, final int shot) catch (final MdsException exc) { logServer("Cannot Find Node ", name, " : ", exc); + logServer("Tree: ", mdsTree.getName(), " Shot: ", mdsTree.getShot()); return 0x80000000; } doingNid = node.getNid(); diff --git a/javamds/mdsobjects.c b/javamds/mdsobjects.c index 070f41ee57..d241994620 100644 --- a/javamds/mdsobjects.c +++ b/javamds/mdsobjects.c @@ -247,8 +247,11 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, return (*env)->CallStaticObjectMethodA(env, cls, constr, args); case DTYPE_NID: cls = (*env)->FindClass(env, "MDSplus/TreeNode"); +// constr = (*env)->GetStaticMethodID(env, cls, "getData", +// "(I)LMDSplus/TreeNode;"); constr = (*env)->GetStaticMethodID(env, cls, "getData", - "(I)LMDSplus/TreeNode;"); + "(ILMDSplus/Data;LMDSplus/Data;LMDSplus/" + "Data;LMDSplus/Data;)LMDSplus/TreeNode;"); args[0].i = *(int *)desc->pointer; return (*env)->CallStaticObjectMethodA(env, cls, constr, args); case DTYPE_QU: diff --git a/mdsmisc/ScopeUtilities.c b/mdsmisc/ScopeUtilities.c index 88bf783e4f..42bd0c85b9 100644 --- a/mdsmisc/ScopeUtilities.c +++ b/mdsmisc/ScopeUtilities.c @@ -188,7 +188,7 @@ static int recIsSegmented(const mdsdsc_t *const dsc) return 0; } -#define NUM_SEGMENTS_THRESHOLD 10 +#define NUM_SEGMENTS_THRESHOLD 2 #define NUM_SAMPLES_THRESHOLD 500000 /** diff --git a/pydevices/RfxDevices/MARTE2_COMPONENT.py b/pydevices/RfxDevices/MARTE2_COMPONENT.py index 78e1fd8345..2421ba6353 100644 --- a/pydevices/RfxDevices/MARTE2_COMPONENT.py +++ b/pydevices/RfxDevices/MARTE2_COMPONENT.py @@ -99,6 +99,12 @@ def buildOutputs(cls, parts): else: parts.append({'path': '.OUTPUTS.'+sigName + ':SEG_LEN', 'type': 'numeric', 'value': 0}) + if 'stream' in output: + parts.append({'path': '.OUTPUTS.'+sigName+':STREAM', + 'type': 'text', 'value': output['stream']}) + else: + parts.append({'path': '.OUTPUTS.'+sigName + + ':STREAM', 'type': 'text'}) if(output['type'] == 'string'): parts.append( @@ -150,6 +156,12 @@ def buildOutputs(cls, parts): else: parts.append({'path': '.OUTPUTS.'+sigName+'.FIELDS.' + fieldName+':SEG_LEN', 'type': 'numeric', 'value': 0}) + if 'stream' in field: + parts.append({'path': '.OUTPUTS.'+sigName+'.FIELDS.'+fieldName + + ':STREAM', 'type': 'text', 'value': field['stream']}) + else: + parts.append({'path': '.OUTPUTS.'+sigName+'.FIELDS.' + + fieldName+':STREAM', 'type': 'text'}) if(field['type'] == 'string'): parts.append( @@ -320,6 +332,7 @@ def addSignalParameters(self, parsNode, text): return text def reportParameters(self, paramDicts, outText, nTabs=1): + np.set_printoptions(threshold=np.inf) rootParDict = {} for paramDict in paramDicts: currName = paramDict['name'] @@ -489,6 +502,7 @@ def getGamInfo(self): outputDicts = [] if mode != MARTE2_COMPONENT.MODE_OUTPUT: storeSignals = False + streamSignals = False outputNids = np.sort(self.getNode('outputs').getChildren()) for outputNid in outputNids: output = TreeNode(outputNid, self.getTree()) @@ -505,6 +519,15 @@ def getGamInfo(self): if outputDict['seg_len'] > 0: storeSignals = True outputDict['samples'] = output.getNode(':samples').data() + try: + streamName = output.getNode(':stream').data() + if len(streamName) > 0: + outputDict['stream'] = streamName + streamSignals = True + else: + outputDict['stream'] = None + except: + outputDict['stream'] = None # Handle possibly structured data. In this case node 'fields' will contain a list of fields fields = [] @@ -523,6 +546,15 @@ def getGamInfo(self): ':seg_len').data() if fieldDict['seg_len'] > 0: storeSignals = True + try: + streamName = field.getNode(':stream').data() + if len(streamName) > 0: + fieldDict['stream'] = field.getNode(':stream').data() + streamSignals = True + else: + fieldDict['stream'] = None + except: + fieldDict['stream'] = None fields.append(fieldDict) except: pass @@ -553,7 +585,7 @@ def getGamInfo(self): return {'gamName': gamName, 'gamClass': gamClass, 'gamMode': gamMode, 'timebase': timebase, 'paramDicts': paramDicts, 'inputDicts': inputDicts, 'outputDicts': outputDicts, 'outputTrigger': outputTrigger, 'outTimeNid': outTimeNid, 'outTimeIdx': outTimeIdx, 'preTrigger': preTrigger, - 'postTrigger': postTrigger, 'storeSignals': storeSignals, 'cpuMask': cpuMask, 'debug': isDebug} + 'postTrigger': postTrigger, 'storeSignals': storeSignals, 'streamSignals': streamSignals, 'cpuMask': cpuMask, 'debug': isDebug} else: return {'gamName': gamName, 'gamClass': gamClass, 'gamMode': gamMode, 'timebase': timebase, 'paramDicts': paramDicts, 'inputDicts': inputDicts, 'outputDicts': outputDicts} @@ -1101,7 +1133,7 @@ def getMarteGamInfo(self, threadMap, gams, dataSources, gamList, typeDicts): if len(inputDicts) > 0: gamText += ' }\n' - # Output Signals + ######################################################### Output Signals outputSignals = [] # For debug printout synchThreadSignals = [] @@ -1459,7 +1491,137 @@ def getMarteGamInfo(self, threadMap, gams, dataSources, gamList, typeDicts): dataSourceText += ' }\n' dataSources.append(dataSourceText) -# endif configDict['storeSignals'] + # endif configDict['storeSignals'] + ###########Handle possible data streaming: declare IOGAM and StreamOut DataStream + if configDict['streamSignals']: + dataSourceText = ' +'+gamName+'_StreamOutput = {\n' + dataSourceText += ' Class = StreamOut\n' + dataSourceText += ' TimeIdx = 0\n' + dataSourceText += ' TimeStreaming = 1\n' + dataSourceText += ' CpuMask = ' + str(configDict['cpuMask'])+'\n' + dataSourceText += ' StackSize = 10000000\n' + dataSourceText += ' NumberOfBuffers = 10\n' + dataSourceText += ' Signals = {\n' + dataSourceText += ' Time = {\n' + dataSourceText += ' NumberOfDimensions = 0\n' + dataSourceText += ' NumberOfElements = 1\n' + dataSourceText += ' Channel = "'+gamName+'_Time"\n' + dataSourceText += ' }\n' + for outputDict in outputDicts: + if outputDict['stream'] != None: + dataSourceText += ' '+outputDict['name']+' = {\n' + dataSourceText += ' Channel = "' + outputDict['stream']+'"\n' + dataSourceText += ' }\n' + # Check if the output is a struct and seglen is > 0 for one o more fields + for fieldDict in outputDict['fields']: + if fieldDict['stream'] != None: + dataSourceText += ' ' + outputDict['name']+'_'+fieldDict['name']+' = {\n' + dataSourceText += ' Channel = "' + fieldDict['stream']+'"\n' + dataSourceText += ' }\n' + # end for fieldDict in outputDict['fields']: + dataSourceText += ' }\n' + dataSourceText += ' }\n' + dataSources.append(dataSourceText) + + gamList.append(gamName+'_StreamOutIOGAM') + gamText = ' +'+gamName+'_StreamOutIOGAM = {\n' + gamText += ' Class = IOGAM\n' + gamText += ' InputSignals = {\n' +# Time signal management + gamText += ' Time = {\n' + gamText += ' DataSource = ' + timerDDB+'\n' + gamText += ' Type = uint32\n' + gamText += ' }\n' +# first non struct outputs + for outputDict in outputDicts: + if outputDict['stream'] != None and len(outputDict['fields']) == 0: + gamText += ' '+outputDict['name'] + ' = {\n' + gamText += ' DataSource = '+gamName+'_Output_DDB\n' + gamText += ' Type = ' + outputDict['type']+'\n' + gamText += ' }\n' +# then struct outputs for which at least one field has stream != None + for outputDict in outputDicts: + fieldsToStream = False + for fieldDict in outputDict['fields']: + if fieldDict['stream'] != None: + fieldsToStream = True + if fieldsToStream: + gamText += ' '+outputDict['name'] + ' = {\n' + gamText += ' DataSource = '+gamName+'_Output_DDB\n' + gamText += ' Type = ' + outputDict['type']+'\n' + gamText += ' }\n' + # end for outputDict in outputDicts: + + gamText += ' }\n' + gamText += ' OutputSignals = {\n' + gamText += ' Time = {\n' + gamText += ' DataSource = '+gamName+'_StreamOutput\n' + gamText += ' Type = uint32\n' + gamText += ' }\n' +# Other signals + for outputDict in outputDicts: + # first non struct outputs + if outputDict['stream'] != None and len(outputDict['fields']) == 0: + gamText += ' '+outputDict['name'] + ' = {\n' + gamText += ' DataSource = '+gamName+'_StreamOutput\n' + gamText += ' Type = '+outputDict['type']+'\n' + if outputDict['dimensions'] == 0: + numberOfElements = 1 + numberOfDimensions = 0 + else: + numberOfDimensions = len(outputDict['dimensions']) + numberOfElements = 1 + for currDim in outputDict['dimensions']: + numberOfElements *= currDim + gamText += ' NumberOfDimensions = ' + \ + str(numberOfDimensions)+'\n' + gamText += ' NumberOfElements = ' + \ + str(numberOfElements)+'\n' + + gamText += ' }\n' + + needsOutStream_Bus_DDB = False + for outputDict in outputDicts: # split fileds of structured outputs for which at least one field has seg_len > 0 + fieldsToStream = False + for fieldDict in outputDict['fields']: + if fieldDict['stream'] != None: + fieldsToStream = True + if fieldsToStream: + for fieldDict in outputDict['fields']: + gamText += ' ' + \ + outputDict['name']+'_'+fieldDict['name']+' = {\n' + gamText += ' Type = ' + fieldDict['type']+'\n' + if fieldDict['dimensions'] == 0: + numberOfElements = 1 + numberOfDimensions = 0 + else: + numberOfDimensions = len(fieldDict['dimensions']) + numberOfElements = 1 + for currDim in fieldDict['dimensions']: + numberOfElements *= currDim + gamText += ' NumberOfDimensions = ' + \ + str(numberOfDimensions)+'\n' + gamText += ' NumberOfElements = ' + \ + str(numberOfElements)+'\n' + if fieldDict['stream'] != None: + gamText += ' DataSource = '+gamName+'_StreamOutput\n' + else: + needsOutStream_Bus_DDB = True + gamText += ' DataSource = '+gamName+'_OutStream_Bus_DDB\n' + gamText += ' }\n' + # end if fieldsToStore + # end for outputDict in outputDicts: + gamText += ' }\n' + gamText += ' }\n' + gams.append(gamText) + + if needsOutStream_Bus_DDB: + dataSourceText = ' +'+gamName+'_OutStream_Bus_DDB = {\n' + dataSourceText += ' Class = GAMDataSource\n' + dataSourceText += ' }\n' + dataSources.append(dataSourceText) + + # endif configDict['streamSignals'] # Check now if there are structured input signals not directly linked. For these signals, all their fields must be linked. In thic case a new # IOGAM and DDB DDB will be created @@ -1610,7 +1772,8 @@ def getMarteGamInfo(self, threadMap, gams, dataSources, gamList, typeDicts): dataSourceText += ' '+nodeDict['name']+' = {\n' valExpr = nodeDict['expr'] if isinstance(valExpr, TreeNode): - valExpr = valExpr.getFullPath() +# valExpr = valExpr.getPath() + valExpr = str(valExpr) else: valExpr = str(valExpr) dataSourceText += ' DataExpr = "'+valExpr+'"\n' diff --git a/pydevices/RfxDevices/MARTE2_SIMULINK.py b/pydevices/RfxDevices/MARTE2_SIMULINK.py index 2e5939663a..002b22e74e 100644 --- a/pydevices/RfxDevices/MARTE2_SIMULINK.py +++ b/pydevices/RfxDevices/MARTE2_SIMULINK.py @@ -63,9 +63,9 @@ def BUILDER(cls): mmi = GetMmiPtr(states) # Initialization function is called with a dynamically-specified name - InitializeFunc = getattr(ModelLib, initializeFuncName) - InitializeFunc.argtypes = [ctypes.POINTER(None)] - InitializeFunc(states) +# InitializeFunc = getattr(ModelLib, initializeFuncName) +# InitializeFunc.argtypes = [ctypes.POINTER(None)] +# InitializeFunc(states) WrapperLib = ctypes.cdll.LoadLibrary("rtw_capi_wrapper.so") @@ -213,7 +213,7 @@ def GetSignalData(SignalStruct, numOfSignals): retrievedName = WrapperLib.WCAPI_GetSignalName( SignalStruct, signalIdx) retrievedName = retrievedName.decode("utf-8") - print('SIGNAL NAME: ' + retrievedName); + #print('SIGNAL NAME: ' + retrievedName); # retrievedName = removeAngular(retrievedName) # type is retrieved @@ -432,15 +432,15 @@ def GetModelParameterData(ParameterStruct, numOfParameters): retrievedName = WrapperLib.WCAPI_GetModelParameterName( ParameterStruct, paramIdx) retrievedName = retrievedName.decode("utf-8") - print('retrievedname: ', retrievedName) + #print('retrievedname: ', retrievedName) # type is retrieved retrievedTypeIdx = WrapperLib.WCAPI_GetModelParameterDataTypeIdx( ParameterStruct, paramIdx) - print('retrievedTypeIdx: ', str(retrievedTypeIdx)) + #print('retrievedTypeIdx: ', str(retrievedTypeIdx)) retrievedSLIdType = WrapperLib.WCAPI_GetDataTypeSLId( DataTypeMap, retrievedTypeIdx) - print('retrievedSLIdType: ', str(retrievedSLIdType)) + #print('retrievedSLIdType: ', str(retrievedSLIdType)) #retrievedCTypename = WrapperLib.WCAPI_GetDataTypeCName( # DataTypeMap, retrievedTypeIdx) #retrievedCTypename = retrievedCTypename.decode("utf-8") @@ -736,7 +736,7 @@ def GetModelParameterData(ParameterStruct, numOfParameters): #paramList.append(paramDict) #endif STRUCTURED PARAMETER #endfor parameters - print('PARAMETRI FATTI') + #print('PARAMETRI FATTI') return paramList ################################################################# @@ -755,21 +755,21 @@ def GetModelParameterFields(structTypeIdx, ParameterStruct, paramIdx, baseParNam ParameterStruct, paramIdx) paramDataAddr = WrapperLib.WCAPI_GetDataAddress( DataAddrMap, paramAddrIdx) - print('NUM FIELDS: '+str(numFields)) + #print('NUM FIELDS: '+str(numFields)) for fieldIdx in range(numFields): fieldName = WrapperLib.WCAPI_GetElementName( ElementMap, elementMapIndex + fieldIdx) fieldName = fieldName.decode("utf-8") - print('FIELD: '+baseParName+'-'+fieldName) + #print('FIELD: '+baseParName+'-'+fieldName) fieldOffset = WrapperLib.WCAPI_GetElementOffset( ElementMap, elementMapIndex + fieldIdx) fieldTypeIdx = WrapperLib.WCAPI_GetElementDataTypeIdx( ElementMap, elementMapIndex + fieldIdx) - print('fieldTypeIdx: '+str(fieldTypeIdx)) + #print('fieldTypeIdx: '+str(fieldTypeIdx)) fieldSLIdType = WrapperLib.WCAPI_GetDataTypeSLId( DataTypeMap, fieldTypeIdx) - print('fieldSLIdType: '+str(fieldSLIdType)) + #print('fieldSLIdType: '+str(fieldSLIdType)) if fieldSLIdType == 0: fieldMARTe2Typename = 'float64' fieldPythonTypename = ctypes.c_double @@ -827,7 +827,7 @@ def GetModelParameterFields(structTypeIdx, ParameterStruct, paramIdx, baseParNam print('type '+str(fieldEnumType)) raise Exception('Unsupported Enum datatype.') else: #NESTED STRUCTURES!!!!!!!!!!!!!!!! - print('TYPE '+str(fieldSLIdType) + ' '+str(fieldTypeIdx)) + #print('TYPE '+str(fieldSLIdType) + ' '+str(fieldTypeIdx)) GetModelParameterFields(fieldTypeIdx, ParameterStruct, paramIdx, baseParName + '-'+fieldName, paramList, recLev+1) continue #no direct data associated # field dimensions @@ -840,7 +840,7 @@ def GetModelParameterFields(structTypeIdx, ParameterStruct, paramIdx, baseParNam # Number of elements in the dimensionArray referring to this signal fieldDimNum = WrapperLib.WCAPI_GetNumDims( DimensionMap, fieldDimIdx) - print('fieldDimNum: '+ str(fieldDimNum)) + #print('fieldDimNum: '+ str(fieldDimNum)) currDimension = [] for currIdx in range(fieldDimNum): currDimension.append( diff --git a/pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py b/pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py new file mode 100644 index 0000000000..87dfd9a43d --- /dev/null +++ b/pydevices/RfxDevices/MARTE2_SIMULINK_FLUXMAP.py @@ -0,0 +1,31 @@ +# +# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation and/or +# other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +MARTE2_SIMULINK = __import__('MARTE2_SIMULINK', globals()) + + +@MARTE2_SIMULINK.BUILDER +class MARTE2_SIMULINK_FLUXMAP(MARTE2_SIMULINK.MARTE2_SIMULINK): + lib_name = 'FLUXMAP_JET' diff --git a/pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py b/pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py new file mode 100644 index 0000000000..61de7dccff --- /dev/null +++ b/pydevices/RfxDevices/MARTE2_SIMULINK_RABBIT.py @@ -0,0 +1,31 @@ +# +# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation and/or +# other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +MARTE2_SIMULINK = __import__('MARTE2_SIMULINK', globals()) + + +@MARTE2_SIMULINK.BUILDER +class MARTE2_SIMULINK_RABBIT(MARTE2_SIMULINK.MARTE2_SIMULINK): + lib_name = 'RABBIT_JET' diff --git a/pydevices/RfxDevices/RFX_RPADC.py b/pydevices/RfxDevices/RFX_RPADC.py index 16ab12050f..e0efdee3a6 100644 --- a/pydevices/RfxDevices/RFX_RPADC.py +++ b/pydevices/RfxDevices/RFX_RPADC.py @@ -178,6 +178,11 @@ def init(self): print('Cannot get decimation') raise mdsExceptions.TclFAILED_ESSENTIAL print('CLOCK') + try: + trig = self.trigger.getData() + except: + print('Cannot get trigger') + raise mdsExceptions.TclFAILED_ESSENTIAL if self.clock_mode.data() != 'INTERNAL': try: if self.clock_mode.data() == 'HIGHWAY': @@ -229,6 +234,8 @@ def init(self): def start_store(self): try: + self.raw_a.deleteData() + self.raw_b.deleteData() worker = self.AsynchStore() worker.configure(self.conf) worker.daemon = True @@ -246,10 +253,10 @@ def start_store(self): def stop_store(self): try: self.conf.lib.rpadcStop(self.conf.fd) - try: - RFX_RPADC.triggerEv.cancel() - except: - pass + #try: + #RFX_RPADC.triggerEv.cancel() + #except: + #pass except: raise mdsExceptions.TclFAILED_ESSENTIAL From 4e355a783a8c73a164f0cb212400c72c2c9e0327 Mon Sep 17 00:00:00 2001 From: Timo Schroeder Date: Wed, 19 May 2021 23:18:52 +0200 Subject: [PATCH 26/27] Feature: MdsIpThreadStatic ConnectionList; should fix deadlock and be faster (#2288) * clang-format * Fixed race conditions in ServerBuildDispatchTable * fix memory leaks in TclDispatch_show_server and in ServerMonitoCheckin * removed tdicompile DEBUG * MdsipThreadStatic * SendMdsMsg send_bytes * client_event_ast use GetConnectionClientType * MdsIpGetDescriptor use GetConnectionVersion * use Invalid Connection in ConnectToMds * ConnectionLock Sending to Requests * eliminate cvtdef * DoMessage: status and close * DoMessage is an Activity * CloseConnection tdicontext * GetMdsMsg.c as recv * ProcessMessage: debug send reply * PopConnection * threadstatic client addr * updated ioroutinesx * ioroutined tcp threaded * python fixed Connection object * Client used threaded connections * fixed race on connection_id thru local lock * memory leak in pipes * cleanup destroyConnection etc * cleanup thread static connections * invalis message_id * io dont destroy * io race * atexit() and udt extracted refresh_list() * race in AcceptConnection * windows io_pipes_t init * pop_client * try multithreaded udt * fixed username in AcceptConnection * udt: better error message * fixed cleanup,; ClientList->next * pipes fixed * cleanup destroy * fixed memory leak in IoThread * revert kind of.. ProcessMessage returns with TRUE if message free is handled * fixed cleanup in TdiGetData * fixed memory leak in servershr * added suppression for glibc getservbyname * status: fixed RETURN_IF_STATUS_NOT_OK * fixed memoryleak in TdiCall * replaced all DBG with mdsdbg.h * added potential debug messages and fixed servershr issue in ReplyThread * python tests: can use external action monitor * removed mdsdebug.c * generically fixed (status & 1) and !(status & 1) * fixed (!status & 1) in dwscope, xmdsshr, and hdf5 * added time to DBG * added more potential debug messages * cleanup do_callback_done and debug * shortcut if connection id invalid * use JOB_PRI and CLIENT_PRI and fixed JobId * fixed Exception issues in a3248.py * fixed mdslib status * fixed mdsip setup/cleanup in python tests * dont try to stop server; this may hang * cleanup DispatchPhase; disable ACTION_DONE_THREAD * make_idents fixup type * fixed mdsdbg if not DEBUG * moved private shared includes out of teh way * fixed ACTION_DBG * socket_port includes socket error handling for windows * deal with oses without MSG_NOSIGNAL * disconnect on destroy * moved mit headers to mitdevices * fixed pointer issues in Xmds * fixed misc pointer issues * safe load_lib in librtl * replace with MUTEXT_LOCK_PUSH * DEFINE_INITIALIZESOCKETS * servershr: action_done lock * include socket_port fiorst for windows winsock2 order * servershr/ debug * avoid static vars in javamds * added MdsIpTest and fixed client side MdsIpGetDescriptor * fixed mdsip SerialIO * fixed alpine and disable debug * addresses issues popped by macosx * suppress python leaks and make race condition of STATIC_debug values more obvious * suppress helgrind misc in dlopen * handle clobbered in LibFreeVm * wait for mdsip server in _start_mdsip * user tcpv6 as default protocol * Windows socket error use FormatMessageW to get propert message * mdstcpip: make tracks changes in io_routines headers * move io_check to tcp header * Tests: no need for pthread.h in mdsip and added mdsip tcp in tests * cleanup UdpEvent in mdsshr * decouple socket_port and pthread_port headers * mdsmsg.h and cpp thread helper to support both posix and windows * removed Threads from testutils as it could block under windows * Close ocket to signal cancel in ioreoutinesx.h * avoid pthread_cancel for Win32 in MDSIpTest * fixe race in UdpEvent again * mdstcpip tests-valgrind * Windows cannot really do tcpv6 * fail with -1 on MdsConnect * setting: mdsip timeout 10 sec not infty * fixed connect and listen * TRY disconnect in thread * use compression not maxcompression on windows service * cleanup deprecated methods * clang-format.sh * STATIC_lock for STATIC * missing newline * suppress _PyObject_MakeTpCall holds lock on exit * call it action * activated some debug messages * accessible TestEnv * Makefile servershr depend on servershrp.h * ServerShr debug * use strdup * include threadid in debug * some cleanup in servershr * fixup python tests * more verbosity if debug symbols are added * fixed PATH_DOWN issue on dispatch * suppress Server unknown message * added python helgrind suppression * fixed race on free in ServerWait * fixed tditests against variables and different OS * fixed memory leak in ShowServerInfo * fixed tdi tests * macosx does not do gettid or getpid * clobbered in ServerConnect * cloberser in Client_remove * fixup abandon * use mdsshr (private) LibGetHostAddr * clobbered err in Job_wait_and_pop_by_jobid * fixed _LibGetHostAddr signature and portstr * Windows become_user with words * fixed mdstcpip brought windows and linux closer * fixed mdsip more shared code betewwn windows and linux * clang and fixed remaining pthread_cancel * Windows dsc_dispatcher_test runs when started manually wine python -B /git/mdsplus/testing/testing.py /dcl_dispatcher_test.py * initialize lerror * use same executions in tditest * allow to change default mdsip protocoll but dont use tcpv6 as default * alpine has a lower default thread stack size. set size to working value * suppress message on connection close * fixed RemoteAccess to work with multithreaded segment remote writes * activated and standadized connection_write_test * MDSSHR_LOAD_LIBROUTINE to load from other lib * cleanup treeshr RemoteAccess * Connection debug messages * IoRoutinesTunnel: redirect stdout for windows * clang python_test * PIPES_OBJECTS depend on ioroutines_pipes.h * mdsipshr/ConnectToMds.c * io_routines/IoRoutinesTunnel.c * cleanup Connections, set flag if in list * use fixup_eventname * mdsipshar depends on mdsip_connections.h * CON_PRI and CON_VAR pair for messages * HOST_PRI and HOST_VAR pair and fixed leak * fixed MdsEvent alloc_eventname * used strdup where possible * tcl cleanup mdsdclAddCommands * cleanup complexity of send_response * connection_write_test.py causes valgrind to hang? * use mdsip_stop to clean up * reenable SetMdsplusFileProtection suppression * added timeout to assertRun * debug strings in mdsipshr * eliminated confusing STATCIdef.h * use more advanced version for clock_gettime substitutes * fixed deadlock if job finishes fast * final clang-format * python.Connection, removed to local for a conn Co-authored-by: Timo Schroeder --- .gitignore | 1 + Makefile.inc.in | 2 +- _include/P2WMutex.hpp | 282 ++++ _include/P2WSem.hpp | 72 + _include/P2WThread.hpp | 350 +++++ .../WindowsUnnamedSemaphore.h | 0 _include/_mdsshr.h | 22 + {include => _include}/condition.h | 18 +- {include => _include}/coz.h | 0 {include => _include}/getusername.h | 0 {include => _include}/int128.h | 0 _include/mdsmsg.h | 99 ++ {include => _include}/pthread_port.h | 51 +- _include/socket_port.h | 152 ++ actions/actlogp.h | 2 +- camshr/RemCamMulti.c | 10 +- camshr/RemCamSingle.c | 6 +- camshr/cam_functions.c | 4 +- camshr/get_crate_status.c | 4 +- camshr/turn_crate_on_off_line.c | 3 +- camshr/verbs.c | 2 +- ccl/ccl_verbs.c | 6 +- conf/valgrind.supp/fc32.supp | 54 +- conf/valgrind.supp/mdsplus.supp | 2 +- configure.ac | 9 +- deploy/packaging/debian/devel.noarch | 10 - deploy/packaging/redhat/devel.noarch | 10 - deploy/platform/platform_docker_build.sh | 2 +- .../redpitaya/AsyncStoreManager.cpp | 34 +- device_support/redpitaya/AsyncStoreManager.h | 13 +- device_support/redpitaya/redpitaya.cpp | 24 +- device_support/redpitaya/rfx_stream.h | 194 ++- dwscope/evaluate.c | 5 +- epics/mdsrecords/mdsexprRecord.c | 2 +- epics/mdsrecords/mdsputRecord.c | 2 +- hdf5/MDSplus2HDF5.c | 14 +- hdf5/dynhdf5.c | 2 +- hdf5/hdf5ToMds.c | 4 +- hdf5/hdf5tdi.c | 14 +- idlmdsevent/mdsevent.c | 19 +- idlmdswidgets/cw_wveditv5.c | 8 +- include/STATICdef.h | 6 - include/ipdesc.h | 9 +- include/libroutines.h | 2 - include/mdsdescrip.h | 10 +- include/mdsobjects.h | 4 +- include/mdsshr.h | 1 + include/socket_port.h | 61 - include/status.h | 6 +- .../src/test/java/mds/MdsShr_Test.java | 2 +- javamds/ServerSupport.c | 66 +- javamds/mdsobjects.c | 236 ++- m4/m4_ax_check_enable_debug.m4 | 16 +- m4/m4_ax_mdsplus_testing.m4 | 13 +- m4/m4_ax_valgrind_check.m4 | 3 +- math/umach.f | 77 +- mdsdcl/cmdExecute.c | 49 +- mdsdcl/yylex/cmdParse.l | 16 +- mdsdebug.c | 70 - mdsdebugc.c | 68 - mdslib/MdsLib.c | 50 +- mdslib/testing/dtype_test.c | 31 +- mdslib/testing/mdslib_ctest.c | 24 +- mdslibidl/MdsLibIdl.c | 8 +- mdsmisc/ScopeUtilities.c | 5 +- mdsmisc/getreferences.c | 4 +- mdsobjects/cpp/mdsdata.c | 46 +- mdsobjects/cpp/mdsdataobjects.cpp | 8 +- mdsobjects/cpp/mdsipobjects.cpp | 20 +- mdsobjects/cpp/mdsobjects.c | 62 +- mdsobjects/cpp/mdstree.c | 6 +- mdsobjects/cpp/mdstreeobjects.cpp | 160 +- mdsobjects/cpp/testing/MdsDataStreamTest.c | 4 +- mdsobjects/cpp/testing/MdsTdiTest.cpp | 18 +- mdsobjects/cpp/testing/testutils/Makefile.am | 5 +- mdsobjects/cpp/testing/testutils/Threads.h | 41 - mdsshr/MDSprintf.c | 9 +- mdsshr/Makefile.in | 6 +- mdsshr/MdsCmprs.c | 7 +- mdsshr/MdsCompress.c | 49 +- mdsshr/MdsEvents.c | 298 ++-- mdsshr/MdsGet1DxA.c | 1 - mdsshr/MdsGet1DxS.c | 1 - mdsshr/MdsGetSetShotId.c | 1 - mdsshr/MdsPk.c | 5 +- mdsshr/MdsSerialize.c | 15 +- mdsshr/MdsThreadStatic.c | 7 +- mdsshr/MdsXdRoutines.c | 1 - mdsshr/UdpEventSettings.c | 19 +- mdsshr/UdpEvents.c | 206 +-- mdsshr/librtl.c | 268 ++-- mdsshr/mds_dsc_string.c | 1 - mdsshr/mdsthreadstatic.h | 5 +- mdsshr/testing/Makefile.am | 18 +- mdsshr/testing/UdpEventsTest.c | 28 +- mdsshr/testing/UdpEventsTestStatics.c | 91 +- mdstcpip/Makefile.in | 63 +- mdstcpip/io_routines/IoRoutinesGsi.c | 10 +- mdstcpip/io_routines/IoRoutinesThread.c | 62 +- mdstcpip/io_routines/IoRoutinesTunnel.c | 76 +- mdstcpip/io_routines/ioroutines.h | 13 +- mdstcpip/io_routines/ioroutinesV6.h | 12 +- mdstcpip/io_routines/ioroutines_pipes.h | 89 +- mdstcpip/io_routines/ioroutinestcp.h | 566 ++++--- mdstcpip/io_routines/ioroutinesudt.h | 152 +- mdstcpip/io_routines/ioroutinesx.h | 355 +++-- mdstcpip/mdsIo.h | 7 +- mdstcpip/mdsip.c | 3 +- mdstcpip/mdsip_connections.h | 117 +- mdstcpip/mdsip_service.c | 6 +- mdstcpip/mdsipshr/CheckClient.c | 5 +- mdstcpip/mdsipshr/ConnectToMds.c | 129 +- mdstcpip/mdsipshr/Connections.c | 486 +++--- mdstcpip/mdsipshr/DoMessage.c | 40 +- mdstcpip/mdsipshr/GetAnswerInfo.c | 4 +- mdstcpip/mdsipshr/GetMdsMsg.c | 78 +- mdstcpip/mdsipshr/GetSetSettings.c | 236 ++- mdstcpip/mdsipshr/IdlApi.c | 51 +- mdstcpip/mdsipshr/LoadIo.c | 3 +- mdstcpip/mdsipshr/MdsClose.c | 5 +- mdstcpip/mdsipshr/MdsEventAst.c | 2 +- ...{CloseConnection.c => MdsIpThreadStatic.c} | 62 +- mdstcpip/mdsipshr/MdsOpen.c | 3 +- mdstcpip/mdsipshr/MdsPut.c | 1 - mdstcpip/mdsipshr/MdsSetCompression.c | 4 - mdstcpip/mdsipshr/MdsSetDefault.c | 5 +- mdstcpip/mdsipshr/MdsValue.c | 59 +- mdstcpip/mdsipshr/ParseCommand.c | 13 +- mdstcpip/mdsipshr/ProcessMessage.c | 1320 +++++++++-------- mdstcpip/mdsipshr/SendArg.c | 5 +- mdstcpip/mdsipshr/SendMdsMsg.c | 86 +- mdstcpip/mdsipshr/cvtdef.h | 51 - mdstcpip/mdsipshr/mdsipthreadstatic.h | 18 + mdstcpip/testing/Makefile.am | 41 + mdstcpip/testing/MdsIpTest.c | 227 +++ mdstcpip/testing/mdscp.c | 20 +- mdstcpip/testing/mdsiptest.c | 68 - mitdevices/DevRoutines.c | 6 +- mitdevices/GenDeviceCallData.c | 12 +- mitdevices/GenDeviceCvtStringCode.c | 2 +- mitdevices/GenDeviceFree.c | 2 +- mitdevices/Makefile.in | 7 +- mitdevices/a12.c | 12 +- mitdevices/a12_gen.c | 6 +- mitdevices/a14.c | 12 +- mitdevices/a14_gen.c | 18 +- mitdevices/a3204.c | 6 +- mitdevices/a3204_gen.c | 18 +- mitdevices/b2408.c | 4 +- mitdevices/b2408_gen.c | 18 +- mitdevices/b3224.c | 2 +- mitdevices/b3224_gen.c | 18 +- mitdevices/b5910a.c | 12 +- mitdevices/b5910a_gen.c | 18 +- mitdevices/dsp2904.c | 14 +- mitdevices/dsp2904_gen.c | 18 +- mitdevices/dt200.c | 2 +- mitdevices/dt_acq16.c | 2 +- mitdevices/ec727.c | 10 +- mitdevices/ec727_gen.c | 18 +- mitdevices/fera.c | 20 +- mitdevices/fera_gen.c | 18 +- mitdevices/gen_device_msg.c | 2 +- mitdevices/h908.c | 12 +- mitdevices/h908_gen.c | 18 +- mitdevices/h911.c | 6 +- mitdevices/h911_gen.c | 18 +- mitdevices/h912.c | 12 +- mitdevices/h912_gen.c | 18 +- mitdevices/hm650.c | 8 +- mitdevices/hm650_gen.c | 18 +- mitdevices/hv1440.c | 10 +- mitdevices/hv1440_gen.c | 18 +- mitdevices/hv1443.c | 6 +- mitdevices/hv1443_gen.c | 18 +- mitdevices/hv4032.c | 8 +- mitdevices/hv4032_gen.c | 18 +- mitdevices/hv4032a1.c | 6 +- mitdevices/hv4032a1_gen.c | 18 +- mitdevices/idl.c | 8 +- mitdevices/idl_gen.c | 18 +- mitdevices/incaa16.c | 14 +- mitdevices/incaa16_gen.c | 18 +- mitdevices/incaa4.c | 14 +- mitdevices/incaa4_gen.c | 18 +- mitdevices/incaa6.c | 16 +- mitdevices/incaa6_gen.c | 18 +- mitdevices/j1819.c | 6 +- mitdevices/j1819_gen.c | 18 +- mitdevices/j221.c | 18 +- mitdevices/j221_gen.c | 18 +- mitdevices/j412.c | 10 +- mitdevices/j412_gen.c | 18 +- mitdevices/joerger_adc.c | 4 +- mitdevices/joerger_adc_gen.c | 18 +- mitdevices/joerger_adcp.c | 4 +- mitdevices/joerger_adcp_gen.c | 18 +- mitdevices/joerger_cg.c | 4 +- mitdevices/joerger_cg_gen.c | 18 +- mitdevices/joerger_dac16.c | 4 +- mitdevices/joerger_dac16_gen.c | 18 +- mitdevices/joerger_tr16.c | 16 +- mitdevices/joerger_tr16_gen.c | 18 +- mitdevices/joerger_tr612.c | 12 +- mitdevices/joerger_tr612_gen.c | 18 +- mitdevices/joerger_tr812.c | 12 +- mitdevices/joerger_tr812_gen.c | 18 +- mitdevices/l2232.c | 4 +- mitdevices/l2232_gen.c | 18 +- mitdevices/l2256.c | 6 +- mitdevices/l2256_gen.c | 18 +- mitdevices/l2415.c | 4 +- mitdevices/l2415_gen.c | 18 +- mitdevices/l3512.c | 4 +- mitdevices/l3512_gen.c | 18 +- mitdevices/l3512a.c | 4 +- mitdevices/l3512a_gen.c | 18 +- mitdevices/l4202.c | 4 +- mitdevices/l4202_gen.c | 18 +- mitdevices/l6810.c | 12 +- mitdevices/l6810_gen.c | 18 +- mitdevices/l6810a.c | 14 +- mitdevices/l6810a_gen.c | 18 +- mitdevices/l6810b.c | 14 +- mitdevices/l6810b_gen.c | 18 +- mitdevices/l6810c.c | 14 +- mitdevices/l6810c_gen.c | 18 +- mitdevices/l8100.c | 8 +- mitdevices/l8100_gen.c | 18 +- mitdevices/l8201.c | 4 +- mitdevices/l8201_gen.c | 18 +- mitdevices/l8206.c | 6 +- mitdevices/l8206_gen.c | 18 +- mitdevices/l8210.c | 30 +- mitdevices/l8210_gen.c | 18 +- mitdevices/l8212.c | 26 +- mitdevices/l8212_04_gen.c | 18 +- mitdevices/l8212_08_gen.c | 18 +- mitdevices/l8212_16_gen.c | 18 +- mitdevices/l8212_32_gen.c | 18 +- mitdevices/l8501.c | 8 +- mitdevices/l8501_gen.c | 18 +- mitdevices/l8590.c | 8 +- mitdevices/l8590_gen.c | 18 +- mitdevices/l8590_mem.c | 12 +- mitdevices/l8590_mem_gen.c | 18 +- mitdevices/l8590_sclr_gen.c | 18 +- mitdevices/l8818.c | 12 +- mitdevices/l8818_gen.c | 18 +- mitdevices/l8828.c | 12 +- mitdevices/l8828_gen.c | 18 +- {include => mitdevices}/mds_gendevice.h | 60 +- mitdevices/mdsdcl.c | 8 +- mitdevices/mdsdcl_gen.c | 18 +- mitdevices/mit__clock.c | 6 +- mitdevices/mit__clock_gen.c | 18 +- mitdevices/mit__dclock.c | 6 +- mitdevices/mit__dclock_gen.c | 18 +- mitdevices/mit__gate.c | 8 +- mitdevices/mit__gate_gen.c | 18 +- mitdevices/mit_clock.c | 12 +- mitdevices/mit_clock_gen.c | 18 +- mitdevices/mit_dclock.c | 10 +- mitdevices/mit_dclock_gen.c | 18 +- mitdevices/mit_decoder.c | 14 +- mitdevices/mit_decoder_gen.c | 18 +- mitdevices/mit_encoder.c | 8 +- mitdevices/mit_encoder_gen.c | 18 +- mitdevices/mit_gate_gen.c | 18 +- mitdevices/mit_gclock.c | 12 +- mitdevices/mit_gclock_gen.c | 18 +- mitdevices/mit_pulse-gate.c | 8 +- mitdevices/mit_pulse_gen.c | 18 +- mitdevices/mitdevices_msg.c | 2 +- {include => mitdevices}/mitdevices_msg.h | 0 mitdevices/mpb__decoder.c | 42 +- mitdevices/mpb__decoder_gen.c | 18 +- mitdevices/paragon_hist.c | 10 +- mitdevices/paragon_hist_gen.c | 18 +- mitdevices/paragon_rpt.c | 6 +- mitdevices/paragon_rpt_gen.c | 18 +- mitdevices/preamp.c | 10 +- mitdevices/preamp_gen.c | 18 +- mitdevices/reticon120.c | 22 +- mitdevices/reticon120_gen.c | 18 +- mitdevices/t2812_gen.c | 18 +- mitdevices/t2814_gen.c | 18 +- mitdevices/t2824_gen.c | 18 +- mitdevices/t2825_gen.c | 18 +- mitdevices/t2860_gen.c | 18 +- mitdevices/t4012.c | 28 +- mitdevices/t4012_gen.c | 18 +- mitdevices/u_of_m_spect.c | 4 +- mitdevices/u_of_m_spect_gen.c | 18 +- mitdevices/umccd_gen.c | 18 +- php/mdsplus.c | 26 +- pydevices/MitDevices/a3248.py | 86 +- python/MDSplus/connection.py | 187 ++- python/MDSplus/tests/Makefile.am | 9 +- python/MDSplus/tests/_common.py | 147 +- python/MDSplus/tests/connection_case.py | 206 ++- python/MDSplus/tests/dcl_case.py | 101 +- remcam/CamMulti.c | 10 +- remcam/CamSingle.c | 6 +- roam/roam_gridmap_callout.c | 2 +- servershr/Client.h | 228 +++ servershr/Job.h | 264 ++++ servershr/Makefile.in | 2 + servershr/ServerBuildDispatchTable.c | 215 +-- servershr/ServerDispatchClose.c | 4 +- servershr/ServerDispatchPhase.c | 660 +++++---- servershr/ServerFindServers.c | 2 +- servershr/ServerGetInfo.c | 84 +- servershr/ServerMonitorCheckin.c | 68 +- servershr/ServerQAction.c | 355 +++-- servershr/ServerSendMessage.c | 760 +++------- servershr/ServerSetDetailProc.c | 14 +- servershr/servershrp.h | 14 + tcl/tcl_delete_node.c | 2 +- tcl/tcl_directory.c | 2 +- tcl/tcl_dispatch.c | 2 + tcl/tcl_help_device.c | 2 +- tcl/tcl_set_callbacks.c | 13 +- tcl/tcl_set_node.c | 12 +- tcl/tcl_set_readonly.c | 2 +- tcl/tcl_set_tree.c | 6 +- tcl/tcl_set_view.c | 2 +- tcl/tcl_setshow_attribute.c | 10 +- tcl/tcl_setshow_versions.c | 6 +- tcl/tcl_wfevent.c | 2 +- tdic/TdiShrExt.c | 16 +- tdic/tdic.c | 2 +- tdishr/CvtConvertFloat.c | 4 +- tdishr/TdiCall.c | 116 +- tdishr/TdiCompile.c | 10 +- tdishr/TdiDoTask.c | 7 +- tdishr/TdiExtPython.c | 35 +- tdishr/TdiGetData.c | 333 +++-- tdishr/TdiSubscript.c | 3 +- tdishr/TdiVar.c | 21 +- tdishr/TdiYaccSubs.c | 12 +- tdishr/cvtdef.h | 52 - tdishr/tdirefstandard.h | 2 +- tditest/testing/do_tditests.sh | 140 +- tditest/testing/test-mdsip.ans | 2 +- tditest/testing/test-tcl.ans | 4 +- tditest/testing/test-tcl.tdi | 2 +- testing/Makefile.am | 19 +- testing/helgrind | 1 + testing/memcheck | 1 + traverser/CallbacksUil.c | 40 +- traverser/GetSupportedDevices.c | 2 +- treeshr/RemoteAccess.c | 381 ++--- treeshr/TreeAddNode.c | 42 +- treeshr/TreeAddTag.c | 3 +- treeshr/TreeCallHook.c | 1 - treeshr/TreeCleanDatafile.c | 3 +- treeshr/TreeCreatePulseFile.c | 17 +- treeshr/TreeDeleteNode.c | 5 +- treeshr/TreeDeletePulseFile.c | 11 +- treeshr/TreeDoMethod.c | 1 - treeshr/TreeFindNode.c | 4 +- treeshr/TreeGetDbi.c | 4 +- treeshr/TreeGetNci.c | 6 +- treeshr/TreeGetSetShotId.c | 2 +- treeshr/TreeOpen.c | 18 +- treeshr/TreePutRecord.c | 18 +- treeshr/TreeRenameNode.c | 10 +- treeshr/TreeSegments.c | 14 +- treeshr/TreeSetDbi.c | 2 +- treeshr/TreeSetDefault.c | 2 +- treeshr/TreeSetNci.c | 2 - treeshr/TreeThreadStatic.c | 20 + treeshr/testing/TreeDeleteNodeTest.c | 16 +- treeshr/testing/TreeSegmentTest.c | 6 +- treeshr/treethreadstatic.h | 14 + treeshr/yylex/TreeFindNodeWild.l | 15 +- wfevent/wfevent.c | 4 +- xmdsshr/ListTree.c | 60 +- xmdsshr/XmdsDigChans.c | 13 +- xmdsshr/XmdsDisplay.c | 4 +- xmdsshr/XmdsExpr.c | 8 +- xmdsshr/XmdsGetPutNid.c | 2 +- xmdsshr/XmdsInput.c | 10 +- xmdsshr/XmdsNidOptionMenu.c | 4 +- xmdsshr/XmdsPath.c | 2 +- xmdsshr/XmdsSetSubvalues.c | 17 +- xmdsshr/XmdsSupport.c | 10 +- xmdsshr/XmdsWaveform.c | 3 +- xmdsshr/XmdsXdBox.c | 6 +- xtreeshr/XTreeDefaultResample.c | 8 +- xtreeshr/XTreeGetSegmentList.c | 4 +- 392 files changed, 8180 insertions(+), 7460 deletions(-) create mode 100644 _include/P2WMutex.hpp create mode 100644 _include/P2WSem.hpp create mode 100644 _include/P2WThread.hpp rename {include => _include}/WindowsUnnamedSemaphore.h (100%) create mode 100644 _include/_mdsshr.h rename {include => _include}/condition.h (90%) rename {include => _include}/coz.h (100%) rename {include => _include}/getusername.h (100%) rename {include => _include}/int128.h (100%) create mode 100644 _include/mdsmsg.h rename {include => _include}/pthread_port.h (77%) create mode 100644 _include/socket_port.h delete mode 100644 include/STATICdef.h delete mode 100644 include/socket_port.h delete mode 100644 mdsdebug.c delete mode 100644 mdsdebugc.c delete mode 100644 mdsobjects/cpp/testing/testutils/Threads.h rename mdstcpip/mdsipshr/{CloseConnection.c => MdsIpThreadStatic.c} (59%) delete mode 100644 mdstcpip/mdsipshr/cvtdef.h create mode 100644 mdstcpip/mdsipshr/mdsipthreadstatic.h create mode 100644 mdstcpip/testing/Makefile.am create mode 100644 mdstcpip/testing/MdsIpTest.c delete mode 100644 mdstcpip/testing/mdsiptest.c rename {include => mitdevices}/mds_gendevice.h (94%) rename {include => mitdevices}/mitdevices_msg.h (100%) create mode 100644 servershr/Client.h create mode 100644 servershr/Job.h delete mode 100644 tdishr/cvtdef.h diff --git a/.gitignore b/.gitignore index 8b21a4a867..f833ed6955 100644 --- a/.gitignore +++ b/.gitignore @@ -166,6 +166,7 @@ mdsshr/testing/Makefile.in mdsshr/version.h mdstcpip/docs/Makefile.in mdstcpip/docs/img/Makefile.in +mdstcpip/testing/Makefile.in mdstcpip/zlib/Makefile.in python/MDSplus/docs/Makefile.in python/MDSplus/compound.py diff --git a/Makefile.inc.in b/Makefile.inc.in index 65efaee6c5..d9fc1a9534 100644 --- a/Makefile.inc.in +++ b/Makefile.inc.in @@ -5,7 +5,7 @@ echo-%: --always @echo '$* = $($*)' -DEFAULT_CFLAGS=-g -O3 +DEFAULT_CFLAGS = -O3 ifeq "$(NOWARN)" "" WARNFLAGS = @WARNFLAGS@ diff --git a/_include/P2WMutex.hpp b/_include/P2WMutex.hpp new file mode 100644 index 0000000000..2e780fe90f --- /dev/null +++ b/_include/P2WMutex.hpp @@ -0,0 +1,282 @@ +#pragma once +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#define __STDC_FORMAT_MACROS + +#include + +#include +#include +#include +#include +#include + +#ifdef _P2W_GTHREADS +#include +#include +#include +#endif + +#include "mdsmsg.h" + +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) + +#undef P2W_PTHREAD_CLEANUP +#ifdef P2W_PTHREAD_CLEANUP +template +static void p2w_cleanup_lock(void *arg) { ((_Lock *)arg)->unlock(); } +#define P2W_LOCK_CLEANUP_PUSH(lock) pthread_cleanup_push(p2w_cleanup_lock, (void *)&lock) +#define P2W_LOCK_CLEANUP_POP(lock) pthread_cleanup_pop(0) +#else +#define P2W_LOCK_CLEANUP_PUSH(lock) +#define P2W_LOCK_CLEANUP_POP(lock) +#endif +#define P2W_UNIQUE_LOCK_ACQUIRE(lock, mutex) \ + { \ + std::unique_lock lock(mutex); \ + P2W_LOCK_CLEANUP_PUSH(lock) +#define P2W_UNIQUE_LOCK_ADOPT(lock, mutex) \ + { \ + std::unique_lock lock(mutex, std::adopt_lock); \ + P2W_LOCK_CLEANUP_PUSH(lock) +#define P2W_UNIQUE_LOCK_RELEASE(lock, mutex) \ + P2W_LOCK_CLEANUP_POP(lock); \ + } +#define P2W_SHARED_LOCK_ACQUIRE(lock, mutex) \ + { \ + (mutex).lock_shared(); \ + std::unique_lock lock(mutex, std::adopt_lock); \ + P2W_LOCK_CLEANUP_PUSH(lock) +#define P2W_SHARED_LOCK_ADOPT(lock, mutex) \ + { \ + std::unique_lock lock(mutex, std::adopt_lock); \ + P2W_LOCK_CLEANUP_PUSH(lock) +#define P2W_SHARED_LOCK_RELEASE(lock, mutex) \ + P2W_LOCK_CLEANUP_POP(lock); \ + } + +template +static inline void p2w_time_point_to_timespec(const std::chrono::time_point &time_point, struct timespec &ts) +{ + auto nsec = std::chrono::duration_cast(time_point.time_since_epoch()); + auto sec = std::chrono::duration_cast(nsec); + nsec -= sec; + ts.tv_sec = sec.count(); + ts.tv_nsec = nsec.count(); +} + +#define _P2W_PTHREAD // define st + +#ifndef _P2W_PTHREAD +#define P2WMutex std::mutex +#else +#include + +class P2WCond; +template +class _P2WMutex +{ + friend P2WCond; + +protected: + T native; + +public: + bool try_lock() const + { + bool const locked = TRYLOCK((T *)&native) == 0; + if (locked) + MDSDBG("MUTEX: 0x%" PRIxPTR " locked 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + return locked; + } + void lock() const + { +#ifdef DEBUG + if (try_lock()) + return; +#endif + MDSDBG("MUTEX: 0x%" PRIxPTR " wait for 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + int const err = LOCK((T *)&native); + if (err != 0) + throw std::runtime_error(strerror(err)); + MDSDBG("MUTEX: 0x%" PRIxPTR " locked 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + } + void unlock() const + { + MDSDBG("MUTEX: 0x%" PRIxPTR " unlocking 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + int const err = UNLOCK((T *)&native); + if (err != 0) + throw std::runtime_error(strerror(err)); + } + T *native_handle() { return &native; }; +}; + +class P2WMutex : public _P2WMutex +{ +public: + P2WMutex(const pthread_mutexattr_t *attr = NULL) + { + int const err = pthread_mutex_init(&native, attr); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + }; + ~P2WMutex() + { + pthread_mutex_destroy(&native); + } + P2WMutex(int const type) + { + pthread_mutexattr_t attr; + int err = pthread_mutexattr_init(&attr); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + err = pthread_mutexattr_settype(&attr, type); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + err = pthread_mutex_init(&native, &attr); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + pthread_mutexattr_destroy(&attr); + } +}; + +class P2WSharedMutex : public _P2WMutex +{ +public: + P2WSharedMutex(const pthread_rwlockattr_t *attr = NULL) + { + int const err = pthread_rwlock_init(&native, attr); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + }; + ~P2WSharedMutex() + { + pthread_rwlock_destroy(&native); + } + bool try_lock_shared() const + { + bool const locked = pthread_rwlock_tryrdlock((pthread_rwlock_t *)&native) == 0; + if (locked) + MDSDBG("MUTEX: 0x%" PRIxPTR " rdlocked 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + return locked; + } + void lock_shared() const + { +#ifdef DEBUG + if (try_lock_shared()) + return; +#endif + MDSDBG("MUTEX: 0x%" PRIxPTR " rdwait for 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + int const err = pthread_rwlock_rdlock((pthread_rwlock_t *)&native); + if (err != 0) + throw std::runtime_error(strerror(err)); + MDSDBG("MUTEX: 0x%" PRIxPTR " rdlocked 0x%" PRIxPTR, (uintptr_t)pthread_self(), (uintptr_t)this); + } + void unlock_shared() const { unlock(); } +}; + +static_assert(sizeof(pthread_mutex_t) == sizeof(P2WMutex), "Size is not correct"); +#endif + +#ifndef _P2W_PTHREAD +class P2WCond : public std::condition_variable +{ +public: + void wait(std::unique_lock &lock) + { + while (std::cv_status::timeout == wait_until( + lock, std::chrono::time_point::max())) + ; + } + template + void wait(std::unique_lock &lock, Predicate pred) + { + while (!wait_until( + lock, std::chrono::time_point::max(), pred)) + ; + } +}; +#else +class P2WCond +{ +public: + pthread_cond_t native; + P2WCond() + { + if (pthread_cond_init(&native, NULL) != 0) + throw std::runtime_error(strerror(errno)); + } + ~P2WCond() + { + pthread_cond_destroy(&native); + } + P2WCond(const P2WCond &) = delete; + P2WCond &operator=(const P2WCond &) = delete; + void notify_one() noexcept + { + pthread_cond_signal(&native); + } + void notify_all() noexcept + { + pthread_cond_broadcast(&native); + } + void wait(std::unique_lock &lock) + { + const int err = pthread_cond_wait(&native, (pthread_mutex_t *)&lock.mutex()->native); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + } + template + void wait(std::unique_lock &lock, Predicate pred) + { + while (!pred()) + { + const int err = pthread_cond_wait(&native, (pthread_mutex_t *)&lock.mutex()->native); + if (unlikely(err != 0)) + throw std::runtime_error(strerror(err)); + } + } + template + std::cv_status wait_until(std::unique_lock &lock, const std::chrono::time_point &abs_time) + { + struct timespec ts; + p2w_time_point_to_timespec(abs_time, ts); + const int err = pthread_cond_timedwait(&native, &lock.mutex()->native, &ts); + if (likely(err == 0)) + return std::cv_status::no_timeout; + if (likely(err == ETIMEDOUT)) + return std::cv_status::timeout; + throw std::runtime_error(strerror(err)); + } + template + bool wait_until(std::unique_lock &lock, const std::chrono::time_point &abs_time, Predicate pred) + { + struct timespec ts; + p2w_time_point_to_timespec(abs_time, ts); + while (!pred()) + { + const int err = pthread_cond_timedwait(&native, (pthread_mutex_t *)&lock.mutex()->native, &ts); + if (likely(err == 0)) + continue; + if (likely(err == ETIMEDOUT)) + return false; + throw std::runtime_error(strerror(err)); + } + return true; + } + template + std::cv_status wait_for(std::unique_lock &lock, const std::chrono::duration &rel_time) + { + return wait_until(lock, std::chrono::system_clock::now() + rel_time); + } + template + bool wait_for(std::unique_lock &lock, const std::chrono::duration &rel_time, Predicate pred) + { + return wait_until(lock, std::chrono::system_clock::now() + rel_time, pred); + } + pthread_cond_t *native_handle() { return &native; } +}; +static_assert(sizeof(pthread_cond_t) == sizeof(P2WCond), "Size is not correct"); +#endif diff --git a/_include/P2WSem.hpp b/_include/P2WSem.hpp new file mode 100644 index 0000000000..2e5cc8f314 --- /dev/null +++ b/_include/P2WSem.hpp @@ -0,0 +1,72 @@ +#pragma once +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#define __STDC_FORMAT_MACROS + +#include +#include + +#include +#include +#include + +#ifdef _P2W_GTHREADS +#include +#include +#include +#endif + +class P2WSem +{ +public: + sem_t native; + +public: + P2WSem(int count = 0) + { + if (sem_init(&native, 0, count) != 0) + throw std::runtime_error(strerror(errno)); + } + ~P2WSem() + { + sem_destroy(&native); + } + void release(std::ptrdiff_t update = 1) + { + for (intptr_t i = update; i-- > 0;) + sem_post(&native); + } + void acquire() + { + sem_wait(&native); + } + bool try_acquire() + { + return sem_trywait(&native) == 0; + } + template + bool try_acquire_for(const std::chrono::duration &rel_time) + { + return try_acquire_until(std::chrono::system_clock::now() + rel_time); + } + template // Clock could be template but cannot cast to different clocks, so .. + bool try_acquire_until(const std::chrono::time_point &abs_time) + { + struct timespec ts; + p2w_time_point_to_timespec(abs_time, ts); + return sem_timedwait(&native, &ts) == 0; + } + sem_t *native_handle() { return &native; } + // extra + bool try_acquire_until(const struct timespec *abs_timeout) + { + return sem_timedwait((sem_t *)&native, abs_timeout) == 0; + } + void acquire_rest() + { + while (try_acquire()) + ; + } +}; +static_assert(sizeof(sem_t) == sizeof(P2WSem), "Size is not correct"); diff --git a/_include/P2WThread.hpp b/_include/P2WThread.hpp new file mode 100644 index 0000000000..c6270281d8 --- /dev/null +++ b/_include/P2WThread.hpp @@ -0,0 +1,350 @@ +#pragma once +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#define __STDC_FORMAT_MACROS +#include +#include +#ifndef _WIN32 +#include +#endif + +#include "P2WMutex.hpp" +#include "mdsmsg.h" + +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) + +#ifndef _WIN32 +#include +inline bool p2w_try_sched(bool const a = true) +{ + static bool try_sched = true; + if (unlikely(!a)) + try_sched = false; + return try_sched; +} +#endif + +template +class P2WThread +{ +#define P2WTHREAD_NAME_MAX 32 +public: + /** Thread manager + * @param routine routine to run in thread + * @param priority thread priority: highest 0 to 255 lowest or -1 to inherit (default = -1) + * @param cpu preferred cpu, -1 unspecified (default = -1) + */ + P2WThread(void *(*routine)(T *), int priority = -1, int cpu = -1) + : m_routine(routine), m_priority(priority), m_cpu(cpu), m_name(""), active(false) + { + m_name[0] = 0; + } + /** Thread manager + * @param routine routine to run in thread + * @param name name of thread for debugging and logs ( will call free on pointer, cast to if not desired) + * @param priority thread priority: highest 0 to 255 lowest or -1 to inherit (default = -1) + * @param cpu preferred cpu, -1 unspecified (default = -1) + */ + P2WThread(void *(*routine)(T *), char *name, int priority = -1, int cpu = -1) + : m_routine(routine), m_priority(priority), m_cpu(cpu), active(false) + { + rename(name); + }; + /** Thread manager + * @param routine routine to run in thread + * @param name name of thread for debugging and logs + * @param priority thread priority: highest 0 to 255 lowest or -1 to inherit (default = -1) + * @param cpu preferred cpu, -1 unspecified ( default = -1) + */ + P2WThread(void *(*routine)(T *), const char *name, int priority = -1, int cpu = -1) + : m_routine(routine), m_priority(priority), m_cpu(cpu), active(false) + { + rename(name); + }; + ~P2WThread() { stop(); }; + +private: +#ifdef _P2W_GTHREADS // i.e. WIN threads + HANDLE native = NULL; +#else + pthread_t native = 0; +#define m_thread_id native +#endif + void *(*const m_routine)(T *); + const int m_priority; + const int m_cpu; + char m_name[P2WTHREAD_NAME_MAX + 1]; + P2WMutex mutex; + std::atomic_bool active; + constexpr bool hasname() { return m_name[0] != 0; }; + +public: + /** + * @brief Returns true if thread was started. + */ + bool is_active() const + { + return active; + } + /** + * @brief Returns true if thread is still alive. + */ + bool is_alive() + { + P2W_UNIQUE_LOCK_ACQUIRE(lock, mutex); + if (native != 0 && !tryjoin(NULL)) + return true; + reset(); + P2W_UNIQUE_LOCK_RELEASE(lock, mutex); + return false; + }; + /** + * @brief Rename thread; Thread must be restarted to change internal name. + */ + void rename(char *name) + { + rename((const char *)name); + free(name); + }; + void rename(const char *name) + { + if (name == NULL) + m_name[0] = 0; + else + strncpy(m_name, name, P2WTHREAD_NAME_MAX); + }; + const char *name() const + { + return m_name; + }; + /** + * @brief Start thread using optional args pointer + */ + bool start(T *arg = NULL) + { + P2W_UNIQUE_LOCK_ACQUIRE(lock, mutex); + if (native != 0 && !tryjoin(NULL)) + return true; + reset(); + if (create(arg)) + { + active = true; + return true; + } + P2W_UNIQUE_LOCK_RELEASE(lock, mutex); + return false; + }; + /** + * @brief Stop running thread using cancel + */ + bool stop(void **result = NULL) + { + P2W_UNIQUE_LOCK_ACQUIRE(lock, mutex); + if (native != 0) + { + if (cancel(result) || tryjoin(result)) + { + if (hasname()) + MDSDBG("P2WThread::stop(\"%s\") Stopped ID: %" PRIxPTR ".", m_name, (intptr_t)m_thread_id); + } + else if (hasname()) + MDSWRN("P2WThread::stop(\"%s\") Failed ID: %" PRIxPTR ".", m_name, (intptr_t)m_thread_id); + } + reset(); + P2W_UNIQUE_LOCK_RELEASE(lock, mutex); + return true; + }; + /** + * @brief Wait for thread to exit gracefully (blocking) + */ + bool wait(void **result = NULL) + { + P2W_UNIQUE_LOCK_ACQUIRE(lock, mutex); + if (native != 0) + { + if (join(result)) + { + if (hasname()) + MDSDBG("P2WThread::join(\"%s\") Joined ID: %" PRIxPTR ".", m_name, (intptr_t)m_thread_id); + } + else if (hasname()) + MDSWRN("P2WThread::join(\"%s\") Failed ID: %" PRIxPTR ".", m_name, (intptr_t)m_thread_id); + } + reset(); + P2W_UNIQUE_LOCK_RELEASE(lock, mutex); + return true; + }; + +private: +#ifdef _P2W_GTHREADS // i.e. WIN threads + DWORD m_thread_id = 0; + inline void reset() + { + m_thread_id = 0; + native = NULL; + }; + inline bool cancel(void **const result) const { return native == NULL || !!TerminateThread(native, 0); }; + // WaitForSingleObject returns WAIT_OBJECT_0 or WAIT_TIMEOUT or WAIT_FAILED + inline bool tryjoin(void **const result) const { return native == NULL || WaitForSingleObject(native, 0) != WAIT_TIMEOUT; }; + inline bool join(void **const result) const { return native == NULL || WaitForSingleObject(native, -1) != WAIT_TIMEOUT; }; + inline bool create(void *const args) + { + native = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)m_routine, args, 0, &m_thread_id); + if (native == NULL) + { + m_thread_id = 0; + if (hasname()) + MDSERR("P2WThread::create(\"%s\") Failed %ld", m_name, GetLastError()); + return false; + } + else + { + if (hasname()) + MDSMSG("P2WThread::create(\"%s\") 0x%lx", m_name, m_thread_id); + return true; + } + } +#else // PTHREAD + /** + * @brief reset fields; thread not active + */ + inline void reset() + { + active = false; + native = 0; + }; +#ifdef _WIN32 + inline bool cancel(void **const result) const + { + for (int retry = 10; retry-- > 0;) + { + if (tryjoin(result)) + return true; + usleep(100000); + } + HANDLE handle = pthread_gethandle(native); + MDSWRN("P2WThread::cancel(\"%s\") failed to gracefully end 0x%lx!", m_name, m_thread_id); + return TerminateThread(handle, 0xDEADBEEF) && join(result); + }; +#else + inline bool cancel(void **const result) const + { + return pthread_cancel(native) == 0 && join(result); + }; +#endif + inline bool join(void **const result) const + { + errno = pthread_join(native, result); + return (errno == 0 || errno == EINVAL); + }; + inline bool tryjoin(void **const result) const + { + errno = pthread_tryjoin_np(native, result); + return (errno == 0 || errno == EINVAL); + }; + bool create(void *const args) + { + int policy = SCHED_OTHER; + int priority = 20; + struct sched_param param; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); +#ifndef _WIN32 + if (p2w_try_sched()) + { + if (m_cpu >= 0) + { + cpu_set_t cpuSet; + CPU_ZERO(&cpuSet); + CPU_SET(m_cpu, &cpuSet); + if (unlikely(pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuSet) != 0)) + { + if (hasname()) + MDSWRN("P2WThread::create(\"%s\") Setting affinity to cpu %d failed", m_name, m_cpu); + } + } + if (unlikely((errno = pthread_attr_setschedpolicy(&attr, SCHED_FIFO)) != 0)) + { + if (hasname()) + MDSWRN("P2WThread::create(\"%s\") Setting policy to SCHED_FIFO failed", m_name); + } + else + policy = SCHED_FIFO; + } +#endif + if (m_priority < 0) + { + errno = pthread_getschedparam(pthread_self(), &policy, ¶m); + if (unlikely(errno != 0)) + { + if (hasname()) + MDSWRN("P2WThread::create(\"%s\") failed to get sched param.", m_name); + } + else + priority = param.sched_priority; + } + else + { + const int max_priority = sched_get_priority_max(policy); + const int min_priority = sched_get_priority_min(policy); + if (unlikely(m_priority > 255)) + priority = min_priority; + else // map priority range [0..255] to native range of current policy + priority = min_priority - (((255 - m_priority) * (min_priority - max_priority)) / 255); + param.sched_priority = priority; + MDSDBG("priority %d -> %d, [%d .. %d]", m_priority, priority, min_priority, max_priority); + if (unlikely((errno = pthread_attr_setschedparam(&attr, ¶m)) != 0)) + { + if (hasname()) + MDSWRN("P2WThread::create(\"%s\") Setting priority to %d failed for policy %d", m_name, m_priority, policy); + } + } + errno = pthread_create(&native, &attr, (void *(*)(void *))(void *)m_routine, args); + if (unlikely(errno != 0)) + { +#ifndef _WIN32 + if (errno == EPERM) + { + MDSWRN("P2WThread::create(\"%s\") Failed. Disabling SCHEDuler options", m_name); + p2w_try_sched(false); + pthread_attr_destroy(&attr); + return create(args); + } +#endif + if (hasname()) + MDSWRN("P2WThread::create(\"%s\") Failed", m_name); + pthread_attr_destroy(&attr); + reset(); + return false; + } + pthread_attr_destroy(&attr); + if (hasname()) + { + errno = pthread_getschedparam(native, &policy, ¶m); + if (unlikely(errno != 0)) + { + MDSWRN("P2WThread::create(\"%s\") 0x%" PRIxPTR ", SCHED unknown!", + m_name, (intptr_t)native); + } +#ifndef _WIN32 + else if (p2w_try_sched() && m_cpu >= 0) + { + MDSMSG("P2WThread::create(\"%s\") 0x%" PRIxPTR " on cpu %d with priority %d %s.", + m_name, (intptr_t)native, m_cpu, param.sched_priority, + policy == SCHED_FIFO ? "SCHED_FIFO OK" : "NOT SCHED_FIFO"); + } +#endif + else + { + MDSMSG("P2WThread::create(\"%s\") 0x%" PRIxPTR " with priority %d.", + m_name, (intptr_t)native, param.sched_priority); + } + pthread_setname_np(native, m_name); + } + return true; + } +#endif // PTHREAD +}; diff --git a/include/WindowsUnnamedSemaphore.h b/_include/WindowsUnnamedSemaphore.h similarity index 100% rename from include/WindowsUnnamedSemaphore.h rename to _include/WindowsUnnamedSemaphore.h diff --git a/_include/_mdsshr.h b/_include/_mdsshr.h new file mode 100644 index 0000000000..6ee15497a8 --- /dev/null +++ b/_include/_mdsshr.h @@ -0,0 +1,22 @@ +#pragma once +#include +#include +#include + +struct sockaddr; + +#define MDSSHR_LOAD_LIBROUTINE(var, lib, method, on_error) \ + do \ + { \ + const int status = LibFindImageSymbol_C(#lib, #method, &var); \ + if (STATUS_NOT_OK) \ + { \ + MDSERR("Failed to load " #lib "->" #method "()"); \ + on_error; \ + } \ + } while (0) +#define MDSSHR_LOAD_LIBROUTINE_LOCAL(lib, method, on_error, returns, args) \ + static returns(*method) args = NULL; \ + MDSSHR_LOAD_LIBROUTINE(method, lib, method, on_error) + +extern int _LibGetHostAddr(const char *hostname, const char *service, struct sockaddr *sin); \ No newline at end of file diff --git a/include/condition.h b/_include/condition.h similarity index 90% rename from include/condition.h rename to _include/condition.h index bdd85fa940..3611acf4fb 100644 --- a/include/condition.h +++ b/_include/condition.h @@ -39,14 +39,14 @@ typedef struct _Condition_p #define _CONDITION_WAIT_RESET(input) \ while ((input)->value) \ _CONDITION_WAIT(input) -#define _CONDITION_WAIT_1SEC(input, status) \ - do \ - { \ - struct timespec tp; \ - clock_gettime(CLOCK_REALTIME, &tp); \ - tp.tv_sec++; \ - status pthread_cond_timedwait(&(input)->cond, &(input)->mutex, &tp); \ - } while (0) +#define _CONDITION_WAIT_1SEC(input) \ + ( \ + { \ + struct timespec tp; \ + clock_gettime(CLOCK_REALTIME, &tp); \ + tp.tv_sec++; \ + pthread_cond_timedwait(&(input)->cond, &(input)->mutex, &tp); \ + }) #define CONDITION_SET_TO(input, value_in) \ do \ { \ @@ -68,7 +68,7 @@ typedef struct _Condition_p do \ { \ _CONDITION_LOCK(input); \ - _CONDITION_WAIT_1SEC(input, ); \ + _CONDITION_WAIT_1SEC(input); \ _CONDITION_UNLOCK(input); \ } while (0) #define CONDITION_DESTROY(input, destroy_lock) \ diff --git a/include/coz.h b/_include/coz.h similarity index 100% rename from include/coz.h rename to _include/coz.h diff --git a/include/getusername.h b/_include/getusername.h similarity index 100% rename from include/getusername.h rename to _include/getusername.h diff --git a/include/int128.h b/_include/int128.h similarity index 100% rename from include/int128.h rename to _include/int128.h diff --git a/_include/mdsmsg.h b/_include/mdsmsg.h new file mode 100644 index 0000000000..498a0a6465 --- /dev/null +++ b/_include/mdsmsg.h @@ -0,0 +1,99 @@ +#include +#include + +//#define DEBUG +//#undef DEBUG +#ifdef MDSDBG +#undef MDSDBG +#undef __MDSMSGTOFUN +#undef __MDSMSGPREFIX +#endif + +#ifdef _WIN32 +#include +#define CURRENT_THREAD_ID() (long)GetCurrentThreadId() +#elif defined(__APPLE__) || defined(__MACH__) +#define CURRENT_THREAD_ID() (long)0 +#else +#ifdef HAVE_UNISTD_H +#include +#endif +#include +#define CURRENT_THREAD_ID() (long)syscall(__NR_gettid) +#endif + +#if defined(WITH_DEBUG_SYMBOLS) && !defined(__APPLE__) && !defined(__MACH__) +#define __MDSMSGTOFUN 70 +#define __MDSMSGPREFIX(LV) ( \ + { \ + pos = __FILE__; \ + while (!strncmp(pos, "../", 3)) \ + pos += 3; \ + pos = msg + sprintf(msg, "%c, %u:%lu, %u.%09u: %s:%d ", \ + LV, getpid(), CURRENT_THREAD_ID(), \ + (unsigned int)ts.tv_sec, \ + (unsigned int)ts.tv_nsec, \ + pos, __LINE__); \ + }) +#else +#define __MDSMSGTOFUN 20 +#define __MDSMSGPREFIX(LV) \ + (msg + sprintf(msg, "%c, %u.%03u: ", \ + LV, \ + (unsigned int)ts.tv_sec, \ + (unsigned int)ts.tv_nsec / 1000000)) +#endif + +#define MDSNOP(...) \ + do \ + { /**/ \ + } while (0) + +#define MSG_DEBUG 'D' +#define MSG_INFO 'I' +#define MSG_WARNING 'W' +#define MSG_ERROR 'E' + +#define __MDSMSGTOMSG (__MDSMSGTOFUN + 30) +#define __MDSMSG(LV, ...) \ + do \ + { \ + struct timespec ts; \ + clock_gettime(CLOCK_REALTIME, &ts); \ + char msg[1024]; \ + char *pos; \ + pos = __MDSMSGPREFIX(LV); \ + if (pos < msg + __MDSMSGTOFUN) \ + { \ + memset(pos, ' ', msg + __MDSMSGTOFUN - pos); \ + pos = msg + __MDSMSGTOFUN; \ + } \ + pos += sprintf(pos, "%s() ", __FUNCTION__); \ + if (pos < msg + __MDSMSGTOMSG) \ + { \ + memset(pos, ' ', msg + __MDSMSGTOMSG - pos); \ + pos = msg + __MDSMSGTOMSG; \ + } \ + pos += sprintf(pos, __VA_ARGS__); \ + if (LV == MSG_ERROR) \ + { \ + perror(msg); \ + } \ + else \ + { \ + strcpy(pos, "\n"); \ + fputs(msg, stderr); \ + } \ + } while (0) + +#ifdef DEBUG +#define MDSDBG(...) __MDSMSG(MSG_DEBUG, __VA_ARGS__) +#else +#define MDSDBG(...) MDSNOP() +#endif +#define MDSMSG(...) __MDSMSG(MSG_INFO, __VA_ARGS__) +#define MDSWRN(...) __MDSMSG(MSG_WARNING, __VA_ARGS__) +#define MDSERR(...) __MDSMSG(MSG_ERROR, __VA_ARGS__) + +#define IPADDRPRI "%d.%d.%d.%d" +#define IPADDRVAR(var) (int)(((uint8_t *)var)[0]), (int)(((uint8_t *)var)[1]), (int)(((uint8_t *)var)[2]), (int)(((uint8_t *)var)[3]) diff --git a/include/pthread_port.h b/_include/pthread_port.h similarity index 77% rename from include/pthread_port.h rename to _include/pthread_port.h index 64eb31f3f3..8fe60af020 100644 --- a/include/pthread_port.h +++ b/_include/pthread_port.h @@ -1,10 +1,17 @@ #ifndef PTHREAD_PORT_H #define PTHREAD_PORT_H + +#include + +#define NOP() \ + do \ + { \ + } while (0) + #define _GNU_SOURCE -#include #include #include -#ifdef _WIN32 +#ifdef WIN32 #include #endif #include @@ -55,16 +62,27 @@ #include #if defined(__MACH__) && !defined(CLOCK_REALTIME) +#include +#include +#ifndef CLOCK_REALTIME #define CLOCK_REALTIME 0 -// clock_gettime is not implemented on older versions of OS X (< 10.12). -// If implemented, CLOCK_REALTIME will have already been defined. -#define clock_gettime(clk_id_unused, timespec) \ - { \ - struct timeval now; \ - int rv = gettimeofday(&now, NULL); \ - (timespec)->tv_sec = rv ? 0 : now.tv_sec; \ - (timespec)->tv_nsec = rv ? 0 : now.tv_usec * 1000; \ - } +#endif +static inline void clock_gettime(clk_id_unused, struct timespec *ts) +{ + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + ts->tv_sec = mts.tv_sec; + ts->tv_nsec = mts.tv_nsec; +} +#elif !defined(HAVE_CLOCK_GETTIME) +static inline void clock_gettime(clk_id_unused, struct timespec *ts) +{ + ts->tv_sec = time(0); + ts->tv_nsec = 0; +} #endif // FREE @@ -107,4 +125,15 @@ static void __attribute__((unused)) fclose_if(void *ptr) RUN_SHARED_FUNCTION_ONCE(fun); \ } while (0) +#define MUTEX_LOCK_PUSH(ptr) \ + pthread_mutex_lock(ptr); \ + pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)(ptr)) +#define MUTEX_LOCK_POP(ptr) \ + pthread_cleanup_pop(1) +#define MUTEX_UNLOCK_PUSH(ptr) \ + pthread_mutex_unlock(ptr); \ + pthread_cleanup_push((void *)pthread_mutex_lock, (void *)(ptr)) +#define MUTEX_UNLOCK_POP(ptr) \ + pthread_cleanup_pop(1) + #endif // PTHREAD_PORT_H diff --git a/_include/socket_port.h b/_include/socket_port.h new file mode 100644 index 0000000000..b3e025b2f1 --- /dev/null +++ b/_include/socket_port.h @@ -0,0 +1,152 @@ +#ifndef SOCKET_PORT_H +#define SOCKET_PORT_H +#ifdef _WIN32 +#ifdef _WIN32_WINNT +#undef _WIN32_WINNT +#endif +#define _WIN32_WINNT _WIN32_WINNT_WIN8 // Windows 8.0 +#include +#include +#include +#include +#include +#include "pthread_port.h" +typedef int socklen_t; +#define FIONREAD_TYPE u_long +#define snprintf _snprintf +#define getpid _getpid +#define SHUT_RDWR 2 +#else +typedef struct sockaddr SOCKADDR; +#define SOCKADDR struct sockaddr +#define closesocket close +#define ioctlsocket ioctl +typedef int SOCKET; +#define INVALID_SOCKET (SOCKET)(-1) +#define SOCKET_ERROR (-1) +#define FIONREAD_TYPE int +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#ifdef _WIN32 +#define MSG_NOSIGNAL_ALT_PUSH() NOP() +#define MSG_NOSIGNAL_ALT_POP() NOP() +#else +#include +#define MSG_NOSIGNAL_ALT_PUSH() signal(SIGPIPE, SIG_IGN) +#define MSG_NOSIGNAL_ALT_POP() signal(SIGPIPE, SIG_DFL) +#endif +#else +#define MSG_NOSIGNAL_ALT_PUSH() NOP() +#define MSG_NOSIGNAL_ALT_POP() NOP() +#endif +#ifndef MSG_DONTWAIT +#define MSG_DONTWAIT 0 +#endif + +#define SEND_BUF_SIZE 32768 +#define RECV_BUF_SIZE 32768 + +#ifdef _WIN32 +#define DEFINE_INITIALIZESOCKETS \ + static void InitializeSockets() \ + { \ + WSADATA wsaData; \ + WORD wVersionRequested; \ + wVersionRequested = MAKEWORD(1, 1); \ + WSAStartup(wVersionRequested, &wsaData); \ + } \ + INIT_SHARED_FUNCTION_ONCE(InitializeSockets) +#define INITIALIZESOCKETS RUN_SHARED_FUNCTION_ONCE(InitializeSockets) +#define socklen_t int +static void _print_socket_error(char *message, int error) +{ + wchar_t *werrorstr = NULL; + FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPWSTR)&werrorstr, 0, NULL); + if (werrorstr) + { + fprintf(stderr, "%s - WSA(%d) %S\n", message, error, werrorstr); + LocalFree(werrorstr); + } + else + { + char *errorstr; + switch (error) + { +#define __SOCKET_CASE(WSA) \ + case WSA: \ + errorstr = #WSA; \ + break; + __SOCKET_CASE(WSAEINTR); + __SOCKET_CASE(WSAEBADF); + __SOCKET_CASE(WSAEACCES); + __SOCKET_CASE(WSAEFAULT); + __SOCKET_CASE(WSAEINVAL); + __SOCKET_CASE(WSAEMFILE); + __SOCKET_CASE(WSAEWOULDBLOCK); + __SOCKET_CASE(WSAEINPROGRESS); + __SOCKET_CASE(WSAEALREADY); + __SOCKET_CASE(WSAENOTSOCK); + __SOCKET_CASE(WSAEDESTADDRREQ); + __SOCKET_CASE(WSAEMSGSIZE); + __SOCKET_CASE(WSAEPROTOTYPE); + __SOCKET_CASE(WSAENOPROTOOPT); + __SOCKET_CASE(WSAEPROTONOSUPPORT); + __SOCKET_CASE(WSAEOPNOTSUPP); + __SOCKET_CASE(WSAEPFNOSUPPORT); + __SOCKET_CASE(WSAEADDRINUSE); + __SOCKET_CASE(WSAEADDRNOTAVAIL); + __SOCKET_CASE(WSAENETDOWN); + __SOCKET_CASE(WSAENETUNREACH); + __SOCKET_CASE(WSAENETRESET); + __SOCKET_CASE(WSAECONNABORTED); + __SOCKET_CASE(WSAECONNRESET); + __SOCKET_CASE(WSAENOBUFS); + __SOCKET_CASE(WSAEISCONN); + __SOCKET_CASE(WSAENOTCONN); + __SOCKET_CASE(WSAESHUTDOWN); + __SOCKET_CASE(WSAETOOMANYREFS); + __SOCKET_CASE(WSAETIMEDOUT); + __SOCKET_CASE(WSAECONNREFUSED); + __SOCKET_CASE(WSAELOOP); + __SOCKET_CASE(WSAENAMETOOLONG); + __SOCKET_CASE(WSAEHOSTDOWN); + __SOCKET_CASE(WSAEHOSTUNREACH); + __SOCKET_CASE(WSAENOTEMPTY); + __SOCKET_CASE(WSAEPROCLIM); + __SOCKET_CASE(WSASYSNOTREADY); + __SOCKET_CASE(WSAVERNOTSUPPORTED); + __SOCKET_CASE(WSANOTINITIALISED); + __SOCKET_CASE(WSAEDISCON); +#undef __SOCKET_CASE + default: + fprintf(stderr, "%s - WSA(%d) WSAError\n", message, error); + return; + } + fprintf(stderr, "%s - WSA(%d) %s\n", message, error, errorstr); + } +} +inline static void print_socket_error(char *message) +{ + _print_socket_error(message, WSAGetLastError()); +} +#else +#define print_socket_error(message) fprintf(stderr, "%s\n", message) +#define DEFINE_INITIALIZESOCKETS +#define INITIALIZESOCKETS +#endif + +#endif // SOCKET_PORT_H diff --git a/actions/actlogp.h b/actions/actlogp.h index 311b5be053..a0cc90d388 100644 --- a/actions/actlogp.h +++ b/actions/actlogp.h @@ -108,7 +108,7 @@ static int parseMsg(char *msg, LinkedEvent *event) char *tmp; if (!msg) return C_ERROR; - event->msg = strcpy(malloc(strlen(msg) + 1), msg); + event->msg = strdup(msg); event->tree = strtok(event->msg, " "); if (!event->tree) return C_ERROR; diff --git a/camshr/RemCamMulti.c b/camshr/RemCamMulti.c index cc303baf8a..da415f0872 100644 --- a/camshr/RemCamMulti.c +++ b/camshr/RemCamMulti.c @@ -74,7 +74,7 @@ static void getiosb(int serverid, short *iosb) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && + if (STATUS_OK && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && ans_d.dims[0] == 4) { memcpy(RemCamLastIosb, ans_d.ptr, 8); @@ -89,7 +89,7 @@ static void getdata(int serverid, void *data) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, NULL); - if (status & 1 && + if (STATUS_OK && (ans_d.dtype == DTYPE_USHORT || ans_d.dtype == DTYPE_LONG) && ans_d.ptr) memcpy(data, ans_d.ptr, ((ans_d.dtype == DTYPE_USHORT) ? 2 : 4) * ans_d.dims[0]); @@ -121,7 +121,7 @@ static int DoCamMulti(char *routine, char *name, int a, int f, int count, { status = MdsValue(serverid, cmd, &ans_d, NULL); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); @@ -144,7 +144,7 @@ int RemCamSetMAXBUF(char *name, int new) char cmd[512]; sprintf(cmd, "CamSetMAXBUF('%s',%d)", name, new); status = MdsValue(serverid, cmd, &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); @@ -166,7 +166,7 @@ int RemCamGetMAXBUF(char *name) char cmd[512]; sprintf(cmd, "CamGetMAXBUF('%s')", name); status = MdsValue(serverid, cmd, &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); diff --git a/camshr/RemCamSingle.c b/camshr/RemCamSingle.c index 2082f6c60e..a0f7b2ec74 100644 --- a/camshr/RemCamSingle.c +++ b/camshr/RemCamSingle.c @@ -68,7 +68,7 @@ MakeSingle(RemCamPiow, Piow) MakeSingle(RemCamPioQrepw, PioQrepw) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, NULL); - if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && + if (STATUS_OK && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && ans_d.dims[0] == 4) { memcpy(RemCamLastIosb, ans_d.ptr, 8); @@ -83,7 +83,7 @@ static void getdata(int serverid, void *data) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, NULL); - if (status & 1 && + if (STATUS_OK && (ans_d.dtype == DTYPE_USHORT || ans_d.dtype == DTYPE_LONG) && ans_d.ptr) memcpy(data, ans_d.ptr, (ans_d.dtype == DTYPE_USHORT) ? 2 : 4); free(ans_d.ptr); @@ -114,7 +114,7 @@ static int CamSingle(char *routine, char *name, int a, int f, void *data, { status = MdsValue(serverid, cmd, &ans_d, NULL); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); diff --git a/camshr/cam_functions.c b/camshr/cam_functions.c index 87853c3de1..d2d641e64f 100644 --- a/camshr/cam_functions.c +++ b/camshr/cam_functions.c @@ -1367,7 +1367,7 @@ EXPORT int CamSetMAXBUF(char *Name, int new) int scsiDevice, enhanced, online; CamKey Key; int status = CamAssign(Name, &Key); - if (status & 1) + if (STATUS_OK) { char dev_name[12]; sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, @@ -1399,7 +1399,7 @@ EXPORT int CamGetMAXBUF(char *Name) int scsiDevice, enhanced, online; CamKey Key; int status = CamAssign(Name, &Key); - if (status & 1) + if (STATUS_OK) { char dev_name[12]; sprintf(dev_name, "GK%c%d%02d", Key.scsi_port, Key.scsi_address, diff --git a/camshr/get_crate_status.c b/camshr/get_crate_status.c index 538e59b01b..4cdfcd9526 100644 --- a/camshr/get_crate_status.c +++ b/camshr/get_crate_status.c @@ -40,7 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------- #include #include - +#include #include "common.h" #include "crate.h" #include "prototypes.h" @@ -76,7 +76,7 @@ int get_crate_status(char *crate_name, int *ptr_crate_status) &iosb // *iosb ); - *ptr_crate_status = (short)((status & 1) ? SCCdata : 0) & 0x0ffff; + *ptr_crate_status = (short)((STATUS_OK) ? SCCdata : 0) & 0x0ffff; if (MSGLVL(DETAILS)) printf( diff --git a/camshr/turn_crate_on_off_line.c b/camshr/turn_crate_on_off_line.c index edfddecb60..512108d4c6 100644 --- a/camshr/turn_crate_on_off_line.c +++ b/camshr/turn_crate_on_off_line.c @@ -41,6 +41,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include "common.h" #include "crate.h" @@ -114,7 +115,7 @@ int turn_crate_on_off_line(char *crate_name, int state) 16, // mem == 16-bit data &iosb // *iosb ); - if (status & 1) + if (STATUS_OK) { status = get_crate_status(pController, &crateStatus); online = ((crateStatus & 0x1000) != 0x1000) ? TRUE : FALSE; diff --git a/camshr/verbs.c b/camshr/verbs.c index a41935d382..d0f82da06e 100644 --- a/camshr/verbs.c +++ b/camshr/verbs.c @@ -465,7 +465,7 @@ EXPORT int SetCrate(void *ctx, char **error, { status = turn_crate_on_off_line(cratename, (on) ? ON : OFF); - if (!(status & 1) && !quiet) + if (STATUS_NOT_OK && !quiet) { if (*error == NULL) *error = strdup(""); diff --git a/ccl/ccl_verbs.c b/ccl/ccl_verbs.c index fd74bc3b9c..d363e25018 100644 --- a/ccl/ccl_verbs.c +++ b/ccl/ccl_verbs.c @@ -62,7 +62,7 @@ static int Qrequired = 0; EXPORT int ccl_name(void *ctx, char **error, char **output) \ { \ int status = ParseQualifiers(ctx, error, output); \ - if (status & 1) \ + if (STATUS_OK) \ status = cam_name(Name, A, F, Count, D, Mem, (unsigned short *)&iosb); \ return CheckErrors(status, (unsigned short *)&iosb, error, output); \ } @@ -71,7 +71,7 @@ static int Qrequired = 0; EXPORT int ccl_name(void *ctx, char **error, char **output) \ { \ int status = ParseQualifiers(ctx, error); \ - if (status & 1) \ + if (STATUS_OK) \ status = cam_name(Name, A, F, D, Mem, (unsigned short *)&iosb); \ return CheckErrors(status, (unsigned short *)&iosb, error, output); \ } @@ -247,7 +247,7 @@ static void append(char **target, char *string) static int CheckErrors(int status, IOSB *iosb, char **error, char **output) { LastStatus = status; - if (status & 1) + if (STATUS_OK) { if (Xrequired) { diff --git a/conf/valgrind.supp/fc32.supp b/conf/valgrind.supp/fc32.supp index 6b97acb63d..da87b6190f 100644 --- a/conf/valgrind.supp/fc32.supp +++ b/conf/valgrind.supp/fc32.supp @@ -33,6 +33,15 @@ fun:gethostbyaddr_r@@GLIBC_2.2.5 fun:getnameinfo } +{ + getservbyname + Helgrind:Race + fun:_nss_files_parse_servent + fun:internal_getent + fun:_nss_files_getservbyname_r + fun:getservbyname_r@@GLIBC_2.2.5 + fun:getservbyname +} { pthread_create Memcheck:Leak @@ -45,7 +54,30 @@ Helgrind:Race fun:mempcpy } - +{ + lock still held on thread_exit + Helgrind:Misc + fun:__open_nocancel + fun:open_verify.constprop.0 + fun:_dl_map_object + fun:dl_open_worker + fun:_dl_catch_exception + fun:_dl_open + fun:dlopen_doit + fun:_dl_catch_exception + fun:_dl_catch_error + fun:_dlerror_run + fun:dlopen@@GLIBC_2.2.5 +} +{ + inside data symbol "environ" with putenv + Helgrind:Race + fun:dlopen_doit + fun:_dl_catch_exception + fun:_dl_catch_error + fun:_dlerror_run + fun:dlopen@@GLIBC_2.2.5 +} # python { @@ -69,6 +101,13 @@ Helgrind:Race fun:_PyThreadState_Swap } +{ + PyThread_allocate_lock + Memcheck:Leak + match-leak-kinds: possible + fun:malloc + fun:PyThread_allocate_lock +} { PyBytes_FromStringAndSize Memcheck:Leak @@ -297,6 +336,19 @@ fun:pthread_cond_timedwait@* obj:/usr/lib64/libpython3.8.so.1.0 } +{ + _PyObject_MakeTpCall holds lock on exit + Helgrind:Misc + fun:open + obj:/usr/lib64/libpython3.8.so.1.0 + obj:/usr/lib64/libpython3.8.so.1.0 + fun:_PyObject_MakeTpCall +} +{ + python still holds a lock somewhere + Helgrind:Misc + obj:/usr/lib64/libpython3.8.so.1.0 +} # java diff --git a/conf/valgrind.supp/mdsplus.supp b/conf/valgrind.supp/mdsplus.supp index c520223266..08143fd3d9 100644 --- a/conf/valgrind.supp/mdsplus.supp +++ b/conf/valgrind.supp/mdsplus.supp @@ -33,4 +33,4 @@ obj:* obj:* fun:TclDispatch_show_server -} \ No newline at end of file +} diff --git a/configure.ac b/configure.ac index af7be6c265..4ec864598c 100644 --- a/configure.ac +++ b/configure.ac @@ -336,7 +336,7 @@ IDL_LD="" LIBPRE="lib" CFLAGS="$CFLAGS $GCCPROF -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64" -CPPFLAGS="-I\${top_srcdir}/include -I\${top_builddir}/include $CPPFLAGS" +CPPFLAGS="-I\${top_srcdir}/include -I\${top_srcdir}/_include -I\${top_builddir}/include $CPPFLAGS" if test "$exec_prefix" = "NONE" -a "$prefix" = "NONE" then @@ -994,13 +994,13 @@ AX_PYTHON_ARCH(PYTHON_ARCHITECTURE) AC_SUBST(PYTHON_ARCHITECTURE) AC_MSG_CHECKING(PyLib) -DEF_PYLIB=${PyLib:-$($PYTHON -c ' +PYLIB=${PyLib:-$($PYTHON -c ' import sys,ctypes.util name = ("python%d%d" if sys.platform.startswith("win") else "python%d.%d")%sys.version_info[[0:2]] name = ctypes.util.find_library(name) if not name is None: print(name) ')} -AC_MSG_RESULT($DEF_PYLIB) +AC_MSG_RESULT($PYLIB) @@ -1326,7 +1326,7 @@ AC_SUBST(MOTIF_LDARC) AC_SUBST(MOTIF_LD_LDSHARE) AC_SUBST(MOTIF_LD_LDARC) AC_SUBST(PYTHON_INCLUDE_DIR) -AC_SUBST(DEF_PYLIB) +AC_SUBST(PYLIB) AC_SUBST(NEED_SEMUN) AC_SUBST(RELEASE_MAJOR) @@ -1433,6 +1433,7 @@ AC_OUTPUT( mdsshr/docs/Makefile mdssql/Makefile mdstcpip/Makefile + mdstcpip/testing/Makefile mdstcpip/zlib/Makefile mdstcpip/docs/Makefile mdstcpip/docs/img/Makefile diff --git a/deploy/packaging/debian/devel.noarch b/deploy/packaging/debian/devel.noarch index 2344937028..0c0c5e041b 100644 --- a/deploy/packaging/debian/devel.noarch +++ b/deploy/packaging/debian/devel.noarch @@ -1,5 +1,3 @@ -./usr/local/mdsplus/include/STATICdef.h -./usr/local/mdsplus/include/WindowsUnnamedSemaphore.h ./usr/local/mdsplus/include/Xmds/ListTree.h ./usr/local/mdsplus/include/Xmds/ListTreeP.h ./usr/local/mdsplus/include/Xmds/XmdsCallbacks.h @@ -30,16 +28,11 @@ ./usr/local/mdsplus/include/camshr.h ./usr/local/mdsplus/include/camshr_messages.h ./usr/local/mdsplus/include/classdef.h -./usr/local/mdsplus/include/condition.h -./usr/local/mdsplus/include/coz.h ./usr/local/mdsplus/include/dbidef.h ./usr/local/mdsplus/include/dcl.h ./usr/local/mdsplus/include/dtypedef.h -./usr/local/mdsplus/include/getusername.h -./usr/local/mdsplus/include/int128.h ./usr/local/mdsplus/include/ipdesc.h ./usr/local/mdsplus/include/libroutines.h -./usr/local/mdsplus/include/mds_gendevice.h ./usr/local/mdsplus/include/mds_stdarg.h ./usr/local/mdsplus/include/mdsdcl_messages.h ./usr/local/mdsplus/include/mdsdescrip.h @@ -60,15 +53,12 @@ ./usr/local/mdsplus/include/mdstypes.h ./usr/local/mdsplus/include/mdsversion.h ./usr/local/mdsplus/include/mitdevices_messages.h -./usr/local/mdsplus/include/mitdevices_msg.h ./usr/local/mdsplus/include/msc_stdint.h ./usr/local/mdsplus/include/ncidef.h ./usr/local/mdsplus/include/opcbuiltins.h -./usr/local/mdsplus/include/pthread_port.h ./usr/local/mdsplus/include/rtevents.h ./usr/local/mdsplus/include/servershr.h ./usr/local/mdsplus/include/servershr_messages.h -./usr/local/mdsplus/include/socket_port.h ./usr/local/mdsplus/include/sqldb.h ./usr/local/mdsplus/include/sqlfront.h ./usr/local/mdsplus/include/status.h diff --git a/deploy/packaging/redhat/devel.noarch b/deploy/packaging/redhat/devel.noarch index df23f31085..936e4605b7 100644 --- a/deploy/packaging/redhat/devel.noarch +++ b/deploy/packaging/redhat/devel.noarch @@ -1,6 +1,4 @@ ./usr/local/mdsplus/include -./usr/local/mdsplus/include/STATICdef.h -./usr/local/mdsplus/include/WindowsUnnamedSemaphore.h ./usr/local/mdsplus/include/Xmds ./usr/local/mdsplus/include/Xmds/ListTree.h ./usr/local/mdsplus/include/Xmds/ListTreeP.h @@ -32,16 +30,11 @@ ./usr/local/mdsplus/include/camshr.h ./usr/local/mdsplus/include/camshr_messages.h ./usr/local/mdsplus/include/classdef.h -./usr/local/mdsplus/include/condition.h -./usr/local/mdsplus/include/coz.h ./usr/local/mdsplus/include/dbidef.h ./usr/local/mdsplus/include/dcl.h ./usr/local/mdsplus/include/dtypedef.h -./usr/local/mdsplus/include/getusername.h -./usr/local/mdsplus/include/int128.h ./usr/local/mdsplus/include/ipdesc.h ./usr/local/mdsplus/include/libroutines.h -./usr/local/mdsplus/include/mds_gendevice.h ./usr/local/mdsplus/include/mds_stdarg.h ./usr/local/mdsplus/include/mdsdcl_messages.h ./usr/local/mdsplus/include/mdsdescrip.h @@ -63,15 +56,12 @@ ./usr/local/mdsplus/include/mdstypes.h ./usr/local/mdsplus/include/mdsversion.h ./usr/local/mdsplus/include/mitdevices_messages.h -./usr/local/mdsplus/include/mitdevices_msg.h ./usr/local/mdsplus/include/msc_stdint.h ./usr/local/mdsplus/include/ncidef.h ./usr/local/mdsplus/include/opcbuiltins.h -./usr/local/mdsplus/include/pthread_port.h ./usr/local/mdsplus/include/rtevents.h ./usr/local/mdsplus/include/servershr.h ./usr/local/mdsplus/include/servershr_messages.h -./usr/local/mdsplus/include/socket_port.h ./usr/local/mdsplus/include/sqldb.h ./usr/local/mdsplus/include/sqlfront.h ./usr/local/mdsplus/include/status.h diff --git a/deploy/platform/platform_docker_build.sh b/deploy/platform/platform_docker_build.sh index ba60ff1c1d..bf6c9a58ba 100755 --- a/deploy/platform/platform_docker_build.sh +++ b/deploy/platform/platform_docker_build.sh @@ -39,7 +39,7 @@ testarch(){ config() { if [ -z "$JARS_DIR" ] then - JAVA_OPTS= + JAVA_OPTS= else JAVA_OPTS="--with-jars=${JARS_DIR}" fi diff --git a/device_support/redpitaya/AsyncStoreManager.cpp b/device_support/redpitaya/AsyncStoreManager.cpp index c4274cf1b5..8a9564b886 100644 --- a/device_support/redpitaya/AsyncStoreManager.cpp +++ b/device_support/redpitaya/AsyncStoreManager.cpp @@ -3,11 +3,10 @@ pthread_mutex_t globalMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t segmentMutex = PTHREAD_MUTEX_INITIALIZER; - -SaveItem::SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, - MDSplus::Data *triggerTime, void *treePtr, - double *startTimes, double *endTimes, double freq, int blocksInSegment, - MDSplus::TreeNode *resampledNode) +SaveItem::SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode) { this->buffer = buffer; this->segmentSamples = segmentSamples; @@ -17,17 +16,16 @@ SaveItem::SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNod this->blocksInSegment = blocksInSegment; this->startTimes = new double[blocksInSegment]; this->endTimes = new double[blocksInSegment]; - for(int i = 0; i < blocksInSegment; i++) + for (int i = 0; i < blocksInSegment; i++) { - this->startTimes[i] = startTimes[i]; - this->endTimes[i] = endTimes[i]; + this->startTimes[i] = startTimes[i]; + this->endTimes[i] = endTimes[i]; } this->freq = freq; this->resampledNode = resampledNode; nxt = 0; } - void SaveItem::save() { MDSplus::Array *chanData = @@ -62,7 +60,7 @@ void SaveItem::save() MDSplus::compileWithArgs("$1+$2", treePtr, 2, endData, triggerTime); try { - std::cout << "MAKE SEGMENT SAMPLES:"<< segmentSamples << std::endl; + std::cout << "MAKE SEGMENT SAMPLES:" << segmentSamples << std::endl; dataNode->makeSegment(startSegData, endSegData, timebase, chanData); } catch (MDSplus::MdsException &exc) @@ -76,10 +74,10 @@ void SaveItem::save() MDSplus::deleteData(startSegData); MDSplus::deleteData(endSegData); delete[] buffer; - delete [] startTimes; - delete [] endTimes; -} - + delete[] startTimes; + delete[] endTimes; +} + SaveList::SaveList() { int status = pthread_mutex_init(&mutex, NULL); @@ -90,13 +88,13 @@ SaveList::SaveList() } void SaveList::addItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, - MDSplus::Data *triggerTime, void *treePtr, - double *startTimes, double *endTimes, double freq, int blocksInSegment, - MDSplus::TreeNode *resampledNode) + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode) { SaveItem *newItem = new SaveItem( - buffer, segmentSamples, dataNode, triggerTime, treePtr, startTimes, endTimes, freq, blocksInSegment, resampledNode); + buffer, segmentSamples, dataNode, triggerTime, treePtr, startTimes, endTimes, freq, blocksInSegment, resampledNode); pthread_mutex_lock(&mutex); if (saveHead == NULL) diff --git a/device_support/redpitaya/AsyncStoreManager.h b/device_support/redpitaya/AsyncStoreManager.h index 529912d3ee..31380b7c55 100644 --- a/device_support/redpitaya/AsyncStoreManager.h +++ b/device_support/redpitaya/AsyncStoreManager.h @@ -26,13 +26,12 @@ class SaveItem double *startTimes, *endTimes; double freq; int blocksInSegment; - + public: - - SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, - MDSplus::Data *triggerTime, void *treePtr, - double *startTimes, double *endTimes, double freq, int blocksInSegment, - MDSplus::TreeNode *resampledNode = NULL); + SaveItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, + MDSplus::Data *triggerTime, void *treePtr, + double *startTimes, double *endTimes, double freq, int blocksInSegment, + MDSplus::TreeNode *resampledNode = NULL); void setNext(SaveItem *itm) { nxt = itm; } SaveItem *getNext() { return nxt; } @@ -70,7 +69,7 @@ class SaveList SaveList(); void addItem(short *buffer, int segmentSamples, MDSplus::TreeNode *dataNode, - MDSplus::Data *triggerTime, void *treePtr, + MDSplus::Data *triggerTime, void *treePtr, double *startTimes, double *endTimes, double freq, int blocksInSegment, MDSplus::TreeNode *resampledNode = NULL); diff --git a/device_support/redpitaya/redpitaya.cpp b/device_support/redpitaya/redpitaya.cpp index 522ab8287b..f808f31883 100644 --- a/device_support/redpitaya/redpitaya.cpp +++ b/device_support/redpitaya/redpitaya.cpp @@ -9,7 +9,6 @@ #include #include - extern "C" { void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, @@ -226,7 +225,7 @@ static void adcTrigger(int fd) ioctl(fd, RFX_STREAM_SET_COMMAND_REGISTER, &command); ioctl(fd, RFX_STREAM_GET_DRIVER_BUFLEN, &command); - std::cout<<"DATA FIFO LEN: " << command << std::endl; + std::cout << "DATA FIFO LEN: " << command << std::endl; // ioctl(fd, RFX_STREAM_GET_DATA_FIFO_VAL, &command); // ioctl(fd, RFX_STREAM_GET_TIME_FIFO_LEN, &command); // ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &command); @@ -261,8 +260,9 @@ static void writeSegment(MDSplus::Tree *t, MDSplus::TreeNode *chan1, double *endTimes, int segmentSamples, int blocksInSegment, double freq, SaveList *saveList) { -std::cout << "WRITE SEGMENT " << segmentSamples; -if(segmentSamples == 0) return; + std::cout << "WRITE SEGMENT " << segmentSamples; + if (segmentSamples == 0) + return; short *chan1Samples, *chan2Samples; //std::cout << "WRITE SEGMENT SAMPLES: " << segmentSamples << std::endl; chan1Samples = new short[segmentSamples]; @@ -273,12 +273,12 @@ if(segmentSamples == 0) return; chan1Samples[i] = dataSamples[i] & 0x0000ffff; chan2Samples[i] = (dataSamples[i] >> 16) & 0x0000ffff; } - - saveList->addItem(chan1Samples, segmentSamples, chan1, triggerTime, t, - startTimes, endTimes, freq, blocksInSegment); - saveList->addItem(chan2Samples, segmentSamples, chan2, triggerTime, t, - startTimes, endTimes, freq, blocksInSegment); + saveList->addItem(chan1Samples, segmentSamples, chan1, triggerTime, t, + startTimes, endTimes, freq, blocksInSegment); + + saveList->addItem(chan2Samples, segmentSamples, chan2, triggerTime, t, + startTimes, endTimes, freq, blocksInSegment); } // Stop void rpadcStop(int fd) @@ -372,7 +372,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, ioctl(fd, RFX_STREAM_GET_LEV_TRIG_COUNT, &trig_lev_count); trig_lev_count++; ioctl(fd, RFX_STREAM_SET_LEV_TRIG_COUNT, &trig_lev_count); - + while (true) { for (int currBlock = 0; currBlock < blocksInSegment; currBlock++) @@ -382,7 +382,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, { int rb = read(fd, &dataSamples[currBlock * blockSamples + currSample], (blockSamples - currSample) * sizeof(int)); -//std::cout << "READ " << rb << std::endl; + //std::cout << "READ " << rb << std::endl; currSample += rb / sizeof(int); if (stopped) // May happen when block readout has terminated or in the @@ -424,7 +424,7 @@ void rpadcStream(int fd, char *treeName, int shot, int chan1Nid, int chan2Nid, ioctl(fd, RFX_STREAM_GET_TIME_FIFO_VAL, &time2); currTime = (unsigned long long)time1 | (((unsigned long long)time2) << 32); - std::cout << "MULTIPLE 2 "<< currBlock << std::endl; + std::cout << "MULTIPLE 2 " << currBlock << std::endl; startTimes[currBlock] = (currTime - preSamples) / freq; endTimes[currBlock] = (currTime + postSamples - 1) / freq; // include last sample diff --git a/device_support/redpitaya/rfx_stream.h b/device_support/redpitaya/rfx_stream.h index 2df3cf6f4b..785c55f2e6 100644 --- a/device_support/redpitaya/rfx_stream.h +++ b/device_support/redpitaya/rfx_stream.h @@ -1,95 +1,93 @@ #ifndef RFX_STREAM_H #define RFX_STREAM_H - #include #include - - #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif //Temporaneo #define DMA_SOURCE 1 -//////////////// - + //////////////// -#define DEVICE_NAME "rfx_stream" /* Dev name as it appears in /proc/devices */ +#define DEVICE_NAME "rfx_stream" /* Dev name as it appears in /proc/devices */ #define MODULE_NAME "rfx_stream" -//Generic IOCTL commands - -#define RFX_STREAM_IOCTL_BASE 'W' -#define RFX_STREAM_ARM_DMA _IO(RFX_STREAM_IOCTL_BASE, 1) -#define RFX_STREAM_START_DMA _IO(RFX_STREAM_IOCTL_BASE, 2) -#define RFX_STREAM_STOP_DMA _IO(RFX_STREAM_IOCTL_BASE, 3) -#define RFX_STREAM_SET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 4) -#define RFX_STREAM_GET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 5) -#define RFX_STREAM_IS_DMA_RUNNING _IO(RFX_STREAM_IOCTL_BASE, 6) -#define RFX_STREAM_GET_DMA_DATA _IO(RFX_STREAM_IOCTL_BASE, 7) -#define RFX_STREAM_SET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 8) -#define RFX_STREAM_GET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 9) -#define RFX_STREAM_GET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 10) -#define RFX_STREAM_SET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 11) -#define RFX_STREAM_FIFO_INT_HALF_SIZE _IO(RFX_STREAM_IOCTL_BASE, 12) -#define RFX_STREAM_FIFO_INT_FIRST_SAMPLE _IO(RFX_STREAM_IOCTL_BASE, 13) -#define RFX_STREAM_FIFO_FLUSH _IO(RFX_STREAM_IOCTL_BASE, 14) -#define RFX_STREAM_START_READ _IO(RFX_STREAM_IOCTL_BASE, 15) -#define RFX_STREAM_STOP_READ _IO(RFX_STREAM_IOCTL_BASE, 16) -#define RFX_STREAM_GET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 20) -#define RFX_STREAM_SET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 21) -#define RFX_STREAM_GET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 22) -#define RFX_STREAM_SET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 23) -#define RFX_STREAM_GET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 24) -#define RFX_STREAM_SET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 25) -#define RFX_STREAM_GET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 26) -#define RFX_STREAM_SET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 27) -#define RFX_STREAM_GET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 28) -#define RFX_STREAM_SET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 29) -#define RFX_STREAM_GET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 30) -#define RFX_STREAM_SET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 31) -#define RFX_STREAM_GET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 32) -#define RFX_STREAM_SET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 33) -#define RFX_STREAM_GET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 34) -#define RFX_STREAM_SET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 35) -#define RFX_STREAM_GET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 36) -#define RFX_STREAM_SET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 37) -#define RFX_STREAM_GET_DATA_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 38) -#define RFX_STREAM_GET_DATA_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 39) -#define RFX_STREAM_CLEAR_DATA_FIFO _IO(RFX_STREAM_IOCTL_BASE, 40) -#define RFX_STREAM_GET_TIME_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 41) -#define RFX_STREAM_GET_TIME_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 42) -#define RFX_STREAM_CLEAR_TIME_FIFO _IO(RFX_STREAM_IOCTL_BASE, 43) - + //Generic IOCTL commands + +#define RFX_STREAM_IOCTL_BASE 'W' +#define RFX_STREAM_ARM_DMA _IO(RFX_STREAM_IOCTL_BASE, 1) +#define RFX_STREAM_START_DMA _IO(RFX_STREAM_IOCTL_BASE, 2) +#define RFX_STREAM_STOP_DMA _IO(RFX_STREAM_IOCTL_BASE, 3) +#define RFX_STREAM_SET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 4) +#define RFX_STREAM_GET_DMA_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 5) +#define RFX_STREAM_IS_DMA_RUNNING _IO(RFX_STREAM_IOCTL_BASE, 6) +#define RFX_STREAM_GET_DMA_DATA _IO(RFX_STREAM_IOCTL_BASE, 7) +#define RFX_STREAM_SET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 8) +#define RFX_STREAM_GET_DRIVER_BUFLEN _IO(RFX_STREAM_IOCTL_BASE, 9) +#define RFX_STREAM_GET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 10) +#define RFX_STREAM_SET_REGISTERS _IO(RFX_STREAM_IOCTL_BASE, 11) +#define RFX_STREAM_FIFO_INT_HALF_SIZE _IO(RFX_STREAM_IOCTL_BASE, 12) +#define RFX_STREAM_FIFO_INT_FIRST_SAMPLE _IO(RFX_STREAM_IOCTL_BASE, 13) +#define RFX_STREAM_FIFO_FLUSH _IO(RFX_STREAM_IOCTL_BASE, 14) +#define RFX_STREAM_START_READ _IO(RFX_STREAM_IOCTL_BASE, 15) +#define RFX_STREAM_STOP_READ _IO(RFX_STREAM_IOCTL_BASE, 16) +#define RFX_STREAM_GET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 20) +#define RFX_STREAM_SET_COMMAND_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 21) +#define RFX_STREAM_GET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 22) +#define RFX_STREAM_SET_DECIMATOR_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 23) +#define RFX_STREAM_GET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 24) +#define RFX_STREAM_SET_LEV_TRIG_COUNT _IO(RFX_STREAM_IOCTL_BASE, 25) +#define RFX_STREAM_GET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 26) +#define RFX_STREAM_SET_MODE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 27) +#define RFX_STREAM_GET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 28) +#define RFX_STREAM_SET_PACKETIZER _IO(RFX_STREAM_IOCTL_BASE, 29) +#define RFX_STREAM_GET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 30) +#define RFX_STREAM_SET_POST_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 31) +#define RFX_STREAM_GET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 32) +#define RFX_STREAM_SET_PRE_REGISTER _IO(RFX_STREAM_IOCTL_BASE, 33) +#define RFX_STREAM_GET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 34) +#define RFX_STREAM_SET_TRIG_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 35) +#define RFX_STREAM_GET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 36) +#define RFX_STREAM_SET_EVENT_CODE _IO(RFX_STREAM_IOCTL_BASE, 37) +#define RFX_STREAM_GET_DATA_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 38) +#define RFX_STREAM_GET_DATA_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 39) +#define RFX_STREAM_CLEAR_DATA_FIFO _IO(RFX_STREAM_IOCTL_BASE, 40) +#define RFX_STREAM_GET_TIME_FIFO_LEN _IO(RFX_STREAM_IOCTL_BASE, 41) +#define RFX_STREAM_GET_TIME_FIFO_VAL _IO(RFX_STREAM_IOCTL_BASE, 42) +#define RFX_STREAM_CLEAR_TIME_FIFO _IO(RFX_STREAM_IOCTL_BASE, 43) #ifndef AXI_ENUMS_DEFINED #define AXI_ENUMS_DEFINED -enum AxiStreamFifo_Register { - ISR = 0x00, ///< Interrupt Status Register (ISR) - IER = 0x04, ///< Interrupt Enable Register (IER) - TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) - TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) - TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port + enum AxiStreamFifo_Register + { + ISR = 0x00, ///< Interrupt Status Register (ISR) + IER = 0x04, ///< Interrupt Enable Register (IER) + TDFR = 0x08, ///< Transmit Data FIFO Reset (TDFR) + TDFV = 0x0c, ///< Transmit Data FIFO Vacancy (TDFV) + TDFD = 0x10, ///< Transmit Data FIFO 32-bit Wide Data Write Port TDFD4 = 0x1000, ///< Transmit Data FIFO for AXI4 Data Write Port - TLR = 0x14, ///< Transmit Length Register (TLR) - RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) - RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) - RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) + TLR = 0x14, ///< Transmit Length Register (TLR) + RDFR = 0x18, ///< Receive Data FIFO reset (RDFR) + RDFO = 0x1c, ///< Receive Data FIFO Occupancy (RDFO) + RDFD = 0x20, ///< Receive Data FIFO 32-bit Wide Data Read Port (RDFD) RDFD4 = 0x1000, ///< Receive Data FIFO for AXI4 Data Read Port (RDFD) - RLR = 0x24, ///< Receive Length Register (RLR) - SRR = 0x28, ///< AXI4-Stream Reset (SRR) - TDR = 0x2c, ///< Transmit Destination Register (TDR) - RDR = 0x30, ///< Receive Destination Register (RDR) + RLR = 0x24, ///< Receive Length Register (RLR) + SRR = 0x28, ///< AXI4-Stream Reset (SRR) + TDR = 0x2c, ///< Transmit Destination Register (TDR) + RDR = 0x30, ///< Receive Destination Register (RDR) /// not supported yet .. /// - TID = 0x34, ///< Transmit ID Register - TUSER = 0x38, ///< Transmit USER Register - RID = 0x3c, ///< Receive ID Register - RUSER = 0x40 ///< Receive USER Register -}; - -enum AxiStreamFifo_ISREnum { + TID = 0x34, ///< Transmit ID Register + TUSER = 0x38, ///< Transmit USER Register + RID = 0x3c, ///< Receive ID Register + RUSER = 0x40 ///< Receive USER Register + }; + + enum AxiStreamFifo_ISREnum + { ISR_RFPE = 1 << 19, ///< Receive FIFO Programmable Empty ISR_RFPF = 1 << 20, ///< Receive FIFO Programmable Full ISR_TFPE = 1 << 21, ///< Transmit FIFO Programmable Empty @@ -103,9 +101,10 @@ enum AxiStreamFifo_ISREnum { ISR_RPUE = 1 << 29, ///< Receive Packet Underrun Error ISR_RPORE = 1 << 30, ///< Receive Packet Overrun Read Error ISR_RPURE = 1 << 31, ///< Receive Packet Underrun Read Error -}; + }; -enum RegisterIdx { + enum RegisterIdx + { FIFO_00_IDX = 0, FIFO_01_IDX = 1, FIFO_10_IDX = 2, @@ -114,35 +113,32 @@ enum RegisterIdx { PRE_POST_REG_IDX = 5, DEC_REG_IDX = 6, MODE_REG_IDX = 8 -}; + }; #endif #pragma pack(1) -struct rfx_stream_registers -{ - char command_register_enable; - unsigned int command_register; - char decimator_register_enable; - unsigned int decimator_register; - char lev_trig_count_enable; - unsigned int lev_trig_count; - char mode_register_enable; - unsigned int mode_register; - char packetizer_enable; - unsigned int packetizer; - char post_register_enable; - unsigned int post_register; - char pre_register_enable; - unsigned int pre_register; - char trig_event_code_enable; - unsigned int trig_event_code; - char event_code_enable; - unsigned int event_code; - -}; - - + struct rfx_stream_registers + { + char command_register_enable; + unsigned int command_register; + char decimator_register_enable; + unsigned int decimator_register; + char lev_trig_count_enable; + unsigned int lev_trig_count; + char mode_register_enable; + unsigned int mode_register; + char packetizer_enable; + unsigned int packetizer; + char post_register_enable; + unsigned int post_register; + char pre_register_enable; + unsigned int pre_register; + char trig_event_code_enable; + unsigned int trig_event_code; + char event_code_enable; + unsigned int event_code; + }; #ifdef __cplusplus } diff --git a/dwscope/evaluate.c b/dwscope/evaluate.c index d14cb1628a..bdcde239af 100644 --- a/dwscope/evaluate.c +++ b/dwscope/evaluate.c @@ -109,6 +109,7 @@ Boolean EvaluateText(String text, String error_prefix, String *text_ret, String #include #include #include +#include #ifndef _toupper #define _toupper(c) (((c) >= 'a' && (c) <= 'z') ? (c)&0xDF : (c)) #endif @@ -272,7 +273,7 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, status = (TdiDimOf(&sig, &x_xd MDS_END_ARG) & 1) && (TdiData(&x_xd, &x_xd MDS_END_ARG) & 1) && (TdiCvt(&x_xd, &float_dsc, &x_xd MDS_END_ARG) & 1); - if (!(status & 1) && (y_a->class == CLASS_S)) + if (STATUS_NOT_OK && (y_a->class == CLASS_S)) { static int zero = 0; static DESCRIPTOR_LONG(zero_d, &zero); @@ -871,7 +872,7 @@ Boolean EvaluateData(Boolean brief, int row, int col, int idx, Boolean *event, else status = MdsValue(sock, "f_float(data(dim_of(_y$$dwscope)))", &xans, NULL); - if (status & 1) + if (STATUS_OK) { int xcount = Nelements(&xans); if (xcount < count) diff --git a/epics/mdsrecords/mdsexprRecord.c b/epics/mdsrecords/mdsexprRecord.c index afee3b1303..6de7f56248 100644 --- a/epics/mdsrecords/mdsexprRecord.c +++ b/epics/mdsrecords/mdsexprRecord.c @@ -364,6 +364,6 @@ static void checkAlarms(mdsexprRecord *prec) return; } - if (!(status & 1)) + if (STATUS_NOT_OK) recGblSetSevr(prec, WRITE_ALARM, MAJOR_ALARM); } diff --git a/epics/mdsrecords/mdsputRecord.c b/epics/mdsrecords/mdsputRecord.c index c408a362cf..2adb7df76f 100644 --- a/epics/mdsrecords/mdsputRecord.c +++ b/epics/mdsrecords/mdsputRecord.c @@ -366,6 +366,6 @@ static void checkAlarms(mdsputRecord *prec) return; } - if (!(status & 1)) + if (STATUS_NOT_OK) recGblSetSevr(prec, WRITE_ALARM, MAJOR_ALARM); } diff --git a/hdf5/MDSplus2HDF5.c b/hdf5/MDSplus2HDF5.c index d3a9e11143..ac392de397 100644 --- a/hdf5/MDSplus2HDF5.c +++ b/hdf5/MDSplus2HDF5.c @@ -117,7 +117,7 @@ static int GetNidNCI(int nid, char *expr) DESCRIPTOR_NID(nid_dsc, &nid); DESCRIPTOR_FROM_CSTRING(getnci, expr); status = TdiExecute(&getnci, &nid_dsc, &ans_xd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { struct descriptor *d_ptr; for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; @@ -198,7 +198,7 @@ static char *GetNidString(int nid, char *expr) static EMPTYXD(ans_xd); int status; status = TdiExecute(&expr_d, &nid_dsc, &ans_xd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { struct descriptor *d_ptr; for (d_ptr = (struct descriptor *)&ans_xd; d_ptr->dtype == DTYPE_DSC; @@ -239,7 +239,7 @@ static int is_child(int nid) void ExitOnMDSError(int status, const char *msg) { - if (!(status & 1)) + if (STATUS_NOT_OK) { fprintf(stderr, "MDS Error\n%s\n%s\n", msg, MdsGetMsg(status)); exit(0); @@ -454,10 +454,10 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { static EMPTYXD(xd3); status = TdiEvaluate(d_ptr, &xd3 MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { status = TdiData((struct descriptor *)&xd3, &xd3 MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { for (d_ptr = (struct descriptor *)&xd3; d_ptr->dtype == DTYPE_DSC; d_ptr = (struct descriptor *)d_ptr->pointer) @@ -523,7 +523,7 @@ static void WriteData(hid_t parent, char *name, struct descriptor *dsc) { // static EMPTYXD(xd2); // status = TdiData(d_ptr, &xd2); - // if (status & 1) + // if (STATUS_OK) // WriteData(parent, name, &xd2); } } @@ -556,7 +556,7 @@ static void WriteDataNID(hid_t parent, char *name, int nid) DESCRIPTOR_NID(nid_dsc, &nid); int status; status = TdiEvaluate(&nid_dsc, &xd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { WriteData(parent, name, (struct descriptor *)&xd); } diff --git a/hdf5/dynhdf5.c b/hdf5/dynhdf5.c index d94eaadcbb..b0bae3c0ff 100644 --- a/hdf5/dynhdf5.c +++ b/hdf5/dynhdf5.c @@ -77,7 +77,7 @@ static void *FindSymbol(char *name) { void *rtn = NULL; int status = LibFindImageSymbol_C("hdf5", name, &rtn); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Error activating hdf5 shared library\n"); exit(1); diff --git a/hdf5/hdf5ToMds.c b/hdf5/hdf5ToMds.c index b5d44d045a..874f549da6 100644 --- a/hdf5/hdf5ToMds.c +++ b/hdf5/hdf5ToMds.c @@ -134,7 +134,7 @@ static int AddNode(const char *h5name, int usage) } status = TreeAddNode(name, &nid, usage); } - if (status & 1) + if (STATUS_OK) { int old; int name_nid; @@ -605,7 +605,7 @@ int main(int argc, const char *argv[]) } status = TreeOpenNew((char *)tree, strtol(shot, NULL, 0)); - if (!status & 1) + if (STATUS_NOT_OK) { printf("Error creating new tree for treename /%s/, shot number /%s/\n", tree, shot); diff --git a/hdf5/hdf5tdi.c b/hdf5/hdf5tdi.c index 2dbae116ef..988dae669b 100644 --- a/hdf5/hdf5tdi.c +++ b/hdf5/hdf5tdi.c @@ -152,7 +152,7 @@ static int find_attr(hid_t attr_id, const char *name, void *op_data) h5item *item = (h5item *)malloc(sizeof(h5item)); h5item *itm; item->item_type = -1; - item->name = strcpy(malloc(strlen(name) + 1), name); + item->name = strdup(name); item->child = 0; item->brother = 0; item->parent = parent; @@ -189,7 +189,7 @@ static int find_objs(hid_t group, const char *name, void *op_data) h5item *item = (h5item *)malloc(sizeof(h5item)); h5item *itm; item->item_type = 0; - item->name = strcpy(malloc(strlen(name) + 1), name); + item->name = strdup(name); item->child = 0; item->brother = 0; item->parent = parent; @@ -236,7 +236,7 @@ static int find_objs(hid_t group, const char *name, void *op_data) /* static void ListItem(h5item * item) { - char *name = strcpy(malloc(strlen(item->name) + 1), item->name); + char *name = strdup(item->name); char *tmp; h5item *itm; for (itm = item->parent; itm; itm = itm->parent) { @@ -258,7 +258,7 @@ static void ListItem(h5item * item) */ static void list_one(h5item *item, struct descriptor *xd) { - char *name = strcpy(malloc(strlen(item->name) + 1), item->name); + char *name = strdup(item->name); char *tmp; h5item *itm; for (itm = item->parent; itm; itm = itm->parent) @@ -296,7 +296,7 @@ EXPORT void hdf5list(struct descriptor *xd) static int find_one(h5item *item, char *findname, hid_t *obj, int *item_type) { int status = 0; - char *name = strcpy(malloc(strlen(item->name) + 1), item->name); + char *name = strdup(item->name); char *tmp; h5item *itm; for (itm = item->parent; itm; itm = itm->parent) @@ -331,7 +331,7 @@ static int FindItem(char *namein, hid_t *obj, int *item_type) { int status; int i; - char *name = strcpy(malloc(strlen(namein) + 1), namein); + char *name = strdup(namein); for (i = strlen(name) - 1; i >= 0; i--) if (name[i] == 32) name[i] = 0; @@ -347,7 +347,7 @@ EXPORT int hdf5read(char *name, struct descriptor_xd *xd) hid_t obj, type; int item_type; int status = FindItem(name, &obj, &item_type); - if (status & 1) + if (STATUS_OK) { if (item_type == H5G_DATASET) { diff --git a/idlmdsevent/mdsevent.c b/idlmdsevent/mdsevent.c index 32f9ec020f..5b460a67f7 100644 --- a/idlmdsevent/mdsevent.c +++ b/idlmdsevent/mdsevent.c @@ -53,12 +53,15 @@ EventStruct *MDSEVENT(int *base_id, int *stub_id, struct dsc$descriptor *name) Invoked from MDSEVENT.PRO ------------------------------------------------------------------------------*/ -#include -#include -#include + #include #include +#include +#include +#include +#include + typedef struct _event_struct { int stub_id; @@ -120,8 +123,8 @@ EXPORT int IDLMdsEventCan(int argc, void **argv) if (argc == 2) { EventStruct *e, *p; - SOCKET sock = (SOCKET)((char *)argv[0] - (char *)0); - int eventid = (unsigned int)((char *)argv[1] - (char *)0); + SOCKET sock = (SOCKET)((intptr_t)argv[0]); + int eventid = (int)((intptr_t)argv[1]); BlockSig(SIGALRM); status = (sock >= 0) ? MdsEventCan(sock, eventid) : MDSEventCan(eventid); UnBlockSig(SIGALRM); @@ -148,7 +151,7 @@ EXPORT int IDLMdsGetevi(int argc, void **argv) { if (argc == 2) { - int eventid = (unsigned int)((char *)argv[0] - (char *)0); + int eventid = (int)((intptr_t)argv[0]); EventStruct *e; for (e = EventList; e && e->loc_event_id != eventid; e = e->next) ; @@ -218,7 +221,7 @@ EXPORT int IDLMdsEvent(int argc, void **argv) { if (argc == 4) { - SOCKET sock = (SOCKET)((char *)argv[0] - (char *)0); + SOCKET sock = (SOCKET)(intptr_t)argv[0]; int *base_id = (int *)argv[1]; int *stub_id = (int *)argv[2]; char *name = (char *)argv[3]; @@ -252,7 +255,7 @@ EXPORT int IDLMdsEvent(int argc, void **argv) { XtAppAddInput(XtWidgetToApplicationContext(w1), sock, (XtPointer)XtInputExceptMask, MdsDispatchEvent, - (char *)0 + sock); + (void *)(intptr_t)sock); } if (pipe(event_pipe) == -1) perror("Error creating event pipes\n"); diff --git a/idlmdswidgets/cw_wveditv5.c b/idlmdswidgets/cw_wveditv5.c index fa83051eab..e659fa8230 100644 --- a/idlmdswidgets/cw_wveditv5.c +++ b/idlmdswidgets/cw_wveditv5.c @@ -622,17 +622,17 @@ PasteComplete(Widget w, int stub, Atom *selection __attribute__((unused)), */ XtGetSelectionValue(w, XA_PRIMARY, XA_X_AXIS, (XtSelectionCallbackProc)PasteComplete, - (XtPointer)((char *)0 + stub), + (XtPointer)(void *)(intptr_t)stub, XtLastTimestampProcessed(XtDisplay(w))); XtGetSelectionValue(w, XA_PRIMARY, XA_Y_AXIS, (XtSelectionCallbackProc)PasteComplete, - (XtPointer)((char *)0 + stub), + (XtPointer)(void *)(intptr_t)stub, XtLastTimestampProcessed(XtDisplay(w))); } else if (supports_string_paste) XtGetSelectionValue(w, XA_PRIMARY, XA_STRING, (XtSelectionCallbackProc)PasteComplete, - (XtPointer)((char *)0 + stub), + (XtPointer)(void *)(intptr_t)stub, XtLastTimestampProcessed(XtDisplay(w))); XtFree((String)values); } @@ -651,7 +651,7 @@ static void Paste(Widget w, int stub, } XtGetSelectionValue( w, XA_PRIMARY, XA_TARGETS, (XtSelectionCallbackProc)PasteComplete, - (XtPointer)((char *)0 + stub), XtLastTimestampProcessed(XtDisplay(w))); + (XtPointer)((void *)(intptr_t)stub), XtLastTimestampProcessed(XtDisplay(w))); } static void LoseSelection(Widget w, Atom *selection __attribute__((unused))) diff --git a/include/STATICdef.h b/include/STATICdef.h deleted file mode 100644 index 5ea860b10c..0000000000 --- a/include/STATICdef.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef __STATICdef -#define STATIC_ROUTINE static -#define STATIC_CONSTANT static -#define STATIC_THREADSAFE static -#define __STATICdef -#endif diff --git a/include/ipdesc.h b/include/ipdesc.h index 0a53c0606e..75d370081d 100644 --- a/include/ipdesc.h +++ b/include/ipdesc.h @@ -1,14 +1,6 @@ #ifndef IPDESC_H #define IPDESC_H -#ifdef _WIN32 -#ifndef _WS2DEF_ -#include "windows.h" -#endif -#else -typedef int SOCKET; -#define INVALID_SOCKET -1 -#endif #define MAX_DIMS 8 #define DTYPE_UCHAR 2 #define DTYPE_USHORT 3 @@ -48,6 +40,7 @@ extern "C" #endif #ifndef __MDSIP_H__ +#define INVALID_CONNECTION_ID -1 extern int ConnectToMds(char *host); extern int SendArg(int s, unsigned char i, char dtype, unsigned char nargs, short len, char ndims, int *dims, char *ptr); diff --git a/include/libroutines.h b/include/libroutines.h index d8114420fd..f3726de0ea 100644 --- a/include/libroutines.h +++ b/include/libroutines.h @@ -62,8 +62,6 @@ extern int LibTraverseTree(LibTreeNode **treehead, int (*user_rtn)(), extern int LibWait(const float *const secs); extern int libffs(const int *const position, const int *const size, const char *const base, int *const find_position); -extern uint32_t LibGetHostAddr(const char *const host); - /// @} #endif diff --git a/include/mdsdescrip.h b/include/mdsdescrip.h index 8122ab4cf8..c99cd39df2 100644 --- a/include/mdsdescrip.h +++ b/include/mdsdescrip.h @@ -254,7 +254,15 @@ typedef struct descriptor_xd l_length_t l_length; } mdsdsc_xd_t; -#define EMPTYXD(name) mdsdsc_xd_t name = {0, DTYPE_DSC, CLASS_XD, 0, 0} +#define MDSDSC_D_INITIALIZER \ + { \ + 0, DTYPE_DSC, CLASS_D, 0 \ + } +#define MDSDSC_XD_INITIALIZER \ + { \ + 0, DTYPE_DSC, CLASS_XD, 0, 0 \ + } +#define EMPTYXD(name) mdsdsc_xd_t name = MDSDSC_XD_INITIALIZER /************************************************ CLASS_XS extended static descriptor definition. diff --git a/include/mdsobjects.h b/include/mdsobjects.h index 659f0610ab..ec2b08d479 100644 --- a/include/mdsobjects.h +++ b/include/mdsobjects.h @@ -3614,13 +3614,15 @@ namespace MDSplus // version virtual void makeSegmentResampled(Data *start, Data *end, Data *time, Array *initialData, - TreeNode *resampledNode) + TreeNode *resampledNode, + int resFactor = 100) { (void)start; (void)end; (void)initialData; (void)time; (void)resampledNode; + (void)resFactor; throw MdsException( "makeSegmentResampled() not supported for TreeNodeThinClient object"); } diff --git a/include/mdsshr.h b/include/mdsshr.h index 056ff96159..6b5d43f028 100644 --- a/include/mdsshr.h +++ b/include/mdsshr.h @@ -85,6 +85,7 @@ extern "C" extern void MdsEnableSandbox(); extern int MDSfprintf(FILE *const fp, const char *const fmt, ...); extern void MdsFree(void *const ptr); + extern void MdsFreeDescriptor(mdsdsc_t *d); extern int MdsGet1Dx(const l_length_t *const len, const dtype_t *const dtype, mdsdsc_xd_t *const dsc, void **const zone); extern int MdsGet1DxA(const mdsdsc_a_t *const in, const length_t *const len, diff --git a/include/socket_port.h b/include/socket_port.h deleted file mode 100644 index ae759a9e07..0000000000 --- a/include/socket_port.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef SOCKET_PORT_H -#define SOCKET_PORT_H -#ifdef _WIN32 -#ifdef _WIN32_WINNT -#undef _WIN32_WINNT -#endif -#define _WIN32_WINNT _WIN32_WINNT_WIN8 // Windows 8.0 -#include -#include -#include -#include -typedef int socklen_t; -#define close closesocket -#define ioctl ioctlsocket -#define FIONREAD_TYPE u_long -#define snprintf _snprintf -#define getpid _getpid -#define SHUT_RDWR 2 -#else -typedef int SOCKET; -#define INVALID_SOCKET -1 -#define FIONREAD_TYPE int -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif -#include - -#ifndef MSG_NOSIGNAL -#define MSG_NOSIGNAL 0 -#endif -#ifndef MSG_DONTWAIT -#define MSG_DONTWAIT 0 -#endif - -#define SEND_BUF_SIZE 32768 -#define RECV_BUF_SIZE 32768 - -#ifdef _WIN32 -#define DEFINE_INITIALIZESOCKETS \ - static void InitializeSockets() \ - { \ - WSADATA wsaData; \ - WORD wVersionRequested; \ - wVersionRequested = MAKEWORD(1, 1); \ - WSAStartup(wVersionRequested, &wsaData); \ - } \ - INIT_SHARED_FUNCTION_ONCE(InitializeSockets) -#define INITIALIZESOCKETS RUN_SHARED_FUNCTION_ONCE(InitializeSockets) -#else -#define DEFINE_INITIALIZESOCKETS -#define INITIALIZESOCKETS -#endif - -#endif // SOCKET_PORT_H diff --git a/include/status.h b/include/status.h index f20435a561..77f8b8567b 100644 --- a/include/status.h +++ b/include/status.h @@ -18,8 +18,10 @@ #define STATUS_TO_CODE TO_CODE(status) #define RETURN_IF_STATUS_NOT_OK \ if (STATUS_NOT_OK) \ - return status; \ -#define BREAK_IF_STATUS_NOT_OK if (STATUS_NOT_OK) break; + return status; +#define BREAK_IF_STATUS_NOT_OK \ + if (STATUS_NOT_OK) \ + break; #define GOTO_IF_STATUS_NOT_OK(MARK) \ if (STATUS_NOT_OK) \ goto MARK; diff --git a/java/mdsplus-api/src/test/java/mds/MdsShr_Test.java b/java/mdsplus-api/src/test/java/mds/MdsShr_Test.java index ee2ae7532a..1545acde72 100644 --- a/java/mdsplus-api/src/test/java/mds/MdsShr_Test.java +++ b/java/mdsplus-api/src/test/java/mds/MdsShr_Test.java @@ -51,7 +51,7 @@ public final void testMdsCompress() throws MdsException @Test public final void testMdsEvent() throws MdsException { - Assert.assertEquals(1, MdsShr_Test.mdsshr.mdsEvent(null, "myevent")); + Assert.assertEquals(1, MdsShr_Test.mdsshr.mdsEvent(null, "myevent") & 1); } @Test diff --git a/javamds/ServerSupport.c b/javamds/ServerSupport.c index 01cb77d04a..2e4696c8c5 100644 --- a/javamds/ServerSupport.c +++ b/javamds/ServerSupport.c @@ -101,7 +101,7 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, DESCRIPTOR_SIGNAL_1(retSigDsc, &dataDsc, NULL, ×Dsc); printf("JavaResample %d %f %f %f\n", nid, *xmin, *xmax, *dt); status = TreeGetNumSegments(nid, &numSegments); - if (!(status & 1) || numSegments < 1) + if (STATUS_NOT_OK || numSegments < 1) { printf("JavaResample: Unexpected Non Segmented Item!!\n"); return &emptyXd; @@ -114,21 +114,21 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, for (currSegment = 0; currSegment < numSegments; currSegment++) { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); - if (status & 1) + if (STATUS_OK) status = TdiData(&startXd, &startXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&startXd, &startXd MDS_END_ARG); - if (!(status & 1) || startXd.pointer == NULL || + if (STATUS_NOT_OK || startXd.pointer == NULL || startXd.pointer->class != CLASS_S) { printf("Cannot get segment start!!\n"); return &xd; } - if (status & 1) + if (STATUS_OK) status = TdiData(&endXd, &endXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&endXd, &endXd MDS_END_ARG); - if (!(status & 1) || endXd.pointer == NULL || + if (STATUS_NOT_OK || endXd.pointer == NULL || endXd.pointer->class != CLASS_S) { printf("Cannot get segment end!!\n"); @@ -170,15 +170,15 @@ EXPORT struct descriptor_xd *JavaResample(int *nidPtr, float *xmin, float *xmax, for (currSegment = minSegment; currSegment <= maxSegment; currSegment++) { status = TreeGetSegment(nid, currSegment, &segDataXd, &segTimesXd); - if (status & 1) + if (STATUS_OK) status = TdiData(&segDataXd, &segDataXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&segDataXd, &segDataXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiData(&segTimesXd, &segTimesXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&segTimesXd, &segTimesXd MDS_END_ARG); - if (!(status & 1) || segDataXd.pointer->class != CLASS_A || + if (STATUS_NOT_OK || segDataXd.pointer->class != CLASS_A || segTimesXd.pointer->class != CLASS_A) { printf("Cannot Get segment %d\n", currSegment); @@ -355,7 +355,7 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, currName[dsc->length] = 0; status = TreeFindNode(currName, &nid); free(currName); - if (status & 1) + if (STATUS_OK) return traverseNodeMinMax(nid, xMin, xMax); return 0; case DTYPE_NID: @@ -433,7 +433,7 @@ static int traverseExprMinMax(struct descriptor *dsc, float *xMin, if (!recD->dscptrs[2]) return 0; status = TdiData(recD->dscptrs[2], &xd MDS_END_ARG); - if (!(status & 1) || !xd.pointer) + if (STATUS_NOT_OK || !xd.pointer) return 0; status = traverseExprMinMax(xd.pointer, xMin, xMax); MdsFree1Dx(&xd, 0); @@ -473,24 +473,24 @@ static int traverseNodeMinMax(int nid, float *xMin, float *xMax) int numSegments, status; status = TreeGetNumSegments(nid, &numSegments); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (numSegments == 0) { status = TreeGetRecord(nid, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = traverseExprMinMax(xd.pointer, xMin, xMax); MdsFree1Dx(&xd, 0); return status; } status = TreeGetSegmentLimits(nid, 0, &startXd, &endXd); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = TdiData(&startXd, &startXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&startXd, &startXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (startXd.pointer->length == 8) *xMin = *((double *)startXd.pointer->pointer); @@ -499,12 +499,12 @@ static int traverseNodeMinMax(int nid, float *xMin, float *xMax) MdsFree1Dx(&startXd, 0); MdsFree1Dx(&endXd, 0); status = TreeGetSegmentLimits(nid, numSegments - 1, &startXd, &endXd); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = TdiData(&endXd, &endXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&endXd, &endXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (endXd.pointer->length == 8) *xMax = *((double *)endXd.pointer->pointer); @@ -523,7 +523,7 @@ EXPORT int JavaGetMinMax(char *sigExpr, float *xMin, float *xMax) struct descriptor sigD = {strlen(sigExpr), DTYPE_T, CLASS_S, sigExpr}; status = TdiCompile(&sigD, &xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = traverseExprMinMax(xd.pointer, xMin, xMax); @@ -547,7 +547,7 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, char dtype, dimct; int dims[16], next_row; status = TdiCompile(&sigD, &xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (xd.pointer->dtype != DTYPE_NID) { @@ -556,12 +556,12 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, } nid = *((int *)xd.pointer->pointer); status = TreeGetNumSegments(nid, &numSegments); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (numSegments == 0) { status = TdiData(&xd, &xd MDS_END_ARG); - if (!(status & 1) || !xd.pointer || xd.pointer->class != CLASS_A) + if (STATUS_NOT_OK || !xd.pointer || xd.pointer->class != CLASS_A) numPoints = 0; else { @@ -574,12 +574,12 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, for (currSegment = 0; currSegment < numSegments; currSegment++) { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = TdiData(&startXd, &startXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&startXd, &startXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (startXd.pointer->length == 8) currStart = *((double *)startXd.pointer->pointer); @@ -593,12 +593,12 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, for (numPoints = 0; currSegment < numSegments; currSegment++) { status = TreeGetSegmentLimits(nid, currSegment, &startXd, &endXd); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; status = TdiData(&endXd, &endXd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiFloat(&endXd, &endXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; if (endXd.pointer->length == 8) currEnd = *((double *)endXd.pointer->pointer); @@ -611,7 +611,7 @@ EXPORT int JavaGetNumPoints(char *sigExpr, float *xMin, float *xMax, break; status = TreeGetSegmentInfo(nid, currSegment, &dtype, &dimct, dims, &next_row); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; numPoints += dims[0]; if (numPoints > nThreshold) diff --git a/javamds/mdsobjects.c b/javamds/mdsobjects.c index d241994620..99f77491e6 100644 --- a/javamds/mdsobjects.c +++ b/javamds/mdsobjects.c @@ -100,11 +100,10 @@ extern int GetAnswerInfoTS(int sock, char *dtype, short *length, char *ndims, int *dims, int *numbytes, void **dptr, void **m); #ifdef DEBUG -static void printDecompiled(struct descriptor *dsc) +static void printDecompiled(mdsdsc_t *dsc) { EMPTYXD(out_xd); - static char decompiled[1024]; - + char decompiled[1024]; TdiDecompile(dsc, &out_xd MDS_END_ARG); if (!out_xd.pointer) printf("NULL\n"); @@ -113,11 +112,10 @@ static void printDecompiled(struct descriptor *dsc) printf("%s\n", decompiled); MdsFree1Dx(&out_xd, 0); } -static void printDecompiled1(void *ctx, struct descriptor *dsc) +static void printDecompiled1(void *ctx, mdsdsc_t *dsc) { EMPTYXD(out_xd); - static char decompiled[1024]; - + char decompiled[1024]; CTXCALLR(TdiDecompile, dsc, &out_xd MDS_END_ARG); if (!out_xd.pointer) printf("NULL\n"); @@ -128,7 +126,7 @@ static void printDecompiled1(void *ctx, struct descriptor *dsc) } #endif -static void FreeDescrip(struct descriptor *desc); +static void FreeDescrip(mdsdsc_t *desc); static jintArray getDimensions(JNIEnv *env, void *dsc) { @@ -147,7 +145,7 @@ static jintArray getDimensions(JNIEnv *env, void *dsc) return jdims; } -static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, +static jobject DescripToObject(JNIEnv *env, void *ctx, mdsdsc_t *desc, jobject helpObj, jobject unitsObj, jobject errorObj, jobject validationObj) { @@ -169,7 +167,7 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, double *double_buf; char message[64]; - struct descriptor_a *array_d; + mdsdsc_a_t *array_d; struct descriptor_r *record_d; char *buf; // EMPTYXD(float_xd); @@ -184,7 +182,7 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, // desc->class); if (desc->class == CLASS_XD) - return DescripToObject(env, ctx, ((struct descriptor_xd *)desc)->pointer, + return DescripToObject(env, ctx, ((mdsdsc_xd_t *)desc)->pointer, helpObj, unitsObj, errorObj, validationObj); memset(&args, 0, sizeof(args)); switch (desc->class) @@ -247,11 +245,11 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, return (*env)->CallStaticObjectMethodA(env, cls, constr, args); case DTYPE_NID: cls = (*env)->FindClass(env, "MDSplus/TreeNode"); -// constr = (*env)->GetStaticMethodID(env, cls, "getData", -// "(I)LMDSplus/TreeNode;"); + // constr = (*env)->GetStaticMethodID(env, cls, "getData", + // "(I)LMDSplus/TreeNode;"); constr = (*env)->GetStaticMethodID(env, cls, "getData", "(ILMDSplus/Data;LMDSplus/Data;LMDSplus/" - "Data;LMDSplus/Data;)LMDSplus/TreeNode;"); + "Data;LMDSplus/Data;)LMDSplus/TreeNode;"); args[0].i = *(int *)desc->pointer; return (*env)->CallStaticObjectMethodA(env, cls, constr, args); case DTYPE_QU: @@ -383,9 +381,9 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, args[4].l = errorObj; args[5].l = validationObj; if (is_ca) - array_d = (struct descriptor_a *)ca_xd.pointer; + array_d = (mdsdsc_a_t *)ca_xd.pointer; else - array_d = (struct descriptor_a *)desc; + array_d = (mdsdsc_a_t *)desc; args[1].l = getDimensions(env, array_d); length = (array_d->length != 0) ? array_d->arsize / array_d->length : 0; @@ -796,7 +794,7 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, args[2].l = unitsObj; args[3].l = errorObj; args[4].l = validationObj; - array_d = (struct descriptor_a *)desc; + array_d = (mdsdsc_a_t *)desc; length = array_d->arsize / array_d->length; switch (desc->dtype) { @@ -821,7 +819,7 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, for (i = 0; i < length; i++) { if ((curr_obj = DescripToObject( - env, ctx, ((struct descriptor **)array_d->pointer)[i], 0, 0, 0, + env, ctx, ((mdsdsc_t **)array_d->pointer)[i], 0, 0, 0, 0))) (*env)->SetObjectArrayElement(env, jobjects, i, curr_obj); } @@ -837,11 +835,11 @@ static jobject DescripToObject(JNIEnv *env, void *ctx, struct descriptor *desc, return 0; } -static struct descriptor *completeDescr(struct descriptor *dataDscPtr, - struct descriptor *helpDscPtr, - struct descriptor *unitsDscPtr, - struct descriptor *errorDscPtr, - struct descriptor *validationDscPtr) +static mdsdsc_t *completeDescr(mdsdsc_t *dataDscPtr, + mdsdsc_t *helpDscPtr, + mdsdsc_t *unitsDscPtr, + mdsdsc_t *errorDscPtr, + mdsdsc_t *validationDscPtr) { DESCRIPTOR_PARAM(templateParam, 0, 0, 0); DESCRIPTOR_WITH_UNITS(templateWithUnits, 0, 0); @@ -859,7 +857,7 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, currWithErrorDsc->error = errorDscPtr; currWithErrorDsc->data = completeDescr(dataDscPtr, helpDscPtr, unitsDscPtr, 0, validationDscPtr); - return (struct descriptor *)currWithErrorDsc; + return (mdsdsc_t *)currWithErrorDsc; } if (unitsDscPtr) { @@ -870,7 +868,7 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, currWithUnitsDsc->units = unitsDscPtr; currWithUnitsDsc->data = completeDescr(dataDscPtr, helpDscPtr, 0, errorDscPtr, validationDscPtr); - return (struct descriptor *)currWithUnitsDsc; + return (mdsdsc_t *)currWithUnitsDsc; } if (helpDscPtr || validationDscPtr) { @@ -881,12 +879,12 @@ static struct descriptor *completeDescr(struct descriptor *dataDscPtr, currParamDsc->validation = validationDscPtr; currParamDsc->value = completeDescr(dataDscPtr, 0, unitsDscPtr, errorDscPtr, 0); - return (struct descriptor *)currParamDsc; + return (mdsdsc_t *)currParamDsc; } return dataDscPtr; } -static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) +static mdsdsc_t *ObjectToDescrip(JNIEnv *env, jobject obj) { jclass cls; jfieldID datum_fid, descs_fid, ndescs_fid, opcode_fid, dtype_fid, dclass_fid, @@ -895,8 +893,8 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) static DESCRIPTOR_A_COEFF(template_array, 0, 0, 0, (unsigned char)255, 0); ARRAY_COEFF(char, 255) * array_d; static DESCRIPTOR_A(template_apd, 0, 0, 0, 0); - struct descriptor_a *apd_d; - // struct descriptor_a *array_d; + mdsdsc_a_t *apd_d; + // mdsdsc_a_t *array_d; static DESCRIPTOR_R(template_rec, 0, 1); struct descriptor_r *record_d; int i, ndescs, opcode, dtype, dclass, nDims; @@ -920,9 +918,9 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) int maxlen; jstring java_string; const char *string; - struct descriptor *desc; + mdsdsc_t *desc; jfieldID getUnitsFid, getHelpFid, getValidationFid, getErrorFid; - struct descriptor *unitsDscPtr, *helpDscPtr, *validationDscPtr, *errorDscPtr; + mdsdsc_t *unitsDscPtr, *helpDscPtr, *validationDscPtr, *errorDscPtr; // printf("ObjectTodescrip %x\n", obj); @@ -960,7 +958,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) switch (dclass) { case CLASS_S: - desc = (struct descriptor *)malloc(sizeof(struct descriptor)); + desc = (mdsdsc_t *)malloc(sizeof(mdsdsc_t)); desc->class = dclass; desc->dtype = dtype; @@ -1114,7 +1112,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) array_d->pointer = (char *)malloc(array_d->arsize); memcpy(array_d->pointer, bytes, array_d->arsize); (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_W: case DTYPE_WU: @@ -1127,7 +1125,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) array_d->pointer = (char *)malloc(array_d->arsize); memcpy(array_d->pointer, shorts, array_d->arsize); (*env)->ReleaseShortArrayElements(env, jshorts, shorts, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_L: case DTYPE_LU: @@ -1140,7 +1138,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) array_d->pointer = (char *)malloc(array_d->arsize); memcpy(array_d->pointer, ints, array_d->arsize); (*env)->ReleaseIntArrayElements(env, jints, ints, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_Q: case DTYPE_QU: @@ -1153,7 +1151,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) array_d->pointer = (char *)malloc(array_d->arsize); memcpy(array_d->pointer, longs, array_d->arsize); (*env)->ReleaseLongArrayElements(env, jlongs, longs, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_O: case DTYPE_OU: @@ -1166,7 +1164,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) array_d->pointer = (char *)malloc(array_d->arsize); memcpy(array_d->pointer, longs, array_d->arsize); (*env)->ReleaseLongArrayElements(env, jlongs, longs, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_FLOAT: datum_fid = (*env)->GetFieldID(env, cls, "datum", "[F"); @@ -1181,7 +1179,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) CvtConvertFloat(&floats[i], DTYPE_FS, &((float *)array_d->pointer)[i], array_d->dtype, 0); (*env)->ReleaseFloatArrayElements(env, jfloats, floats, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_DOUBLE: datum_fid = (*env)->GetFieldID(env, cls, "datum", "[D"); @@ -1196,7 +1194,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) CvtConvertFloat(&doubles[i], DTYPE_DOUBLE, &((double *)array_d->pointer)[i], array_d->dtype, 0); (*env)->ReleaseDoubleArrayElements(env, jdoubles, doubles, 0); - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case DTYPE_T: datum_fid = (*env)->GetFieldID(env, cls, "datum", "[Ljava/lang/String;"); @@ -1221,7 +1219,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) } array_d->length = maxlen; array_d->arsize = array_d->length * length; - return completeDescr((struct descriptor *)array_d, helpDscPtr, + return completeDescr((mdsdsc_t *)array_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); default: printf("\nUnsupported type for CLASS_A: %d\n", dtype); @@ -1266,7 +1264,7 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) record_d->dscptrs[i] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jdescs, i)); } - return completeDescr((struct descriptor *)record_d, helpDscPtr, unitsDscPtr, + return completeDescr((mdsdsc_t *)record_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); case CLASS_APD: descs_fid = (*env)->GetFieldID(env, cls, "descs", "[LMDSplus/Data;"); @@ -1274,17 +1272,17 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) ndescs_fid = (*env)->GetFieldID(env, cls, "nDescs", "I"); ndescs = (*env)->GetIntField(env, obj, ndescs_fid); // ndescs = (*env)->GetArrayLength(env, jdescs); - apd_d = (struct descriptor_a *)malloc(sizeof(struct descriptor_a)); - memcpy(apd_d, &template_apd, sizeof(struct descriptor_a)); + apd_d = (mdsdsc_a_t *)malloc(sizeof(mdsdsc_a_t)); + memcpy(apd_d, &template_apd, sizeof(mdsdsc_a_t)); apd_d->dtype = dtype; apd_d->class = CLASS_APD; - apd_d->length = sizeof(struct descriptor *); + apd_d->length = sizeof(mdsdsc_t *); apd_d->arsize = apd_d->length * ndescs; apd_d->pointer = (char *)malloc(sizeof(void *) * ndescs); for (i = 0; i < ndescs; i++) - ((struct descriptor **)(apd_d->pointer))[i] = + ((mdsdsc_t **)(apd_d->pointer))[i] = ObjectToDescrip(env, (*env)->GetObjectArrayElement(env, jdescs, i)); - return completeDescr((struct descriptor *)apd_d, helpDscPtr, unitsDscPtr, + return completeDescr((mdsdsc_t *)apd_d, helpDscPtr, unitsDscPtr, errorDscPtr, validationDscPtr); default: printf("\nUnsupported class: %d\n", dclass); @@ -1292,10 +1290,10 @@ static struct descriptor *ObjectToDescrip(JNIEnv *env, jobject obj) return 0; } -static void FreeDescrip(struct descriptor *desc) +static void FreeDescrip(mdsdsc_t *desc) { struct descriptor_r *record_d; - struct descriptor_a *array_d; + mdsdsc_a_t *array_d; int i; if (!desc) @@ -1312,7 +1310,7 @@ static void FreeDescrip(struct descriptor *desc) break; case CLASS_A: if (desc->pointer) - free(((struct descriptor_a *)desc)->pointer); + free(((mdsdsc_a_t *)desc)->pointer); break; case CLASS_R: record_d = (struct descriptor_r *)desc; @@ -1322,9 +1320,9 @@ static void FreeDescrip(struct descriptor *desc) FreeDescrip(record_d->dscptrs[i]); break; case CLASS_APD: - array_d = (struct descriptor_a *)desc; + array_d = (mdsdsc_a_t *)desc; for (i = 0; i < (int)array_d->arsize / array_d->length; i++) - FreeDescrip(((struct descriptor **)array_d->pointer)[i]); + FreeDescrip(((mdsdsc_t **)array_d->pointer)[i]); break; } free(desc); @@ -1343,8 +1341,8 @@ JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *env, jclass exc; int status; char *errorMsg; - struct descriptor_a *arrPtr; - struct descriptor *dscPtr = ObjectToDescrip(env, obj); + mdsdsc_a_t *arrPtr; + mdsdsc_t *dscPtr = ObjectToDescrip(env, obj); jbyteArray jserialized; status = MdsSerializeDscOut(dscPtr, &xd); if (STATUS_NOT_OK) @@ -1354,7 +1352,7 @@ JNIEXPORT jbyteArray JNICALL Java_MDSplus_Data_serialize(JNIEnv *env, (*env)->ThrowNew(env, exc, errorMsg); return NULL; } - arrPtr = (struct descriptor_a *)xd.pointer; + arrPtr = (mdsdsc_a_t *)xd.pointer; if (arrPtr->dtype != DTYPE_B && arrPtr->dtype != DTYPE_BU) { printf("FATAL ERROR: MdsSerializeDscOut returned a wrong type"); @@ -1415,7 +1413,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_compile(JNIEnv *env, const char *expr = (*env)->GetStringUTFChars(env, jexpr, 0); char *error_msg; jclass exc; - struct descriptor exprD = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t exprD = {0, DTYPE_T, CLASS_S, 0}; jobject ris; jint numArgs; @@ -1462,11 +1460,11 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_decompile(JNIEnv *env, jobject jobj, EMPTYXD(outXd); jstring ris; jclass exc; - struct descriptor *decD; + mdsdsc_t *decD; char *buf; char *error_msg; int status; - struct descriptor *dataD; + mdsdsc_t *dataD; void *ctx = JLONG2PTR(jctx); dataD = ObjectToDescrip(env, jobj); @@ -1505,7 +1503,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_cloneData(JNIEnv *env, jobject jobj) { - struct descriptor *descr; + mdsdsc_t *descr; jobject retObj; descr = ObjectToDescrip(env, jobj); retObj = DescripToObject(env, NULL, descr, 0, 0, 0, 0); @@ -1530,7 +1528,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *env, const char *expr = (*env)->GetStringUTFChars(env, jexpr, 0); char *error_msg; jclass exc; - struct descriptor exprD = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t exprD = {0, DTYPE_T, CLASS_S, 0}; jobject ris; jint numArgs = (*env)->GetArrayLength(env, jargs); @@ -1558,7 +1556,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_execute(JNIEnv *env, (*env)->ThrowNew(env, exc, error_msg); return NULL; } - status = TdiData((struct descriptor *)&outXd, &outXd MDS_END_ARG); + status = TdiData((mdsdsc_t *)&outXd, &outXd MDS_END_ARG); if (STATUS_NOT_OK) { error_msg = (char *)MdsGetMsg(status); @@ -1586,7 +1584,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Data_dataData(JNIEnv *env, jobject jobj, jclass exc; int status; - struct descriptor *descr; + mdsdsc_t *descr; descr = ObjectToDescrip(env, jobj); status = CTXCALLR(TdiData, descr, &xd MDS_END_ARG); if (STATUS_NOT_OK) @@ -1616,7 +1614,7 @@ JNIEXPORT jstring JNICALL Java_MDSplus_Data_evaluateData(JNIEnv *env, char *error_msg; jobject retObj; jclass exc; - struct descriptor *descr = ObjectToDescrip(env, jobj); + mdsdsc_t *descr = ObjectToDescrip(env, jobj); int status = CTXCALLR(TdiEvaluate, descr, &xd MDS_END_ARG); if (STATUS_NOT_OK) { @@ -1953,7 +1951,7 @@ JNIEXPORT void JNICALL Java_MDSplus_Tree_setTreeTimeContext( JNIEnv *env, jclass cls __attribute__((unused)), jlong jctx, jobject jstart, jobject jend, jobject jdelta) { - struct descriptor *start, *end, *delta; + mdsdsc_t *start, *end, *delta; int status; void *ctx = JLONG2PTR(jctx); start = ObjectToDescrip(env, jstart); @@ -2208,7 +2206,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_compile(JNIEnv *env, const char *expr = (*env)->GetStringUTFChars(env, jexpr, 0); char *error_msg; jclass exc; - struct descriptor exprD = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t exprD = {0, DTYPE_T, CLASS_S, 0}; jobject ris; jint numArgs; @@ -2263,7 +2261,7 @@ JNIEXPORT jobject JNICALL Java_MDSplus_Tree_execute(JNIEnv *env, const char *expr = (*env)->GetStringUTFChars(env, jexpr, 0); char *error_msg; jclass exc; - struct descriptor exprD = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t exprD = {0, DTYPE_T, CLASS_S, 0}; jobject ris; jint numArgs; @@ -2666,7 +2664,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putData(JNIEnv *env, jint nid, jlong jctx, jobject jdata) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2710,7 +2708,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_setExtendedAttribute( JNIEnv *env, jclass class __attribute__((unused)), jint nid, jlong jctx, jstring jname, jobject jdata) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); const char *name = (*env)->GetStringUTFChars(env, jname, 0); @@ -2735,7 +2733,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_deleteData(JNIEnv *env, EMPTYXD(emptyXd); int status; void *ctx = JLONG2PTR(jctx); - status = CTXCALLN(TreePutRecord, nid, (struct descriptor *)&emptyXd, 0); + status = CTXCALLN(TreePutRecord, nid, (mdsdsc_t *)&emptyXd, 0); if (STATUS_NOT_OK) throwMdsException(env, status); } @@ -2754,8 +2752,8 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_doMethod(JNIEnv *env, const char *method; int status; void *ctx = JLONG2PTR(jctx); - struct descriptor nidD = {sizeof(int), DTYPE_NID, CLASS_S, 0}; - struct descriptor methodD = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t nidD = {sizeof(int), DTYPE_NID, CLASS_S, 0}; + mdsdsc_t methodD = {0, DTYPE_T, CLASS_S, 0}; EMPTYXD(xd); method = (*env)->GetStringUTFChars(env, jmethod, 0); @@ -2815,7 +2813,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment( jobject jstart, jobject jend, jobject jdim, jobject jdata, jint filledRows __attribute__((unused))) { - struct descriptor *startD, *endD, *dimD, *dataD; + mdsdsc_t *startD, *endD, *dimD, *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2825,7 +2823,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeSegment( dataD = ObjectToDescrip(env, jdata); status = CTXCALLN(TreeMakeSegment, nid, startD, endD, dimD, - (struct descriptor_a *)dataD, -1, filledRows); + (mdsdsc_a_t *)dataD, -1, filledRows); FreeDescrip(startD); FreeDescrip(endD); @@ -2844,7 +2842,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jobject jstart, jobject jend, jobject jdim, jobject jdata) { - struct descriptor *startD, *endD, *dimD, *dataD; + mdsdsc_t *startD, *endD, *dimD, *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2854,7 +2852,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginSegment( dataD = ObjectToDescrip(env, jdata); status = CTXCALLN(TreeBeginSegment, nid, startD, endD, dimD, - (struct descriptor_a *)dataD, -1); + (mdsdsc_a_t *)dataD, -1); FreeDescrip(startD); FreeDescrip(endD); @@ -2873,12 +2871,12 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jobject jdata, jint offset) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); dataD = ObjectToDescrip(env, jdata); - status = CTXCALLN(TreePutSegment, nid, offset, (struct descriptor_a *)dataD); + status = CTXCALLN(TreePutSegment, nid, offset, (mdsdsc_a_t *)dataD); FreeDescrip(dataD); if (STATUS_NOT_OK) throwMdsException(env, status); @@ -2893,7 +2891,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_updateSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jint segmentOffset, jobject jstart, jobject jend, jobject jdim) { - struct descriptor *startD, *endD, *dimD; + mdsdsc_t *startD, *endD, *dimD; int status; void *ctx = JLONG2PTR(jctx); @@ -2918,7 +2916,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jobject jdata) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); @@ -2926,7 +2924,7 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( // printDecompiled(dataD); status = CTXCALLN(TreeBeginTimestampedSegment, nid, - (struct descriptor_a *)dataD, -1); + (mdsdsc_a_t *)dataD, -1); FreeDescrip(dataD); if (STATUS_NOT_OK) throwMdsException(env, status); @@ -2939,24 +2937,24 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_beginTimestampedSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata, jlongArray jtimes) + jobject jdata, jlongArray jtimesArray) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); int numTimes; - int64_t *times; + jlong *jtimes; - numTimes = (*env)->GetArrayLength(env, jtimes); - times = (int64_t *)(*env)->GetLongArrayElements(env, jtimes, NULL); + numTimes = (*env)->GetArrayLength(env, jtimesArray); + jtimes = (*env)->GetLongArrayElements(env, jtimesArray, NULL); dataD = ObjectToDescrip(env, jdata); // printDecompiled(dataD); - status = CTXCALLN(TreeMakeTimestampedSegment, nid, times, - (struct descriptor_a *)dataD, -1, numTimes); + status = CTXCALLN(TreeMakeTimestampedSegment, nid, (int64_t *)jtimes, + (mdsdsc_a_t *)dataD, -1, numTimes); FreeDescrip(dataD); - (*env)->ReleaseLongArrayElements(env, jtimes, times, JNI_ABORT); + (*env)->ReleaseLongArrayElements(env, jtimesArray, jtimes, JNI_ABORT); if (STATUS_NOT_OK) throwMdsException(env, status); } @@ -2968,25 +2966,23 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_makeTimestampedSegment( */ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putTimestampedSegment( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, - jobject jdata, jlongArray jtimes) + jobject jdata, jlongArray jtimesArray) { - struct descriptor *dataD; + mdsdsc_t *dataD; int status; void *ctx = JLONG2PTR(jctx); - // int numTimes; - int64_t *times; - (*env)->GetArrayLength(env, jtimes); - times = (int64_t *)(*env)->GetLongArrayElements(env, jtimes, NULL); + jlong *jtimes; + if ((*env)->GetArrayLength(env, jtimesArray) < 1) + throwMdsException(env, TreeBUFFEROVF); + jtimes = (*env)->GetLongArrayElements(env, jtimesArray, NULL); dataD = ObjectToDescrip(env, jdata); - // printDecompiled(dataD); - - status = CTXCALLN(TreePutTimestampedSegment, nid, times, - (struct descriptor_a *)dataD); + status = CTXCALLN(TreePutTimestampedSegment, nid, (int64_t *)jtimes, + (mdsdsc_a_t *)dataD); FreeDescrip(dataD); - (*env)->ReleaseLongArrayElements(env, jtimes, times, JNI_ABORT); + (*env)->ReleaseLongArrayElements(env, jtimesArray, jtimes, JNI_ABORT); if (STATUS_NOT_OK) throwMdsException(env, status); } @@ -3002,13 +2998,13 @@ JNIEXPORT void JNICALL Java_MDSplus_TreeNode_putRow( JNIEnv *env, jclass cls __attribute__((unused)), jint nid, jlong jctx, jobject jrow, jlong jtime, jint size) { - struct descriptor *rowD; + mdsdsc_t *rowD; int status; void *ctx = JLONG2PTR(jctx); rowD = ObjectToDescrip(env, jrow); status = CTXCALLN(TreePutRow, nid, size, (int64_t *)&jtime, - (struct descriptor_a *)rowD); + (mdsdsc_a_t *)rowD); FreeDescrip(rowD); if (STATUS_NOT_OK) @@ -3542,12 +3538,12 @@ JNIEXPORT void JNICALL Java_MDSplus_Event_setEventRaw(JNIEnv *env, JNIEXPORT jstring JNICALL Java_MDSplus_Data_convertToDate( JNIEnv *env, jclass cls __attribute__((unused)), jlong time) { - struct descriptor_d dateDsc = {0, DTYPE_T, CLASS_D, 0}; + mdsdsc_d_t dateDsc = {0, DTYPE_T, CLASS_D, 0}; unsigned short len; jstring jdate; char *date; - LibSysAscTim(&len, (struct descriptor *)&dateDsc, (int *)&time); + LibSysAscTim(&len, (mdsdsc_t *)&dateDsc, (int *)&time); date = malloc(dateDsc.length + 1); memcpy(date, dateDsc.pointer, dateDsc.length); date[dateDsc.length] = 0; @@ -3700,17 +3696,17 @@ static int convertType(int mdsType) } } -static char getDType(struct descriptor *dsc) { return convertType(dsc->dtype); } +static char getDType(mdsdsc_t *dsc) { return convertType(dsc->dtype); } -static char getNDims(struct descriptor *dsc) +static char getNDims(mdsdsc_t *dsc) { if (dsc->class == CLASS_S) return 0; - return ((struct descriptor_a *)dsc)->dimct; + return ((mdsdsc_a_t *)dsc)->dimct; } -static void getDims(struct descriptor *dsc, int *dims) +static void getDims(mdsdsc_t *dsc, int *dims) { ARRAY_BOUNDS(char *, MAX_DIMS) * arrPtr; int i; @@ -3722,14 +3718,14 @@ static void getDims(struct descriptor *dsc, int *dims) dims[i] = arrPtr->m[i]; } -static short getLength(struct descriptor *dsc) { return dsc->length; } +static short getLength(mdsdsc_t *dsc) { return dsc->length; } -static void *getPtr(struct descriptor *dsc) +static void *getPtr(mdsdsc_t *dsc) { if (dsc->class == CLASS_S) return dsc->pointer; - return ((struct descriptor_a *)dsc)->pointer; + return ((mdsdsc_a_t *)dsc)->pointer; } /* @@ -3744,14 +3740,14 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), const char *expr; jobject exc, currArg, retObj; int nArgs, i, status; - struct descriptor **dscs; + mdsdsc_t **dscs; char dtype, nDims; short length; void *ptr; int dims[MAX_DIMS]; int numBytes; void *mem = 0; - struct descriptor scalarDsc = {0, 0, CLASS_S, 0}; + mdsdsc_t scalarDsc = {0, 0, CLASS_S, 0}; DESCRIPTOR_A_COEFF(arrayDsc, 0, 0, 0, MAX_DIMS, 0); expr = (*env)->GetStringUTFChars(env, jExpr, 0); @@ -3760,7 +3756,7 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), (char *)expr); (*env)->ReleaseStringUTFChars(env, jExpr, expr); - dscs = (struct descriptor **)malloc(nArgs * sizeof(struct descriptor *)); + dscs = (mdsdsc_t **)malloc(nArgs * sizeof(mdsdsc_t *)); for (i = 0; i < nArgs; i++) { currArg = (*env)->GetObjectArrayElement(env, jargs, i); @@ -3891,7 +3887,7 @@ Java_MDSplus_Connection_get(JNIEnv *env, jobject obj __attribute__((unused)), return NULL; } retObj = - DescripToObject(env, NULL, (struct descriptor *)&arrayDsc, 0, 0, 0, 0); + DescripToObject(env, NULL, (mdsdsc_t *)&arrayDsc, 0, 0, 0, 0); } if (mem) FreeMessage(mem); @@ -3913,7 +3909,7 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( char *path, *putExpr; jobject exc, currArg; int nArgs, i, status; - struct descriptor **dscs; + mdsdsc_t **dscs; char dtype, nDims; short length; void *ptr; @@ -3956,7 +3952,7 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( putExpr); free(putExpr); - dscs = (struct descriptor **)malloc(nArgs * sizeof(struct descriptor *)); + dscs = (mdsdsc_t **)malloc(nArgs * sizeof(mdsdsc_t *)); for (i = 0; i < nArgs; i++) { currArg = (*env)->GetObjectArrayElement(env, jArgs, i); @@ -3985,7 +3981,7 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( (*env)->ThrowNew(env, exc, MdsGetMsg(status)); return; } - if (status & 1 && dtype == DTYPE_LONG && nDims == 0 && + if (STATUS_OK && dtype == DTYPE_LONG && nDims == 0 && numBytes == sizeof(int)) memcpy(&status, ptr, numBytes); if (mem) @@ -3999,7 +3995,7 @@ JNIEXPORT void JNICALL Java_MDSplus_Connection_put( ///////////////////GetDeviceField for Netbeans Builder -EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) +EXPORT mdsdsc_xd_t *getDeviceFields(char *deviceName) { int status, nid, curr_nid, i; char *names, *path; @@ -4017,15 +4013,15 @@ EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) } status = TreeOpenNew("device_beans", -1); printf("%s\n", MdsGetMsg(status)); - if (!(status & 1)) + if (STATUS_NOT_OK) return &xd; status = TreeAddNode("Boh", &nid, TreeUSAGE_STRUCTURE); TreeSetDefaultNid(nid); status = TreeAddConglom("TEST", deviceName, &nid); printf("%s\n", MdsGetMsg(status)); - if (status & 1) + if (STATUS_OK) status = TreeGetNci(nid, nci_list); - if (!(status & 1) || conglomerate_nids == 0) + if (STATUS_NOT_OK || conglomerate_nids == 0) { TreeQuitTree("device_beans", -1); return &xd; @@ -4039,7 +4035,7 @@ EXPORT struct descriptor_xd *getDeviceFields(char *deviceName) sprintf(&names[strlen(names)], "%s ", TreeGetMinimumPath(&nid, curr_nid)); dsc.arsize = strlen(names); dsc.pointer = names; - MdsCopyDxXd((struct descriptor *)&dsc, &xd); + MdsCopyDxXd((mdsdsc_t *)&dsc, &xd); printf("%s\n", names); free(names); status = TreeQuitTree("device_beans", -1); diff --git a/m4/m4_ax_check_enable_debug.m4 b/m4/m4_ax_check_enable_debug.m4 index 05b5c975b6..5122401bf6 100644 --- a/m4/m4_ax_check_enable_debug.m4 +++ b/m4/m4_ax_check_enable_debug.m4 @@ -76,29 +76,29 @@ AC_DEFUN([AX_CHECK_ENABLE_DEBUG],[ AS_CASE([$enable_debug], [yes],[ AC_MSG_RESULT(yes) - CFLAGS="${CFLAGS} -g -O0" - CXXFLAGS="${CXXFLAGS} -g -O0" + CFLAGS="${CFLAGS} -g -DWITH_DEBUG_SYMBOLS -O0" + CXXFLAGS="${CXXFLAGS} -g -DWITH_DEBUG_SYMBOLS -O0" FCFLAGS="${FCFLAGS} -g -O0" OBJCFLAGS="${OBJCFLAGS} -g -O0" ], [define],[ AC_MSG_RESULT(yes) - CFLAGS="${CFLAGS} -g -O0 -DDEBUG" - CXXFLAGS="${CXXFLAGS} -g -O0 -DDEBUG" + CFLAGS="${CFLAGS} -g -O0 -DDEBUG -DWITH_DEBUG_SYMBOLS " + CXXFLAGS="${CXXFLAGS} -g -O0 -DDEBUG -DWITH_DEBUG_SYMBOLS " FCFLAGS="${FCFLAGS} -g -O0" OBJCFLAGS="${OBJCFLAGS} -g -O0" ], [info],[ AC_MSG_RESULT(info) - CFLAGS="${CFLAGS} -g $5" - CXXFLAGS="${CXXFLAGS} -g $5" + CFLAGS="${CFLAGS} -g -DWITH_DEBUG_SYMBOLS $5" + CXXFLAGS="${CXXFLAGS} -g -DWITH_DEBUG_SYMBOLS $5" FCFLAGS="${FCFLAGS} -g $5" OBJCFLAGS="${OBJCFLAGS} -g $5" ], [profile],[ AC_MSG_RESULT(profile) - CFLAGS="${CFLAGS} -g -pg $5" - CXXFLAGS="${CXXFLAGS} -g -pg $5" + CFLAGS="${CFLAGS} -g -pg -DWITH_DEBUG_SYMBOLS $5" + CXXFLAGS="${CXXFLAGS} -g -pg -DWITH_DEBUG_SYMBOLS $5" FCFLAGS="${FCFLAGS} -g -pg $5" OBJCFLAGS="${OBJCFLAGS} -g -pg $5" LDFLAGS="${LDFLAGS} -pg $5" diff --git a/m4/m4_ax_mdsplus_testing.m4 b/m4/m4_ax_mdsplus_testing.m4 index 8fce5b5b0b..cbee727002 100644 --- a/m4/m4_ax_mdsplus_testing.m4 +++ b/m4/m4_ax_mdsplus_testing.m4 @@ -96,7 +96,7 @@ AC_DEFUN([TS_WINE_ENV],[ dnl # launch boot in wine bottle (creating new one if it does not exist) AS_VAR_SET_IF([HAVE_WINEBOOT],,[AC_CHECK_PROG(HAVE_WINEBOOT,wineboot,yes,no)]) - AS_VAR_IF([HAVE_WINEBOOT],[yes], + AS_VAR_IF([HAVE_WINEBOOT],[yes], [# Creating bottle using wineboot # WINEDLLOVERRIDES prevents asking to install mono and geko here AS_IF([test -d ${$1}], @@ -239,11 +239,11 @@ AC_DEFUN([TS_SELECT],[ AS_VAR_APPEND([TESTS_ENVIRONMENT],"MDS_PYDEVICE_PATH='\$(abs_top_srcdir)/pydevices;\$(abs_top_srcdir)/python/MDSplus/tests/devices' ") AS_VAR_APPEND([TESTS_ENVIRONMENT],"main_path='.;\$(abs_top_srcdir)/trees' ") AS_VAR_APPEND([TESTS_ENVIRONMENT],"subtree_path='.;\$(abs_top_srcdir)/trees/subtree' ") - AS_VAR_APPEND([TESTS_ENVIRONMENT],"${LIBPATH}=${MAKESHLIBDIR}\$(if \${${LIBPATH}},:\${${LIBPATH}}) ") - AS_VAR_APPEND([TESTS_ENVIRONMENT],"PYTHONPATH=\$(abs_top_srcdir)/python\$(if \${PYTHONPATH},:\${PYTHONPATH}) PYTHONDONTWRITEBYTECODE=yes ") - AS_VAR_APPEND([TESTS_ENVIRONMENT],"PyLib=${PyLib:-$DEF_PYLIB} ") - AS_VAR_APPEND([TESTS_ENVIRONMENT],"PYTHON=$PYTHON ") - AS_VAR_APPEND([PY_LOG_COMPILER], ["${PYTHON} -B \$(top_srcdir)/testing/testing.py"]) + AS_VAR_APPEND([TESTS_ENVIRONMENT],"${LIBPATH}=${MAKESHLIBDIR}\${${LIBPATH}:+:\${${LIBPATH}}} ") + AS_VAR_APPEND([TESTS_ENVIRONMENT],"PYTHONPATH=\$(abs_top_srcdir)/python\${PYTHONPATH:+:\${PYTHONPATH}} PYTHONDONTWRITEBYTECODE=yes ") + AS_VAR_APPEND([TESTS_ENVIRONMENT],"PyLib=\${PYLIB} ") + AS_VAR_APPEND([TESTS_ENVIRONMENT],"PYTHON=\${PYTHON} ") + AS_VAR_APPEND([PY_LOG_COMPILER], ["\${PYTHON} -B \$(top_srcdir)/testing/testing.py"]) ], # # OTHER @@ -316,4 +316,3 @@ dnl tr.run(tests); dnl #prova: dnl # echo $(TEST_LOGS); dnl # python -c "${_tap_py_execute}" pyex1; - diff --git a/m4/m4_ax_valgrind_check.m4 b/m4/m4_ax_valgrind_check.m4 index d0002cd8b1..8507706e3f 100644 --- a/m4/m4_ax_valgrind_check.m4 +++ b/m4/m4_ax_valgrind_check.m4 @@ -169,7 +169,8 @@ VALGRIND_FLAGS ?= VALGRIND_FLAGS += --gen-suppressions=all \ --num-callers=64 \ --trace-children=yes \ - --child-silent-after-fork=yes + --child-silent-after-fork=yes \ + --trace-children-skip-by-arg='*SetMdsplusFileProtection*' VALGRIND_memcheck_FLAGS ?= VALGRIND_memcheck_FLAGS += --leak-check=full --show-reachable=no diff --git a/math/umach.f b/math/umach.f index c430dc7e3d..94c1d06737 100644 --- a/math/umach.f +++ b/math/umach.f @@ -8,19 +8,19 @@ Integer Function IMACH(i) Integer mach(12) Data mach / 1 32, !bits per integer storage unit - 2 4, !characters per integer - 3 2, !integer base + 2 4, !characters per integer + 3 2, !integer base 4 31, !integer digits - 5 0 , !largest integer - 6 2, !single base + 5 0, !largest integer + 6 2, !single base 7 24, !single digits - 8 -127, !smallest single exp - 9 127, !largest single exp + 8 -127, !smallest single exp + 9 127, !largest single exp 1 56, !double digits - 1 -127, !smallest double exp - 2 127/ !largest double exp + 1 -127, !smallest double exp + 2 127/ !largest double exp If (i.gt.0.and.i.le.12) Then - mach(5)=int('7fffffff'x) + mach(5)=int(x7fffffff) IMACH = mach(i) Else IMACH = 0 @@ -33,24 +33,15 @@ Real Function AMACH(i) Real xmach(8) Integer mach(8) Equivalence (xmach,mach) -c Data mach -c 1/'00000080'x, !smallest number -c 2 'fffe7fff'x, !largest number -c 3 '00003480'x, !base**(-number_of_digits) -c 4 '00003500'x, !base**(1-number_of_digits) -c 5 0, !log10(base) -c 6 'ffff7fff'x, !not-a-number -c 7 'fffe7fff'x, !positive infinity -c 8 'fffeffff'x/ !negative infinity If (i.gt.0.and.i.le.8) Then - mach(1)=int('00000080'x) !smallest number - mach(2)=int('fffe7fff'x) !largest number - mach(3)=int('00003480'x) !base**(-number_of_digits) - mach(4)=int('00003500'x) !base**(1-number_of_digits) + mach(1)=int(x00000080) !smallest number + mach(2)=int(xfffe7fff) !largest number + mach(3)=int(x00003480) !base**(-number_of_digits) + mach(4)=int(x00003500) !base**(1-number_of_digits) mach(5)=0 !log10(base) - mach(6)=int('ffff7fff'x) !not-a-number - mach(7)=int('fffe7fff'x) !positive infinity - mach(8)=int('fffeffff'x) !negative infinity + mach(6)=int(xffff7fff) !not-a-number + mach(7)=int(xfffe7fff) !positive infinity + mach(8)=int(xfffeffff) !negative infinity If (i.eq.5.and.mach(5).eq.0) xmach(5) = alog10(2.0e0) AMACH = real(xmach(i)) Else @@ -65,31 +56,31 @@ Real(KIND=8) Function DMACH(i) Integer mach(2,8) Equivalence (xmach,mach) c Data mach/ -c 1'00000080'x,0, !smallest number -c 2 'ffff7fff'x,'fffeffff'x, !largest number -c 3 '00002480'x,0, !base**(-number_of_digits) -c 4 '00002500'x,0, !base**(1-number_of_digits) +c 1 x00000080,0, !smallest number +c 2 xffff7fff,xfffeffff, !largest number +c 3 x00002480,0, !base**(-number_of_digits) +c 4 x00002500,0, !base**(1-number_of_digits) c 5 0,0, !log10(base) -c 6 'ffff7fff'x,'ffffffff'x, !not-a-number or bigger than infinity -c 7 'ffff7fff'x,'fffeffff'x, !positive infinity -c 8 'ffffffff'x,'fffeffff'x/ !negative infinity +c 6 xffff7fff,xffffffff, !not-a-number or bigger than infinity +c 7 xffff7fff,xfffeffff, !positive infinity +c 8 xffffffff,xfffeffff/ !negative infinity If (i.gt.0.and.i.le.8) Then - mach(1,1)=int('00000080'x) !smallest number + mach(1,1)=int(x00000080) !smallest number mach(2,1)=0 - mach(1,2)=int('ffff7fff'x) - mach(2,2)=int('fffeffff'x) !largest number - mach(1,3)=int('00002480'x) + mach(1,2)=int(xffff7fff) + mach(2,2)=int(xfffeffff) !largest number + mach(1,3)=int(x00002480) mach(2,3)=0 !base**(-number_of_digits) - mach(1,4)=int('00002500'x) + mach(1,4)=int(x00002500) mach(2,4)=0 !base**(1-number_of_digits) mach(1,5)=0 mach(2,5)=0 !log10(base) - mach(1,6)=int('ffff7fff'x) - mach(2,6)=int('ffffffff'x) !not-a-number or bigger than infinity - mach(1,7)=int('ffff7fff'x) - mach(2,7)=int('fffeffff'x) !positive infinity - mach(1,8)=int('ffffffff'x) - mach(2,8)=int('fffeffff'x) !negative infinity + mach(1,6)=int(xffff7fff) + mach(2,6)=int(xffffffff) !not-a-number or bigger than infinity + mach(1,7)=int(xffff7fff) + mach(2,7)=int(xfffeffff) !positive infinity + mach(1,8)=int(xffffffff) + mach(2,8)=int(xfffeffff) !negative infinity If (i.eq.5.and.mach(1,5).eq.0) xmach(5) = dlog10(2.0d0) DMACH = Real(xmach(i)) diff --git a/mdsdcl/cmdExecute.c b/mdsdcl/cmdExecute.c index 0dde002128..7988a7d4a6 100644 --- a/mdsdcl/cmdExecute.c +++ b/mdsdcl/cmdExecute.c @@ -930,10 +930,10 @@ static int dispatchToHandler(char *image, dclCommandPtr cmd, if (cmdDef->image) image = cmdDef->image; status = LibFindImageSymbol_C(image, cmdDef->routine, &handler); - if (status & 1) + if (STATUS_OK) { status = handler(cmd, error, output, getline, getlineinfo); - if (!(status & 1)) + if (STATUS_NOT_OK) { if ((*error == 0) && (status != 0)) { @@ -1230,34 +1230,31 @@ static inline void mdsdcl_alloc_docdef(dclDocListPtr doc_l, } EXPORT int mdsdclAddCommands(const char *name_in, char **error) { - size_t i; - char *name = 0; char *commands; - char *commands_part; + char *tmp; xmlDocPtr doc; dclDocListPtr doc_l, doc_p; char *mdsplus_dir; char *filename = 0; int status = 0; - name = strdup(name_in); - - /* convert the name to lowercase. The table xml files should always be named - as tablename_commands.xml all lowercase. */ - - for (i = 0; i < strlen(name); i++) - name[i] = tolower(name[i]); - - /* see if the caller included the "_commands" suffix in the name and if not - add it */ - - commands_part = strstr(name, "_commands"); - if (commands_part && - ((name + strlen(name_in) - strlen("_commands")) == commands_part)) - commands_part[0] = '\0'; - commands = strcpy(malloc(strlen(name) + strlen("_commands") + 1), name); - strcat(commands, "_commands"); - free(name); - + commands = strdup(name_in); + // convert the name to lowercase + // NOTE: table xml filenames should match "[a-z]+_commands.xml" + for (tmp = commands; *tmp; tmp++) + *tmp = tolower(*tmp); + size_t cmd_len = tmp - commands; + // check if caller included "_commands" suffix, add it otherwise + tmp = strstr(commands, "_commands"); + if (!tmp || *(tmp + sizeof("_commands") - 1)) + { + // append '_commands' + char *newcmd = realloc(commands, cmd_len + sizeof("_commands")); + if (newcmd) + { + commands = newcmd; + memcpy(commands + cmd_len, "_commands", sizeof("_commands")); + } + } /* See if that command table has already been loaded in the private list. If it has, pop that table to the top of the stack and return */ DCLTHREADSTATIC_INIT; @@ -1456,7 +1453,7 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, status = processCommand(doc_l, matchingVerbs.nodes[0], cmd, cmdDef, &prompt, &error_tmp, &output_tmp, getline, getlineinfo); - if (status & 1) + if (STATUS_OK) { free(error); error = error_tmp; @@ -1521,7 +1518,7 @@ int cmdExecute(dclCommandPtr cmd, char **prompt_out, char **error_out, free(prompt); } } - if ((prompt == NULL) && (error == 0) && (!(status & 1))) + if ((prompt == NULL) && (error == 0) && (STATUS_NOT_OK)) { if (status == MdsdclIVVERB && error == NULL) { diff --git a/mdsdcl/yylex/cmdParse.l b/mdsdcl/yylex/cmdParse.l index 5203d58639..5d04e3a684 100644 --- a/mdsdcl/yylex/cmdParse.l +++ b/mdsdcl/yylex/cmdParse.l @@ -36,16 +36,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "dclyacc.h" //#define DEBUG -#ifdef DEBUG -# define DBG(...) do{\ -fprintf(stderr, "cmdParse: ");\ -fprintf(stderr, __VA_ARGS__);\ -fprintf(stderr, "\n");\ -}while(0) //" -#else -# define DBG(...) -#endif -#define DBGM(RETURN,prefix) DBG("%-9s -> %-12s : '%s'", #RETURN, #prefix, yytext) +#include +#define DBGM(RETURN,prefix) MDSDBG("%-9s -> %-12s : '%s'", #RETURN, #prefix, yytext) %} %x start verb qualifier qualval qualval_list rest_of_line parameter @@ -137,7 +129,7 @@ qualval {unquoted_value_3}|{quoted_value} BEGIN parameter; } -<*>(EOL|\n) DBG("end parameter : 0x%02x",(int)yytext[0]);BEGIN parameter; +<*>(EOL|\n) MDSDBG("end parameter : 0x%02x",(int)yytext[0]);BEGIN parameter; {value} { DBGM(P_VALUE,verb); @@ -149,6 +141,6 @@ qualval {unquoted_value_3}|{quoted_value} return(P_VALUE); } -<*>. DBG("any * : 0x%02x",(int)yytext[0]); +<*>. MDSDBG("any * : 0x%02x",(int)yytext[0]); %% diff --git a/mdsdebug.c b/mdsdebug.c deleted file mode 100644 index 988f723d4e..0000000000 --- a/mdsdebug.c +++ /dev/null @@ -1,70 +0,0 @@ -/* - Dependencies: - stdio.h (for fprintf, sprintf) - mdslib.h (for MdsValue, descr) - */ - -#include -#include -/* #define status_ok(status) (((status) & 1) == 1) */ - -/* - status_ok - - Description: - Returns 1 if OK, 0 otherwise. Status is OK if the - LSB is set. - - Dependencies: - none. -*/ -int status_ok(int status) { return ((status & 1) == 1); } - -int main(int argc, char *argv[]) -{ - int status; - int shot = 3; - - int dtype_long = DTYPE_LONG; - int dtype_cstring = DTYPE_CSTRING; - int tstat, len, null = 0; - int bufsize = 1024; - char buf[1024]; - int idesc = descr(&dtype_long, &tstat, &null); - int sdesc = descr(&dtype_cstring, buf, &null, &bufsize); - - /* Open tree */ - status = MdsOpen("cryocon18i", &shot); - if (!status_ok(status)) - { - printf("Error shot number %d\n", shot); - fprintf(stderr, "Error shot number %d\n", shot); - return -1; - } - printf("Status: Tree opened %d\n", status); - - puts("Demonstrating use of TCL() function."); - /* status = MdsValue("TCL(\"set def cryo18i\",_output)", &idesc, &null, &len); - */ - status = MdsValue("TCL(\"set def cryo18i\",_output)", &idesc, &null, &len); - if (!status_ok(status)) - { - printf("Error with set def command.\n"); - fprintf(stderr, "Error with set def command.\n"); - return -1; - } - printf("Status of TCL(\"set def\") = %i\n", tstat); - - /* If the command was successful, print its output. */ - if (status_ok(tstat)) - { - status = MdsValue("_output", &sdesc, &null, &len); - if (!status_ok(status)) - { - fprintf(stderr, "Error getting _output from set def command.\n"); - return -1; - } - printf("Output of TCL(\"set def\") = %s\n", buf); - } - return 0; -} diff --git a/mdsdebugc.c b/mdsdebugc.c deleted file mode 100644 index 61edbd28fb..0000000000 --- a/mdsdebugc.c +++ /dev/null @@ -1,68 +0,0 @@ -/* - Dependencies: - stdio.h (for fprintf, sprintf) - mdslib.h (for MdsValue, descr) - */ - -#include "treeshr/treeshrp.h" -#include -#include -#include -/* #define status_ok(status) (((status) & 1) == 1) */ - -/* - status_ok - - Description: - Returns 1 if OK, 0 otherwise. Status is OK if the - LSB is set. - - Dependencies: - none. -*/ -int status_ok(int status) { return ((status & 1) == 1); } - -int main(int argc, char *argv[]) -{ - int status; - int shot = 3; - /*char const tree="cryocon18i"; - char path = 'cryo18i';*/ - int read_only = 1; - - void *dbid; - int nidout = 0; - int startnid = 0; - // NID * nid_out = 0; - // struct context *ctx = NULL; - - status = _TreeOpen(&dbid, "cryocon18i", shot, read_only); - /*status = _TreeOpen(TreeCtx(), "cryocon18i", shot, read_only);*/ - if (!status_ok(status)) - { - printf("Error shot number %d\n", shot); - fprintf(stderr, "Error shot number %d\n", shot); - return -1; - } - // PINO_DATABASE *dblist = (PINO_DATABASE *) dbid; - - // struct context { - // char *expt; - // int shot; - // int defnid; - // }; - // if (IS_OPEN(dblist)) { - // ctx = malloc(sizeof(struct context)); - // ctx->expt = strcpy(malloc(strlen(dblist->experiment) + 1), - // dblist->experiment); ctx->shot = dblist->shotid; - // } - - _TreeGetDefaultNid(dbid, &nidout); - startnid = nidout; - int usage_mask = 0xFFFF; - void *ctx = NULL; - // _TreeFindNode(dbid, "cryocon18i::top:cryo18i", &nidout); - _TreeFindNodeWild(dbid, "cryocon18i::top:cryo18i", &nidout, &ctx, usage_mask); - - return 0; -} diff --git a/mdslib/MdsLib.c b/mdslib/MdsLib.c index 974258e3a9..ede325185c 100644 --- a/mdslib/MdsLib.c +++ b/mdslib/MdsLib.c @@ -498,7 +498,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, /* send each argument */ va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= nargs && (status & 1); i++) + for (i = 1; i <= nargs && (STATUS_OK); i++) { descnum = va_arg(incrmtr, int *); if (*descnum > 0) @@ -515,7 +515,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, } } - if (status & 1) + if (STATUS_OK) { int numbytes; short len; @@ -533,7 +533,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, ** present for client-only library. **/ - if (status & 1) + if (STATUS_OK) { int ansdescr = 0; int dims[MAX_DIMS]; @@ -597,7 +597,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, status = 0; break; } - if (status & 1) + if (STATUS_OK) mds_value_set(dscAnswer, GetDescriptorCache()[ansdescr - 1], length); } free(dnew); @@ -634,7 +634,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, *(int *)&arglist[0] = argidx - 1; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) + if (STATUS_OK) { descnum = va_arg(incrmtr, int *); @@ -642,7 +642,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, status = TdiData(xd1.pointer, &xd2 MDS_END_ARG); - if (status & 1 && xd2.pointer != 0 && xd2.pointer->pointer != 0) + if (STATUS_OK && xd2.pointer != 0 && xd2.pointer->pointer != 0) { int templen = (xd2.pointer)->length; status = TdiCvt(&xd2, dsc, &xd3 MDS_END_ARG); @@ -657,7 +657,7 @@ static inline int mds_value_vargs(va_list incrmtr, int connection, (xd3.pointer)->length = MIN(templen, (xd3.pointer)->length); } - if (status & 1) + if (STATUS_OK) { mds_value_set(dsc, xd3.pointer, length); @@ -750,7 +750,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, /* send each argument */ va_copy(incrmtr, initial_incrmtr); - for (i = 1; i <= nargs && (status & 1); i++) + for (i = 1; i <= nargs && (STATUS_OK); i++) { descnum = va_arg(incrmtr, int *); if (*descnum > 0) @@ -768,7 +768,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, } } - if (status & 1) + if (STATUS_OK) { int numbytes; short len; @@ -786,7 +786,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, ** present for client-only library. **/ - if (status & 1) + if (STATUS_OK) { int ansdescr = 0; int dims[MAX_DIMS]; @@ -850,7 +850,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, status = 0; break; } - if (status & 1) + if (STATUS_OK) mds_value_set(dscAnswer, GetDescriptorCache()[ansdescr - 1], length); } free(dnew); @@ -888,7 +888,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, *(int *)&arglist[0] = argidx - 1; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) + if (STATUS_OK) { descnum = va_arg(incrmtr, int *); @@ -897,7 +897,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, status = TdiData(xd1.pointer, &xd2 MDS_END_ARG); - if (status & 1 && xd2.pointer) + if (STATUS_OK && xd2.pointer) { int templen = (xd2.pointer)->length; status = TdiCvt(&xd2, dsc, &xd3 MDS_END_ARG); @@ -912,7 +912,7 @@ static inline int mds_value2_vargs(va_list incrmtr, int connection, (xd3.pointer)->length = MIN(templen, (xd3.pointer)->length); } - if (status & 1) + if (STATUS_OK) { mds_value_set(dsc, xd3.pointer, length); @@ -986,7 +986,7 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, status = SendArg(connection, idx++, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); arg = MakeDescrip(&exparg, DTYPE_CSTRING, 0, 0, expression); - for (i = idx; i < nargs && (status & 1); i++) + for (i = idx; i < nargs && (STATUS_OK); i++) { status = SendArg(connection, (char)i, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); @@ -998,7 +998,7 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, } } - if (status & 1) + if (STATUS_OK) { char dtype; int dims[MAX_DIMS]; @@ -1008,7 +1008,7 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, void *dptr; status = GetAnswerInfo(connection, &dtype, &len, &ndims, dims, &numbytes, &dptr); - if (status & 1 && dtype == DTYPE_LONG && ndims == 0 && + if (STATUS_OK && dtype == DTYPE_LONG && ndims == 0 && numbytes == sizeof(int)) memcpy(&status, dptr, numbytes); } @@ -1048,7 +1048,7 @@ static inline int mds_put_vargs(va_list incrmtr, int connection, char *pathname, status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) + if (STATUS_OK) { if ((status = TreePutRecord( nid, (struct descriptor *)arglist[argidx - 2], 0)) & @@ -1125,7 +1125,7 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, status = SendArg(connection, idx++, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); arg = MakeDescrip(&exparg, DTYPE_CSTRING, 0, 0, expression); - for (i = idx; i < nargs && (status & 1); i++) + for (i = idx; i < nargs && (STATUS_OK); i++) { status = SendArg(connection, (char)i, arg->dtype, nargs, ArgLen(arg), arg->ndims, arg->dims, arg->ptr); @@ -1138,7 +1138,7 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, } } - if (status & 1) + if (STATUS_OK) { char dtype; int dims[MAX_DIMS]; @@ -1148,7 +1148,7 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, void *dptr; status = GetAnswerInfo(connection, &dtype, &len, &ndims, dims, &numbytes, &dptr); - if (status & 1 && dtype == DTYPE_LONG && ndims == 0 && + if (STATUS_OK && dtype == DTYPE_LONG && ndims == 0 && numbytes == sizeof(int)) memcpy(&status, dptr, numbytes); } @@ -1189,7 +1189,7 @@ static int mds_put2_vargs(va_list incrmtr, int connection, char *pathname, status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) + if (STATUS_OK) { if ((status = TreePutRecord(nid, (struct descriptor *)arglist[argidx - 2]), @@ -1615,7 +1615,7 @@ EXPORT int MdsOpenR(int *connection, char *tree, int *shot) d3 = descr(&dtype_long, &answer, &null); status = MdsValueR(connection, expression, &d1, &d2, &d3, &null, &length); - if ((status & 1)) + if ((STATUS_OK)) { return *(int *)&answer; } @@ -1670,7 +1670,7 @@ extern EXPORT int MdsCloseR(int *connection, char *tree, int *shot) status = MdsValueR(connection, expression, &d1, &d2, &d3, &null, &length); - if ((status & 1)) + if ((STATUS_OK)) { return *(int *)&answer; } @@ -1715,7 +1715,7 @@ EXPORT int MdsSetDefaultR(int *connection, char *node) strcat(expression, "')"); status = MdsValueR(connection, expression, &d1, &null, &length); free(expression); - if ((status & 1)) + if ((STATUS_OK)) { return *(int *)&answer; } diff --git a/mdslib/testing/dtype_test.c b/mdslib/testing/dtype_test.c index e82427c0b9..e585c76b36 100644 --- a/mdslib/testing/dtype_test.c +++ b/mdslib/testing/dtype_test.c @@ -23,6 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mdslib.h" +#include #include #include @@ -91,82 +92,82 @@ int main(int argc __attribute__((unused)), dsc = descr(&dtype_uchar, &vUChar, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vUChar == UCHAR_MAX - 1); dsc = descr(&dtype_ushort, &vUShort, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vUShort == USHRT_MAX - 1); dsc = descr(&dtype_ulong, &vULong, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vULong == UINT_MAX - 1); dsc = descr(&dtype_ulonglong, vULongLong, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); /* do the test right on big endian machines */ #if defined(_QUAD_HIGHWORD) && defined(_QUAD_LOWWORD) - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vULongLong[_QUAD_LOWWORD] == UINT_MAX - 1) && (vULongLong[_QUAD_HIGHWORD] == UINT_MAX)); #else - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vULongLong[0] == UINT_MAX - 1) && (vULongLong[1] == UINT_MAX)); #endif dsc = descr(&dtype_char, &vChar, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vChar == CHAR_MAX - 1); dsc = descr(&dtype_short, &vShort, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vShort == SHRT_MAX - 1); dsc = descr(&dtype_long, &vLong, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vLong == INT_MAX - 1); dsc = descr(&dtype_longlong, vLongLong, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); #if defined(_QUAD_HIGHWORD) && defined(_QUAD_LOWWORD) - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vLongLong[_QUAD_LOWWORD] == INT_MAX - 1) && (vLongLong[_QUAD_HIGHWORD] == INT_MAX)); #else - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vLongLong[0] == INT_MAX - 1) && (vLongLong[1] == INT_MAX)); #endif dsc = descr(&dtype_float, &vFloat, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vFloat - FLOAT_TEST + 1 < 1.e-7); dsc = descr(&dtype_double, &vDouble, &null); status = MdsValue("$-1", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(vDouble == DOUBLE_TEST - 1); dsc = descr(&dtype_complex, vComplex, &null); status = MdsValue("$-CMPLX(0,1)", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vComplex[0] == COMPLEX_TEST0) && (vComplex[1] == COMPLEX_TEST1 - 1)); dsc = descr(&dtype_complex_double, vComplexDouble, &null); status = MdsValue("$-CMPLX(0,1)", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1((vComplexDouble[0] == COMPLEX_DOUBLE_TEST0) && (vComplexDouble[1] == COMPLEX_DOUBLE_TEST1 - 1)); len = 14; dsc = descr(&dtype_cstring, vCstring, &null, &len); status = MdsValue("UPCASE($)", &dsc, &dsc, &null, &len); - TEST1(status & 1); + TEST1(STATUS_OK); TEST1(strcmp(vCstring, CSTRING_TEST1) == 0); END_TESTING; diff --git a/mdslib/testing/mdslib_ctest.c b/mdslib/testing/mdslib_ctest.c index 8a06ae1578..12d5637f31 100644 --- a/mdslib/testing/mdslib_ctest.c +++ b/mdslib/testing/mdslib_ctest.c @@ -23,10 +23,12 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include +#include #include + #include #include -#include +#include #define BUFFLEN 10 int status; @@ -71,7 +73,7 @@ int testScalarString(char *expression, char *expected) int dsc = descr(&dtype_cstring, string, &null, &lenalloc); returnlength = 0; status = MdsValue(expression, &dsc, &null, &returnlength); - if (status & 1) + if (STATUS_OK) { fprintf(stderr, "testScalarString(%.*s -- %s %d)\n", returnlength, string, expected, returnlength); status = @@ -89,7 +91,7 @@ int testNull(char *expression) int bufflen = BUFFLEN; int dsc = descr(&dtype_cstring, buf, &null, &bufflen); status = MdsValue(expression, &dsc, &null, &returnlength); - return ((status & 1) == 0 && (returnlength == 0)); + return ((STATUS_OK) == 0 && (returnlength == 0)); } int testPut1Dsc(char *node, char *expression, int dsc) @@ -138,7 +140,7 @@ void TestTdi() dsc = descr(&dtype_float, result, &sresult, &null); status = MdsValue("2. : 20. : 2.", &dsc, &null, &returnlength); status = (status && (returnlength == 10)); - if (status & 1) + if (STATUS_OK) { for (i = 0; i < returnlength; i++) status = status && (result[i] == 2. * (i + 1)); @@ -150,7 +152,7 @@ void TestTdi() dsc = descr(&dtype_float, &result1, &null); status = MdsValue("$ * $", &dsc1, &dsc2, &dsc, &null, &returnlength); status = status && (returnlength == 1); - if (status & 1) + if (STATUS_OK) status = status && (sqrt(result1 * result1) - (arg1 * arg2) < 1.e-7); TEST(status); @@ -175,10 +177,10 @@ void TestArray1D() dsc = descr(&dtype_float, compare, &size, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) + if (STATUS_OK) { status = (returnlength == size); - if (status & 1) + if (STATUS_OK) { int i; for (i = 0; i < size; i++) @@ -226,10 +228,10 @@ void TestArray2D() dsc = descr(&dtype_float, compare, &sx, &sy, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) + if (STATUS_OK) { status = (returnlength == sx * sy); - if (status & 1) + if (STATUS_OK) { int i; for (i = 0; i < sx; i++) @@ -245,10 +247,10 @@ void TestArray2D() TEST(status); dsc = descr(&dtype_float, compareBigger, &sxx, &syy, &null); status = MdsValue("\\TOP:A", &dsc, &null, &returnlength); - if (status & 1) + if (STATUS_OK) { status = (returnlength == sx * sy); - if (status & 1) + if (STATUS_OK) { int i; for (i = 0; i < sx; i++) diff --git a/mdslibidl/MdsLibIdl.c b/mdslibidl/MdsLibIdl.c index a4f830962b..0bc04c3171 100644 --- a/mdslibidl/MdsLibIdl.c +++ b/mdslibidl/MdsLibIdl.c @@ -381,11 +381,11 @@ EXPORT int IdlMdsValue(int argc, void **argv) arglist[argidx++] = MdsEND_ARG; *(long *)&arglist[0] = argidx; status = (int)(intptr_t)LibCallg(arglist, TdiExecute); - if (status & 1) + if (STATUS_OK) { status = TdiData(tmp.pointer, &mdsValueAnswer MDS_END_ARG); MdsFree1Dx(&tmp, NULL); - if (status & 1) + if (STATUS_OK) { if (mdsValueAnswer.pointer->dtype == DTYPE_F || mdsValueAnswer.pointer->dtype == DTYPE_FS) @@ -613,7 +613,7 @@ EXPORT int IdlMdsPut(int argc, void **argv) memset(arglist, 0, arglistlen * sizeof(void *)); BlockSig(SIGALRM); status = TreeFindNode((char *)argv[0], &nid); - if (status & 1) + if (STATUS_OK) { expression.length = strlen((char *)argv[1]); expression.pointer = (char *)argv[1]; @@ -627,7 +627,7 @@ EXPORT int IdlMdsPut(int argc, void **argv) arglist[argidx++] = MdsEND_ARG; *(int *)&arglist[0] = argidx; status = (int)(intptr_t)LibCallg(arglist, TdiCompile); - if (status & 1) + if (STATUS_OK) { status = TreePutRecord(nid, (struct descriptor *)&tmp, 0); MdsFree1Dx(&tmp, NULL); diff --git a/mdsmisc/ScopeUtilities.c b/mdsmisc/ScopeUtilities.c index 42bd0c85b9..74354fc9e4 100644 --- a/mdsmisc/ScopeUtilities.c +++ b/mdsmisc/ScopeUtilities.c @@ -90,10 +90,7 @@ static double to_doublex(const void *const ptr, const dtype_t dtype, return defval; } } -inline static double to_double(const void *const ptr, const dtype_t dtype) -{ - return to_doublex(ptr, dtype, 0, FALSE); -} + static int recIsSegmented(const mdsdsc_t *const dsc) { /* returns nid of the first segmented node found diff --git a/mdsmisc/getreferences.c b/mdsmisc/getreferences.c index f9903b4308..ba9ba19fba 100644 --- a/mdsmisc/getreferences.c +++ b/mdsmisc/getreferences.c @@ -37,7 +37,7 @@ EXPORT int GetReferenceCount(int *nid) { int cnt = 0; int status = TreeGetRecord(*nid, &src); - if (status & 1) + if (STATUS_OK) { cnt = CountRefs((struct descriptor *)&src); } @@ -118,7 +118,7 @@ static int GetNid(struct descriptor *dsc) tmp[dsc->length] = 0; status = TreeFindNode(tmp, &ans); free(tmp); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) return -1; else return ans; diff --git a/mdsobjects/cpp/mdsdata.c b/mdsobjects/cpp/mdsdata.c index 92287811d8..0c34b1996c 100644 --- a/mdsobjects/cpp/mdsdata.c +++ b/mdsobjects/cpp/mdsdata.c @@ -84,7 +84,7 @@ void *convertToScalarDsc(int clazz, int dtype, int length, char *ptr) dsc.length = length; dsc.pointer = ptr; status = MdsCopyDxXd(&dsc, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("PANIC in convertToScalarDsc: MdsCopyDxXd failed\n"); exit(0); @@ -107,7 +107,7 @@ void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, { arr1Dsc.class = clazz; status = MdsCopyDxXd((struct descriptor *)&arr1Dsc, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("PANIC in convertToArrayDsc: MdsCopyDxXd failed: %s\n", MdsGetMsg(status)); @@ -121,7 +121,7 @@ void *convertToArrayDsc(int clazz, int dtype, int length, int arsize, int nDims, arrNDsc.pointer = ptr; status = MdsCopyDxXd((struct descriptor *)&arrNDsc, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("PANIC in convertToArrayDsc: MdsCopyDxXd failed\n"); exit(0); @@ -157,7 +157,7 @@ void *convertToCompoundDsc(int clazz __attribute__((unused)), int dtype, recDsc.dscptrs[i] = 0; } status = MdsCopyDxXd((struct descriptor *)&recDsc, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("PANIC in convertToCompoundDsc: MdsCopyDxXd failed\n"); exit(0); @@ -197,7 +197,7 @@ void *convertToApdDsc(int type, int ndescs, void **descs) ((struct descriptor **)apdDsc.pointer)[i] = 0; } status = MdsCopyDxXd((struct descriptor *)&apdDsc, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("PANIC in convertToApdDsc: MdsCopyDxXd failed\n"); exit(0); @@ -236,7 +236,7 @@ void *evaluateData(void *dscPtr, void *ctx, int isEvaluate, int *retStatus) status = TdiData((struct descriptor *)dscPtr, xdPtr MDS_END_ARG); } *retStatus = status; - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; return (void *)xdPtr; } @@ -305,7 +305,7 @@ void *convertFromDsc(void *ptr, void *tree) tree); case CLASS_CA: status = TdiData(dscPtr, &caXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Cannot evaluate CA descriptor\n"); return NULL; @@ -443,7 +443,7 @@ char *decompileDsc(void *ptr, void *ctx) status = _TdiDecompile(&ctx, dscPtr, &xd MDS_END_ARG); else status = TdiDecompile(dscPtr, &xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Error decompiling expression: %s\n", MdsGetMsg(status)); return NULL; @@ -503,7 +503,7 @@ void *compileFromExprWithArgs(char *expr, int nArgs, void **args, void *tree, { status = *retStatus = (int)(intptr_t)LibCallg(arglist, TdiCompile); } - if (!(status & 1)) + if (STATUS_NOT_OK) return NULL; data = convertFromDsc(&xd, tree); @@ -526,7 +526,7 @@ void *convertToByte(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -546,7 +546,7 @@ void *convertToByteUnsigned(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -566,7 +566,7 @@ void *convertToShort(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -586,7 +586,7 @@ void *convertToShortUnsigned(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -606,7 +606,7 @@ void *convertToInt(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -626,7 +626,7 @@ void *convertToIntUnsigned(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -646,7 +646,7 @@ void *convertToLong(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -666,7 +666,7 @@ void *convertToLongUnsigned(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -687,7 +687,7 @@ void *convertToFloat(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -708,7 +708,7 @@ void *convertToDouble(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -728,7 +728,7 @@ void *convertToShape(void *dsc) *xdPtr = emptyXd; funD.arguments[0] = dsc; status = TdiData((struct descriptor *)&funD, xdPtr MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { free(xdPtr); return 0; @@ -819,7 +819,7 @@ char *serializeData(void *dsc, int *retSize, void **retDsc) *xdPtr = emptyXd; status = MdsSerializeDscOut(dscIn, xdPtr); - if (!(status & 1) || !xdPtr->pointer) + if (STATUS_NOT_OK || !xdPtr->pointer) { free(xdPtr); return 0; @@ -844,7 +844,7 @@ void *deserializeData(char const *serialized) xdPtr = (struct descriptor_xd *)malloc(sizeof(struct descriptor_xd)); *xdPtr = emptyXd; status = MdsSerializeDscIn(serialized, xdPtr); - if (!(status & 1)) + if (STATUS_NOT_OK) return 0; return xdPtr; } @@ -897,7 +897,7 @@ void convertToIEEEFloatArray(int dtype, int length, int nDims, int *dims, outArrD.dtype = DTYPE_DOUBLE; status = TdiConvert((struct descriptor_a *)&inArrD, (struct descriptor_a *)&outArrD); - if (!(status & 1)) + if (STATUS_NOT_OK) printf("Internal Error: cannot issue TdiConvert\n"); // copy back results memcpy(ptr, outArrD.pointer, arsize); diff --git a/mdsobjects/cpp/mdsdataobjects.cpp b/mdsobjects/cpp/mdsdataobjects.cpp index c67337534d..fb58bf6d22 100644 --- a/mdsobjects/cpp/mdsdataobjects.cpp +++ b/mdsobjects/cpp/mdsdataobjects.cpp @@ -844,7 +844,7 @@ Data *MDSplus::compileWithArgs(const char *expr, int nArgs...) &status); } - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return res; } @@ -883,7 +883,7 @@ Data *MDSplus::compileWithArgs(const char *expr, Tree *tree, int nArgs...) expr, nArgs, (void *)args, tree, (tree) ? tree->getCtx() : NULL, &status); for (i = 0; i < nArgs; i++) freeDsc(args[i]); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return res; } @@ -915,7 +915,7 @@ Data *MDSplus::executeWithArgs(const char *expr, int nArgs...) Data *compData = (Data *)compileFromExprWithArgs( expr, nArgs, (void *)args, actTree, (actTree) ? actTree->getCtx() : NULL, &status); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); Data *evalData = compData->data(); deleteData(compData); @@ -947,7 +947,7 @@ Data *MDSplus::executeWithArgs(const char *expr, Tree *tree, int nArgs...) Data *compData = (Data *)compileFromExprWithArgs((char *)expr, nArgs, (void *)args, tree, (tree) ? tree->getCtx() : NULL, &status); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); if (!compData) throw MdsException("Cannot compile expression"); diff --git a/mdsobjects/cpp/mdsipobjects.cpp b/mdsobjects/cpp/mdsipobjects.cpp index ab349e8038..e5b86642b8 100644 --- a/mdsobjects/cpp/mdsipobjects.cpp +++ b/mdsobjects/cpp/mdsipobjects.cpp @@ -328,14 +328,14 @@ void Connection::openTree(char *tree, int shot) { int status = MdsOpen(sockId, tree, shot); // std::cout << "SOCK ID: " << sockId << std::endl; - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void Connection::closeAllTrees() { int status = MdsClose(sockId); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -363,7 +363,7 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) // lockGlobal(); status = SendArg(sockId, 0, DTYPE_CSTRING_IP, nArgs + 1, std::string(expr).size(), 0, 0, (char *)expr); - if (!(status & 1)) + if (STATUS_NOT_OK) { unlockLocal(); throw MdsException(status); @@ -375,7 +375,7 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) status = SendArg(sockId, argIdx + 1, convertType(dtype), nArgs + 1, length, nDims, dims, (char *)ptr); delete[] dims; - if (!(status & 1)) + if (STATUS_NOT_OK) { unlockLocal(); throw MdsException(status); @@ -385,7 +385,7 @@ Data *Connection::get(const char *expr, Data **args, int nArgs) status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, retDims, &numBytes, &ptr, &mem); unlockLocal(); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } @@ -514,7 +514,7 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) status = SendArg(sockId, 0, DTYPE_CSTRING_IP, nArgs + 1, putExpr.length(), 0, 0, const_cast(putExpr.c_str())); - if (!(status & 1)) + if (STATUS_NOT_OK) { unlockLocal(); throw MdsException(status); @@ -525,7 +525,7 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) args[argIdx]->getInfo(&clazz, &dtype, &length, &nDims, &dims, &ptr); status = SendArg(sockId, argIdx + 1, convertType(dtype), nArgs + 1, length, nDims, dims, (char *)ptr); - if (!(status & 1)) + if (STATUS_NOT_OK) { unlockLocal(); throw MdsException(status); @@ -539,19 +539,19 @@ void Connection::put(const char *inPath, char *expr, Data **args, int nArgs) status = GetAnswerInfoTS(sockId, &dtype, &length, &nDims, retDims, &numBytes, &ptr, &mem); unlockLocal(); - if ((status & 1) && dtype == DTYPE_LONG_IP && nDims == 0 && + if ((STATUS_OK) && dtype == DTYPE_LONG_IP && nDims == 0 && numBytes == sizeof(int)) status = *(reinterpret_cast(ptr)); if (mem) FreeMessage(mem); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void Connection::setDefault(char *path) { int status = MdsSetDefault(sockId, path); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } diff --git a/mdsobjects/cpp/mdsobjects.c b/mdsobjects/cpp/mdsobjects.c index 698a69f1f2..c41ade7fae 100644 --- a/mdsobjects/cpp/mdsobjects.c +++ b/mdsobjects/cpp/mdsobjects.c @@ -73,7 +73,7 @@ static void printDecompiled(struct descriptor *inD) char *buf; status = TdiDecompile(inD, &out_xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("%s\n", MdsGetMsg(status)); return; @@ -262,7 +262,7 @@ static jobject DescripToObject(JNIEnv *env, struct descriptor *desc) } case CLASS_CA: status = TdiData(desc, &ca_xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Cannot evaluate CA descriptor\n"); return NULL; @@ -936,7 +936,7 @@ JNIEXPORT jstring JNICALL Java_mdsdata_Data_decompile(JNIEnv *env, struct descriptor *data_d = ObjectToDescrip(env, obj); status = TdiDecompile(data_d, &out_xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Error decompiling expression: %s\n", MdsGetMsg(status)); return NULL; @@ -1014,7 +1014,7 @@ JNIEXPORT jobject JNICALL Java_mdsdata_Data_evaluate(JNIEnv *env, jobject obj) jclass exc; status = TdiData(dataD, &xd MDS_END_ARG); - if (!(status & 1) || !xd.pointer) + if (STATUS_NOT_OK || !xd.pointer) { exc = (*env)->FindClass(env, "mdsdata/DataException"); (*env)->ThrowNew(env, exc, MdsGetMsg(status)); @@ -1066,7 +1066,7 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getFullPath(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1088,7 +1088,7 @@ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getData(JNIEnv *env, jclass cls, jobject retObj; status = TreeGetRecord(nid, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1111,7 +1111,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_deleteData(JNIEnv *env, jclass cls, int status; status = TreePutRecord(nid, (struct descriptor *)&xd, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); } @@ -1129,7 +1129,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putData(JNIEnv *env, jclass cls, struct descriptor *dataD = ObjectToDescrip(env, jData); status = TreePutRecord(nid, dataD, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); } @@ -1145,7 +1145,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOn(JNIEnv *env, jclass cls, jint nid) { int status = TreeTurnOn(nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); } @@ -1160,7 +1160,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_turnOff(JNIEnv *env, jclass cls, jint nid) { int status = TreeTurnOff(nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); } @@ -1175,7 +1175,7 @@ JNIEXPORT jboolean JNICALL Java_mdstree_MdsTree_isOn(JNIEnv *env, jclass cls, jint nid) { int status = TreeIsOn(nid); - return (status & 1); + return (STATUS_OK); } static void convertTime(int *time, char *retTime) @@ -1206,7 +1206,7 @@ JNIEXPORT jstring JNICALL Java_mdstree_MdsTree_getInsertionDate(JNIEnv *env, struct nci_itm nciList[] = {{8, NciTIME_INSERTED, timeInserted, &timeLen}, {NciEND_OF_LIST, 0, 0, 0}}; int status = TreeGetNci(nid, nciList); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); convertTime(timeInserted, ascTim); @@ -1228,7 +1228,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_open(JNIEnv *env, jclass cls, char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeOpen(experiment, shot, 0); (*env)->ReleaseStringUTFChars(env, jexperiment, experiment); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1245,7 +1245,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_close(JNIEnv *env, jclass cls, char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeClose(experiment, shot); (*env)->ReleaseStringUTFChars(env, jexperiment, experiment); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1262,7 +1262,7 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_find(JNIEnv *env, jclass cls, status = TreeFindNode(path, &nid); (*env)->ReleaseStringUTFChars(env, jpath, path); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); return nid; } @@ -1319,7 +1319,7 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getMembersOf(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list1); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1331,7 +1331,7 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getMembersOf(JNIEnv *env, nci_list2[0].buffer_length = sizeof(int) * numNids; nci_list2[0].pointer = nids; status = TreeGetNci(nid, nci_list2); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1362,7 +1362,7 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getChildrenOf(JNIEnv *env, {NciEND_OF_LIST, 0, 0, 0}}; status = TreeGetNci(nid, nci_list1); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1374,7 +1374,7 @@ JNIEXPORT jintArray JNICALL Java_mdstree_MdsTree_getChildrenOf(JNIEnv *env, nci_list2[0].buffer_length = sizeof(int) * numNids; nci_list2[0].pointer = nids; status = TreeGetNci(nid, nci_list2); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; @@ -1400,7 +1400,7 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getParent(JNIEnv *env, jclass cls, {NciEND_OF_LIST, 0, 0, 0}}; int status = TreeGetNci(nid, nciList); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); return parentNid; } @@ -1416,7 +1416,7 @@ JNIEXPORT jint JNICALL Java_mdstree_MdsTree_getDefault(JNIEnv *env, int defaultNid, status; status = TreeGetDefaultNid(&defaultNid); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); return defaultNid; } @@ -1430,7 +1430,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_setDefault(JNIEnv *env, jclass cls, jint nid) { int status = TreeSetDefaultNid(nid); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1457,7 +1457,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginSegment( freeDescrip(endD); freeDescrip(dimD); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1479,7 +1479,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putRow(JNIEnv *env, jclass cls, dataD = ObjectToDescrip(env, data); status = TreePutRow(nid, BUFSIZE, &time, (struct descriptor_a *)dataD); freeDescrip(dataD); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1504,7 +1504,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginCachedSegment( freeDescrip(startD); freeDescrip(endD); freeDescrip(dimD); - if (!(status & 1)) + if (STATUS_NOT_OK) { freeDescrip(dataD); RaiseException(env, MdsGetMsg(status), status); @@ -1512,7 +1512,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_beginCachedSegment( status = RTreePutSegment(nid, -1, (struct descriptor_a *)dataD, WRITE_BUFFER); freeDescrip(dataD); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1537,7 +1537,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedRow(JNIEnv *env, status = RTreePutRow(nid, BUFSIZE, &time, (struct descriptor_a *)dataD, (isLast) ? WRITE_LAST : WRITE_BUFFER); freeDescrip(dataD); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1554,7 +1554,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_openCached(JNIEnv *env, jclass cls, char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = RTreeOpen(experiment, shot); (*env)->ReleaseStringUTFChars(env, jexperiment, experiment); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1571,7 +1571,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_closeCached(JNIEnv *env, jclass cls, char *experiment = (char *)(*env)->GetStringUTFChars(env, jexperiment, 0); int status = TreeClose(experiment, shot); (*env)->ReleaseStringUTFChars(env, jexperiment, experiment); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1616,7 +1616,7 @@ JNIEXPORT void JNICALL Java_mdstree_MdsTree_putCachedData(JNIEnv *env, dataD = ObjectToDescrip(env, data); status = RTreePutRecord(nid, dataD, WRITE_BACK); freeDescrip(dataD); - if (!(status & 1)) + if (STATUS_NOT_OK) RaiseException(env, MdsGetMsg(status), status); } @@ -1634,7 +1634,7 @@ JNIEXPORT jobject JNICALL Java_mdstree_MdsTree_getCachedData(JNIEnv *env, jobject retObj; status = RTreeGetRecord(nid, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) { RaiseException(env, MdsGetMsg(status), status); return NULL; diff --git a/mdsobjects/cpp/mdstree.c b/mdsobjects/cpp/mdstree.c index 13dc2f56d8..625594a2dd 100644 --- a/mdsobjects/cpp/mdstree.c +++ b/mdsobjects/cpp/mdstree.c @@ -89,7 +89,7 @@ int getTreeData(void *dbid, int nid, void **data, void *tree) int status; status = _TreeGetRecord(dbid, nid, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *data = convertFromDsc(&xd, tree); @@ -327,7 +327,7 @@ int updateTreeSegment(void *dbid, int nid, int segIdx, void *startDsc, if (segIdx == -1) { status = _TreeGetNumSegments(dbid, nid, &numSegments); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; segmentIdx = numSegments - 1; } @@ -459,7 +459,7 @@ int getTreeXNci(void *dbid, int nid, const char *name, void **data, int status; status = _TreeGetXNci(dbid, nid, name, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *data = convertFromDsc(&xd, tree); MdsFree1Dx(&xd, 0); diff --git a/mdsobjects/cpp/mdstreeobjects.cpp b/mdsobjects/cpp/mdstreeobjects.cpp index 60f0bfab13..be43c782d3 100644 --- a/mdsobjects/cpp/mdstreeobjects.cpp +++ b/mdsobjects/cpp/mdstreeobjects.cpp @@ -167,7 +167,7 @@ Tree::Tree(char const *name, int shot) : name(name), shot(shot), ctx(nullptr), fromActiveTree(false) { int status = _TreeOpen(&ctx, name, shot, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); // setActiveTree(this); } @@ -199,7 +199,7 @@ Tree::Tree(char const *name, int shot, char const *mode) else throw MdsException("Invalid Open mode"); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -211,14 +211,14 @@ Tree::~Tree() { int status = _TreeQuitTree(&ctx, name.c_str(), shot); (void)status; - // if(!(status & 1)) + // if(STATUS_NOT_OK) // throw MdsException(status); } else { int status = _TreeClose(&ctx, name.c_str(), shot); (void)status; - // if(!(status & 1)) + // if(STATUS_NOT_OK) // throw MdsException(status); } TreeFreeDbid(ctx); @@ -236,21 +236,21 @@ void Tree::edit(const bool st) throw MdsException("Tree is read only"); int status = st ? _TreeOpenEdit(&ctx, name.c_str(), shot) : _TreeOpen(&ctx, name.c_str(), shot, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void Tree::write() { int status = _TreeWriteTree(&ctx, name.c_str(), shot); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } // void Tree::quit() //{ // int status = _TreeQuitTree(&ctx, name.c_str(), shot); -// if(!(status & 1)) +// if(STATUS_NOT_OK) // throw MdsException(status); //} @@ -353,7 +353,7 @@ TreeNode *Tree::addNode(char const *name, char const *usage) { int newNid; int status = _TreeAddNode(ctx, name, &newNid, convertUsage(usage)); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, this); } @@ -362,7 +362,7 @@ TreeNode *Tree::addDevice(char const *name, char const *type) { int newNid; int status = _TreeAddConglom(ctx, name, type, &newNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, this); } @@ -372,9 +372,9 @@ void Tree::remove(char const *name) int count; AutoPointer delNode(getNode(name)); int status = _TreeDeleteNodeInitialize(ctx, delNode.ptr->getNid(), &count, 1); - if (status & 1) + if (STATUS_OK) _TreeDeleteNodeExecute(ctx); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -383,7 +383,7 @@ TreeNode *Tree::getNode(char const *path) int nid; int status = _TreeFindNode(ctx, path, &nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } @@ -436,7 +436,7 @@ TreeNodeArray *Tree::getNodeWild(char const *path) void Tree::setDefault(TreeNode *treeNode) { int status = _TreeSetDefaultNid(ctx, treeNode->getNid()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -445,7 +445,7 @@ TreeNode *Tree::getDefault() int nid; int status = _TreeGetDefaultNid(ctx, &nid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(nid, this); } @@ -458,7 +458,7 @@ static bool dbiTest(void *ctx, short int code) {0, DbiEND_OF_LIST, 0, 0}}; int status = _TreeGetDbi(ctx, dbiList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return supports ? true : false; @@ -488,7 +488,7 @@ static void dbiSet(void *ctx, short int code, bool value) {0, DbiEND_OF_LIST, 0, 0}}; int status = _TreeSetDbi(ctx, dbiList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -507,10 +507,10 @@ void Tree::setViewDate(char *date) int64_t qtime; int status = LibConvertDateString(date, &qtime); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException("Invalid date format"); status = TreeSetViewDate(&qtime); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -519,14 +519,14 @@ void Tree::setTimeContext(Data *start, Data *end, Data *delta) int status = setTreeTimeContext(ctx, (start) ? start->convertToDsc() : 0, (end) ? end->convertToDsc() : 0, (delta) ? delta->convertToDsc() : 0); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void Tree::setCurrent(char const *treeName, int shot) { int status = TreeSetCurrentShotId(treeName, shot); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -538,14 +538,14 @@ int Tree::getCurrent(char const *treeName) void Tree::createPulse(int shot) { int status = _TreeCreatePulseFile(getCtx(), shot, 0, NULL); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void Tree::deletePulse(int shot) { int status = _TreeDeletePulseFile(getCtx(), shot, 1); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -572,7 +572,7 @@ StringArray *Tree::findTags(char *wild) void Tree::removeTag(char const *tagName) { int status = _TreeRemoveTag(getCtx(), tagName); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -617,7 +617,7 @@ static T getNci(void *ctx, int nid, short int code) {0, NciEND_OF_LIST, 0, 0}}; int status = _TreeGetNci(ctx, nid, nciList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return value; @@ -632,7 +632,7 @@ std::string getNci(void *ctx, int nid, short int code) {0, NciEND_OF_LIST, 0, 0}}; int status = _TreeGetNci(ctx, nid, nciList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return value; @@ -653,7 +653,7 @@ void TreeNode::setFlag(int flagOfs, bool flag) status = _TreeSetNci(tree->getCtx(), nid, setNciList); else status = _TreeSetNci(tree->getCtx(), nid, clearNciList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -791,7 +791,7 @@ Data *TreeNode::getData() Data *data = 0; resolveNid(); int status = getTreeData(tree->getCtx(), nid, (void **)&data, tree); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } @@ -802,7 +802,7 @@ void TreeNode::putData(Data *data) { resolveNid(); int status = putTreeData(tree->getCtx(), nid, (void *)data); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } @@ -812,7 +812,7 @@ void TreeNode::deleteData() { resolveNid(); int status = deleteTreeData(tree->getCtx(), nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } @@ -867,7 +867,7 @@ Data *TreeNode::getExtendedAttribute(const char *name) { Data *data = NULL; int status = getTreeXNci(tree->getCtx(), nid, name, (void **)&data, tree); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return data; } @@ -881,7 +881,7 @@ void TreeNode::setExtendedAttribute(const char *name, Data *data) { resolveNid(); int status = setTreeXNci(tree->getCtx(), nid, name, data->convertToDsc()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -890,7 +890,7 @@ void TreeNode::setExtendedAttribute(std::string name, Data *data) resolveNid(); int status = setTreeXNci(tree->getCtx(), nid, name.c_str(), data->convertToDsc()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -898,7 +898,7 @@ void TreeNode::doMethod(char *method) { resolveNid(); int status = doTreeMethod(tree->getCtx(), nid, method); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1049,7 +1049,7 @@ TreeNode **TreeNode::getChildren(int *numChildren) {0, NciEND_OF_LIST, 0, 0}}; int status = _TreeGetNci(tree->getCtx(), nid, nciList1); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); TreeNode **retNodes = new TreeNode *[nidCnt]; @@ -1071,7 +1071,7 @@ TreeNode **TreeNode::getMembers(int *numMembers) {0, NciEND_OF_LIST, 0, 0}}; int status = _TreeGetNci(tree->getCtx(), nid, nciList1); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); TreeNode **retNodes = new TreeNode *[nidCnt]; @@ -1152,7 +1152,7 @@ TreeNodeArray *TreeNode::getConglomerateNodes() resolveNid(); int status = _TreeGetNci(tree->getCtx(), nid, nciList); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); int *nids = new int[nNids]; @@ -1161,7 +1161,7 @@ TreeNodeArray *TreeNode::getConglomerateNodes() {0, NciEND_OF_LIST, 0, 0}}; status = _TreeGetNci(tree->getCtx(), nid, nciList1); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); TreeNodeArray *resArray = new TreeNodeArray(nids, nNids, tree); @@ -1194,7 +1194,7 @@ void TreeNode::makeSegment(Data *start, Data *end, Data *time, time->convertToDsc(), shape[0]); deleteNativeArray(shape); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1212,7 +1212,7 @@ void TreeNode::makeSegmentMinMax(Data *start, Data *end, Data *time, shape[0], resampledNode->getNid(), resFactor); deleteNativeArray(shape); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1230,7 +1230,7 @@ void TreeNode::makeSegmentResampled(Data *start, Data *end, Data *time, shape[0], resampledNode->getNid(), resFactor); deleteNativeArray(shape); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void TreeNode::beginSegment(Data *start, Data *end, Data *time, @@ -1242,7 +1242,7 @@ void TreeNode::beginSegment(Data *start, Data *end, Data *time, tree->getCtx(), getNid(), initialData->convertToDsc(), start->convertToDsc(), end->convertToDsc(), time->convertToDsc()); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void TreeNode::beginSegmentResampled(Data *start, Data *end, Data *time, @@ -1254,7 +1254,7 @@ void TreeNode::beginSegmentResampled(Data *start, Data *end, Data *time, tree->getCtx(), getNid(), initialData->convertToDsc(), start->convertToDsc(), end->convertToDsc(), time->convertToDsc(), resampledNode->getNid(), resFactor); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void TreeNode::beginSegmentMinMax(Data *start, Data *end, Data *time, @@ -1266,7 +1266,7 @@ void TreeNode::beginSegmentMinMax(Data *start, Data *end, Data *time, tree->getCtx(), getNid(), initialData->convertToDsc(), start->convertToDsc(), end->convertToDsc(), time->convertToDsc(), resampledNode->getNid(), resFactor); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } /*void TreeNode::beginSegmentMinMax(Data *start, Data *end, Data *time, Array @@ -1318,7 +1318,7 @@ void TreeNode::putSegment(Array *data, int ofs) int status = putTreeSegment(tree->getCtx(), getNid(), data->convertToDsc(), ofs); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1331,7 +1331,7 @@ void TreeNode::putSegmentResampled(Array *data, int ofs, putTreeSegmentResampled(tree->getCtx(), getNid(), data->convertToDsc(), ofs, resampledNode->getNid(), resFactor); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } void TreeNode::putSegmentMinMax(Array *data, int ofs, TreeNode *resampledNode, @@ -1343,7 +1343,7 @@ void TreeNode::putSegmentMinMax(Array *data, int ofs, TreeNode *resampledNode, putTreeSegmentMinMax(tree->getCtx(), getNid(), data->convertToDsc(), ofs, resampledNode->getNid(), resFactor); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } /*void TreeNode::putSegmentMinMax(Array *data, int ofs, TreeNode*resampledNode, @@ -1387,7 +1387,7 @@ void TreeNode::updateSegment(Data *start, Data *end, Data *time) updateTreeSegment(tree->getCtx(), getNid(), -1, start->convertToDsc(), end->convertToDsc(), time->convertToDsc()); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1399,7 +1399,7 @@ void TreeNode::updateSegment(int segIdx, Data *start, Data *end, Data *time) updateTreeSegment(tree->getCtx(), getNid(), segIdx, start->convertToDsc(), end->convertToDsc(), time->convertToDsc()); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1411,7 +1411,7 @@ int TreeNode::getNumSegments() // if(tree) tree->lock(); int status = getTreeNumSegments(tree->getCtx(), getNid(), &numSegments); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return numSegments; } @@ -1422,7 +1422,7 @@ void TreeNode::getSegmentInfo(int segIdx, char *dtype, char *dimct, int *dims, resolveNid(); int status = getTreeSegmentInfo(tree->getCtx(), getNid(), segIdx, dtype, dimct, dims, nextRow); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1434,7 +1434,7 @@ void TreeNode::getSegmentLimits(int segmentIdx, Data **start, Data **end) int status = getTreeSegmentLimits(tree->getCtx(), getNid(), segmentIdx, &startDsc, &endDsc); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); *start = (Data *)convertFromDsc(startDsc, tree); freeDsc(startDsc); @@ -1451,7 +1451,7 @@ Array *TreeNode::getSegment(int segIdx) int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, &dataDsc, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) { freeDsc(dataDsc); freeDsc(timeDsc); @@ -1470,7 +1470,7 @@ Data *TreeNode::getSegmentDim(int segIdx) // if(tree) tree->lock(); int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, NULL, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) { freeDsc(timeDsc); throw MdsException(status); @@ -1490,7 +1490,7 @@ void TreeNode::getSegmentAndDimension(int segIdx, Array *&segment, int status = getTreeSegment(tree->getCtx(), getNid(), segIdx, &dataDsc, &timeDsc); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) { freeDsc(dataDsc); freeDsc(timeDsc); @@ -1509,7 +1509,7 @@ Data *TreeNode::getSegmentScale() // if(tree) tree->lock(); int status = getTreeSegmentScale(tree->getCtx(), getNid(), &sclDsc); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) { freeDsc(sclDsc); sclDsc = NULL; @@ -1526,7 +1526,7 @@ void TreeNode::setSegmentScale(Data *scale) int status = setTreeSegmentScale(tree->getCtx(), getNid(), scale->convertToDsc()); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1537,7 +1537,7 @@ void TreeNode::beginTimestampedSegment(Array *initData) int status = beginTreeTimestampedSegment(tree->getCtx(), getNid(), initData->convertToDsc()); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1552,7 +1552,7 @@ void TreeNode::makeTimestampedSegment(Array *data, int64_t *times) tree->getCtx(), getNid(), data->convertToDsc(), times, shape[0]); // if(tree) tree->unlock(); deleteNativeArray(shape); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1563,7 +1563,7 @@ void TreeNode::putTimestampedSegment(Array *data, int64_t *times) int status = putTreeTimestampedSegment(tree->getCtx(), getNid(), data->convertToDsc(), times); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1574,7 +1574,7 @@ void TreeNode::putRow(Data *data, int64_t *time, int size) int status = putTreeRow(tree->getCtx(), getNid(), data->convertToDsc(), time, size); // if(tree) tree->unlock(); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1585,7 +1585,7 @@ TreeNode *TreeNode::getNode(char const *relPath) int status = _TreeFindNodeRelative(tree->getCtx(), relPath, nid, &newNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, tree); } @@ -1598,7 +1598,7 @@ TreeNode *TreeNode::getNode(String *relPathStr) int status = _TreeFindNodeRelative(tree->getCtx(), relPath.ptr, nid, &newNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, tree); } @@ -1638,13 +1638,13 @@ TreeNode *TreeNode::addNode(char const *name, char const *usage) int newNid; resolveNid(); int status = _TreeGetDefaultNid(tree->getCtx(), &defNid); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), nid); - if (status & 1) + if (STATUS_OK) status = _TreeAddNode(tree->getCtx(), name, &newNid, convertUsage(usage)); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), defNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, tree); } @@ -1655,16 +1655,16 @@ void TreeNode::remove(char const *name) int defNid; resolveNid(); int status = _TreeGetDefaultNid(tree->getCtx(), &defNid); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), nid); AutoPointer delNode(getNode(name)); status = _TreeDeleteNodeInitialize(tree->getCtx(), delNode.ptr->nid, &count, 1); - if (status & 1) + if (STATUS_OK) _TreeDeleteNodeExecute(tree->getCtx()); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), defNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1674,13 +1674,13 @@ TreeNode *TreeNode::addDevice(char const *name, char const *type) int newNid; resolveNid(); int status = _TreeGetDefaultNid(tree->getCtx(), &defNid); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), nid); - if (status & 1) + if (STATUS_OK) status = _TreeAddConglom(tree->getCtx(), name, type, &newNid); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(tree->getCtx(), defNid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); return new TreeNode(newNid, tree); } @@ -1689,7 +1689,7 @@ void TreeNode::rename(std::string const &newName) { resolveNid(); int status = _TreeRenameNode(tree->getCtx(), nid, newName.c_str()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1711,7 +1711,7 @@ void TreeNode::addTag(std::string const &tagName) { resolveNid(); int status = _TreeAddTag(tree->getCtx(), nid, tagName.c_str()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1725,7 +1725,7 @@ void TreeNode::removeTag(std::string const &tagName) throw MdsException("No such tag for this tree node"); // The tag does not // refer to this node status = _TreeRemoveTag(tree->getCtx(), tagName.c_str()); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1737,7 +1737,7 @@ void TreeNode::setSubtree(bool isSubtree) status = _TreeSetSubtree(tree->getCtx(), nid); else status = _TreeSetNoSubtree(tree->getCtx(), nid); - if (!(status & 1)) + if (STATUS_NOT_OK) throw MdsException(status); } @@ -1782,7 +1782,7 @@ void TreePath::resolveNid() if (!tree) tree = getActiveTree(); int status = _TreeFindNode(tree->getCtx(), path.c_str(), &nid); - if (!(status & 1)) + if (STATUS_NOT_OK) nid = -1; } @@ -2345,7 +2345,7 @@ Tree *MDSplus::getActiveTree() {sizeof(int), DbiSHOTID, &shot, &retShotLen}, {0, DbiEND_OF_LIST, 0, 0}}; int status = TreeGetDbi(dbiItems); - if (!(status & 1)) + if (STATUS_NOT_OK) { throw MdsException(status); } diff --git a/mdsobjects/cpp/testing/MdsDataStreamTest.c b/mdsobjects/cpp/testing/MdsDataStreamTest.c index 591a22ef46..6640b090ee 100644 --- a/mdsobjects/cpp/testing/MdsDataStreamTest.c +++ b/mdsobjects/cpp/testing/MdsDataStreamTest.c @@ -46,7 +46,7 @@ static void printDecompiled(struct descriptor *inD) char *buf; status = TdiDecompile(inD, &out_xd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("%s\n", MdsGetMsg(status)); return; @@ -84,7 +84,7 @@ int main(int argc, char *argv[]) exit(0); } status = MdsSerializeDscIn(retXd->pointer->pointer, &xd); - if (!(status & 1)) + if (STATUS_NOT_OK) { printf("Error: decompressing result\n"); exit(0); diff --git a/mdsobjects/cpp/testing/MdsTdiTest.cpp b/mdsobjects/cpp/testing/MdsTdiTest.cpp index f35c0bdbc3..aca0790989 100644 --- a/mdsobjects/cpp/testing/MdsTdiTest.cpp +++ b/mdsobjects/cpp/testing/MdsTdiTest.cpp @@ -91,7 +91,7 @@ int SingleThreadTest(int idx, int repeats) std::cerr << "FAILED in cycle " << ii << " >> " << cmds[ic] << "\n"; err = 1; } - else if (!(status & 1)) + else if (STATUS_NOT_OK) throw MDSplus::MdsException(status); } catch (MDSplus::MdsException e) @@ -121,24 +121,18 @@ void *ThreadTest(void *args) void MultiThreadTest() { pthread_t threads[NUM_THREADS]; - pthread_attr_t attr, *attrp; - if (pthread_attr_init(&attr)) - attrp = NULL; - else - { - attrp = &attr; - pthread_attr_setstacksize(&attr, 0x40000); - } + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, 0x40000); int thread_idx, results[NUM_THREADS]; for (thread_idx = 0; thread_idx < NUM_THREADS; thread_idx++) { results[thread_idx] = thread_idx; - if (pthread_create(&threads[thread_idx], attrp, ThreadTest, + if (pthread_create(&threads[thread_idx], &attr, ThreadTest, &results[thread_idx])) break; } - if (attrp) - pthread_attr_destroy(attrp); + pthread_attr_destroy(&attr); if (thread_idx < NUM_THREADS) fprintf(stderr, "Could not create all %d threads\n", NUM_THREADS); for (thread_idx = 0; thread_idx < NUM_THREADS; thread_idx++) diff --git a/mdsobjects/cpp/testing/testutils/Makefile.am b/mdsobjects/cpp/testing/testutils/Makefile.am index 9957bb054d..50e04096f9 100644 --- a/mdsobjects/cpp/testing/testutils/Makefile.am +++ b/mdsobjects/cpp/testing/testutils/Makefile.am @@ -22,9 +22,7 @@ library_include_HEADERS = \ type_traits.h \ unique_ptr.h \ vector_test.h \ - Threads.h \ MdsIpInstancer.h - _SOURCES = \ testutils.cpp \ mdsipmain.c @@ -51,8 +49,7 @@ libMdsTestUtils_a_SOURCES = $(_SOURCES) # libMdsTestDummy.so: testutils.cpp $(CC) $(CPPFLAGS) $(CFLAGS) $(AM_CXXFLAGS) -shared -o $@ $^ - + MOSTLYCLEANFILES = libMdsTestDummy.so all-local: libMdsTestDummy.so - diff --git a/mdsobjects/cpp/testing/testutils/Threads.h b/mdsobjects/cpp/testing/testutils/Threads.h deleted file mode 100644 index 80e63ece0f..0000000000 --- a/mdsobjects/cpp/testing/testutils/Threads.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef TESTUTILS_THREADS_H -#define TESTUTILS_THREADS_H - -#include - -//////////////////////////////////////////////////////////////////////////////// -// THREAD BASE //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace testing -{ - class Thread - { - public: - Thread() {} - virtual ~Thread() {} - - bool StartThread() - { - return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0); - } - - void StopThread() { pthread_cancel(_thread); } - - void WaitForThreadToExit() { (void)pthread_join(_thread, NULL); } - - protected: - virtual void InternalThreadEntry() = 0; - - private: - static void *InternalThreadEntryFunc(void *This) - { - ((Thread *)This)->InternalThreadEntry(); - return NULL; - } - - pthread_t _thread; - }; -} // namespace testing - -#endif // THREADS_H diff --git a/mdsshr/MDSprintf.c b/mdsshr/MDSprintf.c index 597eb3a9ef..f997802b06 100644 --- a/mdsshr/MDSprintf.c +++ b/mdsshr/MDSprintf.c @@ -63,7 +63,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ -#include #include #include #include @@ -72,9 +71,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /*===================================================== * Static variables ... *====================================================*/ -STATIC_THREADSAFE int (*MDSvprintf)() = +static int (*MDSvprintf)() = vprintf; /* not really threadsafe but ok */ -STATIC_THREADSAFE int (*MDSvfprintf)() = +static int (*MDSvfprintf)() = vfprintf; /* not really threadsafe but ok */ /****************************************************************** @@ -134,7 +133,7 @@ void MdsGetOutputFunctions(void **const CURvprintf, void **const CURvfprintf) * main: ****************************************************************/ -STATIC_ROUTINE int woof(const char *const fmt, va_list ap) +static int woof(const char *const fmt, va_list ap) { char xxfmt[80]; @@ -142,7 +141,7 @@ STATIC_ROUTINE int woof(const char *const fmt, va_list ap) return (vprintf(xxfmt, ap)); } -STATIC_ROUTINE int tweet(FILE *fp, const char *const fmt, va_list ap) +static int tweet(FILE *fp, const char *const fmt, va_list ap) { char xxfmt[80]; diff --git a/mdsshr/Makefile.in b/mdsshr/Makefile.in index 1539f9c58c..6c24b398f3 100644 --- a/mdsshr/Makefile.in +++ b/mdsshr/Makefile.in @@ -3,7 +3,7 @@ include @top_builddir@/Makefile.inc LIBPREFIX=Mds srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ MKDIR_P=@MKDIR_P@ @AX_RECONFIGURE_TARGET@ @@ -44,8 +44,8 @@ SOURCES = \ UdpEvents.c \ UdpEventSettings.c -OBJECTS = $(SOURCES:.c=.o) - +OBJECTS = $(SOURCES:.c=.o) + ## Version info for git needs to be checked for tag each time .PHONY: MdsVersionInfo.o MdsVersionInfo.o: CFLAGS := $(CFLAGS) -D_GIT_TAG=$(GIT_TAG) diff --git a/mdsshr/MdsCmprs.c b/mdsshr/MdsCmprs.c index 3580ca8d58..8f6e36e133 100644 --- a/mdsshr/MdsCmprs.c +++ b/mdsshr/MdsCmprs.c @@ -87,7 +87,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "mdsshrp.h" -#include #include #include #include @@ -123,8 +122,8 @@ struct HEADER int e; }; -STATIC_CONSTANT signed char FIELDSY = BITSY + BITSX; -STATIC_CONSTANT int FIELDSX = 2; +static signed char FIELDSY = BITSY + BITSX; +static int FIELDSX = 2; int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, mdsdsc_a_t *const pack_dsc_ptr, int *const bit_ptr) @@ -151,7 +150,7 @@ int MdsCmprs(const int *const nitems_ptr, const mdsdsc_a_t *const items_dsc_ptr, signed char yn_c; signed char ye_c; int diff[MAXX], exce[MAXX]; - STATIC_CONSTANT int signif[65] = { + static int signif[65] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7}; diff --git a/mdsshr/MdsCompress.c b/mdsshr/MdsCompress.c index 1ef4654c03..1406a098dd 100644 --- a/mdsshr/MdsCompress.c +++ b/mdsshr/MdsCompress.c @@ -71,7 +71,6 @@ output number of bits in packed. (untested) */ #include "mdsshrp.h" -#include #include #include #include @@ -86,23 +85,23 @@ output number of bits in packed. (untested) typedef ARRAY_COEFF(char, 1) array_coef; typedef RECORD(4) mds_decompress_t; static opcode_t OpcDECOMPRESS = OPC_DECOMPRESS; -STATIC_CONSTANT mds_decompress_t rec0 = {sizeof(opcode_t), - DTYPE_FUNCTION, - CLASS_R, - (uint8_t *)&OpcDECOMPRESS, - 4, - __fill_value__{0, 0, 0, 0}}; -STATIC_CONSTANT DESCRIPTOR_A(dat0, 1, DTYPE_BU, 0, 0); -STATIC_CONSTANT mdsdsc_d_t EMPTY_D = {0, DTYPE_T, CLASS_D, 0}; +static mds_decompress_t rec0 = {sizeof(opcode_t), + DTYPE_FUNCTION, + CLASS_R, + (uint8_t *)&OpcDECOMPRESS, + 4, + __fill_value__{0, 0, 0, 0}}; +static DESCRIPTOR_A(dat0, 1, DTYPE_BU, 0, 0); +static mdsdsc_d_t EMPTY_D = {0, DTYPE_T, CLASS_D, 0}; -STATIC_CONSTANT EMPTYXD(EMPTY_XD); +static EMPTYXD(EMPTY_XD); /*-------------------------------------------------------------------------- The inner routine scans some classes and tries to compress arrays. If successful returns 1, if unsuccessful returns NORMAL. */ -STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, - const mdsdsc_t *const pcentry, const int64_t delta, - mdsdsc_t *const pwork) +static int compress(const mdsdsc_t *const pcimage, + const mdsdsc_t *const pcentry, const int64_t delta, + mdsdsc_t *const pwork) { int j, stat1, status = 1; unsigned int bit = 0; @@ -133,7 +132,7 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, case CLASS_R: ppd = &((mdsdsc_r_t *)pwork)->dscptrs[0]; j = ((mdsdsc_r_t *)pwork)->ndesc; - while ((--j >= 0) && (status & 1)) + while ((--j >= 0) && (STATUS_OK)) if ((stat1 = compress(pcimage, pcentry, delta, *(ppd++))) != 1) status = stat1; break; @@ -195,7 +194,7 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, dximage = EMPTY_D; dxentry = EMPTY_D; status = LibFindImageSymbol(pcimage, pcentry, &symbol); - if (status & 1) + if (STATUS_OK) status = (*symbol)(&nitems, pwork, pdat, &bit, &dximage, &dxentry); pdat->arsize = (bit + 7) / 8; pd0 = (mdsdsc_t *)(pdat->pointer + pdat->arsize); @@ -227,7 +226,7 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, pd0 = pd1; StrFree1Dx(&dxentry); } - if ((status & 1) && (status != LibSTRTRU) && + if ((STATUS_OK) && (status != LibSTRTRU) && ((char *)pd0 < (char *)plim)) goto good; /************************************************** @@ -245,7 +244,7 @@ STATIC_ROUTINE int compress(const mdsdsc_t *const pcimage, ********************/ status = MdsCmprs(&nitems, (mdsdsc_a_t *)pwork, pdat, (int *)&bit); pdat->arsize = (bit + 7) / 8; - if ((status & 1) && (status != LibSTRTRU)) + if ((STATUS_OK) && (status != LibSTRTRU)) goto good; /************************************* Did not do a good job, so restore all. @@ -281,7 +280,7 @@ EXPORT int MdsCompress(const mdsdsc_t *const cimage_ptr, { int status = 1; mdsdsc_xd_t work; - STATIC_CONSTANT dtype_t dsc_dtype = DTYPE_DSC; + static dtype_t dsc_dtype = DTYPE_DSC; if (in_ptr == 0) return MdsFree1Dx(out_ptr, NULL); switch (in_ptr->class) @@ -314,11 +313,11 @@ Compact/copy from work. #ifdef _RECURSIVE_COMPRESS while (status == MdsCOMPRESSIBLE) #else - if (status & 1) + if (STATUS_OK) #endif { status = MdsGet1Dx(&work.l_length, &dsc_dtype, out_ptr, NULL); - if (status & 1) + if (STATUS_OK) { #ifdef _RECURSIVE_COMPRESS int orig_len = work.l_length; @@ -327,7 +326,7 @@ Compact/copy from work. status = compress(cimage_ptr, centry_ptr, (char *)out_ptr->pointer - (char *)work.pointer, work.pointer); - if (status & 1) + if (STATUS_OK) status = MdsCopyDxXd(work.pointer, out_ptr); MdsFree1Dx(&work, NULL); #ifdef _RECURSIVE_COMPRESS @@ -375,7 +374,7 @@ EXPORT int MdsDecompress(const mdsdsc_r_t *rec_ptr, mdsdsc_xd_t *out_ptr) if (prec->dscptrs[1]) { status = LibFindImageSymbol(prec->dscptrs[0], prec->dscptrs[1], &symbol); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; } else @@ -383,15 +382,15 @@ EXPORT int MdsDecompress(const mdsdsc_r_t *rec_ptr, mdsdsc_xd_t *out_ptr) symbol = MdsXpand; status = 1; } - if (status & 1) + if (STATUS_OK) status = MdsGet1DxA(pa, &pa->length, &pa->dtype, out_ptr); - if (status & 1) + if (STATUS_OK) { if (prec->dscptrs[3]->class == CLASS_CA) { EMPTYXD(tmp_xd); status = MdsDecompress((mdsdsc_r_t *)prec->dscptrs[3], &tmp_xd); - if (status & 1) + if (STATUS_OK) status = (*symbol)(&nitems, tmp_xd.pointer, out_ptr->pointer, &bit); MdsFree1Dx(&tmp_xd, 0); } diff --git a/mdsshr/MdsEvents.c b/mdsshr/MdsEvents.c index 5d49be5e51..432a45157e 100644 --- a/mdsshr/MdsEvents.c +++ b/mdsshr/MdsEvents.c @@ -22,21 +22,22 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../mdstcpip/mdsip_connections.h" +#include + #include #include -#include -#include -#include -#include -#include #include #include #include -#ifdef HAVE_ALLOCA_H -#include -#endif + +#include "../mdstcpip/mdsip_connections.h" +#include +#include +#include +#include +#include #include "mdsshrp.h" +#include <_mdsshr.h> #ifdef _WIN32 #define pipe(fds) _pipe(fds, 4096, _O_BINARY) @@ -45,167 +46,111 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define _GNU_SOURCE /* glibc2 needs this */ #include #include -#define MAX_ACTIVE_EVENTS \ - 2000 /* Maximum number events concurrently dealt with by processes */ +/// Maximum number events concurrently dealt with by processes +#define MAX_ACTIVE_EVENTS 2000 #ifndef EVENT_THREAD_STACK_SIZE_MIN #define EVENT_THREAD_STACK_SIZE_MIN 102400 #endif -static int receive_ids[256]; /* Connection to receive external events */ -static int send_ids[256]; /* Connection to send external events */ -static int receive_sockets[256]; /* Socket to receive external events */ -static int send_sockets[256]; /* Socket to send external events */ -static char *receive_servers[256]; /* Receive server names */ -static char *send_servers[256]; /* Send server names */ -static int external_shutdown = - 0; /* flag to request remote events thread termination */ +static int receive_ids[256]; /* Connection to receive external events */ +static int send_ids[256]; /* Connection to send external events */ +static int receive_sockets[256]; /* Socket to receive external events */ +static int send_sockets[256]; /* Socket to send external events */ +static char *receive_servers[256]; /* Receive server names */ +static char *send_servers[256]; /* Send server names */ +static int external_shutdown = 0; /* request remote events thread termination */ static int external_count = 0; /* remote event pendings count */ static int num_receive_servers = 0; /* numer of external event sources */ static int num_send_servers = 0; /* numer of external event destination */ -static int external_thread_created = - 0; /* Thread for remot event handling flag */ -static int fds[2]; /* file descriptors used by the pipe */ +static int external_thread_created = 0; /* Thread for remot event handling flag */ +static int fds[2]; /* file descriptors used by the pipe */ static int eventAstRemote(char const *eventnam, void (*astadr)(), void *astprm, int *eventid); static void initializeRemote(int receive_events); -static int ConnectToMds_(const char *const host) +static int ConnectToMds_(const char *host) { - static int (*rtn)(const char *const host) = 0; - int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "ConnectToMds", - (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(host); - } - return -1; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, ConnectToMds, return -1, int, (const char *)); + return ConnectToMds(host); } -static int DisconnectFromMds_(const int id) +static int DisconnectFromMds_(int id) { - static int (*rtn)() = 0; - int status = - (rtn == 0) - ? LibFindImageSymbol_C("MdsIpShr", "DisconnectFromMds", (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(id); - } - return -1; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, DisconnectFromMds, return -1, int, (int)); + return DisconnectFromMds(id); } -static void *GetConnectionInfo_(const int id, char **const name, - int *const readfd, size_t *const len) +static void *GetConnectionInfo_(int id, char **name, int *readfd, size_t *len) { - static void *(*rtn)() = 0; - int status = - (rtn == 0) - ? LibFindImageSymbol_C("MdsIpShr", "GetConnectionInfo", (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(id, name, readfd, len); - } - return 0; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, GetConnectionInfo, return NULL, void *, ()); + return GetConnectionInfo(id, name, readfd, len); } -static int MdsEventAst_(const int conid, char const *const eventnam, - void (*const astadr)(), void *const astprm, - int *const eventid) +static int MdsEventAst_(int conid, const char *eventnam, void (*astadr)(), void *astprm, int *eventid) { - static int (*rtn)() = 0; - int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "MdsEventAst", - (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(conid, eventnam, astadr, astprm, eventid); - } - return 0; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, MdsEventAst, return 0, int, ()); + return MdsEventAst(conid, eventnam, astadr, astprm, eventid); } static Message *GetMdsMsg_(const int id, const int *const stat) { - static Message *(*rtn)() = 0; - int status = - (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "GetMdsMsg", (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(id, stat); - } - return 0; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, GetMdsMsg, return NULL, Message *, ()); + return GetMdsMsg(id, stat); } static int MdsEventCan_(const int id, const int eid) { - static int (*rtn)() = 0; - int status = (rtn == 0) ? LibFindImageSymbol_C("MdsIpShr", "MdsEventCan", - (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(id, eid); - } - return 0; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, MdsEventCan, return 0, int, ()); + return MdsEventCan(id, eid); } static int MdsValue_(const int id, const char *const exp, struct descrip *const d1, struct descrip *const d2, struct descrip *const d3) { - static int (*rtn)() = 0; - int status = (rtn == 0) - ? LibFindImageSymbol_C("MdsIpShr", "MdsValue", (void **)&rtn) - : 1; - if (STATUS_OK) - { - return rtn(id, exp, d1, d2, d3); - } - return 0; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, MdsValue, return 0, int, ()); + return MdsValue(id, exp, d1, d2, d3); } #ifdef GLOBUS static int RegisterRead_(const int conid) { - int status = 1; - static int (*rtn)(int) = 0; - if (rtn == 0) - status = LibFindImageSymbol_C("MdsIpShr", "RegisterRead", (void **)&rtn); - if (STATUS_NOT_OK) + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, RegisterRead, return status, int, ()); + return RegisterRead(conid); +} +#endif + +/// concat on ' ', cast to uppercase and return new strlen +static inline int fixup_eventname(char *in) +{ + char *src = in; + char *out = in; + for (; *src; src++) { - printf("%s\n", MdsGetMsg(status)); - return status; + if (*src != ' ') + *(out++) = (char)toupper(*src); } - return rtn(conid); + *out = '\0'; + return out - in; } -#endif -static char *eventName(const char *const eventnam_in) +static char *alloc_eventname(const char *const in) { - size_t i, j; - char *eventnam = 0; - if (eventnam_in) + if (!in) + return NULL; + char *out = strdup(in); + if (!out) + return NULL; + int len = fixup_eventname(out); + if (len == 0) { - eventnam = strdup(eventnam_in); - for (i = 0, j = 0; i < strlen(eventnam); i++) - { - if (eventnam[i] != 32) - eventnam[j++] = (char)toupper(eventnam[i]); - } - eventnam[j] = 0; - if (strlen(eventnam) == 0) - { - free(eventnam); - eventnam = 0; - } + free(out); + return NULL; } - return eventnam; + return realloc(out, len + 1); } #ifndef HAVE_VXWORKS_H @@ -374,7 +319,7 @@ static void getServerDefinition(char const *env_var, char **servers, curr_name[j] = envname[i]; curr_name[j] = 0; i++; - servers[*num_servers] = malloc(strlen(curr_name) + 1); + servers[*num_servers] = strdup(curr_name); strcpy(servers[*num_servers], curr_name); (*num_servers)++; } @@ -840,12 +785,7 @@ EXPORT int MDSGetEventQueue(const int eventid, const int timeout, if (timeout > 0) { static struct timespec abstime; -#ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_REALTIME, &abstime); -#else - abstime.tv_sec = time(0); - abstime.tv_nsec = 0; -#endif abstime.tv_sec += timeout; state = pthread_cond_timedwait(&qh->cond, &qh->mutex, &abstime) == 0; } @@ -879,19 +819,18 @@ EXPORT int MDSGetEventQueue(const int eventid, const int timeout, return state; } -int RemoteMDSEventAst(const char *const eventnam_in, void (*const astadr)(), - void *const astprm, int *const eventid) +int RemoteMDSEventAst(const char *eventNameIn, void (*astadr)(), void *astprm, int *eventid) { - int status = 0; - char *eventnam = eventName(eventnam_in); *eventid = -1; - if (eventnam) + char *eventName = alloc_eventname(eventNameIn); + if (eventName) { initializeRemote(1); - status = eventAstRemote(eventnam, astadr, astprm, eventid); - free(eventnam); + int status = eventAstRemote(eventName, astadr, astprm, eventid); + free(eventName); + return status; } - return status; + return 0; } static int canEventRemote(const int eventid) @@ -975,24 +914,17 @@ static int sendRemoteEvent(const char *const evname, const int data_len, return status; } -int RemoteMDSEvent(const char *const evname_in, const int data_len, - char *const data) +int RemoteMDSEvent(const char *eventNameIn, int data_len, char *data) { - int j; - unsigned int u; - char *evname; - int status = 1; - initializeRemote(0); - evname = strdup(evname_in); - for (u = 0, j = 0; u < strlen(evname); u++) + char *eventName = alloc_eventname(eventNameIn); + if (eventName) { - if (evname[u] != 32) - evname[j++] = (char)toupper(evname[u]); + initializeRemote(0); + int status = sendRemoteEvent(eventName, data_len, data); + free(eventName); + return status; } - evname[j] = 0; - status = sendRemoteEvent(evname, data_len, data); - free(evname); - return status; + return 0; } #endif @@ -1001,61 +933,53 @@ EXPORT int MDSEventAst(const char *const eventNameIn, void (*const astadr)(void *, int, char *), void *const astprm, int *const eventid) { - char *eventName = malloc(strlen(eventNameIn) + 1); - unsigned int i, j; - int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) + char *eventName = alloc_eventname(eventNameIn); + if (eventName) { - if (eventNameIn[i] != 32) - eventName[j++] = (char)toupper(eventNameIn[i]); + int status; + if (getenv("mds_event_server")) + status = RemoteMDSEventAst(eventName, astadr, astprm, eventid); + else + status = MDSUdpEventAst(eventName, astadr, astprm, eventid); + free(eventName); + return status; } - eventName[j] = 0; - if (getenv("mds_event_server")) - status = RemoteMDSEventAst(eventName, astadr, astprm, eventid); - else - status = MDSUdpEventAst(eventName, astadr, astprm, eventid); - free(eventName); - return status; + return 0; } EXPORT int MDSEventAstMask(const char *const eventNameIn, void (*const astadr)(void *, int, char *), void *const astprm, int *const eventid, unsigned int cpuMask) { - char *eventName = malloc(strlen(eventNameIn) + 1); - unsigned int i, j; - int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) + char *eventName = alloc_eventname(eventNameIn); + if (eventName) { - if (eventNameIn[i] != 32) - eventName[j++] = (char)toupper(eventNameIn[i]); + int status; + if (getenv("mds_event_server")) + status = RemoteMDSEventAst(eventName, astadr, astprm, eventid); + else + status = MDSUdpEventAstMask(eventName, astadr, astprm, eventid, cpuMask); + free(eventName); + return status; } - eventName[j] = 0; - if (getenv("mds_event_server")) - status = RemoteMDSEventAst(eventName, astadr, astprm, eventid); - else - status = MDSUdpEventAstMask(eventName, astadr, astprm, eventid, cpuMask); - free(eventName); - return status; + return 0; } EXPORT int MDSEvent(const char *const eventNameIn, const int bufLen, char *const buf) { - char *eventName = alloca(strlen(eventNameIn) + 1); - unsigned int i, j; - int status; - for (i = 0, j = 0; i < strlen(eventNameIn); i++) + char *eventName = alloc_eventname(eventNameIn); + if (eventName) { - if (eventNameIn[i] != 32) - eventName[j++] = (char)toupper(eventNameIn[i]); + int status; + if (getenv("mds_event_target")) + status = RemoteMDSEvent(eventName, bufLen, buf); + else + status = MDSUdpEvent(eventName, bufLen, buf); + free(eventName); + return status; } - eventName[j] = 0; - if (getenv("mds_event_target")) - status = RemoteMDSEvent(eventName, bufLen, buf); - else - status = MDSUdpEvent(eventName, bufLen, buf); - return status; + return 0; } EXPORT int MDSEventCan(const int id) diff --git a/mdsshr/MdsGet1DxA.c b/mdsshr/MdsGet1DxA.c index 407ce78071..05daa3ce3f 100644 --- a/mdsshr/MdsGet1DxA.c +++ b/mdsshr/MdsGet1DxA.c @@ -69,7 +69,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-----------------------------------------------------------------------------*/ -#include #include #include #include diff --git a/mdsshr/MdsGet1DxS.c b/mdsshr/MdsGet1DxS.c index dde94ee8d8..af23535023 100644 --- a/mdsshr/MdsGet1DxS.c +++ b/mdsshr/MdsGet1DxS.c @@ -63,7 +63,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-----------------------------------------------------------------------------*/ -#include #include #include #include diff --git a/mdsshr/MdsGetSetShotId.c b/mdsshr/MdsGetSetShotId.c index 5386c08fd8..e5f050b644 100644 --- a/mdsshr/MdsGetSetShotId.c +++ b/mdsshr/MdsGetSetShotId.c @@ -47,7 +47,6 @@ int MdsGetCurrentShotId(experiment,shot) use without specific written approval of MIT Plasma Fusion Center Management. ------------------------------------------------------------------------------*/ -#include #include int MdsGetCurrentShotId() diff --git a/mdsshr/MdsPk.c b/mdsshr/MdsPk.c index 6853e7c2c6..b05b28c576 100644 --- a/mdsshr/MdsPk.c +++ b/mdsshr/MdsPk.c @@ -53,9 +53,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 3.40 Unpack Macro timings 3.01 3.07 3.02 */ -#include #include -STATIC_CONSTANT unsigned int masks[33] = { +static unsigned int masks[33] = { 0, 0x1, 0x3, @@ -94,7 +93,7 @@ STATIC_CONSTANT unsigned int masks[33] = { #include #include -STATIC_ROUTINE int SwapBytes(char *in_c) +static int SwapBytes(char *in_c) { int out; char *out_c = (char *)&out; diff --git a/mdsshr/MdsSerialize.c b/mdsshr/MdsSerialize.c index c986a10450..d49ddf5952 100644 --- a/mdsshr/MdsSerialize.c +++ b/mdsshr/MdsSerialize.c @@ -22,7 +22,6 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include #include #include #include @@ -131,8 +130,8 @@ union __bswap { #endif -STATIC_ROUTINE int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, - l_length_t *b_out, l_length_t *b_in) +static int copy_rec_dx(char const *in_ptr, mdsdsc_xd_t *out_dsc_ptr, + l_length_t *b_out, l_length_t *b_in) { int status = 1; uint32_t bytes_out = 0, bytes_in = 0, i, j, size_out, size_in; @@ -561,8 +560,8 @@ EXPORT int MdsSerializeDscIn(char const *in, mdsdsc_xd_t *out) return status; } -STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, - l_length_t *b_out, l_length_t *b_in) +static int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, + l_length_t *b_out, l_length_t *b_in) { int status = MDSplusSUCCESS; unsigned bytes_out = 0, bytes_in = 0, j, size_out, size_in, num_dsc; @@ -964,8 +963,8 @@ STATIC_ROUTINE int copy_dx_rec(const mdsdsc_t *in_ptr, char *out_ptr, return status; } -STATIC_ROUTINE int Dsc2Rec(const mdsdsc_t *inp, mdsdsc_xd_t *out_ptr, - arsize_t *reclen) +static int Dsc2Rec(const mdsdsc_t *inp, mdsdsc_xd_t *out_ptr, + arsize_t *reclen) { arsize_t size_out, size_in; static const dtype_t b_dtype = DTYPE_B; @@ -988,7 +987,7 @@ STATIC_ROUTINE int Dsc2Rec(const mdsdsc_t *inp, mdsdsc_xd_t *out_ptr, return status; } -STATIC_CONSTANT int PointerToOffset(mdsdsc_t *dsc_ptr, l_length_t *length) +static int PointerToOffset(mdsdsc_t *dsc_ptr, l_length_t *length) { int status = 1; if ((dsc_ptr->dtype == DTYPE_DSC) && (dsc_ptr->class != CLASS_A) && diff --git a/mdsshr/MdsThreadStatic.c b/mdsshr/MdsThreadStatic.c index 934770c207..1286251264 100644 --- a/mdsshr/MdsThreadStatic.c +++ b/mdsshr/MdsThreadStatic.c @@ -105,9 +105,14 @@ static inline MDSTHREADSTATIC_TYPE *buffer_alloc() MDS_MDSGETMSG_DESC.pointer = MDS_MDSGETMSG_CSTR; return MDSTHREADSTATIC_VAR; } +static inline void buffer_free(MDSTHREADSTATIC_ARG) +{ + free(MDS_FIS_ERROR); + free(MDSTHREADSTATIC_VAR); +} IMPLEMENT_GETTHREADSTATIC(MDSTHREADSTATIC_TYPE, MdsGetThreadStatic, - THREADSTATIC_MDSSHR, buffer_alloc, free) + THREADSTATIC_MDSSHR, buffer_alloc, buffer_free) EXPORT void LockMdsShrMutex(pthread_mutex_t *mutex, int *initialized) { diff --git a/mdsshr/MdsXdRoutines.c b/mdsshr/MdsXdRoutines.c index 8cea0d1677..1e8908fd27 100644 --- a/mdsshr/MdsXdRoutines.c +++ b/mdsshr/MdsXdRoutines.c @@ -38,7 +38,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* *1 19-OCT-1995 13:38:16 TWF "XD handling" */ /* CMS REPLACEMENT HISTORY, Element MDSXDROUTINES.C */ #include "mdsshrp.h" -#include #include #include #include diff --git a/mdsshr/UdpEventSettings.c b/mdsshr/UdpEventSettings.c index 3923cc90be..f16fd46194 100644 --- a/mdsshr/UdpEventSettings.c +++ b/mdsshr/UdpEventSettings.c @@ -22,18 +22,22 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include -#include -#include #include -#include + #include #include #include #include #include +#include +#include +#include +#include + +#include +#include + //#define DEBUG typedef enum @@ -309,8 +313,7 @@ DEFINE_INITIALIZESOCKETS; EXPORT void InitializeEventSettings() { INITIALIZESOCKETS; - pthread_mutex_lock(&init_lock); - pthread_cleanup_push((void *)pthread_mutex_unlock, &init_lock); + MUTEX_LOCK_PUSH(&init_lock); int i, missing = 0; xmlInitParser_supp(); for (i = 0; i < NUM_SETTINGS; i++) @@ -414,5 +417,5 @@ EXPORT void InitializeEventSettings() fprintf(stderr, "\n"); #endif } - pthread_cleanup_pop(1); + MUTEX_LOCK_POP(&init_lock); } diff --git a/mdsshr/UdpEvents.c b/mdsshr/UdpEvents.c index c39dfe78f5..e404b7b5e2 100644 --- a/mdsshr/UdpEvents.c +++ b/mdsshr/UdpEvents.c @@ -23,7 +23,6 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _GNU_SOURCE -#include #include #include @@ -38,6 +37,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include +#include <_mdsshr.h> extern int UdpEventGetPort(unsigned short *port); extern int UdpEventGetAddress(char **addr_format, unsigned char *arange); @@ -53,65 +54,6 @@ extern int UdpEventGetInterface(struct in_addr **interface_addr); #define EVENT_THREAD_STACK_SIZE_MIN 102400 #endif -#ifdef _WIN32 -#define socklen_t int -static void print_error_code(char *message, int error) -{ - char *errorstr; - switch (error) - { - case WSANOTINITIALISED: - errorstr = "WSANOTINITIALISED"; - break; - case WSAENETDOWN: - errorstr = "WSAENETDOWN"; - break; - case WSAEADDRINUSE: - errorstr = "WSAEADDRINUSE"; - break; - case WSAEINTR: - errorstr = "WSAEINTR"; - break; - case WSAEINPROGRESS: - errorstr = "WSAEINPROGRESS"; - break; - case WSAEALREADY: - errorstr = "WSAEALREADY"; - break; - case WSAEADDRNOTAVAIL: - errorstr = "WSAEADDRNOTAVAIL"; - break; - case WSAEAFNOSUPPORT: - errorstr = "WSAEAFNOSUPPORT"; - break; - case WSAECONNREFUSED: - errorstr = "WSAECONNREFUSED"; - break; - case WSAENOPROTOOPT: - errorstr = "WSAENOPROTOOPT"; - break; - case WSAEFAULT: - errorstr = "WSAEFAULT"; - break; - case WSAENOTSOCK: - errorstr = "WSAENOTSOCK"; - break; - default: - errorstr = 0; - } - if (errorstr) - fprintf(stderr, "%s - %s\n", message, errorstr); - else - fprintf(stderr, "%s - error code %d\n", message, error); -} -inline static void print_error(char *message) -{ - print_error_code(message, WSAGetLastError()); -} -#else -#define print_error(message) fprintf(stderr, "%s\n", message) -#endif - typedef struct _EventList { int eventid; @@ -128,7 +70,6 @@ struct EventInfo void (*astadr)(void *, int, char *); }; -static int EVENTID = 0; static EventList *EVENTLIST = 0; static pthread_mutex_t eventIdMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t sendEventMutex = PTHREAD_MUTEX_INITIALIZER; @@ -145,69 +86,70 @@ static pthread_mutex_t sendEventMutex = PTHREAD_MUTEX_INITIALIZER; static void *handleMessage(void *info_in) { + struct EventInfo *info = (struct EventInfo *)info_in; - pthread_mutex_lock(&eventIdMutex); SOCKET socket = info->socket; size_t thisNameLen = strlen(info->eventName); char *thisEventName = strcpy(alloca(thisNameLen + 1), info->eventName); void *arg = info->arg; void (*astadr)(void *, int, char *) = info->astadr; - ssize_t recBytes; - char recBuf[MAX_MSG_LEN]; // TODO: would malloc be better for a slim stack - struct sockaddr clientAddr; - socklen_t addrSize = sizeof(clientAddr); - unsigned int nameLen, bufLen; - char *eventName; - char *currPtr; free(info->eventName); free(info); - pthread_mutex_unlock(&eventIdMutex); + INIT_AND_FREE_ON_EXIT(char *, recBuf); + struct sockaddr clientAddr; + recBuf = malloc(MAX_MSG_LEN); for (;;) { - recBytes = recvfrom(socket, (char *)recBuf, MAX_MSG_LEN, 0, - (struct sockaddr *)&clientAddr, &addrSize); + socklen_t addrSize = sizeof(clientAddr); + MSG_NOSIGNAL_ALT_PUSH(); + const ssize_t recBytes = recvfrom( + socket, (char *)recBuf, MAX_MSG_LEN, MSG_NOSIGNAL, + (struct sockaddr *)&clientAddr, &addrSize); + MSG_NOSIGNAL_ALT_PUSH(); if (recBytes <= 0) { #ifdef _WIN32 int error = WSAGetLastError(); if (!(recBytes == 0 || error == WSAEBADF || error == WSAESHUTDOWN || error == WSAEINTR || error == WSAENOTSOCK)) - print_error_code("Error getting data", error); + _print_socket_error("Error getting data", error); #endif break; } if (recBytes < (int)(sizeof(int) * 2 + thisNameLen)) continue; - currPtr = recBuf; - memcpy(&nameLen, currPtr, sizeof(nameLen)); - nameLen = ntohl(nameLen); + char *currPtr = recBuf; + uint32_t swap; + memcpy(&swap, currPtr, sizeof(swap)); + uint32_t nameLen = ntohl(swap); if (nameLen != thisNameLen) continue; currPtr += sizeof(int); - eventName = currPtr; + char *eventName = currPtr; currPtr += nameLen; - memcpy(&bufLen, currPtr, sizeof(bufLen)); - bufLen = ntohl(bufLen); + memcpy(&swap, currPtr, sizeof(swap)); + uint32_t bufLen = ntohl(swap); currPtr += sizeof(int); - if ((size_t)recBytes != - (nameLen + bufLen + 2 * sizeof(int))) /*** check for invalid buffer ***/ + // check for invalid buffer + if ((size_t)recBytes != (nameLen + bufLen + 2 * sizeof(int))) continue; - if (strncmp(thisEventName, eventName, - nameLen)) /*** check to see if this message matches the event - name ***/ + // check to see if this message matches the event name + if (strncmp(thisEventName, eventName, nameLen)) continue; astadr(arg, (int)bufLen, currPtr); } - return 0; + FREE_NOW(recBuf); + return NULL; } static int pushEvent(pthread_t thread, SOCKET socket) { - pthread_mutex_lock(&eventIdMutex); EventList *ev = malloc(sizeof(EventList)); - ev->eventid = ++EVENTID; ev->socket = socket; ev->thread = thread; + pthread_mutex_lock(&eventIdMutex); + static int EVENTID = 0; + ev->eventid = EVENTID++; ev->next = EVENTLIST; EVENTLIST = ev; pthread_mutex_unlock(&eventIdMutex); @@ -216,17 +158,16 @@ static int pushEvent(pthread_t thread, SOCKET socket) static EventList *popEvent(int eventid) { + EventList *ev; pthread_mutex_lock(&eventIdMutex); - EventList *ev, *ev_prev; - for (ev = EVENTLIST, ev_prev = 0; ev && ev->eventid != eventid; - ev_prev = ev, ev = ev->next) - ; - if (ev) + EventList **prev = &EVENTLIST; + for (ev = EVENTLIST; ev; prev = &ev->next, ev = ev->next) { - if (ev_prev) - ev_prev->next = ev->next; - else - EVENTLIST = ev->next; + if (ev->eventid == eventid) + { + *prev = ev->next; + break; + } } pthread_mutex_unlock(&eventIdMutex); return ev; @@ -251,15 +192,8 @@ static void getMulticastAddr(char const *eventName, char *retIp) int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char *), void *astprm, int *eventid, __attribute__((unused)) unsigned int cpuMask) { - int check_bind_in_directive; struct sockaddr_in serverAddr; - -#ifdef _WIN32 - char flag = 1; -#else - int flag = 1; - int const SOCKET_ERROR = -1; -#endif + int one = 1; int udpSocket; char ipAddress[64]; struct ip_mreq ipMreq; @@ -270,39 +204,30 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * UdpEventGetPort(&port); if ((udpSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { - print_error("Error creating socket"); - return 0; + print_socket_error("Error creating socket"); + return MDSplusERROR; } - // serverAddr.sin_len = sizeof(serverAddr); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Allow multiple connections - if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == - SOCKET_ERROR) + if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))) { - print_error("Cannot set REUSEADDR option"); - return 0; + print_socket_error("Cannot set REUSEADDR option"); + return MDSplusERROR; } + #ifdef SO_REUSEPORT - if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) == - SOCKET_ERROR) + if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))) { - print_error("Cannot set REUSEPORT option"); + print_socket_error("Cannot set REUSEPORT option"); } #endif -#ifdef _WIN32 - check_bind_in_directive = - (bind(udpSocket, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) != 0); -#else - check_bind_in_directive = (bind(udpSocket, (struct sockaddr *)&serverAddr, - sizeof(struct sockaddr_in)) != 0); -#endif - if (check_bind_in_directive) + if (bind(udpSocket, (SOCKADDR *)&serverAddr, sizeof(serverAddr))) { perror("Cannot bind socket\n"); - return 0; + return MDSplusERROR; } getMulticastAddr(eventName, ipAddress); @@ -311,9 +236,9 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * if (setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ipMreq, sizeof(ipMreq)) < 0) { - print_error( + print_socket_error( "Error setting socket options IP_ADD_MEMBERSHIP in udpStartReceiver"); - return 0; + return MDSplusERROR; } currInfo = (struct EventInfo *)malloc(sizeof(struct EventInfo)); currInfo->eventName = strdup(eventName); @@ -329,7 +254,7 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * if (s != 0) { perror("pthread_attr_init"); - return 0; + return MDSplusERROR; } pthread_attr_getstacksize(&attr, &ssize); if (ssize < EVENT_THREAD_STACK_SIZE_MIN) @@ -338,14 +263,14 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * if (s != 0) { perror("pthread_attr_setstacksize"); - return 0; + return MDSplusERROR; } } s = pthread_create(&thread, &attr, handleMessage, (void *)currInfo); if (s != 0) { perror("pthread_create"); - return 0; + return MDSplusERROR; } #ifdef CPU_SET if (cpuMask != 0) @@ -366,7 +291,7 @@ int MDSUdpEventAstMask(char const *eventName, void (*astadr)(void *, int, char * } *eventid = pushEvent(thread, udpSocket); - return 1; + return MDSplusSUCCESS; } int MDSUdpEventAst(char const *eventName, void (*astadr)(void *, int, char *), @@ -381,7 +306,7 @@ int MDSUdpEventCan(int eventid) if (!ev) { printf("invalid eventid %d\n", eventid); - return 0; + return MDSplusERROR; } #ifdef _WIN32 /********************************************** @@ -391,17 +316,14 @@ int MDSUdpEventCan(int eventid) This however is a race condition so we cancel when we can (ifndef _WIN32) **********************************************/ + shutdown(ev->socket, SHUT_RDWR); closesocket(ev->socket); #else pthread_cancel(ev->thread); #endif pthread_join(ev->thread, NULL); -#ifndef _WIN32 - shutdown(ev->socket, SHUT_RDWR); - close(ev->socket); -#endif free(ev); - return 1; + return MDSplusSUCCESS; } static SOCKET send_socket = INVALID_SOCKET; @@ -410,7 +332,7 @@ static pthread_once_t send_socket_once = PTHREAD_ONCE_INIT; static void send_socket_get() { if ((send_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) - print_error("Error creating socket"); + print_socket_error("Error creating socket"); UdpEventGetPort(&sendPort); } @@ -419,7 +341,7 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) char multiIp[64]; uint32_t buflen_net_order = (uint32_t)htonl(bufLen); SOCKET udpSocket; - static struct sockaddr_in sin; + struct sockaddr_in sin; char *msg = 0, *currPtr; unsigned int msgLen, nameLen = (unsigned int)strlen(eventName), actBufLen; uint32_t namelen_net_order = (uint32_t)htonl(nameLen); @@ -432,7 +354,9 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) udpSocket = send_socket; memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; - *(int *)&sin.sin_addr = LibGetHostAddr(multiIp); + sin.sin_addr.s_addr = INADDR_ANY; + if (_LibGetHostAddr(multiIp, NULL, (struct sockaddr *)&sin)) + return MDSplusERROR; sin.sin_port = htons(sendPort); nameLen = (unsigned int)strlen(eventName); if (bufLen < MAX_MSG_LEN - (4u + 4u + nameLen)) @@ -471,11 +395,11 @@ int MDSUdpEvent(char const *eventName, unsigned int bufLen, char const *buf) if (sendto(udpSocket, msg, msgLen, 0, (struct sockaddr *)&sin, sizeof(sin)) == -1) { - print_error("Error sending UDP message"); - status = 0; + print_socket_error("Error sending UDP message"); + status = MDSplusERROR; } else - status = 1; + status = MDSplusSUCCESS; free(msg); pthread_mutex_unlock(&sendEventMutex); return status; diff --git a/mdsshr/librtl.c b/mdsshr/librtl.c index 23569a9556..a581bd97ed 100644 --- a/mdsshr/librtl.c +++ b/mdsshr/librtl.c @@ -38,15 +38,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include +#include <_mdsshr.h> // #define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif +#include #ifdef _WIN32 #include @@ -58,13 +54,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #endif -#include #include #include #include #include #include #include +#include "mdsthreadstatic.h" #define LIBRTL_SRC @@ -132,7 +128,7 @@ static inline time_t get_tz_offset(time_t *const time) #endif } -STATIC_CONSTANT int64_t VMS_TIME_OFFSET = LONG_LONG_CONSTANT(0x7c95674beb4000); +static int64_t VMS_TIME_OFFSET = LONG_LONG_CONSTANT(0x7c95674beb4000); /// /// Waits for the specified time in seconds. Supports fractions of seconds. @@ -285,26 +281,51 @@ EXPORT void *LibCallg(void **const a, void *(*const routine)()) } DEFINE_INITIALIZESOCKETS; -EXPORT uint32_t LibGetHostAddr(const char *const name) +EXPORT int _LibGetHostAddr(const char *name, const char *portstr, struct sockaddr *sin) { INITIALIZESOCKETS; - uint32_t addr = 0; struct addrinfo *entry, *info = NULL; - const struct addrinfo hints = {0, AF_INET, SOCK_STREAM, 0, - 0, NULL, NULL, NULL}; - if (!getaddrinfo(name, NULL, &hints, &info)) + const struct addrinfo hints = {0, sin->sa_family, 0, 0, 0, NULL, NULL, NULL}; + uint32_t port = 0; + const char *service = portstr; + if (portstr && (sin->sa_family == AF_INET || sin->sa_family == AF_INET6)) { - for (entry = info; entry && !entry->ai_addr; entry = entry->ai_next) - ; - if (entry) + port = (uint32_t)strtol(portstr, NULL, 0); + if (port && port <= 0xFFFF) { - const struct sockaddr_in *addrin = (struct sockaddr_in *)entry->ai_addr; - addr = *(uint32_t *)&addrin->sin_addr; + port = htons(port); + service = NULL; + } + else + { + port = 0; } - if (info) - freeaddrinfo(info); } - return addr == 0xffffffff ? 0 : addr; + if (!getaddrinfo(name, service, &hints, &info) && info) + { + for (entry = info; entry; entry = entry->ai_next) + { + if (entry->ai_addr) + { + *sin = *entry->ai_addr; + if (port) + { + if (sin->sa_family == AF_INET) + { + ((struct sockaddr_in *)sin)->sin_port = port; + } + else if (sin->sa_family == AF_INET6) + { + ((struct sockaddr_in6 *)sin)->sin6_port = port; + } + } + break; + } + } + freeaddrinfo(info); + return C_OK; + } + return C_ERROR; } #ifdef _WIN32 @@ -497,6 +518,18 @@ EXPORT int TranslateLogicalXd(const mdsdsc_t *const in, EXPORT void MdsFree(void *const ptr) { free(ptr); } +EXPORT void MdsFreeDescriptor(mdsdsc_t *d) +{ + if (d) + { + if (d->class == CLASS_XD) + MdsFree1Dx((mdsdsc_xd_t *)d, NULL); + else if (d->class == CLASS_D) + free(d->pointer); + free(d); + } +} + EXPORT char *MdsDescrToCstring(const mdsdsc_t *const in) { char *out = malloc((size_t)in->length + 1); @@ -506,17 +539,14 @@ EXPORT char *MdsDescrToCstring(const mdsdsc_t *const in) return out; } -// int LibSigToRet() -//{ -// return 1; -//} - -STATIC_THREADSAFE char *FIS_Error = ""; - -EXPORT char *LibFindImageSymbolErrString() { return FIS_Error; } +EXPORT char *LibFindImageSymbolErrString() +{ + MDSTHREADSTATIC_INIT; + return MDS_FIS_ERROR; +} -static void *loadLib(const char *const dirspec, const char *const filename, - char *errorstr) +static void *load_lib(const char *const dirspec, const char *const filename, + char *errorstr) { void *handle = NULL; char *full_filename = alloca(strlen(dirspec) + strlen(filename) + 10); @@ -535,7 +565,7 @@ static void *loadLib(const char *const dirspec, const char *const filename, { strcpy(full_filename, filename); } -#ifndef _WIN32 +#ifdef RTLD_NOLOAD handle = dlopen(full_filename, RTLD_NOLOAD | RTLD_LAZY); if (!handle) #endif @@ -552,9 +582,8 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, const char *const symbol, void **symbol_value) { int status; - static pthread_mutex_t dlopen_mutex = PTHREAD_MUTEX_INITIALIZER; - pthread_mutex_lock(&dlopen_mutex); - pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&dlopen_mutex); + static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + MUTEX_LOCK_PUSH(&lock); if (*symbol_value) // already loaded status = 1; else @@ -582,7 +611,7 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, { strcat(filename, SHARELIB_TYPE); } - handle = loadLib("", filename, errorstr); + handle = load_lib("", filename, errorstr); if (handle == NULL && (strchr(filename, '/') == 0) && (strchr(filename, '\\') == 0)) { @@ -596,7 +625,7 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, char *dptr = strchr(libpath + offset, delim); if (dptr) *dptr = '\0'; - handle = loadLib(libpath + offset, filename, errorstr); + handle = load_lib(libpath + offset, filename, errorstr); if (handle) break; offset = offset + strlen(libpath + offset) + 1; @@ -610,7 +639,7 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, { char *libdir = alloca(strlen(mdir) + 10); sprintf(libdir, "%s/%s", mdir, "lib"); - handle = loadLib(libdir, filename, errorstr); + handle = load_lib(libdir, filename, errorstr); } } } @@ -623,20 +652,20 @@ EXPORT int LibFindImageSymbol_C(const char *const filename_in, "Error: %s\n", dlerror()); } } - if (strlen(FIS_Error) > 0) - { - free(FIS_Error); - FIS_Error = ""; - } + MDSTHREADSTATIC_INIT; + free(MDS_FIS_ERROR); if (*symbol_value == NULL) { - FIS_Error = strdup(errorstr); + MDS_FIS_ERROR = strdup(errorstr); status = LibKEYNOTFOU; } else + { + MDS_FIS_ERROR = NULL; status = 1; + } } - pthread_cleanup_pop(1); + MUTEX_LOCK_POP(&lock); return status; } @@ -843,15 +872,11 @@ EXPORT int StrRight(mdsdsc_t *const out, const mdsdsc_t *const in, } static pthread_mutex_t zones_lock = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_ZONES \ - pthread_mutex_lock(&zones_lock); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &zones_lock) -#define UNLOCK_ZONES pthread_cleanup_pop(1); +#define LOCK_ZONES MUTEX_LOCK_PUSH(&zones_lock) +#define UNLOCK_ZONES MUTEX_LOCK_POP(&zones_lock) ZoneList *MdsZones = NULL; -#define LOCK_ZONE(zone) \ - pthread_mutex_lock(&(zone)->lock); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &(zone)->lock) -#define UNLOCK_ZONE(zone) pthread_cleanup_pop(1); +#define LOCK_ZONE(zone) MUTEX_LOCK_PUSH(&(zone)->lock) +#define UNLOCK_ZONE(zone) MUTEX_LOCK_POP(&(zone)->lock) EXPORT int LibCreateVmZone(ZoneList **const zone) { @@ -925,49 +950,54 @@ EXPORT int LibResetVmZone(ZoneList **const zone) return MDSplusSUCCESS; } -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wclobbered" - -EXPORT int LibFreeVm(const uint32_t *const len, void **const vm, - ZoneList **const zone) +static VmList *ZoneList_remove_VmList(ZoneList **zone, void *vm) { - VmList *list = NULL; - if (zone) + VmList *list; + LOCK_ZONE(*zone); + VmList **prev = &(*zone)->vm; + for (list = (*zone)->vm; list; prev = &list->next, list = list->next) { - LOCK_ZONE(*zone); - VmList *prev; - for (prev = NULL, list = (*zone)->vm; list && (list->ptr != *vm); - prev = list, list = list->next) - ; - if (list) + if (list->ptr == vm) { - if (prev) - prev->next = list->next; - else - (*zone)->vm = list->next; + *prev = list->next; + break; } - UNLOCK_ZONE(*zone); } - if (len && *len && vm && *vm) + UNLOCK_ZONE(*zone); + return list; +} + +static void ZoneList_add_VmList(ZoneList **zone, VmList *list) +{ + LOCK_ZONE(*zone); + list->next = (*zone)->vm; + (*zone)->vm = list; + UNLOCK_ZONE(*zone); +} + +EXPORT int LibFreeVm(const uint32_t *len, void **vm, ZoneList **zone) +{ + (void)len; + if (vm && *vm) + { free(*vm); - free(list); + if (zone) + { + free(ZoneList_remove_VmList(zone, *vm)); + } + } return MDSplusSUCCESS; } -#pragma GCC diagnostic pop - -EXPORT int libfreevm_(const uint32_t *const len, void **const vm, - ZoneList **const zone) +EXPORT int libfreevm_(const uint32_t *len, void **vm, ZoneList **zone) { return LibFreeVm(len, vm, zone); } -EXPORT int libfreevm(const uint32_t *const len, void **const vm, - ZoneList **const zone) +EXPORT int libfreevm(const uint32_t *len, void **vm, ZoneList **zone) { return LibFreeVm(len, vm, zone); } -EXPORT int LibGetVm(const uint32_t *const len, void **const vm, - ZoneList **const zone) +EXPORT int LibGetVm(const uint32_t *len, void **vm, ZoneList **zone) { *vm = malloc(*len); if (*vm == NULL) @@ -979,29 +1009,19 @@ EXPORT int LibGetVm(const uint32_t *const len, void **const vm, { VmList *list = malloc(sizeof(VmList)); list->ptr = *vm; - LOCK_ZONE(*zone); - list->next = (*zone)->vm; - (*zone)->vm = list; - UNLOCK_ZONE(*zone); + ZoneList_add_VmList(zone, list); } return MDSplusSUCCESS; } -EXPORT int libgetvm_(const uint32_t *const len, void **const vm, - ZoneList **const zone) +EXPORT int libgetvm_(const uint32_t *len, void **vm, ZoneList **zone) { return LibGetVm(len, vm, zone); } -EXPORT int libgetvm(const uint32_t *const len, void **const vm, - ZoneList **const zone) +EXPORT int libgetvm(const uint32_t *len, void **vm, ZoneList **zone) { return LibGetVm(len, vm, zone); } -// int LibEstablish() -//{ -// return 1; -//} - #define SEC_PER_DAY (60 * 60 * 24) EXPORT int LibConvertDateString(const char *asc_time, int64_t *const qtime) @@ -1335,8 +1355,7 @@ static int MdsInsertTree(struct bbtree_info *const bbtree_ptr) return MDSplusERROR; } save_current = currentNode; - if ((in_balance = (*(bbtree_ptr->compare_routine))( - bbtree_ptr->keyname, currentNode, bbtree_ptr->user_context)) <= 0) + if ((in_balance = (*(bbtree_ptr->compare_routine))(bbtree_ptr->keyname, currentNode, bbtree_ptr->user_context)) <= 0) { if ((in_balance == 0) && (!(bbtree_ptr->controlflags & 1))) { @@ -1830,10 +1849,10 @@ static size_t findfileloop(ctx_t *const ctx) return ctx->stack[ctx->cur_stack].wlen + flen; if (ctx->recursive && ISDIRECTORY(ctx)) { - // DBG("path = %s\n", ctx->buffer); + // MDSDBG("path = %s", ctx->buffer); if (++ctx->cur_stack == ctx->max_stack) { - DBG("max_stack increased = %d\n", ctx->max_stack); + MDSDBG("max_stack increased = %d", ctx->max_stack); findstack_t *old = ctx->stack; ctx->max_stack *= 2; ctx->stack = malloc(sizeof(findstack_t) * ctx->max_stack); @@ -1858,7 +1877,7 @@ static inline void *_findfilestart(const char *const envname, const char *const filename, const int recursive, const int case_blind) { - DBG("looking for '%s' in '%s'\n", filename, envname); + MDSDBG("looking for '%s' in '%s'", filename, envname); ctx_t *ctx = (ctx_t *)malloc(sizeof(ctx_t)); ctx->max_stack = recursive ? 8 : 1; ctx->stack = malloc(ctx->max_stack * sizeof(findstack_t)); @@ -2074,51 +2093,6 @@ EXPORT int LibFindFileCaseBlind(const mdsdsc_t *const filespec, EXPORT void TranslateLogicalFree(char *const value) { free(value); } -#ifdef LOBYTE -#undef LOBYTE -#endif -#ifdef HIBYTE -#undef HIBYTE -#endif -#define LOBYTE(x) ((x)&0xFF) -#define HIBYTE(x) (((x) >> 8) & 0xFF) - -/* -// Cyclic redundancy check but seems unused -static uint16_t icrc1(const uint16_t crc) -{ - int i; - uint32_t ans = crc; - for (i = 0; i < 8; i++) { - if (ans & 0x8000) { - ans <<= 1; - ans = ans ^ 4129; - } else - ans <<= 1; - } - return (uint16_t)ans; -} -uint16_t Crc(const uint32_t len, uint8_t *const bufptr) -{ - STATIC_THREADSAFE pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; - STATIC_THREADSAFE uint16_t icrctb[256], init = 0; - pthread_mutex_lock(&mutex); - // STATIC_THREADSAFE unsigned char rchr[256]; - //STATIC_CONSTANT unsigned it[16] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, -3, 11, 7, 15 }; if (!init) { init = 1; int i; for (i = 0; i < 256; i++) { - icrctb[i] = icrc1((uint16_t)(i << 8)); - // rchr[i] = (unsigned char)(it[i & 0xF] << 4 | it[i >> 4]); - } - } - int cword = 0; - uint32_t j; - for (j = 0; j < len; j++) - cword = icrctb[bufptr[j] ^ HIBYTE(cword)] ^ LOBYTE(cword) << 8; - pthread_mutex_unlock(&mutex); - return (uint16_t)cword; -} -*/ - EXPORT int MdsPutEnv(const char *const cmd) { /* cmd action @@ -2138,12 +2112,12 @@ EXPORT int MdsPutEnv(const char *const cmd) if (*value) { *(value++) = '\0'; - DBG("setenv %s=%s\n", name, value); + MDSDBG("setenv %s=%s", name, value); status = setenv(name, value, 1); } else { - DBG("unsetenv %s\n", name); + MDSDBG("unsetenv %s", name); status = unsetenv(name); } status = status ? MDSplusERROR : MDSplusSUCCESS; diff --git a/mdsshr/mds_dsc_string.c b/mdsshr/mds_dsc_string.c index 04500b70fa..d6cecbf323 100644 --- a/mdsshr/mds_dsc_string.c +++ b/mdsshr/mds_dsc_string.c @@ -22,7 +22,6 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include #include #include #include diff --git a/mdsshr/mdsthreadstatic.h b/mdsshr/mdsthreadstatic.h index 7906dc5e80..69f8f4a1d8 100644 --- a/mdsshr/mdsthreadstatic.h +++ b/mdsshr/mdsthreadstatic.h @@ -7,7 +7,8 @@ #define THREADSTATIC_TDISHR 1 #define THREADSTATIC_TREESHR 2 #define THREADSTATIC_DCLSHR 3 -#define THREADSTATIC_SIZE 4 +#define THREADSTATIC_MDSIP 4 +#define THREADSTATIC_SIZE 5 typedef struct { @@ -50,9 +51,11 @@ typedef struct char MdsMsg_cstr[1024]; char MdsGetMsg_cstr[1024]; mdsdsc_t MdsGetMsg_desc; + char *librtl_fis_error; } MDSTHREADSTATIC_TYPE; #define MDS_MDSMSG_CSTR MDSTHREADSTATIC_VAR->MdsMsg_cstr #define MDS_MDSGETMSG_CSTR MDSTHREADSTATIC_VAR->MdsGetMsg_cstr #define MDS_MDSGETMSG_DESC MDSTHREADSTATIC_VAR->MdsGetMsg_desc +#define MDS_FIS_ERROR MDSTHREADSTATIC_VAR->librtl_fis_error extern DEFINE_GETTHREADSTATIC(MDSTHREADSTATIC_TYPE, MdsGetThreadStatic); diff --git a/mdsshr/testing/Makefile.am b/mdsshr/testing/Makefile.am index 35fe41ca81..14500f7656 100644 --- a/mdsshr/testing/Makefile.am +++ b/mdsshr/testing/Makefile.am @@ -2,10 +2,9 @@ include @top_builddir@/Makefile.inc include ../../testing/testing.am - -AM_CFLAGS = $(TARGET_ARCH) $(WARNFLAGS) $(TEST_CFLAGS) +AM_CFLAGS = $(TARGET_ARCH) $(WARNFLAGS) $(TEST_CFLAGS) AM_CXXFLAGS = $(TARGET_ARCH) $(WARNFLAGS) -Wno-deprecated @CXXFLAGS@ $(TEST_CFLAGS) -AM_LDFLAGS = -L@MAKESHLIBDIR@ $(RPATHLINK),@MAKESHLIBDIR@ +AM_LDFLAGS = -L@MAKESHLIBDIR@ $(RPATHLINK),@MAKESHLIBDIR@ LDADD = @LIBS@ $(TEST_LIBS) -lMdsShr $(LIBSOCKET) ## ////////////////////////////////////////////////////////////////////////// ## @@ -16,30 +15,25 @@ TEST_EXTENSIONS = .py .pl AM_DEFAULT_SOURCE_EXT = .c TESTS = \ - UdpEventsTest \ - UdpEventsTestStatics + UdpEventsTest \ + UdpEventsTestStatics +UdpEventsTestStatics.o: ../UdpEvents.c VALGRIND_SUPPRESSIONS_FILES = \ $(srcdir)/valgrind.supp - # # Files produced by tests that must be purged # MOSTLYCLEANFILES = *.out - ## ////////////////////////////////////////////////////////////////////////// ## ## // TARGETS ////////////////////////////////////////////////////////////// ## ## ////////////////////////////////////////////////////////////////////////// ## - - all-local: $(TESTS) clean-local: clean-local-tests check_PROGRAMS = $(TESTS) -check_SCRIPTS = - - +check_SCRIPTS = diff --git a/mdsshr/testing/UdpEventsTest.c b/mdsshr/testing/UdpEventsTest.c index 9268ddd287..ebe01aa430 100644 --- a/mdsshr/testing/UdpEventsTest.c +++ b/mdsshr/testing/UdpEventsTest.c @@ -22,22 +22,13 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include #include -#include -#include -#include -#ifdef _WIN32 -#include -#define syscall(__NR_gettid) GetCurrentThreadId() -#else -#include -#endif #include +#include -#include - +#include +#include #include "testing.h" static pthread_mutex_t astCount_lock; @@ -49,8 +40,7 @@ static int astCount = 0; void eventAst(void *arg, int len __attribute__((unused)), char *buf __attribute__((unused))) { - printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), - (char *)arg); + printf("received event in thread %ld, name=%s\n", CURRENT_THREAD_ID(), (char *)arg); pthread_mutex_lock(&astCount_lock); astCount++; pthread_mutex_unlock(&astCount_lock); @@ -61,8 +51,7 @@ static int first = 0, second = 0; void eventAstFirst(void *arg, int len __attribute__((unused)), char *buf __attribute__((unused))) { - printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), - (char *)arg); + printf("received event in thread %ld, name=%s\n", CURRENT_THREAD_ID(), (char *)arg); pthread_mutex_lock(&first_lock); first = 1; pthread_mutex_unlock(&first_lock); @@ -71,8 +60,7 @@ void eventAstFirst(void *arg, int len __attribute__((unused)), void eventAstSecond(void *arg, int len __attribute__((unused)), char *buf __attribute__((unused))) { - printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), - (char *)arg); + printf("received event in thread %ld, name=%s\n", CURRENT_THREAD_ID(), (char *)arg); pthread_mutex_lock(&second_lock); second = 1; pthread_mutex_unlock(&second_lock); @@ -142,5 +130,5 @@ int main(int argc, char **args) status = MDSEventCan(id2); END_TESTING; - return (status & 1) == 0; + return (STATUS_OK) == 0; } diff --git a/mdsshr/testing/UdpEventsTestStatics.c b/mdsshr/testing/UdpEventsTestStatics.c index 50214ed68d..6233d7caff 100644 --- a/mdsshr/testing/UdpEventsTestStatics.c +++ b/mdsshr/testing/UdpEventsTestStatics.c @@ -24,20 +24,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include -#ifdef _WIN32 -#include -#include -#define syscall(__NR_gettid) GetCurrentThreadId() -#else -#include -#endif -#include #include #include #include +#include "../UdpEvents.c" +#include #include "testing.h" -#include <../UdpEvents.c> //////////////////////////////////////////////////////////////////////////////// // utils //////////////////////////////////////////////////////////////////// @@ -55,13 +48,20 @@ static char *_new_unique_event_name(const char *prefix, ...) return strdup(buffer); } +pthread_mutex_t astCount_mutex = PTHREAD_MUTEX_INITIALIZER; static int astCount = 0; -void eventAst(void *arg, int len __attribute__((unused)), - char *buf __attribute__((unused))) +void eventAst(void *arg, int len, char *buf) { - printf("received event in thread %ld, name=%s\n", syscall(__NR_gettid), - (char *)arg); + printf("received event in thread %ld, name=%s, len=%d\n", CURRENT_THREAD_ID(), (char *)arg, len); + char access = 0; + int i; + for (i = 0; i < len; i++) + { // this will trigger asan if len is invalid + access ^= buf[i]; + } + pthread_mutex_lock(&astCount_mutex); astCount++; + pthread_mutex_unlock(&astCount_mutex); pthread_exit(0); } @@ -91,14 +91,8 @@ void test_handleMessage() BEGIN_TESTING(UdpEvents handleMessage); char *eventName = new_unique_event_name("test_event"); - // char * eventName = strdup("event"); struct sockaddr_in serverAddr; -#ifdef _WIN32 - char flag = 1; -#else - int flag = 1; - int const SOCKET_ERROR = -1; -#endif + int one = 1; SOCKET udpSocket; char ipAddress[64]; struct ip_mreq ipMreq; @@ -117,22 +111,15 @@ void test_handleMessage() serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Allow multiple connections - TEST1(setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) != - SOCKET_ERROR); + TEST0(setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))); // bind -#ifdef _WIN32 - TEST0(bind(udpSocket, (SOCKADDR *)&serverAddr, sizeof(serverAddr))); -#else - TEST0(bind(udpSocket, (struct sockaddr *)&serverAddr, - sizeof(struct sockaddr_in))); -#endif + TEST0(bind(udpSocket, (void *)&serverAddr, sizeof(serverAddr))); getMulticastAddr(eventName, ipAddress); ipMreq.imr_multiaddr.s_addr = inet_addr(ipAddress); ipMreq.imr_interface.s_addr = INADDR_ANY; - TEST0(setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ipMreq, - sizeof(ipMreq)) < 0); + TEST0(setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ipMreq, sizeof(ipMreq))); currInfo = (struct EventInfo *)malloc(sizeof(struct EventInfo)); currInfo->eventName = strdup(eventName); @@ -142,15 +129,9 @@ void test_handleMessage() pthread_t thread; pthread_create(&thread, NULL, handleMessage, currInfo); - usleep(200000); MDSUdpEvent(eventName, strlen(eventName), eventName); pthread_join(thread, NULL); - free(eventName); - // free(currInfo->eventName); - // free(currInfo); - // *eventid = pushEvent(thread, udpSocket); - END_TESTING; } @@ -203,40 +184,6 @@ void test_popEvent() END_TESTING } -//////////////////////////////////////////////////////////////////////////////// -// Suppression /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -static void *_thread_action(void *arg) -{ - (void)arg; - int status __attribute__((unused)); - status = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); - status = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); - while (1) - { - // do nothing .. // - } - return NULL; -} - -void test_pthread_cancel_Suppresstion() -{ - pthread_t thread[10]; - int i; - for (i = 0; i < 10; ++i) - { - pthread_create(&thread[i], NULL, _thread_action, NULL); - pthread_detach(thread[i]); - } - usleep(10000); - for (i = 0; i < 10; ++i) - { - while (pthread_cancel(thread[i]) != 0) - ; - } -} - //////////////////////////////////////////////////////////////////////////////// // MAIN ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// @@ -247,9 +194,5 @@ int main(int argc __attribute__((unused)), test_handleMessage(); test_pushEvent(); test_popEvent(); - - // generate a suppression for pthread_cancel valgrind issue // - // test_pthread_cancel_Suppresstion(); - return 0; } diff --git a/mdstcpip/Makefile.in b/mdstcpip/Makefile.in index 4f842115c9..c232f61552 100644 --- a/mdstcpip/Makefile.in +++ b/mdstcpip/Makefile.in @@ -44,31 +44,42 @@ endif #SHARETYPE ## MdsIpShr sources ## -LIB_SOURCES = $(wildcard @srcdir@/mdsipshr/*.c) -LIB_OBJECTS = $(LIB_SOURCES:@srcdir@/%.c=%.o) -$(LIB_OBJECTS): | --mdsipshr-dir +shr_srcdir = $(srcdir)/mdsipshr --mdsipshr-dir: @$(MKDIR_P) mdsipshr +LIB_SOURCES = $(wildcard $(shr_srcdir)/*.c) +LIB_OBJECTS = $(LIB_SOURCES:$(srcdir)/%.c=%.o) +LIB_HEADERS = $(srcdir)/mdsip_connections.h +$(LIB_OBJECTS): $(LIB_HEADERS) | --mdsipshr-dir SERVER_SOURCES = mdsip.c SERVER_OBJECTS = $(SERVER_SOURCES:.c=.o) - +io_srcdir = $(srcdir)/io_routines --io_routines-dir: @$(MKDIR_P) io_routines - -TCP_SOURCES = @srcdir@/io_routines/IoRoutinesTcp.c -TCP_OBJECTS = $(TCP_SOURCES:@srcdir@/%.c=%.o) -$(TCP_OBJECTS): | --io_routines-dir - -TCPV6_SOURCES = @srcdir@/io_routines/IoRoutinesTcpV6.c -TCPV6_OBJECTS = $(TCPV6_SOURCES:@srcdir@/%.c=%.o) -$(TCPV6_OBJECTS): | --io_routines-dir - - -PIPE_SOURCES = $(addprefix @srcdir@/io_routines/, IoRoutinesTunnel.c IoRoutinesThread.c) -PIPE_OBJECTS = $(PIPE_SOURCES:@srcdir@/%.c=%.o) -$(PIPE_OBJECTS): | --io_routines-dir +ETH_HEADERS = $(addprefix $(io_srcdir)/,ioroutines.h ioroutinesx.h) +ETHV6_HEADERS = $(addprefix $(io_srcdir)/,ioroutinesV6.h ioroutinesx.h) +TCP_HEADERS = $(ETH_HEADERS) $(io_srcdir)/ioroutinestcp.h +UDT_HEADERS = $(ETH_HEADERS) $(io_srcdir)/ioroutinesudt.h + +TCP_SOURCES = $(io_srcdir)/IoRoutinesTcp.c +TCP_OBJECTS = $(TCP_SOURCES:$(srcdir)/%.c=%.o) +TCPV6_SOURCES = $(io_srcdir)/IoRoutinesTcpV6.c +TCPV6_OBJECTS = $(TCPV6_SOURCES:$(srcdir)/%.c=%.o) + +UDT_SOURCES = $(io_srcdir)/IoRoutinesUdt.c +UDT_OBJECTS = $(UDT_SOURCES:$(srcdir)/%.c=%.o) +UDTV6_SOURCES = $(io_srcdir)/IoRoutinesUdtV6.c +UDTV6_OBJECTS = $(UDTV6_SOURCES:$(srcdir)/%.c=%.o) + +$(TCP_OBJECTS) $(TCPV6_OBJECTS): $(TCP_HEADERS) | --io_routines-dir +$(UDT_OBJECTS) $(UDTV6_OBJECTS): $(UDT_HEADERS) $(UDT4_OBJECTS) | --io_routines-dir + +PIPE_SOURCES = $(addprefix $(io_srcdir)/,IoRoutinesTunnel.c IoRoutinesThread.c) +PIPE_OBJECTS = $(PIPE_SOURCES:$(srcdir)/%.c=%.o) +PIPE_HEADERS = $(io_srcdir)/ioroutines_pipes.h +$(PIPE_OBJECTS): $(PIPE_HEADERS) | --io_routines-dir LIB_SOURCES += $(PIPE_SOURCES) LIB_OBJECTS += $(PIPE_OBJECTS) @@ -78,15 +89,11 @@ LIB_OBJECTS += $(PIPE_OBJECTS) UDT4_SOURCES = $(wildcard @srcdir@/udt4/src/*.cpp) $(wildcard @srcdir@/udt4/udtc/*.cpp) UDT4_OBJECTS = $(UDT4_SOURCES:@srcdir@/%.cpp=%.o) $(UDT4_OBJECTS): | --udt4-dirs -UDT_OBJECTS = io_routines/IoRoutinesUdt.o $(UDT4_OBJECTS) - -$(UDT_OBJECTS): | --io_routines-dir -UDTV6_OBJECTS = io_routines/IoRoutinesUdtV6.o $(UDT4_OBJECTS) -$(UDTV6_OBJECTS): | --io_routines-dir -CLEAN_OBJECTS = $(COMPRESSION_OBJECTS) $(LIB_OBJECTS) $(TCP_OBJECTS) $(TCPV6_OBJECTS) $(UDT_OBJECTS) $(UDTV6_OBJECTS) -ALL_SOURCES = $(LIB_SOURCES) $(TCP_SOURCES) +CLEAN_OBJECTS = $(COMPRESSION_OBJECTS) $(LIB_OBJECTS) $(UDT4_OBJECTS)\ + $(TCP_OBJECTS) $(UDT_OBJECTS) $(TCPV6_OBJECTS) $(UDTV6_OBJECTS) +ALL_SOURCES = $(LIB_SOURCES) $(TCP_SOURCES) $(TCPV6_SOURCES) $(UDT_SOURCES) $(UDTV6_SOURCES) bin_SCRIPTS = @MINGW_TRUE@bin_SCRIPTS += @MAKEBINDIR@mdsip_service.exe.manifest @@ -212,11 +219,11 @@ $(MdsIpTCP): $(TCP_OBJECTS) $(MdsIpShr) $(MdsIpTCPV6): $(TCPV6_OBJECTS) $(MdsIpShr) $(LINK.c) $(OUTPUT_OPTION) @LINKSHARED@ $(TCPV6_OBJECTS) $(LINK_MDSIPSHR) $(LIBS) -$(MdsIpUDT): $(UDT_OBJECTS) $(MdsIpShr) - $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDT_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) +$(MdsIpUDT): $(UDT_OBJECTS) $(UDT4_OBJECTS) $(MdsIpShr) + $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDT_OBJECTS) $(UDT4_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) -$(MdsIpUDTV6): $(UDTV6_OBJECTS) $(MdsIpShr) - $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDTV6_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) +$(MdsIpUDTV6): $(UDTV6_OBJECTS) $(UDT4_OBJECTS) $(MdsIpShr) + $(CXX) $(TARGET_ARCH) $(OUTPUT_OPTION) @LINKSHARED@ $(LDFLAGS) $(UDTV6_OBJECTS) $(UDT4_OBJECTS) $(CXXFLAGS) $(LINK_MDSIPSHR) $(LIBS) @MAKEETCDIR@mdsip.hosts : mdsip.hosts$(WIN) cp $< $@ diff --git a/mdstcpip/io_routines/IoRoutinesGsi.c b/mdstcpip/io_routines/IoRoutinesGsi.c index bb38f45463..01fd073a92 100644 --- a/mdstcpip/io_routines/IoRoutinesGsi.c +++ b/mdstcpip/io_routines/IoRoutinesGsi.c @@ -45,7 +45,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #undef SIZEOF_LONG #endif -#include #include #include #include @@ -122,7 +121,7 @@ static GSI_INFO *getGsiInfoC(Connection *c) size_t len; char *info_name; int readfd; - GSI_INFO *info = (GSI_INFO *)GetConnectionInfoC(c, &info_name, &readfd, &len); + GSI_INFO *info = (GSI_INFO *)ConnectionGetInfo(c, &info_name, &readfd, &len); return (info_name && strcmp(info_name, "gsi") == 0) && len == sizeof(GSI_INFO) ? info : 0; @@ -397,7 +396,7 @@ static int gsi_connect(Connection *c, char *protocol __attribute__((unused)), "GSI Set KEEPALIVE", return C_ERROR); doit(result, globus_xio_open(info.xio_handle, contact_string, attr), "Error connecting", return C_ERROR); - SetConnectionInfoC(c, "gsi", 0, &info, sizeof(info)); + ConnectionSetInfo(c, "gsi", 0, &info, sizeof(info)); return C_OK; } @@ -567,9 +566,8 @@ static int gsi_listen(int argc, char **argv) testStatus(res, "get handle to connection"); status = AcceptConnection("gsi", "gsi", 0, &info, sizeof(info), &id, &username); - if (STATUS_OK) - while (DoMessage(id)) - ; + while (STATUS_OK) + status = DoMessage(id); } return C_OK; } diff --git a/mdstcpip/io_routines/IoRoutinesThread.c b/mdstcpip/io_routines/IoRoutinesThread.c index bd194e9985..dcca25aee1 100644 --- a/mdstcpip/io_routines/IoRoutinesThread.c +++ b/mdstcpip/io_routines/IoRoutinesThread.c @@ -37,62 +37,45 @@ static int io_disconnect(Connection *c) if (p && p->pth != PARENT_THREAD) { #ifdef _WIN32 - if (WaitForSingleObject(p->pid, 0) == WAIT_TIMEOUT) + close_pipe(p->in); + close_pipe(p->out); + if (WaitForSingleObject(p->pid, 100) == WAIT_TIMEOUT) TerminateThread(p->pid, 0); CloseHandle(p->pid); #else pthread_cancel(p->pth); pthread_join(p->pth, NULL); -#endif close_pipe(p->in); close_pipe(p->out); +#endif } return C_OK; } -static void io_cleanup(void *pp) +static void io_listen(void *pp) { - void *ctx = (void *)-1; int id; - char *info_name; - io_pipes_t *info; - size_t info_len = 0; - pthread_t me = pthread_self(); - while ((id = NextConnection(&ctx, &info_name, (void *)&info, &info_len)) != - INVALID_CONNECTION_ID) + int status = AcceptConnection( + PROTOCOL, PROTOCOL, 0, pp, sizeof(io_pipes_t), &id, NULL); + free(pp); + if (STATUS_OK) { - if (info_name && strcmp(info_name, PROTOCOL) == 0 && - pthread_equal(info->pth, me)) - { - DisconnectConnection(id); - break; - } + Connection *connection = PopConnection(id); + pthread_cleanup_push((void *)destroyConnection, (void *)connection); + do + status = ConnectionDoMessage(connection); + while (STATUS_OK); + pthread_cleanup_pop(1); } - free(pp); -} - -static void io_listen(void *pp) -{ - int id, status; - pthread_cleanup_push(io_cleanup, pp); - INIT_AND_FREE_ON_EXIT(char *, username); - status = AcceptConnection("thread", "thread", 0, pp, sizeof(io_pipes_t), &id, - &username); - FREE_NOW(username); - - while (STATUS_OK) - status = DoMessage(id); - close_pipe(((io_pipes_t *)pp)->in); - close_pipe(((io_pipes_t *)pp)->out); - pthread_cleanup_pop(1); } inline static int io_connect(Connection *c, char *protocol __attribute__((unused)), char *host __attribute__((unused))) { + io_pipes_t p, *pp = calloc(1, sizeof(p)); + memset(&p, 0, sizeof(p)); #ifdef _WIN32 - io_pipes_t p = {NULL, NULL, NULL, 0}, *pp = calloc(sizeof(p), 1); pp->pth = PARENT_THREAD; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); @@ -106,7 +89,6 @@ inline static int io_connect(Connection *c, NULL))) { #else - io_pipes_t p, *pp = malloc(sizeof(p)); int pipe_up[2], pipe_dn[2], ok_up, ok_dn; ok_up = pipe(pipe_up); ok_dn = pipe(pipe_dn); @@ -130,16 +112,22 @@ inline static int io_connect(Connection *c, pp->in = pipe_up[0]; pp->out = pipe_dn[1]; pp->pth = PARENT_THREAD; - if (pthread_create(&p.pth, NULL, (void *)io_listen, pp)) + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, 0x40000); + const int err = pthread_create(&p.pth, &attr, (void *)io_listen, (void *)pp); + pthread_attr_destroy(&attr); + if (err) { #endif close_pipe(p.in); close_pipe(p.out); close_pipe(pp->out); close_pipe(pp->in); + free(pp); return C_ERROR; } - SetConnectionInfoC(c, PROTOCOL, 0, &p, sizeof(p)); + ConnectionSetInfo(c, PROTOCOL, 0, &p, sizeof(p)); return C_OK; } diff --git a/mdstcpip/io_routines/IoRoutinesTunnel.c b/mdstcpip/io_routines/IoRoutinesTunnel.c index c7e0a7e2b4..4dee5c040b 100644 --- a/mdstcpip/io_routines/IoRoutinesTunnel.c +++ b/mdstcpip/io_routines/IoRoutinesTunnel.c @@ -22,16 +22,20 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + #define PROTOCOL "tunnel" #define PROT_TUNNEL #include "ioroutines_pipes.h" +// #define DEBUG +#include + static int io_disconnect(Connection *c) { io_pipes_t *p = get_pipes(c); if (p) { -#ifdef _WIN32 +#ifdef WIN32 if (p->pid) { DWORD exitcode; @@ -64,7 +68,7 @@ static int io_disconnect(Connection *c) return C_OK; } -#ifndef _WIN32 +#ifndef WIN32 static void ChildSignalHandler(int num __attribute__((unused))) { // Ensure that the handler does not spoil errno. @@ -90,7 +94,7 @@ static void ChildSignalHandler(int num __attribute__((unused))) if (info_name && strcmp(info_name, PROTOCOL) == 0 && ((io_pipes_t *)info)->pid == pid) { - DisconnectConnection(id); + CloseConnection(id); break; } } @@ -101,7 +105,7 @@ static void ChildSignalHandler(int num __attribute__((unused))) static int io_connect(Connection *c, char *protocol, char *host) { -#ifdef _WIN32 +#ifdef WIN32 size_t len = strlen(protocol) * 2 + strlen(host) + 512; char *cmd = (char *)malloc(len); _snprintf_s(cmd, len, len - 1, @@ -160,7 +164,7 @@ static int io_connect(Connection *c, char *protocol, char *host) CloseHandle(pipe_c2p.wr); CloseHandle(pipe_p2c.rd); CloseHandle(piProcInfo.hThread); - SetConnectionInfoC(c, PROTOCOL, INVALID_SOCKET, &p, sizeof(p)); + ConnectionSetInfo(c, PROTOCOL, INVALID_SOCKET, &p, sizeof(p)); return C_OK; } fprintf(stderr, "CreateProcess"); @@ -186,7 +190,7 @@ err:; int err_c2p = pipe((int *)&pipe_c2p); if (err_p2c || err_c2p) { - perror("Error in mdsip io_connect creating pipes\n"); + perror("Error in mdsip io_connect creating pipes"); if (!err_p2c) { close(pipe_p2c.rd); @@ -202,7 +206,7 @@ err:; pid_t pid = fork(); if (pid < 0) { // error - fprintf(stderr, "Error %d from fork()\n", errno); + perror("Error from fork()"); close(pipe_c2p.rd); close(pipe_c2p.wr); close(pipe_p2c.rd); @@ -227,7 +231,7 @@ err:; sigaddset(&handler.sa_mask, SIGPIPE); sigaction(SIGCHLD, &handler, NULL); sigaction(SIGPIPE, &handler, NULL); - SetConnectionInfoC(c, PROTOCOL, INVALID_SOCKET, &p, sizeof(p)); + ConnectionSetInfo(c, PROTOCOL, INVALID_SOCKET, &p, sizeof(p)); return C_OK; } /*if (pid==0)*/ { // child @@ -247,6 +251,8 @@ err:; fcntl(pipe_p2c.rd, F_SETFD, FD_CLOEXEC); close(pipe_c2p.rd); fcntl(pipe_c2p.wr, F_SETFD, FD_CLOEXEC); + // sleep(1); // uncomment to simulate slow clients + MDSDBG("Starting client process for protocol '%s'", protocol); int err = execvp(localcmd, arglist) ? errno : 0; if (err == 2) { @@ -257,6 +263,10 @@ err:; } else if ((errno = err)) perror("Client process terminated"); + else + { + MDSDBG("Client process terminated"); + } exit(err); } #endif @@ -265,29 +275,39 @@ err:; static int io_listen(int argc __attribute__((unused)), char **argv __attribute__((unused))) { - int id, status; - INIT_AND_FREE_ON_EXIT(char *, username); -#ifdef _WIN32 - io_pipes_t p; - p.in = GetStdHandle(STD_INPUT_HANDLE); - p.out = GetStdHandle(STD_OUTPUT_HANDLE); - p.pid = NULL; + io_pipes_t pipes; + memset(&pipes, 0, sizeof(pipes)); +#ifdef WIN32 + pipes.in = GetStdHandle(STD_INPUT_HANDLE); + pipes.out = GetStdHandle(STD_OUTPUT_HANDLE); + // redirect regular stdout to stderr + HANDLE pid = GetCurrentProcess(); + HANDLE err = GetStdHandle(STD_ERROR_HANDLE); + HANDLE out; + DuplicateHandle(pid, err, pid, &out, 0, TRUE, DUPLICATE_SAME_ACCESS); + SetStdHandle(STD_OUTPUT_HANDLE, out); #else - io_pipes_t p = {0, 1, 0}; - p.in = dup(0); - p.out = dup(1); - fcntl(p.in, F_SETFD, FD_CLOEXEC); - fcntl(p.out, F_SETFD, FD_CLOEXEC); - fcntl(0, F_SETFD, FD_CLOEXEC); - close(1); // fcntl(1,F_SETFD,FD_CLOEXEC); + pipes.in = 0; // use stdin directly + pipes.out = dup(1); // use copy of stdout so we can redirect to stderr + close(1); dup2(2, 1); + fcntl(pipes.in, F_SETFD, FD_CLOEXEC); + fcntl(pipes.out, F_SETFD, FD_CLOEXEC); #endif - status = AcceptConnection(GetProtocol(), PROTOCOL, 0, &p, sizeof(p), &id, - &username); - FREE_NOW(username); - while (STATUS_OK) - status = DoMessage(id); - return C_OK; + int id; + int status = AcceptConnection( + GetProtocol(), PROTOCOL, 0, &pipes, sizeof(io_pipes_t), &id, NULL); + if (STATUS_OK) + { + Connection *connection = PopConnection(id); + pthread_cleanup_push((void *)destroyConnection, (void *)connection); + do + status = ConnectionDoMessage(connection); + while (STATUS_OK); + pthread_cleanup_pop(1); + return C_OK; + } + return C_ERROR; } const IoRoutines tunnel_routines = {io_connect, io_send, io_recv, NULL, diff --git a/mdstcpip/io_routines/ioroutines.h b/mdstcpip/io_routines/ioroutines.h index 3cd91943a9..d328c2c379 100644 --- a/mdstcpip/io_routines/ioroutines.h +++ b/mdstcpip/io_routines/ioroutines.h @@ -3,7 +3,6 @@ #define PORTDELIM ':' #define SOCKADDR_IN sockaddr_in #define SIN_FAMILY sin_family -#define SIN_ADDR sin_addr.s_addr #define SIN_PORT sin_port #define _INADDR_ANY INADDR_ANY #define GET_IPHOST(sin) char *iphost = inet_ntoa(sin.sin_addr) @@ -23,21 +22,21 @@ #include #endif -#include #include +DEFINE_INITIALIZESOCKETS; #include "../mdsip_connections.h" +#include -static int GetHostAndPort(char *hostin, struct sockaddr_in *sin); +static int GetHostAndPort(char *hostin, struct sockaddr *sin); static int io_reuseCheck(char *host, char *unique, size_t buflen) { struct sockaddr_in sin; - if (IS_OK(GetHostAndPort(host, &sin))) + if (IS_OK(GetHostAndPort(host, (struct sockaddr *)&sin))) { - uint8_t *addr = (uint8_t *)&sin.sin_addr; - snprintf(unique, buflen, "%s://%u.%u.%u.%u:%u", PROT, addr[0], addr[1], - addr[2], addr[3], (unsigned)ntohs(sin.sin_port)); + snprintf(unique, buflen, "%s://" IPADDRPRI ":%u", + PROT, IPADDRVAR(&sin.sin_addr), (unsigned)ntohs(sin.sin_port)); return C_OK; } *unique = 0; diff --git a/mdstcpip/io_routines/ioroutinesV6.h b/mdstcpip/io_routines/ioroutinesV6.h index ba107064a5..6b5f613332 100644 --- a/mdstcpip/io_routines/ioroutinesV6.h +++ b/mdstcpip/io_routines/ioroutinesV6.h @@ -3,13 +3,14 @@ #define PORTDELIM '#' #define SOCKADDR_IN sockaddr_in6 #define SIN_FAMILY sin6_family -#define SIN_ADDR sin6_addr #define SIN_PORT sin6_port #define _INADDR_ANY in6addr_any #define GET_IPHOST(sin) \ char iphost[INET6_ADDRSTRLEN]; \ inet_ntop(AF_INET6, &sin.sin6_addr, iphost, INET6_ADDRSTRLEN) +#include + #include #include #include @@ -23,17 +24,18 @@ #include #endif -#include #include +DEFINE_INITIALIZESOCKETS; + #include "../mdsip_connections.h" -#include +#include -static int GetHostAndPort(char *hostin, struct sockaddr_in6 *sin); +static int GetHostAndPort(char *hostin, struct sockaddr *sin); static int io_reuseCheck(char *host, char *unique, size_t buflen) { struct sockaddr_in6 sin; - if (IS_OK(GetHostAndPort(host, &sin))) + if (IS_OK(GetHostAndPort(host, (struct sockaddr *)&sin))) { uint16_t *addr = (uint16_t *)&sin.sin6_addr; snprintf(unique, buflen, diff --git a/mdstcpip/io_routines/ioroutines_pipes.h b/mdstcpip/io_routines/ioroutines_pipes.h index 0c454a307b..4b7a658d0b 100644 --- a/mdstcpip/io_routines/ioroutines_pipes.h +++ b/mdstcpip/io_routines/ioroutines_pipes.h @@ -22,31 +22,35 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../mdsip_connections.h" +#include #include #include #include -#include #include -#include #include #include #include #ifdef HAVE_UNISTD_H #include #endif -#ifdef _WIN32 +#ifdef WIN32 #include #define close_pipe(p) CloseHandle(p) #else #include -#define INVALID_SOCKET -1 #define close_pipe(p) close(p) #endif +#include "../mdsip_connections.h" +#include +#include + +// #define DEBUG +#include + typedef struct { -#ifdef _WIN32 +#ifdef WIN32 HANDLE out; HANDLE in; HANDLE pid; @@ -66,11 +70,11 @@ static io_pipes_t *get_pipes(Connection *c) { size_t len; char *info_name; - io_pipes_t *p = (io_pipes_t *)GetConnectionInfoC(c, &info_name, 0, &len); + io_pipes_t *p = (io_pipes_t *)ConnectionGetInfo(c, &info_name, 0, &len); return (info_name && !strcmp(PROTOCOL, info_name) && len == sizeof(io_pipes_t)) ? p - : 0; + : NULL; } static ssize_t io_send(Connection *c, const void *buffer, size_t buflen, @@ -79,21 +83,28 @@ static ssize_t io_send(Connection *c, const void *buffer, size_t buflen, io_pipes_t *p = get_pipes(c); if (!p) return -1; -#ifdef _WIN32 - ssize_t num = 0; - return WriteFile(p->out, buffer, buflen, (DWORD *)&num, NULL) ? num : -1; + ssize_t ans = 0; + errno = 0; +#ifdef WIN32 + if (!WriteFile(p->out, buffer, buflen, (DWORD *)&ans, NULL)) + ans = -1; #else - return write(p->out, buffer, buflen); + ans = write(p->out, buffer, buflen); #endif + MDSDBG("conid=%d, ans=%" PRId64 ", errno=%d: %s", + c->id, (int64_t)ans, errno, strerror(errno)); + return ans; } static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, - int to_msec) + const int to_msec) { io_pipes_t *p = get_pipes(c); if (!p) return -1; -#ifdef _WIN32 + ssize_t ans = 0; + errno = 0; +#ifdef WIN32 DWORD toval; if (to_msec < 0) toval = 0; @@ -103,8 +114,8 @@ static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, toval = to_msec; COMMTIMEOUTS timeouts = {0, 0, toval, 0, 0}; SetCommTimeouts(p->in, &timeouts); - ssize_t num = 0; - return ReadFile(p->in, buffer, buflen, (DWORD *)&num, NULL) ? num : -1; + if (!ReadFile(p->in, buffer, buflen, (DWORD *)&ans, NULL)) + ans = -1; #else struct timeval to, timeout; if (to_msec < 0) @@ -117,24 +128,42 @@ static ssize_t io_recv_to(Connection *c, void *buffer, size_t buflen, timeout.tv_sec = to_msec / 1000; timeout.tv_usec = (to_msec % 1000) * 1000; } - int sel, fd = p->in; - fd_set rf, readfds; + int fd = p->in; + fd_set readfds; FD_ZERO(&readfds); - FD_SET(fd, &readfds); - do + to = timeout; + for (;;) { // loop even for nowait for responsiveness + FD_SET(fd, &readfds); + ans = select(fd + 1, &readfds, NULL, NULL, &to); + MDSDBG("select %d, conid=%d, ans=%" PRId64 ", errno=%d: %s", + fd, c->id, (int64_t)ans, errno, strerror(errno)); + if (ans > 0) // good to go + { + ans = read(fd, buffer, buflen); + MDSDBG("read %d, conid=%d, ans=%" PRId64 ", errno=%d: %s", + fd, c->id, (int64_t)ans, errno, strerror(errno)); + break; + } + else if (ans < 0) + { + if (errno == EINTR) + continue; + if (errno != EAGAIN) + break; + } + if (to_msec >= 0) + { + ans = 0; + errno = ETIMEDOUT; + break; + } to = timeout; - rf = readfds; - sel = select(fd + 1, &rf, NULL, NULL, &to); - if (sel > 0) // good to go - return read(fd, buffer, buflen); - if (errno == EAGAIN) - continue; - if (sel < 0) // Error - return sel; - } while (to_msec < 0); - return 0; // timeout + } #endif + MDSDBG("conid=%d, ans=%" PRId64 ", errno=%d: %s", + c->id, (int64_t)ans, errno, strerror(errno)); + return ans; } static ssize_t io_recv(Connection *c, void *buffer, size_t buflen) diff --git a/mdstcpip/io_routines/ioroutinestcp.h b/mdstcpip/io_routines/ioroutinestcp.h index 0722407a18..02a9fa0b28 100644 --- a/mdstcpip/io_routines/ioroutinestcp.h +++ b/mdstcpip/io_routines/ioroutinestcp.h @@ -1,94 +1,14 @@ #define _TCP -DEFINE_INITIALIZESOCKETS; -#ifdef _WIN32 -static void socketerror() -{ - int err; - switch (err = WSAGetLastError()) - { - case 0: - perror(""); - break; - case WSANOTINITIALISED: - fprintf(stderr, "WSANOTINITIALISED\n"); - break; - case WSAENETDOWN: - fprintf(stderr, "WSAENETDOWN\n"); - break; - case WSAEADDRINUSE: - fprintf(stderr, "WSAEADDRINUSE\n"); - break; - case WSAEINTR: - fprintf(stderr, "WSAEINTR\n"); - break; - case WSAENOTCONN: - fprintf(stderr, "WSAENOTCONN\n"); - break; - case WSAEINPROGRESS: - fprintf(stderr, "WSAEINPROGRESS\n"); - break; - case WSAEALREADY: - fprintf(stderr, "WSAEALREADY\n"); - break; - case WSAEADDRNOTAVAIL: - fprintf(stderr, "WSAEADDRNOTAVAIL\n"); - break; - case WSAEAFNOSUPPORT: - fprintf(stderr, "WSAEAFNOSUPPORT\n"); - break; - case WSAECONNREFUSED: - fprintf(stderr, "WSAECONNREFUSED\n"); - break; - case WSAENOPROTOOPT: - fprintf(stderr, "WSAENOPROTOOPT\n"); - break; - case WSAEFAULT: - fprintf(stderr, "WSAEFAULT\n"); - break; - case WSAENOTSOCK: - fprintf(stderr, "WSAENOTSOCK\n"); - break; - case WSAESHUTDOWN: - fprintf(stderr, "WSAESHUTDOWN\n"); - break; - case WSAEHOSTUNREACH: - fprintf(stderr, "WSAEHOSTUNREACH\n"); - break; - case WSAEACCES: - fprintf(stderr, "WSAEACCES\n"); - break; - default: - fprintf(stderr, "WSA %d\n", err); - } -} -#define PERROR(...) \ - do \ - { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - socketerror(); \ - } while (0) -#else -#define PERROR(...) \ - do \ - { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - perror(""); \ - } while (0) -#include -#endif #define SOCKLEN_T socklen_t #define GETPEERNAME getpeername #define SEND send #define RECV recv // active select file descriptor -static fd_set fdactive; static int io_flush(Connection *c); #include "ioroutinesx.h" -//////////////////////////////////////////////////////////////////////////////// -// CONNECT /////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// + +// CONNECT // + /// /// set socket options on the socket s for TCP protocol. This sets the receive /// buffer, the send buffer, the SO_OOBINLINE, the SO_KEEPALIVE and TCP_NODELAY @@ -97,7 +17,7 @@ static int io_flush(Connection *c); /// \param s socket to set options to /// \param reuse set SO_REUSEADDR to be able to reuse the same address. /// -static void SetSocketOptions(SOCKET s, int reuse) +static void set_socket_options(SOCKET s, int reuse) { int sendbuf = SEND_BUF_SIZE, recvbuf = RECV_BUF_SIZE; int one = 1; @@ -118,26 +38,153 @@ static void SetSocketOptions(SOCKET s, int reuse) setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *)&one, sizeof(one)); } +static int io_check(Connection *c) +{ + SOCKET sock = getSocket(c); + ssize_t err = -1; + if (sock != INVALID_SOCKET) + { + PushSocket(sock); + MSG_NOSIGNAL_ALT_PUSH(); + struct timeval timeout = {0, 0}; + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(sock, &readfds); + err = select(sock + 1, &readfds, NULL, NULL, &timeout); + switch (err) + { + case -1: + break; // Error + case 0: + break; // Timeout + default: + { // for select this will be 1 + char bptr[1]; + err = RECV(sock, bptr, 1, MSG_NOSIGNAL | MSG_PEEK); + err = (err == 1) ? 0 : -1; + break; + } + } + MSG_NOSIGNAL_ALT_POP(); + PopSocket(sock); + } + return (int)err; +} + /* io_connect() * interruptable connect implementation with optional timeout * _WIN32 requires hack to break out of select(): * create a self connected DGRAM socket and close it on SIGINT */ -#ifdef _WIN32 -static SOCKET int_sock = INVALID_SOCKET; -static void *old_handler; +#ifdef WIN32 +pthread_mutex_t int_mutex = PTHREAD_MUTEX_INITIALIZER; +static SOCKET int_socket = INVALID_SOCKET; +static uint32_t int_parallel = 0; +static void *int_handler; static void int_select(int signo) { - signal(signo, old_handler); + signal(signo, int_handler); + pthread_mutex_lock(&int_mutex); + if (int_socket != INVALID_SOCKET) + { + closesocket(int_socket); + int_socket = INVALID_SOCKET; + } + pthread_mutex_unlock(&int_mutex); raise(signo); - if (int_sock != INVALID_SOCKET) - close(int_sock); } +/// ends with int_socket set up and handler installed +static int int_setup() +{ + int sock; + pthread_mutex_lock(&int_mutex); + if (int_socket == INVALID_SOCKET) + { + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = INADDR_LOOPBACK; + int len = sizeof(addr); + int_socket = socket(AF_INET, SOCK_STREAM, 0); + bind(int_socket, (struct sockaddr *)&addr, len); + getsockname(int_socket, (struct sockaddr *)&addr, &len); + connect(int_socket, (struct sockaddr *)&addr, len); + int_handler = signal(SIGINT, int_select); + } + else if (int_parallel == 0) + { + int_handler = signal(SIGINT, int_select); + } + int_parallel++; + sock = int_socket; + pthread_mutex_unlock(&int_mutex); + return sock; +} +static void int_cleanup(void *null) +{ + (void)null; + pthread_mutex_lock(&int_mutex); + int_parallel--; + if (int_parallel == 0) + { + signal(SIGINT, int_handler); + int_handler = NULL; + } + pthread_mutex_unlock(&int_mutex); +} + +int interruptable_select(int nfds, fd_set *restrict readfds, + fd_set *restrict writefds, fd_set *restrict exceptfds, + struct timeval *restrict timeout) +{ + int err, lerrno; + static fd_set rd; + int sock = int_setup(); + pthread_cleanup_push(int_cleanup, NULL); + if (!readfds) + { + FD_ZERO(&rd); + readfds = &rd; + } + FD_SET(sock, readfds); + if (sock >= nfds) + nfds = sock + 1; + err = select(nfds, readfds, writefds, exceptfds, timeout); + lerrno = errno; + if (FD_ISSET(sock, readfds)) + { + FD_CLR(sock, readfds); + if (err > 0) + { + lerrno = EINTR; + err = -1; + } + } + pthread_cleanup_pop(1); + errno = lerrno; + return err; +} +#define IS_EINPROGRESS (WSAGetLastError() == WSAEWOULDBLOCK) +#define socket_set_nonblocking(sock) ({u_long ul = TRUE; ioctlsocket(sock, FIONBIO, &ul); }) +#define socket_set_blocking(sock) ({u_long ul = FALSE; ioctlsocket(sock, FIONBIO, &ul); }) +#else +#define IS_EINPROGRESS (errno == EINPROGRESS) +#define interruptable_select select +#define socket_set_nonblocking(sock) fcntl(sock, F_SETFL, O_NONBLOCK) +#define socket_set_blocking(sock) fcntl(sock, F_SETFL, 0) #endif + +static inline long get_timeout_sec() +{ + const char *timeout = getenv("MDSIP_CONNECT_TIMEOUT"); + if (timeout) + return strtol(timeout, NULL, 0); + return 10; +} + static int io_connect(Connection *c, char *protocol __attribute__((unused)), char *host) { - struct SOCKADDR_IN sin; + struct sockaddr sin; SOCKET sock; if (IS_NOT_OK(GetHostAndPort(host, &sin))) { @@ -148,112 +195,54 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), sock = socket(AF_T, SOCK_STREAM, 0); if (sock == INVALID_SOCKET) { - PERROR("Error creating socket"); + print_socket_error("Error creating socket"); return C_ERROR; } - struct timeval connectTimer = {0, 0}; - connectTimer.tv_sec = GetMdsConnectTimeout(); - int err; -#ifdef _WIN32 - struct timeval *timeout = connectTimer.tv_sec > 0 ? &connectTimer : NULL; - u_long ul = TRUE; - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = 0; - addr.sin_addr.s_addr = INADDR_LOOPBACK; - int len = sizeof(addr); - int_sock = socket(AF_INET, SOCK_DGRAM, 0); - bind(int_sock, (struct sockaddr *)&addr, len); - getsockname(int_sock, (struct sockaddr *)&addr, &len); - connect(int_sock, (struct sockaddr *)&addr, len); - SOCKET maxsock = sock > int_sock ? sock + 1 : int_sock + 1; - err = ioctlsocket(sock, FIONBIO, &ul); - if (err == 0) - err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); - if ((err == -1) && (WSAGetLastError() == WSAEWOULDBLOCK)) - { - fd_set rdfds, wrfds; - FD_ZERO(&wrfds); - FD_ZERO(&rdfds); - FD_SET(sock, &wrfds); - FD_SET(int_sock, &rdfds); - old_handler = signal(SIGINT, int_select); - err = select(maxsock, &rdfds, &wrfds, NULL, timeout); - signal(SIGINT, old_handler); - if (err < 1) - { - if (err < 0) - PERROR("Error in connect"); - else - fprintf(stderr, "Error in connect: timeout ?!\n"); - close(int_sock); - goto error; - } - if (FD_ISSET(int_sock, &rdfds)) - { - errno = EINTR; - perror("Error in connect"); - goto error; - } - close(int_sock); - socklen_t len = sizeof(err); - getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &len); - } - ul = FALSE; - ioctlsocket(sock, FIONBIO, &ul); -#else // _WIN32 - if (connectTimer.tv_sec) + struct timeval connectTimer = {.tv_sec = get_timeout_sec(), .tv_usec = 0}; + socket_set_nonblocking(sock); + int err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); + if (err == -1) { - err = fcntl(sock, F_SETFL, O_NONBLOCK); - if (err == 0) - err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); - if ((err == -1) && (errno == EINPROGRESS)) + if (IS_EINPROGRESS) { fd_set writefds; FD_ZERO(&writefds); FD_SET(sock, &writefds); - sigset_t sigmask, origmask; - sigemptyset(&sigmask); - pthread_sigmask(SIG_SETMASK, &sigmask, &origmask); err = select(sock + 1, NULL, &writefds, NULL, &connectTimer); - pthread_sigmask(SIG_SETMASK, &origmask, NULL); if (err < 1) { if (err == 0) fprintf(stderr, "Error in connect: timeout\n"); else perror("Error in connect"); - goto error; } - socklen_t len = sizeof(err); - getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &len); + else + { + socklen_t len = sizeof(err); + getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &len); + if (err) + print_socket_error("Error in connect to service"); + else + socket_set_blocking(sock); + } } - if (err != -1) - fcntl(sock, F_SETFL, 0); } - else - err = connect(sock, (struct sockaddr *)&sin, sizeof(sin)); -#endif // !_WIN32 if (err == -1) { - PERROR("Error in connect to service"); - error:; shutdown(sock, SHUT_RDWR); - close(sock); + closesocket(sock); return C_ERROR; } - SetSocketOptions(sock, 0); - SetConnectionInfoC(c, PROT, sock, NULL, 0); + set_socket_options(sock, 0); + ConnectionSetInfo(c, PROT, sock, NULL, 0); return C_OK; } -//////////////////////////////////////////////////////////////////////////////// -// FLUSH ///////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +// FLUSH // static int io_flush(Connection *c) { -#if !defined(__sparc__) +#ifndef __sparc__ SOCKET sock = getSocket(c); if (sock != INVALID_SOCKET) { @@ -265,9 +254,11 @@ static int io_flush(Connection *c) fd_set readfds, writefds; FD_ZERO(&readfds); FD_SET(sock, &readfds); + // why write? is this how it detects a disconnection? FD_ZERO(&writefds); FD_SET(sock, &writefds); - while (((((err = select(sock + 1, &readfds, &writefds, 0, &timout)) > 0) && + MSG_NOSIGNAL_ALT_PUSH(); + while (((((err = select(sock + 1, &readfds, NULL, NULL, &timout)) > 0) && FD_ISSET(sock, &readfds)) || (err == -1 && errno == EINTR)) && tries < 10) @@ -275,7 +266,7 @@ static int io_flush(Connection *c) tries++; if (FD_ISSET(sock, &readfds)) { - err = ioctl(sock, FIONREAD, &nbytes); + err = ioctlsocket(sock, FIONREAD, &nbytes); if (nbytes > 0 && err != -1) { nbytes = recv(sock, buffer, @@ -292,38 +283,92 @@ static int io_flush(Connection *c) timout.tv_usec = 100000; FD_CLR(sock, &writefds); } + MSG_NOSIGNAL_ALT_POP(); } #endif return C_OK; } -//////////////////////////////////////////////////////////////////////////////// -// LISTEN //////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +// LISTEN // -static short getPort(char *name) +static uint16_t get_nport(char *name) { - short port; - struct servent *sp; - port = htons((short)strtol(name, NULL, 0)); - if (port == 0) + int port = strtol(name, NULL, 0); + if (port && port <= 0xFFFF) + return htons((uint16_t)port); + struct servent *sp = getservbyname(name, "tcp"); + if (!sp) { - sp = getservbyname(name, "tcp"); - if (!sp) + if (errno) { - if (errno) + fprintf(stderr, "Error: unknown service port %s/%s; %s\n", name, PROT, + strerror(errno)); + return 0; + } + fprintf(stderr, "Error: unknown service port %s/%s; default to 8000\n", + name, PROT); + return htons(8000); + } + return sp->s_port; +} + +static inline void listen_loop(SOCKET ssock, int *go) +{ + pthread_cleanup_push(destroyClientList, NULL); + struct timeval readto, timeout = {1, 0}; + fd_set readfds; + FD_ZERO(&readfds); + while (go) + { + readto = timeout; + FD_SET(ssock, &readfds); + int num = select(FD_SETSIZE, &readfds, NULL, NULL, &readto); + MDSDBG("io_listen: select = %d.", num); + if (num == 0) + { + continue; // timeout + } + else if (num > 0) + { // read ready from socket list + if (FD_ISSET(ssock, &readfds)) { - fprintf(stderr, "Error: unknown service port %s/%s; %s\n", name, PROT, - strerror(errno)); - exit(0); + struct sockaddr sin; + socklen_t len = sizeof(sin); + int id = -1; + char *username; + // ACCEPT new connection and register new socket + SOCKET sock = accept(ssock, (struct sockaddr *)&sin, &len); + if (sock == INVALID_SOCKET) + print_socket_error("Error accepting socket"); + else + set_socket_options(sock, 0); + if (IS_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username))) + { + // add client to client list // + Client *client = calloc(1, sizeof(Client)); + client->connection = PopConnection(id); + client->sock = sock; + client->username = username; + client->iphost = getHostInfo(sock, &client->host); + if (sin.sa_family == AF_INET) + { + client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; + } + dispatch_client(client); + } } - fprintf(stderr, "Error: unknown service port %s/%s; default to 8000\n", - name, PROT); - return 8000; } - port = sp->s_port; - } - return port; + else if (errno == EINTR) + { + continue; + } + else + { + print_socket_error("Error in server select, shutting down"); + break; + } + } // end LISTEN LOOP // + pthread_cleanup_pop(1); } static int io_listen(int argc, char **argv) @@ -350,150 +395,49 @@ static int io_listen(int argc, char **argv) else if (GetPortname() == 0) SetPortname("mdsip"); INITIALIZESOCKETS; + uint16_t nport = get_nport(GetPortname()); + if (nport == 0) + return C_ERROR; if (!GetMulti()) return run_server_mode(&options[1]); /// MULTIPLE CONNECTION MODE /// /// multiple connections with own context /// char *matchString[] = {"multi"}; if (CheckClient(0, 1, matchString) == ACCESS_DENIED) -#ifdef _WIN32 + { +#ifdef WIN32 // cannot change user on Windows fprintf(stderr, "WARNING: 'multi' user found hostfile but Windows cannot " "change user.\n"); #else - exit(EX_NOPERM); + errno = EX_NOPERM; + return C_ERROR; #endif - // SOCKET // - /* Create the socket and set it up to accept connections. */ + } + // Create the socket and set it up to accept connections. SOCKET ssock = socket(AF_T, SOCK_STREAM, 0); if (ssock == INVALID_SOCKET) { - PERROR("Error getting Connection Socket"); - exit(EXIT_FAILURE); + print_socket_error("Error getting Connection Socket"); + return C_ERROR; } - FD_ZERO(&fdactive); - FD_SET(ssock, &fdactive); - // OPTIONS // - SetSocketOptions(ssock, 1); - // BIND // - unsigned short port = getPort(GetPortname()); + set_socket_options(ssock, 1); struct SOCKADDR_IN sin; memset(&sin, 0, sizeof(sin)); - sin.SIN_PORT = port; sin.SIN_FAMILY = AF_T; - sin.SIN_ADDR = _INADDR_ANY; + sin.SIN_PORT = nport; if (bind(ssock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { - PERROR("Error binding to service (tcp_listen)"); - exit(EXIT_FAILURE); + print_socket_error("Error binding to service (tcp_listen)"); + return C_ERROR; } // LISTEN // if (listen(ssock, 128) < 0) { - PERROR("Error from listen"); - exit(EXIT_FAILURE); + print_socket_error("Error from listen"); + return C_ERROR; } - // LISTEN LOOP /////////////////////////////////////////////////////////// - struct timeval readto, timeout = {1, 0}; - int error_count = 0; - fd_set readfds; - for (;;) - { - readfds = fdactive; - readto = timeout; - int num = select(FD_SETSIZE, &readfds, NULL, NULL, &readto); - if (num == 0) - continue; // timeout - if (num > 0) - { - // read ready from socket list // - error_count = 0; - if (FD_ISSET(ssock, &readfds)) - { - socklen_t len = sizeof(sin); - int id = -1; - char *username; - // ACCEPT new connection and register new socket // - SOCKET sock = accept(ssock, (struct sockaddr *)&sin, &len); - if (sock == INVALID_SOCKET) - PERROR("Error accepting socket"); - else - SetSocketOptions(sock, 0); - if (IS_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username))) - { - // add client to client list // - Client *client = memset(malloc(sizeof(Client)), 0, sizeof(Client)); - client->id = id; - client->sock = sock; - client->next = ClientList; - client->username = username; - client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; - client->iphost = getHostInfo(sock, &client->host); - ClientList = client; - // add socket to active sockets // - FD_SET(sock, &fdactive); - } - } - // Process Clients in list searching for active sockets // - Client *c = ClientList; - while (c) - { - if (FD_ISSET(c->sock, &readfds)) - { - // process active socket client // - MdsSetClientAddr(c->addr); - // DO MESSAGE ---> ProcessMessage() on client c // - DoMessage(c->id); - Client *c_chk; - for (c_chk = ClientList; c_chk && c_chk != c; c_chk = c_chk->next) - ; - if (c_chk) - FD_CLR(c->sock, &readfds); - c = ClientList; - } - else - c = c->next; - } - } - else if (errno == EINTR) - { - continue; // exit(EINTR);// signal interrupt; can be triggered by python - // os.system() - } - else - { // Select returned -1 error code - error_count++; - PERROR("error in main select"); - fprintf(stderr, "Error count=%d\n", error_count); - fflush(stderr); - if (error_count > 100) - { - fprintf(stderr, "Error count exceeded, shutting down\n"); - exit(EXIT_FAILURE); - } - else - { - Client *c; - FD_ZERO(&fdactive); - if (ssock != INVALID_SOCKET) - FD_SET(ssock, &fdactive); - for (c = ClientList; c; c = c->next) - { - struct SOCKADDR_IN sin; - socklen_t n = sizeof(sin); - LockAsts(); - if (getpeername(c->sock, (struct sockaddr *)&sin, &n)) - { - fprintf(stderr, "Removed disconnected client\n"); - fflush(stderr); - CloseConnection(c->id); - } - else - FD_SET(c->sock, &fdactive); - UnlockAsts(); - } - } - } - } // end LISTEN LOOP // + int run = 1; + listen_loop(ssock, &run); return C_ERROR; } diff --git a/mdstcpip/io_routines/ioroutinesudt.h b/mdstcpip/io_routines/ioroutinesudt.h index ed1b38e340..88eb6b04cd 100644 --- a/mdstcpip/io_routines/ioroutinesudt.h +++ b/mdstcpip/io_routines/ioroutinesudt.h @@ -1,25 +1,5 @@ -#ifdef _WIN32 -#define close closesocket -#define PERROR(...) \ - do \ - { \ - errno = WSAGetLastError(); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": "); \ - perror(""); \ - } while (0) -#undef INVALID_SOCKET -#else -#define PERROR(...) \ - do \ - { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, ": %s\n", udt_getlasterror_desc()); \ - } while (0) -#endif #undef SOCKET #define SOCKET UDTSOCKET -#define INVALID_SOCKET -1 #include "udtc.h" #define SOCKLEN_T int #define GETPEERNAME udt_getpeername @@ -35,7 +15,7 @@ int server_epoll = -1; static int io_connect(Connection *c, char *protocol __attribute__((unused)), char *host) { - struct SOCKADDR_IN sin; + struct sockaddr sin; UDTSOCKET sock; if (IS_OK(GetHostAndPort(host, &sin))) { @@ -45,12 +25,12 @@ static int io_connect(Connection *c, char *protocol __attribute__((unused)), perror("Error in (udt) connect"); return C_ERROR; } - if (udt_connect(sock, (struct sockaddr *)&sin, sizeof(sin))) + if (udt_connect(sock, &sin, sizeof(sin))) { - PERROR("Error in connect to service"); + print_socket_error("Error in connect to service"); return C_ERROR; } - SetConnectionInfoC(c, PROT, sock, NULL, 0); + ConnectionSetInfo(c, PROT, sock, NULL, 0); return C_OK; } else @@ -89,12 +69,11 @@ static int io_listen(int argc, char **argv) // multiple connections with own context ///////////////////////////////// struct addrinfo *result, *rp; UDTSOCKET ssock = INVALID_SOCKET; - struct SOCKADDR_IN sin; UDTSOCKET readfds[1024]; int events = UDT_UDT_EPOLL_IN | UDT_UDT_EPOLL_ERR; int gai_stat; - static const struct addrinfo hints = {AI_PASSIVE, AF_T, SOCK_STREAM, 0, - 0, 0, 0, 0}; + static const struct addrinfo hints = { + AI_PASSIVE, AF_T, SOCK_STREAM, 0, 0, 0, 0, 0}; gai_stat = getaddrinfo(NULL, GetPortname(), &hints, &result); if (gai_stat) { @@ -117,111 +96,50 @@ static int io_listen(int argc, char **argv) continue; if (udt_bind(ssock, rp->ai_addr, rp->ai_addrlen) == 0) break; - close(ssock); + closesocket(ssock); + } + if (ssock == INVALID_SOCKET) + { + fprintf(stderr, "Error from udt_socket/bind: %s\n", udt_getlasterror_desc()); + exit(EXIT_FAILURE); } udt_epoll_add_usock(server_epoll, ssock, &events); - memset(&sin, 0, sizeof(sin)); if (udt_listen(ssock, 128) < 0) { fprintf(stderr, "Error from udt_listen: %s\n", udt_getlasterror_desc()); exit(EXIT_FAILURE); } + atexit(destroyClientList); for (;;) { - int i; - int readfds_num = 1024; - if (udt_epoll_wait2(server_epoll, readfds, &readfds_num, NULL, NULL, 5000, - NULL, NULL, NULL, NULL)) + int readfds_num = 1; + while (udt_epoll_wait2(server_epoll, readfds, &readfds_num, NULL, NULL, 5000, + NULL, NULL, NULL, NULL)) + continue; + if (readfds[0] == ssock) { - Client *c; - LockAsts(); - for (;;) + struct sockaddr sin; + int len = sizeof(sin); + int id = -1; + char *username = NULL; + UDTSOCKET sock = udt_accept(ssock, (struct sockaddr *)&sin, &len); + int status = AcceptConnection(PROT, PROT, sock, NULL, 0, &id, &username); + if (STATUS_OK) { - for (c = ClientList; c; c = c->next) + Client *client = calloc(1, sizeof(Client)); + client->connection = PopConnection(id); + client->sock = sock; + client->username = username; + client->iphost = getHostInfo(sock, &client->host); + if (sin.sa_family == AF_INET) { - int c_epoll = udt_epoll_create(); - UDTSOCKET readfds[1]; - UDTSOCKET writefds[1]; - int readnum = 1; - int writenum = 1; - udt_epoll_add_usock(c_epoll, c->sock, NULL); - int err = udt_epoll_wait2(c_epoll, readfds, &readnum, writefds, - &writenum, 0, NULL, NULL, NULL, NULL); - udt_epoll_release(c_epoll); - if (err) - { - CloseConnection(c->id); - goto next; - break; - } + client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; } - break; - next: - continue; + dispatch_client(client); } - UnlockAsts(); - } - else - { - for (i = 0; readfds_num != 1024 && i < readfds_num; i++) + else { - if (readfds[i] == ssock) - { - // int events = UDT_UDT_EPOLL_IN | UDT_UDT_EPOLL_ERR; - int len = sizeof(sin); - int id = -1; - int status; - char *username; - UDTSOCKET sock = udt_accept(ssock, (struct sockaddr *)&sin, &len); - status = - AcceptConnection(PROT, PROT, sock, NULL, 0, &id, &username); - if (STATUS_OK) - { - Client *client = - memset(malloc(sizeof(Client)), 0, sizeof(Client)); - client->id = id; - client->sock = sock; - client->next = ClientList; - client->username = username; - client->addr = ((struct sockaddr_in *)&sin)->sin_addr.s_addr; - client->iphost = getHostInfo(sock, &client->host); - ClientList = client; - udt_epoll_add_usock(server_epoll, sock, &events); - } - } - else - { - Client *c; - for (c = ClientList; c;) - { - if (c->sock == readfds[i]) - { - Client *c_chk; - int c_epoll = udt_epoll_create(); - UDTSOCKET readfds[1]; - UDTSOCKET writefds[1]; - int readnum = 1; - int writenum = 1; - udt_epoll_add_usock(c_epoll, c->sock, NULL); - int err = udt_epoll_wait2(c_epoll, readfds, &readnum, writefds, - &writenum, 0, NULL, NULL, NULL, NULL); - udt_epoll_release(c_epoll); - if (err) - { - CloseConnection(c->id); - break; - } - MdsSetClientAddr(c->addr); - DoMessage(c->id); - for (c_chk = ClientList; c_chk && c_chk != c; - c_chk = c_chk->next) - ; - c = c_chk ? c->next : ClientList; - } - else - c = c->next; - } - } + free(username); } } } diff --git a/mdstcpip/io_routines/ioroutinesx.h b/mdstcpip/io_routines/ioroutinesx.h index b09c89e200..5828cc62ec 100644 --- a/mdstcpip/io_routines/ioroutinesx.h +++ b/mdstcpip/io_routines/ioroutinesx.h @@ -1,6 +1,13 @@ #include #include +#include +#include +#include <_mdsshr.h> + +//#define DEBUG +#include + static ssize_t io_send(Connection *c, const void *buffer, size_t buflen, int nowait); static int io_disconnect(Connection *c); @@ -23,25 +30,31 @@ static IoRoutines io_routines = { #include #include #include +#include -#define IP(addr) ((uint8_t *)&addr) -#define ADDR2IP(a) IP(a) \ - [0], IP(a)[1], IP(a)[2], IP(a)[3] +#define ACCESS_NOMATCH 0 +#define ACCESS_GRANTED 1 +#define ACCESS_DENIED 2 // Connected client definition for client list typedef struct _client { struct _client *next; - SOCKET sock; - int id; + Connection *connection; + pthread_t *thread; char *username; - uint32_t addr; char *host; char *iphost; + SOCKET sock; + uint32_t addr; } Client; +#define CLIENT_PRI "%s" +#define CLIENT_VAR(c) (c)->iphost + // List of clients connected to server instance. +static pthread_mutex_t ClientListLock = PTHREAD_MUTEX_INITIALIZER; static Client *ClientList = NULL; //////////////////////////////////////////////////////////////////////////////// @@ -65,16 +78,13 @@ static SOCKET getSocket(Connection *c) size_t len; char *info_name; SOCKET readfd; - GetConnectionInfoC(c, &info_name, &readfd, &len); + ConnectionGetInfo(c, &info_name, &readfd, &len); return (info_name && strcmp(info_name, PROT) == 0) ? readfd : INVALID_SOCKET; } static pthread_mutex_t socket_list_mutex = PTHREAD_MUTEX_INITIALIZER; -static void unlock_socket_list() { pthread_mutex_unlock(&socket_list_mutex); } -#define LOCK_SOCKET_LIST \ - pthread_mutex_lock(&socket_list_mutex); \ - pthread_cleanup_push(unlock_socket_list, NULL); -#define UNLOCK_SOCKET_LIST pthread_cleanup_pop(1); +#define LOCK_SOCKET_LIST MUTEX_LOCK_PUSH(&socket_list_mutex) +#define UNLOCK_SOCKET_LIST MUTEX_LOCK_POP(&socket_list_mutex) #ifdef _TCP static void socket_list_cleanup() @@ -158,61 +168,29 @@ static void PopSocket(SOCKET socket) UNLOCK_SOCKET_LIST; } -static int GetHostAndPort(char *hostin, struct SOCKADDR_IN *sin) +static int GetHostAndPort(char *hostin, struct sockaddr *sin) { int status; - INITIALIZESOCKETS; - char *host = strdup(hostin); - FREE_ON_EXIT(host); - char *service = NULL; - size_t i; - for (i = 0; i < strlen(host) && host[i] != PORTDELIM; i++) - ; - if (i < strlen(host)) + char *port = strchr(hostin, PORTDELIM); + sin->sa_family = AF_T; + if (port) { - host[i] = '\0'; - service = &host[i + 1]; + int hostlen = port - hostin; + char *host = memcpy(malloc(hostlen + 1), hostin, hostlen); + FREE_ON_EXIT(host); + host[hostlen] = 0; + status = _LibGetHostAddr(host, port + 1, sin) + ? MDSplusERROR + : MDSplusSUCCESS; + FREE_NOW(host); } else { - service = "mdsip"; + status = _LibGetHostAddr(hostin, NULL, sin) + ? MDSplusERROR + : MDSplusSUCCESS; + ((struct SOCKADDR_IN *)sin)->SIN_PORT = htons(8000); } - if (strtol(service, NULL, 0) == 0) - { - if (!getservbyname(service, "tcp")) - { - char *env_service = getenv(service); - if ((env_service == NULL)) - { - if (strcmp(service, "mdsip") == 0) - { - service = "8000"; - } - } - else - { - service = env_service; - } - } - } - struct addrinfo *info = NULL; - static const struct addrinfo hints = {0, AF_T, SOCK_STREAM, 0, 0, 0, 0, 0}; - int err = getaddrinfo(host, service, &hints, &info); - if (err) - { - status = MDSplusERROR; - fprintf(stderr, "Error connecting to host: %s, port %s error=%s\n", host, - service, gai_strerror(err)); - } - else - { - memcpy(sin, info->ai_addr, - sizeof(*sin) < info->ai_addrlen ? sizeof(*sin) : info->ai_addrlen); - status = MDSplusSUCCESS; - } - if (info) - freeaddrinfo(info); - FREE_NOW(host); return status; } @@ -273,26 +251,24 @@ VOID CALLBACK ShutdownEvent(PVOID arg __attribute__((unused)), exit(0); } -static int getSocketHandle(char *name) +static inline SOCKET get_single_server_socket(char *name) { HANDLE shutdownEvent, waitHandle; HANDLE h; int ppid; SOCKET psock; char shutdownEventName[120]; - char *logdir = GetLogDir(); - FREE_ON_EXIT(logdir); - char *portnam = GetPortname(); - char *logfile = malloc(strlen(logdir) + strlen(portnam) + 50); - FREE_ON_EXIT(logfile); if (name == 0 || sscanf(name, "%d:%d", &ppid, (int *)&psock) != 2) { fprintf(stderr, "Mdsip single connection server can only be started from " "windows service\n"); - free(logfile); - free(logdir); exit(EXIT_FAILURE); } + char *logdir = GetLogDir(); + FREE_ON_EXIT(logdir); + char *portnam = GetPortname(); + char *logfile = malloc(strlen(logdir) + strlen(portnam) + 50); + FREE_ON_EXIT(logfile); sprintf(logfile, "%s\\MDSIP_%s_%d.log", logdir, portnam, _getpid()); freopen(logfile, "a", stdout); freopen(logfile, "a", stderr); @@ -316,6 +292,11 @@ static int getSocketHandle(char *name) return *(int *)&h; } #else +static inline SOCKET get_single_server_socket(char *name) +{ + (void)name; + return 0; +} static void ChildSignalHandler(int num __attribute__((unused))) { sigset_t set, oldset; @@ -354,8 +335,8 @@ static int io_authorize(Connection *c, char *username) Now32(now); if ((iphost = getHostInfo(sock, &hoststr))) { - printf("%s (%d) (pid %d) Connection received from %s@%s [%s]\r\n", now, - (int)sock, getpid(), username, hoststr, iphost); + fprintf(stdout, "%s (%d) (pid %d) Connection received from %s@%s [%s]\r\n", + now, (int)sock, getpid(), username, hoststr, iphost); char *matchString[2] = {NULL, NULL}; FREE_ON_EXIT(matchString[0]); FREE_ON_EXIT(matchString[1]); @@ -377,7 +358,7 @@ static int io_authorize(Connection *c, char *username) FREE_NOW(matchString[0]); } else - PERROR("error getting hostinfo"); + print_socket_error("error getting hostinfo"); FREE_NOW(iphost); FREE_NOW(hoststr); fflush(stdout); @@ -389,14 +370,17 @@ static int io_authorize(Connection *c, char *username) // SEND ////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -static ssize_t io_send(Connection *c, const void *bptr, size_t num, - int nowait) +static ssize_t io_send(Connection *c, const void *bptr, size_t num, int nowait) { SOCKET sock = getSocket(c); - int options = nowait ? MSG_DONTWAIT : 0; - if (sock != INVALID_SOCKET) - return SEND(sock, bptr, num, options | MSG_NOSIGNAL); - return -1; // sent + if (sock == INVALID_SOCKET) + return -1; + int sent; + int options = nowait ? MSG_DONTWAIT | MSG_NOSIGNAL : MSG_NOSIGNAL; + MSG_NOSIGNAL_ALT_PUSH(); + sent = SEND(sock, bptr, num, options); + MSG_NOSIGNAL_ALT_POP(); + return sent; } //////////////////////////////////////////////////////////////////////////////// @@ -410,6 +394,7 @@ static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) if (sock != INVALID_SOCKET) { PushSocket(sock); + MSG_NOSIGNAL_ALT_PUSH(); #ifdef _TCP struct timeval to, timeout; if (to_msec < 0) @@ -451,87 +436,120 @@ static ssize_t io_recv_to(Connection *c, void *bptr, size_t num, int to_msec) break; // Error } } while (to_msec < 0); // else timeout + MSG_NOSIGNAL_ALT_POP(); PopSocket(sock); } return recved; } +static inline void Client_cancel(Client *c) +{ +#ifdef _WIN32 + shutdown(c->sock, SHUT_RDWR); + closesocket(c->sock); +#else + pthread_cancel(*c->thread); +#endif +} -#ifdef _TCP -static int io_check(Connection *c) +//////////////////////////////////////////////////////////////////////////////// +// DISCONNECT //////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +static void destroyClient(Client *c) { - SOCKET sock = getSocket(c); - ssize_t err = -1; - if (sock != INVALID_SOCKET) + MDSDBG("destroyClient"); + if (c->thread) { - PushSocket(sock); - struct timeval timeout = {0, 0}; - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(sock, &readfds); - err = select(sock + 1, &readfds, NULL, NULL, &timeout); - switch (err) + if (!pthread_equal(*c->thread, pthread_self())) { - case -1: - break; // Error - case 0: - break; // Timeout - default: - { // for select this will be 1 - char bptr[1]; - err = RECV(sock, bptr, 1, MSG_NOSIGNAL || MSG_PEEK); - err = (err == 1) ? 0 : -1; - break; + Client_cancel(c); + pthread_join(*c->thread, NULL); } + else + { + pthread_detach(*c->thread); } - PopSocket(sock); + free(c->thread); + } + else + { + Connection *con = c->connection; + if (con) + { + con->io = NULL; + io_disconnect(con); + } + destroyConnection(con); } - return (int)err; + free(c->username); + free(c->iphost); + free(c->host); + free(c); } -#endif -//////////////////////////////////////////////////////////////////////////////// -// DISCONNECT //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +static inline void destroyClientList() +{ + Client *cl; + pthread_mutex_lock(&ClientListLock); + cl = ClientList; + for (; ClientList; ClientList = ClientList->next) + { + if (ClientList->thread) + { + Client_cancel(ClientList); + } + } + pthread_mutex_unlock(&ClientListLock); + while (cl) + { + Client *const c = cl; + cl = cl->next; + destroyClient(c); + } +} + +inline static Client *pop_client(Connection *con) +{ + Client *c, *p; + pthread_mutex_lock(&ClientListLock); + for (p = NULL, c = ClientList; + c; + p = c, c = c->next) + { + if (c->connection == con) + { + if (p) + p->next = c->next; + else + ClientList = c->next; + break; + } + } + pthread_mutex_unlock(&ClientListLock); + return c; +} static int io_disconnect(Connection *con) { - SOCKET sock = getSocket(con); int err = C_OK; - char now[32]; - Now32(now); + SOCKET sock = getSocket(con); + Client *c = pop_client(con); + if (c) + { + char now[32]; + Now32(now); + fprintf(stdout, "%s (%d) (pid %d) Connection disconnected from %s@%s [%s]\r\n", + now, (int)sock, getpid(), c->username, c->host, c->iphost); + c->connection = NULL; + destroyClient(c); + } if (sock != INVALID_SOCKET) { - Client *c, **p; - for (p = &ClientList, c = ClientList; c && c->id != con->id; - p = &c->next, c = c->next) - ; - if (c) - { - *p = c->next; -#ifdef _TCP - if (FD_ISSET(sock, &fdactive)) - { - FD_CLR(sock, &fdactive); -#else - if (server_epoll != -1) - { - udt_epoll_remove_usock(server_epoll, sock); -#endif - printf("%s (%d) (pid %d) Connection disconnected from %s@%s [%s]\r\n", - now, (int)sock, getpid(), c->username, c->host, c->iphost); - } - free(c->username); - free(c->iphost); - free(c->host); - free(c); - } #ifdef _TCP err = shutdown(sock, SHUT_RDWR); #endif - err = close(sock); + err = closesocket(sock); } fflush(stdout); - fflush(stderr); return err; } @@ -539,34 +557,63 @@ static int run_server_mode(Options *options) { /// SERVER MODE /////////////// /// Handle single connection /// -#ifdef _WIN32 - SOCKET sock = getSocketHandle(options->value); -#else - SOCKET sock = 0; - (void)options; -#endif + SOCKET sock = get_single_server_socket(options->value); int id; - char *username; - if (IS_NOT_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, &username))) + if (IS_NOT_OK(AcceptConnection(PROT, PROT, sock, 0, 0, &id, NULL))) return C_ERROR; struct SOCKADDR_IN sin; SOCKLEN_T len = sizeof(sin); if (GETPEERNAME(sock, (struct sockaddr *)&sin, &len) == 0) MdsSetClientAddr(((struct sockaddr_in *)&sin)->sin_addr.s_addr); - Client *client = calloc(1, sizeof(Client)); - client->id = id; - client->sock = sock; - client->next = ClientList; - client->username = username; - client->iphost = getHostInfo(sock, &client->host); - ClientList = client; -#ifdef _TCP - FD_SET(sock, &fdactive); -#endif + Connection *connection = PopConnection(id); + pthread_cleanup_push((void *)destroyConnection, (void *)connection); + int status; + do + status = ConnectionDoMessage(connection); + while (STATUS_OK); + pthread_cleanup_pop(1); + return C_ERROR; +} + +static void *client_thread(void *args) +{ + Client *client = (Client *)args; + Connection *connection = client->connection; + MdsSetClientAddr(client->addr); + pthread_cleanup_push((void *)destroyConnection, (void *)connection); int status; do { - status = DoMessage(id); + status = ConnectionDoMessage(connection); } while (STATUS_OK); - return C_ERROR; + pthread_cleanup_pop(1); + return NULL; +} + +static inline int dispatch_client(Client *client) +{ + client->thread = (pthread_t *)malloc(sizeof(pthread_t)); + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, 0x40000); + const int err = pthread_create(client->thread, &attr, client_thread, (void *)client); + pthread_attr_destroy(&attr); + if (err) + { + errno = err; + perror("dispatch_client"); + free(client->thread); + client->thread = NULL; + client->connection->id = INVALID_CONNECTION_ID; + destroyClient(client); + } + else + { + fprintf(stderr, "dispatched client " CLIENT_PRI "\n", CLIENT_VAR(client)); + pthread_mutex_lock(&ClientListLock); + client->next = ClientList; + ClientList = client; + pthread_mutex_unlock(&ClientListLock); + } + return err; } diff --git a/mdstcpip/mdsIo.h b/mdstcpip/mdsIo.h index 1763f1c2b9..56bfca1156 100644 --- a/mdstcpip/mdsIo.h +++ b/mdstcpip/mdsIo.h @@ -31,10 +31,6 @@ typedef enum #define MDS_IO_LOCK_NONE 0x00 #define MDS_IO_LOCK_NOWAIT 0x08 -#ifndef MSG_DONTWAIT -#define MSG_DONTWAIT 0 -#endif - #ifndef O_BINARY #define O_BINARY 0 #endif @@ -45,7 +41,8 @@ typedef enum #define MDSIP_VERSION_DSC_ARGS 1 #define MDSIP_VERSION_OPEN_ONE 2 -#define MDSIP_VERSION MDSIP_VERSION_OPEN_ONE +#define MDSIP_VERSION_DSC_ANS 3 +#define MDSIP_VERSION MDSIP_VERSION_DSC_ANS #define MAX_DIMS 8 diff --git a/mdstcpip/mdsip.c b/mdstcpip/mdsip.c index 2e32c8ca61..352f105e47 100644 --- a/mdstcpip/mdsip.c +++ b/mdstcpip/mdsip.c @@ -25,8 +25,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "mdsip_connections.h" +#include #include +#include "mdsip_connections.h" int main(int argc, char **argv) { diff --git a/mdstcpip/mdsip_connections.h b/mdstcpip/mdsip_connections.h index 4c0ef38afe..54fbffcbea 100644 --- a/mdstcpip/mdsip_connections.h +++ b/mdstcpip/mdsip_connections.h @@ -6,10 +6,11 @@ #ifndef _WIN32 #include #endif + +#include #include #include #include -#include #include #define MDSIP_MAX_ARGS 256 #define MDSIP_MAX_COMPRESS 9 @@ -18,15 +19,16 @@ #define NULL (void *)0 #endif -enum _mdsip_client_types +typedef enum _mdsip_client_types { + INVALID_CLIENT = 0, VMS_CLIENT = 1, IEEE_CLIENT = 2, JAVA_CLIENT = 3, VMSG_CLIENT = 4, CRAY_IEEE_CLIENT = 7, CRAY_CLIENT = 8 -}; +} client_t; typedef struct { @@ -67,38 +69,39 @@ typedef struct _connection { struct _connection *next; int id; // unique connection id - pthread_cond_t cond; con_t state; char *protocol; char *info_name; + uint16_t version; + char *rm_user; void *info; size_t info_len; - void *DBID; - unsigned char message_id; - int client_type; + uint8_t message_id; + client_t client_type; int nargs; - struct descriptor *descrip[MDSIP_MAX_ARGS]; // list for message arguments + mdsdsc_t *descrip[MDSIP_MAX_ARGS]; // list for message arguments MdsEventList *event; void *tdicontext[6]; - int addr; int compression_level; SOCKET readfd; struct _io_routines *io; - unsigned short version; - char *rm_user; } Connection; +#define CON_PRI "Connection(id=%d, state=0x%02x, protocol='%s', info_name='%s', version=%u, user='%s')" +#define CON_VAR(c) (c)->id, (c)->state, (c)->protocol, (c)->info_name, (c)->version, (c)->rm_user -#define INVALID_CONNECTION_ID 0 +#define INVALID_CONNECTION_ID -1 +#define INVALID_MESSAGE_ID 0 +#define CON_ACTIVITY (con_t)0x7F #define CON_IDLE (con_t)0x00 #define CON_CONNECT (con_t)0x01 #define CON_AUTHORIZE (con_t)0x02 #define CON_SEND (con_t)0x04 #define CON_FLUSH (con_t)0x08 #define CON_RECV (con_t)0x10 -#define CON_SENDARG (con_t)0x20 +#define CON_REQUEST (con_t)0x20 #define CON_USER (con_t)0x40 -#define CON_DISCONNECT (con_t)0x80 +#define CON_INLIST (con_t)0x80 #if defined(__CRAY) || defined(CRAY) int errno = 0; @@ -136,10 +139,15 @@ typedef struct typedef struct { MsgHdr h; - char bytes[1]; + char bytes[0]; } Message, *MsgPtr; +#define MESSAGE_PRI "Message(msglen=%d, status=%d, length=%d, " \ + "nargs=%d, descriptor_idx=%d, message_id=%d, " \ + "dtype=%d, client_type=%d, header.ndims=%d)" +#define MESSAGE_VAR(c) (c)->h.msglen, (c)->h.status, (c)->h.length, \ + (c)->h.nargs, (c)->h.descriptor_idx, (c)->h.message_id, \ + (c)->h.dtype, (c)->h.client_type, (c)->h.ndims -/// /// \brief Structure for Protocol plugin anchor function /// /// | function ptr | description | @@ -256,7 +264,7 @@ EXPORT char ClientType(void); /// the server "MdsIpSrvShr" library. /// EXPORT int CloseConnection(int conid); -int CloseConnectionC(Connection *connection); // internal use +int destroyConnection(Connection *connection); // internal use //////////////////////////////////////////////////////////////////////////////// /// @@ -285,11 +293,11 @@ EXPORT int ConnectToMds(char *connection_string); /// \param id the id of connection to be disconnected /// \return true if the connection was correctly freed or false otherwise. /// -EXPORT int DisconnectConnection(int id); +EXPORT int CloseConnection(int id); //////////////////////////////////////////////////////////////////////////////// /// -/// calls DisconnectConnection for the connection id. +/// calls CloseConnection for the connection id. /// EXPORT int DisconnectFromMds(int id); @@ -306,6 +314,7 @@ EXPORT int DisconnectFromMds(int id); /// \return the status of the Process message. /// EXPORT int DoMessage(int id); +EXPORT int ConnectionDoMessage(Connection *connection); //////////////////////////////////////////////////////////////////////////////// /// @@ -317,7 +326,11 @@ EXPORT int DoMessage(int id); /// instance /// \return the Connection intance identified by id or NULL pointer of not found /// -EXPORT Connection *FindConnection(int id, Connection **prev); +EXPORT Connection *PopConnection(int id); + +client_t GetConnectionClientType(int id); + +int GetConnectionVersion(int id); extern void FlipData(Message *m); extern void FlipHeader(MsgHdr *header); @@ -390,40 +403,17 @@ EXPORT int GetCompressionLevel(); //////////////////////////////////////////////////////////////////////////////// /// -EXPORT void *GetConnectionInfoC(Connection *c, char **info_name, SOCKET *readfd, - size_t *len); +EXPORT void *ConnectionGetInfo(Connection *c, char **info_name, SOCKET *readfd, + size_t *len); EXPORT void *GetConnectionInfo(int id, char **info_name, SOCKET *readfd, size_t *len); -//////////////////////////////////////////////////////////////////////////////// -/// -/// \brief GetConnectionIo finds the Connection structure in ConnectionList and -/// returns the ioRoutines structure associated to a given Connection -/// identified by id. -/// -/// \param id id of the connection that holds the ioRoutines -/// \return ioRoutines structure in the io field of Connection element found. -/// -EXPORT IoRoutines *GetConnectionIo(int id); - EXPORT int GetContextSwitching(); - EXPORT int GetFlags(); - EXPORT char *GetHostfile(); +#ifdef _WIN32 EXPORT char *GetLogDir(); -EXPORT int GetMaxCompressionLevel(); - -//////////////////////////////////////////////////////////////////////////////// -/// -/// Finds connection by id and returns its the message id -/// -/// \param id the connection id -/// \return message_id field of selected connection or 0 as no connection found -/// -EXPORT unsigned char GetConnectionMessageId(int id); - -EXPORT int GetMdsConnectTimeout(); +#endif //////////////////////////////////////////////////////////////////////////////// /// @@ -461,24 +451,10 @@ Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec); /// multiple connections each with own context) /// EXPORT unsigned char GetMulti(); - EXPORT char *GetPortname(); - EXPORT char *GetProtocol(); - EXPORT SOCKET GetSocketHandle(); -//////////////////////////////////////////////////////////////////////////////// -/// -/// Finds the Connection intance held in the list of connections by id and -/// increments the connection message id. -/// -/// \param id id of the connection -/// \return the incremented connection message id or 0 if connection was not -/// found. -/// -EXPORT unsigned char IncrementConnectionMessageId(int id); - //////////////////////////////////////////////////////////////////////////////// /// /// This is the dynamic protocol loader. The mdsshr lib routines are used to @@ -693,8 +669,8 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options); /// EXPORT void SetConnectionInfo(int conid, char *info_name, SOCKET readfd, void *info, size_t len); -EXPORT void SetConnectionInfoC(Connection *c, char *info_name, SOCKET readfd, - void *info, size_t len); +EXPORT void ConnectionSetInfo(Connection *c, char *info_name, SOCKET readfd, + void *info, size_t len); EXPORT int SetCompressionLevel(int setting); @@ -704,10 +680,6 @@ EXPORT int SetFlags(int flags); EXPORT char *SetHostfile(char *newhostfile); -EXPORT int SetMaxCompressionLevel(int setting); - -EXPORT int SetMdsConnectTimeout(int sec); - EXPORT unsigned char SetMulti(unsigned char setting); EXPORT char *SetPortname(char *); @@ -722,8 +694,7 @@ EXPORT void UnlockAsts(); /// /// Finds the Connection intance held in the list of connections by id and sets /// the compression level indicated in arguments. Compression level spans from -/// 0 (no compression) to \ref GetMaxCompressionLevel (maximum compression -/// level usually the integer value 9) +/// 0 (no compression) to 9 /// /// \param conid id of the Connection to set the compression /// \param compression the compression level to set @@ -756,9 +727,9 @@ EXPORT int GetConnectionCompression(int conid); /// \return The new instanced connection id or -1 if error occurred. /// -Connection *NewConnectionC(char *protocol); -void DisconnectConnectionC(Connection *c); -unsigned char IncrementConnectionMessageIdC(Connection *c); +Connection *newConnection(char *protocol); +EXPORT int destroyConnection(Connection *c); +unsigned char ConnectionIncMessageId(Connection *c); int AddConnection(Connection *c); Connection *FindConnectionWithLock(int id, con_t state); @@ -773,6 +744,4 @@ EXPORT int ReceiveFromConnection(int id, void *buffer, size_t buflen); // Deprecated ipaddr routines EXPORT int MdsGetClientAddr(); EXPORT void MdsSetClientAddr(int); -EXPORT char *MdsGetServerPortname(); - #endif diff --git a/mdstcpip/mdsip_service.c b/mdstcpip/mdsip_service.c index 5d792f93d4..b833955158 100644 --- a/mdstcpip/mdsip_service.c +++ b/mdstcpip/mdsip_service.c @@ -61,14 +61,10 @@ static int SpawnWorker(SOCKET sock) sc_atts.nLength = sizeof(sc_atts); sc_atts.bInheritHandle = TRUE; sc_atts.lpSecurityDescriptor = NULL; - // sprintf(cmd, - // "%s\\%s\\mdsip.exe --port=%s --hostfile=\"%s\" --compression=%d - //--sockethandle=%d:%d", getenv("MDSPLUS_DIR"), dirname, GetPortname(), - //GetHostfile(), GetMaxCompressionLevel(), _getpid(), sock); sprintf(cmd, "mdsip.exe --port=%s --hostfile=\"%s\" --compression=%d " "--sockethandle=%d:%u", - GetPortname(), GetHostfile(), GetMaxCompressionLevel(), _getpid(), + GetPortname(), GetHostfile(), GetCompressionLevel(), _getpid(), (unsigned int)sock); memset(&startupinfo, 0, sizeof(startupinfo)); startupinfo.cb = sizeof(startupinfo); diff --git a/mdstcpip/mdsipshr/CheckClient.c b/mdstcpip/mdsipshr/CheckClient.c index 7e77af53ba..b05fb621b4 100644 --- a/mdstcpip/mdsipshr/CheckClient.c +++ b/mdstcpip/mdsipshr/CheckClient.c @@ -65,11 +65,8 @@ static inline int filter_string(char **const str_ptr, const int upcase) return c - str; // is strlen } -#define ACCESS_NOMATCH 0 -#define ACCESS_GRANTED 1 -#define ACCESS_DENIED 2 #ifdef _WIN32 -#define become_user(remote_user, local_user) 1 +#define become_user(remote_user, local_user) ACCESS_GRANTED #else static int become_user(const char *remote_user, const char *local_user) diff --git a/mdstcpip/mdsipshr/ConnectToMds.c b/mdstcpip/mdsipshr/ConnectToMds.c index 584f7a9231..5036a821c7 100644 --- a/mdstcpip/mdsipshr/ConnectToMds.c +++ b/mdstcpip/mdsipshr/ConnectToMds.c @@ -26,18 +26,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include +#include #include #include #include "../mdsip_connections.h" #include "../mdsIo.h" -//////////////////////////////////////////////////////////////////////////////// -// Parse Host //////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -static void parseHost(char *hostin, char **protocol, char **host) +static void parse_host(char *hostin, char **protocol, char **host) { size_t i; *protocol = strcpy((char *)malloc(strlen(hostin) + 10), ""); @@ -64,81 +60,72 @@ static void parseHost(char *hostin, char **protocol, char **host) } } -//////////////////////////////////////////////////////////////////////////////// -// Do Login ////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// /// Execute login inside server using given connection /// /// \param id of connection (on client) to be used /// \return status o login into server 1 if success, MDSplusERROR if not authorized or error /// occurred -/// -static int doLogin(Connection *c) +static int do_login(Connection *c) { - INIT_STATUS; - Message *m; - static char *user_p; + static char *user_p = NULL; GETUSERNAME(user_p); - unsigned int length = strlen(user_p); - m = calloc(1, sizeof(MsgHdr) + length); - m->h.client_type = SENDCAPABILITIES; - m->h.length = (short)length; - m->h.msglen = sizeof(MsgHdr) + length; - m->h.dtype = DTYPE_CSTRING; - m->h.status = c->compression_level; - m->h.ndims = 1; - m->h.dims[0] = MDSIP_VERSION; - memcpy(m->bytes, user_p, length); - status = SendMdsMsgC(c, m, 0); - free(m); - if (STATUS_OK) + uint32_t length = strlen(user_p); + Message *msend = calloc(1, sizeof(MsgHdr) + length); + msend->h.client_type = SENDCAPABILITIES; + msend->h.length = (short)length; + msend->h.msglen = sizeof(MsgHdr) + length; + msend->h.dtype = DTYPE_CSTRING; + msend->h.status = c->compression_level; + msend->h.ndims = 1; + msend->h.dims[0] = MDSIP_VERSION; + memcpy(msend->bytes, user_p, length); + int status = SendMdsMsgC(c, msend, 0); + int err; + free(msend); + if (STATUS_NOT_OK) + { + perror("Error during login: send"); + err = C_ERROR; + } + else { - m = GetMdsMsgTOC(c, &status, 10000); - if (!m || STATUS_NOT_OK) + Message *mrecv = GetMdsMsgTOC(c, &status, 10000); + if (STATUS_NOT_OK) + { + perror("Error during login: recv"); + err = C_ERROR; + } + else if (!mrecv) { - printf("Error in connect\n"); - return MDSplusERROR; + fputs("Error during login: recv NULL\n", stderr); + err = C_ERROR; + } + else if (IS_NOT_OK(mrecv->h.status)) + { + fputs("Error during login: Access denied\n", stderr); + err = C_ERROR; } else { - if (IS_NOT_OK(m->h.status)) - { - printf("Error in connect: Access denied\n"); - free(m); - return MDSplusERROR; - } - // SET CLIENT COMPRESSION FROM SERVER // - c->compression_level = (m->h.status & 0x1e) >> 1; - c->client_type = m->h.client_type; - if (m->h.ndims > 0) - c->version = m->h.dims[0]; + // SET CLIENT COMPRESSION FROM SERVER + c->compression_level = (mrecv->h.status & 0x1e) >> 1; + c->client_type = mrecv->h.client_type; + if (mrecv->h.ndims > 0) + c->version = mrecv->h.dims[0]; + err = C_OK; } - free(m); + free(mrecv); } - else - { - fprintf(stderr, "Error connecting to server (DoLogin)\n"); - fflush(stderr); - return MDSplusERROR; - } - return status; + return err; } -//////////////////////////////////////////////////////////////////////////////// -// Reuse Check /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/// /// Trigger reuse check funcion for IoRoutines on host. -/// -int ReuseCheck(char *hostin, char *unique, size_t buflen) +EXPORT int ReuseCheck(char *hostin, char *unique, size_t buflen) { int ok = -1; char *host = 0; char *protocol = 0; - parseHost(hostin, &protocol, &host); + parse_host(hostin, &protocol, &host); IoRoutines *io = LoadIo(protocol); if (io) { @@ -157,27 +144,23 @@ int ReuseCheck(char *hostin, char *unique, size_t buflen) return ok; } -//////////////////////////////////////////////////////////////////////////////// -// ConnectToMds ////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -int ConnectToMds(char *hostin) +EXPORT int ConnectToMds(char *hostin) { - int id = -1; + int id = INVALID_CONNECTION_ID; char *host = 0; char *protocol = 0; if (hostin == 0) return id; - parseHost(hostin, &protocol, &host); - Connection *c = NewConnectionC(protocol); + parse_host(hostin, &protocol, &host); + Connection *c = newConnection(protocol); if (c) { if (c->io && c->io->connect) { c->compression_level = GetCompressionLevel(); - if (c->io->connect(c, protocol, host) < 0 || IS_NOT_OK(doLogin(c))) + if (c->io->connect(c, protocol, host) < 0 || do_login(c)) { - DisconnectConnectionC(c); + destroyConnection(c); } else { @@ -190,12 +173,12 @@ int ConnectToMds(char *hostin) return id; } -int DisconnectFromMds(int id) +EXPORT int DisconnectFromMds(int id) { - return DisconnectConnection(id); + return CloseConnection(id); } -void FreeMessage(void *m) +EXPORT void FreeMessage(void *m) { free(m); } \ No newline at end of file diff --git a/mdstcpip/mdsipshr/Connections.c b/mdstcpip/mdsipshr/Connections.c index a4de0e7bc6..5fd2ebbefa 100644 --- a/mdstcpip/mdsipshr/Connections.c +++ b/mdstcpip/mdsipshr/Connections.c @@ -25,134 +25,150 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include #include "../mdsip_connections.h" #include "../mdsIo.h" +#include "mdsipthreadstatic.h" #include #include -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif - -static Connection *ConnectionList = NULL; -static pthread_mutex_t connection_mutex = PTHREAD_MUTEX_INITIALIZER; +// #define DEBUG +#include -#define CONNECTIONLIST_LOCK \ - pthread_mutex_lock(&connection_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, (void *)&connection_mutex); -#define CONNECTIONLIST_UNLOCK pthread_cleanup_pop(1); - -Connection *_FindConnection(int id, Connection **prev) +Connection *_FindConnection(int id, Connection **prev, MDSIPTHREADSTATIC_ARG) { - Connection *c, *p; - for (p = 0, c = ConnectionList; c && c->id != id; p = c, c = c->next) - ; + if (id == INVALID_CONNECTION_ID) + return NULL; + Connection *c = MDSIP_CONNECTIONS, *p = NULL; + for (; c; p = c, c = c->next) + { + if (c->id == id) + break; + } if (prev) *prev = p; return c; } -Connection *FindConnection(int id, Connection **prev) +Connection *PopConnection(int id) { - Connection *c; - CONNECTIONLIST_LOCK; - c = _FindConnection(id, prev); - if (c && c->state & CON_DISCONNECT) + MDSIPTHREADSTATIC_INIT; + Connection *p, *c; + c = _FindConnection(id, &p, MDSIPTHREADSTATIC_VAR); + if (c && !(c->state & CON_INLIST)) c = NULL; - CONNECTIONLIST_UNLOCK; + else if (c) + { + c->state &= CON_ACTIVITY; // clears INLIST + if (c->state & CON_ACTIVITY) + { // if any oustanding task + struct timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + tp.tv_sec += 10; + // wait upto 10 seconds to allow current task to finish + // while exits if no other task but disconnect or on timeout + if (c->state & CON_ACTIVITY) + { + MDSDBG(CON_PRI " is waiting for lock", CON_VAR(c)); + } + c = _FindConnection(id, &p, MDSIPTHREADSTATIC_VAR); // we were waiting, so we need to update p + } + if (c) + { + // remove after task is complete + if (p) + { + p->next = c->next; + } + else + { + MDSIP_CONNECTIONS = c->next; + } + c->next = NULL; + MDSDBG(CON_PRI " popped", CON_VAR(c)); + } + } return c; } +/// Find Connection that is ready for sending +/// must be CON_IDLE or CON_REQUEST Connection *FindConnectionSending(int id) { + MDSIPTHREADSTATIC_INIT; Connection *c; - CONNECTIONLIST_LOCK; - c = _FindConnection(id, NULL); - if (c && c->state != CON_SENDARG) + c = _FindConnection(id, NULL, MDSIPTHREADSTATIC_VAR); + if (c) { - if (c->state & CON_SENDARG) + if ((c->state & CON_ACTIVITY & ~CON_REQUEST) && (c->state & CON_INLIST)) { - c->state &= CON_DISCONNECT; // preserve CON_DISCONNECT - DBG("Connection %02d -> %02x unlocked\n", c->id, c->state); - pthread_cond_signal(&c->cond); + if (c->state & CON_REQUEST) + { + c->state &= ~CON_REQUEST; // clear request + MDSDBG(CON_PRI " unlocked 0x%02x", CON_VAR(c), CON_REQUEST); + } + c = NULL; } - c = NULL; } - CONNECTIONLIST_UNLOCK; return c; } EXPORT int GetConnectionVersion(int id) { + MDSIPTHREADSTATIC_INIT; int version; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(id, NULL); + Connection *c = _FindConnection(id, NULL, MDSIPTHREADSTATIC_VAR); version = c ? (int)c->version : -1; - CONNECTIONLIST_UNLOCK; return version; } Connection *FindConnectionWithLock(int id, con_t state) { - Connection *c; - CONNECTIONLIST_LOCK; - c = _FindConnection(id, NULL); - if (c) + MDSIPTHREADSTATIC_INIT; + Connection *c = _FindConnection(id, NULL, MDSIPTHREADSTATIC_VAR); + while (c && (c->state & CON_ACTIVITY) && (c->state & CON_INLIST)) { - while (c->state & ~CON_DISCONNECT) + MDSDBG(CON_PRI " is waiting for lock 0x%02x", CON_VAR(c), state); + c = _FindConnection(id, NULL, MDSIPTHREADSTATIC_VAR); + if (c && !(c->state & CON_INLIST)) { - DBG("Connection %02d -- %02x waiting\n", c->id, state); - pthread_cond_wait(&c->cond, &connection_mutex); - } - if (c->state & CON_DISCONNECT) - { - pthread_cond_signal(&c->cond); // pass on signal c = NULL; } - else - { - DBG("Connection %02d -> %02x locked\n", c->id, state); - c->state = state; - } } - CONNECTIONLIST_UNLOCK + if (c) + { + c->state |= state & CON_ACTIVITY; + MDSDBG(CON_PRI " locked 0x%02x", CON_VAR(c), state); + } return c; } void UnlockConnection(Connection *c_in) { - CONNECTIONLIST_LOCK; + MDSIPTHREADSTATIC_INIT; Connection *c; // check if not yet freed - for (c = ConnectionList; c && c != c_in; c = c->next) - ; - if (c) + for (c = MDSIP_CONNECTIONS; c; c = c->next) { - c->state &= CON_DISCONNECT; // preserve CON_DISCONNECT - DBG("Connection %02d -> %02x unlocked\n", c->id, c->state); - pthread_cond_signal(&c->cond); + if (c == c_in) + { + c->state &= ~CON_ACTIVITY; // clear activity + MDSDBG(CON_PRI " unlocked 0x%02x", CON_VAR(c), CON_ACTIVITY); + break; + } } - CONNECTIONLIST_UNLOCK; } -#define CONNECTION_UNLOCK_PUSH(c) \ - pthread_cleanup_push((void *)UnlockConnection, (void *)c) -#define CONNECTION_UNLOCK(c) pthread_cleanup_pop(1) - int NextConnection(void **ctx, char **info_name, void **info, size_t *info_len) { // check int ans; - CONNECTIONLIST_LOCK; + MDSIPTHREADSTATIC_INIT; Connection *c, *next; - next = (*ctx != (void *)-1) ? (Connection *)*ctx : ConnectionList; - for (c = ConnectionList; c && c != next; c = c->next) + next = (*ctx != (void *)-1) ? (Connection *)*ctx : MDSIP_CONNECTIONS; + for (c = MDSIP_CONNECTIONS; c && c != next; c = c->next) ; if (c) { @@ -170,7 +186,6 @@ int NextConnection(void **ctx, char **info_name, void **info, *ctx = 0; ans = INVALID_CONNECTION_ID; } - CONNECTIONLIST_UNLOCK; return ans; } @@ -178,12 +193,11 @@ int SendToConnection(int id, const void *buffer, size_t buflen, int nowait) { int res; Connection *c = FindConnectionWithLock(id, CON_SEND); - CONNECTION_UNLOCK_PUSH(c); if (c && c->io && c->io->send) res = c->io->send(c, buffer, buflen, nowait); else res = -1; - CONNECTION_UNLOCK(c); + UnlockConnection(c); return res; } @@ -191,12 +205,11 @@ int FlushConnection(int id) { int res; Connection *c = FindConnectionWithLock(id, CON_FLUSH); - CONNECTION_UNLOCK_PUSH(c); if (c && c->io) res = c->io->flush ? c->io->flush(c) : 0; else res = -1; - CONNECTION_UNLOCK(c); + UnlockConnection(c); return res; } @@ -204,108 +217,32 @@ int ReceiveFromConnection(int id, void *buffer, size_t buflen) { int res; Connection *c = FindConnectionWithLock(id, CON_RECV); - CONNECTION_UNLOCK_PUSH(c); if (c && c->io && c->io->recv) res = c->io->recv(c, buffer, buflen); else res = -1; - CONNECTION_UNLOCK(c); + UnlockConnection(c); return res; } -static void exitHandler(void) -{ - int id; - void *ctx = (void *)-1; - while ((id = NextConnection(&ctx, 0, 0, 0)) != INVALID_CONNECTION_ID) - { - DisconnectConnection(id); - ctx = 0; - } -} -static void registerHandler() { atexit(exitHandler); } - -//////////////////////////////////////////////////////////////////////////////// -// DisconnectConnection ////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -void DisconnectConnectionC(Connection *c) -{ - // connection should not be in list at this point - c->io->disconnect(c); - free(c->info); - FreeDescriptors(c); - free(c->protocol); - free(c->info_name); - free(c->rm_user); - TreeFreeDbid(c->DBID); - pthread_cond_destroy(&c->cond); - free(c); -} - -int DisconnectConnection(int conid) -{ - Connection *p, *c; - CONNECTIONLIST_LOCK; - c = _FindConnection(conid, &p); - if (c && c->state & CON_DISCONNECT) - c = NULL; - else if (c) - { - c->state |= CON_DISCONNECT; // sets disconnect - pthread_cond_broadcast(&c->cond); - if (c->state & ~CON_DISCONNECT) - { // if any task but disconnect - struct timespec tp; - clock_gettime(CLOCK_REALTIME, &tp); - tp.tv_sec += 10; - // wait upto 10 seconds to allow current task to finish - // while exits if no other task but disconnect or on timeout - while (c->state & ~CON_DISCONNECT && - !pthread_cond_timedwait(&c->cond, &connection_mutex, &tp)) - ; - if (c->state & ~CON_DISCONNECT) - fprintf(stderr, - "DisconnectConnection: Timeout waiting for connection %d " - "state=%d\n", - conid, c->state); - c = _FindConnection(conid, &p); // we were waiting, so we need to update p - } - // remove after task is complete - if (p) - p->next = c->next; - else - ConnectionList = c->next; - } - CONNECTIONLIST_UNLOCK; - if (c) - { - DisconnectConnectionC(c); - return MDSplusSUCCESS; - } - return MDSplusERROR; -} - //////////////////////////////////////////////////////////////////////////////// // NewConnection ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -Connection *NewConnectionC(char *protocol) +Connection *newConnection(char *protocol) { Connection *connection; IoRoutines *io = LoadIo(protocol); if (io) { - RUN_FUNCTION_ONCE(registerHandler); connection = calloc(1, sizeof(Connection)); connection->io = io; - connection->readfd = -1; - connection->message_id = -1; + connection->readfd = INVALID_SOCKET; + connection->message_id = INVALID_MESSAGE_ID; connection->protocol = strdup(protocol); connection->id = INVALID_CONNECTION_ID; connection->state = CON_IDLE; - _TreeNewDbid(&connection->DBID); - pthread_cond_init(&connection->cond, NULL); + connection->compression_level = 0; return connection; } else @@ -323,39 +260,68 @@ void FreeDescriptors(Connection *c) { for (i = 0; i < MDSIP_MAX_ARGS; i++) { - if (c->descrip[i]) - { - if (c->descrip[i] != MdsEND_ARG) - { - free(c->descrip[i]->pointer); - free(c->descrip[i]); - } - c->descrip[i] = NULL; - } + MdsFreeDescriptor(c->descrip[i]); + c->descrip[i] = NULL; } } } //////////////////////////////////////////////////////////////////////////////// -// GetConnectionIo /////////////////////////////////////////////////////////// +// CloseConnection ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// +extern int TdiDeleteContext(); +extern int MDSEventCan(); +int destroyConnection(Connection *connection) +{ + if (!connection) + return MDSplusERROR; + if (connection->id != INVALID_CONNECTION_ID) + { + if (connection->state & CON_INLIST) + { + MDSIPTHREADSTATIC_INIT; + if (connection == _FindConnection(connection->id, NULL, MDSIPTHREADSTATIC_VAR)) + { + PopConnection(connection->id); + } + } + MdsEventList *e, *nexte; + for (e = connection->event; e; e = nexte) + { + nexte = e->next; + MDSEventCan(e->eventid); + if (e->info_len > 0) + free(e->info); + free(e); + } + TdiDeleteContext(connection->tdicontext); + FreeDescriptors(connection); + } + if (connection->io) + { + connection->io->disconnect(connection); + } + MDSDBG(CON_PRI " disconnected", CON_VAR(connection)); + free(connection->info); + free(connection->protocol); + free(connection->info_name); + free(connection->rm_user); + free(connection); + return MDSplusSUCCESS; +} -IoRoutines *GetConnectionIo(int conid) +int CloseConnection(int id) { - IoRoutines *io; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); - io = c ? c->io : NULL; - CONNECTIONLIST_UNLOCK; - return io; + Connection *const c = PopConnection(id); + return destroyConnection(c); } //////////////////////////////////////////////////////////////////////////////// // GetConnectionInfo ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void *GetConnectionInfoC(Connection *c, char **info_name, SOCKET *readfd, - size_t *len) +void *ConnectionGetInfo(Connection *c, char **info_name, SOCKET *readfd, + size_t *len) { if (c) { @@ -373,24 +339,23 @@ void *GetConnectionInfoC(Connection *c, char **info_name, SOCKET *readfd, void *GetConnectionInfo(int conid, char **info_name, SOCKET *readfd, size_t *len) { + MDSIPTHREADSTATIC_INIT; void *ans; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); - ans = GetConnectionInfoC(c, info_name, readfd, len); - CONNECTIONLIST_UNLOCK; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); + ans = ConnectionGetInfo(c, info_name, readfd, len); return ans; } //////////////////////////////////////////////////////////////////////////////// -// SetConnectionInfo ///////////////////////////////////////////////////////// +// ConnectionSetInfo ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -void SetConnectionInfoC(Connection *c, char *info_name, SOCKET readfd, - void *info, size_t len) +void ConnectionSetInfo(Connection *c, char *info_name, SOCKET readfd, + void *info, size_t len) { if (c) { - c->info_name = strcpy(malloc(strlen(info_name) + 1), info_name); + c->info_name = strdup(info_name); if (info) { c->info = memcpy(malloc(len), info, len); @@ -408,11 +373,9 @@ void SetConnectionInfoC(Connection *c, char *info_name, SOCKET readfd, void SetConnectionInfo(int conid, char *info_name, SOCKET readfd, void *info, size_t len) { - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); - if (c) - SetConnectionInfoC(c, info_name, readfd, info, len); - CONNECTIONLIST_UNLOCK; + MDSIPTHREADSTATIC_INIT; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); + ConnectionSetInfo(c, info_name, readfd, info, len); } //////////////////////////////////////////////////////////////////////////////// @@ -421,72 +384,37 @@ void SetConnectionInfo(int conid, char *info_name, SOCKET readfd, void *info, void SetConnectionCompression(int conid, int compression) { - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, NULL); + MDSIPTHREADSTATIC_INIT; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); if (c) c->compression_level = compression; - CONNECTIONLIST_UNLOCK; } -static inline int GetConnectionCompressionC(Connection *c) +static inline int ConnectionGetCompression(Connection *c) { return c ? c->compression_level : 0; } int GetConnectionCompression(int conid) { + MDSIPTHREADSTATIC_INIT; int complv; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, NULL); - complv = GetConnectionCompressionC(c); - CONNECTIONLIST_UNLOCK; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); + complv = ConnectionGetCompression(c); return complv; } -//////////////////////////////////////////////////////////////////////////////// -// IncrementConnectionMessageId ////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -unsigned char IncrementConnectionMessageIdC(Connection *c) +unsigned char ConnectionIncMessageId(Connection *c) { if (c) { c->message_id++; - if (c->message_id == 0) + if (c->message_id == INVALID_MESSAGE_ID) c->message_id = 1; return c->message_id; } return 0; } -unsigned char IncrementConnectionMessageId(int conid) -{ - unsigned char id; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, NULL); - id = IncrementConnectionMessageIdC(c); - CONNECTIONLIST_UNLOCK; - return id; -} - -//////////////////////////////////////////////////////////////////////////////// -// GetConnectionMessageId //////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -inline static unsigned char GetConnectionMessageIdC(Connection *c) -{ - return c ? c->message_id : 0; -} - -unsigned char GetConnectionMessageId(int conid) -{ - unsigned char id; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); - id = GetConnectionMessageIdC(c); - CONNECTIONLIST_UNLOCK; - return id; -} - /// /// Finds connection by id and sets the client_type field of the connection /// structure. \note see ClientType() function. @@ -496,11 +424,10 @@ unsigned char GetConnectionMessageId(int conid) /// void SetConnectionClientType(int conid, int client_type) { - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); + MDSIPTHREADSTATIC_INIT; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); if (c) c->client_type = client_type; - CONNECTIONLIST_UNLOCK; } /// @@ -510,13 +437,12 @@ void SetConnectionClientType(int conid, int client_type) /// \param conid the connection id /// \return client_type value stored in connection structure /// -int GetConnectionClientType(int conid) +client_t GetConnectionClientType(int conid) { - int type; - CONNECTIONLIST_LOCK; - Connection *c = _FindConnection(conid, 0); - type = c ? c->client_type : 0; - CONNECTIONLIST_UNLOCK; + MDSIPTHREADSTATIC_INIT; + client_t type; + Connection *c = _FindConnection(conid, NULL, MDSIPTHREADSTATIC_VAR); + type = c ? c->client_type : INVALID_CLIENT; return type; } @@ -540,44 +466,49 @@ static inline int authorize_client(Connection *c, char *username) //////////////////////////////////////////////////////////////////////////////// int AddConnection(Connection *c) { - static int id = 0; - CONNECTIONLIST_LOCK; - while (++id == INVALID_CONNECTION_ID && _FindConnection(++id, 0)) - ; // find next free id + MDSIPTHREADSTATIC_INIT; + static int id = INVALID_CONNECTION_ID; + static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + pthread_mutex_lock(&lock); + do + { + id++; // find next free id + } while (id == INVALID_CONNECTION_ID && _FindConnection(id, NULL, MDSIPTHREADSTATIC_VAR)); c->id = id; - c->next = ConnectionList; - ConnectionList = c; - CONNECTIONLIST_UNLOCK; + pthread_mutex_unlock(&lock); + c->state |= CON_INLIST; + c->next = MDSIP_CONNECTIONS; + MDSIP_CONNECTIONS = c; + MDSDBG("Connection %02d connected", c->id); return c->id; } int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, size_t info_len, int *id, char **usr) { - Connection *c = NewConnectionC(protocol); + if (usr) + *usr = NULL; + Connection *c = newConnection(protocol); INIT_STATUS_ERROR; if (c) { - static Message m; - Message *m_user; + Message *msg; char *user = NULL, *user_p = NULL; // SET INFO // - SetConnectionInfoC(c, info_name, readfd, info, info_len); - m_user = GetMdsMsgTOC(c, &status, 10000); - if (!m_user || STATUS_NOT_OK) + ConnectionSetInfo(c, info_name, readfd, info, info_len); + msg = GetMdsMsgTOC(c, &status, 10000); + if (!msg || STATUS_NOT_OK) { - free(m_user); - *usr = NULL; - DisconnectConnectionC(c); + free(msg); + destroyConnection(c); return MDSplusERROR; } - m.h.msglen = sizeof(MsgHdr); // AUTHORIZE // - if (STATUS_OK && (m_user) && (m_user->h.dtype == DTYPE_CSTRING)) + if (STATUS_OK && (msg) && (msg->h.dtype == DTYPE_CSTRING)) { - user = malloc(m_user->h.length + 1); - memcpy(user, m_user->bytes, m_user->h.length); - user[m_user->h.length] = 0; + user = malloc(msg->h.length + 1); + memcpy(user, msg->bytes, msg->h.length); + user[msg->h.length] = 0; } c->rm_user = user; user_p = user ? user : "?"; @@ -585,33 +516,34 @@ int AcceptConnection(char *protocol, char *info_name, SOCKET readfd, void *info, // SET COMPRESSION // if (STATUS_OK) { - c->compression_level = m_user->h.status & 0xf; - c->client_type = m_user->h.client_type; - *usr = strdup(user_p); - if (m_user->h.ndims > 0) - c->version = m_user->h.dims[0]; + c->compression_level = msg->h.status & 0xf; + c->client_type = msg->h.client_type; + if (msg->h.ndims > 0) + c->version = msg->h.dims[0]; + fprintf(stderr, "Connected: %s\n", user_p); } else - *usr = NULL; - if (STATUS_NOT_OK) + { fprintf(stderr, "Access denied: %s\n", user_p); - else - fprintf(stderr, "Connected: %s\n", user_p); - m.h.status = STATUS_OK ? (1 | (c->compression_level << 1)) : 0; - m.h.client_type = m_user ? m_user->h.client_type : 0; - m.h.ndims = 1; - m.h.dims[0] = MDSIP_VERSION; - MdsIpFree(m_user); + } + msg->h.msglen = sizeof(MsgHdr); + msg->h.status = STATUS_OK ? (1 | (c->compression_level << 1)) : 0; + msg->h.ndims = 1; + msg->h.dims[0] = MDSIP_VERSION; // reply to client // - SendMdsMsgC(c, &m, 0); + status = SendMdsMsgC(c, msg, 0); + free(msg); if (STATUS_OK) { + if (usr) + *usr = strdup(user_p); // all good add connection *id = AddConnection(c); } else - DisconnectConnectionC(c); - // fflush(stderr); stderr needs no flush + { + destroyConnection(c); + } } return status; } diff --git a/mdstcpip/mdsipshr/DoMessage.c b/mdstcpip/mdsipshr/DoMessage.c index bc5086c33e..d6bf003d15 100644 --- a/mdstcpip/mdsipshr/DoMessage.c +++ b/mdstcpip/mdsipshr/DoMessage.c @@ -22,38 +22,38 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include #include #include #include "../mdsip_connections.h" +#include +#include -extern void ProcessMessage(Connection *, Message *); +/// returns true if message cleanup is handled +extern int ProcessMessage(Connection *, Message *); //////////////////////////////////////////////////////////////////////////////// // DoMessage ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -int DoMessageC(Connection *connection) +int ConnectionDoMessage(Connection *connection) { - int status = MDSplusFATAL; if (!connection) - return status; // will cause tunnel to terminate - Message *message = GetMdsMsgTOC(connection, &status, -1); - if (STATUS_OK && !message) - status = MDSplusFATAL; - if (STATUS_OK) - { - ProcessMessage(connection, message); - } - else - { - free(message); - CloseConnectionC(connection); - } - return status; + return 0; // will cause tunnel to terminate + int err; + INIT_AND_FREE_ON_EXIT(Message *, message); + err = 1; + int status = MDSplusFATAL; + message = GetMdsMsgTOC(connection, &status, -1); + err = !(message && STATUS_OK && ProcessMessage(connection, message)); + FREE_IF(message, err); + return !err; } int DoMessage(int id) { - Connection *connection = FindConnection(id, NULL); - return DoMessageC(connection); + Connection *connection = FindConnectionWithLock(id, CON_ACTIVITY); + int ok = ConnectionDoMessage(connection); + UnlockConnection(connection); + if (!ok) + CloseConnection(id); + return ok; } diff --git a/mdstcpip/mdsipshr/GetAnswerInfo.c b/mdstcpip/mdsipshr/GetAnswerInfo.c index 666590e90d..e77f407cc9 100644 --- a/mdstcpip/mdsipshr/GetAnswerInfo.c +++ b/mdstcpip/mdsipshr/GetAnswerInfo.c @@ -52,7 +52,7 @@ __attribute__((deprecated)) int GetAnswerInfo(int id, char *dtype, //////////////////////////////////////////////////////////////////////////////// int GetAnswerInfoTS(int id, char *dtype, short *length, char *ndims, - int *dims, int *numbytes, void **dptr, void **mout) + int *dims, int *numbytes, void **dptr, void **mout) { return GetAnswerInfoTO(id, dtype, length, ndims, dims, numbytes, dptr, mout, -1); @@ -71,7 +71,7 @@ int GetAnswerInfoTO(int id, char *dtype, short *length, char *ndims, int *dims, UnlockConnection(c); if (!m && status == SsINTERNAL) { - DisconnectConnection(id); + CloseConnection(id); status = MDSplusERROR; } if (STATUS_NOT_OK) diff --git a/mdstcpip/mdsipshr/GetMdsMsg.c b/mdstcpip/mdsipshr/GetMdsMsg.c index 11e81dbbf7..a8c4f1cfb1 100644 --- a/mdstcpip/mdsipshr/GetMdsMsg.c +++ b/mdstcpip/mdsipshr/GetMdsMsg.c @@ -32,46 +32,51 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +//#define DEBUG +#include -static int get_bytes_to(Connection *c, void *buffer, size_t bytes_to_recv, - int to_msec) +static int get_bytes_to(Connection *c, void *buffer, size_t bytes_to_recv, int to_msec) { char *bptr = (char *)buffer; - if (c && c->io) + if (!c || !c->io) + return MDSplusERROR; + MDSDBG(CON_PRI " awaiting %ld bytes", CON_VAR(c), (long)bytes_to_recv); + while (bytes_to_recv > 0) { - int id = c->id; - while (bytes_to_recv > 0) + ssize_t ans; + errno = 0; + // don't use timeout if not available or requested + if (c->io->recv_to && to_msec >= 0) + ans = c->io->recv_to(c, bptr, bytes_to_recv, to_msec); + else + ans = c->io->recv(c, bptr, bytes_to_recv); + if (ans > 0) { - ssize_t bytes_recv; - if (c->io->recv_to && - to_msec >= 0) // don't use timeout if not available or requested - bytes_recv = c->io->recv_to(c, bptr, bytes_to_recv, to_msec); - else - bytes_recv = c->io->recv(c, bptr, bytes_to_recv); - if (bytes_recv > 0) - { - bytes_to_recv -= bytes_recv; - bptr += bytes_recv; - continue; - } // only exception from here on + bytes_to_recv -= ans; + bptr += ans; + continue; + } // only exception from here on + ssize_t received = bptr - (char *)buffer; + if (ans < 0) + { + MDSERR(CON_PRI " error %ld/%ld", CON_VAR(c), + (long)received, (long)(received + bytes_to_recv)); if (errno == ETIMEDOUT) return TdiTIMEOUT; - if (bytes_recv == 0 && to_msec >= 0) - return TdiTIMEOUT; if (errno == EINTR) return MDSplusERROR; if (errno == EINVAL) return SsINTERNAL; - if (errno) - { - fprintf(stderr, "Connection %d ", id); - perror("possibly lost"); - } - return SsINTERNAL; } - return MDSplusSUCCESS; + else + { + MDSDBG(CON_PRI " closed %ld/%ld", CON_VAR(c), + (long)received, (long)(received + bytes_to_recv)); + } + return SsINTERNAL; } - return MDSplusERROR; + MDSDBG(CON_PRI "got all bytes", CON_VAR(c)); + return MDSplusSUCCESS; } //////////////////////////////////////////////////////////////////////////////// @@ -89,20 +94,18 @@ Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) { if (Endian(header.client_type) != Endian(ClientType())) FlipHeader(&header); -#ifdef DEBUG - printf("msglen = %d\nstatus = %d\nlength = %d\nnargs = " - "%d\ndescriptor_idx = %d\nmessage_id = %d\ndtype = %d\n", + MDSDBG("Message(msglen = %d, status = %d, length = %d, nargs = %d, " + "descriptor_idx = %d, message_id = %d, dtype = %d, " + "client_type = %d, header.ndims = %d)", header.msglen, header.status, header.length, header.nargs, - header.descriptor_idx, header.message_id, header.dtype); - printf("client_type = %d\nndims = %d\n", header.client_type, - header.ndims); -#endif + header.descriptor_idx, header.message_id, header.dtype, + header.client_type, header.ndims); uint32_t msglen = (uint32_t)header.msglen; if (msglen < sizeof(MsgHdr) || CType(header.client_type) > CRAY_CLIENT || header.ndims > MAX_DIMS) { fprintf(stderr, - "\rGetMdsMsg shutdown connection %d: bad msg header, " + "\nGetMdsMsg shutdown connection %d: bad msg header, " "header.ndims=%d, client_type=%d\n", c->id, header.ndims, CType(header.client_type)); *status = SsINTERNAL; @@ -141,12 +144,13 @@ Message *GetMdsMsgTOC(Connection *c, int *status, int to_msec) Message *GetMdsMsgTO(int id, int *status, int to_msec) { - Connection *c = FindConnection(id, NULL); + Connection *c = FindConnectionWithLock(id, CON_RECV); Message *msg = GetMdsMsgTOC(c, status, to_msec); + UnlockConnection(c); if (!msg && *status == SsINTERNAL) { // not for ETIMEDOUT or EINTR like exceptions - DisconnectConnection(id); + CloseConnection(id); *status = MDSplusERROR; } return msg; diff --git a/mdstcpip/mdsipshr/GetSetSettings.c b/mdstcpip/mdsipshr/GetSetSettings.c index 5bee89bd67..b833faa12e 100644 --- a/mdstcpip/mdsipshr/GetSetSettings.c +++ b/mdstcpip/mdsipshr/GetSetSettings.c @@ -23,184 +23,152 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../mdsip_connections.h" +#include "mdsipthreadstatic.h" #include #include -#ifdef _WIN32 -#define DEFAULT_HOSTFILE "C:\\MDSIP.HOSTS" -#else -#define DEFAULT_HOSTFILE "/etc/mdsip.hosts" -#endif - -static unsigned char multi = 0; -static int ContextSwitching = 0; -static int MaxCompressionLevel = 9; -static int CompressionLevel = 0; -static char *Portname = 0; -static char *protocol = "tcp"; -static char *hostfile = 0; -static int flags = 0; -static SOCKET socketHandle = 0; - -SOCKET GetSocketHandle() { return socketHandle; } - +//#define DEBUG +#include + +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +#define GET_THREAD_SAFE(var) ({ \ + typeof(var) ans; \ + pthread_mutex_lock(&lock); \ + ans = var; \ + pthread_mutex_unlock(&lock); \ + ans; \ +}) +#define SET_THREAD_SAFE(var, val) ({ \ + typeof(var) ans; \ + pthread_mutex_lock(&lock); \ + ans = var; \ + var = val; \ + pthread_mutex_unlock(&lock); \ + ans; \ +}) + +static SOCKET socket_handle = 0; +SOCKET GetSocketHandle() +{ + return GET_THREAD_SAFE(socket_handle); +} SOCKET SetSocketHandle(SOCKET handle) { - SOCKET old = socketHandle; - socketHandle = handle; - return old; + return SET_THREAD_SAFE(socket_handle, handle); } -int GetFlags() { return flags; } - +static int flags = 0; +int GetFlags() +{ + return GET_THREAD_SAFE(flags); +} int SetFlags(int f) { - int old = flags; - flags = f; - return old; + return SET_THREAD_SAFE(flags, f); } -char *GetProtocol() { return protocol; } - +static char *protocol = "tcp"; +char *GetProtocol() +{ + return GET_THREAD_SAFE(protocol); +} char *SetProtocol(char *p) { - char *old = protocol; - protocol = p; - return old; + return SET_THREAD_SAFE(protocol, p); } -char *GetPortname() { return Portname; } - -char *MdsGetServerPortname() { return Portname; } - +static char *portname = 0; +char *GetPortname() +{ + return GET_THREAD_SAFE(portname); +} char *SetPortname(char *p) { - char *old = Portname; - Portname = p; - return old; + return SET_THREAD_SAFE(portname, p); } -char *GetHostfile() { return hostfile ? hostfile : DEFAULT_HOSTFILE; } - -char *SetHostfile(char *newhostfile) +#ifdef _WIN32 +#define DEFAULT_HOSTFILE "C:\\mdsip.hosts" +#else +#define DEFAULT_HOSTFILE "/etc/mdsip.hosts" +#endif +static char *hostfile = NULL; +char *GetHostfile() { - char *old = hostfile; - hostfile = newhostfile; - return old; + char *ans = GET_THREAD_SAFE(hostfile); + return ans ? ans : DEFAULT_HOSTFILE; } - -//////////////////////////////////////////////////////////////////////////////// -// CONTEXT /////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -char *GetLogDir() +char *SetHostfile(char *newhostfile) { - char *logdir = getenv("MDSIP_SERVICE_LOGDIR"); - if (logdir && (strlen(logdir) > 0)) - { - logdir = strdup(logdir); - size_t len = strlen(logdir); - if ((logdir[len - 1] == '\\') || (logdir[len - 1] == '/')) - { - logdir[len - 1] = '\000'; - } - } - else - { - logdir = strdup("C:\\"); - } - return logdir; + return SET_THREAD_SAFE(hostfile, newhostfile); } -unsigned char GetMulti() { return multi; } - -/// /// Set multi mode active in this scope. /// Mutiple connection mode (accepts multiple connections each with own context) -/// +static unsigned char multi = 0; +unsigned char GetMulti() +{ + return GET_THREAD_SAFE(multi); +} unsigned char SetMulti(unsigned char s) { - unsigned char old_multi = multi; - multi = s; - return old_multi; + return SET_THREAD_SAFE(multi, s); } -int GetContextSwitching() { return ContextSwitching; } - +static int ContextSwitching = 0; +int GetContextSwitching() +{ + return GET_THREAD_SAFE(ContextSwitching); +} int SetContextSwitching(int s) { - int old_ctx_switching = ContextSwitching; - ContextSwitching = s; - return old_ctx_switching; + return SET_THREAD_SAFE(ContextSwitching, s); } -//////////////////////////////////////////////////////////////////////////////// -// COMPRESSION /////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -int GetMaxCompressionLevel() { return MaxCompressionLevel; } - -int SetMaxCompressionLevel(int s) +// COMPRESSION +static int compression = 0; +/// used in ConnectToMds, mdsip_service +int GetCompressionLevel() { - int old_max_compression = MaxCompressionLevel; - MaxCompressionLevel = s; - return old_max_compression; + return GET_THREAD_SAFE(compression); } - int SetCompressionLevel(int level) { - int old_level = CompressionLevel; - CompressionLevel = level; - return old_level; + return SET_THREAD_SAFE(compression, level); } -int GetCompressionLevel() { return CompressionLevel; } - -//////////////////////////////////////////////////////////////////////////////// -// CONNECTION TIMEOUT //////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -static int timeout_value = 0; -static pthread_once_t timeout_once = PTHREAD_ONCE_INIT; -static pthread_mutex_t timeout_mutex = PTHREAD_MUTEX_INITIALIZER; -static void timeout_init() +/// CLIENT ADDRESS +/// used in ServerShr +int MdsGetClientAddr() { - char *timeout = getenv("MDSIP_CONNECT_TIMEOUT"); - if (timeout) - timeout_value = strtol(timeout, NULL, 0); + MDSIPTHREADSTATIC_INIT; + MDSDBG("GET CLIENT " IPADDRPRI, IPADDRVAR(&MDSIP_CLIENTADDR)); + return MDSIP_CLIENTADDR; } - -//////////////////////////////////////////////////////////////////////////////// -// GetMdsConnectTimeout ////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -int GetMdsConnectTimeout() +void MdsSetClientAddr(int addr) { - int connect_timeout; - pthread_mutex_lock(&timeout_mutex); - pthread_cleanup_push((void *)pthread_mutex_unlock, &timeout_mutex); - pthread_once(&timeout_once, timeout_init); - connect_timeout = timeout_value; - pthread_cleanup_pop(1); - return connect_timeout; + MDSIPTHREADSTATIC_INIT; + MDSIP_CLIENTADDR = addr; + MDSDBG("SET CLIENT " IPADDRPRI, IPADDRVAR(&MDSIP_CLIENTADDR)); } -int SetMdsConnectTimeout(int sec) +#ifdef _WIN32 +char *GetLogDir() { - int old; - pthread_mutex_lock(&timeout_mutex); - pthread_cleanup_push((void *)pthread_mutex_unlock, &timeout_mutex); - pthread_once(&timeout_once, timeout_init); - old = timeout_value; - timeout_value = sec; - pthread_cleanup_pop(1); - return old; + char *logdir = getenv("MDSIP_SERVICE_LOGDIR"); + if (logdir && (strlen(logdir) > 0)) + { + logdir = strdup(logdir); + size_t len = strlen(logdir); + if ((logdir[len - 1] == '\\') || (logdir[len - 1] == '/')) + { + logdir[len - 1] = '\000'; + } + } + else + { + logdir = strdup("C:\\"); + } + return logdir; } - -//////////////////////////////////////////////////////////////////////////////// -// CLIENT ADDRESS //////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -static int ClientAddr = 0; -int MdsGetClientAddr() { return ClientAddr; } - -/// Address of current client structure -void MdsSetClientAddr(int addr) { ClientAddr = addr; } +#endif \ No newline at end of file diff --git a/mdstcpip/mdsipshr/IdlApi.c b/mdstcpip/mdsipshr/IdlApi.c index ad8c5ad8df..295af48559 100644 --- a/mdstcpip/mdsipshr/IdlApi.c +++ b/mdstcpip/mdsipshr/IdlApi.c @@ -22,19 +22,21 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include #include +#include + +#include +#include + #ifdef _WIN32 #define BlockSig(arg) #define UnBlockSig(arg) #else #include -#include #ifndef NULL #define NULL (void *)0 #endif -STATIC_ROUTINE int BlockSig(int sig_number) +static int BlockSig(int sig_number) { sigset_t newsigset; #if defined(sun) @@ -55,7 +57,7 @@ STATIC_ROUTINE int BlockSig(int sig_number) return sigprocmask(SIG_BLOCK, &newsigset, NULL); } -STATIC_ROUTINE int UnBlockSig(int sig_number) +static int UnBlockSig(int sig_number) { sigset_t newsigset; sigemptyset(&newsigset); @@ -68,7 +70,7 @@ STATIC_ROUTINE int UnBlockSig(int sig_number) // Start of Mac Changes static short bGUSIInit = 0; -STATIC_ROUTINE void BlockSig(int) +static void BlockSig(int) { if (!bGUSIInit) { @@ -78,7 +80,7 @@ STATIC_ROUTINE void BlockSig(int) } } -STATIC_ROUTINE void UnBlockSig(int) {} +static void UnBlockSig(int) {} void main() {} @@ -93,7 +95,7 @@ EXPORT int IdlMdsClose(int lArgc, void **lpvArgv) BlockSig(SIGALRM); if (lArgc == 1) { - status = MdsClose((int)((char *)lpvArgv[0] - (char *)0)); + status = MdsClose((int)(intptr_t)(lpvArgv[0])); } UnBlockSig(SIGALRM); return status; @@ -122,7 +124,7 @@ EXPORT int IdlDisconnectFromMds(int lArgc, void **lpvArgv) BlockSig(SIGALRM); if (lArgc == 1) { - status = DisconnectFromMds((int)((char *)lpvArgv[0] - (char *)0)); + status = DisconnectFromMds((int)(intptr_t)(lpvArgv[0])); } UnBlockSig(SIGALRM); return status; @@ -137,8 +139,8 @@ EXPORT int IdlMdsOpen(int lArgc, void **lpvArgv) if (lArgc == 3) { BlockSig(SIGALRM); - status = MdsOpen((int)((char *)lpvArgv[0] - (char *)0), (char *)lpvArgv[1], - (int)((char *)lpvArgv[2] - (char *)0)); + status = MdsOpen((int)(intptr_t)(lpvArgv[0]), (char *)lpvArgv[1], + (int)(intptr_t)(lpvArgv[2])); UnBlockSig(SIGALRM); } return status; @@ -153,8 +155,7 @@ EXPORT int IdlMdsSetDefault(int lArgc, void **lpvArgv) if (lArgc == 2) { BlockSig(SIGALRM); - status = MdsSetDefault((int)((char *)lpvArgv[0] - (char *)0), - (char *)lpvArgv[1]); + status = MdsSetDefault((int)(intptr_t)(lpvArgv[0]), (char *)lpvArgv[1]); UnBlockSig(SIGALRM); } return status; @@ -170,7 +171,7 @@ EXPORT int IdlGetAnsInfo(int lArgc, void **lpvArgv) if (lArgc == 7) { BlockSig(SIGALRM); - status = GetAnswerInfo((int)((char *)lpvArgv[0] - (char *)0), + status = GetAnswerInfo((int)(intptr_t)(lpvArgv[0]), (char *)lpvArgv[1], (short *)lpvArgv[2], (char *)lpvArgv[3], (int *)lpvArgv[4], (int *)lpvArgv[5], (void **)lpvArgv[6]); @@ -188,11 +189,9 @@ EXPORT int Idlmemcpy(int lArgc, void **lpvArgv) if (lArgc == 3) { #ifdef __alpha - memcpy((void *)lpvArgv[0], *(void **)lpvArgv[1], - (int)((char *)lpvArgv[2] - (char *)0)); + memcpy((void *)lpvArgv[0], *(void **)lpvArgv[1], (intptr_t)(lpvArgv[2])); #else - memcpy((void *)lpvArgv[0], (void *)lpvArgv[1], - (int)((char *)lpvArgv[2] - (char *)0)); + memcpy((void *)lpvArgv[0], (void *)lpvArgv[1], (intptr_t)(lpvArgv[2])); #endif status = 1; } @@ -208,13 +207,13 @@ EXPORT int IdlSendArg(int lArgc, void **lpvArgv) int status = 0; if (lArgc == 8) { - unsigned char idx = (unsigned char)((char *)lpvArgv[1] - (char *)0); - unsigned char dtype = (unsigned char)((char *)lpvArgv[2] - (char *)0); - unsigned char nargs = (unsigned char)((char *)lpvArgv[3] - (char *)0); - short length = (short)((char *)lpvArgv[4] - (char *)0); - char ndims = (char)((char *)lpvArgv[5] - (char *)0); + unsigned char idx = (unsigned char)(intptr_t)(lpvArgv[1]); + unsigned char dtype = (unsigned char)(intptr_t)(lpvArgv[2]); + unsigned char nargs = (unsigned char)(intptr_t)(lpvArgv[3]); + short length = (short)(intptr_t)(lpvArgv[4]); + char ndims = (char)(intptr_t)(lpvArgv[5]); BlockSig(SIGALRM); - status = SendArg((int)((char *)lpvArgv[0] - (char *)0), idx, dtype, nargs, + status = SendArg((int)(intptr_t)(lpvArgv[0]), idx, dtype, nargs, length, ndims, (int *)lpvArgv[6], (char *)lpvArgv[7]); UnBlockSig(SIGALRM); } @@ -230,8 +229,8 @@ EXPORT int IdlSetCompressionLevel(int lArgc, void **lpvArgv) int status = 0; if (lArgc == 2) { - status = MdsSetCompression((int)((char *)lpvArgv[0] - (char *)0), - (int)((char *)lpvArgv[1] - (char *)0)); + status = MdsSetCompression((int)(intptr_t)(lpvArgv[0]), + (int)(intptr_t)(lpvArgv[1])); } return status; } diff --git a/mdstcpip/mdsipshr/LoadIo.c b/mdstcpip/mdsipshr/LoadIo.c index 2a712737ab..c419d91774 100644 --- a/mdstcpip/mdsipshr/LoadIo.c +++ b/mdstcpip/mdsipshr/LoadIo.c @@ -29,7 +29,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "../mdsshr/version.h" #include "../mdsip_connections.h" //////////////////////////////////////////////////////////////////////////////// @@ -43,7 +42,7 @@ IoRoutines *LoadIo(char *protocol_in) { if (protocol_in == 0) protocol_in = "TCP"; - char *protocol = strcpy((char *)malloc(strlen(protocol_in) + 1), protocol_in); + char *protocol = strdup(protocol_in); size_t i; for (i = 0; i < strlen(protocol); i++) protocol[i] = toupper(protocol[i]); diff --git a/mdstcpip/mdsipshr/MdsClose.c b/mdstcpip/mdsipshr/MdsClose.c index c6a932a374..f8e1f10d17 100644 --- a/mdstcpip/mdsipshr/MdsClose.c +++ b/mdstcpip/mdsipshr/MdsClose.c @@ -24,7 +24,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../mdsip_connections.h" -#include #include //////////////////////////////////////////////////////////////////////////////// @@ -34,9 +33,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. int MdsClose(int id) { struct descrip ansarg; - STATIC_CONSTANT char *expression = "TreeClose()"; + static char *expression = "TreeClose()"; int status = MdsValue(id, expression, &ansarg, NULL); - if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) + if ((STATUS_OK) && (ansarg.dtype == DTYPE_LONG)) status = *(int *)ansarg.ptr; free(ansarg.ptr); return status; diff --git a/mdstcpip/mdsipshr/MdsEventAst.c b/mdstcpip/mdsipshr/MdsEventAst.c index 2b56c29e99..4f1ee51e7f 100644 --- a/mdstcpip/mdsipshr/MdsEventAst.c +++ b/mdstcpip/mdsipshr/MdsEventAst.c @@ -49,7 +49,7 @@ int MdsEventAst(int id, char *eventnam, void (*astadr)(), void *astprm, eventnam), MakeDescrip((struct descrip *)&infoarg, DTYPE_UCHAR, 1, &size, &info), (struct descrip *)&ansarg, (struct descrip *)NULL); - if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) + if ((STATUS_OK) && (ansarg.dtype == DTYPE_LONG)) { *eventid = *(int *)ansarg.ptr; } diff --git a/mdstcpip/mdsipshr/CloseConnection.c b/mdstcpip/mdsipshr/MdsIpThreadStatic.c similarity index 59% rename from mdstcpip/mdsipshr/CloseConnection.c rename to mdstcpip/mdsipshr/MdsIpThreadStatic.c index 07b5668f87..aaaef212c7 100644 --- a/mdstcpip/mdsipshr/CloseConnection.c +++ b/mdstcpip/mdsipshr/MdsIpThreadStatic.c @@ -22,47 +22,41 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include + #include +#include + +#include +#include +#include +#include +#include -#include "../mdsip_connections.h" +#include "../mdsshr/version.h" +#include "mdsipthreadstatic.h" -extern int _TreeClose(); -extern int TdiSaveContext(); -extern int TdiDeleteContext(); -extern int TdiRestoreContext(); -extern int MDSEventCan(); +#define DEBUG +#include -int CloseConnectionC(Connection *connection) +static void buffer_free(MDSIPTHREADSTATIC_ARG) { - int status = 0; - if (connection) + Connection *c; + while ((c = MDSIP_CONNECTIONS)) { - void *tdi_context[6]; - MdsEventList *e, *nexte; - FreeDescriptors(connection); - for (e = connection->event; e; e = nexte) - { - nexte = e->next; - /**/ MDSEventCan(e->eventid); - /**/ if (e->info_len > 0) - free(e->info); - free(e); - } - do - { - status = _TreeClose(&connection->DBID, 0, 0); - } while (STATUS_OK); - TdiSaveContext(tdi_context); - TdiDeleteContext(connection->tdicontext); - TdiRestoreContext(tdi_context); - status = DisconnectConnection(connection->id); + MDSIP_CONNECTIONS = c->next; + MDSDBG(CON_PRI, CON_VAR(c)); + destroyConnection(c); } - return status; + free(MDSIPTHREADSTATIC_VAR); } - -int CloseConnection(int id) +static inline MDSIPTHREADSTATIC_TYPE *buffer_alloc() { - Connection *connection = FindConnection(id, NULL); - return CloseConnectionC(connection); + MDSIPTHREADSTATIC_ARG = + (MDSIPTHREADSTATIC_TYPE *)calloc(1, sizeof(MDSIPTHREADSTATIC_TYPE)); + + return MDSIPTHREADSTATIC_VAR; } + +IMPLEMENT_GETTHREADSTATIC(MDSIPTHREADSTATIC_TYPE, MdsIpGetThreadStatic, + THREADSTATIC_MDSIP, buffer_alloc, buffer_free) diff --git a/mdstcpip/mdsipshr/MdsOpen.c b/mdstcpip/mdsipshr/MdsOpen.c index e72502922a..e60d70827e 100644 --- a/mdstcpip/mdsipshr/MdsOpen.c +++ b/mdstcpip/mdsipshr/MdsOpen.c @@ -23,7 +23,6 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../mdsip_connections.h" -#include #include #include @@ -41,7 +40,7 @@ int MdsOpen(int id, char *tree, int shot) MakeDescrip((struct descrip *)&treearg, DTYPE_CSTRING, 0, 0, tree), MakeDescrip((struct descrip *)&shotarg, DTYPE_LONG, 0, 0, &shot), (struct descrip *)&ansarg, (struct descrip *)NULL); - if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) + if ((STATUS_OK) && (ansarg.dtype == DTYPE_LONG)) status = *(int *)ansarg.ptr; free(ansarg.ptr); return status; diff --git a/mdstcpip/mdsipshr/MdsPut.c b/mdstcpip/mdsipshr/MdsPut.c index 2a0463f89a..9e6367ff6a 100644 --- a/mdstcpip/mdsipshr/MdsPut.c +++ b/mdstcpip/mdsipshr/MdsPut.c @@ -24,7 +24,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../mdsip_connections.h" -#include #include #include diff --git a/mdstcpip/mdsipshr/MdsSetCompression.c b/mdstcpip/mdsipshr/MdsSetCompression.c index b954c32de2..782b033183 100644 --- a/mdstcpip/mdsipshr/MdsSetCompression.c +++ b/mdstcpip/mdsipshr/MdsSetCompression.c @@ -27,10 +27,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -//////////////////////////////////////////////////////////////////////////////// -// MdsSetCompression ///////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - int MdsSetCompression(int id, int level) { int old_level; diff --git a/mdstcpip/mdsipshr/MdsSetDefault.c b/mdstcpip/mdsipshr/MdsSetDefault.c index 40d99f6f31..d2f3feb2c8 100644 --- a/mdstcpip/mdsipshr/MdsSetDefault.c +++ b/mdstcpip/mdsipshr/MdsSetDefault.c @@ -24,7 +24,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../mdsip_connections.h" -#include #include //////////////////////////////////////////////////////////////////////////////// @@ -35,11 +34,11 @@ int MdsSetDefault(int id, char *node) { struct descrip nodearg; struct descrip ansarg; - STATIC_CONSTANT char *expression = "TreeSetDefault($)"; + static char *expression = "TreeSetDefault($)"; int status = MdsValue(id, expression, MakeDescrip(&nodearg, DTYPE_CSTRING, 0, 0, node), &ansarg, NULL); - if ((status & 1) && (ansarg.dtype == DTYPE_LONG)) + if ((STATUS_OK) && (ansarg.dtype == DTYPE_LONG)) status = *(int *)ansarg.ptr; free(ansarg.ptr); return status; diff --git a/mdstcpip/mdsipshr/MdsValue.c b/mdstcpip/mdsipshr/MdsValue.c index d3d3adbb00..843b7938fb 100644 --- a/mdstcpip/mdsipshr/MdsValue.c +++ b/mdstcpip/mdsipshr/MdsValue.c @@ -35,53 +35,60 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // MdsValue ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { \ - } -#endif +#include + +#define SERIAL +#define DEF_SERIAL_IN \ + "public fun __si(in _i)" \ + "{" \ + "_o=*;" \ + "MdsShr->MdsSerializeDscIn(ref(_i),xd(_o));" \ + "return(_o);" \ + "};" +#define DEF_SERIAL_OUT \ + "public fun __so(optional in _i)" \ + "{" \ + "_o=*;" \ + "MdsShr->MdsSerializeDscOut(xd(_i),xd(_o));" \ + "return(_o);" \ + "};" EXPORT int MdsIpGetDescriptor(int id, const char *expression, int nargs, - struct descriptor **arglist_in, - struct descriptor_xd *ans_ptr) + mdsdsc_t **arglist_in, + mdsdsc_xd_t *ans_ptr) { int dim = 0; int i, status; - Connection *c = FindConnection(id, NULL); - if (c->version >= MDSIP_VERSION_DSC_ARGS) + int version = GetConnectionVersion(id); + const int expect_serial = version >= MDSIP_VERSION_DSC_ARGS; + if (expect_serial) { - status = - SendArg(id, 0, DTYPE_CSTRING, ++nargs, 0, 0, &dim, (char *)expression); + DESCRIPTOR_FROM_CSTRING(exp_dsc, expression); + status = SendDsc(id, 0, ++nargs, &exp_dsc); for (i = 1; i < nargs && STATUS_OK; i++) status = SendDsc(id, i, nargs, arglist_in[i - 1]); } else { EMPTYXD(xd); - char *newexp = malloc(strlen(expression) + 256 + nargs * 8); - strcpy(newexp, "public fun __si(in " - "_i){_o=*;MdsShr->MdsSerializeDscIn(ref(_i),xd(_o));return(_" - "o);};public fun __so(optional in " - "_i){_o=*;MdsShr->MdsSerializeDscOut(xd(_i),xd(_o));return(_" - "o);};__so(execute($"); + char *newexp = malloc(16 + 8 * 8 + sizeof(DEF_SERIAL_OUT) + sizeof(DEF_SERIAL_IN)); + strcpy(newexp, DEF_SERIAL_IN DEF_SERIAL_OUT "__so(execute($"); for (i = 0; i < nargs; i++) strcat(newexp, ",__si($)"); strcat(newexp, "))"); nargs += 2; - DBG("%s\n", newexp); + MDSDBG(newexp); status = SendArg(id, 0, DTYPE_CSTRING, nargs, strlen(newexp), 0, &dim, (char *)newexp); free(newexp); - DBG("%s\n", expression); + MDSDBG(expression); struct descriptor_a *arr; status = SendArg(id, 1, DTYPE_CSTRING, nargs, strlen(expression), 0, &dim, (char *)expression); for (i = 2; i < nargs && STATUS_OK; i++) { status = MdsSerializeDscOut(arglist_in[i - 2], &xd); - arr = (struct descriptor_a *)xd.pointer; + arr = (mdsdsc_a_t *)xd.pointer; if (STATUS_OK) status = SendArg(id, i, arr->dtype, nargs, arr->length, 1, (int *)&arr->arsize, arr->pointer); @@ -93,15 +100,15 @@ EXPORT int MdsIpGetDescriptor(int id, const char *expression, int nargs, char ndims; void *mem = 0; int dims[MAX_DIMS] = {0}; - struct descriptor_a ser = {0}; + mdsdsc_a_t ser = {0}; status = GetAnswerInfoTS(id, (char *)&ser.dtype, (short int *)&ser.length, &ndims, dims, (int *)&ser.arsize, (void **)&ser.pointer, &mem); ser.class = CLASS_A; - if (ser.dtype == DTYPE_SERIAL || ser.dtype == DTYPE_B) + if ((expect_serial && ser.dtype == DTYPE_SERIAL) || ser.dtype == DTYPE_B) status = MdsSerializeDscIn(ser.pointer, ans_ptr); else - status = MDSplusERROR; + status = MdsCopyDxXd((mdsdsc_t *)&ser, ans_ptr); free(mem); } return status; @@ -110,7 +117,7 @@ EXPORT int MdsIpGetDescriptor(int id, const char *expression, int nargs, EXPORT int _MdsValue(int id, int nargs, struct descrip **arglist, struct descrip *ans_arg) { - DBG("mdstcpip.MdsValue> '%s'\n", (char *)(**arglist).ptr); + MDSDBG("mdstcpip.MdsValue> '%s'", (char *)(**arglist).ptr); int i, status = 1; for (i = 0; i < nargs && STATUS_OK; i++) status = SendArg(id, i, arglist[i]->dtype, nargs, ArgLen(arglist[i]), diff --git a/mdstcpip/mdsipshr/ParseCommand.c b/mdstcpip/mdsipshr/ParseCommand.c index 9d5650871e..791156a61e 100644 --- a/mdstcpip/mdsipshr/ParseCommand.c +++ b/mdstcpip/mdsipshr/ParseCommand.c @@ -29,8 +29,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include - #include "../mdsip_connections.h" static void print_help(char *option) @@ -47,9 +45,9 @@ static void print_help(char *option) "[-h hostfile] [-c[level]] [-p port] [protocol-specific-options]\n\n" " -?, --help This help message\n" " -P protocol Specifies server protocol, defaults to tcp\n" - " --protocol=protocal-name\n" + " --protocol=protocal-name\n" " -p port|service Specifies port number or tcp service name\n" - " --port=port|service\n" + " --port=port|service\n" " -m, --multi Use multi mode\n" " Accepts multiple connections each with own " "context.\n" @@ -69,11 +67,11 @@ static void print_help(char *option) "/etc/mdsip.hosts" #endif ".\n" - " --hostfile=hostfile\n" + " --hostfile=hostfile\n" " -c[] Specify maximum zlip compression level\n" " 0: none or 1-9: fastest/least to slowest/most\n" " defaults to 9 if present and 0 if absent\n" - " --compression[=]\n\n"); + " --compression[=]\n\n"); exit(option ? 1 : 0); } @@ -83,7 +81,7 @@ static void print_help(char *option) void ParseCommand(int argc, char **argv, Options options[], int more, int *rem_argc, char ***rem_argv) { - INIT_AS_AND_FREE_ON_EXIT(char **, extra_argv, malloc(argc * sizeof(char *))); + char **extra_argv = malloc(argc * sizeof(char *)); int i; int extra_argc = 1; extra_argv[0] = argv[0]; @@ -192,7 +190,6 @@ void ParseCommand(int argc, char **argv, Options options[], int more, } else free(extra_argv); - FREE_CANCEL(); } /// diff --git a/mdstcpip/mdsipshr/ProcessMessage.c b/mdstcpip/mdsipshr/ProcessMessage.c index 2b553f768b..bb6cba2fac 100644 --- a/mdstcpip/mdsipshr/ProcessMessage.c +++ b/mdstcpip/mdsipshr/ProcessMessage.c @@ -52,16 +52,32 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include "../tdishr/tdithreadstatic.h" #include "../treeshr/treeshrp.h" -#include "cvtdef.h" #include "../mdsIo.h" #include "../mdsip_connections.h" +//#define DEBUG +#include + extern int TdiRestoreContext(void **); extern int TdiSaveContext(void **); +extern int CvtConvertFloat(void *invalue, uint32_t indtype, void *outvalue, + uint32_t outdtype, uint32_t options); +#define VAX_F DTYPE_F /* VAX F Floating point data */ +#define VAX_D DTYPE_D /* VAX D Floating point data */ +#define VAX_G DTYPE_G /* VAX G Floating point data */ +#define VAX_H DTYPE_H /* VAX H Floating point data */ +#define IEEE_S DTYPE_FS /* IEEE S Floating point data */ +#define IEEE_T DTYPE_FT /* IEEE T Floating point data */ +#define IBM_LONG 6 /* IBM Long Floating point data */ +#define IBM_SHORT 7 /* IBM Short Floating point data */ +#define CRAY 8 /* Cray Floating point data */ +#define IEEE_X 9 /* IEEE X Floating point data */ + static void convert_binary(int num, int sign_extend, short in_length, char *in_ptr, short out_length, char *out_ptr) { @@ -90,7 +106,7 @@ static void convert_float(int num, int in_type, char in_length, char *in_ptr, { char *ptr = in_p; char cray_f[8]; - if (in_type == CvtCRAY) + if (in_type == CRAY) { int j, k; for (j = 0; j < 2; j++) @@ -104,7 +120,7 @@ static void convert_float(int num, int in_type, char in_length, char *in_ptr, } CvtConvertFloat(ptr, in_type, out_p, out_type, 0); #ifdef WORDS_BIGENDIAN - if (out_type == CvtCRAY) + if (out_type == CRAY) { int j, k; ptr = out_p; @@ -118,15 +134,8 @@ static void convert_float(int num, int in_type, char in_length, char *in_ptr, } } -static void send_response(Connection *connection, Message *message, - int status, mdsdsc_t *d) +static inline uint32_t get_nbytes(uint16_t *length, uint32_t *num, int client_type, mdsdsc_t *d) { - const int client_type = connection->client_type; - const unsigned char message_id = connection->message_id; - Message *m = NULL; - int nbytes = (d->class == CLASS_S) ? d->length : ((array_coeff *)d)->arsize; - int num = nbytes / ((d->length < 1) ? 1 : d->length); - short length = d->length; if (CType(client_type) == CRAY_CLIENT) { switch (d->dtype) @@ -137,20 +146,19 @@ static void send_response(Connection *connection, Message *message, case DTYPE_LONG: case DTYPE_F: case DTYPE_FS: - length = 8; + *length = 8; break; case DTYPE_FC: case DTYPE_FSC: case DTYPE_D: case DTYPE_G: case DTYPE_FT: - length = 16; + *length = 16; break; default: - length = d->length; + *length = d->length; break; } - nbytes = num * length; } else if (CType(client_type) == CRAY_IEEE_CLIENT) { @@ -158,320 +166,416 @@ static void send_response(Connection *connection, Message *message, { case DTYPE_USHORT: case DTYPE_SHORT: - length = 4; + *length = 4; break; case DTYPE_ULONG: case DTYPE_LONG: - length = 8; + *length = 8; break; default: - length = d->length; + *length = d->length; break; } - nbytes = num * length; } - m = malloc(sizeof(MsgHdr) + nbytes); - memset(&m->h, 0, sizeof(MsgHdr)); - m->h.msglen = sizeof(MsgHdr) + nbytes; - m->h.client_type = client_type; - m->h.message_id = message_id; - m->h.status = status; - m->h.dtype = d->dtype; - m->h.length = length; + else + { + *length = d->length; + } if (d->class == CLASS_S) - m->h.ndims = 0; + { + *num = 1; + } + else if (*length == 0) + { + *num = 0; + } else { - int i; - array_coeff *a = (array_coeff *)d; - m->h.ndims = a->dimct; - if (a->aflags.coeff) - for (i = 0; i < m->h.ndims && i < MAX_DIMS; i++) - m->h.dims[i] = a->m[i]; - else - m->h.dims[0] = a->length ? a->arsize / a->length : 0; - for (i = m->h.ndims; i < MAX_DIMS; i++) - m->h.dims[i] = 0; + *num = ((array_coeff *)d)->arsize / (*length); } - switch (CType(client_type)) + return (*num) * (*length); +} + +static inline void convert_ieee(Message *m, int num, const mdsdsc_t *d, uint32_t nbytes) +{ + switch (d->dtype) { - case IEEE_CLIENT: - case JAVA_CLIENT: - switch (d->dtype) - { - case DTYPE_F: - convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtIEEE_S, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FS: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - convert_float(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - convert_float(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - convert_float(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FT: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } + case DTYPE_F: + convert_float(num, VAX_F, (char)d->length, d->pointer, IEEE_S, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; break; - case CRAY_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, - m->bytes); - break; - case DTYPE_F: - convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FS: - convert_float(num, CvtIEEE_S, (char)d->length, d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FC: - convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtCRAY, (char)(m->h.length / 2), m->bytes); - break; - case DTYPE_FSC: - convert_float(num * 2, CvtIEEE_S, (char)(d->length / 2), d->pointer, - CvtCRAY, (char)(m->h.length / 2), m->bytes); - break; - case DTYPE_D: - convert_float(num, CvtVAX_D, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_G: - convert_float(num, CvtVAX_G, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - case DTYPE_FT: - convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtCRAY, - (char)m->h.length, m->bytes); - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; - } + case DTYPE_FC: + convert_float(num * 2, VAX_F, (char)(d->length / 2), d->pointer, + IEEE_S, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; break; - case CRAY_IEEE_CLIENT: - switch (d->dtype) + case DTYPE_FS: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, VAX_D, (char)d->length, d->pointer, IEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, VAX_D, (char)(d->length / 2), d->pointer, + IEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, VAX_G, (char)d->length, d->pointer, IEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, VAX_G, (char)(d->length / 2), d->pointer, + IEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FT: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } +} + +static inline void convert_cray(Message *m, int num, const mdsdsc_t *d, uint32_t nbytes) +{ + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, + m->bytes); + break; + case DTYPE_F: + convert_float(num, VAX_F, (char)d->length, d->pointer, CRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FS: + convert_float(num, IEEE_S, (char)d->length, d->pointer, CRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FC: + convert_float(num * 2, VAX_F, (char)(d->length / 2), d->pointer, + CRAY, (char)(m->h.length / 2), m->bytes); + break; + case DTYPE_FSC: + convert_float(num * 2, IEEE_S, (char)(d->length / 2), d->pointer, + CRAY, (char)(m->h.length / 2), m->bytes); + break; + case DTYPE_D: + convert_float(num, VAX_D, sizeof(double), d->pointer, CRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_G: + convert_float(num, VAX_G, sizeof(double), d->pointer, CRAY, + (char)m->h.length, m->bytes); + break; + case DTYPE_FT: + convert_float(num, IEEE_T, sizeof(double), d->pointer, CRAY, + (char)m->h.length, m->bytes); + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } +} + +static inline void convert_cray_ieee(Message *m, int num, const mdsdsc_t *d, uint32_t nbytes) +{ + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, + m->bytes); + break; + case DTYPE_F: + convert_float(num, VAX_F, (char)d->length, d->pointer, IEEE_S, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + convert_float(num * 2, VAX_F, (char)(d->length / 2), d->pointer, + IEEE_S, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FS: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, VAX_D, (char)d->length, d->pointer, IEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, VAX_D, (char)(d->length / 2), d->pointer, + IEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, VAX_G, (char)d->length, d->pointer, IEEE_T, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, VAX_G, (char)(d->length / 2), d->pointer, + IEEE_T, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FT: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } +} + +static inline void convert_vmsg(Message *m, int num, const mdsdsc_t *d, uint32_t nbytes) +{ + switch (d->dtype) + { + case DTYPE_F: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + convert_float(num, VAX_D, sizeof(double), d->pointer, VAX_G, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + convert_float(num * 2, VAX_D, (char)(d->length / 2), d->pointer, + VAX_G, (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FS: + convert_float(num, IEEE_S, sizeof(float), d->pointer, VAX_F, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + convert_float(num * 2, IEEE_S, sizeof(float), d->pointer, VAX_F, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FT: + convert_float(num, IEEE_T, sizeof(double), d->pointer, VAX_G, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + convert_float(num * 2, IEEE_T, sizeof(double), d->pointer, VAX_G, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } +} + +static inline void convert_default(Message *m, int num, const mdsdsc_t *d, uint32_t nbytes) +{ + switch (d->dtype) + { + case DTYPE_F: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_D: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_DC: + memcpy(m->bytes, d->pointer, nbytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_G: + convert_float(num, VAX_G, sizeof(double), d->pointer, VAX_D, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_GC: + convert_float(num * 2, VAX_G, sizeof(double), d->pointer, VAX_D, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + case DTYPE_FS: + convert_float(num, IEEE_S, sizeof(float), d->pointer, VAX_F, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_FLOAT; + break; + case DTYPE_FSC: + convert_float(num * 2, IEEE_S, sizeof(float), d->pointer, VAX_F, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX; + break; + case DTYPE_FT: + convert_float(num, IEEE_T, sizeof(double), d->pointer, VAX_D, + (char)m->h.length, m->bytes); + m->h.dtype = DTYPE_DOUBLE; + break; + case DTYPE_FTC: + convert_float(num * 2, IEEE_T, sizeof(double), d->pointer, VAX_D, + (char)(m->h.length / 2), m->bytes); + m->h.dtype = DTYPE_COMPLEX_DOUBLE; + break; + default: + memcpy(m->bytes, d->pointer, nbytes); + break; + } +} + +static inline int _send_response(Connection *connection, Message **message, int status, mdsdsc_t *d) +{ + const int client_type = connection->client_type; + const unsigned char message_id = connection->message_id; + Message *m = NULL; + int serial = STATUS_NOT_OK || (connection->descrip[0] && connection->descrip[0]->dtype == DTYPE_SERIAL); + if (!serial && SupportsCompression(client_type)) + { + EMPTYXD(xd); + status = MdsSerializeDscOut(d, &xd); + MdsFreeDescriptor(d); + d = xd.pointer; + serial = 1; + } + if (serial && STATUS_OK && d->class == CLASS_A) + { + mdsdsc_a_t *array = (mdsdsc_a_t *)d; + *message = m = malloc(sizeof(MsgHdr) + array->arsize); + memset(&m->h, 0, sizeof(MsgHdr)); + m->h.msglen = sizeof(MsgHdr) + array->arsize; + m->h.client_type = client_type; + m->h.message_id = message_id; + m->h.status = status; + m->h.dtype = DTYPE_SERIAL; + m->h.ndims = 1; + m->h.dims[0] = array->arsize; + m->h.length = 1; + memcpy(m->bytes, array->pointer, array->arsize); + } + else + { + uint16_t length; + uint32_t num; + uint32_t nbytes = get_nbytes(&length, &num, client_type, d); + *message = m = malloc(sizeof(MsgHdr) + nbytes); + memset(&m->h, 0, sizeof(MsgHdr)); + m->h.msglen = sizeof(MsgHdr) + nbytes; + m->h.client_type = client_type; + m->h.message_id = message_id; + m->h.status = status; + m->h.dtype = d->dtype; + m->h.length = length; + if (d->class == CLASS_S) { - case DTYPE_USHORT: - case DTYPE_ULONG: - convert_binary(num, 0, d->length, d->pointer, m->h.length, m->bytes); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - convert_binary(num, 1, (char)d->length, d->pointer, (char)m->h.length, - m->bytes); - break; - case DTYPE_F: - convert_float(num, CvtVAX_F, (char)d->length, d->pointer, CvtIEEE_S, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - convert_float(num * 2, CvtVAX_F, (char)(d->length / 2), d->pointer, - CvtIEEE_S, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FS: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - convert_float(num, CvtVAX_D, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - convert_float(num, CvtVAX_G, (char)d->length, d->pointer, CvtIEEE_T, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - convert_float(num * 2, CvtVAX_G, (char)(d->length / 2), d->pointer, - CvtIEEE_T, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FT: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; + m->h.ndims = 0; } - break; - case VMSG_CLIENT: - switch (d->dtype) + else { - case DTYPE_F: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - convert_float(num, CvtVAX_D, sizeof(double), d->pointer, CvtVAX_G, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - convert_float(num * 2, CvtVAX_D, (char)(d->length / 2), d->pointer, - CvtVAX_G, (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FS: - convert_float(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FSC: - convert_float(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_FT: - convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_FTC: - convert_float(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_G, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - default: - memcpy(m->bytes, d->pointer, nbytes); - break; + int i; + array_coeff *a = (array_coeff *)d; + m->h.ndims = a->dimct; + if (a->aflags.coeff) + for (i = 0; i < m->h.ndims && i < MAX_DIMS; i++) + m->h.dims[i] = a->m[i]; + else + m->h.dims[0] = a->length ? a->arsize / a->length : 0; + for (i = m->h.ndims; i < MAX_DIMS; i++) + m->h.dims[i] = 0; } - break; - default: - switch (d->dtype) + switch (CType(client_type)) { - case DTYPE_F: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_FLOAT; - break; - case DTYPE_FC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX; - break; - case DTYPE_D: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_DC: - memcpy(m->bytes, d->pointer, nbytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_G: - convert_float(num, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; - break; - case DTYPE_GC: - convert_float(num * 2, CvtVAX_G, sizeof(double), d->pointer, CvtVAX_D, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; - break; - case DTYPE_FS: - convert_float(num, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_FLOAT; + case IEEE_CLIENT: + case JAVA_CLIENT: + convert_ieee(m, num, d, nbytes); break; - case DTYPE_FSC: - convert_float(num * 2, CvtIEEE_S, sizeof(float), d->pointer, CvtVAX_F, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX; + case CRAY_CLIENT: + convert_cray(m, num, d, nbytes); break; - case DTYPE_FT: - convert_float(num, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, - (char)m->h.length, m->bytes); - m->h.dtype = DTYPE_DOUBLE; + case CRAY_IEEE_CLIENT: + convert_cray_ieee(m, num, d, nbytes); break; - case DTYPE_FTC: - convert_float(num * 2, CvtIEEE_T, sizeof(double), d->pointer, CvtVAX_D, - (char)(m->h.length / 2), m->bytes); - m->h.dtype = DTYPE_COMPLEX_DOUBLE; + case VMSG_CLIENT: + convert_vmsg(m, num, d, nbytes); break; default: - memcpy(m->bytes, d->pointer, nbytes); + convert_default(m, num, d, nbytes); break; } - break; } - status = SendMdsMsgC(connection, m, 0); - free(m); - free(message); + return SendMdsMsgC(connection, m, 0); +} + +/// returns true if message cleanup is handled +static int send_response(Connection *connection, Message *message, const int status_in, mdsdsc_t *const d) +{ + int status; + INIT_AND_FREE_ON_EXIT(Message *, m); + status = _send_response(connection, &m, status_in, d); + FREE_NOW(m); if (STATUS_NOT_OK) - DisconnectConnection(connection->id); + return FALSE; // no good close connection + free(message); + return TRUE; +} + +/// returns true if message cleanup is handled +static int return_status(Connection *connection, Message *message, int status) +{ + struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&status}; + return send_response(connection, message, 1, &ans_d); } static void GetErrorText(int status, mdsdsc_xd_t *xd) @@ -487,54 +591,51 @@ static void GetErrorText(int status, mdsdsc_xd_t *xd) MdsCopyDxXd((mdsdsc_t *)&unknown, xd); } -static void client_event_ast(MdsEventList *e, int data_len, char *data) +static void _client_event_ast_cleanup(Message **m) +{ + free(*m); + UnlockAsts(); +} + +static inline void _client_event_ast(MdsEventList *e, int data_len, char *data, int client_type, Message **m) { - Connection *c = FindConnection(e->conid, 0); - int i; - char client_type; - Message *m; - JMdsEventInfo *info; int len; - // Check Connection: if down, cancel the event and return - if (!c) - { - MDSEventCan(e->eventid); - return; - } - client_type = c->client_type; - LockAsts(); if (CType(client_type) == JAVA_CLIENT) { + JMdsEventInfo *info; len = sizeof(MsgHdr) + sizeof(JMdsEventInfo); - m = memset(malloc(len), 0, len); - m->h.ndims = 0; - m->h.client_type = client_type; - m->h.msglen = len; - m->h.dtype = DTYPE_EVENT_NOTIFY; - info = (JMdsEventInfo *)m->bytes; - if (data_len > 0) - memcpy(info->data, data, (data_len < 12) ? data_len : 12); - for (i = data_len; i < 12; i++) - info->data[i] = 0; + *m = calloc(1, len); + info = (JMdsEventInfo *)(*m)->bytes; info->eventid = e->jeventid; } else { - m = memset(malloc(sizeof(MsgHdr) + e->info_len), 0, - sizeof(MsgHdr) + e->info_len); - m->h.ndims = 0; - m->h.client_type = client_type; - m->h.msglen = sizeof(MsgHdr) + e->info_len; - m->h.dtype = DTYPE_EVENT_NOTIFY; - if (data_len > 0) - memcpy(e->info->data, data, (data_len < 12) ? data_len : 12); - for (i = data_len; i < 12; i++) - e->info->data[i] = 0; - memcpy(m->bytes, e->info, e->info_len); + len = sizeof(MsgHdr) + e->info_len; + *m = calloc(1, len); + memcpy((*m)->bytes, e->info, e->info_len); } - SendMdsMsg(e->conid, m, MSG_DONTWAIT); - free(m); - UnlockAsts(); + (*m)->h.client_type = client_type; + (*m)->h.msglen = len; + (*m)->h.dtype = DTYPE_EVENT_NOTIFY; + if (data_len > 0) + memcpy(e->info->data, data, (data_len < 12) ? data_len : 12); + SendMdsMsg(e->conid, *m, MSG_DONTWAIT); +} + +static void client_event_ast(MdsEventList *e, int data_len, char *data) +{ + const client_t client_type = GetConnectionClientType(e->conid); + // Check Connection: if down, cancel the event and return + if (client_type == INVALID_CLIENT) + { + MDSEventCan(e->eventid); + return; + } + LockAsts(); + Message *m = NULL; + pthread_cleanup_push((void *)_client_event_ast_cleanup, (void *)&m); + _client_event_ast(e, data_len, data, client_type, &m); + pthread_cleanup_pop(1); } typedef struct @@ -569,18 +670,31 @@ static inline int execute_command(Connection *connection, mdsdsc_xd_t *ans_xd) p.connection = connection; EMPTYXD(xd); p.xdp = &xd; + const int serialize_out = connection->descrip[0]->dtype == DTYPE_SERIAL; + if (serialize_out) + { + connection->descrip[0]->dtype = DTYPE_T; + } pthread_cleanup_push(cleanup_command, (void *)&p); TDITHREADSTATIC_INIT; --TDI_INTRINSIC_REC; status = TdiIntrinsic(OPC_EXECUTE, connection->nargs, connection->descrip, &xd); ++TDI_INTRINSIC_REC; if (STATUS_OK) - status = TdiData(xd.pointer, ans_xd MDS_END_ARG); + { + if (serialize_out) + { + connection->descrip[0]->dtype = DTYPE_SERIAL; + status = MdsSerializeDscOut(xd.pointer, ans_xd); + } + else + status = TdiData(xd.pointer, ans_xd MDS_END_ARG); + } pthread_cleanup_pop(1); return status; } -/// +/// returns true if message cleanup is handled /// Executes TDI expression held by a connecion instance. This first searches if /// connection message corresponds to AST or CAN requests, if no asyncronous ops /// are requested the TDI actual expression is parsed through tdishr library. @@ -597,16 +711,20 @@ static inline int execute_command(Connection *connection, mdsdsc_xd_t *ans_xd) /// arguments \return the execute message answer built using BuildAnswer() /// -static void execute_message(Connection *connection, Message *message) +static int execute_message(Connection *connection, Message *message) { - int status = 1; // return status // - + int status = 1; + int freed_message = FALSE; char *evname; - DESCRIPTOR(eventastreq, EVENTASTREQUEST); // AST request descriptor // - DESCRIPTOR(eventcanreq, EVENTCANREQUEST); // Can request descriptor // + static const DESCRIPTOR(eventastreq, EVENTASTREQUEST); // AST request descriptor // + static const DESCRIPTOR(eventcanreq, EVENTCANREQUEST); // Can request descriptor // const int java = CType(connection->client_type) == JAVA_CLIENT; - - if (StrCompare(connection->descrip[0], (mdsdsc_t *)&eventastreq) == 0) + if (!connection->descrip[0]) + { + MDSWRN("NULL_ptr as first descrip argument"); + freed_message = return_status(connection, message, TdiNULL_PTR); + } + else if (StrCompare(connection->descrip[0], (mdsdsc_t *)&eventastreq) == 0) { // AST REQUEST // int eventid = -1; DESCRIPTOR_LONG(eventiddsc, &eventid); @@ -656,9 +774,12 @@ static void execute_message(Connection *connection, Message *message) connection->event = newe; } if (!java) - send_response(connection, message, status, &eventiddsc); + freed_message = send_response(connection, message, status, &eventiddsc); else + { free(message); + freed_message = TRUE; + } } else if (StrCompare(connection->descrip[0], (mdsdsc_t *)&eventcanreq) == 0) { // CAN REQUEST // @@ -683,9 +804,12 @@ static void execute_message(Connection *connection, Message *message) } } if (!java) - send_response(connection, message, status, &eventiddsc); + freed_message = send_response(connection, message, status, &eventiddsc); else + { free(message); + freed_message = TRUE; + } } else // NORMAL TDI COMMAND // { @@ -693,206 +817,235 @@ static void execute_message(Connection *connection, Message *message) status = execute_command(connection, &ans_xd); if (STATUS_NOT_OK) GetErrorText(status, &ans_xd); - if (GetCompressionLevel() != connection->compression_level) - { - connection->compression_level = GetCompressionLevel(); - if (connection->compression_level > GetMaxCompressionLevel()) - connection->compression_level = GetMaxCompressionLevel(); - SetCompressionLevel(connection->compression_level); - } - - send_response(connection, message, status, ans_xd.pointer); + connection->compression_level = GetCompressionLevel(); + freed_message = send_response(connection, message, status, ans_xd.pointer); FREEXD_NOW(ans_xd); } FreeDescriptors(connection); + return freed_message; } -static void standard_command(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static int standard_command(Connection *connection, Message *message) { + if (connection->message_id != message->h.message_id) + { + MDSDBG("%d NewM %3d (%2d/%2d) : '%.*s'", + connection->id, message->h.message_id, message->h.descriptor_idx, message->h.nargs, + message->h.length, message->bytes); + FreeDescriptors(connection); + if (message->h.nargs < MDSIP_MAX_ARGS - 1) + { + connection->message_id = message->h.message_id; + connection->nargs = message->h.nargs; + } + else + { + return return_status(connection, message, 0); + } + } // set connection to the message client_type // connection->client_type = message->h.client_type; -#define COPY_DESC(name, GENERATOR, ...) \ - do \ - { \ - const GENERATOR(__VA_ARGS__); \ - *(void **)&d = memcpy(malloc(sizeof(tmp)), &tmp, sizeof(tmp)); \ - } while (0) - // d -> reference to curent idx argument desctriptor // - + int status = 1; mdsdsc_t *d = connection->descrip[message->h.descriptor_idx]; if (message->h.dtype == DTYPE_SERIAL) { - if (d && d->class != CLASS_XD) + MdsFreeDescriptor(d); + mdsdsc_xd_t xd = MDSDSC_XD_INITIALIZER; + MDSDBG("%d NewA %3d (%2d/%2d) : serial", + connection->id, message->h.message_id, message->h.descriptor_idx + 1, message->h.nargs); + status = MdsSerializeDscIn(message->bytes, &xd); + connection->descrip[message->h.descriptor_idx] = d = xd.pointer; + if (STATUS_OK && message->h.descriptor_idx == 0 && d->dtype == DTYPE_T) { - if (d->class == CLASS_D && d->pointer) - free(d->pointer); - free(d); + d->dtype = DTYPE_SERIAL; } - COPY_DESC(d, EMPTYXD, tmp); - connection->descrip[message->h.descriptor_idx] = d; - free(message); - return; } - if (!d) + else { - // instance the connection descriptor field // - const short lengths[] = {0, 0, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 8, 16, 0}; - if (message->h.ndims == 0) + if (!d) { - d = calloc(1, sizeof(struct descriptor_s)); - d->class = CLASS_S; - } - else - COPY_DESC(d, DESCRIPTOR_A_COEFF, tmp, 0, 0, 0, MAX_DIMS, 0); - d->length = message->h.dtype < DTYPE_CSTRING ? lengths[message->h.dtype] - : message->h.length; - d->dtype = message->h.dtype; - if (d->class == CLASS_A) - { - array_coeff *a = (array_coeff *)d; - int num = 1; - int i; - a->dimct = message->h.ndims; - for (i = 0; i < a->dimct; i++) + // instance the connection descriptor field // + const short lengths[] = {0, 0, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 8, 16, 0}; + length_t length = message->h.dtype < DTYPE_CSTRING + ? lengths[message->h.dtype] + : message->h.length; + if (message->h.ndims == 0) { - a->m[i] = message->h.dims[i]; - num *= a->m[i]; + d = malloc(sizeof(mdsdsc_s_t) + length); + d->class = CLASS_S; + d->dtype = message->h.dtype; + d->length = length; + d->pointer = length ? (void *)d + sizeof(mdsdsc_s_t) : 0; } - a->arsize = a->length * num; - a->pointer = a->a0 = malloc(a->arsize); + else + { + static const DESCRIPTOR_A_COEFF(empty, 0, 0, 0, MAX_DIMS, 0); + int i; + int num = 1; + for (i = 0; i < message->h.ndims; i++) + { + num *= message->h.dims[i]; + } + arsize_t arsize = length * num; + d = memcpy(malloc(sizeof(empty) + arsize), &empty, sizeof(empty)); + d->dtype = message->h.dtype; + array_coeff *a = (array_coeff *)d; + a->dimct = message->h.ndims; + for (i = 0; i < a->dimct; i++) + { + a->m[i] = message->h.dims[i]; + } + a->length = length; + a->arsize = arsize; + a->pointer = a->a0 = (void *)d + sizeof(empty); + } + connection->descrip[message->h.descriptor_idx] = d; } - else - d->pointer = d->length ? malloc(d->length) : 0; - // set new instance // - connection->descrip[message->h.descriptor_idx] = d; - } - if (d) - { - // have valid connection descriptor instance // - // copy the message buffer into the descriptor // - - int dbytes = d->class == CLASS_S ? (int)d->length - : (int)((array_coeff *)d)->arsize; - int num = d->length > 1 ? (dbytes / d->length) : dbytes; - - switch (CType(connection->client_type)) + if (d) { - case IEEE_CLIENT: - case JAVA_CLIENT: - memcpy(d->pointer, message->bytes, dbytes); - break; - case CRAY_IEEE_CLIENT: - switch (d->dtype) + // have valid connection descriptor instance // + // copy the message buffer into the descriptor // + int dbytes = d->class == CLASS_S + ? (int)d->length + : (int)((array_coeff *)d)->arsize; + int num = d->length > 1 ? (dbytes / d->length) : dbytes; + + switch (CType(connection->client_type)) { - case DTYPE_USHORT: - case DTYPE_ULONG: - convert_binary(num, 0, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - convert_binary(num, 1, message->h.length, message->bytes, d->length, - d->pointer); - break; - default: + case IEEE_CLIENT: + case JAVA_CLIENT: memcpy(d->pointer, message->bytes, dbytes); break; - } - break; - case CRAY_CLIENT: - switch (d->dtype) - { - case DTYPE_USHORT: - case DTYPE_ULONG: - convert_binary(num, 0, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_SHORT: - case DTYPE_LONG: - convert_binary(num, 1, message->h.length, message->bytes, d->length, - d->pointer); - break; - case DTYPE_FLOAT: - convert_float(num, CvtCRAY, (char)message->h.length, message->bytes, - CvtIEEE_S, (char)d->length, d->pointer); - break; - case DTYPE_COMPLEX: - convert_float(num * 2, CvtCRAY, (char)(message->h.length / 2), - message->bytes, CvtIEEE_S, (char)(d->length / 2), - d->pointer); + case CRAY_IEEE_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, message->h.length, message->bytes, d->length, + d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } break; - case DTYPE_DOUBLE: - convert_float(num, CvtCRAY, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); + case CRAY_CLIENT: + switch (d->dtype) + { + case DTYPE_USHORT: + case DTYPE_ULONG: + convert_binary(num, 0, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_SHORT: + case DTYPE_LONG: + convert_binary(num, 1, message->h.length, message->bytes, d->length, + d->pointer); + break; + case DTYPE_FLOAT: + convert_float(num, CRAY, (char)message->h.length, message->bytes, + IEEE_S, (char)d->length, d->pointer); + break; + case DTYPE_COMPLEX: + convert_float(num * 2, CRAY, (char)(message->h.length / 2), + message->bytes, IEEE_S, (char)(d->length / 2), + d->pointer); + break; + case DTYPE_DOUBLE: + convert_float(num, CRAY, (char)message->h.length, message->bytes, + IEEE_T, sizeof(double), d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } break; default: - memcpy(d->pointer, message->bytes, dbytes); - break; + switch (d->dtype) + { + case DTYPE_FLOAT: + convert_float(num, VAX_F, (char)message->h.length, message->bytes, + IEEE_S, sizeof(float), d->pointer); + break; + case DTYPE_COMPLEX: + convert_float(num * 2, VAX_F, (char)message->h.length, + message->bytes, IEEE_S, sizeof(float), d->pointer); + break; + case DTYPE_DOUBLE: + if (CType(connection->client_type) == VMSG_CLIENT) + convert_float(num, VAX_G, (char)message->h.length, message->bytes, + IEEE_T, sizeof(double), d->pointer); + else + convert_float(num, VAX_D, (char)message->h.length, message->bytes, + IEEE_T, sizeof(double), d->pointer); + break; + + case DTYPE_COMPLEX_DOUBLE: + if (CType(connection->client_type) == VMSG_CLIENT) + convert_float(num * 2, VAX_G, (char)(message->h.length / 2), + message->bytes, IEEE_T, sizeof(double), d->pointer); + else + convert_float(num * 2, VAX_D, (char)(message->h.length / 2), + message->bytes, IEEE_T, sizeof(double), d->pointer); + break; + default: + memcpy(d->pointer, message->bytes, dbytes); + break; + } } - break; - default: switch (d->dtype) { + default: + break; case DTYPE_FLOAT: - convert_float(num, CvtVAX_F, (char)message->h.length, message->bytes, - CvtIEEE_S, sizeof(float), d->pointer); + d->dtype = DTYPE_FS; break; case DTYPE_COMPLEX: - convert_float(num * 2, CvtVAX_F, (char)message->h.length, - message->bytes, CvtIEEE_S, sizeof(float), d->pointer); + d->dtype = DTYPE_FSC; break; case DTYPE_DOUBLE: - if (CType(connection->client_type) == VMSG_CLIENT) - convert_float(num, CvtVAX_G, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); - else - convert_float(num, CvtVAX_D, (char)message->h.length, message->bytes, - CvtIEEE_T, sizeof(double), d->pointer); + d->dtype = DTYPE_FT; break; - case DTYPE_COMPLEX_DOUBLE: - if (CType(connection->client_type) == VMSG_CLIENT) - convert_float(num * 2, CvtVAX_G, (char)(message->h.length / 2), - message->bytes, CvtIEEE_T, sizeof(double), d->pointer); - else - convert_float(num * 2, CvtVAX_D, (char)(message->h.length / 2), - message->bytes, CvtIEEE_T, sizeof(double), d->pointer); - break; - default: - memcpy(d->pointer, message->bytes, dbytes); + d->dtype = DTYPE_FTC; break; } + MDSDBG("%d NewA %3d (%2d/%2d) : simple", + connection->id, message->h.message_id, message->h.descriptor_idx + 1, message->h.nargs); } - switch (d->dtype) + else { - default: - break; - case DTYPE_FLOAT: - d->dtype = DTYPE_FS; - break; - case DTYPE_COMPLEX: - d->dtype = DTYPE_FSC; - break; - case DTYPE_DOUBLE: - d->dtype = DTYPE_FT; - break; - case DTYPE_COMPLEX_DOUBLE: - d->dtype = DTYPE_FTC; - break; + status = LibINSVIRMEM; } + } + if (STATUS_OK) + { // CALL EXECUTE MESSAGE // if (message->h.descriptor_idx == (message->h.nargs - 1)) { - execute_message(connection, message); - } - else - { - free(message); + MDSDBG("%d Call %3d (%2d/%2d)", + connection->id, message->h.message_id, message->h.descriptor_idx + 1, message->h.nargs); + int freed_message = execute_message(connection, message); + UnlockConnection(connection); + return freed_message; } + free(message); + return TRUE; + } + else + { + return return_status(connection, message, status); } } -static inline void mdsio_open_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_open_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; char *filename = (char *)message->bytes; @@ -913,19 +1066,21 @@ static inline void mdsio_open_k(Connection *connection, Message *message) fopts |= O_RDWR; int fd = MDS_IO_OPEN(filename, fopts, mode); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&fd}; - send_response(connection, message, 3, &ans_d); + return send_response(connection, message, 3, &ans_d); } -static inline void mdsio_close_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_close_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; int fd = mdsio->close.fd; int ans_o = MDS_IO_CLOSE(fd); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, 1, &ans_d); + return send_response(connection, message, 1, &ans_d); } -static inline void mdsio_lseek_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_lseek_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; int fd = mdsio->lseek.fd; @@ -936,10 +1091,11 @@ static inline void mdsio_lseek_k(Connection *connection, Message *message) struct descriptor ans_d = {8, DTYPE_Q, CLASS_S, 0}; ans_d.pointer = (char *)&ans_o; SWAP_INT_IF_BIGENDIAN(ans_d.pointer); - send_response(connection, message, 1, (mdsdsc_t *)&ans_d); + return send_response(connection, message, 1, (mdsdsc_t *)&ans_d); } -static inline void mdsio_read_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_read_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; int fd = mdsio->read.fd; @@ -949,22 +1105,25 @@ static inline void mdsio_read_k(Connection *connection, Message *message) #ifdef USE_PERF TreePerfRead(nbytes); #endif + int freed_message; if (nbytes > 0) { DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); if ((size_t)nbytes != count) - perror("READ_K wrong byte count"); - send_response(connection, message, 1, (mdsdsc_t *)&ans_d); + MDSWRN("READ_K wrong byte count"); + freed_message = send_response(connection, message, 1, (mdsdsc_t *)&ans_d); } else { DESCRIPTOR(ans_d, ""); - send_response(connection, message, 1, (mdsdsc_t *)&ans_d); + freed_message = send_response(connection, message, 1, (mdsdsc_t *)&ans_d); } free(buf); + return freed_message; } -static inline void mdsio_write_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_write_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; /* from http://man7.org/linux/man-pages/man2/write.2.html @@ -981,11 +1140,12 @@ static inline void mdsio_write_k(Connection *connection, Message *message) (char *)&ans_o}; SWAP_INT_IF_BIGENDIAN(ans_d.pointer); if (ans_o != mdsio->write.count) - perror("WRITE_K wrong byte count"); - send_response(connection, message, 1, &ans_d); + MDSWRN("WRITE_K wrong byte count"); + return send_response(connection, message, 1, &ans_d); } -static inline void mdsio_lock_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_lock_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; int fd = mdsio->lock.fd; @@ -998,35 +1158,39 @@ static inline void mdsio_lock_k(Connection *connection, Message *message) int deleted; int ans_o = MDS_IO_LOCK(fd, offset, size, mode | nowait, &deleted); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, deleted ? 3 : 1, &ans_d); + return send_response(connection, message, deleted ? 3 : 1, &ans_d); } -static inline void mdsio_exists_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_exists_k(Connection *connection, Message *message) { char *filename = message->bytes; int ans_o = MDS_IO_EXISTS(filename); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, 1, &ans_d); + return send_response(connection, message, 1, &ans_d); } -static inline void mdsio_remove_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_remove_k(Connection *connection, Message *message) { char *filename = message->bytes; int ans_o = MDS_IO_REMOVE(filename); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, 1, &ans_d); + return send_response(connection, message, 1, &ans_d); } -static inline void mdsio_rename_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_rename_k(Connection *connection, Message *message) { char *old = message->bytes; char *new = message->bytes + strlen(old) + 1; int ans_o = MDS_IO_RENAME(old, new); struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, 1, &ans_d); + return send_response(connection, message, 1, &ans_d); } -static inline void mdsio_read_x_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_read_x_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; int fd = mdsio->read_x.fd; @@ -1036,22 +1200,25 @@ static inline void mdsio_read_x_k(Connection *connection, Message *message) void *buf = malloc(count); int deleted; size_t nbytes = MDS_IO_READ_X(fd, offset, buf, count, &deleted); + int freed_message; if (nbytes > 0) { DESCRIPTOR_A(ans_d, 1, DTYPE_B, buf, nbytes); if ((size_t)nbytes != count) - perror("READ_X_K wrong byte count"); - send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); + MDSWRN("READ_X_K wrong byte count"); + freed_message = send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); } else { DESCRIPTOR(ans_d, ""); - send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); + freed_message = send_response(connection, message, deleted ? 3 : 1, (mdsdsc_t *)&ans_d); } free(buf); + return freed_message; } -static inline void mdsio_open_one_k(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static inline int mdsio_open_one_k(Connection *connection, Message *message) { const mdsio_t *mdsio = (mdsio_t *)message->h.dims; char *treename = message->bytes; @@ -1074,57 +1241,41 @@ static inline void mdsio_open_one_k(Connection *connection, Message *message) memcpy(msg + 8, fullpath, msglen - 8); free(fullpath); } - send_response(connection, message, 3, (mdsdsc_t *)&ans_d); + int freed_message = send_response(connection, message, 3, (mdsdsc_t *)&ans_d); free(msg); + return freed_message; } -static void return_status(Connection *connection, Message *message, int ans_o) -{ - struct descriptor ans_d = {4, DTYPE_L, CLASS_S, (char *)&ans_o}; - send_response(connection, message, 1, &ans_d); -} - -static void mdsio_command(Connection *connection, Message *message) +/// returns true if message cleanup is handled +static int mdsio_command(Connection *connection, Message *message) { connection->client_type = message->h.client_type; switch (message->h.descriptor_idx) { case MDS_IO_OPEN_K: - mdsio_open_k(connection, message); - break; + return mdsio_open_k(connection, message); case MDS_IO_CLOSE_K: - mdsio_close_k(connection, message); - break; + return mdsio_close_k(connection, message); case MDS_IO_LSEEK_K: - mdsio_lseek_k(connection, message); - break; + return mdsio_lseek_k(connection, message); case MDS_IO_READ_K: - mdsio_read_k(connection, message); - break; + return mdsio_read_k(connection, message); case MDS_IO_WRITE_K: - mdsio_write_k(connection, message); - break; + return mdsio_write_k(connection, message); case MDS_IO_LOCK_K: - mdsio_lock_k(connection, message); - break; + return mdsio_lock_k(connection, message); case MDS_IO_EXISTS_K: - mdsio_exists_k(connection, message); - break; + return mdsio_exists_k(connection, message); case MDS_IO_REMOVE_K: - mdsio_remove_k(connection, message); - break; + return mdsio_remove_k(connection, message); case MDS_IO_RENAME_K: - mdsio_rename_k(connection, message); - break; + return mdsio_rename_k(connection, message); case MDS_IO_READ_X_K: - mdsio_read_x_k(connection, message); - break; + return mdsio_read_x_k(connection, message); case MDS_IO_OPEN_ONE_K: - mdsio_open_one_k(connection, message); - break; + return mdsio_open_one_k(connection, message); default: - return_status(connection, message, 0); - break; + return return_status(connection, message, 0); } } @@ -1132,7 +1283,7 @@ static void mdsio_command(Connection *connection, Message *message) #ifdef THREADED_IO struct command { - void (*method)(Connection *, Message *); + int (*method)(Connection *, Message *); Connection *connection; Message *message; }; @@ -1140,12 +1291,14 @@ struct command static void *thread_command(void *args) { struct command *cm = (struct command *)args; - cm->method(cm->connection, cm->message); + if (!cm->method(cm->connection, cm->message)) + free(cm->message); return NULL; } -static Message *dispatch_command( - void (*method)(Connection *, Message *), +/// returns true if message cleanup is handled +static int dispatch_command( + int (*method)(Connection *, Message *), Connection *connection, Message *message) { @@ -1156,12 +1309,14 @@ static Message *dispatch_command( args->connection = connection; args->message = message; pthread_t thread; - if (pthread_create(&thread, NULL, thread_command, (void *)args)) - perror("pthread_create"); - else if (pthread_detach(thread)) - perror("pthread_detach"); + if ((errno = pthread_create(&thread, NULL, thread_command, (void *)args))) + MDSERR("pthread_create"); + else if ((errno = pthread_detach(thread))) + MDSERR("pthread_detach"); + else + return TRUE; } - return_status(connection, message, MDSplusFATAL); + return return_status(connection, message, MDSplusFATAL); } #endif @@ -1172,41 +1327,24 @@ static Message *dispatch_command( /// /// \param connection the connection instance to handle /// \param message the message to process -/// \return message answer +/// \return true if message cleanup is handled /// -void ProcessMessage(Connection *connection, Message *message) +int ProcessMessage(Connection *connection, Message *message) { - //MDSplusThreadStatic(connection->mts); - // COMING NEW MESSAGE // - // reset connection id // - if (connection->message_id != message->h.message_id) - { - FreeDescriptors(connection); - if (message->h.nargs < MDSIP_MAX_ARGS - 1) - { - connection->message_id = message->h.message_id; - connection->nargs = message->h.nargs; - } - else - { - return_status(connection, message, 0); - return; - } - } - if (message->h.descriptor_idx < connection->nargs) + if (message->h.descriptor_idx < message->h.nargs) { #ifdef THREADED_IO - dispatch_command(standard_command, connection, message); + return dispatch_command(standard_command, connection, message); #else - standard_command(connection, message); + return standard_command(connection, message); #endif } else { #ifdef THREADED_IO - dispatch_command(mdsio_command, connection, message); + return dispatch_command(mdsio_command, connection, message); #else - mdsio_command(connection, message); + return mdsio_command(connection, message); #endif } } diff --git a/mdstcpip/mdsipshr/SendArg.c b/mdstcpip/mdsipshr/SendArg.c index 39488788be..825a8f33a4 100644 --- a/mdstcpip/mdsipshr/SendArg.c +++ b/mdstcpip/mdsipshr/SendArg.c @@ -51,7 +51,7 @@ int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, unsigned short length, char ndims, int *dims, char *bytes) { Connection *c = (idx == 0 || idx > nargs) - ? FindConnectionWithLock(id, CON_SENDARG) + ? FindConnectionWithLock(id, CON_REQUEST) : FindConnectionSending(id); if (!c) return MDSplusERROR; // both methods will leave connection id unlocked @@ -84,7 +84,6 @@ int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, msglen = sizeof(MsgHdr) + nbytes; m = malloc(msglen); memset(&m->h, 0, sizeof(m->h)); - m->h.client_type = 0; m->h.msglen = msglen; m->h.descriptor_idx = idx; m->h.dtype = dtype; @@ -101,7 +100,7 @@ int SendArg(int id, unsigned char idx, char dtype, unsigned char nargs, #endif if (nbytes > 0) memcpy(m->bytes, bytes, nbytes); - m->h.message_id = (idx == 0 || nargs == 0) ? IncrementConnectionMessageIdC(c) + m->h.message_id = (idx == 0 || nargs == 0) ? ConnectionIncMessageId(c) : c->message_id; int status = m->h.message_id ? SendMdsMsgC(c, m, 0) : MDSplusERROR; free(m); diff --git a/mdstcpip/mdsipshr/SendMdsMsg.c b/mdstcpip/mdsipshr/SendMdsMsg.c index e98991bad1..fd6c60e451 100644 --- a/mdstcpip/mdsipshr/SendMdsMsg.c +++ b/mdstcpip/mdsipshr/SendMdsMsg.c @@ -22,57 +22,56 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "../zlib/zlib.h" +#include "../mdsip_connections.h" + #include #include #include #include #include -#include "../zlib/zlib.h" - -#include "../mdsip_connections.h" +//#define DEBUG +#include -static int SendBytes(Connection *c, void *buffer, size_t bytes_to_send, - int options) +static int send_bytes(Connection *c, void *buffer, size_t bytes_to_send, int options) { + if (!c || !c->io) + return MDSplusERROR; char *bptr = (char *)buffer; - if (c && c->io) + int tries = 0; + MDSDBG(CON_PRI " %ld bytes", CON_VAR(c), (long)bytes_to_send); + while ((bytes_to_send > 0) && (tries < 10)) { - int tries = 0; - while ((bytes_to_send > 0) && (tries < 10)) + ssize_t bytes_sent; + bytes_sent = c->io->send(c, bptr, bytes_to_send, options); + if (bytes_sent < 0) { - ssize_t bytes_sent; - bytes_sent = c->io->send(c, bptr, bytes_to_send, options); - if (bytes_sent < 0) + if (errno != EINTR) { - if (errno != EINTR) - { - perror("Error sending data to remote server"); - return MDSplusERROR; - } - tries++; - } - else - { - bytes_to_send -= bytes_sent; - bptr += bytes_sent; - if (bytes_sent) - tries = 0; - else - tries++; + MDSDBG(CON_PRI " error %d: %s", CON_VAR(c), errno, strerror(errno)); + perror("send_bytes: Error sending data to remote server"); + return MDSplusERROR; } + tries++; } - if (tries >= 10) + else { - char msg[256]; - sprintf(msg, "\rsend failed, shutting down connection %d", c->id); - perror(msg); - return SsINTERNAL; + bytes_to_send -= bytes_sent; + bptr += bytes_sent; + if (bytes_sent) + tries = 0; + else + tries++; } - return MDSplusSUCCESS; } - printf("Connection to remote server failed"); - return MDSplusERROR; + if (tries >= 10) + { + MDSERR(CON_PRI " send failed; shutting down", CON_VAR(c)); + return SsINTERNAL; + } + MDSDBG(CON_PRI " sent all bytes", CON_VAR(c)); + return MDSplusSUCCESS; } int SendMdsMsgC(Connection *c, Message *m, int msg_options) @@ -82,7 +81,7 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) Message *cm = 0; int status; int do_swap = 0; /*Added to handle byte swapping with compression */ - if (len > 0 && GetCompressionLevel() > 0 && + if (len > 0 && c->compression_level > 0 && m->h.client_type != SENDCAPABILITIES) { clength = len; @@ -91,7 +90,7 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) if (!msg_options && c && c->io && c->io->flush) c->io->flush(c); if (m->h.client_type == SENDCAPABILITIES) - m->h.status = GetCompressionLevel(); + m->h.status = c->compression_level; if ((m->h.client_type & SwapEndianOnServer) != 0) { if (Endian(m->h.client_type) != Endian(ClientType())) @@ -105,19 +104,20 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) m->h.client_type = ClientType(); if (clength && compress2((unsigned char *)cm->bytes + 4, &clength, - (unsigned char *)m->bytes, len, GetCompressionLevel()) == 0 && + (unsigned char *)m->bytes, len, c->compression_level) == 0 && clength < len) { cm->h = m->h; cm->h.client_type |= COMPRESSED; memcpy(cm->bytes, &cm->h.msglen, 4); int msglen = cm->h.msglen = clength + 4 + sizeof(MsgHdr); + MDSDBG(MESSAGE_PRI, MESSAGE_VAR(cm)); if (do_swap) FlipBytes(4, (char *)&cm->h.msglen); - status = SendBytes(c, (char *)cm, msglen, msg_options); + status = send_bytes(c, (char *)cm, msglen, msg_options); } else - status = SendBytes(c, (char *)m, len + sizeof(MsgHdr), msg_options); + status = send_bytes(c, (char *)m, len + sizeof(MsgHdr), msg_options); if (clength) free(cm); return status; @@ -125,10 +125,12 @@ int SendMdsMsgC(Connection *c, Message *m, int msg_options) int SendMdsMsg(int id, Message *m, int msg_options) { - Connection *c = FindConnection(id, NULL); - if (SendMdsMsgC(c, m, msg_options) == SsINTERNAL) + Connection *c = FindConnectionWithLock(id, CON_REQUEST); + int status = SendMdsMsgC(c, m, msg_options); + if (status == SsINTERNAL) { - DisconnectConnection(id); + UnlockConnection(c); + CloseConnection(id); return MDSplusFATAL; } return MDSplusSUCCESS; diff --git a/mdstcpip/mdsipshr/cvtdef.h b/mdstcpip/mdsipshr/cvtdef.h deleted file mode 100644 index 2bcb01852c..0000000000 --- a/mdstcpip/mdsipshr/cvtdef.h +++ /dev/null @@ -1,51 +0,0 @@ -/********************************************************************************************************************************/ -/* Created: 28-DEC-1995 08:04:14 by OpenVMS SDL EV1-33 */ -/* Source: 28-DEC-1995 08:03:53 HARPO$DKA400:[SYS0.SYSUPD.CC052]CVTDEF.SDI;1 */ -/********************************************************************************************************************************/ -/*** MODULE cvtdef ***/ -#ifndef __CVTDEF_LOADED -#define __CVTDEF_LOADED 1 - -//#ifndef _MSC_VER -//#pragma nostandard -//#endif - -#ifdef __cplusplus -extern "C" -{ -#define __unknown_params ... -#else -#define __unknown_params -#endif - -#if !defined(__VAXC) && !defined(VAXC) -#define __struct struct -#define __union union -#else -#define __struct variant_struct -#define __union variant_union -#endif - -#define CvtVAX_F 10 /* VAX F Floating point data */ -#define CvtVAX_D 11 /* VAX D Floating point data */ -#define CvtVAX_G 27 /* VAX G Floating point data */ -#define CvtVAX_H 28 /* VAX H Floating point data */ -#define CvtIEEE_S 52 /* IEEE S Floating point data */ -#define CvtIEEE_T 53 /* IEEE T Floating point data */ -#define CvtIBM_LONG 6 /* IBM Long Floating point data */ -#define CvtIBM_SHORT 7 /* IBM Short Floating point data */ -#define CvtCRAY 8 /* Cray Floating point data */ -#define CvtIEEE_X 9 /* IEEE X Floating point data */ - - extern int CvtConvertFloat(void *invalue, uint32_t indtype, void *outvalue, - uint32_t outdtype, uint32_t options); - -#ifdef __cplusplus -} -#endif - -//#ifndef _MSC_VER -//#pragma standard -//#endif - -#endif /* __CVTDEF_LOADED */ diff --git a/mdstcpip/mdsipshr/mdsipthreadstatic.h b/mdstcpip/mdsipshr/mdsipthreadstatic.h new file mode 100644 index 0000000000..cdc21dd368 --- /dev/null +++ b/mdstcpip/mdsipshr/mdsipthreadstatic.h @@ -0,0 +1,18 @@ +#pragma once +#include "../mdsshr/mdsthreadstatic.h" +#include "../mdsip_connections.h" + +#define MDSIPTHREADSTATIC_VAR MdsIpThreadStatic_p +#define MDSIPTHREADSTATIC_TYPE MdsIpThreadStatic_t +#define MDSIPTHREADSTATIC_ARG MDSIPTHREADSTATIC_TYPE *MDSIPTHREADSTATIC_VAR +#define MDSIPTHREADSTATIC(MTS) MDSIPTHREADSTATIC_ARG = MdsIpGetThreadStatic(MTS) +#define MDSIPTHREADSTATIC_INIT MDSIPTHREADSTATIC(NULL) +typedef struct +{ + Connection *connections; + uint32_t clientaddr; +} MDSIPTHREADSTATIC_TYPE; +#define MDSIP_CLIENTADDR MDSIPTHREADSTATIC_VAR->clientaddr +#define MDSIP_CONNECTIONS MDSIPTHREADSTATIC_VAR->connections + +extern DEFINE_GETTHREADSTATIC(MDSIPTHREADSTATIC_TYPE, MdsIpGetThreadStatic); diff --git a/mdstcpip/testing/Makefile.am b/mdstcpip/testing/Makefile.am new file mode 100644 index 0000000000..45064608c7 --- /dev/null +++ b/mdstcpip/testing/Makefile.am @@ -0,0 +1,41 @@ + +include @top_builddir@/Makefile.inc +include ../../testing/testing.am + + +AM_CFLAGS = $(TARGET_ARCH) $(WARNFLAGS) $(TEST_CFLAGS) +AM_CXXFLAGS = $(TARGET_ARCH) $(WARNFLAGS) -Wno-deprecated @CXXFLAGS@ $(TEST_CFLAGS) +AM_LDFLAGS = -L@MAKESHLIBDIR@ $(RPATHLINK),@MAKESHLIBDIR@ +LDADD = @LIBS@ $(TEST_LIBS) -lMdsShr -lMdsIpShr + +## ////////////////////////////////////////////////////////////////////////// ## +## // TESTS //////////////////////////////////////////////////////////////// ## +## ////////////////////////////////////////////////////////////////////////// ## + +TEST_EXTENSIONS = .py .pl +AM_DEFAULT_SOURCE_EXT = .c + +TESTS = MdsIpTest + +VALGRIND_TESTS = $(TESTS) + +VALGRIND_SUPPRESSIONS_FILES = + + +# +# Files produced by tests that must be purged +# +MOSTLYCLEANFILES = + + +## ////////////////////////////////////////////////////////////////////////// ## +## // TARGETS ////////////////////////////////////////////////////////////// ## +## ////////////////////////////////////////////////////////////////////////// ## + + + +all-local: $(TESTS) +clean-local: clean-local-tests + +check_PROGRAMS = $(TESTS) +check_SCRIPTS = diff --git a/mdstcpip/testing/MdsIpTest.c b/mdstcpip/testing/MdsIpTest.c new file mode 100644 index 0000000000..e8eeb323f5 --- /dev/null +++ b/mdstcpip/testing/MdsIpTest.c @@ -0,0 +1,227 @@ +/* +Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "../mdsip_connections.h" +#include + +static int __test_passed = 0, __test_failed = 0; + +#define TEST_FATAL(cond, ...) \ + do \ + { \ + if (cond) \ + { \ + MDSWRN("FATAL: " __VA_ARGS__); \ + exit(1); \ + } \ + } while (0) + +#define TEST_FAIL(...) \ + do \ + { \ + MDSWRN("FAILED: " __VA_ARGS__); \ + __test_failed++; \ + } while (0) +#define TEST_PASS(...) \ + do \ + { \ + __test_passed++; \ + } while (0) + +static inline void TEST_TOTAL() +{ + if (__test_failed) + { + fprintf(stderr, "TOTAL: FAILED %d/%d\n", __test_failed, __test_failed + __test_passed); + exit(1); + } + else + { + fprintf(stderr, "TOTAL: PASSED %d/%d\n", __test_passed, __test_failed + __test_passed); + exit(0); + } +} + +#define TEST_TRUE(cond, ...) \ + if (!(cond)) \ + TEST_FAIL(__VA_ARGS__) +#define TEST_FALSE(cond, ...) \ + if ((cond)) \ + TEST_FAIL(__VA_ARGS__) +#define TEST_OK(...) TEST_TRUE(status & 1, __VA_ARGS__) + +static void test_value(int c, char *expr, dtype_t typ, int len, void *val) +{ + struct descrip ans = {0}; + int status = MdsValue(c, expr, &ans, NULL); + if (STATUS_NOT_OK) + TEST_FAIL("'%s' : STATUS = %d : %s\n", expr, status, MdsGetMsg(status)); + else if (ans.ndims != 0) + TEST_FAIL("'%s' : ndims\n", expr); + else if (ans.dtype != typ) + TEST_FAIL("'%s' : DTYPE %d != %d\n", expr, ans.dtype, typ); + else if (ans.length != len) + TEST_FAIL("'%s' : LENGTH %d != %d\n", expr, ans.length, len); + else if (memcmp(ans.ptr, val, len)) + TEST_FAIL("'%s' : VALUE\n", expr); + else + TEST_PASS(); + free(ans.ptr); +} +#define TEST_VALUE(expr, DT, type, val) \ + do \ + { \ + type v = val; \ + test_value(c, expr, DTYPE_##DT, sizeof(v), &v); \ + } while (0) + +extern int MdsIpGetDescriptor(int id, const char *expression, int nargs, + mdsdsc_t **arglist_in, + mdsdsc_xd_t *ans_ptr); +static void test_descr(int c, char *expr, int argn, mdsdsc_t **argv, class_t cls, dtype_t typ, int len, void *val) +{ + EMPTYXD(ans); + int status = MdsIpGetDescriptor(c, expr, argn, argv, &ans); + if (STATUS_NOT_OK) + TEST_FAIL("'%s' : STATUS = %d : %s\n", expr, status, MdsGetMsg(status)); + else if (ans.pointer->dtype != typ) + TEST_FAIL("'%s' : DTYPE %d != %d\n", expr, ans.pointer->dtype, typ); + else if (ans.pointer->length != len) + TEST_FAIL("'%s' : LENGTH %d != %d\n", expr, ans.pointer->length, len); + else if (memcmp(ans.pointer->pointer, val, len)) + TEST_FAIL("'%s' : VALUE\n", expr); + else if (ans.pointer->class != cls) + TEST_FAIL("'%s' : CLASS\n", expr); // fails if server does not serialize + else + TEST_PASS(); + MdsFree1Dx(&ans, NULL); +} + +#define TEST_DESCR(expr, DT, type, val) \ + do \ + { \ + type v = val; \ + test_descr(c, expr, 0, NULL, CLASS_S, DTYPE_##DT, sizeof(v), &v); \ + } while (0) + +void testio(char server[]) +{ + fprintf(stdout, "Testing io with '%s'\n", server); + int c = ConnectToMds(server); + TEST_DESCR("-1", L, int, -1); + TEST_FATAL(c == -1, "MdsConnection failed.\n"); + TEST_VALUE("-1", L, int, -1); + TEST_VALUE("0xffffffffLU", LU, uint32_t, -1); + TEST_VALUE("-1W", W, short, -1); + TEST_VALUE("-1B", B, char, -1); +} + +typedef struct +{ + pthread_t thread; + IoRoutines *io; + char **argv; + int argc; +} mdsip_t; + +void mdsip_main(void *arg) +{ + mdsip_t *param = (mdsip_t *)arg; + pthread_exit((void *)(intptr_t)param->io->listen(param->argc, param->argv)); +} + +#define MODE_SS 0b00 +#define MODE_MS 0b10 +#define MODE_SM 0b01 +#define MODE_MM 0b11 + +int start_mdsip(mdsip_t *mdsip, char *prot, int mode, char server[32], char *port) +{ + char *hostsfile = "mdsip.hosts"; + FILE *f = fopen(hostsfile, "w+"); + fprintf(f, (mode & MODE_MS) ? "multi|SELF\n*" : "*|SELF"); + fclose(f); + char *argv[] = { + "mdsip", + "-P", + prot, + (mode & MODE_SM) ? "-s" : "-m", + "-p", + port, + "-h", + hostsfile, + }; + int argc = sizeof(argv) / sizeof(char *); + ParseStdArgs(argc, argv, &mdsip->argc, &mdsip->argv); + mdsip->io = LoadIo(GetProtocol()); + TEST_FATAL(!mdsip->io || !mdsip->io->listen, "IoRoutine for protocol '%s' has no listen.", prot); + sprintf(server, "localhost:%s", port); + return pthread_create(&mdsip->thread, NULL, (void *)mdsip_main, (void *)mdsip); +} + +int main(int argc, char **argv) +{ + (void)test_value; + (void)test_descr; + atexit(TEST_TOTAL); + if (argc > 1) + { + int i; + for (i = 1; i < argc; i++) + { + testio(argv[i]); + } + } + else + { + testio("thread://0"); + testio("local://0"); + char server[32] = ""; + mdsip_t mdsip = {0, NULL, NULL, 0}; + if (!start_mdsip(&mdsip, "Tcp", MODE_SS, server, "12345")) + { + sleep(3); + testio(server); +#ifdef _WIN32 + // TODO: kill? +#else + pthread_cancel(mdsip.thread); + pthread_join(mdsip.thread, NULL); +#endif + } + free(mdsip.argv); + } + return 0; +} diff --git a/mdstcpip/testing/mdscp.c b/mdstcpip/testing/mdscp.c index a4f2a2233b..a2128aadb6 100644 --- a/mdstcpip/testing/mdscp.c +++ b/mdstcpip/testing/mdscp.c @@ -88,7 +88,7 @@ static void printHelp() static int doOpen(int streams, char *name, int options, int mode, struct mdsfile *mfile) { - char *tmp = strcpy((char *)malloc(strlen(name) + 1), name); + char *tmp = strdup(name); char *hostpart = tmp; char *filepart = strstr(tmp, "::"); int status; @@ -123,7 +123,7 @@ static int doOpen(int streams, char *name, int options, int mode, info[2] = (int)mode; status = SendArg(mfile->socket, MDS_IO_OPEN_K, 0, 0, 0, sizeof(info) / sizeof(int), info, filepart); - if (status & 1) + if (STATUS_OK) { char dtype; short length; @@ -162,11 +162,9 @@ static int doOpen(int streams, char *name, int options, int mode, mfile->fd = open(name, options, mode); if (mfile->fd == -1) { - char *fmt = "Error opening file: %s"; - char *msg = (char *)malloc(strlen(name) + strlen(fmt) + 10); - sprintf(msg, fmt, name); + char *msg = alloc(strlen(name) + 32); + sprintf(msg, "Error opening file: %s", name); perror(msg); - free(msg); status = -1; } else @@ -195,7 +193,7 @@ off_t getSize(struct mdsfile *file) *(off_t *)(&info[2]) = 0; status = SendArg(sock, MDS_IO_LSEEK_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) + if (STATUS_OK) { char dtype; unsigned short length; @@ -217,7 +215,7 @@ off_t getSize(struct mdsfile *file) } status = SendArg(sock, MDS_IO_LSEEK_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) + if (STATUS_OK) { char dtype; unsigned short length; @@ -258,7 +256,7 @@ off_t doRead(struct mdsfile *file, off_t count, void *buff) info[2] = count; status = SendArg(sock, MDS_IO_READ_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) + if (STATUS_OK) { char dtype; unsigned short length; @@ -297,7 +295,7 @@ static off_t doWrite(struct mdsfile *file, off_t count, void *buff) info[0] = count; status = SendArg(sock, MDS_IO_WRITE_K, 0, 0, 0, sizeof(info) / sizeof(int), info, buff); - if (status & 1) + if (STATUS_OK) { char dtype; unsigned short length; @@ -333,7 +331,7 @@ static int doClose(struct mdsfile *file) info[1] = file->fd; status = SendArg(sock, MDS_IO_CLOSE_K, 0, 0, 0, sizeof(info) / sizeof(int), info, 0); - if (status & 1) + if (STATUS_OK) { char dtype; short length; diff --git a/mdstcpip/testing/mdsiptest.c b/mdstcpip/testing/mdsiptest.c deleted file mode 100644 index 5d92fdc218..0000000000 --- a/mdstcpip/testing/mdsiptest.c +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* CMS REPLACEMENT HISTORY, Element T.C */ -/* *3 16-OCT-1995 13:31:44 TWF "Update from msdos" */ -/* *2 5-JAN-1995 14:07:43 TWF "new definitions" */ -/* *1 28-NOV-1994 15:30:39 TWF "Test program for mdstcpip" */ -/* CMS REPLACEMENT HISTORY, Element T.C */ -#include -#include -#include -int main(int argc, char **argv) -{ - int status; - struct descrip ans; - float val = 9876; - struct descrip vald = {DTYPE_FLOAT, 0, {0}, 0, 0}; - long sock = ConnectToMds((argc > 1) ? argv[1] : "lost.pfc.mit.edu:9000"); - if (sock != -1) - { - printf("status from MdsOpen = %d\n", MdsOpen(sock, "main", -1)); - ans.ptr = 0; - if (MdsValue(sock, "f_float(member)", &ans, NULL) & 1) - { - printf("%g\n", *(float *)ans.ptr); - val = *(float *)ans.ptr; - val = val + (float)1.; - } - else - printf("%s\n", (char *)ans.ptr); - if (ans.ptr) - { - free(ans.ptr); - ans.ptr = 0; - } - vald.ptr = (void *)&val; - status = MdsPut(sock, "member", "$", &vald, NULL); - if (!(status & 1)) - printf("Error during put %d\n", status); - if (MdsValue(sock, "42.0", &ans, NULL) & 1) - printf("%g\n", *(float *)ans.ptr); - else - printf("%s\n", (char *)ans.ptr); - free(ans.ptr); - } - return 1; -} diff --git a/mitdevices/DevRoutines.c b/mitdevices/DevRoutines.c index 1db689e327..d2491e7939 100644 --- a/mitdevices/DevRoutines.c +++ b/mitdevices/DevRoutines.c @@ -24,7 +24,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include -#include +#include "mitdevices_msg.h" #include #include #include @@ -55,7 +55,7 @@ EXPORT int DevFloat(int *nid, float *ans) EXPORT int DevCamChk(int status, int *expect_x, int *expect_q) { - if (!(status & 1)) + if (STATUS_NOT_OK) return status; if (expect_x) { @@ -90,7 +90,7 @@ EXPORT int DevNid(int *nid_in, int *nid_out) { EMPTYXD(xd); int status = TreeGetRecord(*nid_in, &xd); - if (status & 1) { + if (STATUS_OK) { switch (xd.pointer->dtype) { case DTYPE_NID: *nid_out = *(int *)xd.pointer->pointer; diff --git a/mitdevices/GenDeviceCallData.c b/mitdevices/GenDeviceCallData.c index 4b839e8921..73e2b04954 100644 --- a/mitdevices/GenDeviceCallData.c +++ b/mitdevices/GenDeviceCallData.c @@ -70,7 +70,7 @@ Calls TDI$DATA for INCAA CADF. ------------------------------------------------------------------------------*/ #include -#include +#include "mds_gendevice.h" #include #include #include @@ -105,7 +105,7 @@ EXPORT int GenDeviceCallData(int mode, int cur_nid, struct descriptor_xd *settin Executable: */ status = TreeGetRecord(cur_nid, &record_d); - if (!(status & 1)) + if (STATUS_NOT_OK) return (status); type = record_d.pointer->dtype; switch (mode) { @@ -114,7 +114,7 @@ EXPORT int GenDeviceCallData(int mode, int cur_nid, struct descriptor_xd *settin status = TdiData(record_d.pointer, setting_d_ptr MDS_END_ARG); else MdsCopyDxXd((struct descriptor *)&record_d, setting_d_ptr); - if (~status & 1) { + if (STATUS_NOT_OK) { if ((setting_d_ptr) && (setting_d_ptr->pointer)) setting_d_ptr->pointer->class = CLASS_D; } else { @@ -138,7 +138,7 @@ EXPORT int GenDeviceCallData(int mode, int cur_nid, struct descriptor_xd *settin break; case DevMODSLO: status = TdiEvaluate(record_d.pointer, setting_d_ptr MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { if (((setting_d_ptr->pointer)->dtype != DTYPE_SLOPE) && ((setting_d_ptr->pointer)->dtype != DTYPE_RANGE)) { MdsFree1Dx(setting_d_ptr, 0); @@ -148,7 +148,7 @@ EXPORT int GenDeviceCallData(int mode, int cur_nid, struct descriptor_xd *settin break; case DevMODRAN: status = TdiEvaluate(record_d.pointer, &temp_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { if ((temp_xd.pointer)->dtype != DTYPE_RANGE) { MdsFree1Dx(&temp_xd, 0); status = DEV$_BADPARAM; @@ -180,7 +180,7 @@ EXPORT int GenDeviceCallData(int mode, int cur_nid, struct descriptor_xd *settin break; case DevMODRANLON: status = TdiEvaluate(record_d.pointer, &temp_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { if ((temp_xd.pointer)->dtype != DTYPE_RANGE) { MdsFree1Dx(&temp_xd, 0); status = DEV$_BADPARAM; diff --git a/mitdevices/GenDeviceCvtStringCode.c b/mitdevices/GenDeviceCvtStringCode.c index f4bba19486..e835dd6e39 100644 --- a/mitdevices/GenDeviceCvtStringCode.c +++ b/mitdevices/GenDeviceCvtStringCode.c @@ -51,7 +51,7 @@ EXPORT int GEN_DEVICE$CVT_STRING_CODE( ) #include #include #include -#include +#include "mds_gendevice.h" struct _table { short code; diff --git a/mitdevices/GenDeviceFree.c b/mitdevices/GenDeviceFree.c index 6ff2f12ba5..bf629a2ecf 100644 --- a/mitdevices/GenDeviceFree.c +++ b/mitdevices/GenDeviceFree.c @@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EXPORT int GenDeviceFree(CommonInStruct * in_struct) { int i, status = 1; - for (i = 0; (status & 1) && (i < in_struct->num_xds); i++) + for (i = 0; (STATUS_OK) && (i < in_struct->num_xds); i++) status = MdsFree1Dx(&in_struct->xds[i], 0); if (in_struct->num_xds) { free(in_struct->xds); diff --git a/mitdevices/Makefile.in b/mitdevices/Makefile.in index e8056e5c92..0241d264dd 100644 --- a/mitdevices/Makefile.in +++ b/mitdevices/Makefile.in @@ -1,7 +1,7 @@ include @top_builddir@/Makefile.inc srcdir=@srcdir@ -builddir=@builddir@ +builddir=@builddir@ VPATH=@srcdir@ @AX_RECONFIGURE_TARGET@ @@ -206,7 +206,7 @@ u_of_m_spect_gen.c u_of_m_spect.c IO_SOURCES = \ io.c\ -curvefit.c +curvefit.c OBJECTS = $(SOURCES:.c=.o) @@ -269,7 +269,7 @@ endif l8590_mem.c: l8590_sclr_gen.c %_gen.c: %.gen @MAKEBINDIR@/gen_device $< sx _gen - $(SED) -i.tmp $$'1s/^/#include \\\n/' $@; $(RM) $@.tmp + $(SED) -i.tmp $$'1s/^/#include "mitdevices_msg.h"\\\n/' $@; $(RM) $@.tmp @MAKEBINDIR@daq_server : daq_server cp ${srcdir}/daq_server @MAKEBINDIR@daq_server @@ -334,4 +334,3 @@ dc1394_support2.o : dc1394_support2.c cp $< $@ .NOTPARALLEL: - diff --git a/mitdevices/a12.c b/mitdevices/a12.c index db77861b5a..81bca7a8e7 100644 --- a/mitdevices/a12.c +++ b/mitdevices/a12.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include #include #include @@ -133,16 +133,16 @@ EXPORT int a12__store(struct descriptor *niddsc_ptr __attribute__ ((unused))) fast = TreeIsOn(c_nids[A12_N_COMMENT]) & 1; if ((max_samples == 8192) && ((TreeIsOn(c_nids[A12_N_NAME]) & 1) == 0)) max_samples = 32767; - for (chan = 0; ((chan < 6) && (status & 1)); chan++) { + for (chan = 0; ((chan < 6) && (STATUS_OK)); chan++) { if (TreeIsOn(CHAN_NID(chan, A12_N_INP_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, A12_N_INP_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_samples - 1, max(0, raw.bounds[0].l)); else raw.bounds[0].l = 0; status = DevLong(&CHAN_NID(chan, A12_N_INP_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_samples - 1, max(0, raw.bounds[0].u)); else raw.bounds[0].u = max_samples - 1; @@ -151,7 +151,7 @@ EXPORT int a12__store(struct descriptor *niddsc_ptr __attribute__ ((unused))) if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u + 1; status = ReadChannel(name, fast, &max_samples, chan, channel_data); - if (status & 1) { + if (STATUS_OK) { offset = ((1 << chan) & polarity) != 0 ? -2048 : 0; raw.pointer = (char *)(channel_data + (raw.bounds[0].l)); raw.a0 = (char *)channel_data; @@ -179,7 +179,7 @@ static int ReadSetup(char *name, float *freq_ptr, int *offset) int status; int one = 1; status = DevCamChk(CamPiow(name, 0, 0, &setup, 16, 0), &one, 0); - if (status & 1) { + if (STATUS_OK) { *offset = setup.a12_setup_v_offset; *freq_ptr = freq[setup.a12_setup_v_period]; } diff --git a/mitdevices/a12_gen.c b/mitdevices/a12_gen.c index 009c306272..17f7f498c3 100644 --- a/mitdevices/a12_gen.c +++ b/mitdevices/a12_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "a12_gen.h" EXPORT int a12__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -142,7 +142,7 @@ EXPORT int a12__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)), NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (A12_N_HEAD + 1): diff --git a/mitdevices/a14.c b/mitdevices/a14.c index e83dab967a..2948df7d3b 100644 --- a/mitdevices/a14.c +++ b/mitdevices/a14.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include "a14_gen.h" #include #include @@ -128,7 +128,7 @@ static int ReadChannel(InStoreStruct * setup, int memptr, int first_idx, int sam *samples_read = 0; channel_select.channel = channel; pio(16, 6, channel_select); - while (status & 1 && *samples_read < samples) { + while (STATUS_OK && *samples_read < samples) { int samples_to_read = min(samples - *samples_read, 32000); int smps; if (samples_to_read > 1 && (((address + samples_to_read) & 0xff) == 0xff)) @@ -273,7 +273,7 @@ EXPORT int a14___store(struct descriptor *niddsc __attribute__ ((unused)), InSto } free(raw.pointer); raw.pointer = malloc((max_idx - min_idx + 1) * sizeof(short)); - for (i = 0; i < 6 && status & 1; i++, range = range >> 3) { + for (i = 0; i < 6 && STATUS_OK; i++, range = range >> 3) { int chan_nid = setup->head_nid + (A14_N_INPUT_2 - A14_N_INPUT_1) * i + A14_N_INPUT_1; if (TreeIsOn(chan_nid) & 1) { int start_idx_nid = chan_nid + A14_N_INPUT_1_STARTIDX - A14_N_INPUT_1; @@ -281,12 +281,12 @@ EXPORT int a14___store(struct descriptor *niddsc __attribute__ ((unused)), InSto offset = offsets[range & 7]; coefficient = coeffs[range & 7]; status = DevLong(&start_idx_nid, &raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&end_idx_nid, &raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -296,7 +296,7 @@ EXPORT int a14___store(struct descriptor *niddsc __attribute__ ((unused)), InSto status = ReadChannel(setup, start_addr, raw.bounds[0].l, raw.m[0], i, (short *)raw.pointer, &samples_read); - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l * sizeof(short); raw.arsize = samples_read * sizeof(short); raw.bounds[0].u = raw.bounds[0].l + samples_read - 1; diff --git a/mitdevices/a14_gen.c b/mitdevices/a14_gen.c index 57cb9cf352..e512e4685e 100644 --- a/mitdevices/a14_gen.c +++ b/mitdevices/a14_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "a14_gen.h" EXPORT int a14__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int a14__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(A14_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -157,7 +157,7 @@ EXPORT int a14__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -169,7 +169,7 @@ EXPORT int a14__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)), NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (A14_N_HEAD + 1): diff --git a/mitdevices/a3204.c b/mitdevices/a3204.c index 7f1ad9e897..6128576439 100644 --- a/mitdevices/a3204.c +++ b/mitdevices/a3204.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include #include "a3204_gen.h" #include @@ -91,9 +91,9 @@ static int StoreChannel(InStoreStruct * setup, int chan) offset = ctl * 10. / 2048.0 - 10.0; out_nid_d.pointer = (char *)&output_nid; status = TdiCompile((struct descriptor *)&expression, &out_nid_d, &offset_d, &gain_d, &value MDS_END_ARG); - if (!(status & 1)) { return status; } + if (STATUS_NOT_OK) { return status; } status = TreePutRecord(input_nid, (struct descriptor *)&value, 0); - if (!(status & 1)) { return status; } + if (STATUS_NOT_OK) { return status; } if (TreeIsOn(filter_on_nid) & 1) { status = TreePutRecord(filter_on_nid, filter, 0); } diff --git a/mitdevices/a3204_gen.c b/mitdevices/a3204_gen.c index f38b1af2fd..d46e59863e 100644 --- a/mitdevices/a3204_gen.c +++ b/mitdevices/a3204_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "a3204_gen.h" EXPORT int a3204__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int a3204__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(A3204_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -147,7 +147,7 @@ EXPORT int a3204__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -159,7 +159,7 @@ EXPORT int a3204__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (A3204_N_HEAD + 1): diff --git a/mitdevices/b2408.c b/mitdevices/b2408.c index 0c59c8dfae..d87b9bf970 100644 --- a/mitdevices/b2408.c +++ b/mitdevices/b2408.c @@ -23,12 +23,12 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include #include "b2408_gen.h" #include #include -#include +#include "mitdevices_msg.h" #include #include "devroutines.h" #include diff --git a/mitdevices/b2408_gen.c b/mitdevices/b2408_gen.c index 0dc949c644..66ac7466d4 100644 --- a/mitdevices/b2408_gen.c +++ b/mitdevices/b2408_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "b2408_gen.h" EXPORT int b2408__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int b2408__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(B2408_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -72,7 +72,7 @@ EXPORT int b2408__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -84,7 +84,7 @@ EXPORT int b2408__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (B2408_N_HEAD + 1): diff --git a/mitdevices/b3224.c b/mitdevices/b3224.c index fa7a531ae5..11bc942ef8 100644 --- a/mitdevices/b3224.c +++ b/mitdevices/b3224.c @@ -23,7 +23,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include "b3224_gen.h" #include "devroutines.h" diff --git a/mitdevices/b3224_gen.c b/mitdevices/b3224_gen.c index 5585c97c6a..df1286820d 100644 --- a/mitdevices/b3224_gen.c +++ b/mitdevices/b3224_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "b3224_gen.h" EXPORT int b3224__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int b3224__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(B3224_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -64,7 +64,7 @@ EXPORT int b3224__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -76,7 +76,7 @@ EXPORT int b3224__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (B3224_N_HEAD + 1): diff --git a/mitdevices/b5910a.c b/mitdevices/b5910a.c index a46e078ee6..edb2e1cacf 100644 --- a/mitdevices/b5910a.c +++ b/mitdevices/b5910a.c @@ -23,9 +23,9 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include +#include "mds_gendevice.h" #include -#include +#include "mitdevices_msg.h" #include #include #include @@ -141,7 +141,7 @@ EXPORT int b5910a__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), }; char *title; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + (nid + B5910A_N_EXT_CLOCK); + uilnames[0].value = (void *)(intptr_t)(nid + B5910A_N_EXT_CLOCK); status = XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "B5910A", uilnames, XtNumber(uilnames), &w); @@ -585,7 +585,7 @@ static int InitMath() static DESCRIPTOR(csval_d, "csval_"); int status; status = LibFindImageSymbol(&image, &csakm_d, &csakm); - if (status & 1) + if (STATUS_OK) status = LibFindImageSymbol(&image, &csval_d, &csval); return status; } @@ -599,7 +599,7 @@ EXPORT int b5910a_SPLFIT(int *num_knots, float *knots_x, float *knots_y, int *nu float *cscoef = (float *)XtCalloc(*num_knots * 4, sizeof(float)); if (csakm == 0 || csval == 0) status = InitMath(); - if (status & 1) { + if (STATUS_OK) { (*csakm) (num_knots, knots_x, knots_y, fbreak, cscoef); for (i = 0; i < *num_v; i++) y[i] = (*csval) (&x[i], num_knots, fbreak, cscoef); @@ -892,7 +892,7 @@ EXPORT int b5910a___init(struct descriptor *niddsc_ptr __attribute__ ((unused)), return DEVBAD_ACTIVE_CHAN; } status = TdiExecute((struct descriptor *)&chan_exp, data, &y MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { float *yval = (float *)y.pointer->pointer; float volts_per_bit; short max_counts; diff --git a/mitdevices/b5910a_gen.c b/mitdevices/b5910a_gen.c index 879816041a..6e57edb4fe 100644 --- a/mitdevices/b5910a_gen.c +++ b/mitdevices/b5910a_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "b5910a_gen.h" EXPORT int b5910a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int b5910a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(B5910A_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -109,7 +109,7 @@ EXPORT int b5910a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -121,7 +121,7 @@ EXPORT int b5910a__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (B5910A_N_HEAD + 1): diff --git a/mitdevices/dsp2904.c b/mitdevices/dsp2904.c index dd2bb13329..ce0edc90ab 100644 --- a/mitdevices/dsp2904.c +++ b/mitdevices/dsp2904.c @@ -25,8 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -180,7 +180,7 @@ EXPORT int dsp2904___store(struct descriptor *niddsc __attribute__ ((unused)), I } } } - if ((status & 1) && (TreeIsOn(counter_nid) & 1)) { + if ((STATUS_OK) && (TreeIsOn(counter_nid) & 1)) { int channel_nid = setup->head_nid + DSP2904_N_COUNTER_CHANNEL; int channel; return_on_error(DevLong(&channel_nid, &channel), status); @@ -230,14 +230,14 @@ static int ReadChannel(InStoreStruct * setup, int channel, int num, unsigned sho AccessTraq(setup, 0x0A000 | channel, 24); AccessTraq(setup, 0x0B000, 24); pio(8, 0, 0, 16); - for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (status & 1); try++) { + for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (STATUS_OK); try++) { pio(8, 0, 0, 16); } pio(10, 0, 0, 16); - for (points_to_read = num; points_to_read && (status & 1); points_to_read = num - points_read) { + for (points_to_read = num; points_to_read && (STATUS_OK); points_to_read = num - points_read) { int count = points_to_read > 32767 ? 32767 : points_to_read; status = CamQstopw(setup->traq_name, 0, 2, count, buffer + points_read, 16, (unsigned short *)&iosb); - status = (status & 1) ? iosb.status : status; + status = (STATUS_OK) ? iosb.status : status; if (iosb.bytcnt == 0) break; points_read += iosb.bytcnt / 2; @@ -265,7 +265,7 @@ static int AccessTraq(InStoreStruct * setup, int data, int memsize) int try; int status; pio(17, 0, &data, memsize); - for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (status & 1); try++) { + for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (STATUS_OK); try++) { DevWait((float).0005); pio(17, 0, &data, memsize); } diff --git a/mitdevices/dsp2904_gen.c b/mitdevices/dsp2904_gen.c index 2da104b55a..e7a270a3cc 100644 --- a/mitdevices/dsp2904_gen.c +++ b/mitdevices/dsp2904_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "dsp2904_gen.h" extern int dsp2904___add(int *nid); EXPORT int dsp2904__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) @@ -39,21 +39,21 @@ EXPORT int dsp2904__add(struct descriptor *name_d_ptr, struct descriptor *dummy_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(DSP2904_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -115,7 +115,7 @@ EXPORT int dsp2904__add(struct descriptor *name_d_ptr, struct descriptor *dummy_ ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = dsp2904___add(&head_nid); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -127,7 +127,7 @@ EXPORT int dsp2904__part_name(struct descriptor *nid_d_ptr __attribute__ ((unuse NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (DSP2904_N_HEAD + 1): diff --git a/mitdevices/dt200.c b/mitdevices/dt200.c index 4813bc95c3..dfa3bb5945 100644 --- a/mitdevices/dt200.c +++ b/mitdevices/dt200.c @@ -46,7 +46,7 @@ EXPORT int dt200__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), s static NCI_ITM nci[] = { {4, NciCONGLOMERATE_NIDS, (unsigned char *)&nid, 0}, {0, NciEND_OF_LIST, 0, 0} }; TreeGetNci(nid, nci); - uilnames[0].value = (XtPointer) (nid + (char *)0); + uilnames[0].value = (void *)(intptr_t)nid; return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "DT200", uilnames, XtNumber(uilnames), 0); } diff --git a/mitdevices/dt_acq16.c b/mitdevices/dt_acq16.c index ae270ff893..b056bb5af7 100644 --- a/mitdevices/dt_acq16.c +++ b/mitdevices/dt_acq16.c @@ -46,7 +46,7 @@ EXPORT int dt_acq16__dw_setup(struct descriptor *niddsc __attribute__ ((unused)) static NCI_ITM nci[] = { {4, NciCONGLOMERATE_NIDS, (unsigned char *)&nid, 0}, {0, NciEND_OF_LIST, 0, 0} }; TreeGetNci(nid, nci); - uilnames[0].value = (XtPointer) (nid + (char *)0); + uilnames[0].value = (void *)(intptr_t)nid; return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "DT_ACQ16", uilnames, XtNumber(uilnames), 0); } diff --git a/mitdevices/ec727.c b/mitdevices/ec727.c index eb11293d89..e1348642f9 100644 --- a/mitdevices/ec727.c +++ b/mitdevices/ec727.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -66,19 +66,19 @@ EXPORT int ec727___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), pio(17, 0); for (i = 0; i < 4; i++, dptr += 8192) stop(0, 0, 8192, dptr); - for (chan = 0; ((chan < 32) && (status & 1)); chan++) { + for (chan = 0; ((chan < 32) && (STATUS_OK)); chan++) { int c_nid = setup->head_nid + EC727_N_INPUT_01 + chan * (EC727_N_INPUT_02 - EC727_N_INPUT_01); int s_nid = c_nid + EC727_N_INPUT_01_STARTIDX - EC727_N_INPUT_01; int e_nid = c_nid + EC727_N_INPUT_01_ENDIDX - EC727_N_INPUT_01; if (TreeIsOn(c_nid) & 1) { status = DevLong(&s_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(1023, max(0, raw.bounds[0].l)); else raw.bounds[0].l = 0; status = DevLong(&e_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(1023, max(0, raw.bounds[0].u)); else raw.bounds[0].u = 1023; diff --git a/mitdevices/ec727_gen.c b/mitdevices/ec727_gen.c index e349554e50..a248096705 100644 --- a/mitdevices/ec727_gen.c +++ b/mitdevices/ec727_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "ec727_gen.h" EXPORT int ec727__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int ec727__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(EC727_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -414,7 +414,7 @@ EXPORT int ec727__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -426,7 +426,7 @@ EXPORT int ec727__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (EC727_N_HEAD + 1): diff --git a/mitdevices/fera.c b/mitdevices/fera.c index 3058aa5309..6a05472fa8 100644 --- a/mitdevices/fera.c +++ b/mitdevices/fera.c @@ -104,8 +104,8 @@ The data is dumped into the 4302 memory modules without using the hardware #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -169,7 +169,7 @@ EXPORT int fera___init(struct descriptor *niddsc_ptr __attribute__ ((unused)), I status = FERA$_NODIG; /* setup the memory modules */ - if (status & 1) { + if (STATUS_OK) { if ((num_mem = NElements(setup->head_nid + FERA_N_MEM_NAME))) { int i; for (i = 0; i < num_mem; i++) { @@ -255,12 +255,12 @@ EXPORT int fera___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), } status = Unpack(&buffer, num_pts, num_mem, num_chan, total_data / num_chan); - if ((status & 1) || (status == FERA$_CONFUSED) || (status == FERA$_OVERFLOW)) + if ((STATUS_OK) || (status == FERA$_CONFUSED) || (status == FERA$_OVERFLOW)) put_status = Put(buffer, total_data / num_chan, num_chan, setup->head_nid + FERA_N_EXT_CLOCK, setup->head_nid + FERA_N_OUTPUT); free(buffer); - return (put_status & 1) ? ((status & 1) ? mem_status : status) : put_status; + return (put_status & 1) ? ((STATUS_OK) ? mem_status : status) : put_status; } static int Unpack(unsigned short **buffer, int *num_pts, int num_mems, int chans, int pts_per_chan) @@ -306,12 +306,12 @@ static int NElements(int nid) last_nid = 0; status = TdiExecute((struct descriptor *)&set_var, &nid_dsc, &dummy_xd MDS_END_ARG); } - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR(size_expr, "SIZE(_TextArray)"); last_nid = nid; status = TdiExecute((struct descriptor *)&size_expr, &num_dsc MDS_END_ARG); } - return (status & 1) ? num : 0; + return (STATUS_OK) ? num : 0; } static char *ArrayRef(int nid, int num) @@ -328,13 +328,13 @@ static char *ArrayRef(int nid, int num) last_nid = 0; status = TdiExecute((struct descriptor *)&set_var, &nid_dsc, &dummy_xd MDS_END_ARG); } - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR(subscript_expr, "_TextArray[$]//\"\\0\""); struct descriptor_s num_dsc = { sizeof(int), DTYPE_L, CLASS_S, (char *)0 }; num_dsc.pointer = (char *)# status = TdiExecute((struct descriptor *)&subscript_expr, &num_dsc, &empty_string MDS_END_ARG); } - return ((status & 1) == 0) ? 0 : empty_string.pointer; + return ((STATUS_OK) == 0) ? 0 : empty_string.pointer; } static int Put(unsigned short int *buffer, int pts_per_chan, int chans, int clock_nid, int nid) @@ -355,7 +355,7 @@ static int Put(unsigned short int *buffer, int pts_per_chan, int chans, int cloc clock_nid_dsc.pointer = (char *)&clock_nid; num_dsc.pointer = (char *)&max_chan_num; status = TdiCompile((struct descriptor *)&expr, &a_dsc, &clock_nid_dsc, &num_dsc, &output_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { status = TreePutRecord(nid, (struct descriptor *)&output_xd, 0); MdsFree1Dx(&output_xd, 0); } diff --git a/mitdevices/fera_gen.c b/mitdevices/fera_gen.c index 348080bbc5..da57e69439 100644 --- a/mitdevices/fera_gen.c +++ b/mitdevices/fera_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "fera_gen.h" EXPORT int fera__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int fera__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(FERA_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:DIG_NAME, TreeUSAGE_TEXT) @@ -69,7 +69,7 @@ EXPORT int fera__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -81,7 +81,7 @@ EXPORT int fera__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (FERA_N_HEAD + 1): diff --git a/mitdevices/gen_device_msg.c b/mitdevices/gen_device_msg.c index 33c6b6f63a..70cc558f9a 100644 --- a/mitdevices/gen_device_msg.c +++ b/mitdevices/gen_device_msg.c @@ -23,4 +23,4 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define MSG_LIBRARY -#include +#include "mds_gendevice.h" diff --git a/mitdevices/h908.c b/mitdevices/h908.c index 6c282d0cd0..897298e522 100644 --- a/mitdevices/h908.c +++ b/mitdevices/h908.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -68,7 +68,7 @@ EXPORT int h908___init(struct descriptor *niddsc __attribute__ ((unused)), InIni if (msetup.pretrig) { int pts; status = TdiGetLong((struct descriptor *)setup->pts, &pts); - if (status & 1) { + if (STATUS_OK) { msetup.pts = (pts + 15) / 16; } else return H908$_BAD_PTS; @@ -165,13 +165,13 @@ EXPORT int h908___store(struct descriptor *niddsc __attribute__ ((unused)), InSt if ((onstat & 1) || (onstat == TreePARENT_OFF)) { int samples_to_read; status = DevLong(&startidx_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -180,7 +180,7 @@ EXPORT int h908___store(struct descriptor *niddsc __attribute__ ((unused)), InSt if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(setup, samples_to_read, chan, buffer); - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR(sig_exp, "BUILD_SIGNAL(BUILD_WITH_UNITS(1.25E-3*$VALUE,'volts'),BUILD_WITH_UNITS($,'counts')," // "BUILD_DIM(BUILD_WINDOW($,$,$),$))"); raw.pointer = (char *)(buffer + (raw.bounds[0].l - min_idx)); diff --git a/mitdevices/h908_gen.c b/mitdevices/h908_gen.c index 8a9d6f2e9d..95efe5afe7 100644 --- a/mitdevices/h908_gen.c +++ b/mitdevices/h908_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "h908_gen.h" EXPORT int h908__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int h908__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(H908_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -428,7 +428,7 @@ EXPORT int h908__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -440,7 +440,7 @@ EXPORT int h908__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (H908_N_HEAD + 1): diff --git a/mitdevices/h911.c b/mitdevices/h911.c index de22fa139e..80586abedb 100644 --- a/mitdevices/h911.c +++ b/mitdevices/h911.c @@ -50,8 +50,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -110,7 +110,7 @@ EXPORT int h911___store(struct descriptor *nid_d_ptr __attribute__ ((unused)), I data_dsc.pointer = (char *)buffer; data_dsc.arsize = samples * sizeof(short); clk_nid = in->head_nid + H911_N_EXT_CLOCK; - for (i = 0, status = 1; ((status & 1) && (i < chans)); i++) { + for (i = 0, status = 1; ((STATUS_OK) && (i < chans)); i++) { int nid = in->head_nid + H911_N_CHANNEL_01 + i; if (TreeIsOn(nid)) { short addr = i; diff --git a/mitdevices/h911_gen.c b/mitdevices/h911_gen.c index 707d69bb35..b683a68f54 100644 --- a/mitdevices/h911_gen.c +++ b/mitdevices/h911_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "h911_gen.h" EXPORT int h911__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int h911__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(H911_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -222,7 +222,7 @@ EXPORT int h911__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -234,7 +234,7 @@ EXPORT int h911__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (H911_N_HEAD + 1): diff --git a/mitdevices/h912.c b/mitdevices/h912.c index 33d63b94d8..e9b270ea32 100644 --- a/mitdevices/h912.c +++ b/mitdevices/h912.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -65,7 +65,7 @@ EXPORT int h912___init(struct descriptor *niddsc __attribute__ ((unused)), InIni if (msetup.pretrig) { int pts; status = TdiGetLong(setup->pts, &pts); - if (status & 1) { + if (STATUS_OK) { pio(16, 1, &pts, 16); } else return H912$_BAD_PTS; @@ -174,13 +174,13 @@ EXPORT int h912___store(struct descriptor *niddsc __attribute__ ((unused)), InSt if ((onstat & 1) || (onstat == TreePARENT_OFF)) { int samples_to_read; status = DevLong(&startidx_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(samples - 1, max(0, raw.bounds[0].l)); else raw.bounds[0].l = 0; status = DevLong(&endidx_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(samples - 1, max(0, raw.bounds[0].u)); else raw.bounds[0].u = samples - 1; @@ -189,7 +189,7 @@ EXPORT int h912___store(struct descriptor *niddsc __attribute__ ((unused)), InSt if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u + 1; status = ReadChannel(setup, samples_to_read, chan, buffer); - if (status & 1) { + if (STATUS_OK) { raw.pointer = (char *)(buffer + (raw.bounds[0].l)); raw.a0 = (char *)buffer; raw.arsize = raw.m[0] * sizeof(short); diff --git a/mitdevices/h912_gen.c b/mitdevices/h912_gen.c index 29acd59374..c357ed9f7d 100644 --- a/mitdevices/h912_gen.c +++ b/mitdevices/h912_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "h912_gen.h" EXPORT int h912__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int h912__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(H912_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -245,7 +245,7 @@ EXPORT int h912__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -257,7 +257,7 @@ EXPORT int h912__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (H912_N_HEAD + 1): diff --git a/mitdevices/hm650.c b/mitdevices/hm650.c index bbba6b01fb..6050a61ece 100644 --- a/mitdevices/hm650.c +++ b/mitdevices/hm650.c @@ -47,8 +47,8 @@ Note also that the front panel VETO and CLR inputs may inhibit action. ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "hm650_gen.h" @@ -109,7 +109,7 @@ EXPORT int hm650___init(struct descriptor *niddsc __attribute__ ((unused)), InIn ndelay = 0xFFFF; } pio(16, i, &ndelay, 16); - if (status & 1) { + if (STATUS_OK) { static struct descriptor_xd out_xd = { 0, DTYPE_DSC, CLASS_XD, 0, 0 }; int trig_in = setup->head_nid + HM650_N_TRIG_IN_0 + i; int trig_out = setup->head_nid + HM650_N_TRIG_OUT_0 + i; @@ -134,7 +134,7 @@ EXPORT int hm650___init(struct descriptor *niddsc __attribute__ ((unused)), InIn pio(21, 0, &zero, 16); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) return status; else if ((dly_status & 1) == 0) return dly_status; diff --git a/mitdevices/hm650_gen.c b/mitdevices/hm650_gen.c index b12f201e0c..b08b6f69a4 100644 --- a/mitdevices/hm650_gen.c +++ b/mitdevices/hm650_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "hm650_gen.h" EXPORT int hm650__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int hm650__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(HM650_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -159,7 +159,7 @@ EXPORT int hm650__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -171,7 +171,7 @@ EXPORT int hm650__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (HM650_N_HEAD + 1): diff --git a/mitdevices/hv1440.c b/mitdevices/hv1440.c index 3c51131cdb..ad2ba962eb 100644 --- a/mitdevices/hv1440.c +++ b/mitdevices/hv1440.c @@ -129,8 +129,8 @@ comunications via LeCroy 2132 module. #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -230,19 +230,19 @@ static int GetPodSettings(int nid, int *settings) { static int dev_nid; int status = DevNid(&nid, &dev_nid); - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR(get_settings, "GET_SETTINGS"); static DESCRIPTOR_NID(nid_dsc, &dev_nid); status = TreeDoMethod(&nid_dsc, (struct descriptor *)&get_settings, HV1440_K_CHANS_PER_POD, settings MDS_END_ARG); } - if ((status & 1) == 0) { + if ((STATUS_OK) == 0) { int i; for (i = 0; i < HV1440_K_CHANS_PER_POD; i++) settings[i] = 0; } - return status & 1; + return STATUS_OK; } EXPORT int hv1440___on(struct descriptor *niddsc __attribute__ ((unused)), InOnStruct * setup) diff --git a/mitdevices/hv1440_gen.c b/mitdevices/hv1440_gen.c index ae6f34c7b3..d9259bbc6c 100644 --- a/mitdevices/hv1440_gen.c +++ b/mitdevices/hv1440_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "hv1440_gen.h" EXPORT int hv1440__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int hv1440__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(HV1440_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -121,7 +121,7 @@ EXPORT int hv1440__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:ON_ACTION, ON, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:OFF_ACTION, OFF, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -133,7 +133,7 @@ EXPORT int hv1440__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (HV1440_N_HEAD + 1): diff --git a/mitdevices/hv1443.c b/mitdevices/hv1443.c index 4711fbeb6f..e36dd5fddb 100644 --- a/mitdevices/hv1443.c +++ b/mitdevices/hv1443.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "hv1443_gen.h" @@ -46,7 +46,7 @@ EXPORT int hv1443__get_settings(struct descriptor *niddsc_ptr __attribute__ ((un if (max_chans != HV1443_K_CHANS) return HV1440$_WRONG_POD_TYPE; status = hv1443___get_settings(niddsc_ptr, &setup); - if (status & 1) { + if (STATUS_OK) { int i; for (i = 0; i < HV1443_K_CHANS; i++) { int nid = setup.head_nid + HV1443_N_VOLTAGE_01 + i; diff --git a/mitdevices/hv1443_gen.c b/mitdevices/hv1443_gen.c index 901c594211..02ad7e8984 100644 --- a/mitdevices/hv1443_gen.c +++ b/mitdevices/hv1443_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "hv1443_gen.h" EXPORT int hv1443__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int hv1443__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(HV1443_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:VOLTAGE_01, TreeUSAGE_NUMERIC) flags |= NciM_NO_WRITE_SHOT; @@ -103,7 +103,7 @@ EXPORT int hv1443__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -115,7 +115,7 @@ EXPORT int hv1443__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (HV1443_N_HEAD + 1): diff --git a/mitdevices/hv4032.c b/mitdevices/hv4032.c index 9504738ede..8ace1b6b85 100644 --- a/mitdevices/hv4032.c +++ b/mitdevices/hv4032.c @@ -121,8 +121,8 @@ comunications via LeCroy 2132 module. ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -192,14 +192,14 @@ static void GetPodSettings(int nid, int *settings) { static int dev_nid; int status = DevNid(&nid, &dev_nid); - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR(get_settings, "GET_SETTINGS"); static DESCRIPTOR_NID(nid_dsc, &dev_nid); status = TreeDoMethod(&nid_dsc, (struct descriptor *)&get_settings, HV4032_K_CHANS_PER_POD, settings MDS_END_ARG); } - if ((status & 1) == 0) { + if ((STATUS_OK) == 0) { int i; for (i = 0; i < HV4032_K_CHANS_PER_POD; i++) settings[i] = 0; diff --git a/mitdevices/hv4032_gen.c b/mitdevices/hv4032_gen.c index 33b109796b..a9d1916739 100644 --- a/mitdevices/hv4032_gen.c +++ b/mitdevices/hv4032_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "hv4032_gen.h" EXPORT int hv4032__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int hv4032__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(HV4032_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -89,7 +89,7 @@ EXPORT int hv4032__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:ON_ACTION, ON, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:OFF_ACTION, OFF, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -101,7 +101,7 @@ EXPORT int hv4032__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (HV4032_N_HEAD + 1): diff --git a/mitdevices/hv4032a1.c b/mitdevices/hv4032a1.c index 9a00338902..60a90fde01 100644 --- a/mitdevices/hv4032a1.c +++ b/mitdevices/hv4032a1.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -45,7 +45,7 @@ EXPORT int hv4032a1__get_settings(struct descriptor *niddsc_ptr __attribute__ (( if (max_chans != HV4032A1_K_CHANS) return HV4032$_WRONG_POD_TYPE; status = hv4032a1___get_settings(niddsc_ptr, &setup); - if (status & 1) { + if (STATUS_OK) { int i; for (i = 0; i < HV4032A1_K_CHANS; i++) { int nid = setup.head_nid + HV4032A1_N_VOLTAGE_1 + i; diff --git a/mitdevices/hv4032a1_gen.c b/mitdevices/hv4032a1_gen.c index ad30e42d5f..ae55a48d4b 100644 --- a/mitdevices/hv4032a1_gen.c +++ b/mitdevices/hv4032a1_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "hv4032a1_gen.h" EXPORT int hv4032a1__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int hv4032a1__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(HV4032A1_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:VOLTAGE_1, TreeUSAGE_NUMERIC) flags |= NciM_NO_WRITE_SHOT; @@ -67,7 +67,7 @@ EXPORT int hv4032a1__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -79,7 +79,7 @@ EXPORT int hv4032a1__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (HV4032A1_N_HEAD + 1): diff --git a/mitdevices/idl.c b/mitdevices/idl.c index 8702af0687..7232f3adef 100644 --- a/mitdevices/idl.c +++ b/mitdevices/idl.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -46,9 +46,9 @@ static void InitIdl() DESCRIPTOR(execute_d, "execute"); int status; status = LibFindImageSymbol(&image, &execute_d, &execute); - if (status & 1) + if (STATUS_OK) status = (*execute) ("print,'IDL Activated'") == 0; - if (status & 1) + if (STATUS_OK) idl_initialized = 1; else printf("Error activating IDL"); diff --git a/mitdevices/idl_gen.c b/mitdevices/idl_gen.c index 10c53dc3ba..55bc1aa1e3 100644 --- a/mitdevices/idl_gen.c +++ b/mitdevices/idl_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "idl_gen.h" EXPORT int idl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int idl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(IDL_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:COMMANDS, TreeUSAGE_TEXT) @@ -60,7 +60,7 @@ EXPORT int idl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_pt status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:EXEC_ACTION, EXECUTE, ANALYSIS, 50, 0, 0, IDL_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -72,7 +72,7 @@ EXPORT int idl__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)), NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (IDL_N_HEAD + 1): diff --git a/mitdevices/incaa16.c b/mitdevices/incaa16.c index a44639dd0e..d1b10065af 100644 --- a/mitdevices/incaa16.c +++ b/mitdevices/incaa16.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "incaa16_gen.h" #include @@ -183,20 +183,20 @@ EXPORT int incaa16___store(struct descriptor *niddsc_ptr __attribute__ ((unused) min_idx = setup->ptsc - samps_per_chan; free(raw.pointer); raw.pointer = malloc(samps_per_chan * 2); - for (chan = 0; ((chan < active_chans) && (status & 1)); chan++) { + for (chan = 0; ((chan < active_chans) && (STATUS_OK)); chan++) { int input_nid = setup->head_nid + INCAA16_N_INPUT_01 + chan * (INCAA16_N_INPUT_02 - INCAA16_N_INPUT_01); int startidx_nid = input_nid + 1; int endidx_nid = input_nid + 2; if (TreeIsOn(input_nid) & 1) { status = DevLong(&startidx_nid, &raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, &raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -210,13 +210,13 @@ EXPORT int incaa16___store(struct descriptor *niddsc_ptr __attribute__ ((unused) addr = (unsigned int)(start_addr + chan + (raw.bounds[0].l - min_idx) * active_chans) % memsize; - (samples_to_read > 0) && (status & 1); + (samples_to_read > 0) && (STATUS_OK); samples_to_read -= samps, data_ptr += samps, addr += (samps * active_chans)) { pio(16, 0, &addr); samps = min(samples_to_read, 32767); fstop(2, 0, samps, data_ptr); } - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l; raw.arsize = raw.m[0] * 2; status = TreePutRecord(input_nid, (struct descriptor *)&signal, 0); diff --git a/mitdevices/incaa16_gen.c b/mitdevices/incaa16_gen.c index 8227df8604..aa23cbcd90 100644 --- a/mitdevices/incaa16_gen.c +++ b/mitdevices/incaa16_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "incaa16_gen.h" EXPORT int incaa16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int incaa16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(INCAA16_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -270,7 +270,7 @@ EXPORT int incaa16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -282,7 +282,7 @@ EXPORT int incaa16__part_name(struct descriptor *nid_d_ptr __attribute__ ((unuse NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (INCAA16_N_HEAD + 1): diff --git a/mitdevices/incaa4.c b/mitdevices/incaa4.c index d1872f52ac..e50ded89dc 100644 --- a/mitdevices/incaa4.c +++ b/mitdevices/incaa4.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "incaa4_gen.h" @@ -188,20 +188,20 @@ EXPORT int incaa4___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) min_idx = setup->ptsc - samps_per_chan; free(raw.pointer); raw.pointer = malloc(samps_per_chan * 2); - for (chan = 0; ((chan < active_chans) && (status & 1)); chan++) { + for (chan = 0; ((chan < active_chans) && (STATUS_OK)); chan++) { int input_nid = setup->head_nid + INCAA4_N_INPUT_1 + chan * (INCAA4_N_INPUT_2 - INCAA4_N_INPUT_1); int startidx_nid = input_nid + 1; int endidx_nid = input_nid + 2; if (TreeIsOn(input_nid) & 1) { status = DevLong(&startidx_nid, &raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, &raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -212,13 +212,13 @@ EXPORT int incaa4___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) int samps; pio(16, 0, &addr); for (samples_to_read = raw.m[0], data_ptr = (short *)raw.pointer; - (samples_to_read > 0) && (status & 1); + (samples_to_read > 0) && (STATUS_OK); samples_to_read -= samps, data_ptr += samps, addr += (samps * active_chans)) { pio(16, 0, &addr); samps = min(samples_to_read, 32767); fstop(2, 0, samps, data_ptr); } - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l; raw.arsize = raw.m[0] * 2; status = TreePutRecord(input_nid, (struct descriptor *)&signal, 0); diff --git a/mitdevices/incaa4_gen.c b/mitdevices/incaa4_gen.c index 532b3ff117..2215ef3629 100644 --- a/mitdevices/incaa4_gen.c +++ b/mitdevices/incaa4_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "incaa4_gen.h" EXPORT int incaa4__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int incaa4__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(INCAA4_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -138,7 +138,7 @@ EXPORT int incaa4__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -150,7 +150,7 @@ EXPORT int incaa4__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (INCAA4_N_HEAD + 1): diff --git a/mitdevices/incaa6.c b/mitdevices/incaa6.c index 90bce03464..3d26a5d3f5 100644 --- a/mitdevices/incaa6.c +++ b/mitdevices/incaa6.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -87,7 +87,7 @@ static int arm_init(InInitStruct * setup, int start) status = TdiGetFloat(setup->int_clk_frq, &freq); csreg.all_chan = 0; - if (status & 1) { + if (STATUS_OK) { static float freqs[] = { 1000, 500, 250, 125, 50, 10, 5 }; for (i = 0; i < 7; i++) if (freq >= freqs[i]) @@ -223,20 +223,20 @@ EXPORT int incaa6___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) min_idx = setup->ptsc - samps_per_chan - actual_ptsc; free(raw.pointer); raw.pointer = malloc(samps_per_chan * 2); - for (chan = start; ((chan < MAX_CHANS) && (status & 1)); chan += inc) { + for (chan = start; ((chan < MAX_CHANS) && (STATUS_OK)); chan += inc) { int data_nid = setup->head_nid + INCAA6_N_INPUT_1 + (INCAA6_N_INPUT_2 - INCAA6_N_INPUT_1) * chan; int start_nid = data_nid + INCAA6_N_INPUT_1_STARTIDX - INCAA6_N_INPUT_1; int end_nid = data_nid + INCAA6_N_INPUT_1_ENDIDX - INCAA6_N_INPUT_1; if (TreeIsOn(data_nid) & 1) { status = DevLong(&start_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&end_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -248,7 +248,7 @@ EXPORT int incaa6___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) int samps; pio(16, 0, &addr, 24); for (samples_to_read = raw.m[0], data_ptr = (short *)raw.pointer; - (samples_to_read > 0) && (status & 1); samples_to_read -= samps, data_ptr += samps) { + (samples_to_read > 0) && (STATUS_OK); samples_to_read -= samps, data_ptr += samps) { samps = min(samples_to_read, 32767); if (fast) { fstop(2, 0, samps, data_ptr, 16); @@ -256,7 +256,7 @@ EXPORT int incaa6___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) stop(2, 0, samps, data_ptr, 16); } } - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l; raw.arsize = raw.m[0] * 2; status = TreePutRecord(data_nid, (struct descriptor *)&signal, 0); diff --git a/mitdevices/incaa6_gen.c b/mitdevices/incaa6_gen.c index 337651de3c..861670845b 100644 --- a/mitdevices/incaa6_gen.c +++ b/mitdevices/incaa6_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "incaa6_gen.h" EXPORT int incaa6__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int incaa6__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(INCAA6_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -161,7 +161,7 @@ EXPORT int incaa6__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -173,7 +173,7 @@ EXPORT int incaa6__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (INCAA6_N_HEAD + 1): diff --git a/mitdevices/j1819.c b/mitdevices/j1819.c index 30c37c639d..0f19fbe0aa 100644 --- a/mitdevices/j1819.c +++ b/mitdevices/j1819.c @@ -56,8 +56,8 @@ int J1819_TRIGGER(struct descriptor *niddsc); ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -77,7 +77,7 @@ static int one = 1; #define pio(f,a,d) return_on_error(DevCamChk(CamPiow(setup->name, a, f, d, 24, 0), &one, 0),status) #define stop(f,a,n,d) return_on_error(DevCamChk(CamStopw(setup->name, a, f, n, d, 24, 0), &one, 0),status) #define fstop(f,a,n,d) return_on_error(DevCamChk(CamFStopw(setup->name, a, f, n, d, 24, 0), &one, 0),status) -#define return_on_error(func,statret) status = func; if (!(status & 1)) return statret +#define return_on_error(func,statret) status = func; if (STATUS_NOT_OK) return statret EXPORT int j1819___init(struct descriptor *niddsc __attribute__ ((unused)), InInitStruct * setup) { diff --git a/mitdevices/j1819_gen.c b/mitdevices/j1819_gen.c index 3f4a309135..c52d9e2986 100644 --- a/mitdevices/j1819_gen.c +++ b/mitdevices/j1819_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "j1819_gen.h" EXPORT int j1819__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int j1819__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(J1819_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -80,7 +80,7 @@ EXPORT int j1819__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -92,7 +92,7 @@ EXPORT int j1819__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (J1819_N_HEAD + 1): diff --git a/mitdevices/j221.c b/mitdevices/j221.c index 1de7778c16..1013f2c7ea 100644 --- a/mitdevices/j221.c +++ b/mitdevices/j221.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -37,7 +37,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static int one = 1; static short zero = 0; #define return_on_error(f,retstatus) if (!((status = f) & 1)) return retstatus; -#define do_if_no_error(f,retstatus) if (status & 1) retstatus = f; +#define do_if_no_error(f,retstatus) if (STATUS_OK) retstatus = f; #define pio(f,a,d) status = DevCamChk(CamPiow(setup->name,a,f,d,16,0),&one,&one); #define pion(f,a,d) do_if_no_error(DevCamChk(CamPiow(setup->name,a,f,d,16,0),&one,&one),status); @@ -78,9 +78,9 @@ EXPORT int j221___init(struct descriptor *nid __attribute__ ((unused)), InInitSt merge_status = merge_data(setup->head_nid + J221_N_OUTPUT_01, &bit, &time, &num); if (num) { int start_trig_nid = setup->head_nid + J221_N_START_TRIG; - if (status & 1) { + if (STATUS_OK) { int i; - for (i = 0, status = 0; (i < 10) && !(status & 1); i++) { + for (i = 0, status = 0; (i < 10) && STATUS_NOT_OK; i++) { pio(16, 2, &zero); /* Clear the memory address */ if (status) status = CamStopw(setup->name, 1, 16, num, time, 24, 0); /* Load trigger times */ @@ -88,9 +88,9 @@ EXPORT int j221___init(struct descriptor *nid __attribute__ ((unused)), InInitSt if (i > 1) printf("******J221 needed %d tries on the first STOPW******\n", i); } - if (status & 1) { + if (STATUS_OK) { int i; - for (i = 0, status = 0; (i < 10) && !(status & 1); i++) { + for (i = 0, status = 0; (i < 10) && STATUS_NOT_OK; i++) { static short zero = 0; pio(16, 2, &zero); /* Clear the memory address */ if (status) @@ -108,7 +108,7 @@ EXPORT int j221___init(struct descriptor *nid __attribute__ ((unused)), InInitSt free(time); free(bit); } - return status & 1 ? merge_status : status; + return STATUS_OK ? merge_status : status; } static int merge_data(int nid, int **data, int **times, int *ndata) @@ -221,7 +221,7 @@ EXPORT int j221___add(int *head_nid) int status; c_nid = *head_nid + J221_N_OUTPUT_01; status = TdiExecute((struct descriptor *)&check, &nid_dsc, &len_dsc MDS_END_ARG); - if ((status & 1) && (len > 0)) + if ((STATUS_OK) && (len > 0)) return status; for (i = 0; i < 12; i++) { static DESCRIPTOR(trigs, "I_TO_X(BUILD_DIM(,$1),($2 > 0 ? $3 : $3[0:*:2]) ) * $4 + $5"); diff --git a/mitdevices/j221_gen.c b/mitdevices/j221_gen.c index 16bc136f23..19aff7dc27 100644 --- a/mitdevices/j221_gen.c +++ b/mitdevices/j221_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "j221_gen.h" extern int j221___add(int *nid); EXPORT int j221__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) @@ -39,21 +39,21 @@ EXPORT int j221__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(J221_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -285,7 +285,7 @@ EXPORT int j221__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = j221___add(&head_nid); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -297,7 +297,7 @@ EXPORT int j221__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (J221_N_HEAD + 1): diff --git a/mitdevices/j412.c b/mitdevices/j412.c index e834989846..3ab559f989 100644 --- a/mitdevices/j412.c +++ b/mitdevices/j412.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -43,9 +43,9 @@ EXPORT int j412___init(struct descriptor *nid_d_ptr __attribute__ ((unused)), In struct descriptor_xd xd = { 0, DTYPE_DSC, CLASS_XD, 0, 0 }; int status; status = TdiLong((struct descriptor *)in_struct->set_points, &xd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) status = TdiData((struct descriptor *)&xd, &xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { struct descriptor_a *a_ptr = (struct descriptor_a *)xd.pointer; int num = a_ptr->arsize / a_ptr->length; int *buff = (int *)a_ptr->pointer; @@ -54,7 +54,7 @@ EXPORT int j412___init(struct descriptor *nid_d_ptr __attribute__ ((unused)), In num = max(min(1024, num), 0); if (num) { - status = status & 1; + status = STATUS_OK; for (i = 1; (i < num) && status; i++) status = buff[i] > buff[i - 1]; diff --git a/mitdevices/j412_gen.c b/mitdevices/j412_gen.c index 95ee83701a..aa18beca72 100644 --- a/mitdevices/j412_gen.c +++ b/mitdevices/j412_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "j412_gen.h" EXPORT int j412__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int j412__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(J412_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -79,7 +79,7 @@ EXPORT int j412__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_p status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -91,7 +91,7 @@ EXPORT int j412__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused)) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (J412_N_HEAD + 1): diff --git a/mitdevices/joerger_adc.c b/mitdevices/joerger_adc.c index 2176029697..60b4efa819 100644 --- a/mitdevices/joerger_adc.c +++ b/mitdevices/joerger_adc.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "joerger_adc_gen.h" diff --git a/mitdevices/joerger_adc_gen.c b/mitdevices/joerger_adc_gen.c index c1a0cc4bfb..9f7140ce5b 100644 --- a/mitdevices/joerger_adc_gen.c +++ b/mitdevices/joerger_adc_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_adc_gen.h" EXPORT int joerger_adc__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_adc__add(struct descriptor *name_d_ptr, struct descriptor *du flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_ADC_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -67,7 +67,7 @@ EXPORT int joerger_adc__add(struct descriptor *name_d_ptr, struct descriptor *du status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -79,7 +79,7 @@ EXPORT int joerger_adc__part_name(struct descriptor *nid_d_ptr __attribute__ ((u NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_ADC_N_HEAD + 1): diff --git a/mitdevices/joerger_adcp.c b/mitdevices/joerger_adcp.c index 7a175a298c..b0e12d5e57 100644 --- a/mitdevices/joerger_adcp.c +++ b/mitdevices/joerger_adcp.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/joerger_adcp_gen.c b/mitdevices/joerger_adcp_gen.c index 6d1721fca5..82fd4fa848 100644 --- a/mitdevices/joerger_adcp_gen.c +++ b/mitdevices/joerger_adcp_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_adcp_gen.h" EXPORT int joerger_adcp__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_adcp__add(struct descriptor *name_d_ptr, struct descriptor *d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_ADCP_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -66,7 +66,7 @@ EXPORT int joerger_adcp__add(struct descriptor *name_d_ptr, struct descriptor *d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -78,7 +78,7 @@ EXPORT int joerger_adcp__part_name(struct descriptor *nid_d_ptr __attribute__ (( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_ADCP_N_HEAD + 1): diff --git a/mitdevices/joerger_cg.c b/mitdevices/joerger_cg.c index 154cc24d82..0dec8b83a8 100644 --- a/mitdevices/joerger_cg.c +++ b/mitdevices/joerger_cg.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/joerger_cg_gen.c b/mitdevices/joerger_cg_gen.c index f289f4a0f0..c8745b1c50 100644 --- a/mitdevices/joerger_cg_gen.c +++ b/mitdevices/joerger_cg_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_cg_gen.h" EXPORT int joerger_cg__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -35,25 +35,25 @@ EXPORT int joerger_cg__add(struct descriptor *name_d_ptr, struct descriptor *dum long int flags = NciM_WRITE_ONCE; NCI_ITM flag_itm[] = { {2, NciSET_FLAGS, 0, 0}, {0, 0, 0, 0} }; status = TreeStartConglomerate(JOERGER_CG_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; char *name_ptr = strncpy(malloc(name_d_ptr->length + 1), name_d_ptr->pointer, name_d_ptr->length); flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeAddNode(name_ptr, &head_nid, usage); free(name_ptr); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -75,7 +75,7 @@ EXPORT int joerger_cg__add(struct descriptor *name_d_ptr, struct descriptor *dum ADD_NODE(:CHANNEL_4.INVERTED, 0) ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 10, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -87,7 +87,7 @@ EXPORT int joerger_cg__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_CG_N_HEAD + 1): diff --git a/mitdevices/joerger_dac16.c b/mitdevices/joerger_dac16.c index 0b609320f5..3491fb0501 100644 --- a/mitdevices/joerger_dac16.c +++ b/mitdevices/joerger_dac16.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "joerger_dac16_gen.h" #include diff --git a/mitdevices/joerger_dac16_gen.c b/mitdevices/joerger_dac16_gen.c index 2c7e8b0452..54ae4a7ae9 100644 --- a/mitdevices/joerger_dac16_gen.c +++ b/mitdevices/joerger_dac16_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_dac16_gen.h" EXPORT int joerger_dac16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_dac16__add(struct descriptor *name_d_ptr, struct descriptor * flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_DAC16_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -106,7 +106,7 @@ EXPORT int joerger_dac16__add(struct descriptor *name_d_ptr, struct descriptor * status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -118,7 +118,7 @@ EXPORT int joerger_dac16__part_name(struct descriptor *nid_d_ptr __attribute__ ( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_DAC16_N_HEAD + 1): diff --git a/mitdevices/joerger_tr16.c b/mitdevices/joerger_tr16.c index c060c7b672..43e5117207 100644 --- a/mitdevices/joerger_tr16.c +++ b/mitdevices/joerger_tr16.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -180,16 +180,16 @@ int joerger_tr16___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), #undef return_on_error #define return_on_error(f) if (!((status = f) & 1)) {free(channel_data); return status;} - for (chan = 0; ((chan < 16) && (status & 1) && (put_status & 1)); chan++) { + for (chan = 0; ((chan < 16) && (STATUS_OK) && (put_status & 1)); chan++) { if (TreeIsOn(CHAN_NID(chan, JOERGER_TR16_N_CHAN_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, JOERGER_TR16_N_CHAN_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&CHAN_NID(chan, JOERGER_TR16_N_CHAN_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -198,12 +198,12 @@ int joerger_tr16___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), if (raw.m[0] > 0) { int tries; status = 0; - for (tries = 0; (!(status & 1) && (tries < 5)); tries++) { + for (tries = 0; (STATUS_NOT_OK && (tries < 5)); tries++) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(setup->name, chan, &samples_to_read, channel_data, TreeIsOn(c_nids[1]) & 1); - if (status & 1) { + if (STATUS_OK) { coefficient = .610E-3; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); raw.a0 = raw.pointer - (raw.bounds[0].l * sizeof(channel_data[0])); @@ -218,7 +218,7 @@ int joerger_tr16___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), ret_status = put_status; } } - if (!(status & 1) && (ret_status & 1)) + if (STATUS_NOT_OK && (ret_status & 1)) ret_status = status; status = 1; } diff --git a/mitdevices/joerger_tr16_gen.c b/mitdevices/joerger_tr16_gen.c index 7b22bd6798..5227dfe528 100644 --- a/mitdevices/joerger_tr16_gen.c +++ b/mitdevices/joerger_tr16_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_tr16_gen.h" EXPORT int joerger_tr16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_tr16__add(struct descriptor *name_d_ptr, struct descriptor *d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_TR16_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -309,7 +309,7 @@ EXPORT int joerger_tr16__add(struct descriptor *name_d_ptr, struct descriptor *d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -321,7 +321,7 @@ EXPORT int joerger_tr16__part_name(struct descriptor *nid_d_ptr __attribute__ (( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_TR16_N_HEAD + 1): diff --git a/mitdevices/joerger_tr612.c b/mitdevices/joerger_tr612.c index 860ea5e5d4..312048bf2a 100644 --- a/mitdevices/joerger_tr612.c +++ b/mitdevices/joerger_tr612.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -224,19 +224,19 @@ int joerger_tr612___store(struct descriptor *niddsc __attribute__ ((unused)), In c_offset[4] = range2.range_1 & 1 ? -2048 : 0; c_coef[5] = coefs[range2.range_2]; c_offset[5] = range2.range_2 & 1 ? -2048 : 0; - for (chan = 0; ((chan < 6) && (status & 1)); chan++) { + for (chan = 0; ((chan < 6) && (STATUS_OK)); chan++) { int nid = CHAN_NID(chan, JOERGER_TR612_N_INP_HEAD); if (TreeIsOn(nid) & 1) { nid = CHAN_NID(chan, JOERGER_TR612_N_INP_STARTIDX); status = DevLong(&nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; nid = CHAN_NID(chan, JOERGER_TR612_N_INP_ENDIDX); status = DevLong(&nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -245,7 +245,7 @@ int joerger_tr612___store(struct descriptor *niddsc __attribute__ ((unused)), In if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(setup, samples_to_read, chan, channel_data); - if (status & 1) { + if (STATUS_OK) { offset = c_offset[chan]; coefficient = c_coef[chan]; raw.pointer = (char *)(channel_data + raw.bounds[0].l - min_idx); diff --git a/mitdevices/joerger_tr612_gen.c b/mitdevices/joerger_tr612_gen.c index 6b3ba86ff1..311458fd02 100644 --- a/mitdevices/joerger_tr612_gen.c +++ b/mitdevices/joerger_tr612_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_tr612_gen.h" EXPORT int joerger_tr612__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_tr612__add(struct descriptor *name_d_ptr, struct descriptor * flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_TR612_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -141,7 +141,7 @@ EXPORT int joerger_tr612__add(struct descriptor *name_d_ptr, struct descriptor * ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -153,7 +153,7 @@ EXPORT int joerger_tr612__part_name(struct descriptor *nid_d_ptr __attribute__ ( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_TR612_N_HEAD + 1): diff --git a/mitdevices/joerger_tr812.c b/mitdevices/joerger_tr812.c index cc2872bd41..1c22bda648 100644 --- a/mitdevices/joerger_tr812.c +++ b/mitdevices/joerger_tr812.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -160,7 +160,7 @@ static int Store(InStoreStruct * setup, int partial) pio(1, 1, (short *)&f1a1); min_idx = ((long)f0a0.pretrigger * (long)-4096) / ((long)f0a0.act_memory + 1); max_idx = (long)4096 *((long)f0a0.act_memory + 1) + min_idx - 1; - for (chan = 0; ((chan < 8) && (status & 1)); chan++) { + for (chan = 0; ((chan < 8) && (STATUS_OK)); chan++) { int data_nid = setup->head_nid + JOERGER_TR812_N_CHANNEL_1 + (JOERGER_TR812_N_CHANNEL_2 - JOERGER_TR812_N_CHANNEL_1) * chan; @@ -168,13 +168,13 @@ static int Store(InStoreStruct * setup, int partial) int end_nid = data_nid + JOERGER_TR812_N_CHANNEL_1_ENDIDX - JOERGER_TR812_N_CHANNEL_1; if (TreeIsOn(data_nid) & 1) { status = DevLong(&start_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&end_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -183,7 +183,7 @@ static int Store(InStoreStruct * setup, int partial) if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(partial, &f0a0, setup, &chan, &samples_to_read, channel_data); - if (status & 1) { + if (STATUS_OK) { int gain = 1 << ((f1a1 >> (chan * 2)) & 3); coefficient = 20.0 / 4096 / gain; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); diff --git a/mitdevices/joerger_tr812_gen.c b/mitdevices/joerger_tr812_gen.c index 1a2b93d871..3cca7f0bd4 100644 --- a/mitdevices/joerger_tr812_gen.c +++ b/mitdevices/joerger_tr812_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "joerger_tr812_gen.h" EXPORT int joerger_tr812__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int joerger_tr812__add(struct descriptor *name_d_ptr, struct descriptor * flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(JOERGER_TR812_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -189,7 +189,7 @@ EXPORT int joerger_tr812__add(struct descriptor *name_d_ptr, struct descriptor * ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -201,7 +201,7 @@ EXPORT int joerger_tr812__part_name(struct descriptor *nid_d_ptr __attribute__ ( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (JOERGER_TR812_N_HEAD + 1): diff --git a/mitdevices/l2232.c b/mitdevices/l2232.c index fde993d835..34a15f0952 100644 --- a/mitdevices/l2232.c +++ b/mitdevices/l2232.c @@ -53,8 +53,8 @@ EXPORT int L2232__STORE(struct descriptor *niddsc_ptr __attribute__ ((unused)), ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/l2232_gen.c b/mitdevices/l2232_gen.c index 539eaf02bb..9a064063c9 100644 --- a/mitdevices/l2232_gen.c +++ b/mitdevices/l2232_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l2232_gen.h" EXPORT int l2232__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l2232__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L2232_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:CTS_NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -68,7 +68,7 @@ EXPORT int l2232__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -80,7 +80,7 @@ EXPORT int l2232__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L2232_N_HEAD + 1): diff --git a/mitdevices/l2256.c b/mitdevices/l2256.c index b7a1e1ba8f..32e888d01c 100644 --- a/mitdevices/l2256.c +++ b/mitdevices/l2256.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -137,7 +137,7 @@ EXPORT int l2256___store(struct descriptor *niddsc __attribute__ ((unused)), InS raw.arsize = sizeof(channel_data); raw.a0 = (char *)(channel_data - raw.bounds[0].l); fstopw(2, 0, 1024, channel_data); - if (status & 1) + if (STATUS_OK) status = TreePutRecord(channel_nid, (struct descriptor *)&signal, 0); } return status; diff --git a/mitdevices/l2256_gen.c b/mitdevices/l2256_gen.c index ed478fdd0c..4765f6d494 100644 --- a/mitdevices/l2256_gen.c +++ b/mitdevices/l2256_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l2256_gen.h" EXPORT int l2256__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l2256__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L2256_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -72,7 +72,7 @@ EXPORT int l2256__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -84,7 +84,7 @@ EXPORT int l2256__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L2256_N_HEAD + 1): diff --git a/mitdevices/l2415.c b/mitdevices/l2415.c index ed5bc533f3..e6aaf39cf5 100644 --- a/mitdevices/l2415.c +++ b/mitdevices/l2415.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/l2415_gen.c b/mitdevices/l2415_gen.c index 91345bc833..981d9b94ed 100644 --- a/mitdevices/l2415_gen.c +++ b/mitdevices/l2415_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l2415_gen.h" EXPORT int l2415__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l2415__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L2415_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -87,7 +87,7 @@ EXPORT int l2415__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -99,7 +99,7 @@ EXPORT int l2415__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L2415_N_HEAD + 1): diff --git a/mitdevices/l3512.c b/mitdevices/l3512.c index 393bab6d51..12865bdec4 100644 --- a/mitdevices/l3512.c +++ b/mitdevices/l3512.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/l3512_gen.c b/mitdevices/l3512_gen.c index afef3a5384..3479b817aa 100644 --- a/mitdevices/l3512_gen.c +++ b/mitdevices/l3512_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l3512_gen.h" EXPORT int l3512__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l3512__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L3512_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -86,7 +86,7 @@ EXPORT int l3512__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -98,7 +98,7 @@ EXPORT int l3512__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L3512_N_HEAD + 1): diff --git a/mitdevices/l3512a.c b/mitdevices/l3512a.c index 721ad20143..5a081b375c 100644 --- a/mitdevices/l3512a.c +++ b/mitdevices/l3512a.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/l3512a_gen.c b/mitdevices/l3512a_gen.c index 9842a7cffd..ecff97074f 100644 --- a/mitdevices/l3512a_gen.c +++ b/mitdevices/l3512a_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l3512a_gen.h" EXPORT int l3512a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l3512a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L3512A_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -89,7 +89,7 @@ EXPORT int l3512a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -101,7 +101,7 @@ EXPORT int l3512a__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L3512A_N_HEAD + 1): diff --git a/mitdevices/l4202.c b/mitdevices/l4202.c index 34c1d7e814..d32858c87d 100644 --- a/mitdevices/l4202.c +++ b/mitdevices/l4202.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/l4202_gen.c b/mitdevices/l4202_gen.c index cc5928eb6c..f79ef843f0 100644 --- a/mitdevices/l4202_gen.c +++ b/mitdevices/l4202_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l4202_gen.h" EXPORT int l4202__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l4202__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L4202_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -89,7 +89,7 @@ EXPORT int l4202__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -101,7 +101,7 @@ EXPORT int l4202__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L4202_N_HEAD + 1): diff --git a/mitdevices/l6810.c b/mitdevices/l6810.c index 5a02cc4278..22f269e58a 100644 --- a/mitdevices/l6810.c +++ b/mitdevices/l6810.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "l6810_gen.h" #include "devroutines.h" @@ -240,16 +240,16 @@ EXPORT int l6810___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), #undef return_on_error #define return_on_error(f) if (!((status = f) & 1)) {free(channel_data); return status;} - for (chan = 0; ((chan < 4) && (status & 1)); chan++) { + for (chan = 0; ((chan < 4) && (STATUS_OK)); chan++) { if (TreeIsOn(CHAN_NID(chan, L6810_N_CHAN_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, L6810_N_CHAN_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&CHAN_NID(chan, L6810_N_CHAN_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -258,7 +258,7 @@ EXPORT int l6810___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(in_struct->name, chan, &samples_to_read, channel_data); - if (status & 1) { + if (STATUS_OK) { coefficient = coeffs[setup.sensitivity[chan]]; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); raw.a0 = raw.pointer - (raw.bounds[0].l * sizeof(channel_data[0])); diff --git a/mitdevices/l6810_gen.c b/mitdevices/l6810_gen.c index 46ff2a5e1e..adac0ddca7 100644 --- a/mitdevices/l6810_gen.c +++ b/mitdevices/l6810_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l6810_gen.h" EXPORT int l6810__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l6810__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L6810_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -155,7 +155,7 @@ EXPORT int l6810__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -167,7 +167,7 @@ EXPORT int l6810__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L6810_N_HEAD + 1): diff --git a/mitdevices/l6810a.c b/mitdevices/l6810a.c index fb0846b730..7ed7545576 100644 --- a/mitdevices/l6810a.c +++ b/mitdevices/l6810a.c @@ -22,9 +22,9 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include -#include +#include "mds_gendevice.h" +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "l6810a_gen.h" #include "devroutines.h" @@ -242,16 +242,16 @@ EXPORT int l6810a___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) #undef return_on_error #define return_on_error(f) if (!((status = f) & 1)) {free(channel_data); return status;} - for (chan = 0; ((chan < 4) && (status & 1)); chan++) { + for (chan = 0; ((chan < 4) && (STATUS_OK)); chan++) { if (TreeIsOn(CHAN_NID(chan, L6810A_N_CHAN_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, L6810A_N_CHAN_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&CHAN_NID(chan, L6810A_N_CHAN_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -260,7 +260,7 @@ EXPORT int l6810a___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) if (raw.m[0] > 0) { samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(in_struct->name, chan, &samples_to_read, channel_data); - if (status & 1) { + if (STATUS_OK) { short *optr; coefficient = coeffs[setup.sensitivity[chan]]; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); diff --git a/mitdevices/l6810a_gen.c b/mitdevices/l6810a_gen.c index 5c0d9ea39d..530e69de7a 100644 --- a/mitdevices/l6810a_gen.c +++ b/mitdevices/l6810a_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l6810a_gen.h" EXPORT int l6810a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l6810a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L6810A_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -175,7 +175,7 @@ EXPORT int l6810a__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -187,7 +187,7 @@ EXPORT int l6810a__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L6810A_N_HEAD + 1): diff --git a/mitdevices/l6810b.c b/mitdevices/l6810b.c index 2ad8c9c5ea..0d9aad8b45 100644 --- a/mitdevices/l6810b.c +++ b/mitdevices/l6810b.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "l6810b_gen.h" @@ -248,16 +248,16 @@ EXPORT int l6810b___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) #undef return_on_error #define return_on_error(f) if (!((status = f) & 1)) {free(channel_data); return status;} - for (chan = 0; ((chan < setup.active_chan) && (status & 1)); chan++) { + for (chan = 0; ((chan < setup.active_chan) && (STATUS_OK)); chan++) { if (TreeIsOn(CHAN_NID(chan, L6810B_N_CHAN_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, L6810B_N_CHAN_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&CHAN_NID(chan, L6810B_N_CHAN_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -268,7 +268,7 @@ EXPORT int l6810b___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) status = ReadChannel(in_struct->name, chan, segs, samples_per_segment, drop, &samples_to_read, channel_data); - if (status & 1) { + if (STATUS_OK) { short *optr; coefficient = coeffs[setup.sensitivity[chan]]; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); @@ -301,7 +301,7 @@ EXPORT int l6810b___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) (setup.f1_freq == 0) ? (struct descriptor *)&ext_clock_d : (struct descriptor *)&int_clock_d, &dimension_xd MDS_END_ARG); } - if (status & 1) + if (STATUS_OK) status = TreePutRecord(CHAN_NID(chan, L6810B_N_CHAN_HEAD), (struct descriptor *)&signal, 0); } diff --git a/mitdevices/l6810b_gen.c b/mitdevices/l6810b_gen.c index 33bfc0b152..4519bdea44 100644 --- a/mitdevices/l6810b_gen.c +++ b/mitdevices/l6810b_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l6810b_gen.h" EXPORT int l6810b__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l6810b__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L6810B_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -178,7 +178,7 @@ EXPORT int l6810b__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -190,7 +190,7 @@ EXPORT int l6810b__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L6810B_N_HEAD + 1): diff --git a/mitdevices/l6810c.c b/mitdevices/l6810c.c index e936644561..b900c18754 100644 --- a/mitdevices/l6810c.c +++ b/mitdevices/l6810c.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "l6810c_gen.h" @@ -254,16 +254,16 @@ EXPORT int l6810c___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) #undef return_on_error #define return_on_error(f) if (!((status = f) & 1)) {free(channel_data); return status;} - for (chan = 0; ((chan < setup.active_chan) && (status & 1)); chan++) { + for (chan = 0; ((chan < setup.active_chan) && (STATUS_OK)); chan++) { if (TreeIsOn(CHAN_NID(chan, L6810C_N_CHAN_HEAD)) & 1) { status = DevLong(&CHAN_NID(chan, L6810C_N_CHAN_STARTIDX), (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&CHAN_NID(chan, L6810C_N_CHAN_ENDIDX), (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(raw.bounds[0].l, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -274,7 +274,7 @@ EXPORT int l6810c___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) status = ReadChannel(in_struct->name, chan, segs, samples_per_segment, drop, &samples_to_read, channel_data); - if (status & 1) { + if (STATUS_OK) { short *optr; coefficient = coeffs[setup.sensitivity[chan]]; raw.pointer = (char *)(channel_data + (raw.bounds[0].l - min_idx)); @@ -311,7 +311,7 @@ EXPORT int l6810c___store(struct descriptor *niddsc_ptr __attribute__ ((unused)) (setup.f1_freq == 0) ? (struct descriptor *)&ext_clock_d : (struct descriptor *)&int_clock_d, &dimension_xd MDS_END_ARG); } - if (status & 1) + if (STATUS_OK) status = TreePutRecord(CHAN_NID(chan, L6810C_N_CHAN_HEAD), (struct descriptor *)&signal, 0); } diff --git a/mitdevices/l6810c_gen.c b/mitdevices/l6810c_gen.c index 755a28fe5c..95e71f1194 100644 --- a/mitdevices/l6810c_gen.c +++ b/mitdevices/l6810c_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l6810c_gen.h" EXPORT int l6810c__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l6810c__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L6810C_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -181,7 +181,7 @@ EXPORT int l6810c__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -193,7 +193,7 @@ EXPORT int l6810c__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L6810C_N_HEAD + 1): diff --git a/mitdevices/l8100.c b/mitdevices/l8100.c index f11a10ae1e..df1b3da0f2 100644 --- a/mitdevices/l8100.c +++ b/mitdevices/l8100.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "l8100_gen.h" #include @@ -123,9 +123,9 @@ static int StoreChannel(InStoreStruct * setup, int chan) out_nid_d.pointer = (char *)&output_nid; status = TdiCompile ((struct descriptor *)&expression, &out_nid_d, &offset_d, &gain_d, &mult_d, &value MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { status = TreePutRecord(input_nid, (struct descriptor *)&value, 0); - if ((status & 1) && (IsOn(filter_on_nid))) { + if ((STATUS_OK) && (IsOn(filter_on_nid))) { status = TreePutRecord(filter_on_nid, filter, 0); } } diff --git a/mitdevices/l8100_gen.c b/mitdevices/l8100_gen.c index 29608e5c81..4864b3b6bb 100644 --- a/mitdevices/l8100_gen.c +++ b/mitdevices/l8100_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8100_gen.h" EXPORT int l8100__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8100__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8100_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -129,7 +129,7 @@ EXPORT int l8100__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -141,7 +141,7 @@ EXPORT int l8100__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8100_N_HEAD + 1): diff --git a/mitdevices/l8201.c b/mitdevices/l8201.c index f91e65a12a..78d4cd996d 100644 --- a/mitdevices/l8201.c +++ b/mitdevices/l8201.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "l8201_gen.h" diff --git a/mitdevices/l8201_gen.c b/mitdevices/l8201_gen.c index 6b49329bc2..d129a7a7ee 100644 --- a/mitdevices/l8201_gen.c +++ b/mitdevices/l8201_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8201_gen.h" EXPORT int l8201__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8201__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8201_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -66,7 +66,7 @@ EXPORT int l8201__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -78,7 +78,7 @@ EXPORT int l8201__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8201_N_HEAD + 1): diff --git a/mitdevices/l8206.c b/mitdevices/l8206.c index 2ff8f160c4..b2ab44cf75 100644 --- a/mitdevices/l8206.c +++ b/mitdevices/l8206.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "l8206_gen.h" @@ -99,7 +99,7 @@ EXPORT int l8206___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), pio(18, &zero); pio(11, &zero); pio(26, &zero); - if (status & 1) + if (STATUS_OK) status = savstatus; return status; } diff --git a/mitdevices/l8206_gen.c b/mitdevices/l8206_gen.c index 5386815fd4..e2b6bdc0e9 100644 --- a/mitdevices/l8206_gen.c +++ b/mitdevices/l8206_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8206_gen.h" EXPORT int l8206__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8206__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8206_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -66,7 +66,7 @@ EXPORT int l8206__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -78,7 +78,7 @@ EXPORT int l8206__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8206_N_HEAD + 1): diff --git a/mitdevices/l8210.c b/mitdevices/l8210.c index 0a9d6f7ded..fd4a5c4c96 100644 --- a/mitdevices/l8210.c +++ b/mitdevices/l8210.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -130,7 +130,7 @@ EXPORT int l8210___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), (frequency == 0.0) ? (struct descriptor *)&ext_clock_d : (struct descriptor *)(&int_clock_d), 0); - for (chan = 0; ((chan < num_chans) && (status & 1)); chan++) { + for (chan = 0; ((chan < num_chans) && (STATUS_OK)); chan++) { int channel_nid = setup->head_nid + L8210_N_INPUT_1 + chan * (L8210_N_INPUT_2 - L8210_N_INPUT_1); int usetimes_nid = channel_nid + L8210_N_INPUT_1_USETIMES - L8210_N_INPUT_1; @@ -144,28 +144,28 @@ EXPORT int l8210___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), raw.bounds[0].l = min_idx; raw.bounds[0].u = max_idx; status = DevFloat(&startidx_nid, &start_time); - if (~status & 1) + if (STATUS_NOT_OK) start_time = -1; status = DevFloat(&endidx_nid, &end_time); - if (~status & 1) + if (STATUS_NOT_OK) end_time = -1; status = DevXToI(start_time, end_time, &dimension, min_idx, max_idx, &raw.bounds[0].l, &raw.bounds[0].u); - if (~status & 1) { + if (STATUS_NOT_OK) { raw.bounds[0].l = min_idx; raw.bounds[0].u = max_idx; } } else { status = DevLong(&startidx_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -175,7 +175,7 @@ EXPORT int l8210___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(setup, &samples_per_channel, chan, &samples_to_read, channel_data_ptr); - if (status & 1) { + if (STATUS_OK) { raw.pointer = (char *)(channel_data_ptr + (raw.bounds[0].l - min_idx)); raw.a0 = raw.pointer - raw.bounds[0].l * sizeof(*channel_data_ptr); raw.arsize = raw.m[0] * 2; @@ -200,7 +200,7 @@ static int ReadSetup(InStoreStruct * setup, int *mem_ptr, char *head_ptr, int *s static float freq[8] = { 0, 1.E-4, 4.E-5, 2.E-5, 1.E-5, 4.E-6, 2.E-6, 1.E-6 }; int status; pio(1, 0, (short *)&l8210_setup); - if (status & 1) { + if (STATUS_OK) { *noc_ptr = l8210_setup.l8210_setup_v_noc + 1; *freq_ptr = freq[l8210_setup.l8210_setup_v_period]; *samples_ptr = 32768 * *mem_ptr / *noc_ptr; @@ -289,11 +289,11 @@ static int DevXToI(float start_time, time_array_dsc.pointer = (char *)times; time_array_dsc.arsize = num_times * sizeof(float); status = TdiXtoI((struct descriptor *)dimension, &time_array_dsc, &idxs_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { status = TdiNint((struct descriptor *)&idxs_xd, &idxs_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { status = TdiLong((struct descriptor *)&idxs_xd, &idxs_xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { struct descriptor_a *a_ptr = (struct descriptor_a *)idxs_xd.pointer; int *i_ptr = (int *)a_ptr->pointer; if (!nostart) { @@ -352,7 +352,7 @@ EXPORT int l8210__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), s }; int status; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + (nid + L8210_N_MEMORIES); + uilnames[0].value = (void *)(intptr_t)(nid + L8210_N_MEMORIES); status = XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "L8210", uilnames, XtNumber(uilnames), &dbox); @@ -376,7 +376,7 @@ static Boolean apply_proc(Widget w) XmdsComplain(XtParent(w), "Error writing num memories"); if (status) XmdsApplyAllXds(XtParent(w)); - return status & 1; + return STATUS_OK; } static void pts_activate_proc(Widget w) diff --git a/mitdevices/l8210_gen.c b/mitdevices/l8210_gen.c index a8355d382d..ab09bff95c 100644 --- a/mitdevices/l8210_gen.c +++ b/mitdevices/l8210_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8210_gen.h" EXPORT int l8210__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8210__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8210_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -133,7 +133,7 @@ EXPORT int l8210__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -145,7 +145,7 @@ EXPORT int l8210__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8210_N_HEAD + 1): diff --git a/mitdevices/l8212.c b/mitdevices/l8212.c index e1a72ba064..7046d4a367 100644 --- a/mitdevices/l8212.c +++ b/mitdevices/l8212.c @@ -25,8 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include "l8212_04_gen.h" #include @@ -207,7 +207,7 @@ static int FreqToClock(int chans, int noc, int freq_nid, int *clock) int status = 1; status = DevFloat(&freq_nid, &freq); - if ((status & 1) == 0) { + if ((STATUS_OK) == 0) { *clock = 0; status = 1; } else { @@ -392,19 +392,19 @@ static int L8212__STORE(struct descriptor *niddsc_ptr __attribute__ ((unused)), status = 1; vm_size = samples_per_channel * 2; channel_data_ptr = malloc(vm_size); - for (chan = 0; ((chan < num_chans) && (status & 1)); chan++) { + for (chan = 0; ((chan < num_chans) && (STATUS_OK)); chan++) { int chan_head = CHAN_NID(chan, L8212_N_CHAN_HEAD); if (TreeIsOn(chan_head) & 1) { int chan_start_idx = CHAN_NID(chan, L8212_N_CHAN_STARTIDX); int chan_end_idx = CHAN_NID(chan, L8212_N_CHAN_ENDIDX); status = DevLong(&chan_start_idx, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&chan_end_idx, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -413,7 +413,7 @@ static int L8212__STORE(struct descriptor *niddsc_ptr __attribute__ ((unused)), if (raw.m[0] > 0) { //samples_to_read = raw.bounds[0].u - min_idx + 1; status = ReadChannel(setup->name, samples_per_channel, chan, channel_data_ptr, use_qrep); - if (status & 1) { + if (STATUS_OK) { raw.pointer = (char *)(channel_data_ptr + (raw.bounds[0].l - min_idx)); raw.a0 = raw.pointer - raw.bounds[0].l * sizeof(*channel_data_ptr); raw.arsize = raw.m[0] * 2; @@ -561,8 +561,8 @@ static int L8212_SETUP(struct descriptor *niddsc __attribute__ ((unused)), Widge }; int status; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + (nid + L8212_04_N_MEMORIES); - uilnames[1].value = (char *)0 + chans; + uilnames[0].value = (void *)(intptr_t)(nid + L8212_04_N_MEMORIES); + uilnames[1].value = (void *)(intptr_t)chans; switch (chans) { case 32:{ for (i = 0; i < XtNumber(clock_vals_slow); i++) { @@ -640,7 +640,7 @@ static void mems_changed_proc(Widget w, int *tag __attribute__ ((unused)), XmSca static char header[11]; static struct descriptor_s header_dsc = { sizeof(header), DTYPE_T, CLASS_S, header }; int status = TdiText((struct descriptor *)header_xd, &header_dsc MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { ChangePts(pts_menu, header, reason->value); } } @@ -689,7 +689,7 @@ static void header_changed_proc(Widget w, int *tag __attribute__ ((unused)), XmR static char header[11]; static struct descriptor_s header_dsc = { sizeof(header), DTYPE_T, CLASS_S, header }; int status = TdiText((struct descriptor *)header_xd, &header_dsc MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { XmScaleGetValue(XtNameToWidget(XtParent(XtParent(w)), "mems_scale"), &mems); ChangePts(pts_menu, header, mems); } @@ -816,7 +816,7 @@ static void pts_initialize_proc(Widget pts_menu) static char header[11]; static struct descriptor_s header_dsc = { sizeof(header), DTYPE_T, CLASS_S, header }; int status = TdiText((struct descriptor *)header_xd, &header_dsc MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { XmScaleGetValue(XtNameToWidget(XtParent(pts_menu), "mems_scale"), &mems); ChangePts(pts_menu, header, mems); } @@ -838,5 +838,5 @@ static Boolean apply_proc(Widget w) XmdsComplain(XtParent(w), "Error writing num memories"); if (status) XmdsApplyAllXds(XtParent(w)); - return status & 1; + return STATUS_OK; } diff --git a/mitdevices/l8212_04_gen.c b/mitdevices/l8212_04_gen.c index 7d621b06e2..b487c900e4 100644 --- a/mitdevices/l8212_04_gen.c +++ b/mitdevices/l8212_04_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8212_04_gen.h" EXPORT int l8212_04__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8212_04__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8212_04_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -131,7 +131,7 @@ EXPORT int l8212_04__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -143,7 +143,7 @@ EXPORT int l8212_04__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8212_04_N_HEAD + 1): diff --git a/mitdevices/l8212_08_gen.c b/mitdevices/l8212_08_gen.c index 604fc893ce..9803f9214b 100644 --- a/mitdevices/l8212_08_gen.c +++ b/mitdevices/l8212_08_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8212_08_gen.h" EXPORT int l8212_08__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8212_08__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8212_08_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -179,7 +179,7 @@ EXPORT int l8212_08__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -191,7 +191,7 @@ EXPORT int l8212_08__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8212_08_N_HEAD + 1): diff --git a/mitdevices/l8212_16_gen.c b/mitdevices/l8212_16_gen.c index 35a929feb9..c3666ad1db 100644 --- a/mitdevices/l8212_16_gen.c +++ b/mitdevices/l8212_16_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8212_16_gen.h" EXPORT int l8212_16__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8212_16__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8212_16_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -267,7 +267,7 @@ EXPORT int l8212_16__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -279,7 +279,7 @@ EXPORT int l8212_16__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8212_16_N_HEAD + 1): diff --git a/mitdevices/l8212_32_gen.c b/mitdevices/l8212_32_gen.c index 688581fec3..0263d394d5 100644 --- a/mitdevices/l8212_32_gen.c +++ b/mitdevices/l8212_32_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8212_32_gen.h" EXPORT int l8212_32__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8212_32__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8212_32_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -443,7 +443,7 @@ EXPORT int l8212_32__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -455,7 +455,7 @@ EXPORT int l8212_32__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8212_32_N_HEAD + 1): diff --git a/mitdevices/l8501.c b/mitdevices/l8501.c index a561453912..f02a4dd603 100644 --- a/mitdevices/l8501.c +++ b/mitdevices/l8501.c @@ -24,8 +24,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "l8501_gen.h" @@ -243,7 +243,7 @@ EXPORT int l8501___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), time of the stop trigger and write it out. ******************************/ - if (status & 1 && TreeIsOn(stop_out_nid) & 1) { + if (STATUS_OK && TreeIsOn(stop_out_nid) & 1) { static DESCRIPTOR_FUNCTION_2(trig_mult_exp, &OpcMultiply, &dt3, &f3_count); static DESCRIPTOR_FUNCTION_2(trig_add_exp, &OpcAdd, &fswitch, &trig_mult_exp); @@ -395,7 +395,7 @@ EXPORT int l8501__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), s static NCI_ITM nci[] = { {4, NciCONGLOMERATE_NIDS, (unsigned char *)&nid, 0}, {0, NciEND_OF_LIST, 0, 0} }; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + nid; + uilnames[0].value = (void *)(intptr_t)nid; return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "L8501", uilnames, XtNumber(uilnames), 0); } diff --git a/mitdevices/l8501_gen.c b/mitdevices/l8501_gen.c index f803a9bb04..f9aae68ade 100644 --- a/mitdevices/l8501_gen.c +++ b/mitdevices/l8501_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8501_gen.h" EXPORT int l8501__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8501__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8501_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -108,7 +108,7 @@ EXPORT int l8501__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -120,7 +120,7 @@ EXPORT int l8501__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8501_N_HEAD + 1): diff --git a/mitdevices/l8590.c b/mitdevices/l8590.c index ee8e7212fb..d9ddb83ecf 100644 --- a/mitdevices/l8590.c +++ b/mitdevices/l8590.c @@ -24,8 +24,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -104,13 +104,13 @@ EXPORT int l8590___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), int end_nid = data_nid + L8590_N_INPUT_1_ENDIDX - L8590_N_INPUT_1; if (TreeIsOn(data_nid) & 1) { status = DevLong(&start_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&end_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; diff --git a/mitdevices/l8590_gen.c b/mitdevices/l8590_gen.c index 03c4506483..005f95fe58 100644 --- a/mitdevices/l8590_gen.c +++ b/mitdevices/l8590_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8590_gen.h" EXPORT int l8590__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8590__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8590_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -158,7 +158,7 @@ EXPORT int l8590__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -170,7 +170,7 @@ EXPORT int l8590__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8590_N_HEAD + 1): diff --git a/mitdevices/l8590_mem.c b/mitdevices/l8590_mem.c index 0200738072..6d69ec8ab5 100644 --- a/mitdevices/l8590_mem.c +++ b/mitdevices/l8590_mem.c @@ -24,8 +24,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* CMS REPLACEMENT HISTORY, Element L8590_MEM.C */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -166,12 +166,12 @@ int l8590_mem___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), In int end_nid = data_nid + L8590_SCLR_N_INPUT_1_ENDIDX - L8590_SCLR_N_INPUT_1; if (TreeIsOn(data_nid) & 1) { status = DevLong(&start_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&end_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -201,7 +201,7 @@ EXPORT int l8590_mem__dw_setup(struct descriptor *niddsc __attribute__ ((unused) static NCI_ITM nci[] = { {4, NciCONGLOMERATE_NIDS, (unsigned char *)&nid, 0}, {0, NciEND_OF_LIST, 0, 0} }; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + nid; + uilnames[0].value = (void *)(intptr_t)nid; return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "L8590_MEM", uilnames, XtNumber(uilnames), 0); } @@ -227,7 +227,7 @@ static void Load(Widget w) char digname[512]; sprintf(digname, "%s:L8590_%d", l8590_memname, i); status = TreeFindNode(digname, &dig_nid); - if (status & 1) { + if (STATUS_OK) { TreeGetNci(dig_nid, itmlst); item = XmStringCreateSimple(nodename); XmListAddItem(w, item, 0); diff --git a/mitdevices/l8590_mem_gen.c b/mitdevices/l8590_mem_gen.c index 7ea7a08612..3c249aa0da 100644 --- a/mitdevices/l8590_mem_gen.c +++ b/mitdevices/l8590_mem_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8590_mem_gen.h" EXPORT int l8590_mem__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8590_mem__add(struct descriptor *name_d_ptr, struct descriptor *dumm flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8590_MEM_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -62,7 +62,7 @@ EXPORT int l8590_mem__add(struct descriptor *name_d_ptr, struct descriptor *dumm ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -74,7 +74,7 @@ EXPORT int l8590_mem__part_name(struct descriptor *nid_d_ptr __attribute__ ((unu NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8590_MEM_N_HEAD + 1): diff --git a/mitdevices/l8590_sclr_gen.c b/mitdevices/l8590_sclr_gen.c index 3e6eaf5dd4..438d5246c4 100644 --- a/mitdevices/l8590_sclr_gen.c +++ b/mitdevices/l8590_sclr_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8590_sclr_gen.h" EXPORT int l8590_sclr__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8590_sclr__add(struct descriptor *name_d_ptr, struct descriptor *dum flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8590_SCLR_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE_INTEGER(:NUM_ACTIVE, 8, TreeUSAGE_NUMERIC) @@ -147,7 +147,7 @@ EXPORT int l8590_sclr__add(struct descriptor *name_d_ptr, struct descriptor *dum flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -159,7 +159,7 @@ EXPORT int l8590_sclr__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8590_SCLR_N_HEAD + 1): diff --git a/mitdevices/l8818.c b/mitdevices/l8818.c index 9ccc8c8c0d..1b27a8e58f 100644 --- a/mitdevices/l8818.c +++ b/mitdevices/l8818.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -177,13 +177,13 @@ EXPORT int l8818___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), int endidx_nid = setup->head_nid + L8818_N_INPUT_ENDIDX; if (TreeIsOn(input_nid) & 1) { status = DevLong(&startidx_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -194,13 +194,13 @@ EXPORT int l8818___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), int samps; /* for (samples_to_read = raw.m[0]+start_addr+16; */ for (samples_to_read = raw.m[0]; - (samples_to_read > 0) && (status & 1); samples_to_read -= samps, data_ptr += samps) { + (samples_to_read > 0) && (STATUS_OK); samples_to_read -= samps, data_ptr += samps) { int ios; samps = min(samples_to_read, 65534); ios = (samps + 1) / 2; fstop(2, 0, ios, data_ptr); } - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l; raw.arsize = raw.m[0]; status = TreePutRecord(input_nid, (struct descriptor *)&signal, 0); diff --git a/mitdevices/l8818_gen.c b/mitdevices/l8818_gen.c index dd4ad3f8c6..98eb8f2f18 100644 --- a/mitdevices/l8818_gen.c +++ b/mitdevices/l8818_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8818_gen.h" EXPORT int l8818__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8818__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8818_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -94,7 +94,7 @@ EXPORT int l8818__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -106,7 +106,7 @@ EXPORT int l8818__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8818_N_HEAD + 1): diff --git a/mitdevices/l8828.c b/mitdevices/l8828.c index 24f01b7aae..52429a2857 100644 --- a/mitdevices/l8828.c +++ b/mitdevices/l8828.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -172,13 +172,13 @@ EXPORT int l8828___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), int endidx_nid = setup->head_nid + L8828_N_INPUT_ENDIDX; if (TreeIsOn(input_nid) & 1) { status = DevLong(&startidx_nid, (int *)&raw.bounds[0].l); - if (status & 1) + if (STATUS_OK) raw.bounds[0].l = min(max_idx, max(min_idx, raw.bounds[0].l)); else raw.bounds[0].l = min_idx; status = DevLong(&endidx_nid, (int *)&raw.bounds[0].u); - if (status & 1) + if (STATUS_OK) raw.bounds[0].u = min(max_idx, max(min_idx, raw.bounds[0].u)); else raw.bounds[0].u = max_idx; @@ -189,13 +189,13 @@ EXPORT int l8828___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), int samps; /* for (samples_to_read = raw.m[0]+start_addr+16; */ for (samples_to_read = raw.m[0]; - (samples_to_read > 0) && (status & 1); samples_to_read -= samps, data_ptr += samps) { + (samples_to_read > 0) && (STATUS_OK); samples_to_read -= samps, data_ptr += samps) { int ios; samps = min(samples_to_read, 65534); ios = (samps + 1) / 2; fstop(2, 0, ios, data_ptr); } - if (status & 1) { + if (STATUS_OK) { raw.a0 = raw.pointer - raw.bounds[0].l; raw.arsize = raw.m[0]; status = TreePutRecord(input_nid, (struct descriptor *)&signal, 0); diff --git a/mitdevices/l8828_gen.c b/mitdevices/l8828_gen.c index da3a751999..9f0cab6a5f 100644 --- a/mitdevices/l8828_gen.c +++ b/mitdevices/l8828_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "l8828_gen.h" EXPORT int l8828__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int l8828__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(L8828_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -90,7 +90,7 @@ EXPORT int l8828__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -102,7 +102,7 @@ EXPORT int l8828__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (L8828_N_HEAD + 1): diff --git a/include/mds_gendevice.h b/mitdevices/mds_gendevice.h similarity index 94% rename from include/mds_gendevice.h rename to mitdevices/mds_gendevice.h index 02c589f9a9..3109e72d3a 100644 --- a/include/mds_gendevice.h +++ b/mitdevices/mds_gendevice.h @@ -190,7 +190,7 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define ADD_NODE(name, usage) \ { \ status = TreeAddNode(STRING_LITERAL(name), &curr_nid, usage); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -208,9 +208,9 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) else \ status = \ TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ - if (status & 1) \ + if (STATUS_OK) \ status = TreePutRecord(curr_nid, &num_d, 0); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -229,9 +229,9 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) else \ status = \ TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_NUMERIC); \ - if (status & 1) \ + if (STATUS_OK) \ status = TreePutRecord(curr_nid, &num_d, 0); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -247,9 +247,9 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ else \ status = TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_TEXT); \ - if (status & 1) \ + if (STATUS_OK) \ status = TreePutRecord(curr_nid, (struct descriptor *)&string_d, 0); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -264,7 +264,7 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) struct descriptor_xd comp_expr_xd = {0, DTYPE_DSC, CLASS_XD, 0, 0}; \ status = \ TdiCompile((struct descriptor *)&expr_d, &comp_expr_xd MDS_END_ARG); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -304,9 +304,9 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) } \ } \ status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ - if (status & 1) \ + if (STATUS_OK) \ status = TreePutRecord(curr_nid, comp_expr_xd.pointer, 0); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -355,9 +355,9 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) status = TreeAddNode(STRING_LITERAL(name), &curr_nid, curr_usage); \ else \ status = TreeAddNode(STRING_LITERAL(name), &curr_nid, TreeUSAGE_ACTION); \ - if (status & 1) \ + if (STATUS_OK) \ status = TreePutRecord(curr_nid, (struct descriptor *)&action_d, 0); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ { \ TreeSetDefaultNid(old_nid); \ return status; \ @@ -419,40 +419,40 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define read_descriptor(pos, field) \ curr_nid = head_nid + pos; \ status = TreeGetRecord(curr_nid, &xd); \ - if (status & 1) \ + if (STATUS_OK) \ in_struct.field = xd.pointer; \ next_xd #define read_descriptor_error(pos, field, err) \ curr_nid = head_nid + pos; \ status = TreeGetRecord(curr_nid, &xd); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) in_struct.field = xd.pointer; \ next_xd #define read_integer(pos, field) \ curr_nid = head_nid + pos; \ status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ - if (status & 1) \ + if (STATUS_OK) \ in_struct.field = curr_int; #define read_integer_error(pos, field, err) \ curr_nid = head_nid + pos; \ status = TdiData(&curr_nid_d, &curr_int_d MDS_END_ARG); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = curr_int; #define check_range(field, min, max, err) \ if ((in_struct.field < min) || (in_struct.field > max)) \ error(head_nid, GEN_DEV$_INV_SETUP, err); #define check_integer_set(field, table, max_idx, err) \ status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) #define check_integer_conv_set(field, conv_field, table, max_idx, err) \ status = GenDeviceCvtIntCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; #define read_integer_array_error(pos, field, field_count, err) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else \ { \ array_d_ptr = (struct descriptor_a *)xd.pointer; \ @@ -467,7 +467,7 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define read_integer_array(pos, field, field_count) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODINT, curr_nid, &xd); \ - if (status & 1) \ + if (STATUS_OK) \ { \ array_d_ptr = (struct descriptor_a *)xd.pointer; \ if (array_d_ptr->class == CLASS_A) \ @@ -480,7 +480,7 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define read_float_array_error(pos, field, field_count, err) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) array_d_ptr = \ (struct descriptor_a *)xd.pointer; \ if (array_d_ptr->class != CLASS_A) \ @@ -494,7 +494,7 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define read_float_array(pos, field, field_count) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODFLO, curr_nid, &xd); \ - if (status & 1) \ + if (STATUS_OK) \ { \ array_d_ptr = (struct descriptor_a *)xd.pointer; \ if (array_d_ptr->class == CLASS_A) \ @@ -507,41 +507,41 @@ int getmsg(int sts, char **facnam, char **msgnam, char **msgtext) #define read_float(pos, field) \ curr_nid = head_nid + pos; \ status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ - if (status & 1) \ + if (STATUS_OK) \ in_struct.field = curr_float; #define read_float_error(pos, field, err) \ curr_nid = head_nid + pos; \ status = TdiData(&curr_nid_d, &curr_float_d MDS_END_ARG); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = curr_float; #define check_float_set(field, table, max_idx, err) \ status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) #define check_float_conv_set(field, conv_field, table, max_idx, err) \ status = GenDeviceCvtFloatCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; #define read_string(pos, field) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ - if (status & 1) \ + if (STATUS_OK) \ in_struct.field = xd.pointer->pointer; \ next_xd #define read_string_error(pos, field, err) \ curr_nid = head_nid + pos; \ status = GenDeviceCallData(DevMODSTR, curr_nid, &xd); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.field = \ xd.pointer->pointer; \ next_xd #define check_string_set(field, table, max_idx, err) \ status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) #define check_string_conv_set(field, conv_field, table, max_idx, err) \ status = GenDeviceCvtStringCode(&code, in_struct.field, table, max_idx); \ - if (!(status & 1)) \ + if (STATUS_NOT_OK) \ error(head_nid, GEN_DEV$_INV_SETUP, err) else in_struct.conv_field = code; #define build_results_with_xd_and_return(num_xd) \ in_struct.__xds = \ diff --git a/mitdevices/mdsdcl.c b/mitdevices/mdsdcl.c index 1f28f946d8..653c00659c 100644 --- a/mitdevices/mdsdcl.c +++ b/mitdevices/mdsdcl.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -77,7 +77,7 @@ EXPORT int mdsdcl__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), Executable: */ TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + (nid + MDSDCL_N_VERBS); + uilnames[0].value = (void *)(intptr_t)(nid + MDSDCL_N_VERBS); XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "MDSDCL", uilnames, XtNumber(uilnames), 0); return 1; @@ -133,7 +133,7 @@ static int Apply(Widget w) XtFree(old_list); if (status) XmdsApplyAllXds(XtParent(w)); - return status & 1; + return STATUS_OK; } static void Reset(Widget w) diff --git a/mitdevices/mdsdcl_gen.c b/mitdevices/mdsdcl_gen.c index 1cbb068520..8281a062c8 100644 --- a/mitdevices/mdsdcl_gen.c +++ b/mitdevices/mdsdcl_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mdsdcl_gen.h" EXPORT int mdsdcl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mdsdcl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MDSDCL_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:VERBS, TreeUSAGE_TEXT) @@ -63,7 +63,7 @@ EXPORT int mdsdcl__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:EXEC_ACTION, EXECUTE, ANALYSIS, 50, 0, 0, MDSDCL_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -75,7 +75,7 @@ EXPORT int mdsdcl__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MDSDCL_N_HEAD + 1): diff --git a/mitdevices/mit__clock.c b/mitdevices/mit__clock.c index 565432125f..021add6e1a 100644 --- a/mitdevices/mit__clock.c +++ b/mitdevices/mit__clock.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -45,7 +45,7 @@ EXPORT int mit__clock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u int status; InGet_setupStruct s; status = mit__clock___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { static int output_nid; static DESCRIPTOR_NID(output_dsc, (char *)&output_nid); int invert = 0; diff --git a/mitdevices/mit__clock_gen.c b/mitdevices/mit__clock_gen.c index cfb8b2bfab..ebbb389c2d 100644 --- a/mitdevices/mit__clock_gen.c +++ b/mitdevices/mit__clock_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit__clock_gen.h" EXPORT int mit__clock__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit__clock__add(struct descriptor *name_d_ptr, struct descriptor *dum flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT__CLOCK_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) #define expr " 1000. " @@ -85,7 +85,7 @@ EXPORT int mit__clock__add(struct descriptor *name_d_ptr, struct descriptor *dum flags |= NciM_WRITE_ONCE; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -97,7 +97,7 @@ EXPORT int mit__clock__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT__CLOCK_N_HEAD + 1): diff --git a/mitdevices/mit__dclock.c b/mitdevices/mit__dclock.c index c0f0573149..312700bf35 100644 --- a/mitdevices/mit__dclock.c +++ b/mitdevices/mit__dclock.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -46,7 +46,7 @@ EXPORT int mit__dclock__get_setup(struct descriptor *niddsc_ptr __attribute__ (( static int output_nid; static DESCRIPTOR_NID(output_dsc, (char *)&output_nid); status = mit__dclock___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { int start_low_nid = s.head_nid + MIT__DCLOCK_N_START_LOW; int invert = TreeIsOn(start_low_nid); float max_period; diff --git a/mitdevices/mit__dclock_gen.c b/mitdevices/mit__dclock_gen.c index c0e4684940..c7f2d1c3b5 100644 --- a/mitdevices/mit__dclock_gen.c +++ b/mitdevices/mit__dclock_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit__dclock_gen.h" EXPORT int mit__dclock__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit__dclock__add(struct descriptor *name_d_ptr, struct descriptor *du flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT__DCLOCK_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) #define expr " 1000. " @@ -88,7 +88,7 @@ EXPORT int mit__dclock__add(struct descriptor *name_d_ptr, struct descriptor *du flags |= NciM_WRITE_ONCE; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -100,7 +100,7 @@ EXPORT int mit__dclock__part_name(struct descriptor *nid_d_ptr __attribute__ ((u NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT__DCLOCK_N_HEAD + 1): diff --git a/mitdevices/mit__gate.c b/mitdevices/mit__gate.c index c7de5fadbd..e073b608ae 100644 --- a/mitdevices/mit__gate.c +++ b/mitdevices/mit__gate.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -46,7 +46,7 @@ EXPORT int mit__gate__get_setup(struct descriptor *niddsc_ptr __attribute__ ((un int status; InGet_setupStruct s; status = mit__gate___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { float delay = s.pulse_time - s.trigger; float max_period = max(delay, s.duration); float period; @@ -87,7 +87,7 @@ EXPORT int mit__gate__get_setup(struct descriptor *niddsc_ptr __attribute__ ((un if (s.trigger_mode == TM_EVENT_TRIGGER) { int event_nid = s.head_nid + MIT__GATE_N_EVENT; status = mit_decoder__get_event(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) goto error; } else memset(event_mask, 0, sizeof(EventMask)); diff --git a/mitdevices/mit__gate_gen.c b/mitdevices/mit__gate_gen.c index 27b06ae609..466af5be67 100644 --- a/mitdevices/mit__gate_gen.c +++ b/mitdevices/mit__gate_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit__gate_gen.h" EXPORT int mit__gate__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit__gate__add(struct descriptor *name_d_ptr, struct descriptor *dumm flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT__GATE_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE_INTEGER(:TRIGGER_MODE, 0, TreeUSAGE_NUMERIC) @@ -90,7 +90,7 @@ EXPORT int mit__gate__add(struct descriptor *name_d_ptr, struct descriptor *dumm flags |= NciM_WRITE_ONCE; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -102,7 +102,7 @@ EXPORT int mit__gate__part_name(struct descriptor *nid_d_ptr __attribute__ ((unu NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT__GATE_N_HEAD + 1): diff --git a/mitdevices/mit_clock.c b/mitdevices/mit_clock.c index 441bd5143c..3b339cefe7 100644 --- a/mitdevices/mit_clock.c +++ b/mitdevices/mit_clock.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -45,7 +45,7 @@ EXPORT int mit_clock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((un int status; InGet_setupStruct s; status = mit_clock___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { float duty_cycle = 0.; int invert = 0; static float frequency[2]; @@ -61,7 +61,7 @@ EXPORT int mit_clock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((un sizeof(frequency)); memset(event_mask, 0, sizeof(EventMask)); status = TdiData((struct descriptor *)s.frequency, (struct descriptor *)&frequency_a MDS_END_ARG); - if (!(status & 1)) { + if (STATUS_NOT_OK) { status = TIMING$_INVCLKFRQ; goto error; } @@ -112,12 +112,12 @@ EXPORT int mit_clock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((un setup->start_high = 1; } status = TdiCompile((struct descriptor *)&expr, &dt_dsc, &out MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { static int output_nid; static DESCRIPTOR_NID(output_dsc, (char *)&output_nid); output_nid = s.head_nid + MIT_CLOCK_N_OUTPUT; status = TreePutRecord(output_nid, (struct descriptor *)&out, 0); - if (status & 1) + if (STATUS_OK) *output = &output_dsc; else *output = 0; diff --git a/mitdevices/mit_clock_gen.c b/mitdevices/mit_clock_gen.c index 3d122ff32b..4cebe2d117 100644 --- a/mitdevices/mit_clock_gen.c +++ b/mitdevices/mit_clock_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_clock_gen.h" EXPORT int mit_clock__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_clock__add(struct descriptor *name_d_ptr, struct descriptor *dumm flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_CLOCK_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) #define expr " 1000. " @@ -65,7 +65,7 @@ EXPORT int mit_clock__add(struct descriptor *name_d_ptr, struct descriptor *dumm flags |= NciM_NO_WRITE_MODEL; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -77,7 +77,7 @@ EXPORT int mit_clock__part_name(struct descriptor *nid_d_ptr __attribute__ ((unu NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_CLOCK_N_HEAD + 1): diff --git a/mitdevices/mit_dclock.c b/mitdevices/mit_dclock.c index 3363548513..3f07365df1 100644 --- a/mitdevices/mit_dclock.c +++ b/mitdevices/mit_dclock.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -45,7 +45,7 @@ EXPORT int mit_dclock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u int status; InGet_setupStruct s; status = mit_dclock___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { float max_period; float period; static float dt1; @@ -93,12 +93,12 @@ EXPORT int mit_dclock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u dt1 = setup->load * period * 2; dt2 = setup->hold * period * 2; status = TdiCompile((struct descriptor *)&output_exp, &dt1_dsc, &dt2_dsc, &gate_dsc, &out MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { static int output_nid; static DESCRIPTOR_NID(output_dsc, (char *)&output_nid); output_nid = s.head_nid + MIT_DCLOCK_N_OUTPUT; status = TreePutRecord(output_nid, (struct descriptor *)&out, 0); - *output = (status & 1) ? &output_dsc : 0; + *output = (STATUS_OK) ? &output_dsc : 0; } else *output = 0; GenDeviceFree(&s); diff --git a/mitdevices/mit_dclock_gen.c b/mitdevices/mit_dclock_gen.c index 31995aee0c..69f767f339 100644 --- a/mitdevices/mit_dclock_gen.c +++ b/mitdevices/mit_dclock_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_dclock_gen.h" EXPORT int mit_dclock__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_dclock__add(struct descriptor *name_d_ptr, struct descriptor *dum flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_DCLOCK_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) #define expr " 1000. " @@ -73,7 +73,7 @@ EXPORT int mit_dclock__add(struct descriptor *name_d_ptr, struct descriptor *dum flags |= NciM_NO_WRITE_MODEL; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -85,7 +85,7 @@ EXPORT int mit_dclock__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_DCLOCK_N_HEAD + 1): diff --git a/mitdevices/mit_decoder.c b/mitdevices/mit_decoder.c index cb057e1c10..a3da8453bf 100644 --- a/mitdevices/mit_decoder.c +++ b/mitdevices/mit_decoder.c @@ -25,8 +25,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -102,7 +102,7 @@ int mit_decoder___init(struct descriptor *niddsc_ptr __attribute__ ((unused)), I //unsigned short cam_data = chan + 1; chan_flags |= (1 << chan); status = TreeGetRecord(dev_nid, &pseudo_xd); - if (!(status & 1)) { + if (STATUS_NOT_OK) { if (status != TreeNODATA) return status; } else { @@ -130,7 +130,7 @@ int mit_decoder___init(struct descriptor *niddsc_ptr __attribute__ ((unused)), I } memset(&events[STOP_CHAN], 0, sizeof(EventMask)); status = GetEvent("STOP_SCALERS", &events[STOP_CHAN]); - if (status & 1) + if (STATUS_OK) OctaOr(&events[STOP_CHAN], &all_events); /********** Scalers automatically start on recognizing channel event ***** @@ -272,11 +272,11 @@ static int GetEvent(char *name, EventMask * mask) name_dsc.length = strlen(name); name_dsc.pointer = name; status = TdiExecute((struct descriptor *)&expr, &name_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { unsigned char event = *(unsigned char *)xd.pointer->pointer; mask->bits[event / 32] |= 1 << (event % 32); } - return status & 1; + return STATUS_OK; } EXPORT int mit_decoder__get_event(int *ref_nid, unsigned int *event_mask) @@ -288,7 +288,7 @@ EXPORT int mit_decoder__get_event(int *ref_nid, unsigned int *event_mask) int status; nid_dsc.pointer = (char *)ref_nid; status = TdiExecute((struct descriptor *)&expression, &nid_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { if (xd.pointer->class == CLASS_A) { struct descriptor_a *array = (struct descriptor_a *)xd.pointer; char *event = array->pointer; diff --git a/mitdevices/mit_decoder_gen.c b/mitdevices/mit_decoder_gen.c index 3f0bb7c32a..11ebc9b43b 100644 --- a/mitdevices/mit_decoder_gen.c +++ b/mitdevices/mit_decoder_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_decoder_gen.h" EXPORT int mit_decoder__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_decoder__add(struct descriptor *name_d_ptr, struct descriptor *du flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_DECODER_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -98,7 +98,7 @@ EXPORT int mit_decoder__add(struct descriptor *name_d_ptr, struct descriptor *du status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -110,7 +110,7 @@ EXPORT int mit_decoder__part_name(struct descriptor *nid_d_ptr __attribute__ ((u NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_DECODER_N_HEAD + 1): diff --git a/mitdevices/mit_encoder.c b/mitdevices/mit_encoder.c index 0e83d31fac..febaa3fe6c 100644 --- a/mitdevices/mit_encoder.c +++ b/mitdevices/mit_encoder.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include "mit_encoder_gen.h" @@ -35,7 +35,7 @@ extern int GenDeviceFree(); static DESCRIPTOR(event_lookup, "EVENT_LOOKUP($)"); static int one = 1; -#define return_on_error(func,statret) status = func; if (!(status & 1)) return statret +#define return_on_error(func,statret) status = func; if (STATUS_NOT_OK) return statret #define pio(f,a,d) return_on_error(DevCamChk(CamPiow(setup->name, a, f, d, 16, 0), &one, 0), status); int mit_encoder___init(struct descriptor *niddsc_ptr __attribute__ ((unused)), InInitStruct * setup) @@ -82,7 +82,7 @@ EXPORT int mit_encoder__set_event(struct descriptor *niddsc_ptr __attribute__ (( { InSet_eventStruct setup; int status = mit_encoder___set_event(niddsc_ptr, &setup); - if (status & 1) { + if (STATUS_OK) { static unsigned short event = 0; static struct descriptor event_d = { 1, DTYPE_BU, CLASS_S, (char *)&event }; static int nid; diff --git a/mitdevices/mit_encoder_gen.c b/mitdevices/mit_encoder_gen.c index f6502e4e14..70eee88198 100644 --- a/mitdevices/mit_encoder_gen.c +++ b/mitdevices/mit_encoder_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_encoder_gen.h" EXPORT int mit_encoder__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_encoder__add(struct descriptor *name_d_ptr, struct descriptor *du flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_ENCODER_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -102,7 +102,7 @@ EXPORT int mit_encoder__add(struct descriptor *name_d_ptr, struct descriptor *du flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -114,7 +114,7 @@ EXPORT int mit_encoder__part_name(struct descriptor *nid_d_ptr __attribute__ ((u NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_ENCODER_N_HEAD + 1): diff --git a/mitdevices/mit_gate_gen.c b/mitdevices/mit_gate_gen.c index 74f4e2cc11..455500fc7d 100644 --- a/mitdevices/mit_gate_gen.c +++ b/mitdevices/mit_gate_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_gate_gen.h" EXPORT int mit_gate__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_gate__add(struct descriptor *name_d_ptr, struct descriptor *dummy flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_GATE_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE_INTEGER(:TRIGGER_MODE, 0, TreeUSAGE_NUMERIC) @@ -78,7 +78,7 @@ EXPORT int mit_gate__add(struct descriptor *name_d_ptr, struct descriptor *dummy flags |= NciM_NO_WRITE_MODEL; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -90,7 +90,7 @@ EXPORT int mit_gate__part_name(struct descriptor *nid_d_ptr __attribute__ ((unus NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_GATE_N_HEAD + 1): diff --git a/mitdevices/mit_gclock.c b/mitdevices/mit_gclock.c index 52c6df68d6..bf2c9e96e8 100644 --- a/mitdevices/mit_gclock.c +++ b/mitdevices/mit_gclock.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -45,7 +45,7 @@ EXPORT int mit_gclock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u int status; InGet_setupStruct s; status = mit_gclock___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { float duty_cycle = 0.; int invert = 0; static float frequency[2]; @@ -66,7 +66,7 @@ EXPORT int mit_gclock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u gate_nid = s.head_nid + MIT_GCLOCK_N_GATE; memset(event_mask, 0, sizeof(EventMask)); status = TdiData((struct descriptor *)s.frequency, (struct descriptor *)&frequency_a MDS_END_ARG); - if (!(status & 1)) { + if (STATUS_NOT_OK) { status = TIMING$_INVCLKFRQ; goto error; } @@ -117,12 +117,12 @@ EXPORT int mit_gclock__get_setup(struct descriptor *niddsc_ptr __attribute__ ((u setup->start_high = 1; } status = TdiCompile((struct descriptor *)&output_exp, &gate_dsc, &dt_dsc, &out MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { static int output_nid; static DESCRIPTOR_NID(output_dsc, (char *)&output_nid); output_nid = s.head_nid + MIT_GCLOCK_N_OUTPUT; status = TreePutRecord(output_nid, (struct descriptor *)&out, 0); - *output = (status & 1) ? &output_dsc : 0; + *output = (STATUS_OK) ? &output_dsc : 0; } else *output = 0; GenDeviceFree(&s); diff --git a/mitdevices/mit_gclock_gen.c b/mitdevices/mit_gclock_gen.c index 6aa9878f2f..156e5aae04 100644 --- a/mitdevices/mit_gclock_gen.c +++ b/mitdevices/mit_gclock_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_gclock_gen.h" EXPORT int mit_gclock__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_gclock__add(struct descriptor *name_d_ptr, struct descriptor *dum flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_GCLOCK_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) #define expr " 1000. " @@ -68,7 +68,7 @@ EXPORT int mit_gclock__add(struct descriptor *name_d_ptr, struct descriptor *dum flags |= NciM_NO_WRITE_MODEL; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -80,7 +80,7 @@ EXPORT int mit_gclock__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_GCLOCK_N_HEAD + 1): diff --git a/mitdevices/mit_pulse-gate.c b/mitdevices/mit_pulse-gate.c index e60f562d82..a14843fa1c 100644 --- a/mitdevices/mit_pulse-gate.c +++ b/mitdevices/mit_pulse-gate.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -61,7 +61,7 @@ static int GetSetup(struct descriptor *niddsc_ptr __attribute__ ((unused)), stru int status; InGet_setupStruct s; status = mit_pulse___get_setup(niddsc_ptr, &s); - if (status & 1) { + if (STATUS_OK) { float delay = s.pulse_time - s.trigger; float max_period = max(delay, s.duration); float period; @@ -131,7 +131,7 @@ static int GetSetup(struct descriptor *niddsc_ptr __attribute__ ((unused)), stru if (s.trigger_mode == TM_EVENT_TRIGGER) { int event_nid = s.head_nid + MIT_PULSE_N_EVENT; status = mit_decoder__get_event(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) goto error; } else memset(event_mask, 0, sizeof(EventMask)); diff --git a/mitdevices/mit_pulse_gen.c b/mitdevices/mit_pulse_gen.c index 89414dec36..5d071712f0 100644 --- a/mitdevices/mit_pulse_gen.c +++ b/mitdevices/mit_pulse_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mit_pulse_gen.h" EXPORT int mit_pulse__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mit_pulse__add(struct descriptor *name_d_ptr, struct descriptor *dumm flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MIT_PULSE_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE_INTEGER(:TRIGGER_MODE, 0, TreeUSAGE_NUMERIC) @@ -78,7 +78,7 @@ EXPORT int mit_pulse__add(struct descriptor *name_d_ptr, struct descriptor *dumm flags |= NciM_NO_WRITE_MODEL; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -90,7 +90,7 @@ EXPORT int mit_pulse__part_name(struct descriptor *nid_d_ptr __attribute__ ((unu NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MIT_PULSE_N_HEAD + 1): diff --git a/mitdevices/mitdevices_msg.c b/mitdevices/mitdevices_msg.c index 624d269947..e349dd2ae4 100644 --- a/mitdevices/mitdevices_msg.c +++ b/mitdevices/mitdevices_msg.c @@ -24,4 +24,4 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define MSG_LIBRARY #include -#include +#include "mitdevices_msg.h" diff --git a/include/mitdevices_msg.h b/mitdevices/mitdevices_msg.h similarity index 100% rename from include/mitdevices_msg.h rename to mitdevices/mitdevices_msg.h diff --git a/mitdevices/mpb__decoder.c b/mitdevices/mpb__decoder.c index 7d873ab223..3aacbfd771 100644 --- a/mitdevices/mpb__decoder.c +++ b/mitdevices/mpb__decoder.c @@ -22,7 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include +#include "mitdevices_msg.h" #include #include #include @@ -41,7 +41,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "mpb__decoder_gen.h" #include "devroutines.h" -#include +#include "mds_gendevice.h" #if defined __GNUC__ && 800 <= __GNUC__ * 100 + __GNUC_MINOR__ _Pragma ("GCC diagnostic ignored \"-Wcast-function-type\"") #endif @@ -420,11 +420,11 @@ static int GetEventNum(char *name, unsigned int *mask) name_dsc.length = strlen(name); name_dsc.pointer = name; status = TdiExecute((struct descriptor *)&expr, &name_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { unsigned char event = *(unsigned char *)xd.pointer->pointer; mask[event / 32] |= 1 << (event % 32); } - return status & 1; + return STATUS_OK; } */ EXPORT int mpb__decoder__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), struct descriptor *methoddsc __attribute__ ((unused)), Widget parent) @@ -444,7 +444,7 @@ EXPORT int mpb__decoder__dw_setup(struct descriptor *niddsc __attribute__ ((unus name[2] = '0' + i; mode_w = XtNameToWidget(w, name); XtVaGetValues(mode_w, XmNsubMenuId, &pulldown_w, NULL); - XtAddCallback(pulldown_w, XmNentryCallback, (XtCallbackProc) ModeChange, (char *)0 + i); + XtAddCallback(pulldown_w, XmNentryCallback, (XtCallbackProc) ModeChange, (void *)(intptr_t)i); } Reset(w, NULL, NULL); return 1; @@ -459,7 +459,7 @@ static void Reset(Widget w, XtPointer client_data __attribute__ ((unused)), XmAn Widget mode_w; name[2] = '0' + i; mode_w = XtNameToWidget(XtParent(XtParent(XtParent(w))), name); - rc_cb.data = (char *)0 + XmdsGetOptionIdx(mode_w); + rc_cb.data = (void *)(intptr_t)XmdsGetOptionIdx(mode_w); ModeChange(mode_w, i, &rc_cb); } } @@ -680,7 +680,7 @@ static int GetEvent(int *ref_nid, unsigned int *event_mask) int status; nid_dsc.pointer = (char *)ref_nid; status = TdiExecute((struct descriptor *)&expression, &nid_dsc, &xd MDS_END_ARG); - if (status & 1) { + if (STATUS_OK) { if (xd.pointer->class == CLASS_A) { struct descriptor_a *array = (struct descriptor_a *)xd.pointer; char *event = array->pointer; @@ -715,10 +715,10 @@ static int ClockGetSetup(Widget w, int nid, int channel, DecoderSetup * setup_ou static float frequency; static float duty_cycle; status = GetFloat(w, nid, channel, CHANNEL_P1, &frequency); - if ((!(status & 1)) || (frequency <= 0.0)) + if ((STATUS_NOT_OK) || (frequency <= 0.0)) return TIMING$_INVCLKFRQ; status = GetFloat(w, nid, channel, CHANNEL_P2, &duty_cycle); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVDUTY; dt = 1 / frequency; GetClockSet(dt, &source, &period); @@ -760,7 +760,7 @@ static int ClockGetSetup(Widget w, int nid, int channel, DecoderSetup * setup_ou MdsFree1Dx(edges, 0); *setup_out = setup; status = GetEvent(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; } else { String text = (*info = malloc(500)); @@ -789,10 +789,10 @@ static int GatedClockGetSetup(Widget w, int nid, int channel, DecoderSetup * set static float frequency; static float duty_cycle; status = GetFloat(w, nid, channel, CHANNEL_P1, &frequency); - if ((!(status & 1)) || (frequency <= 0.0)) + if ((STATUS_NOT_OK) || (frequency <= 0.0)) return TIMING$_INVCLKFRQ; status = GetFloat(w, nid, channel, CHANNEL_P2, &duty_cycle); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVDUTY; dt = 1 / frequency; GetClockSet(dt, &source, &period); @@ -836,7 +836,7 @@ static int GatedClockGetSetup(Widget w, int nid, int channel, DecoderSetup * set MdsFree1Dx(edges, 0); *setup_out = setup; status = GetEvent(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; } else { String text = (*info = malloc(500)); @@ -866,13 +866,13 @@ static int GateGetSetup(Widget w, int nid, int channel, DecoderSetup * setup_out float pulse_time; int trigger_mode; status = GetFloat(w, nid, channel, CHANNEL_P1, &delay); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVDELDUR; status = GetFloat(w, nid, channel, CHANNEL_P2, &duration); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVDELDUR; status = GetFloat(w, nid, channel, CHANNEL_P3, &pulse_time); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVDELDUR; delay = delay - pulse_time; dt = max(delay, duration); @@ -887,7 +887,7 @@ static int GateGetSetup(Widget w, int nid, int channel, DecoderSetup * setup_out setup.clock_source = source; setup.falling_edge = 0; status = GetInt(w, nid, channel, CHANNEL_P5, &trigger_mode); - if (!(status & 1)) + if (STATUS_NOT_OK) return TIMING$_INVTRGMOD; switch (trigger_mode) { case TM_EVENT_TRIGGER: @@ -929,7 +929,7 @@ static int GateGetSetup(Widget w, int nid, int channel, DecoderSetup * setup_out else event_nid = nid + MPB__DECODER_N_START_EVENT; status = GetEvent(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; } else { String text = (*info = malloc(500)); @@ -958,10 +958,10 @@ static int DualClockGetSetup(Widget w, int nid, int channel, DecoderSetup * setu static float frequency_1; static float frequency_2; status = GetFloat(w, nid, channel, CHANNEL_P1, &frequency_1); - if ((!(status & 1)) || (frequency_1 <= 0.0)) + if ((STATUS_NOT_OK) || (frequency_1 <= 0.0)) return TIMING$_INVCLKFRQ; status = GetFloat(w, nid, channel, CHANNEL_P2, &frequency_2); - if ((!(status & 1)) || (frequency_2 <= 0.0)) + if ((STATUS_NOT_OK) || (frequency_2 <= 0.0)) return TIMING$_INVCLKFRQ; dt = 1 / min(frequency_1, frequency_2); GetClockSet(dt, &source, &period); @@ -1011,7 +1011,7 @@ static int DualClockGetSetup(Widget w, int nid, int channel, DecoderSetup * setu MdsFree1Dx(edges, 0); *setup_out = setup; status = GetEvent(&event_nid, event_mask); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; } else { String text = (*info = malloc(500)); diff --git a/mitdevices/mpb__decoder_gen.c b/mitdevices/mpb__decoder_gen.c index dc64818140..938acee6b3 100644 --- a/mitdevices/mpb__decoder_gen.c +++ b/mitdevices/mpb__decoder_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "mpb__decoder_gen.h" EXPORT int mpb__decoder__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int mpb__decoder__add(struct descriptor *name_d_ptr, struct descriptor *d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(MPB__DECODER_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -210,7 +210,7 @@ EXPORT int mpb__decoder__add(struct descriptor *name_d_ptr, struct descriptor *d status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -222,7 +222,7 @@ EXPORT int mpb__decoder__part_name(struct descriptor *nid_d_ptr __attribute__ (( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (MPB__DECODER_N_HEAD + 1): diff --git a/mitdevices/paragon_hist.c b/mitdevices/paragon_hist.c index 54c6dedd27..a4d030bded 100644 --- a/mitdevices/paragon_hist.c +++ b/mitdevices/paragon_hist.c @@ -52,8 +52,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -129,7 +129,7 @@ static int Store(struct descriptor *niddsc_ptr __attribute__ ((unused)), InStore FILE *file; int isftp; status = PARAGON_FTP_COPY(setup->report_name, (struct descriptor *)&rpt_name, &isftp); - if (!(status & 1)) { + if (STATUS_NOT_OK) { return (status); } for (i = 0; i < 10; i++) { @@ -143,7 +143,7 @@ static int Store(struct descriptor *niddsc_ptr __attribute__ ((unused)), InStore static DESCRIPTOR_NID(nid_dsc, &limit_nid); limit_nid = setup->head_nid + PARAGON_HIST_N_LIMIT_0 + i; status = TdiData((struct descriptor *)&nid_dsc, &limits[i] MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) MdsFree1Dx(&limits[i], 0); nums[i] = 0; sizes[i] = INITIAL_SIZE; @@ -228,7 +228,7 @@ static void StoreSignal(int nid, MdsCopyDxXd((struct descriptor *)&vals, &values); } status = TreeGetRecord(nid, &tmp_xd); - if (status & 1) { + if (STATUS_OK) { static struct descriptor_xd value = { 0, DTYPE_DSC, CLASS_XD, 0, 0 }; static struct descriptor_xd time = { 0, DTYPE_DSC, CLASS_XD, 0, 0 }; //static DESCRIPTOR(sorted_times, "SORT($)"); diff --git a/mitdevices/paragon_hist_gen.c b/mitdevices/paragon_hist_gen.c index 0a6a7d4f21..046373ce92 100644 --- a/mitdevices/paragon_hist_gen.c +++ b/mitdevices/paragon_hist_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "paragon_hist_gen.h" EXPORT int paragon_hist__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int paragon_hist__add(struct descriptor *name_d_ptr, struct descriptor *d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(PARAGON_HIST_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:REPORT_NAME, TreeUSAGE_TEXT) @@ -136,7 +136,7 @@ EXPORT int paragon_hist__add(struct descriptor *name_d_ptr, struct descriptor *d status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, PARAGON_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -148,7 +148,7 @@ EXPORT int paragon_hist__part_name(struct descriptor *nid_d_ptr __attribute__ (( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (PARAGON_HIST_N_HEAD + 1): diff --git a/mitdevices/paragon_rpt.c b/mitdevices/paragon_rpt.c index 082d2baac0..0eb8ed865d 100644 --- a/mitdevices/paragon_rpt.c +++ b/mitdevices/paragon_rpt.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -58,7 +58,7 @@ int paragon_rpt___store(struct descriptor *niddsc_ptr __attribute__ ((unused)), FILE *file; int isftp; int status = PARAGON_FTP_COPY(setup->report_name,(struct descriptor *)&rpt_name,&isftp); - if (!(status & 1)) + if (STATUS_NOT_OK) { return(status); } diff --git a/mitdevices/paragon_rpt_gen.c b/mitdevices/paragon_rpt_gen.c index bd7283e011..0326dee9e0 100644 --- a/mitdevices/paragon_rpt_gen.c +++ b/mitdevices/paragon_rpt_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "paragon_rpt_gen.h" EXPORT int paragon_rpt__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int paragon_rpt__add(struct descriptor *name_d_ptr, struct descriptor *du flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(PARAGON_RPT_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:REPORT_NAME, TreeUSAGE_TEXT) @@ -72,7 +72,7 @@ EXPORT int paragon_rpt__add(struct descriptor *name_d_ptr, struct descriptor *du status = TreeSetNci(curr_nid, flag_itm); ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, PARAGON_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -84,7 +84,7 @@ EXPORT int paragon_rpt__part_name(struct descriptor *nid_d_ptr __attribute__ ((u NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (PARAGON_RPT_N_HEAD + 1): diff --git a/mitdevices/preamp.c b/mitdevices/preamp.c index 90fc3a9622..45e049d050 100644 --- a/mitdevices/preamp.c +++ b/mitdevices/preamp.c @@ -56,8 +56,8 @@ EXPORT int PREAMP_ADD(struct descriptor *name, ------------------------------------------------------------------------------*/ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include @@ -151,9 +151,9 @@ static Boolean ask_incaa_button(Widget w) XtVaGetValues(w, XmNuserData, &device_nid, XmNtextString, &incaa_string, NULL); incaa_name = XmStringUnparse(incaa_string, NULL, 0, XmCHARSET_TEXT, NULL, 0, XmOUTPUT_ALL); status = TreeFindNode(incaa_name, &incaa_nid); - if (status & 1) { + if (STATUS_OK) { status = DevNids(&incaa_nid_dsc, sizeof(c_nids), c_nids); - if (status & 1) { + if (STATUS_OK) { for (i = 1; i <= 16; i++) { DESCRIPTOR_NID(nid_dsc, 0); char name[] = { '*', '.', 'o', 'u', 't', 'p', 'u', 't', '_', '0', '0', 0 }; @@ -168,7 +168,7 @@ static Boolean ask_incaa_button(Widget w) XmdsComplain(parent, "Could not find specified INCAA"); } else XmdsComplain(parent, "Could not find specified INCAA"); - return status & 1; + return STATUS_OK; } static int one = 1; diff --git a/mitdevices/preamp_gen.c b/mitdevices/preamp_gen.c index 5569be275a..35bd590d8a 100644 --- a/mitdevices/preamp_gen.c +++ b/mitdevices/preamp_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "preamp_gen.h" extern int preamp___add(int *nid); EXPORT int preamp__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) @@ -39,21 +39,21 @@ EXPORT int preamp__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(PREAMP_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) ADD_NODE(:COMMENT, TreeUSAGE_TEXT) @@ -396,7 +396,7 @@ EXPORT int preamp__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) status = preamp___add(&head_nid); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -408,7 +408,7 @@ EXPORT int preamp__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (PREAMP_N_HEAD + 1): diff --git a/mitdevices/reticon120.c b/mitdevices/reticon120.c index 266086746a..3e57c95422 100644 --- a/mitdevices/reticon120.c +++ b/mitdevices/reticon120.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -125,7 +125,7 @@ EXPORT int reticon120__dw_setup(struct descriptor *niddsc __attribute__ ((unused {"PopupPixels", (XtPointer) PopupPixels} }; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + (nid + RETICON120_N_PIXEL_SELECT); + uilnames[0].value = (void *)(intptr_t)(nid + RETICON120_N_PIXEL_SELECT); return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "RETICON120", uilnames, XtNumber(uilnames), 0); } @@ -230,7 +230,7 @@ static int Apply(Widget w) } if (do_put) { status = TreePutRecord(nid, (struct descriptor *)&pixels_d, 0) & 1; - if (!(status & 1)) + if (STATUS_NOT_OK) XmdsComplain(XtParent(w), "Error writing pixel selections"); } return status; @@ -290,17 +290,17 @@ EXPORT int reticon120___store(struct descriptor *niddsc_ptr __attribute__ ((unus short *bptr; latch_time = 0.0; bptr = (short *)(buffer = malloc(words * sizeof(*buffer))); - for (; words_to_read && (status & 1); words_to_read -= iosb.bytcnt / 2) { + for (; words_to_read && (STATUS_OK); words_to_read -= iosb.bytcnt / 2) { int count = min(words_to_read, 32767); if (fast && words_to_read < 32767) status = CamFStopw(setup->memory_name, 0, 0, count, bptr, 16, (unsigned short *)&iosb); else status = CamStopw(setup->memory_name, 0, 0, count, bptr, 16, (unsigned short *)&iosb); bptr += iosb.bytcnt / 2; - status = status & 1 ? iosb.status : status; + status = STATUS_OK ? iosb.status : status; } for (i = 0, is_time = 0, frame_count = 0, pixel_count = 0, frame_size = 0, latch_time = 0, j = - 0; i < words && (status & 1); i++) { + 0; i < words && (STATUS_OK); i++) { if (buffer[i].frame_start) { if (is_time) { if (frame_count >= 8192) { @@ -331,9 +331,9 @@ EXPORT int reticon120___store(struct descriptor *niddsc_ptr __attribute__ ((unus } while ((frame_count * frame_size) > words) frame_count--; - for (i = j; status & 1 && i < (frame_count * frame_size); i++) + for (i = j; STATUS_OK && i < (frame_count * frame_size); i++) data[i] = 0; - if (status & 1) { + if (STATUS_OK) { static DESCRIPTOR_A(time_array, sizeof(float), DTYPE_NATIVE_FLOAT, times, 0); static DESCRIPTOR_A(frame_idx_array, sizeof(short), DTYPE_W, frame_index, 0); static DESCRIPTOR(seconds, "sec"); @@ -357,9 +357,9 @@ EXPORT int reticon120___store(struct descriptor *niddsc_ptr __attribute__ ((unus data_array.m[0] = frame_size; data_array.m[1] = frame_count; status = TreePutRecord(data_nid, (struct descriptor *)&signal, 0); - if (status & 1) { + if (STATUS_OK) { status = TreePutRecord(frame_index_nid, (struct descriptor *)&frame_idx_array, 0); - if ((status & 1) && (latch_time != 0.0)) { + if ((STATUS_OK) && (latch_time != 0.0)) { DESCRIPTOR_FLOAT(latch, &latch_time); status = TreePutRecord(event_latch_nid, &latch, 0); } diff --git a/mitdevices/reticon120_gen.c b/mitdevices/reticon120_gen.c index cb3843e9d3..5bc9d688ea 100644 --- a/mitdevices/reticon120_gen.c +++ b/mitdevices/reticon120_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "reticon120_gen.h" EXPORT int reticon120__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int reticon120__add(struct descriptor *name_d_ptr, struct descriptor *dum flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(RETICON120_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -141,7 +141,7 @@ EXPORT int reticon120__add(struct descriptor *name_d_ptr, struct descriptor *dum ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -153,7 +153,7 @@ EXPORT int reticon120__part_name(struct descriptor *nid_d_ptr __attribute__ ((un NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (RETICON120_N_HEAD + 1): diff --git a/mitdevices/t2812_gen.c b/mitdevices/t2812_gen.c index 52800b4341..dfb7da422e 100644 --- a/mitdevices/t2812_gen.c +++ b/mitdevices/t2812_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t2812_gen.h" EXPORT int t2812__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t2812__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T2812_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:INPUT_1, TreeUSAGE_SIGNAL) flags |= NciM_WRITE_ONCE; @@ -183,7 +183,7 @@ EXPORT int t2812__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -195,7 +195,7 @@ EXPORT int t2812__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T2812_N_HEAD + 1): diff --git a/mitdevices/t2814_gen.c b/mitdevices/t2814_gen.c index f953755cbc..229ef4e837 100644 --- a/mitdevices/t2814_gen.c +++ b/mitdevices/t2814_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t2814_gen.h" EXPORT int t2814__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t2814__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T2814_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:INPUT_1, TreeUSAGE_SIGNAL) flags |= NciM_WRITE_ONCE; @@ -119,7 +119,7 @@ EXPORT int t2814__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -131,7 +131,7 @@ EXPORT int t2814__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T2814_N_HEAD + 1): diff --git a/mitdevices/t2824_gen.c b/mitdevices/t2824_gen.c index 7a8e653352..0d73395c7d 100644 --- a/mitdevices/t2824_gen.c +++ b/mitdevices/t2824_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t2824_gen.h" EXPORT int t2824__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t2824__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T2824_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:INPUT_1, TreeUSAGE_SIGNAL) flags |= NciM_WRITE_ONCE; @@ -70,7 +70,7 @@ EXPORT int t2824__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -82,7 +82,7 @@ EXPORT int t2824__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T2824_N_HEAD + 1): diff --git a/mitdevices/t2825_gen.c b/mitdevices/t2825_gen.c index 35bcafc420..7edf9c3dd2 100644 --- a/mitdevices/t2825_gen.c +++ b/mitdevices/t2825_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t2825_gen.h" EXPORT int t2825__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t2825__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T2825_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:INPUT_1, TreeUSAGE_SIGNAL) flags |= NciM_WRITE_ONCE; @@ -119,7 +119,7 @@ EXPORT int t2825__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -131,7 +131,7 @@ EXPORT int t2825__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T2825_N_HEAD + 1): diff --git a/mitdevices/t2860_gen.c b/mitdevices/t2860_gen.c index 7719173298..77660b465e 100644 --- a/mitdevices/t2860_gen.c +++ b/mitdevices/t2860_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t2860_gen.h" EXPORT int t2860__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t2860__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T2860_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:INPUT_1, TreeUSAGE_SIGNAL) flags |= NciM_WRITE_ONCE; @@ -119,7 +119,7 @@ EXPORT int t2860__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flags |= NciM_NO_WRITE_SHOT; status = TreeSetNci(curr_nid, flag_itm); status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -131,7 +131,7 @@ EXPORT int t2860__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T2860_N_HEAD + 1): diff --git a/mitdevices/t4012.c b/mitdevices/t4012.c index 3bc7b83489..fe3c380d74 100644 --- a/mitdevices/t4012.c +++ b/mitdevices/t4012.c @@ -23,8 +23,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include @@ -160,7 +160,7 @@ EXPORT int t4012___init(struct descriptor *nid __attribute__ ((unused)), InInitS pio(9, 0, 0); retry_on_error(AccessTraq((InStoreStruct *) setup, 14, 16, 0, 0), status); pio(0, 0, &sampling); - for (try = 0; (try < 30) && (!(CamQ(0) & 1)) && (status & 1); try++) { + for (try = 0; (try < 30) && (!(CamQ(0) & 1)) && (STATUS_OK); try++) { DevWait((float).001); pio(0, 0, &sampling); } @@ -303,19 +303,19 @@ EXPORT int t4012___store(int *niddsc __attribute__ ((unused)), InStoreStruct * s TreeFree(nodename); strcat(digname, ":T28%%_%%"); status = TreeFindNodeWild(digname, &dig_nid, &ctx, 1 << TreeUSAGE_DEVICE); - for (dig = 1, channels_read = 0; (channels_read < channels) && (status & 1); dig++) { + for (dig = 1, channels_read = 0; (channels_read < channels) && (STATUS_OK); dig++) { static int dig_nids[1 + 8 * T28XX_K_NODES_PER_INP]; static int nidlen; static NCI_ITM itmlst[] = { {sizeof(dig_nids), NciCONGLOMERATE_NIDS, (unsigned char *)&dig_nids, &nidlen}, {0, NciEND_OF_LIST, 0, 0} }; - if (status & 1) { + if (STATUS_OK) { int i; int digchannels; status = TreeGetNci(dig_nid, itmlst); digchannels = (nidlen / sizeof(dig_nid) - 1) / T28XX_K_NODES_PER_INP; - for (i = 0; i < digchannels && (status & 1) && channels_read < channels; i++) { + for (i = 0; i < digchannels && (STATUS_OK) && channels_read < channels; i++) { if (TreeIsOn(CNID(i, HEAD)) & 1) { int channel_select = 0x0A000 | (channels_read + 1); AccessTraq(setup, channel_select, 24, 0, 0); @@ -342,7 +342,7 @@ EXPORT int t4012___store(int *niddsc __attribute__ ((unused)), InStoreStruct * s status = ReadChannel(setup, chunk, *acoef + chunk_offset, mem, &points_read, &CNID(i, CALIBRATION), calib); - if (status & 1) { + if (STATUS_OK) { offset = calib[0]; if (calib[0] == calib[1]) coefficient = (offset > 1000) ? 10. / 4096 : 5. / 4096.; @@ -359,7 +359,7 @@ EXPORT int t4012___store(int *niddsc __attribute__ ((unused)), InStoreStruct * s channels_read++; } } - if (channels_read < channels && (status & 1)) + if (channels_read < channels && (STATUS_OK)) status = TreeFindNodeWild(digname, &dig_nid, &ctx, 1 << TreeUSAGE_DEVICE); } TreeFindNodeEnd(&ctx); @@ -385,7 +385,7 @@ static int ReadChannel(InStoreStruct * setup, int chunk, int samples, unsigned s int points_to_read; int status = 1; //int tries; - for (points_to_read = chunksize; status & 1 && points_to_read; points_to_read = chunksize) { + for (points_to_read = chunksize; STATUS_OK && points_to_read; points_to_read = chunksize) { struct { unsigned short status; unsigned short bytcnt; @@ -401,7 +401,7 @@ static int ReadChannel(InStoreStruct * setup, int chunk, int samples, unsigned s arglist[0] = (void *)(sizeof(arglist) / sizeof(arglist[0])); AccessTraq(setup, chunk_address, 24, arglist, TdiData); pio(8, 0, 0); - for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (status & 1); try++) { + for (try = 0; (try < 20) && (!(CamQ(0) & 1)) && (STATUS_OK); try++) { pio(8, 0, 0); } pio(10, 0, 0); @@ -409,7 +409,7 @@ static int ReadChannel(InStoreStruct * setup, int chunk, int samples, unsigned s (CamQstopw (setup->name, 0, 2, points_to_read, buffer + *samples_read, 16, (unsigned short *)&iosb), &one, 0), status); - status = status & 1 ? iosb.status : status; + status = STATUS_OK ? iosb.status : status; *samples_read += iosb.bytcnt / 2; if (iosb.bytcnt / 2 != points_to_read) break; @@ -431,7 +431,7 @@ static int AccessTraq(InStoreStruct * setup, int data, int memsize, void *arglis } } piomem(17, 0, &data, memsize); - for (try = 0; (try < 30) && (!(CamQ(0) & 1)) && (status & 1); try++) { + for (try = 0; (try < 30) && (!(CamQ(0) & 1)) && (STATUS_OK); try++) { if (arglist && !called) { called = 1; LibCallg(arglist, routine); @@ -454,7 +454,7 @@ EXPORT int t4012__dw_setup(struct descriptor *niddsc __attribute__ ((unused)), s static NCI_ITM nci[] = { {4, NciCONGLOMERATE_NIDS, (unsigned char *)&nid, 0}, {0, NciEND_OF_LIST, 0, 0} }; TreeGetNci(*(int *)niddsc->pointer, nci); - uilnames[0].value = (char *)0 + nid; + uilnames[0].value = (void *)(intptr_t)nid; return XmdsDeviceSetup(parent, (int *)niddsc->pointer, uids, XtNumber(uids), "T4012", uilnames, XtNumber(uilnames), 0); } @@ -483,7 +483,7 @@ static void Load(Widget w) dignam[len++] = '0' + (i % 10); dignam[len++] = 0; status = TreeFindNode(dignam, &dig_nid); - if (status & 1) { + if (STATUS_OK) { NCI_ITM itmlst[] = { {512, NciNODE_NAME, 0, 0} , {0, 0, 0, 0} }; diff --git a/mitdevices/t4012_gen.c b/mitdevices/t4012_gen.c index ec5f5167b8..cd31113b2e 100644 --- a/mitdevices/t4012_gen.c +++ b/mitdevices/t4012_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "t4012_gen.h" EXPORT int t4012__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int t4012__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(T4012_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:NAME, TreeUSAGE_TEXT) flags |= NciM_NO_WRITE_SHOT; @@ -102,7 +102,7 @@ EXPORT int t4012__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, CAMAC_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, CAMAC_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -114,7 +114,7 @@ EXPORT int t4012__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (T4012_N_HEAD + 1): diff --git a/mitdevices/u_of_m_spect.c b/mitdevices/u_of_m_spect.c index aa07816b09..8b11058e5e 100644 --- a/mitdevices/u_of_m_spect.c +++ b/mitdevices/u_of_m_spect.c @@ -26,8 +26,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include +#include "mds_gendevice.h" +#include "mitdevices_msg.h" #include #include #include diff --git a/mitdevices/u_of_m_spect_gen.c b/mitdevices/u_of_m_spect_gen.c index a64dfa230a..527a43acae 100644 --- a/mitdevices/u_of_m_spect_gen.c +++ b/mitdevices/u_of_m_spect_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "u_of_m_spect_gen.h" EXPORT int u_of_m_spect__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int u_of_m_spect__add(struct descriptor *name_d_ptr, struct descriptor *d flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(U_OF_M_SPECT_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:GO_FILE, TreeUSAGE_TEXT) @@ -116,7 +116,7 @@ EXPORT int u_of_m_spect__add(struct descriptor *name_d_ptr, struct descriptor *d ADD_NODE_ACTION(:INIT_ACTION, INIT, INIT, 50, 0, 0, U_OF_M_SERVER, 0) ADD_NODE_ACTION(:STORE_ACTION, STORE, STORE, 50, 0, 0, U_OF_M_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -128,7 +128,7 @@ EXPORT int u_of_m_spect__part_name(struct descriptor *nid_d_ptr __attribute__ (( NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (U_OF_M_SPECT_N_HEAD + 1): diff --git a/mitdevices/umccd_gen.c b/mitdevices/umccd_gen.c index cb24aac303..aaa5ae6bec 100644 --- a/mitdevices/umccd_gen.c +++ b/mitdevices/umccd_gen.c @@ -22,8 +22,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include +#include "mitdevices_msg.h" +#include "mds_gendevice.h" #include "umccd_gen.h" EXPORT int umccd__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ptr __attribute__ ((unused)), int *nid_ptr) { @@ -38,21 +38,21 @@ EXPORT int umccd__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ flag_itm[0].pointer = (unsigned char *)&flags; name_ptr[name_d_ptr->length] = 0; status = TreeStartConglomerate(UMCCD_K_CONG_NODES); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeAddNode(name_ptr, &head_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *nid_ptr = head_nid; status = TreeSetNci(head_nid, flag_itm); status = TreePutRecord(head_nid, (struct descriptor *)&conglom_d, 0); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeGetDefaultNid(&old_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; status = TreeSetDefaultNid(head_nid); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; ADD_NODE(:COMMENT, TreeUSAGE_TEXT) ADD_NODE(:DATA_FILE, TreeUSAGE_TEXT) @@ -247,7 +247,7 @@ EXPORT int umccd__add(struct descriptor *name_d_ptr, struct descriptor *dummy_d_ ADD_NODE_ACTION(:STORE_ACTION, REPLACE_THIS, STORE, 50, 0, 0, IDL_SERVER, 0) ADD_NODE_ACTION(:ANALY_ACTION, REPLACE_THIS, ANALYSIS, 50, 0, 0, SUBMIT_SERVER, 0) status = TreeEndConglomerate(); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; return (TreeSetDefaultNid(old_nid)); } @@ -259,7 +259,7 @@ EXPORT int umccd__part_name(struct descriptor *nid_d_ptr __attribute__ ((unused) NCI_ITM nci_list[] = { {4, NciCONGLOMERATE_ELT, 0, 0}, {0, 0, 0, 0} }; nci_list[0].pointer = (unsigned char *)&element; status = TreeGetNci(*(int *)nid_d_ptr->pointer, nci_list); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; switch (element) { case (UMCCD_N_HEAD + 1): diff --git a/php/mdsplus.c b/php/mdsplus.c index c4ff1c92c5..155438a496 100644 --- a/php/mdsplus.c +++ b/php/mdsplus.c @@ -128,7 +128,7 @@ static void mdsplus_replace_error(char *msg, int do_not_copy) if (do_not_copy) mdsplus_error_msg = msg; else - mdsplus_error_msg = strcpy(malloc(strlen(msg) + 1), msg); + mdsplus_error_msg = strdup(msg); } static char *mdsplus_translate_status(int socket, int status) @@ -245,7 +245,7 @@ PHP_FUNCTION(mdsplus_connect) free(lastHost); lastHost = 0; } - lastHost = strcpy(malloc(strlen(arg) + 1), arg); + lastHost = strdup(arg); persistentConnection = handle; } RETURN_LONG(handle); @@ -317,7 +317,7 @@ PHP_FUNCTION(mdsplus_open) shot = (int)zshot; mdsplus_replace_error(0, 1); status = MdsOpen(socket, tree, shot); - if (status & 1) + if (STATUS_OK) { RETURN_TRUE; } @@ -351,7 +351,7 @@ PHP_FUNCTION(mdsplus_close) socket = (int)zsocket; mdsplus_replace_error(0, 1); status = MdsClose(socket); - if (status & 1) + if (STATUS_OK) { RETURN_TRUE; } @@ -464,7 +464,7 @@ PHP_FUNCTION(mdsplus_value) WRONG_PARAM_COUNT; status = SendArg(socket, 0, DTYPE_CSTRING, num_args - 1, strlen(expression), 0, dims, expression); - for (i = 2; (status & 1) && i < num_args; i++) + for (i = 2; (STATUS_OK) && i < num_args; i++) { switch (Z_TYPE_P(*args[i])) { @@ -485,14 +485,14 @@ PHP_FUNCTION(mdsplus_value) "invalid argument type, must be long, double or string only", 0); RETURN_FALSE; } - if (!(status & 1)) + if (STATUS_NOT_OK) { mdsplus_replace_error("error sending argument to server", 0); RETURN_FALSE; break; } } - if (!(status & 1)) + if (STATUS_NOT_OK) { mdsplus_replace_error("error sending argument to server", 0); RETURN_FALSE; @@ -523,7 +523,7 @@ PHP_FUNCTION(mdsplus_value) free(mem); } } - if (status & 1) + if (STATUS_OK) { if (ans.ndims == 0) { @@ -671,7 +671,7 @@ PHP_FUNCTION(mdsplus_put) node); status = SendArg(socket, 2, DTYPE_CSTRING, num_args, strlen(expression), 0, dims, expression); - for (i = 3; (status & 1) && i < num_args; i++) + for (i = 3; (STATUS_OK) && i < num_args; i++) { switch (Z_TYPE_P(*args[i])) { @@ -694,13 +694,13 @@ PHP_FUNCTION(mdsplus_put) goto done_mdsplus_put; break; } - if (!(status & 1)) + if (STATUS_NOT_OK) { mdsplus_replace_error("error sending argument to server", 0); goto done_mdsplus_put; } } - if (!(status & 1)) + if (STATUS_NOT_OK) { mdsplus_replace_error("error sending argument to server", 0); goto done_mdsplus_put; @@ -731,7 +731,7 @@ PHP_FUNCTION(mdsplus_put) free(mem); } } - if (status & 1) + if (STATUS_OK) { if (ans.ptr && (*(int *)ans.ptr & 1)) { @@ -765,7 +765,7 @@ PHP_FUNCTION(mdsplus_put) } done_mdsplus_put: free(ans.ptr); - if (status & 1) + if (STATUS_OK) { RETURN_TRUE; } diff --git a/pydevices/MitDevices/a3248.py b/pydevices/MitDevices/a3248.py index b8ef08ad6b..d3dcba73bd 100644 --- a/pydevices/MitDevices/a3248.py +++ b/pydevices/MitDevices/a3248.py @@ -23,10 +23,10 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -from MDSplus import Device +import MDSplus -class A3248(Device): +class A3248(MDSplus.Device): """ AEON 3248 4 channel transient recorder @@ -93,49 +93,43 @@ class A3248(Device): dts = (1E-7, 1.5E-7, 2E-7, 2.5E-7, 3E-7, 3.5E-7, 4E-7, 0.0, 1E-6, 1.5E-6, 2E-6, 2.5E-6, 3E-6, 3.5E-6, 4E-6, 0.0) - def getInteger(self, node, cls): + def getInteger(self, node, exc): try: ans = int(node.record) except Exception as e: print("AEON 3248 error reading %s erro is\n%s" % (node, e,)) - raise cls() + raise exc return ans - def getString(self, node, cls): + def getString(self, node, exc): try: ans = str(node.record) except Exception as e: print("AEON 3248 error reading %s erro is\n%s" % (node, e,)) - raise cls() + raise exc return ans def init(self): import math - from MDSplus import Data - from MDSplus.mdsExceptions import DevBAD_GAIN - from MDSplus.mdsExceptions import DevBAD_NAME - from MDSplus.mdsExceptions import DevBAD_OFFSET - from MDSplus.mdsExceptions import DevBAD_PRE_TRIG - from MDSplus.mdsExceptions import DevBAD_CLOCK_FREQ - if self.debug: print("A3248 INIT starting") - name = self.getString(self.name, DevBAD_NAME) - gain = self.getInteger(self.gain, DevBAD_GAIN) + name = self.getString(self.name, MDSplus.DevBAD_NAME) + gain = self.getInteger(self.gain, MDSplus.DevBAD_GAIN) if not gain in (1, 2, 4, 8): - raise(DevBAD_GAIN, "Gain must be one of 1,r or 8") + raise MDSplus.DevBAD_GAIN("Gain must be one of 1,r or 8") gain_code = int(math.log(gain, 2)) - offset = self.getInteger(self.offset, DevBAD_OFFSET) + offset = self.getInteger(self.offset, MDSplus.DevBAD_OFFSET) offset = max(min(offset, 255), 0) gain_offset_reg = (gain_code << 8) | offset pretrig = max( - min(self.getInteger(self.pretrig, DevBAD_PRE_TRIG), 32768), 0) + min(self.getInteger(self.pretrig, MDSplus.DevBAD_PRE_TRIG), 32768), 0) posttrig_code = (32768 - pretrig) << 7 - clock = self.getInteger(self.frequency, DevBAD_CLOCK_FREQ) + clock = self.getInteger(self.frequency, MDSplus.DevBAD_CLOCK_FREQ) if not clock in self.clock_freqs: - raise(DevBAD_CLOCK_FREQ, "Clock must be in ".self.clock_freqs) + raise MDSplus.DevBAD_CLOCK_FREQ( + "Clock must be in %r" % (self.clock_freqs,)) if self.ext_clock.length > 0: clock_code = 7 else: @@ -147,37 +141,30 @@ def init(self): status_reg = clock_code << 8 if pretrig != 0: status_reg = status_reg | posttrig_code | (1 << 12) - status = Data.execute('AEON_ARM("%s", %d, %d)' % - (name, gain_offset_reg, status_reg,)) + status = MDSplus.Data.execute('AEON_ARM("%s", %d, %d)' % ( + name, gain_offset_reg, status_reg,)) if (status & 1) == 0: - raise DevCAMAC_ERROR( + raise MDSplus.DevCAMAC_ERROR( 'AEON 3248 Arming %s status %d' % (name, status,)) INIT = init def trig(self): - from MDSplus import Data - from MDSplus.mdsExceptions import DevBAD_NAME - name = self.getString(self.name, DevBAD_NAME) - status = Data.execute('AEON_TRIGGER("%s")' % (name,)) + name = self.getString(self.name, MDSplus.DevBAD_NAME) + status = MDSplus.Data.execute('AEON_TRIGGER("%s")' % (name,)) if (status & 1) == 0: - raise DevCAMAC_ERROR( + raise MDSplus.DevCAMAC_ERROR( 'AEON 3248 Triggering %s status %d' % (name, status,)) TRIGGER = trig def store(self): """ Store method for the aeon 3248 digitizer """ - from MDSplus import Data - from MDSplus import Range - from MDSplus.mdsExceptions import DevBAD_NAME - from MDSplus.mdsExceptions import DevNOT_TRIGGERED - if self.debug: print("starting A3248 store") - name = self.getString(self.name, DevBAD_NAME) - status = Data.execute('AEON_CHECKTRIGGER("%s")' % (name,)) + name = self.getString(self.name, MDSplus.DevBAD_NAME) + status = MDSplus.Data.execute('AEON_CHECKTRIGGER("%s")' % (name,)) if not (status & 1): - raise DevNOT_TRIGGERED("Module %s not triggered" % name) - setup_vector = Data.execute('AEON_GETSETUP("%s")' % (name,)) + raise MDSplus.DevNOT_TRIGGERED("Module %s not triggered" % name) + setup_vector = MDSplus.Data.execute('AEON_GETSETUP("%s")' % (name,)) status_reg = int(setup_vector[0]) gain_reg = int(setup_vector[1]) addr = int(setup_vector[2]) @@ -200,38 +187,31 @@ def store(self): if dt == 0: self.clock.record = self.ext_clock else: - self.clock.record = Range(None, None, dt) + self.clock.record = MDSplus.Range(None, None, dt) for chan in range(4): self.storeChannel(name, chan, addr, pts, gain, offset) - return 1 STORE = store def dw_setup(self): - from MDSplus import Data - Data.execute('a3248__dw_setup($)', self.nid) - return 1 + MDSplus.Data.execute('a3248__dw_setup($)', self.nid) DW_SETUP = dw_setup def storeChannel(self, name, chan, addr, pts, gain, offset): - import MDSplus - chan_node = self.__getattr__('input_%1.1d' % (chan+1,)) if chan_node.on: if self.debug: print("it is on so ...") - start = 0 - end = pts-1 try: start = max(int(self.__getattr__( 'input_%1.1d_start_idx' % (chan+1,))), 0) - except: - pass + except Exception: + start = 0 try: end = min(int(self.__getattr__( 'input_%1.1d_end_idx' % (chan+1,))), pts-1) - except: - pass + except Exception: + end = pts-1 if self.debug: print("about to aeon_getchannel(%s, %d, %d %d)" % (name, addr, chan, end+1,)) @@ -248,10 +228,8 @@ def storeChannel(self, name, chan, addr, pts, gain, offset): dat = MDSplus.Data.compile( 'build_signal(build_with_units(($value - $2)*.02/$1, "V") ,build_with_units($3,"Counts"),$4)', gain, offset, buf[start: end], dim) - exec('c=self.input_'+'%1d' % (chan+1,)+'.record=dat') + getattr(self, 'input_%d' % (chan+1,)).record = dat def help(self): """ Help method to describe the methods and nodes of the AEON_3248 module type """ - help(A3248) - return 1 - HELP = help + return help(A3248) diff --git a/python/MDSplus/connection.py b/python/MDSplus/connection.py index a5944c62c5..27e0c1ac48 100644 --- a/python/MDSplus/connection.py +++ b/python/MDSplus/connection.py @@ -24,6 +24,11 @@ # +import threading +import numpy +import ctypes + + def _mimport(name, level=1): try: return __import__(name, globals(), level=level) @@ -31,9 +36,6 @@ def _mimport(name, level=1): return __import__(name, globals()) -import ctypes as _C -import numpy as _N - _dsc = _mimport('descriptor') _exc = _mimport('mdsExceptions') _apd = _mimport('apd') @@ -51,46 +53,51 @@ class MdsIpException(_exc.MDSplusException): _ConnectToMds = __MdsIpShr.ConnectToMds _DisconnectFromMds = __MdsIpShr.DisconnectFromMds _GetAnswerInfoTO = __MdsIpShr.GetAnswerInfoTO -_GetAnswerInfoTO.argtypes = [_C.c_int32, _C.POINTER(_C.c_ubyte), _C.POINTER(_C.c_ushort), _C.POINTER(_C.c_ubyte), - _C.c_void_p, _C.POINTER(_C.c_ulong), _C.POINTER(_C.c_void_p), _C.POINTER(_C.c_void_p), _C.c_int32] +_GetAnswerInfoTO.argtypes = [ctypes.c_int32, ctypes.POINTER(ctypes.c_ubyte), ctypes.POINTER(ctypes.c_ushort), ctypes.POINTER(ctypes.c_ubyte), + ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p), ctypes.c_int32] _MdsIpFree = __MdsIpShr.MdsIpFree -_MdsIpFree.argtypes = [_C.c_void_p] +_MdsIpFree.argtypes = [ctypes.c_void_p] _SendArg = __MdsIpShr.SendArg -_SendArg.argtypes = [_C.c_int32, _C.c_ubyte, _C.c_ubyte, - _C.c_ubyte, _C.c_ushort, _C.c_ubyte, _C.c_void_p, _C.c_void_p] +_SendArg.argtypes = [ctypes.c_int32, ctypes.c_ubyte, ctypes.c_ubyte, + ctypes.c_ubyte, ctypes.c_ushort, ctypes.c_ubyte, ctypes.c_void_p, ctypes.c_void_p] -class Connection(object): - """Implements an MDSip connection to an MDSplus server""" - _socket = 0 +INVALID_CONNECTION_ID = -1 +class _Connection: + + _conid = INVALID_CONNECTION_ID + + def __init__(self, hostspec): + self.hostspec = _ver.tobytes(hostspec) @property - def socket(self): - if self._socket == 0: - self._socket = _ConnectToMds(_ver.tobytes(self.hostspec)) - if self._socket == -1: - raise MdsIpException("Error connecting to %s" % (self.hostspec,)) - return self._socket - - @socket.setter - def socket(self, value): - if self._socket > 0: - try: - _DisconnectFromMds(self._socket) - except: - pass - self._socket = value + def conid(self): + self.connect() + return self._conid - def __enter__(self): - """ Used for with statement. """ + def connect(self): + if self._conid == INVALID_CONNECTION_ID: + self._conid = _ConnectToMds(self.hostspec) + if self._conid == INVALID_CONNECTION_ID: + raise MdsIpException("Error connecting to %s" % + _ver.tostr(self.hostspec)) + + def disconnect(self): + if self._conid != INVALID_CONNECTION_ID: + _DisconnectFromMds(self._conid) + self._conid = INVALID_CONNECTION_ID + + def __enter__(self, *a): self.connect() - return self def __exit__(self, type, value, traceback): - """ Cleanup for with statement. """ self.disconnect() - def __inspect__(self, value): + def __del__(self): + self.disconnect() + + @staticmethod + def _inspect(value): """Internal routine used in determining characteristics of the value""" d = value.descriptor if d.dclass == 4: @@ -102,13 +109,13 @@ def __inspect__(self, value): dims.append(d.coeff_and_bounds[i]) dtype = d.dtype length = d.length - dims = _N.array(dims, dtype=_N.uint32) + dims = numpy.array(dims, dtype=numpy.uint32) dimct = d.dimct pointer = d.pointer else: length = d.length dtype = d.dtype - dims = _N.array(0, dtype=_N.uint32) + dims = numpy.array(0, dtype=numpy.uint32) dimct = 0 pointer = d.pointer if dtype == 52: @@ -121,17 +128,17 @@ def __inspect__(self, value): dtype = 13 return {'dtype': dtype, 'length': length, 'dimct': dimct, 'dims': dims, 'address': pointer} - def __getAnswer__(self, to_msec=-1): - dtype = _C.c_ubyte(0) - length = _C.c_ushort(0) - ndims = _C.c_ubyte(0) - dims = _N.array([0, 0, 0, 0, 0, 0, 0, 0], dtype=_N.uint32) - numbytes = _C.c_ulong(0) - ans = _C.c_void_p(0) - mem = _C.c_void_p(0) + def _get_answer(self, to_msec=-1): + dtype = ctypes.c_ubyte(0) + length = ctypes.c_ushort(0) + ndims = ctypes.c_ubyte(0) + dims = numpy.array([0, 0, 0, 0, 0, 0, 0, 0], dtype=numpy.uint32) + numbytes = ctypes.c_ulong(0) + ans = ctypes.c_void_p(0) + mem = ctypes.c_void_p(0) try: - _exc.checkStatus(_GetAnswerInfoTO(self.socket, dtype, length, ndims, - dims.ctypes.data, numbytes, _C.byref(ans), _C.byref(mem), int(to_msec))) + _exc.checkStatus(_GetAnswerInfoTO(self.conid, dtype, length, ndims, + dims.ctypes.data, numbytes, ctypes.byref(ans), ctypes.byref(mem), int(to_msec))) dtype = dtype.value if dtype == 10: dtype = 52 @@ -175,39 +182,80 @@ def __getAnswer__(self, to_msec=-1): if mem.value is not None: _MdsIpFree(mem) + def _send_arg(self, value, idx, num): + """Internal routine to send argument to mdsip server""" + val = _dat.Data(value) + if not isinstance(val, _sca.Scalar) and not isinstance(val, _arr.Array): + val = _dat.Data(val.data()) + info = self._inspect(val) + _exc.checkStatus( + _SendArg(self.conid, + idx, + info['dtype'], + num, + info['length'], + info['dimct'], + info['dims'].ctypes.data, + info['address'])) + + def get(self, exp, *args, **kwargs): + if 'arglist' in kwargs: + args = kwargs['arglist'] + timeout = kwargs.get('timeout', -1) + num = len(args)+1 + exp = _ver.tobytes(exp) + _exc.checkStatus(_SendArg(self.conid, 0, 14, num, + len(exp), 0, 0, ctypes.c_char_p(exp))) + for i, arg in enumerate(args): + self._send_arg(arg, i+1, num) + return self._get_answer(timeout) + + +class Connection(object): + """Implements an MDSip connection to an MDSplus server""" + + @property + def conn(self): + try: + conn = self._local.conn + except AttributeError: + conn = self._local.conn = _Connection(self.hostspec) + return conn + + @conn.deleter + def conn(self): + try: + conn = self._local.conn + except AttributeError: + pass + else: + del(self._local.conn) + conn.disconnect() + + def __enter__(self): + """ Used for with statement. """ + self.conn.__enter__() + return self + + def __exit__(self, type, value, traceback): + """ Cleanup for with statement. """ + self.disconnect() + def __init__(self, hostspec): + self._local = threading.local() self.hostspec = hostspec self.connect() def connect(self): - return self.socket + self.conn.connect() def disconnect(self): - self.socket = 0 + del(self.conn) def reconnect(self): self.disconnect() self.connect() - def __del__(self): - self.disconnect() - - def __sendArg__(self, value, idx, num): - """Internal routine to send argument to mdsip server""" - val = _dat.Data(value) - if not isinstance(val, _sca.Scalar) and not isinstance(val, _arr.Array): - val = _dat.Data(val.data()) - valInfo = self.__inspect__(val) - _exc.checkStatus( - _SendArg(self.socket, - idx, - valInfo['dtype'], - num, - valInfo['length'], - valInfo['dimct'], - valInfo['dims'].ctypes.data, - valInfo['address'])) - def closeAllTrees(self): """Close all open MDSplus trees @rtype: number of closed trees @@ -266,16 +314,7 @@ def get(self, exp, *args, **kwargs): @return: result of evaluating the expression on the remote server @rtype: Scalar or Array """ - if 'arglist' in kwargs: - args = kwargs['arglist'] - timeout = kwargs.get('timeout', -1) - num = len(args)+1 - exp = _ver.tobytes(exp) - _exc.checkStatus(_SendArg(self.socket, 0, 14, num, - len(exp), 0, 0, _C.c_char_p(exp))) - for i, arg in enumerate(args): - self.__sendArg__(arg, i+1, num) - return self.__getAnswer__(timeout) + return self.conn.get(exp, *args, **kwargs) def getObject(self, exp, *args, **kwargs): return self.get('serializeout(`(%s;))' % exp, *args, **kwargs).deserialize() diff --git a/python/MDSplus/tests/Makefile.am b/python/MDSplus/tests/Makefile.am index 46a3b15a6c..6f3663264a 100644 --- a/python/MDSplus/tests/Makefile.am +++ b/python/MDSplus/tests/Makefile.am @@ -54,9 +54,14 @@ connection_thick_test.py \ connection_thread_test.py \ connection_tunnel_test.py \ connection_tcp_test.py \ -dcl_interface_test.py \ -dcl_dispatcher_test.py +connection_write_test.py \ +dcl_interface_test.py +if !MINGW +TESTS += dcl_dispatcher_test.py +endif +# connection_write_test.py causes valgrind to hang? +VALGRIND_TESTS = $(filter-out connection_write_test.py,$(TESTS)) VALGRIND_SUPPRESSIONS_FILES = diff --git a/python/MDSplus/tests/_common.py b/python/MDSplus/tests/_common.py index a68fb2f23f..946a2a9a51 100644 --- a/python/MDSplus/tests/_common.py +++ b/python/MDSplus/tests/_common.py @@ -33,6 +33,12 @@ import sys import time +from MDSplus.mdsExceptions import MDSplusException + + +iswin = sys.platform.startswith('win') +MDSIP_PROTOCOL = getenv('MDSIP_PROTOCOL','TCP') + class logger(object): """wrapper class to force flush on each write""" @@ -55,17 +61,24 @@ class TestThread(threading.Thread): """ Run Tests in parralel and evaluate """ @staticmethod - def assertRun(*threads): + def assertRun(timeout, *threads): for thread in threads: thread.start() + last = time.time() for thread in threads: - thread.join() + if timeout > 0: + thread.join(timeout) + now = time.time() + timeout -= now - last + last = now + else: + thread.join(0) for thread in threads: thread.check() def __init__(self, name, test, *args, **kwargs): super(TestThread, self).__init__(name=name) - self.exc = None + self.exc = threading.ThreadError(name + " still running") self.test = test self.args = args self.kwargs = kwargs @@ -77,6 +90,8 @@ def run(self): if not hasattr(exc, "__traceback__"): _, _, exc.__traceback__ = sys.exc_info() self.exc = exc + else: + self.exc = None def check(self): if self.exc: @@ -96,7 +111,7 @@ class Tests(TestCase): @classmethod def getTests(cls): if cls.__module__.endswith("_test"): - _, test=cls.__module__[:-5].split('_', 1) + _, test = cls.__module__[:-5].split('_', 1) return [test] if not cls.inThread: return list(cls.TESTS) @@ -196,29 +211,29 @@ def main(cls): cls.runTests() else: print('Available tests: %s' % (' '.join(cls.getTests()))) - envx={} - env={} + envx = {} + env = {} @classmethod def _setenv(cls, name, value): - value=str(value) - cls.env[name]=value - cls.envx[name]=value + value = str(value) + cls.env[name] = value + cls.envx[name] = value setenv(name, value) class MdsIp(object): - root=os.path.dirname(os.path.realpath(__file__)) + root = os.path.dirname(os.path.realpath(__file__)) @staticmethod def _setup_mdsip(server_env, port_env, default_port, fix0): - host=getenv(server_env, '') - if len(host) > 0: + host = getenv(server_env, '') + if host: return host, 0 - port=int(getenv(port_env, default_port)) + port = int(getenv(port_env, default_port)) if port == 0: if fix0: - port=default_port + port = default_port else: return None, 0 return 'localhost:%d' % (port,), port @@ -232,12 +247,12 @@ def _testDispatchCommandNoWait(self, mdsip, command, stdout=None, stderr=None): (mdsip, command)) def _checkIdle(self, server, **opt): - show_server="Checking server: %s\n[^,]+, [^,]+, logging enabled, Inactive\n" % server + show_server = "Checking server: %s\n[^,]+, [^,]+, logging (.|\n)*Inactive\n" % server self._doTCLTest('show server %s' % server, out=show_server, regex=True, **opt) def _waitIdle(self, server, timeout): - timeout=time.time()+timeout + timeout = time.time()+timeout while 1: time.sleep(.3) try: @@ -253,12 +268,12 @@ def _wait(self, svr, to): if to <= 0: return svr.poll() if sys.version_info < (3, 3): - rtn=svr.poll() + rtn = svr.poll() for _ in range(int(10*to)): if rtn is not None: break time.sleep(.1) - rtn=svr.poll() + rtn = svr.poll() return rtn try: svr.wait(to) @@ -268,36 +283,40 @@ def _wait(self, svr, to): return svr.poll() def _stop_mdsip(self, *procs_in): - for svr, server in procs_in: - if svr is None: # close trees on externals + # filter unused mdsip + procs = [(svr, server) for svr, server in procs_in if server] + for svr, server in procs: + if not svr: # close trees on externals try: self._doTCLTest( 'dispatch/command/wait/server=%s close/all' % server) - except: + except MDSplusException: pass # filter external mdsip - procs=[(svr, server) for svr, server in procs_in if svr is not None] + procs = [(svr, server) for svr, server in procs if svr] # filter terminated - procs=[(svr, server) for svr, server in procs if svr.poll() is None] + procs = [(svr, server) for svr, server in procs if svr.poll() is None] if len(procs) == 0: return + """ # stop server for svr, server in procs: try: self._doTCLTest('stop server %s' % server) - except: + except MDSplusException: pass - t=time.time()+6 - procs=[(svr, server) + t = time.time()+6 + procs = [(svr, server) for svr, server in procs if self._wait(svr, t-time.time()) is None] if len(procs) == 0: return + """ # terminate server for svr, server in procs: sys.stderr.write("sending SIGTERM to %s" % server) svr.terminate() - t=time.time()+3 - procs=[(svr, server) + t = time.time()+3 + procs = [(svr, server) for svr, server in procs if self._wait(svr, t-time.time()) is None] if len(procs) == 0: return @@ -305,44 +324,53 @@ def _stop_mdsip(self, *procs_in): for svr, server in procs: sys.stderr.write("sending SIGKILL to %s" % server) svr.kill() - t=time.time()+3 - procs=[server for svr, server in procs if self._wait( + t = time.time()+3 + procs = [server for svr, server in procs if self._wait( svr, t-time.time()) is None] if len(procs) == 0: return raise Exception("FAILED cleaning up mdsips: %s" % (", ".join(procs),)) - def _start_mdsip(self, server, port, logname, protocol='TCP'): + def _start_mdsip(self, server, port, logname, protocol=MDSIP_PROTOCOL): if port > 0: from subprocess import Popen, STDOUT - logfile='%s-%s%d.log' % (self.module, logname, self.index) - log=open(logfile, 'w') + logfile = '%s-%s%d.log' % (self.module, logname, self.index) + log = open(logfile, 'w') if iswin else None try: - hosts='%s/mdsip.hosts' % self.root - params=['mdsip', '-s', '-p', + hosts = '%s/mdsip.hosts' % self.root + params = ['mdsip', '-s', '-p', str(port), '-P', protocol, '-h', hosts] - print(' '.join(params+['>', logfile, '2>&1'])) - mdsip=Popen(params, stdout=log, stderr=STDOUT) + + print(' '.join(params + ['&>', logfile])) + if not log: + params.extend(['2>&1', '|', 'tee', logfile]) + mdsip = Popen(params) except: - log.close() + if log: + log.close() + raise + try: + self._waitIdle(server, 10) # allow mdsip to launch + except Exception: + mdsip.kill() raise - time.sleep(.3) - self._waitIdle(server, 10) # allow mdsip to launch else: - mdsip, log=None, None - c=Connection(server) - for envpair in self.envx.items(): - checkStatus(c.get('setenv($//"="//$)', *envpair)) - c.get('tcl($)', 'set verify') + mdsip, log = None, None + if server: + c = Connection(server) + for envpair in self.envx.items(): + checkStatus(c.get('setenv($//"="//$)', *envpair)) + c.get('tcl($)', 'set verify') return mdsip, log class TreeTests(Tests): - lock=threading.RLock() - shotinc=1 - instances=0 - trees=[] - tree=None + lock = threading.RLock() + shotinc = 1 + instances = 0 + trees = [] + tree = None + tmpdir = None @property def shot(self): @@ -355,19 +383,20 @@ def setUpClass(cls): gc.collect() from tempfile import mkdtemp if getenv("TEST_DISTRIBUTED_TREES") is not None: - treepath="thread://tree::%s" + treepath = "thread://tree::%s" else: - treepath="%s" - cls.tmpdir=mkdtemp() - cls.root=os.path.dirname(os.path.realpath(__file__)) - cls.topsrc=os.path.realpath( + treepath = "%s" + cls.tmpdir = mkdtemp() + cls.root = os.path.dirname(os.path.realpath(__file__)) + cls.topsrc = os.path.realpath( cls.root+"%s..%s..%s.." % tuple([os.sep]*3)) - cls.env=dict((k, str(v)) for k, v in os.environ.items()) - cls.envx={} + cls.env = dict((k, str(v)) for k, v in os.environ.items()) + cls.envx = {} cls._setenv('PyLib', getenv('PyLib')) cls._setenv("MDS_PYDEVICE_PATH", '%s/pydevices;%s/devices' % (cls.topsrc, cls.root)) - trees = cls.trees if cls.tree is None else set(cls.trees).union([cls.tree]) + trees = cls.trees if cls.tree is None else set( + cls.trees).union([cls.tree]) for treename in trees: cls._setenv("%s_path" % treename, treepath % cls.tmpdir) if getenv("testing_path") is None: @@ -394,7 +423,7 @@ def is_tree(o): except Exception as e: print(e) return False - trees=[o for o in gc.get_objects() if is_tree(o)] + trees = [o for o in gc.get_objects() if is_tree(o)] for t in trees: try: t.close() diff --git a/python/MDSplus/tests/connection_case.py b/python/MDSplus/tests/connection_case.py index 02f42738f7..7d3407c908 100755 --- a/python/MDSplus/tests/connection_case.py +++ b/python/MDSplus/tests/connection_case.py @@ -70,83 +70,83 @@ def testnci(thick, local, con, nci): raise server, server_port = self._setup_mdsip( 'ACTION_SERVER', 'ACTION_PORT', 7000+self.index, True) - svr = svr_log = None + + svr, svr_log = self._start_mdsip(server, server_port, 'thick') try: - svr, svr_log = self._start_mdsip(server, server_port, 'thick') - try: - con = Connection(server) - self.assertEqual(con.get("zero([1,1,1,1,1,1,1,1],1)").tolist(), [ - [[[[[[[0]]]]]]]]) - with Tree(self.tree, -1, "new") as local: - local.addNode(self.treesub, "SUBTREE") - s = local.addNode("S", "SIGNAL") - s.addTag("tagS") - s.record = ADD(Float32(1), Float32(2)) - t = local.addNode("T", "TEXT") - t.addNode("TT", "TEXT").addTag("tagTT") - t.record = t.TT - t.TT = "recTT" - local.write() - with Tree(self.treesub, -1, "new") as sub: - sub.addNode("OK") - sub.write() - local.normal() - Tree.setCurrent(self.tree, 7) - setenv("%s_path" % self.tree, "%s::" % server) - print(con.get("getenv($//'_path')", self.tree)) - con.get("TreeShr->TreeOpen(ref($),val($),val(1))", self.tree, -1) - thick = Tree(self.tree, -1) - thick.createPulse(1) - thick1 = Tree(self.tree, 1) - self.assertEqual( - getattr(local, self.treesub.upper()).OK.nid, - getattr(thick1, self.treesub.upper()).OK.nid) - local_filename = local.getFileName() - thick_filename = thick.getFileName() - self.assertTrue("::" in thick_filename, thick_filename) - self.assertTrue(local_filename, thick_filename.split("::", 1)[1]) - """ TreeTurnOff / TreeTurnOn """ - thick.S.on = False - self.assertEqual(local.S.on, False) - thick.S.on = True - self.assertEqual(local.S.on, True) - """ TreeSetCurrentShotId / TreeGetCurrentShotId """ - Tree.setCurrent(self.tree, 1) - self.assertEqual(Tree.getCurrent(self.tree), 1) - """ TreeGetRecord / TreeSetRecord """ - self.assertEqual(str(local.S.record), "1. + 2.") - self.assertEqual(str(thick.S.record), "1. + 2.") - thick.S.record = ADD(Float32(2), Float32(4)) - self.assertEqual(str(local.S.record), "2. + 4.") - self.assertEqual(str(thick.S.record), "2. + 4.") - self.assertEqual(str(local.T.record), str(thick.T.record)) - """ GetDefaultNid / SetDefaultNid """ - self.assertEqual(thick.getDefault(), thick.top) - thick.setDefault(thick.S) - self.assertEqual(thick.getDefault(), thick.top.S) - thick.setDefault(thick.top) - """ FindNodeWildRemote """ - self.assertEqual(str(thick.getNodeWild("T*")), - str(local.getNodeWild("T*"))) - """ FindTagWildRemote """ - self.assertEqual(thick.findTags("*"), local.findTags("*")) - """ nci """ - thick.S.write_once = True - self.assertEqual(thick.S.write_once, True) - for nci in ( - 'on', 'depth', 'usage_str', 'dtype', 'length', - 'rlength', 'fullpath', 'minpath', 'member_nids', - 'children_nids', 'rfa', 'write_once', - ): - testnci(thick, local, con, nci) - """ new stuff """ - self.assertEqual(local.getFileName(), con.get( - "treefilename($,-1)", self.tree)) - finally: - self._stop_mdsip((svr, server)) + con = Connection(server) + self.assertEqual( + con.get("zero([1,1,1,1,1,1,1,1],1)").tolist(), + [[[[[[[[0]]]]]]]]) + with Tree(self.tree, -1, "new") as local: + local.addNode(self.treesub, "SUBTREE") + s = local.addNode("S", "SIGNAL") + s.addTag("tagS") + s.record = ADD(Float32(1), Float32(2)) + t = local.addNode("T", "TEXT") + t.addNode("TT", "TEXT").addTag("tagTT") + t.record = t.TT + t.TT = "recTT" + local.write() + with Tree(self.treesub, -1, "new") as sub: + sub.addNode("OK") + sub.write() + local.normal() + Tree.setCurrent(self.tree, 7) + setenv("%s_path" % self.tree, "%s::" % server) + print(con.get("getenv($//'_path')", self.tree)) + con.get("TreeShr->TreeOpen(ref($),val($),val(1))", self.tree, -1) + thick = Tree(self.tree, -1) + thick.createPulse(1) + thick1 = Tree(self.tree, 1) + self.assertEqual( + getattr(local, self.treesub.upper()).OK.nid, + getattr(thick1, self.treesub.upper()).OK.nid) + local_filename = local.getFileName() + thick_filename = thick.getFileName() + self.assertTrue("::" in thick_filename, thick_filename) + self.assertTrue( + local_filename, thick_filename.split("::", 1)[1]) + """ TreeTurnOff / TreeTurnOn """ + thick.S.on = False + self.assertEqual(local.S.on, False) + thick.S.on = True + self.assertEqual(local.S.on, True) + """ TreeSetCurrentShotId / TreeGetCurrentShotId """ + Tree.setCurrent(self.tree, 1) + self.assertEqual(Tree.getCurrent(self.tree), 1) + """ TreeGetRecord / TreeSetRecord """ + self.assertEqual(str(local.S.record), "1. + 2.") + self.assertEqual(str(thick.S.record), "1. + 2.") + thick.S.record = ADD(Float32(2), Float32(4)) + self.assertEqual(str(local.S.record), "2. + 4.") + self.assertEqual(str(thick.S.record), "2. + 4.") + self.assertEqual(str(local.T.record), str(thick.T.record)) + """ GetDefaultNid / SetDefaultNid """ + self.assertEqual(thick.getDefault(), thick.top) + thick.setDefault(thick.S) + self.assertEqual(thick.getDefault(), thick.top.S) + thick.setDefault(thick.top) + """ FindNodeWildRemote """ + self.assertEqual(str(thick.getNodeWild("T*")), + str(local.getNodeWild("T*"))) + """ FindTagWildRemote """ + self.assertEqual(thick.findTags("*"), local.findTags("*")) + """ nci """ + thick.S.write_once = True + self.assertEqual(thick.S.write_once, True) + for nci in ( + 'on', 'depth', 'usage_str', 'dtype', 'length', + 'rlength', 'fullpath', 'minpath', 'member_nids', + 'children_nids', 'rfa', 'write_once', + ): + testnci(thick, local, con, nci) + """ new stuff """ + self.assertEqual(local.getFileName(), con.get( + "treefilename($,-1)", self.tree)) finally: if svr_log: svr_log.close() + self._stop_mdsip((svr, server)) def io(self): connection = Connection("thread://io") @@ -170,7 +170,7 @@ def requests(self, c, idx): self.assertEqual( c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(), args) connection = Connection(server) - _common.TestThread.assertRun(*( + _common.TestThread.assertRun(100, *( _common.TestThread("T%d" % idx, requests, self, connection, idx) for idx in range(5) )) @@ -178,20 +178,13 @@ def requests(self, c, idx): def tcp(self): server, server_port = self._setup_mdsip( 'ACTION_SERVER', 'ACTION_PORT', 7010+self.index, True) - svr = svr_log = None + svr, svr_log = self._start_mdsip(server, server_port, 'tcp') try: - svr, svr_log = self._start_mdsip(server, server_port, 'tcp') - try: - if svr is not None: - time.sleep(1) - self._thread_test(server) - finally: - if svr and svr.poll() is None: - svr.terminate() - svr.wait() + self._thread_test(server) finally: if svr_log: svr_log.close() + self._stop_mdsip((svr, server)) def tunnel(self): self._thread_test('local://threads') @@ -202,39 +195,35 @@ def thread(self): def write(self): count = 100 - def mdsip(hostfile): - with open(hostfile, "w") as f: - f.write("multi|SELF\n*") - process = subprocess.Popen(( - 'mdsip', '-m', - '-p', '8000', - '-P', 'TCP', - '-h', hostfile, - )) - time.sleep(1) - return process - def thread(test, name, node, count): - start = time.time() i = -1 + max_period = 0 + last = start = time.time() for i in range(count): data = Float32([i*10+1]) - now = Float32([time.time()]) - node.makeSegment(now[0], now[0], data, now) - end = time.time() + dim = Float32([last]) + node.makeSegment(dim[0], dim[0], data, dim) + end = time.time() + max_period = max(end-last, max_period) + last = end i += 1 test.assertEqual(i, count) - print("%s: rate %f" % (name, i / (end-start))) + print("%s: rate=%f, max_period=%f" % + (name, i / (end-start), max_period)) + server, server_port = self._setup_mdsip( + 'ACTION_SERVER', 'ACTION_PORT', 7020+self.index, True) tempdir = tempfile.mkdtemp() try: - server = mdsip(os.path.join(tempdir, "mdsip.hosts")) + svr, svr_log = self._start_mdsip(server, server_port, 'tcp') try: - con = Connection('127.0.0.1') + con = Connection(server) def check(line, *args): sts = con.get(line, *args) - self.assertTrue(sts & 1, "error %d in '%s'" % (sts, line)) + self.assertTrue( + sts & 1, "error %d in '%s'" % (sts, line)) + check("setenv('test_path='//$)", tempdir) for line in ( "TreeOpenNew('test', 1)", @@ -244,18 +233,19 @@ def check(line, *args): "TreeClose()", ): check(line) - setenv("test_path", "127.0.0.1::" + tempdir) + setenv("test_path", "%s::%s" % (server, tempdir)) tree = Tree("test", 1) _common.TestThread.assertRun( + 100, _common.TestThread('EV1', thread, self, 'EV1', tree.EV1.copy(), count), _common.TestThread('EV2', thread, self, 'EV2', tree.EV2.copy(), count), ) finally: - if server: - server.kill() - server.wait() + if svr_log: + svr_log.close() + self._stop_mdsip((svr, server)) finally: shutil.rmtree(tempdir, ignore_errors=False, onerror=None) diff --git a/python/MDSplus/tests/dcl_case.py b/python/MDSplus/tests/dcl_case.py index 8052b2af82..7bc7a68b5e 100755 --- a/python/MDSplus/tests/dcl_case.py +++ b/python/MDSplus/tests/dcl_case.py @@ -94,7 +94,8 @@ def interface(self): """ context """ self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) pytree = Tree() - self.assertEqual(str(pytree), 'Tree("%(EXPT)s",%(SHOT)d,"Normal")' % fmt) + self.assertEqual( + str(pytree), 'Tree("%(EXPT)s",%(SHOT)d,"Normal")' % fmt) self._doTCLTest('close %(EXPT)s/shot=%(SHOT)d' % fmt) self.assertEqual(str(pytree), 'Tree("?",?,"Closed")') if self.inThread: @@ -120,7 +121,7 @@ def dispatcher(self): pytree.write() monitor, monitor_port = self._setup_mdsip( 'ACTION_MONITOR', 'MONITOR_PORT', 7100+self.index, False) - monitor_opt = "/monitor=%s" % monitor if monitor_port > 0 else "" + monitor_opt = "/monitor=%s" % monitor if monitor else "" server, server_port = self._setup_mdsip( 'ACTION_SERVER', 'ACTION_PORT', 7110+self.index, True) pytree.normal() @@ -131,40 +132,35 @@ def dispatcher(self): """ using dispatcher """ mon, mon_log, svr, svr_log = (None, None, None, None) try: - mon, mon_log = self._start_mdsip(monitor, monitor_port, 'monitor') - svr, svr_log = self._start_mdsip(server, server_port, 'dispatcher') - try: - if mon: - self.assertEqual(mon.poll(), None) - if svr: - self.assertEqual(svr.poll(), None) - """ tcl dispatch """ - self._testDispatchCommand(server, 'type test') - env = "%s_path" % self.tree - self._doTCLTest('env '+ env, '%s=%s\n' % (env, self.envx[env])) - self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) - self._doTCLTest('dispatch/build%s' % monitor_opt) - self._doTCLTest('dispatch/phase%s INIT' % monitor_opt) - self._waitIdle(server, 3) - self._doTCLTest('dispatch/phase%s PULSE' % monitor_opt) - self._waitIdle(server, 3) - self._doTCLTest('dispatch/phase%s STORE' % monitor_opt) - self._waitIdle(server, 3) - """ tcl exceptions """ - self._doExceptionTest( - 'dispatch/command/server=%s ' % server, Exc.MdsdclIVVERB) - """ tcl check if still alive """ - if mon: - self.assertEqual(mon.poll(), None) - if svr: - self.assertEqual(svr.poll(), None) - finally: - self._stop_mdsip((svr, server), (mon, monitor)) + mon, mon_log = self._start_mdsip(monitor, monitor_port, 'monitor', 'TCP') + svr, svr_log = self._start_mdsip(server, server_port, 'action', 'TCP') + """ tcl dispatch """ + self._testDispatchCommand(server, 'type test') + env = "%s_path" % self.tree + self._doTCLTest('env ' + env, '%s=%s\n' % + (env, self.envx[env])) + self._doTCLTest('set tree %(EXPT)s/shot=%(SHOT)d' % fmt) + self._doTCLTest('dispatch/build%s' % monitor_opt) + self._doTCLTest('dispatch/phase%s INIT' % monitor_opt) + self._waitIdle(server, 3) + self._doTCLTest('dispatch/phase%s PULSE' % monitor_opt) + self._waitIdle(server, 3) + self._doTCLTest('dispatch/phase%s STORE' % monitor_opt) + self._waitIdle(server, 3) + """ tcl exceptions """ + self._doExceptionTest( + 'dispatch/command/server=%s ' % server, Exc.MdsdclIVVERB) + """ tcl check if still alive """ + if mon: + self.assertEqual(mon.poll(), None) + if svr: + self.assertEqual(svr.poll(), None) finally: if svr_log: svr_log.close() if mon_log: mon_log.close() + self._stop_mdsip((svr, server), (mon, monitor)) self._doTCLTest('close/all') pytree.readonly() self.assertTrue(pytree.TESTDEVICE_I.INIT1_DONE.record <= @@ -197,32 +193,31 @@ def test_normal(c, expr, **kv): c.get(expr, **kv) server, server_port = self._setup_mdsip( 'ACTION_SERVER', 'ACTION_PORT', 7120+self.index, True) - svr = svr_log = None + + svr, svr_log = self._start_mdsip(server, server_port, 'timeout') try: - svr, svr_log = self._start_mdsip(server, server_port, 'timeout') - try: - if svr: - self.assertEqual(svr.poll(), None) - c = Connection(server) - test_normal(c, "py('1')") # preload MDSplus on server - test_timeout(c, "wait(3)", 1000) # break tdi wait - # break python sleep - test_timeout(c, "py('from time import sleep;sleep(3)')", 1500) - if full: # timing too unreliable for standard test - test_timeout(c, "for(;1;) ;", 100) # break tdi inf.loop - # break python inf.loop - test_timeout(c, "py('while 1: pass')", 500) - test_normal(c, "1", timeout=1000) - # TODO: make this work under fc29 (python3.7?) - if sys.version_info < (3, 7): - # verify locks are released - test_normal(c, "py('1')", timeout=1000) - self._doTCLTest('stop server %s' % server) - finally: - self._stop_mdsip((svr, server)) + if svr: + self.assertEqual(svr.poll(), None) + c = Connection(server) + test_normal(c, "py('1')") # preload MDSplus on server + test_timeout(c, "wait(3)", 1000) # break tdi wait + # break python sleep + test_timeout(c, "py('from time import sleep;sleep(3)')", 1500) + if full: # timing too unreliable for standard test + test_timeout(c, "for(;1;) ;", 100) # break tdi inf.loop + # break python inf.loop + test_timeout(c, "py('while 1: pass')", 500) + test_normal(c, "1", timeout=1000) + # TODO: make this work under fc29 (python3.7?) + if sys.version_info < (3, 7): + # verify locks are released + test_normal(c, "py('1')", timeout=1000) + self._doTCLTest('stop server %s' % server) finally: if svr_log: svr_log.close() + self._stop_mdsip((svr, server)) + def timeoutfull(self): self.timeout(full=True) diff --git a/remcam/CamMulti.c b/remcam/CamMulti.c index d3c15d06e6..edb310bf10 100644 --- a/remcam/CamMulti.c +++ b/remcam/CamMulti.c @@ -73,7 +73,7 @@ static void getiosb(int serverid, short *iosb) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && + if (STATUS_OK && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && ans_d.dims[0] == 4) { memcpy(RemCamLastIosb, ans_d.ptr, 8); @@ -88,7 +88,7 @@ static void getdata(int serverid, void *data) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, 0); - if (status & 1 && + if (STATUS_OK && (ans_d.dtype == DTYPE_USHORT || ans_d.dtype == DTYPE_LONG) && ans_d.ptr) memcpy(data, ans_d.ptr, ((ans_d.dtype == DTYPE_USHORT) ? 2 : 4) * ans_d.dims[0]); @@ -120,7 +120,7 @@ static int DoCamMulti(char *routine, char *name, int a, int f, int count, { status = MdsValue(serverid, cmd, &ans_d, 0); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); @@ -143,7 +143,7 @@ EXPORT int CamSetMAXBUF(char *name, int new) char cmd[512]; sprintf(cmd, "CamSetMAXBUF('%s',%d)", name, new); status = MdsValue(serverid, cmd, &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); @@ -165,7 +165,7 @@ EXPORT int CamGetMAXBUF(char *name) char cmd[512]; sprintf(cmd, "CamGetMAXBUF('%s')", name); status = MdsValue(serverid, cmd, &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); diff --git a/remcam/CamSingle.c b/remcam/CamSingle.c index ad1f42cc4c..d58f97fde2 100644 --- a/remcam/CamSingle.c +++ b/remcam/CamSingle.c @@ -69,7 +69,7 @@ MakeSingle(CamPiow, Piow) MakeSingle(CamPioQrepw, PioQrepw) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_iosb", &ans_d, 0); - if (status & 1 && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && + if (STATUS_OK && ans_d.dtype == DTYPE_USHORT && ans_d.ndims == 1 && ans_d.dims[0] == 4) { memcpy(RemCamLastIosb, ans_d.ptr, 8); @@ -84,7 +84,7 @@ static void getdata(int serverid, void *data) int status; struct descrip ans_d = {0, 0, {0}, 0, 0}; status = MdsValue(serverid, "_data", &ans_d, 0); - if (status & 1 && + if (STATUS_OK && (ans_d.dtype == DTYPE_USHORT || ans_d.dtype == DTYPE_LONG) && ans_d.ptr) memcpy(data, ans_d.ptr, (ans_d.dtype == DTYPE_USHORT) ? 2 : 4); free(ans_d.ptr); @@ -115,7 +115,7 @@ static int CamSingle(char *routine, char *name, int a, int f, void *data, { status = MdsValue(serverid, cmd, &ans_d, 0); } - if (status & 1 && ans_d.dtype == DTYPE_LONG && ans_d.ptr) + if (STATUS_OK && ans_d.dtype == DTYPE_LONG && ans_d.ptr) { memcpy(&status, ans_d.ptr, 4); free(ans_d.ptr); diff --git a/roam/roam_gridmap_callout.c b/roam/roam_gridmap_callout.c index 74f89d2ee6..7cc7d49428 100644 --- a/roam/roam_gridmap_callout.c +++ b/roam/roam_gridmap_callout.c @@ -173,7 +173,7 @@ EXPORT globus_result_t roam_gridmap_callout(va_list ap) expression_d.length = strlen(expression); expression_d.pointer = expression; status = TdiExecute(&expression_d, &local_user_d MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { rc = GLOBUS_SUCCESS; local_identity = strncpy((char *)malloc(local_user_d.length + 1), diff --git a/servershr/Client.h b/servershr/Client.h new file mode 100644 index 0000000000..bc7aca0490 --- /dev/null +++ b/servershr/Client.h @@ -0,0 +1,228 @@ +#include + +#include +#include + +#include "Job.h" +#include + +typedef struct _client +{ + struct _client *next; + SOCKET reply_sock; + int conid; + uint32_t addr; + uint16_t port; +} Client; +#ifdef _WIN32 +#define CLIENT_PRI "Client(conid=%d, addr=" IPADDRPRI ", port=%d, reply_sock=%" PRIdPTR ")" +#define CLIENT_VAR(c) (c)->conid, IPADDRVAR(&(c)->addr), (c)->port, (intptr_t)(c)->reply_sock +#else +#define CLIENT_PRI "Client(conid=%d, addr=" IPADDRPRI ", port=%d, reply_sock=%d)" +#define CLIENT_VAR(c) (c)->conid, IPADDRVAR(&(c)->addr), (c)->port, (c)->reply_sock +#endif +static pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t clients_cond = PTHREAD_COND_INITIALIZER; +#define LOCK_CLIENTS MUTEX_LOCK_PUSH(&clients_mutex) +#define UNLOCK_CLIENTS MUTEX_LOCK_POP(&clients_mutex) +#define UNLOCK_CLIENTS_REV MUTEX_UNLOCK_PUSH(&clients_mutex) +#define LOCK_CLIENTS_REV MUTEX_UNLOCK_POP(&clients_mutex) +static Client *Clients = NULL; + +Client *newClient(uint32_t addr, uint16_t port, int conid) +{ + Client *client = (Client *)calloc(1, sizeof(Client)); + client->reply_sock = INVALID_SOCKET; + client->conid = conid; + client->addr = addr; + client->port = port; + return client; +} + +static void Client_push_locked(Client *client) +{ + // should add to tail + if (!Clients) + { + Clients = client; + } + else + { + Client *c = Clients; + while (c->next) + c = c->next; + c->next = client; + } +} + +static inline void Client_push(Client *client) +{ + LOCK_CLIENTS; + Client_push_locked(client); + UNLOCK_CLIENTS; +} + +static inline Client *Client_pop_locked(Client *client) +{ + Client *c = Clients; + Client **p = &Clients; // points to previous->next field + for (; c; p = &c->next, c = c->next) + { + if (c == client) + { + *p = c->next; + pthread_cond_signal(&clients_cond); + return c; + } + } + return NULL; +} + +static inline int Client_free(Client *client, fd_set *fdactive) +{ + if (client) + { + const int conid = client->conid; + MDSDBG(CLIENT_PRI, CLIENT_VAR(client)); + if (client->reply_sock != INVALID_SOCKET) + { + shutdown(client->reply_sock, 2); + close(client->reply_sock); + if (fdactive) + FD_CLR(client->reply_sock, fdactive); + } + DisconnectFromMds(client->conid); + free(client); + return conid; + } + return INVALID_CONNECTION_ID; +} + +static void Client_cleanup_jobs(Client *c, fd_set *fdactive) +{ + + MDSDBG(CLIENT_PRI, CLIENT_VAR(c)); + int conid = Client_free(c, fdactive); + for (;;) + { + Job *j = Job_pop_by_conid(conid); + if (j) + { + Job_callback_done(j, ServerPATH_DOWN, FALSE); + free(j); + } + else + break; + } +} + +static Client *Client_get_by_addr_and_port_locked(uint32_t addr, uint16_t port) +{ + Client *c; + for (c = Clients; c; c = c->next) + { + if (c->addr == addr && c->port == port) + { + break; + } + } + return c; +} + +static void Client_remove_locked(Client *c, fd_set *fdactive) +{ + MDSDBG(CLIENT_PRI " removed", CLIENT_VAR(c)); + c = Client_pop_locked(c); + Client_cleanup_jobs(c, fdactive); +} + +static void Client_remove(Client *client, fd_set *fdactive) +{ + Client *c; + LOCK_CLIENTS; + c = Client_pop_locked(client); + UNLOCK_CLIENTS; + Client_cleanup_jobs(c, fdactive); +} + +static void Client_do_message(Client *c, fd_set *fdactive) +{ + char reply[60]; + char *msg = 0; + int jobid; + int replyType; + int status; + int msglen; + int num; + int nbytes; + nbytes = recv(c->reply_sock, reply, 60, MSG_WAITALL); + if (nbytes != 60) + { + if (nbytes != 0) + MDSWRN(CLIENT_PRI " Invalid read %d/60", CLIENT_VAR(c), nbytes); + else + MDSDBG(CLIENT_PRI " Clint disconnected", CLIENT_VAR(c)); + Client_remove(c, fdactive); + return; + } + num = sscanf(reply, "%d %d %d %d", &jobid, &replyType, &status, &msglen); + if (num != 4) + { + MDSWRN(CLIENT_PRI " Invalid reply format '%-*s'", CLIENT_VAR(c), msglen, reply); + Client_remove(c, fdactive); + return; + } + FREE_ON_EXIT(msg); + if (msglen != 0) + { + msg = (char *)malloc(msglen + 1); + msg[msglen] = 0; + nbytes = recv(c->reply_sock, msg, msglen, MSG_WAITALL); + if (nbytes != msglen) + { + MDSWRN(CLIENT_PRI " Incomplete reply.", CLIENT_VAR(c)); + free(msg); + Client_remove(c, fdactive); + return; + } + } + switch (replyType) + { + case SrvJobFINISHED: + { + Job *j = Job_get_by_jobid(jobid); + if (!j) + j = Job_get_by_jobid(MonJob); + if (j) + { + Job_callback_done(j, status, TRUE); + } + else + { + MDSWRN(CLIENT_PRI " no job to finish", CLIENT_VAR(c)); + } + break; + } + case SrvJobSTARTING: + { + Job *j = Job_get_by_jobid(jobid); + if (!j) + j = Job_get_by_jobid(MonJob); + if (j) + { + Job_callback_before(j); + } + else + { + MDSWRN(CLIENT_PRI " no job to start", CLIENT_VAR(c)); + } + break; + } + case SrvJobCHECKEDIN: + break; + default: + MDSWRN(CLIENT_PRI " Invalid reply type %d.", CLIENT_VAR(c), replyType); + Client_remove(c, fdactive); + } + FREE_NOW(msg); +} \ No newline at end of file diff --git a/servershr/Job.h b/servershr/Job.h new file mode 100644 index 0000000000..a571836b54 --- /dev/null +++ b/servershr/Job.h @@ -0,0 +1,264 @@ +#pragma once +#include + +#include + +typedef struct job +{ + struct job *next; + int jobid; + int conid; + int *retstatus; + pthread_rwlock_t *lock; + void (*callback_done)(); + void (*callback_before)(); + void *callback_param; + pthread_cond_t *cond; + int cond_var; +} Job; +#define JOB_PRI "Job(jobid=%d, conid=%d, cond=%d)" +#define JOB_VAR(j) (j)->jobid, (j)->conid, (j)->cond ? (j)->cond_var : -1 +pthread_mutex_t jobs_mutex = PTHREAD_MUTEX_INITIALIZER; +#define LOCK_JOBS MUTEX_LOCK_PUSH(&jobs_mutex) +#define UNLOCK_JOBS MUTEX_LOCK_POP(&jobs_mutex) +#define UNLOCK_JOBS_REV \ + pthread_mutex_unlock(&jobs_mutex); \ + pthread_cleanup_push((void *)pthread_mutex_lock, &jobs_mutex) +#define LOCK_JOBS_REV pthread_cleanup_pop(1) +static Job *Jobs = NULL; +static int MonJob = -1; + +static Job *newJob(int conid, int *retstatus, pthread_rwlock_t *lock, + void (*callback_done)(void *), + void *callback_param, + void (*callback_before)(void *)) +{ + Job *job = (Job *)calloc(1, sizeof(Job)); + job->retstatus = retstatus; + job->lock = lock; + job->callback_param = callback_param; + job->callback_done = callback_done; + job->callback_before = callback_before; + job->conid = conid; + return job; +} + +static void Job_pop_locked(Job *job) +{ + Job *j; + Job **p = &Jobs; + for (j = Jobs; j; p = &j->next, j = j->next) + { + if (j == job) + { + MDSDBG(JOB_PRI, JOB_VAR(job)); + *p = j->next; + free(j); + break; + } + } +} + +/// only call this when cond is NULL +static void Job_pop(Job *job) +{ + LOCK_JOBS; + Job_pop_locked(job); + UNLOCK_JOBS; +} + +static int Job_register(int *msgid, + int conid, int *retstatus, pthread_rwlock_t *lock, + void *callback_param, + void (*callback_done)(void *), + void (*callback_before)(void *)) +{ + Job *j = newJob(conid, retstatus, lock, callback_param, callback_done, callback_before); + LOCK_JOBS; + static int JobId = 0; + j->jobid = JobId++; + if (msgid) + { + j->cond = malloc(sizeof(pthread_cond_t)); + pthread_cond_init(j->cond, NULL); + *msgid = j->jobid; + MDSDBG(JOB_PRI " sync registered", JOB_VAR(j)); + } + else + { + MDSDBG(JOB_PRI " async registered", JOB_VAR(j)); + } + j->next = Jobs; + Jobs = j; + UNLOCK_JOBS; + return j->jobid; +} + +static void Job_callback_before(Job *job) +{ + MDSDBG(JOB_PRI, JOB_VAR(job)); + void *callback_param; + void (*callback_before)(); + callback_param = job->callback_param; + callback_before = job->callback_before; + if (callback_before) + callback_before(callback_param); +} + +/// returns true if job was popped +static int Job_callback_done(Job *j, int status, int remove) +{ + MDSDBG(JOB_PRI " status=%d, remove=%d", JOB_VAR(j), status, remove); + void (*callback_done)(void *); + const int is_mon = j->jobid == MonJob; + if (j->lock) + pthread_rwlock_wrlock(j->lock); + if (j->retstatus) + *j->retstatus = status; + callback_done = j->callback_done; + if (!is_mon) + j->callback_done = NULL; + if (j->lock) + pthread_rwlock_unlock(j->lock); + if (callback_done) + callback_done(j->callback_param); + /**** If job has a condition, RemoveJob will not remove it. ***/ + if (remove && !is_mon) + { + int has_cond; + LOCK_JOBS; + if ((has_cond = !!j->cond)) + { + j->cond_var = 1; + pthread_cond_broadcast(j->cond); + } + UNLOCK_JOBS; + if (!has_cond) + { + Job_pop(j); + return B_TRUE; + } + } + return B_FALSE; +} + +/// only call this when cond is NULL + +static Job *Job_pop_by_conid(int conid) +{ + Job *j; + LOCK_JOBS; + Job **p = &Jobs; + for (j = Jobs; j; p = &j->next, j = j->next) + { + if (j->conid == conid) + { + MDSDBG(JOB_PRI, JOB_VAR(j)); + *p = j->next; + break; + } + } + UNLOCK_JOBS; + return j; +} + +static inline Job *Job_get_by_jobid_locked(int jobid) +{ + Job *j; + for (j = Jobs; j; j = j->next) + { + if (j->jobid == jobid) + { + break; + } + } + return j; +} + +static inline Job *Job_get_by_jobid(int jobid) +{ + Job *job; + LOCK_JOBS; + job = Job_get_by_jobid_locked(jobid); + UNLOCK_JOBS; + return job; +} + +static void Job_abandon_locked(Job *job) +{ + if (job && job->cond) + { + pthread_cond_destroy(job->cond); + free(job->cond); + job->cond = NULL; + MDSDBG(JOB_PRI " sync abandoned!", JOB_VAR(job)); + } +} + +static inline void Job_wait_and_pop_locked(Job *job) +{ + pthread_cleanup_push((void *)Job_abandon_locked, (void *)job); + if (!job->cond_var) + { + pthread_cond_wait(job->cond, &jobs_mutex); + } + pthread_cond_destroy(job->cond); + free(job->cond); + job->cond = NULL; + Job_pop_locked(job); + MDSDBG(JOB_PRI " sync done", JOB_VAR(job)); + pthread_cleanup_pop(0); +} + +static inline int Job_wait_and_pop_by_jobid(int jobid) +{ + int err; + LOCK_JOBS; + Job *job = Job_get_by_jobid_locked(jobid); + if (job && job->cond) + { + MDSDBG(JOB_PRI " sync pending", JOB_VAR(job)); + Job_wait_and_pop_locked(job); + err = B_FALSE; + } + else + { + err = B_TRUE; + } + UNLOCK_JOBS; + return err; +} + +static Job *Job_pop_by_jobid(int jobid) +{ + Job *j; + LOCK_JOBS; + Job **p = &Jobs; + for (j = Jobs; j; p = &j->next, j = j->next) + { + if (j->jobid == jobid) + { + MDSDBG(JOB_PRI, JOB_VAR(j)); + *p = j->next; + break; + } + } + UNLOCK_JOBS; + return j; +} + +static void Job_cleanup(int status, int jobid) +{ + Job *j = Job_pop_by_jobid(jobid); + if (!j) + return; + const int conid = j->conid; + DisconnectFromMds(conid); + do + { + MDSDBG(JOB_PRI " done", JOB_VAR(j)); + Job_callback_done(j, status, FALSE); + free(j); + j = Job_pop_by_conid(conid); + } while (j); +} diff --git a/servershr/Makefile.in b/servershr/Makefile.in index 21b721a9a5..f161e7de48 100644 --- a/servershr/Makefile.in +++ b/servershr/Makefile.in @@ -18,6 +18,8 @@ clean: @ $(RM) @MAKESHLIBDIR@@LIBPRE@MdsServerShr@SHARETYPE@ $(IMPLIB) @ $(RM) @MAKELIBDIR@@LIBPRE@MdsServerShr.a +$(OBJECTS): servershrp.h +ServerSendMessage.o: Job.h Client.h depend: @makedepend -- $(CFLAGS) -- $(SOURCES) diff --git a/servershr/ServerBuildDispatchTable.c b/servershr/ServerBuildDispatchTable.c index 2665294b59..8c52e02fd8 100644 --- a/servershr/ServerBuildDispatchTable.c +++ b/servershr/ServerBuildDispatchTable.c @@ -73,10 +73,7 @@ extern int TdiGetLong(); extern int TdiData(); extern int TdiGetNci(); -static int num_actions; -static ActionInfo *actions; - -static int CompareActions(ActionInfo *a, ActionInfo *b) +static int compare_actions(ActionInfo *a, ActionInfo *b) { return a->on == b->on ? (a->phase == b->phase ? a->sequence - b->sequence : a->phase - b->phase) @@ -85,33 +82,40 @@ static int CompareActions(ActionInfo *a, ActionInfo *b) #define MAX_ACTIONS 10000 -static int ifAddReference(int idx, int *nid) +typedef struct ctx_s +{ + ActionInfo *actions; + int num_actions; + int idx; +} ctx_t; + +static int if_add_reference(int *nid, const ctx_t *const ctx) { int i, j; - for (i = 0; i < num_actions; i++) + for (i = 0; i < ctx->num_actions; i++) { - if (actions[i].nid == *nid) + if (ctx->actions[i].nid == *nid) { - if (actions[i].num_references == 0) - actions[i].referenced_by = (int *)malloc(sizeof(int)); + if (ctx->actions[i].num_references == 0) + ctx->actions[i].referenced_by = (int *)malloc(sizeof(int)); else { - for (j = 0; j < actions[i].num_references; j++) - if (actions[i].referenced_by[j] == idx) + for (j = 0; j < ctx->actions[i].num_references; j++) + if (ctx->actions[i].referenced_by[j] == ctx->idx) return B_TRUE; - actions[i].referenced_by = - (int *)realloc((char *)actions[i].referenced_by, - sizeof(int) * (actions[i].num_references + 1)); + ctx->actions[i].referenced_by = + (int *)realloc((char *)ctx->actions[i].referenced_by, + sizeof(int) * (ctx->actions[i].num_references + 1)); } - actions[i].referenced_by[actions[i].num_references] = idx; - actions[i].num_references++; + ctx->actions[i].referenced_by[ctx->actions[i].num_references] = ctx->idx; + ctx->actions[i].num_references++; return B_TRUE; } } return B_FALSE; } -static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) +static int fixup_nid(int *nid, const ctx_t *const ctx, mdsdsc_d_t *path_out) { INIT_STATUS; static DESCRIPTOR(dtype_str, "DTYPE"); @@ -120,16 +124,16 @@ static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) DESCRIPTOR_NID(niddsc, 0); niddsc.pointer = (char *)nid; status = TdiGetNci(&niddsc, &dtype_str, &dtype_dsc MDS_END_ARG); - if (STATUS_OK && dtype == DTYPE_ACTION && ifAddReference(idx, nid)) + if (STATUS_OK && dtype == DTYPE_ACTION && if_add_reference(nid, ctx)) { char ident[64]; char tmp[64]; - struct descriptor ident_dsc = {0, DTYPE_T, CLASS_S, 0}; + mdsdsc_t ident_dsc = {0, DTYPE_T, CLASS_S, 0}; EMPTYXD(xd); sprintf(ident, "_ACTION_%08X", *nid); ident_dsc.length = strlen(ident); ident_dsc.pointer = ident; - StrCopyDx((struct descriptor *)path_out, (struct descriptor *)&ident_dsc); + StrCopyDx((mdsdsc_t *)path_out, (mdsdsc_t *)&ident_dsc); strcpy(tmp, ident); strcpy(ident, "public "); strcat(ident, tmp); @@ -142,59 +146,57 @@ static int fixup_nid(int *nid, int idx, struct descriptor_d *path_out) return B_FALSE; } -static int fixup_path(struct descriptor *path_in, int idx, - struct descriptor_d *path_out) +inline static int fixup_path(mdsdsc_t *path_in, const ctx_t *const ctx, mdsdsc_d_t *path_out) { - char *path = strncpy((char *)malloc(path_in->length + 1), path_in->pointer, - path_in->length); + char *path = strncpy( + (char *)malloc(path_in->length + 1), path_in->pointer, path_in->length); int nid; int flag = B_FALSE; path[path_in->length] = 0; if (IS_OK(TreeFindNode(path, &nid))) - flag = fixup_nid(&nid, idx, path_out); + flag = fixup_nid(&nid, ctx, path_out); free(path); return flag; } -static int make_idents(struct descriptor *path_in, - int idx __attribute__((unused)), - struct descriptor *path_out __attribute__((unused))) +inline static int make_idents(mdsdsc_t *path_in, + int idx __attribute__((unused)), + mdsdsc_t *path_out __attribute__((unused))) { if (path_in && path_in->pointer && path_in->pointer[0] == '_') path_in->dtype = DTYPE_IDENT; return B_FALSE; } -static void LinkConditions() +inline static void link_conditions(ctx_t *const ctx) { + // (*fixup_nid)(in.pointer, fixup_nid_arg, &path)) int i; - for (i = 0; i < num_actions; i++) + for (i = 0; i < ctx->num_actions; i++) { - if (actions[i].condition) + if (ctx->actions[i].condition) { EMPTYXD(xd); - MdsCopyDxXdZ(actions[i].condition, &xd, 0, fixup_nid, i + (char *)0, - fixup_path, i + (char *)0); - MdsCopyDxXdZ((struct descriptor *)&xd, - (struct descriptor_xd *)actions[i].condition, 0, 0, 0, - make_idents, i + (char *)0); + ctx->idx = i; + MdsCopyDxXdZ(ctx->actions[i].condition, &xd, 0, + fixup_nid, ctx, fixup_path, ctx); + MdsCopyDxXdZ((mdsdsc_t *)&xd, (mdsdsc_xd_t *)ctx->actions[i].condition, + 0, 0, 0, make_idents, (void *)(intptr_t)i); MdsFree1Dx(&xd, 0); } } } +#define ALL_NODES "***" EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, void **table) { if (*table) ServerFreeDispatchTable(*table); DispatchTable **table_ptr = (DispatchTable **)table; - void *ctx = 0; + void *fnwctx = 0; int i; - static char *allnodes = "***"; - static DESCRIPTOR(varnames, "_ACTION_*"); - static struct descriptor_d varnames_d = {0, DTYPE_T, CLASS_D, 0}; - char *nodespec = wildcard ? wildcard : allnodes; + char *nodespec = wildcard ? wildcard : ALL_NODES; int mask = 1 << TreeUSAGE_ACTION; int status = 1; int *nids; @@ -202,9 +204,11 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, char tree[12]; int shot = -1; char *cptr; - static DBI_ITM itmlst[] = {{sizeof(tree), DbiNAME, 0, 0}, - {sizeof(shot), DbiSHOTID, 0, 0}, - {0, 0, 0, 0}}; + DBI_ITM itmlst[] = { + {sizeof(tree), DbiNAME, 0, 0}, + {sizeof(shot), DbiSHOTID, 0, 0}, + {0, 0, 0, 0}, + }; itmlst[0].pointer = &tree; itmlst[1].pointer = &shot; memset(tree, ' ', sizeof(tree)); @@ -218,37 +222,33 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, if (shot == -1) return ServerINVSHOT; nids = (int *)malloc(MAX_ACTIONS * sizeof(int)); - num_actions = 0; - if (!varnames_d.length) - StrCopyDx((struct descriptor *)&varnames_d, (struct descriptor *)&varnames); - while ((TreeFindNodeWild(nodespec, &nids[num_actions], &ctx, mask) & 1) && - (num_actions < MAX_ACTIONS)) - num_actions++; - TreeFindNodeEnd(&ctx); - if (num_actions) + ctx_t ctx = {NULL, 0, 0}; + while ((TreeFindNodeWild(nodespec, &nids[ctx.num_actions], &fnwctx, mask) & 1) && + (ctx.num_actions < MAX_ACTIONS)) + ctx.num_actions++; + TreeFindNodeEnd(&fnwctx); + if (ctx.num_actions) { - static int zero = 0; - int table_size = - sizeof(DispatchTable) + (num_actions - 1) * sizeof(ActionInfo); + int table_size = sizeof(DispatchTable) + (ctx.num_actions - 1) * sizeof(ActionInfo); *table_ptr = (DispatchTable *)calloc(1, table_size); - actions = (*table_ptr)->actions; + ctx.actions = (*table_ptr)->actions; (*table_ptr)->shot = shot; strcpy((*table_ptr)->tree, tree); - for (i = 0, nidptr = nids; i < num_actions; nidptr++, i++) + EMPTYXD(xd); + for (i = 0, nidptr = nids; i < ctx.num_actions; nidptr++, i++) { - struct descriptor_d event_name = {0, DTYPE_T, CLASS_D, 0}; - struct descriptor niddsc = {4, DTYPE_NID, CLASS_S, 0}; - static EMPTYXD(xd); + mdsdsc_d_t event_name = {0, DTYPE_T, CLASS_D, 0}; + mdsdsc_t niddsc = {4, DTYPE_NID, CLASS_S, 0}; niddsc.pointer = (char *)nidptr; - actions[i].nid = *nidptr; - actions[i].on = TreeIsOn(*nidptr) & 1; - actions[i].num_references = 0; - actions[i].referenced_by = 0; - actions[i].status = 0; - actions[i].dispatched = 0; - actions[i].closed = 0; - actions[i].condition = 0; - if (actions[i].on) + ctx.actions[i].nid = *nidptr; + ctx.actions[i].on = TreeIsOn(*nidptr) & 1; + ctx.actions[i].num_references = 0; + ctx.actions[i].referenced_by = 0; + ctx.actions[i].status = 0; + ctx.actions[i].dispatched = 0; + ctx.actions[i].closed = 0; + ctx.actions[i].condition = 0; + if (ctx.actions[i].on) { if (TdiDispatchOf(&niddsc, &xd MDS_END_ARG) & 1) { @@ -256,54 +256,57 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, (struct descriptor_dispatch *)xd.pointer; if (dispatch->pointer && (dispatch->pointer[0] == TreeSCHED_SEQ)) { - struct descriptor server = {sizeof(actions->server), DTYPE_T, - CLASS_S, 0}; - static DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); - struct descriptor phase_d = {sizeof(int), DTYPE_L, CLASS_S, 0}; - server.pointer = actions[i].server; - phase_d.pointer = (char *)&actions[i].phase; - if (!(TdiExecute(&phase_lookup, dispatch->phase, - &phase_d MDS_END_ARG) & - 1)) - actions[i].phase = 0x10000001; - if (!(TdiGetLong(dispatch->when, &actions[i].sequence) & 1)) + mdsdsc_t server = {sizeof(ctx.actions->server), DTYPE_T, + CLASS_S, 0}; + DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); + mdsdsc_t phase_d = {sizeof(int), DTYPE_L, CLASS_S, 0}; + server.pointer = ctx.actions[i].server; + phase_d.pointer = (char *)&ctx.actions[i].phase; + if (IS_NOT_OK(TdiExecute(&phase_lookup, dispatch->phase, &phase_d MDS_END_ARG))) + ctx.actions[i].phase = 0x10000001; + if (IS_NOT_OK(TdiGetLong(dispatch->when, &ctx.actions[i].sequence))) { - static EMPTYXD(emptyxd); - actions[i].sequence = 0; - actions[i].condition = (struct descriptor *)memcpy( + static const EMPTYXD(emptyxd); + ctx.actions[i].sequence = 0; + ctx.actions[i].condition = (mdsdsc_t *)memcpy( malloc(sizeof(emptyxd)), &emptyxd, sizeof(emptyxd)); - MdsCopyDxXd((struct descriptor *)dispatch->when, - (struct descriptor_xd *)actions[i].condition); - actions[i].path = TreeGetMinimumPath(&zero, actions[i].nid); + MdsCopyDxXd((mdsdsc_t *)dispatch->when, + (mdsdsc_xd_t *)ctx.actions[i].condition); + int zero = 0; + ctx.actions[i].path = TreeGetMinimumPath(&zero, ctx.actions[i].nid); } - else if (actions[i].sequence <= 0) - actions[i].phase = 0x10000002; + else if (ctx.actions[i].sequence <= 0) + ctx.actions[i].phase = 0x10000002; else - actions[i].path = TreeGetMinimumPath(&zero, actions[i].nid); - if (!(TdiData(dispatch->ident, &server MDS_END_ARG) & 1)) - actions[i].phase = 0x10000003; + { + int zero = 0; + ctx.actions[i].path = TreeGetMinimumPath(&zero, ctx.actions[i].nid); + } + if (IS_NOT_OK(TdiData(dispatch->ident, &server MDS_END_ARG))) + ctx.actions[i].phase = 0x10000003; } else - actions[i].phase = 0x10000004; + ctx.actions[i].phase = 0x10000004; if (TdiData(dispatch->completion, &event_name MDS_END_ARG) & 1 && event_name.length) { - actions[i].event = strncpy((char *)malloc(event_name.length + 1), - event_name.pointer, event_name.length); - actions[i].event[event_name.length] = 0; + ctx.actions[i].event = strncpy((char *)malloc(event_name.length + 1), + event_name.pointer, event_name.length); + ctx.actions[i].event[event_name.length] = 0; StrFree1Dx(&event_name); } } else - actions[i].phase = 0x10000005; + ctx.actions[i].phase = 0x10000005; } } - qsort(actions, num_actions, sizeof(ActionInfo), - (int (*)(const void *, const void *))CompareActions); - for (i = 0; i < num_actions && actions[i].on; i++) + MdsFree1Dx(&xd, NULL); + qsort(ctx.actions, ctx.num_actions, sizeof(ActionInfo), + (int (*)(const void *, const void *))compare_actions); + for (i = 0; i < ctx.num_actions && ctx.actions[i].on; i++) ; (*table_ptr)->num = i; - LinkConditions(); + link_conditions(&ctx); if (monitor_name) { char tree[13]; @@ -316,21 +319,21 @@ EXPORT int ServerBuildDispatchTable(char *wildcard, char *monitor_name, tree[i] = 0; char *server = ""; #define SKIP_OTHERS -#define SEND(i, mode) \ - ServerSendMonitor(monitor_name, tree, (*table_ptr)->shot, actions[i].phase, \ - actions[i].nid, actions[i].on, mode, server, \ - actions[i].status) +#define SEND(i, mode) \ + ServerSendMonitor(monitor_name, tree, (*table_ptr)->shot, ctx.actions[i].phase, \ + ctx.actions[i].nid, ctx.actions[i].on, mode, server, \ + ctx.actions[i].status) if (IS_OK(SEND(0, MonitorBuildBegin))) { // send begin #ifdef SKIP_OTHERS - if (num_actions > 1) + if (ctx.num_actions > 1) #else for (i = 1; i < num_actions - 1; i++) IS_NOT_OK(SEND(i, MonitorBuild)) break; // send others if (i == num_actions - 1) #endif - SEND(num_actions - 1, MonitorBuildEnd); // send last + SEND(ctx.num_actions - 1, MonitorBuildEnd); // send last } } } diff --git a/servershr/ServerDispatchClose.c b/servershr/ServerDispatchClose.c index b52570c966..3dfafffdc4 100644 --- a/servershr/ServerDispatchClose.c +++ b/servershr/ServerDispatchClose.c @@ -63,12 +63,12 @@ static char *Server(char *out, char *srv) out[i] = 0; return out; } -extern void serverDisarmDispatchTable(void *vtable); +extern void server_dispatch_table_disarm(void *vtable); EXPORT int ServerDispatchClose(void *vtable) { if (!vtable) return MDSplusSUCCESS; - serverDisarmDispatchTable(vtable); + server_dispatch_table_disarm(vtable); char server[33]; DispatchTable *table = (DispatchTable *)vtable; ActionInfo *action = table->actions; diff --git a/servershr/ServerDispatchPhase.c b/servershr/ServerDispatchPhase.c index 69ff1baebf..df554c8e25 100644 --- a/servershr/ServerDispatchPhase.c +++ b/servershr/ServerDispatchPhase.c @@ -62,7 +62,6 @@ int SERVER$DISPATCH_PHASE(int efn, DispatchTable *table, struct descriptor #include #include -#include #include #include #include @@ -76,6 +75,8 @@ int SERVER$DISPATCH_PHASE(int efn, DispatchTable *table, struct descriptor #include #include #include "servershrp.h" +//#define DEBUG +#include extern int TdiCompletionOf(); extern int TdiExecute(); @@ -83,32 +84,19 @@ extern int TdiErrorlogsOf(); extern int TdiGetLong(); extern int ProgLoc; -void SendMonitor(int mode, int idx); - -STATIC_ROUTINE void Dispatch(int idx); -STATIC_ROUTINE void DoSendMonitor(int mode, int idx); -STATIC_ROUTINE void ActionDone(int idx); -STATIC_ROUTINE void DoActionDone(int idx); -STATIC_ROUTINE void Before(int idx); -STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c); -STATIC_ROUTINE void AbortRange(int s, int e); -STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g); -STATIC_ROUTINE int NoOutstandingActions(int s, int e); -STATIC_ROUTINE void RecordStatus(int s, int e); -STATIC_ROUTINE void Dispatch(int i); -STATIC_ROUTINE void WaitForActions(int conditionals, int first_g, int last_g, - int first_c, int last_c); - -// STATIC_CONSTANT const int zero = 0; - -typedef struct _complete -{ - struct _complete *next; - int idx; -} Complete; - -STATIC_THREADSAFE Complete *CompletedQueueHead = NULL; -STATIC_THREADSAFE Complete *CompletedQueueTail = NULL; +static void dispatch(int idx); +static void send_monitor(int mode, int idx); +static void action_done(intptr_t idx); +static void action_done_action_locked(int idx); +static void action_done_action_unlocked(int idx); +static void before(int idx); +static inline void set_action_ranges(int phase, int *first_c, int *last_c); +static void abort_range(int s, int e); +static void set_group(int sync, int first_g, int *last_g); +static int check_actions_done(int s, int e); +static void record_status(int s, int e); +static void wait_for_actions(int conditionals, int first_g, int last_g, + int first_c, int last_c); typedef struct _send_monitor { @@ -117,16 +105,16 @@ typedef struct _send_monitor int mode; } SendMonitorInfo; -STATIC_THREADSAFE SendMonitorInfo *SendMonitorQueueHead = NULL; -STATIC_THREADSAFE SendMonitorInfo *SendMonitorQueueTail = NULL; +static SendMonitorInfo *SendMonitorQueueHead = NULL; +static SendMonitorInfo *SendMonitorQueueTail = NULL; -STATIC_THREADSAFE DispatchTable *table; -STATIC_THREADSAFE int noact; -STATIC_THREADSAFE void (*Output)(); -STATIC_THREADSAFE int MonitorOn = 0; -STATIC_THREADSAFE char *Monitor = 0; -STATIC_THREADSAFE int first_s; -STATIC_THREADSAFE int last_s; +static DispatchTable *table; +static int noact; +static void (*Output)(); +static int MonitorOn = 0; +static char *Monitor = 0; +static int first_s; +static int last_s; static int AbortInProgress; static pthread_mutex_t abortinprogress_mutex = PTHREAD_MUTEX_INITIALIZER; @@ -139,7 +127,7 @@ static inline int setAbortInProgress(int val_in) pthread_mutex_unlock(&abortinprogress_mutex); return val_out; } -static inline int isAbortInProgress() +static inline int is_abort_in_progress() { int val; pthread_mutex_lock(&abortinprogress_mutex); @@ -148,55 +136,63 @@ static inline int isAbortInProgress() return val; } -STATIC_THREADSAFE Condition JobWaitC = CONDITION_INITIALIZER; -STATIC_THREADSAFE Condition SendMonitorC = CONDITION_INITIALIZER; -STATIC_THREADSAFE Condition CompletedC = CONDITION_INITIALIZER; +static Condition JobWaitC = CONDITION_INITIALIZER; +static Condition SendMonitorC = CONDITION_INITIALIZER; static pthread_mutex_t send_monitor_queue_mutex = PTHREAD_MUTEX_INITIALIZER; -#define MONITOR_QUEUE_LOCK \ - pthread_mutex_lock(&send_monitor_queue_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &send_monitor_queue_mutex) -#define MONITOR_QUEUE_UNLOCK pthread_cleanup_pop(1) - -STATIC_THREADSAFE pthread_mutex_t completed_queue_mutex = - PTHREAD_MUTEX_INITIALIZER; +#define MONITOR_QUEUE_LOCK MUTEX_LOCK_PUSH(&send_monitor_queue_mutex) +#define MONITOR_QUEUE_UNLOCK MUTEX_LOCK_POP(&send_monitor_queue_mutex) -STATIC_THREADSAFE pthread_rwlock_t table_lock = PTHREAD_RWLOCK_INITIALIZER; +static pthread_rwlock_t table_lock = PTHREAD_RWLOCK_INITIALIZER; #define WRLOCK_TABLE pthread_rwlock_wrlock(&table_lock) #define RDLOCK_TABLE pthread_rwlock_rdlock(&table_lock) #define UNLOCK_TABLE pthread_rwlock_unlock(&table_lock) #define ACTION_LOCK(idx) table->actions[idx].lock -#define DEBUG_LOCK( \ - idx, info, typ, \ - b) // fprintf(stderr,"%d: %-10s %s[%d,%d]%c\n",idx,#info,#typ,ACTION_LOCK(idx).__data.__readers,ACTION_LOCK(idx).__data.__writers,b) -#define XLOCK_ACTION(idx, info, typ) \ - do \ - { \ - DEBUG_LOCK(idx, info, typ, '?'); \ - pthread_rwlock_##typ##lock(&ACTION_LOCK(idx)); \ - DEBUG_LOCK(idx, info, typ, '!'); \ +#ifdef DEBUG_ACTION +#define ACTION_DBG(idx, info, typ, b) \ + fprintf(stderr, "%d: %-10s %s[%d,%d]%c\n", idx, #info, #typ, \ + ACTION_LOCK(idx).__data.__readers, ACTION_LOCK(idx).__data.__writers, b) +#else +#define ACTION_DBG(idx, info, typ, b) \ + do \ + { \ } while (0) +#endif +#define XLOCK_ACTION(idx, info, typ) \ + ( \ + { \ + ACTION_DBG(idx, info, typ, '?'); \ + int r = pthread_rwlock_##typ##lock(&ACTION_LOCK(idx)); \ + ACTION_DBG(idx, info, typ, '!'); \ + r; \ + }) #define WRLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, wr) #define RDLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, rd) #define UNLOCK_ACTION(idx, info) XLOCK_ACTION(idx, info, un) -//#define DEBUG -#define PRINT_ACTIONS \ - { \ - int sti; \ - for (sti = 0; sti < table->num; sti++) \ - { \ - RDLOCK_ACTION(sti, debug); \ - fprintf(stderr, "Action(%d): %s, p=%d(%d), %d, %d\n", sti, \ - table->actions[sti].path, table->actions[sti].phase, \ - table->actions[sti].condition != NULL, \ - table->actions[sti].dispatched, table->actions[sti].done); \ - UNLOCK_ACTION(sti, debug); \ - } \ +#define ACTION_PRI "Action(%d, path=%s, phase=%d state=%c%c%c%c" +#define ACTION_VAR(i) \ + i, \ + table->actions[i].path, \ + table->actions[i].phase, \ + table->actions[i].condition ? 'C' : 'c', \ + table->actions[i].dispatched ? 'D' : 'd', \ + table->actions[i].doing ? 'S' : 's', \ + table->actions[i].done ? 'F' : 'f' +#define PRINT_ACTIONS \ + { \ + int i; \ + for (i = 0; i < table->num; i++) \ + { \ + RDLOCK_ACTION(i, debug); \ + fprintf(stderr, ACTION_PRI "\n", ACTION_VAR(i)); \ + UNLOCK_ACTION(i, debug); \ + } \ } //" -STATIC_ROUTINE char *Server(char *out, char *srv) + +static char *Server(char *out, char *srv) { int i; for (i = 0; i < 32; i++) @@ -205,124 +201,7 @@ STATIC_ROUTINE char *Server(char *out, char *srv) return out; } -void SendMonitor(int mode, int idx) -{ - if (MonitorOn) - { - char tree[13]; - char *cptr; - int i; - RDLOCK_TABLE; - if (table) - { // if no table prevent seg fault - for (i = 0, cptr = table->tree; i < 12; i++) - if (cptr[i] == (char)32) - break; - else - tree[i] = cptr[i]; - tree[i] = 0; - ActionInfo *actions = table->actions; - RDLOCK_ACTION(idx, sm); - int on = actions[idx].on; - char server[33]; - for (i = 0, cptr = actions[idx].server; i < 32 && (cptr[i] != ' '); i++) - server[i] = cptr[i]; - server[i] = 0; - MonitorOn = ServerSendMonitor(Monitor, tree, table->shot, - actions[idx].phase, actions[idx].nid, on, - mode, server, actions[idx].status); - UNLOCK_ACTION(idx, sm); - } - UNLOCK_TABLE; - } -} - -STATIC_ROUTINE void ActionDone(int idx) -{ - int i; - char logmsg[1024]; - if (idx >= 0) - { - RDLOCK_TABLE; - if (table) - { // if no table prevent seg fault - RDLOCK_ACTION(idx, ad); - ActionInfo *actions = table->actions; - if (actions[idx].event) - MDSEvent(actions[idx].event, sizeof(int), (char *)&table->shot); - DoSendMonitor(MonitorDone, idx); - if (Output) - { - char now[32]; - Now32(now); - if (IS_OK(actions[idx].status)) - sprintf(logmsg, "%s, Action %s completed", now, actions[idx].path); - else - { - char *emsg = MdsGetMsg(actions[idx].status); - sprintf(logmsg, "%s, Action %s failed, %s", now, actions[idx].path, - emsg); - } - (*Output)(logmsg); - } - if (!isAbortInProgress()) - { - EMPTYXD(xd); - char expression[60]; - struct descriptor expression_d = {0, DTYPE_T, CLASS_S, 0}; - expression_d.pointer = expression; - expression_d.length = sprintf(expression, "PUBLIC _ACTION_%08X = %d", - actions[idx].nid, actions[idx].status); - TdiExecute(&expression_d, &xd MDS_END_ARG); - MdsFree1Dx(&xd, NULL); - for (i = 0; i < actions[idx].num_references; i++) - { - int dstat; - int doit; - int cidx = actions[idx].referenced_by[i]; - RDLOCK_ACTION(cidx, adl); - if (!actions[cidx].done) - { - if (IS_OK(dstat = TdiGetLong(actions[cidx].condition, &doit))) - { - UNLOCK_ACTION(cidx, ad_ftt); - if (doit) - Dispatch(cidx); - else - { - WRLOCK_ACTION(cidx, ad_ftte); - actions[cidx].status = ServerNOT_DISPATCHED; - UNLOCK_ACTION(cidx, ad_ftte); - DoActionDone(cidx); - } - } - else if (dstat != TdiUNKNOWN_VAR) - { - UNLOCK_ACTION(cidx, ad_fte); - WRLOCK_ACTION(cidx, ad_fte); - actions[cidx].status = ServerINVALID_DEPENDENCY; - UNLOCK_ACTION(cidx, ad_fte); - DoActionDone(cidx); - } - } - else - UNLOCK_ACTION(cidx, ad_fe); - } - } - UNLOCK_ACTION(idx, ad); - WRLOCK_ACTION(idx, ad); - { - actions[idx].done = 1; - actions[idx].recorded = 0; - } - UNLOCK_ACTION(idx, ad); - } - UNLOCK_TABLE; - } - CONDITION_SET(&JobWaitC); -} - -STATIC_ROUTINE void Before(int idx) +static void before(int idx) { RDLOCK_TABLE; if (table) @@ -332,7 +211,7 @@ STATIC_ROUTINE void Before(int idx) ActionInfo *actions = table->actions; char logmsg[1024]; actions[idx].doing = 1; - DoSendMonitor(MonitorDoing, idx); + send_monitor(MonitorDoing, idx); if (Output) { char server[33]; @@ -368,7 +247,8 @@ STATIC_ROUTINE void Before(int idx) if (i < END) \ UNLOCK_ACTION(i, fnae_##info); -STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c) +/// update range of conditional actions +static inline void set_action_ranges(int phase, int *first_c, int *last_c) { int i; RDLOCK_TABLE; @@ -416,13 +296,10 @@ STATIC_ROUTINE void SetActionRanges(int phase, int *first_c, int *last_c) *last_c = last_s = 0; } UNLOCK_TABLE; -#ifdef DEBUG - fprintf(stderr, "ActionRange: %d,%d,%d,%d\n", *first_c, *last_c, first_s, - last_s); -#endif + MDSDBG("range=[%d, %d], cond=[%d, %d]", first_s, last_s, *first_c, *last_c); } -STATIC_ROUTINE void AbortRange(int s, int e) +static void abort_range(int s, int e) { int i; RDLOCK_TABLE; @@ -443,7 +320,7 @@ STATIC_ROUTINE void AbortRange(int s, int e) UNLOCK_TABLE; } -STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) +static void set_group(int sync, int first_g, int *last_g) { if (first_g == last_s) { @@ -460,8 +337,7 @@ STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) RDLOCK_ACTION(first_g, sg); group = actions[first_g].sequence / sync; UNLOCK_ACTION(first_g, sg); - FIND_NEXT_ACTION(first_g + 1, last_s, (actions[i].sequence / sync) != group, - sg); + FIND_NEXT_ACTION(first_g + 1, last_s, (actions[i].sequence / sync) != group, sg); FIND_NEXT_ACTION_END(last_s, sg); } else @@ -472,19 +348,18 @@ STATIC_ROUTINE void SetGroup(int sync, int first_g, int *last_g) *last_g = i; } -STATIC_ROUTINE int NoOutstandingActions(const int s, const int e) +/// return true if range is complete +static int check_actions_done(const int s, const int e) { int i; ActionInfo *actions = table->actions; FIND_NEXT_ACTION(s, e, actions[i].dispatched && !actions[i].done, noa); FIND_NEXT_ACTION_END(e, noa); -#ifdef DEBUG - fprintf(stderr, "%d -> %d==%d\n", s, i, e); -#endif + MDSDBG("range=[%d, %d], current=%d", s, e, i); return i >= e; } -STATIC_ROUTINE void RecordStatus(int s, int e) +static void record_status(int s, int e) { int i; RDLOCK_TABLE; @@ -517,22 +392,27 @@ STATIC_ROUTINE void RecordStatus(int s, int e) UNLOCK_TABLE; } -STATIC_ROUTINE void WaitForActions(int all, int first_g, int last_g, - int first_c, int last_c) +static void wait_for_actions(int all, int first_g, int last_g, + int first_c, int last_c) { int c_status = C_OK; _CONDITION_LOCK(&JobWaitC); - struct timespec tp; - clock_gettime(CLOCK_REALTIME, &tp); - int g, c = 1; - while ((c_status == ETIMEDOUT || c_status == C_OK) && !isAbortInProgress() && - (g = !NoOutstandingActions(first_g, last_g) || - (all && (c = !NoOutstandingActions(first_c, last_c))))) + int group_done, cond_done = -1; + while ((c_status == ETIMEDOUT || c_status == C_OK) && !is_abort_in_progress() && + !(group_done = check_actions_done(first_g, last_g) && + (!all || (cond_done = check_actions_done(first_c, last_c))))) { + struct timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + if (c_status == C_OK) + { + MDSDBG("group_done=%c, cond_done=%c", + group_done ? 'y' : 'n', + cond_done < 0 ? '?' : (cond_done ? 'y' : 'n')); #ifdef DEBUG - fprintf(stderr, "%lu: %d, %d\n", (long unsigned int)tp.tv_sec, g, c); - PRINT_ACTIONS; + PRINT_ACTIONS; #endif + } tp.tv_sec++; c_status = pthread_cond_timedwait(&JobWaitC.cond, &JobWaitC.mutex, &tp); #if defined(_DECTHREADS_) && (_DECTHREADS_ == 1) @@ -543,7 +423,7 @@ STATIC_ROUTINE void WaitForActions(int all, int first_g, int last_g, _CONDITION_UNLOCK(&JobWaitC); } -STATIC_ROUTINE char *DetailProc(int full) +static char *detail_proc(int full) { char *msg; RDLOCK_TABLE; @@ -592,7 +472,7 @@ STATIC_ROUTINE char *DetailProc(int full) return msg; } -static inline void setMonitor(const char *monitor) +static inline void set_monitor(const char *monitor) { MONITOR_QUEUE_LOCK; if (monitor) @@ -627,7 +507,7 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, int phase; int first_g, last_g = 0, first_c, last_c; DESCRIPTOR_LONG(phase_d, 0); - STATIC_CONSTANT DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); + static DESCRIPTOR(phase_lookup, "PHASE_NUMBER_LOOKUP($)"); struct descriptor phasenam_d = {0, DTYPE_T, CLASS_S, 0}; phase_d.pointer = (char *)&phase; Output = output_rtn; @@ -640,33 +520,33 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, ProgLoc = 6006; if (STATUS_OK && (phase > 0)) { - setMonitor(monitor); + set_monitor(monitor); ProgLoc = 6007; - SetActionRanges(phase, &first_c, &last_c); + set_action_ranges(phase, &first_c, &last_c); ProgLoc = 6008; - ServerSetDetailProc(DetailProc); + ServerSetDetailProc(detail_proc); ProgLoc = 6009; first_g = first_s; - while (!isAbortInProgress() && (first_g < last_s)) + while (!is_abort_in_progress() && (first_g < last_s)) { ProgLoc = 6010; - SetGroup(sync, first_g, &last_g); + set_group(sync, first_g, &last_g); ProgLoc = 6011; for (i = first_g; i < last_g; i++) - Dispatch(i); + dispatch(i); ProgLoc = 6012; - WaitForActions(0, first_g, last_g, first_c, last_c); + wait_for_actions(0, first_g, last_g, first_c, last_c); first_g = last_g; } ProgLoc = 6013; if (setAbortInProgress(0)) { - AbortRange(first_c, last_c); - AbortRange(first_s, last_s); + abort_range(first_c, last_c); + abort_range(first_s, last_s); status = ServerABORT; } ProgLoc = 6014; - WaitForActions(1, first_g, last_g, first_c, last_c); + wait_for_actions(1, first_g, last_g, first_c, last_c); ProgLoc = 6015; setAbortInProgress(1); RDLOCK_TABLE; @@ -675,26 +555,24 @@ EXPORT int ServerDispatchPhase(int *id __attribute__((unused)), void *vtable, ActionInfo *actions = table->actions; for (i = first_c; i < last_c; i++) { - RDLOCK_ACTION(i, sdp); + WRLOCK_ACTION(i, sdpw); if (!actions[i].done) { - UNLOCK_ACTION(i, sdpw); - WRLOCK_ACTION(i, sdpw); actions[i].status = ServerCANT_HAPPEN; - DoActionDone(i); + action_done_action_locked(i); } UNLOCK_ACTION(i, sdp); } } UNLOCK_TABLE; ProgLoc = 6015; - WaitForActions(1, first_g, last_g, first_c, last_c); + wait_for_actions(1, first_g, last_g, first_c, last_c); ProgLoc = 6016; if (!noact) - RecordStatus(first_c, last_c); + record_status(first_c, last_c); ProgLoc = 6017; if (!noact) - RecordStatus(first_s, last_s); + record_status(first_s, last_s); ProgLoc = 6018; } ProgLoc = 6019; @@ -721,7 +599,7 @@ EXPORT int ServerFailedEssential(void *vtable, int reset) return failed; } -STATIC_ROUTINE void Dispatch(int i) +static void dispatch(int i) { RDLOCK_TABLE; if (table) @@ -729,62 +607,179 @@ STATIC_ROUTINE void Dispatch(int i) int status; char logmsg[1024]; char server[33]; + ActionInfo *actions = table->actions; WRLOCK_ACTION(i, d); + MDSDBG(ACTION_PRI, ACTION_VAR(i)); + actions[i].done = 0; + actions[i].doing = 0; + actions[i].dispatched = 0; + if (Output) { - ActionInfo *actions = table->actions; - actions[i].done = 0; - actions[i].doing = 0; - actions[i].dispatched = 0; - if (Output) - { - char now[32]; - Now32(now); - sprintf(logmsg, "%s, Dispatching node %s to %s", now, actions[i].path, - Server(server, actions[i].server)); - (*Output)(logmsg); - } - // ProgLoc = 7001; - DoSendMonitor(MonitorDispatched, i); - // ProgLoc = 7002; - if (noact) + char now[32]; + Now32(now); + sprintf(logmsg, "%s, Dispatching node %s to %s", now, actions[i].path, + Server(server, actions[i].server)); + (*Output)(logmsg); + } + // ProgLoc = 7001; + send_monitor(MonitorDispatched, i); + // ProgLoc = 7002; + if (noact) + { + actions[i].dispatched = 1; + actions[i].status = status = 1; + action_done_action_locked(i); + UNLOCK_ACTION(i, d); + action_done_action_unlocked(i); + } + else + { + UNLOCK_ACTION(i, d_w); + status = ServerDispatchAction( + 0, Server(server, actions[i].server), table->tree, table->shot, + actions[i].nid, action_done, (void *)(intptr_t)i, &actions[i].status, + &actions[i].lock, &actions[i].netid, before); + if (STATUS_OK) { + WRLOCK_ACTION(i, d_w); actions[i].dispatched = 1; - actions[i].status = status = 1; - DoActionDone(i); + UNLOCK_ACTION(i, d); } else { - UNLOCK_ACTION(i, d_w); - status = ServerDispatchAction( - 0, Server(server, actions[i].server), table->tree, table->shot, - actions[i].nid, DoActionDone, i + (char *)0, &actions[i].status, - &actions[i].lock, &actions[i].netid, Before); WRLOCK_ACTION(i, d_w); - // ProgLoc = 7003; - if (STATUS_OK) - actions[i].dispatched = 1; - } - // ProgLoc = 7004; - if (STATUS_NOT_OK) - { actions[i].status = status; - DoActionDone(i); + action_done_action_locked(i); + UNLOCK_ACTION(i, d); + action_done_action_unlocked(i); } - // ProgLoc = 7005; } - UNLOCK_ACTION(i, d); } UNLOCK_TABLE; } -STATIC_ROUTINE void WakeCompletedActionQueue() { CONDITION_SET(&CompletedC); } +static void action_done_action_locked(int idx) +{ + ActionInfo *actions = table->actions; + if (actions[idx].event) + MDSEvent(actions[idx].event, sizeof(int), (char *)&table->shot); + send_monitor(MonitorDone, idx); + if (Output) + { + char logmsg[1024]; + char now[32]; + Now32(now); + if (IS_OK(actions[idx].status)) + sprintf(logmsg, "%s, Action %s completed", now, actions[idx].path); + else + { + char *emsg = MdsGetMsg(actions[idx].status); + sprintf(logmsg, "%s, Action %s failed, %s", now, actions[idx].path, + emsg); + } + (*Output)(logmsg); + } + actions[idx].done = 1; + actions[idx].recorded = 0; + EMPTYXD(xd); + char expression[60]; + struct descriptor expression_d = {0, DTYPE_T, CLASS_S, 0}; + expression_d.pointer = expression; + expression_d.length = sprintf(expression, "PUBLIC _ACTION_%08X = %d", + actions[idx].nid, actions[idx].status); + TdiExecute(&expression_d, &xd MDS_END_ARG); + MdsFree1Dx(&xd, NULL); +} + +static void action_done_action_unlocked(int idx) +{ + if (is_abort_in_progress()) + return; + ActionInfo *actions = table->actions; + int i; + for (i = 0; i < actions[idx].num_references; i++) + { + int dstat; + int doit; + int cidx = actions[idx].referenced_by[i]; + RDLOCK_ACTION(cidx, adl); + if (!actions[cidx].done && !actions[cidx].dispatched) + { + if (IS_OK(dstat = TdiGetLong(actions[cidx].condition, &doit))) + { + UNLOCK_ACTION(cidx, ad_ftt); + if (doit) + { + dispatch(cidx); + } + else + { + WRLOCK_ACTION(cidx, ad_ftte); + actions[cidx].status = ServerNOT_DISPATCHED; + action_done_action_locked(cidx); + UNLOCK_ACTION(cidx, ad_ftte); + action_done_action_unlocked(cidx); + } + } + else if (dstat != TdiUNKNOWN_VAR) + { + UNLOCK_ACTION(cidx, ad_fte); + WRLOCK_ACTION(cidx, ad_fte); + actions[cidx].status = ServerINVALID_DEPENDENCY; + action_done(cidx); + UNLOCK_ACTION(cidx, ad_fte); + action_done_action_unlocked(cidx); + } + } + else + UNLOCK_ACTION(cidx, ad_fe); + } +} + +static inline void action_done_table_locked(int idx) +{ + WRLOCK_ACTION(idx, ad); + action_done_action_locked(idx); + UNLOCK_ACTION(idx, ad); + action_done_action_unlocked(idx); +} -STATIC_ROUTINE void WaitForActionDoneQueue() +static void action_done_do(intptr_t idx) +{ + MDSDBG("Action(%d)", (int)idx); + if (idx >= 0) + { + RDLOCK_TABLE; + if (table) + { // if no table prevent seg fault + action_done_table_locked(idx); + } + UNLOCK_TABLE; + } + CONDITION_SET(&JobWaitC); +} + +//#define ACTION_DONE_THREAD +#ifdef ACTION_DONE_THREAD +typedef struct _complete +{ + struct _complete *next; + int idx; +} Complete; + +static Condition CompletedC = CONDITION_INITIALIZER; +static Complete *CompletedQueueHead = NULL; +static Complete *CompletedQueueTail = NULL; + +static pthread_mutex_t completed_queue_mutex = PTHREAD_MUTEX_INITIALIZER; +static inline void action_done_signal() { CONDITION_SET(&CompletedC); } + +static inline void action_done_wait() { CONDITION_WAIT_1SEC(&CompletedC); } -STATIC_ROUTINE void QueueCompletedAction(int i) +static void action_done_push(intptr_t i) { Complete *c = malloc(sizeof(Complete)); c->idx = i; @@ -796,10 +791,10 @@ STATIC_ROUTINE void QueueCompletedAction(int i) CompletedQueueHead = c; CompletedQueueTail = c; pthread_mutex_unlock(&completed_queue_mutex); - WakeCompletedActionQueue(); + action_done_signal(); } -STATIC_ROUTINE int DequeueCompletedAction(int *i) +static int action_done_pop(intptr_t *i) { int doneAction = -1; while (doneAction == -1) @@ -819,48 +814,89 @@ STATIC_ROUTINE int DequeueCompletedAction(int *i) { CONDITION_RESET(&CompletedC); // reset list state pthread_mutex_unlock(&completed_queue_mutex); - WaitForActionDoneQueue(); + action_done_wait(); } } *i = doneAction; return B_TRUE; } -STATIC_THREADSAFE Condition ActionDoneRunningC = CONDITION_INITIALIZER; +static Condition ActionDoneRunningC = CONDITION_INITIALIZER; -STATIC_ROUTINE void ActionDoneExit() { CONDITION_RESET(&ActionDoneRunningC); } +static void action_done_exit() +{ + MDSDBG("exit"); + CONDITION_RESET(&ActionDoneRunningC); +} -STATIC_ROUTINE void ActionDoneThread() +static void action_done_thread() { - int i; - pthread_cleanup_push(ActionDoneExit, 0); + intptr_t i; + pthread_cleanup_push(action_done_exit, 0); CONDITION_SET(&ActionDoneRunningC); - while (DequeueCompletedAction(&i)) - ActionDone(i); + while (action_done_pop(&i)) + action_done_do(i); pthread_cleanup_pop(1); - pthread_exit(NULL); } -STATIC_ROUTINE void DoActionDone(int i) +static void action_done(intptr_t i) { INIT_STATUS; - pthread_t thread; - QueueCompletedAction(i); /***** must be done before starting thread ****/ - CONDITION_START_THREAD(&ActionDoneRunningC, thread, , ActionDoneThread, NULL); + static pthread_t thread; + action_done_push(i); /***** must be done before starting thread ****/ + CONDITION_START_THREAD(&ActionDoneRunningC, thread, , action_done_thread, NULL); if (STATUS_NOT_OK) - perror("DoActionDone: pthread creation failed"); + perror("action_done: pthread creation failed"); +} +#else +static inline void action_done(intptr_t i) +{ + return action_done_do(i); } +#endif -STATIC_THREADSAFE Condition SendMonitorRunningC = CONDITION_INITIALIZER; +void send_monitor_do(int mode, int idx) +{ + if (MonitorOn) + { + char tree[13]; + char *cptr; + int i; + RDLOCK_TABLE; + if (table) + { // if no table prevent seg fault + for (i = 0, cptr = table->tree; i < 12; i++) + if (cptr[i] == (char)32) + break; + else + tree[i] = cptr[i]; + tree[i] = 0; + ActionInfo *actions = table->actions; + RDLOCK_ACTION(idx, sm); + int on = actions[idx].on; + char server[33]; + for (i = 0, cptr = actions[idx].server; i < 32 && (cptr[i] != ' '); i++) + server[i] = cptr[i]; + server[i] = 0; + MonitorOn = ServerSendMonitor(Monitor, tree, table->shot, + actions[idx].phase, actions[idx].nid, on, + mode, server, actions[idx].status); + UNLOCK_ACTION(idx, sm); + } + UNLOCK_TABLE; + } +} + +static Condition SendMonitorRunningC = CONDITION_INITIALIZER; -STATIC_ROUTINE void WakeSendMonitorQueue() { CONDITION_SET(&SendMonitorC); } +static inline void send_monitor_signal() { CONDITION_SET(&SendMonitorC); } -STATIC_ROUTINE void WaitForSendMonitorQueue() +static inline void send_monitor_wait() { CONDITION_WAIT_1SEC(&SendMonitorC); } -STATIC_ROUTINE void QueueSendMonitor(int mode, int i) +static void send_monitor_push(int mode, int i) { SendMonitorInfo *c = malloc(sizeof(SendMonitorInfo)); c->idx = i; @@ -873,10 +909,10 @@ STATIC_ROUTINE void QueueSendMonitor(int mode, int i) SendMonitorQueueHead = c; SendMonitorQueueTail = c; MONITOR_QUEUE_UNLOCK; - WakeSendMonitorQueue(); + send_monitor_signal(); } -STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) +static int send_monitor_pop(int *mode_out, int *i) { int idx; int mode; @@ -897,11 +933,10 @@ STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) } else { - pthread_mutex_unlock(&send_monitor_queue_mutex); - release = 0; + release = pthread_mutex_unlock(&send_monitor_queue_mutex); idx = -1; mode = 0; - WaitForSendMonitorQueue(); + send_monitor_wait(); } pthread_cleanup_pop(release); } while (idx == -1); @@ -910,32 +945,35 @@ STATIC_ROUTINE int DequeueSendMonitor(int *mode_out, int *i) return B_TRUE; } -STATIC_ROUTINE void SendMonitorExit() { CONDITION_RESET(&SendMonitorRunningC); } +static void send_monitor_exit() +{ + CONDITION_RESET(&SendMonitorRunningC); +} -STATIC_ROUTINE void SendMonitorThread() +static void send_monitor_thread() { int i; int mode; - pthread_cleanup_push(SendMonitorExit, NULL); + pthread_cleanup_push(send_monitor_exit, NULL); CONDITION_SET(&SendMonitorRunningC); - while (DequeueSendMonitor(&mode, &i)) - SendMonitor(mode, i); + while (send_monitor_pop(&mode, &i)) + send_monitor_do(mode, i); pthread_cleanup_pop(1); - pthread_exit(NULL); } -STATIC_ROUTINE void DoSendMonitor(int mode, int idx) +static void send_monitor(int mode, int idx) { INIT_STATUS; - pthread_t thread; - QueueSendMonitor(mode, idx); /***** must be done before starting thread ****/ - CONDITION_START_THREAD(&SendMonitorRunningC, thread, , SendMonitorThread, + static pthread_t thread; + send_monitor_push(mode, idx); /***** must be done before starting thread ****/ + CONDITION_START_THREAD(&SendMonitorRunningC, thread, , send_monitor_thread, NULL); if (STATUS_NOT_OK) - perror("DoSendMonitor: pthread creation failed"); + perror("send_monitor: pthread creation failed"); } -void serverDisarmDispatchTable(void *vtable) +// used in ServerDispatchClose +void server_dispatch_table_disarm(void *vtable) { WRLOCK_TABLE; if (table == vtable) @@ -943,7 +981,7 @@ void serverDisarmDispatchTable(void *vtable) UNLOCK_TABLE; } -static inline void serverFreeDispatchTable(void *vtable) +static inline void server_dispatch_table_free(void *vtable) { ActionInfo *actions = ((DispatchTable *)vtable)->actions; int num_actions = ((DispatchTable *)vtable)->num; @@ -968,8 +1006,8 @@ EXPORT int ServerFreeDispatchTable(void *vtable) // should be called during CloseTopTree if (vtable) { - serverDisarmDispatchTable(vtable); - serverFreeDispatchTable(vtable); + server_dispatch_table_disarm(vtable); + server_dispatch_table_free(vtable); } return MDSplusSUCCESS; } diff --git a/servershr/ServerFindServers.c b/servershr/ServerFindServers.c index af72e6598c..5281339e6b 100644 --- a/servershr/ServerFindServers.c +++ b/servershr/ServerFindServers.c @@ -77,7 +77,7 @@ EXPORT char *ServerFindServers(void **ctx, char *wild_match) struct dirent *entry = readdir(dir); if (entry) { - char *ans_c = strcpy(malloc(strlen(entry->d_name) + 1), entry->d_name); + char *ans_c = strdup(entry->d_name); if ((strcmp(ans_c, ".") == 0) || (strcmp(ans_c, "..") == 0)) continue; else diff --git a/servershr/ServerGetInfo.c b/servershr/ServerGetInfo.c index 7648f881e6..7e0fb565cf 100644 --- a/servershr/ServerGetInfo.c +++ b/servershr/ServerGetInfo.c @@ -56,57 +56,79 @@ doing. ------------------------------------------------------------------------------*/ +#include +#include + +#include #include #include +#include #include "servershrp.h" -#include -#include -extern int ServerConnect(); +#include + extern int GetAnswerInfoTS(); +extern int get_addr_port(char *server, uint32_t *addrp, uint16_t *portp); -EXPORT char *ServerGetInfo(int full __attribute__((unused)), char *server) +EXPORT char *ServerGetInfo(int full __attribute__((unused)), char *server_in) { char *cmd = "MdsServerShr->ServerInfo:dsc()"; char *ans; char *ansret; short len = 0; void *mem = 0; - SOCKET sock = ServerConnect(server); - if (sock != INVALID_SOCKET) + char *srv = TranslateLogical(server_in); + char *server = srv ? srv : server_in; + uint32_t addr; + uint16_t port = 0; + if (get_addr_port(server, &addr, &port)) { - int status = SendArg(sock, (unsigned char)0, (char)DTYPE_CSTRING, - (unsigned char)1, (short)strlen(cmd), 0, 0, cmd); - if (STATUS_OK) + free(srv); + ans = "Could not resolve server"; + len = strlen(ans); + } + else + { + int conid = ConnectToMds(server); + free(srv); + if (conid == INVALID_CONNECTION_ID) { - char dtype; - char ndims; - int dims[8]; - int numbytes; - char *reply; - status = GetAnswerInfoTS(sock, &dtype, &len, &ndims, dims, &numbytes, - (void **)&reply, &mem, 10); - if (STATUS_OK && (dtype == DTYPE_CSTRING)) - ans = reply; - else - { - ans = "Invalid response from server"; - len = strlen(ans); - } + ans = "Error connecting to server"; + len = strlen(ans); } else { - ans = "No response from server"; - len = strlen(ans); + pthread_cleanup_push((void *)DisconnectFromMds, (void *)(intptr_t)conid); + if (IS_NOT_OK(SendArg(conid, (unsigned char)0, (char)DTYPE_CSTRING, + (unsigned char)1, (short)strlen(cmd), 0, 0, cmd))) + { + ans = "No response from server"; + len = strlen(ans); + } + else + { + char dtype; + char ndims; + int dims[8]; + int numbytes; + char *reply; + if (IS_NOT_OK(GetAnswerInfoTS( + conid, &dtype, &len, &ndims, dims, &numbytes, &reply, &mem, 10)) || + (dtype != DTYPE_CSTRING)) + { + ans = "Invalid response from server"; + len = strlen(ans); + } + else + { + ans = reply; + } + } + pthread_cleanup_pop(0); } } - else - { - ans = "Error connecting to server"; - len = strlen(ans); - } ansret = strncpy((char *)malloc(len + 1), ans, len); free(mem); ansret[len] = 0; - return (ansret); + return ansret; } diff --git a/servershr/ServerMonitorCheckin.c b/servershr/ServerMonitorCheckin.c index e941714bf9..fa1971c9a9 100644 --- a/servershr/ServerMonitorCheckin.c +++ b/servershr/ServerMonitorCheckin.c @@ -56,57 +56,67 @@ astparam, void (*link_down)()) #include #include #include +#include #include #include #include #include "servershrp.h" +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static void (*appAst)() = 0; +static int usingEvents = -1; -static void eventAst(void *astprm, int msglen __attribute__((unused)), - char *msg) +static void event_ast(void *astprm, int msglen __attribute__((unused)), char *msg) { - (*appAst)(astprm, msg); + void (*ast)(); + pthread_mutex_lock(&lock); + ast = appAst; + pthread_mutex_unlock(&lock); + (*ast)(astprm, msg); } -EXPORT int ServerMonitorCheckin(char *server, void (*ast)(), void *astprm) +#define EVENT_PREFIX "event:" +#define EVENT_PREFIX_LEN (sizeof(EVENT_PREFIX) - 1) +static inline int using_events(char *server, void (*ast)(), void *astprm) { - static int usingEvents = -1; - const char *event_str = "event:"; - const unsigned int event_len = strlen(event_str); + int yesno; + pthread_mutex_lock(&lock); if (usingEvents == -1) { char *svr_env = getenv(server); if (!svr_env) svr_env = server; - if ((strlen(svr_env) > event_len) && - (strncasecmp(svr_env, event_str, event_len) == 0)) + if ((strlen(svr_env) > EVENT_PREFIX_LEN) && + (strncasecmp(svr_env, EVENT_PREFIX, EVENT_PREFIX_LEN) == 0)) { int evid; appAst = ast; - usingEvents = - MDSEventAst(strdup(svr_env + event_len), eventAst, astprm, &evid) & 1; + usingEvents = IS_OK(MDSEventAst(svr_env + EVENT_PREFIX_LEN, event_ast, astprm, &evid)); } else usingEvents = B_FALSE; } - if (usingEvents) + yesno = usingEvents; + pthread_mutex_unlock(&lock); + return yesno; +} + +EXPORT int ServerMonitorCheckin(char *server, void (*ast)(), void *astprm) +{ + if (using_events(server, ast, astprm)) return MDSplusSUCCESS; - else - { - struct descrip p1, p2, p3, p4, p5, p6, p7, p8; - char *cstring = ""; - int zero = 0; - int mode = MonitorCheckin; - return ServerSendMessage(0, server, SrvMonitor, NULL, NULL, NULL, ast, - astprm, NULL, 8, - MakeDescrip(&p1, DTYPE_CSTRING, 0, 0, cstring), - MakeDescrip(&p2, DTYPE_LONG, 0, 0, &zero), - MakeDescrip(&p3, DTYPE_LONG, 0, 0, &zero), - MakeDescrip(&p4, DTYPE_LONG, 0, 0, &zero), - MakeDescrip(&p5, DTYPE_LONG, 0, 0, &zero), - MakeDescrip(&p6, DTYPE_LONG, 0, 0, &mode), - MakeDescrip(&p7, DTYPE_CSTRING, 0, 0, cstring), - MakeDescrip(&p8, DTYPE_LONG, 0, 0, &zero)); - } + struct descrip p1, p2, p3, p4, p5, p6, p7, p8; + char *cstring = ""; + int zero = 0; + int mode = MonitorCheckin; + return ServerSendMessage(0, server, SrvMonitor, NULL, NULL, NULL, ast, + astprm, NULL, 8, + MakeDescrip(&p1, DTYPE_CSTRING, 0, 0, cstring), + MakeDescrip(&p2, DTYPE_LONG, 0, 0, &zero), + MakeDescrip(&p3, DTYPE_LONG, 0, 0, &zero), + MakeDescrip(&p4, DTYPE_LONG, 0, 0, &zero), + MakeDescrip(&p5, DTYPE_LONG, 0, 0, &zero), + MakeDescrip(&p6, DTYPE_LONG, 0, 0, &mode), + MakeDescrip(&p7, DTYPE_CSTRING, 0, 0, cstring), + MakeDescrip(&p8, DTYPE_LONG, 0, 0, &zero)); } diff --git a/servershr/ServerQAction.c b/servershr/ServerQAction.c index 4370095749..3351fc26e1 100644 --- a/servershr/ServerQAction.c +++ b/servershr/ServerQAction.c @@ -22,6 +22,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include #include @@ -39,18 +40,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef HAVE_UNISTD_H #include #endif -#ifdef _WIN32 -#include -#define MSG_DONTWAIT 0 // TODO: implement workaround usiing select -#else -typedef int SOCKET; -#define INVALID_SOCKET -1 -#include -#include -#include -#endif #include +//#define DEBUG +#include + typedef struct _MonitorList { uint32_t addr; @@ -72,8 +66,8 @@ extern int TdiExecute(); extern int mdsdcl_do_command(char *command); extern int is_broken_socket(SOCKET sock); -static int SendReply(SrvJob *job, int replyType, int status, int length, - char *msg); +static int send_reply(SrvJob *job, int replyType, int status, int length, + char *msg); static int DoSrvCommand(SrvJob *job_in); static int DoSrvAction(SrvJob *job_in); @@ -83,7 +77,7 @@ static void DoSrvMonitor(SrvJob *job_in); static void RemoveClient(SrvJob *job); extern uint32_t MdsGetClientAddr(); -extern char *MdsGetServerPortname(); +extern char *GetPortname(); static ClientList *Clients = NULL; static MonitorList *Monitors = NULL; @@ -115,14 +109,19 @@ static SrvJob *CurrentJob = NULL; static Condition_p JobQueueCond = CONDITION_INITIALIZER; #define JobQueue (JobQueueCond.value) -static char *current_job_text = NULL; - -static int Logging = 1; -static int Debug = 0; -static int QueueLocked = 0; -static int WorkerDied = 0; -static int LeftWorkerLoop = 0; -static int CondWStat = 0; +static pthread_mutex_t STATIC_lock = PTHREAD_MUTEX_INITIALIZER; +static char *STATIC_current_job_text = NULL; +static int STATIC_Logging = 1; +static int STATIC_Debug +#ifdef DEBUG + = 1; +#else + = 0; +#endif +static int STATIC_QueueLocked = 0; +static int STATIC_WorkerDied = 0; +static int STATIC_LeftWorkerLoop = 0; +static int STATIC_CondWStat = 0; int ProgLoc = 0; EXPORT struct descriptor *ServerInfo() @@ -138,15 +137,21 @@ EXPORT struct descriptor *ServerInfo() EXPORT int ServerDebug(int setting) { - int old = Debug; - Debug = setting; + int old; + pthread_mutex_lock(&STATIC_lock); + old = STATIC_Debug; + STATIC_Debug = setting; + pthread_mutex_unlock(&STATIC_lock); return old; } + // main -EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, +EXPORT int ServerQAction(uint32_t *addrp, uint16_t *portp, int *op, int *flags, int *jobid, void *p1, void *p2, void *p3, void *p4, void *p5, void *p6, void *p7, void *p8) { + uint32_t addr = addrp ? *addrp : MdsGetClientAddr(); + MDSDBG(IPADDRPRI ":%d", IPADDRVAR(&addr), portp ? *portp : -1); int status = ServerINVALID_ACTION_OPERATION; switch (*op) { @@ -180,97 +185,129 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, case SrvAction: { SrvActionJob job; - job.h.addr = addr ? *addr : MdsGetClientAddr(); - job.h.port = *port; + job.h.addr = addr; + job.h.port = *portp; job.h.op = *op; job.h.length = sizeof(job); job.h.flags = *flags; job.h.jobid = *jobid; - job.tree = strcpy(malloc(strlen((char *)p1) + 1), (char *)p1); + job.tree = strdup((char *)p1); job.shot = *(int *)p2; job.nid = *(int *)p3; if (job.h.addr) + { + MDSDBG(SVRACTIONJOB_PRI, SVRACTIONJOB_VAR(&job)); status = QJob((SrvJob *)&job); + } else + { + MDSWRN(SVRACTIONJOB_PRI " No Addr", SVRACTIONJOB_VAR(&job)); status = DoSrvAction((SrvJob *)&job); + } break; } case SrvClose: { SrvCloseJob job; - job.h.addr = MdsGetClientAddr(); - job.h.port = *port; + job.h.addr = addr; + job.h.port = *portp; job.h.op = *op; job.h.length = sizeof(job); job.h.flags = *flags; job.h.jobid = *jobid; if (job.h.addr) + { + MDSDBG(SVRCLOSEJOB_PRI, SVRCLOSEJOB_VAR(&job)); status = QJob((SrvJob *)&job); + } else + { + MDSWRN(SVRCLOSEJOB_PRI " No Addr", SVRCLOSEJOB_VAR(&job)); status = DoSrvClose((SrvJob *)&job); + } break; } case SrvCreatePulse: { SrvCreatePulseJob job; - job.h.addr = MdsGetClientAddr(); - job.h.port = *port; + job.h.addr = addr; + job.h.port = *portp; job.h.op = *op; job.h.length = sizeof(job); job.h.flags = *flags; job.h.jobid = *jobid; - job.tree = strcpy(malloc(strlen((char *)p1) + 1), (char *)p1); + job.tree = strdup((char *)p1); job.shot = *(int *)p2; if (job.h.addr) + { + MDSDBG(SVRCREATEPULSEJOB_PRI, SVRCREATEPULSEJOB_VAR(&job)); status = QJob((SrvJob *)&job); + } else + { + MDSWRN(SVRCREATEPULSEJOB_PRI " No Addr", SVRCREATEPULSEJOB_VAR(&job)); status = DoSrvCreatePulse((SrvJob *)&job); + } break; } case SrvSetLogging: { - Logging = *(int *)p1; + pthread_mutex_lock(&STATIC_lock); + STATIC_Logging = *(int *)p1; + pthread_mutex_unlock(&STATIC_lock); status = MDSplusSUCCESS; break; } case SrvCommand: { SrvCommandJob job; - job.h.addr = MdsGetClientAddr(); - job.h.port = *port; + job.h.addr = addr; + job.h.port = *portp; job.h.op = *op; job.h.length = sizeof(job); job.h.flags = *flags; job.h.jobid = *jobid; - job.table = strcpy(malloc(strlen((char *)p1) + 1), (char *)p1); - job.command = strcpy(malloc(strlen((char *)p2) + 1), (char *)p2); + job.table = strdup((char *)p1); + job.command = strdup((char *)p2); if (job.h.addr) + { + MDSDBG(SVRCOMMANDJOB_PRI, SVRCOMMANDJOB_VAR(&job)); status = QJob((SrvJob *)&job); + } else + { + MDSWRN(SVRCOMMANDJOB_PRI " No Addr", SVRCOMMANDJOB_VAR(&job)); status = DoSrvCommand((SrvJob *)&job); + } break; } case SrvMonitor: { SrvMonitorJob job; - job.h.addr = MdsGetClientAddr(); - job.h.port = *port; + job.h.addr = addr; + job.h.port = *portp; job.h.op = *op; job.h.length = sizeof(job); job.h.flags = *flags; job.h.jobid = *jobid; - job.tree = strcpy(malloc(strlen((char *)p1) + 1), (char *)p1); + job.tree = strdup((char *)p1); job.shot = *(int *)p2; job.phase = *(int *)p3; job.nid = *(int *)p4; job.on = *(int *)p5; job.mode = *(int *)p6; - job.server = strcpy(malloc(strlen((char *)p7) + 1), (char *)p7); + job.server = strdup((char *)p7); job.status = *(int *)p8; if (job.h.addr) + { + MDSDBG(SVRMONITORJOB_PRI, SVRMONITORJOB_VAR(&job)); status = QJob((SrvJob *)&job); + } else + { + MDSWRN(SVRMONITORJOB_PRI " No Addr", SVRMONITORJOB_VAR(&job)); status = MDSplusERROR; + } break; } case SrvShow: @@ -289,18 +326,21 @@ EXPORT int ServerQAction(uint32_t *addr, uint16_t *port, int *op, int *flags, } return status; } + // main static void AbortJob(SrvJob *job) { if (job) { - SendReply(job, SrvJobFINISHED, ServerABORT, 0, 0); + send_reply(job, SrvJobFINISHED, ServerABORT, 0, 0); FreeJob(job); } } + // main static int QJob(SrvJob *job) { + MDSDBG("Queued job %d for " IPADDRPRI ":%d", job->h.jobid, IPADDRVAR(&job->h.addr), job->h.port); SrvJob *qjob = (SrvJob *)memcpy(malloc(job->h.length), job, job->h.length); QUEUE_LOCK; if (JobQueueNext) @@ -315,37 +355,37 @@ static int QJob(SrvJob *job) return StartWorker(); } // main -static void LogPrefix(char *ans_c) +static void STATIC_log_prefix_locked(char *ans_c) { if (ans_c) { char hname[512]; - char *port = MdsGetServerPortname(); + char *port = GetPortname(); gethostname(hname, 512); char now[32]; Now32(now); sprintf(ans_c, "%s, %s:%s, %s, ", now, hname, port ? port : "?", - Logging == 0 ? "logging disabled" : "logging enabled"); - if (Debug) + STATIC_Logging ? "logging enabled" : "logging disabled"); + if (STATIC_Debug) { sprintf(ans_c + strlen(ans_c), - "\nDebug info: QueueLocked = %d ProgLoc = %d WorkerDied = %d" - "\n LeftWorkerLoop = %d CondWStat = %d\n", - QueueLocked, ProgLoc, WorkerDied, LeftWorkerLoop, CondWStat); + "\nDebug info: QueueLocked=%d, ProgLoc=%d, WorkerDied=%d, LeftWorkerLoop=%d, CondWStat=%d,\n", + STATIC_QueueLocked, ProgLoc, STATIC_WorkerDied, STATIC_LeftWorkerLoop, STATIC_CondWStat); } } } + // main static int ShowCurrentJob(struct descriptor_xd *ans) { char *ans_c; struct descriptor ans_d = {0, DTYPE_T, CLASS_S, 0}; - QUEUE_LOCK; - char *job_text = current_job_text; + pthread_mutex_lock(&STATIC_lock); + char *job_text = STATIC_current_job_text; if (job_text == 0) { ans_c = malloc(1024); - LogPrefix(ans_c); + STATIC_log_prefix_locked(ans_c); strcat(ans_c, "Inactive"); } else @@ -356,7 +396,7 @@ static int ShowCurrentJob(struct descriptor_xd *ans) ((detail = (*detail_proc)(1)) != 0)) { ans_c = malloc(1024 + strlen(job_text) + strlen(detail)); - LogPrefix(ans_c); + STATIC_log_prefix_locked(ans_c); strcat(ans_c, job_text); strcat(ans_c, detail); free(detail); @@ -364,11 +404,11 @@ static int ShowCurrentJob(struct descriptor_xd *ans) else { ans_c = malloc(1024 + strlen(job_text)); - LogPrefix(ans_c); + STATIC_log_prefix_locked(ans_c); strcat(ans_c, job_text); } } - QUEUE_UNLOCK; + pthread_mutex_unlock(&STATIC_lock); ans_d.length = strlen(ans_c); ans_d.pointer = ans_c; MdsCopyDxXd(&ans_d, ans); @@ -389,8 +429,8 @@ static int RemoveLast() JobQueueNext->h.next = 0; else JobQueue = 0; + MDSMSG(SVRJOB_PRI "Removed pending action", SVRJOB_VAR(job)); FreeJob(job); - printf("Removed pending action"); status = MDSplusSUCCESS; } else @@ -455,13 +495,17 @@ static void SetCurrentJob(SrvJob *job) static inline void LockQueue() { _CONDITION_LOCK(&JobQueueCond); - QueueLocked = 1; + pthread_mutex_lock(&STATIC_lock); + STATIC_QueueLocked = 1; + pthread_mutex_unlock(&STATIC_lock); } // thread static inline void UnlockQueue() { - QueueLocked = 0; _CONDITION_UNLOCK(&JobQueueCond); + pthread_mutex_lock(&STATIC_lock); + STATIC_QueueLocked = 0; + pthread_mutex_unlock(&STATIC_lock); } // main static int doingNid; @@ -476,12 +520,14 @@ EXPORT int GetDoingNid() // thread static int DoSrvAction(SrvJob *job_in) { - INIT_STATUS_ERROR; + int status; SrvActionJob *job = (SrvActionJob *)job_in; char *job_text, *old_job_text; sprintf((job_text = (char *)malloc(100)), "Doing nid %d in %s shot %d", job->nid, job->tree, job->shot); - current_job_text = job_text; + pthread_mutex_lock(&STATIC_lock); + STATIC_current_job_text = job_text; + pthread_mutex_unlock(&STATIC_lock); void *dbid = NULL; status = _TreeNewDbid(&dbid); if (STATUS_NOT_OK) @@ -506,29 +552,33 @@ static int DoSrvAction(SrvJob *job_in) job_text = malloc(fullpath.length + 1024); sprintf(job_text, "Doing %s in %s shot %d", fullpath.pointer, job->tree, job->shot); - old_job_text = current_job_text; - current_job_text = job_text; - free(old_job_text); StrFree1Dx(&fullpath); nid_dsc.pointer = (char *)&job->nid; ans_dsc.pointer = (char *)&retstatus; TreeSetDefaultNid(0); - if (Logging) + pthread_mutex_lock(&STATIC_lock); + old_job_text = STATIC_current_job_text; + STATIC_current_job_text = job_text; + free(old_job_text); + if (STATIC_Logging) { char now[32]; Now32(now); - printf("%s, %s\n", now, current_job_text); + printf("%s, %s\n", now, STATIC_current_job_text); fflush(stdout); } + pthread_mutex_unlock(&STATIC_lock); status = TdiDoTask(&nid_dsc, &ans_dsc MDS_END_ARG); - if (Logging) + pthread_mutex_lock(&STATIC_lock); + memcpy(STATIC_current_job_text, "Done ", 5); + if (STATIC_Logging) { char now[32]; Now32(now); - memcpy(current_job_text, "Done ", 5); - printf("%s, %s\n", now, current_job_text); + printf("%s, %s\n", now, STATIC_current_job_text); fflush(stdout); } + pthread_mutex_unlock(&STATIC_lock); if (STATUS_OK) status = retstatus; } @@ -536,7 +586,7 @@ static int DoSrvAction(SrvJob *job_in) end:; TreeFreeDbid(dbid); if (job_in->h.addr) - SendReply(job_in, SrvJobFINISHED, status, 0, 0); + send_reply(job_in, SrvJobFINISHED, status, 0, 0); return status; } // thread @@ -544,28 +594,31 @@ static int DoSrvClose(SrvJob *job_in) { INIT_STATUS_ERROR; char *job_text = strcpy((char *)malloc(32), "Closing trees"); - current_job_text = job_text; + pthread_mutex_lock(&STATIC_lock); + STATIC_current_job_text = job_text; + pthread_mutex_unlock(&STATIC_lock); do { status = TreeClose(0, 0); } while (STATUS_OK); status = (status == TreeNOT_OPEN) ? TreeSUCCESS : status; if (job_in->h.addr) - SendReply(job_in, SrvJobFINISHED, status, 0, 0); + send_reply(job_in, SrvJobFINISHED, status, 0, 0); return status; } // thread static int DoSrvCreatePulse(SrvJob *job_in) { - INIT_STATUS_ERROR; SrvCreatePulseJob *job = (SrvCreatePulseJob *)job_in; char *job_text = malloc(100); sprintf(job_text, "Creating pulse for %s shot %d", ((SrvCreatePulseJob *)job)->tree, ((SrvCreatePulseJob *)job)->shot); - current_job_text = job_text; - status = TreeCreateTreeFiles(job->tree, job->shot, -1); + pthread_mutex_lock(&STATIC_lock); + STATIC_current_job_text = job_text; + pthread_mutex_unlock(&STATIC_lock); + int status = TreeCreateTreeFiles(job->tree, job->shot, -1); if (job_in->h.addr) - SendReply(job_in, SrvJobFINISHED, status, 0, 0); + send_reply(job_in, SrvJobFINISHED, status, 0, 0); return status; } // thread @@ -576,28 +629,20 @@ static int DoSrvCommand(SrvJob *job_in) char *set_table = strcpy(malloc(strlen(job->table) + 24), "set command "); char *job_text = (char *)malloc(strlen(job->command) + strlen(job->table) + 60); - ProgLoc = 61; sprintf(job_text, "Doing command %s in command table %s", job->command, job->table); - ProgLoc = 62; - current_job_text = job_text; - ProgLoc = 63; + pthread_mutex_lock(&STATIC_lock); + STATIC_current_job_text = job_text; + pthread_mutex_unlock(&STATIC_lock); strcat(set_table, job->table); - ProgLoc = 64; status = mdsdcl_do_command(set_table); - ProgLoc = 65; free(set_table); - ProgLoc = 66; if (STATUS_OK) { - ProgLoc = 67; status = mdsdcl_do_command(job->command); - // ProgLoc = 68; } - ProgLoc = 69; if (job_in->h.addr) - SendReply(job_in, SrvJobFINISHED, status, 0, 0); - ProgLoc = 70; + send_reply(job_in, SrvJobFINISHED, status, 0, 0); return status; } // thread @@ -656,7 +701,7 @@ static void SendToMonitor(MonitorList *m, MonitorList *prev, SrvJob *job_in) job->phase, job->nid, job->on, job->mode, job->server, job->status, now, status_text); } - status = SendReply(job_in, SrvJobFINISHED, 1, strlen(msg), msg); + status = send_reply(job_in, SrvJobFINISHED, 1, strlen(msg), msg); free(msg); if (STATUS_NOT_OK) { @@ -691,42 +736,41 @@ static void DoSrvMonitor(SrvJob *job_in) SrvMonitorJob *job = (SrvMonitorJob *)job_in; status = (job->mode == MonitorCheckin) ? AddMonitorClient(job_in) : SendToMonitors(job_in); - SendReply(job_in, - (job->mode == MonitorCheckin) ? SrvJobCHECKEDIN : SrvJobFINISHED, - status, 0, 0); + send_reply(job_in, + (job->mode == MonitorCheckin) ? SrvJobCHECKEDIN : SrvJobFINISHED, + status, 0, 0); } // thread static void WorkerExit(void *arg __attribute__((unused))) { - if (QueueLocked) + pthread_mutex_lock(&STATIC_lock); + STATIC_WorkerDied++; + if (STATIC_QueueLocked) UnlockQueue(); + pthread_mutex_unlock(&STATIC_lock); CONDITION_RESET(&WorkerRunning); - WorkerDied++; - fprintf(stderr, "Worker thread exitted\n"); + MDSWRN("Worker thread exitted"); } // thread static void WorkerThread(void *arg __attribute__((unused))) { SrvJob *job; pthread_cleanup_push(WorkerExit, NULL); - ProgLoc = 1; CONDITION_SET(&WorkerRunning); while ((job = NextJob(1))) { - if (Debug) + MDSDBG("Starting job %d for " IPADDRPRI ":%d", job->h.jobid, IPADDRVAR(&job->h.addr), job->h.port); + pthread_mutex_lock(&STATIC_lock); + if (STATIC_Debug) fprintf(stderr, "job started.\n"); - char *save_text; - ProgLoc = 2; + ProgLoc = 1; + pthread_mutex_unlock(&STATIC_lock); ServerSetDetailProc(0); - ProgLoc = 3; SetCurrentJob(job); - ProgLoc = 4; if ((job->h.flags & SrvJobBEFORE_NOTIFY) != 0) { - ProgLoc = 5; - SendReply(job, SrvJobSTARTING, 1, 0, 0); + send_reply(job, SrvJobSTARTING, 1, 0, 0); } - ProgLoc = 6; switch (job->h.op) { case SrvAction: @@ -745,19 +789,22 @@ static void WorkerThread(void *arg __attribute__((unused))) DoSrvMonitor(job); break; } - ProgLoc = 7; - SetCurrentJob(0); - ProgLoc = 8; + MDSDBG("Finished job %d for " IPADDRPRI ":%d", job->h.jobid, IPADDRVAR(&job->h.addr), job->h.port); + SetCurrentJob(NULL); FreeJob(job); - ProgLoc = 9; - save_text = current_job_text; - current_job_text = 0; + pthread_mutex_lock(&STATIC_lock); + ProgLoc = 7; + char *save_text = STATIC_current_job_text; + STATIC_current_job_text = NULL; free(save_text); - ProgLoc = 10; - if (Debug) + if (STATIC_Debug) fprintf(stderr, "job done.\n"); + pthread_mutex_unlock(&STATIC_lock); } - LeftWorkerLoop++; + pthread_mutex_lock(&STATIC_lock); + STATIC_LeftWorkerLoop++; + ProgLoc = 9; + pthread_mutex_unlock(&STATIC_lock); pthread_cleanup_pop(1); pthread_exit(NULL); } @@ -773,10 +820,18 @@ static int StartWorker() // main static void KillWorker() { + MDSDBG("enter"); _CONDITION_LOCK(&WorkerRunning); if (WorkerRunning.value) { - pthread_cancel(Worker); +#ifndef WIN32 + MDSDBG("cancel"); + if (pthread_cancel(Worker)) +#endif + { + MDSWRN("kill"); + pthread_kill(Worker, SIGINT); + } _CONDITION_WAIT_RESET(&WorkerRunning); } _CONDITION_UNLOCK(&WorkerRunning); @@ -795,20 +850,20 @@ static SOCKET AttachPort(uint32_t addr, uint16_t port) sin.sin_family = AF_INET; *(uint32_t *)(&sin.sin_addr) = addr; sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock != INVALID_SOCKET) + if (sock == INVALID_SOCKET) + { + MDSERR("Cannot get socket for " IPADDRPRI ":%u", IPADDRVAR(&addr), port); + } + else { if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) { + MDSERR("Cannot connect to " IPADDRPRI ":%u", IPADDRVAR(&addr), port); shutdown(sock, 2); close(sock); - uint8_t *ip = (uint8_t *)&addr; - char now[32]; - Now32(now); - fprintf(stderr, "%s, ERROR Cannot connect to %u.%u.%u.%u:%u", now, ip[0], - ip[1], ip[2], ip[3], port); - perror(" "); return INVALID_SOCKET; } + MDSDBG("Connected to " IPADDRPRI ":%u", IPADDRVAR(&addr), port); new = (ClientList *)malloc(sizeof(ClientList)); l = Clients; Clients = new; @@ -844,39 +899,47 @@ static void RemoveClient(SrvJob *job) } } -#ifndef _WIN32 -static void reset_sigpipe_handler() +/// returns the number of bytes sent +static int send_all(SOCKET sock, char *msg, int len) { - signal(SIGPIPE, SIG_DFL); + int sent; + MSG_NOSIGNAL_ALT_PUSH(); + sent = 0; + do + { + const int bytes = send(sock, msg + sent, len - sent, MSG_NOSIGNAL); + if (bytes <= 0) + { + sent = bytes; + break; + } + sent += bytes; + } while (sent < len); + MSG_NOSIGNAL_ALT_POP(); + return sent; } -#endif -// both -static int SendReply(SrvJob *job, int replyType, int status_in, int length, - char *msg) + +static int send_reply(SrvJob *job, int replyType, int status_in, int length, char *msg) { + MDSDBG(SVRJOB_PRI " %d", SVRJOB_VAR(job), replyType); int status; -#ifndef _WIN32 - signal(SIGPIPE, SIG_IGN); - pthread_cleanup_push((void *)reset_sigpipe_handler, NULL); -#endif status = MDSplusERROR; SOCKET sock; long msg_len = msg ? (long)strlen(msg) : 0; - int try_again = TRUE; + int try_again = FALSE; + char reply[60]; + memset(reply, 0, 60); + sprintf(reply, "%d %d %d %ld", job->h.jobid, replyType, status_in, msg_len); do { errno = 0; sock = AttachPort(job->h.addr, (uint16_t)job->h.port); if (sock == INVALID_SOCKET) break; - char reply[60]; - int bytes; - memset(reply, 0, 60); - sprintf(reply, "%d %d %d %ld", job->h.jobid, replyType, status_in, msg_len); - bytes = send(sock, reply, 60, MSG_DONTWAIT); + int bytes = send_all(sock, reply, 60); if (bytes == 60) { - bytes = send(sock, msg, length, MSG_DONTWAIT); + bytes = send_all(sock, msg, length); if (bytes == length) { status = MDSplusSUCCESS; @@ -886,20 +949,16 @@ static int SendReply(SrvJob *job, int replyType, int status_in, int length, if (STATUS_NOT_OK) { try_again = errno == EPIPE; - if (Debug) + int debug; + pthread_mutex_lock(&STATIC_lock); + debug = STATIC_Debug; + pthread_mutex_unlock(&STATIC_lock); + if (debug) { - uint8_t *ip = (uint8_t *)&job->h.addr; - char now[32]; - Now32(now); - fprintf(stderr, "%s, Dropped connection to %u.%u.%u.%u:%u", now, - ip[0], ip[1], ip[2], ip[3], job->h.port); - perror(" "); + MDSMSG(SVRJOB_PRI " drop connection", SVRJOB_VAR(job)); } RemoveClient(job); } } while (try_again--); -#ifndef _WIN32 - pthread_cleanup_pop(1); -#endif return status; } diff --git a/servershr/ServerSendMessage.c b/servershr/ServerSendMessage.c index b3ea5393a6..d75bfbe23c 100644 --- a/servershr/ServerSendMessage.c +++ b/servershr/ServerSendMessage.c @@ -68,109 +68,28 @@ int ServerSendMessage(); #include #include #include +#include <_mdsshr.h> #include #define _NO_SERVER_SEND_MESSAGE_PROTO #include "servershrp.h" -#ifdef _WIN32 -#define random rand -#define SOCKERROR(...) \ - do \ - { \ - errno = WSAGetLastError(); \ - fprintf(stderr, __VA_ARGS__); \ - } while (0) -#else -#define SOCKERROR(...) fprintf(stderr, __VA_ARGS__) -#endif //#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif - -#define IP(addr) ((uint8_t *)&addr) -#define ADDR2IP(a) IP(a) \ - [0], IP(a)[1], IP(a)[2], IP(a)[3] +#include "Client.h" extern short ArgLen(); extern int GetAnswerInfoTS(); -/* - *typedef struct _Condition { - * pthread_cond_t cond; - * pthread_mutex_t mutex; - * int value; - *} Condition; - */ -typedef struct job -{ - struct job *next; - int jobid; - int conid; - int *retstatus; - pthread_rwlock_t *lock; - Condition *cond; - void (*ast)(); - void *astparam; - void (*before_ast)(); -} Job; -pthread_mutex_t jobs_mutex = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_JOBS \ - pthread_mutex_lock(&jobs_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &jobs_mutex) -#define UNLOCK_JOBS pthread_cleanup_pop(1) -#define UNLOCK_JOBS_REV \ - pthread_mutex_unlock(&jobs_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_lock, &jobs_mutex) -#define LOCK_JOBS_REV pthread_cleanup_pop(1) -static Job *Jobs = NULL; - -typedef struct _client -{ - SOCKET reply_sock; - int conid; - uint32_t addr; - uint16_t port; - struct _client *next; -} Client; -static pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER; -#define LOCK_CLIENTS \ - pthread_mutex_lock(&clients_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &clients_mutex) -#define UNLOCK_CLIENTS pthread_cleanup_pop(1) -#define UNLOCK_CLIENTS_REV \ - pthread_mutex_unlock(&clients_mutex); \ - pthread_cleanup_push((void *)pthread_mutex_lock, &clients_mutex) -#define LOCK_CLIENTS_REV pthread_cleanup_pop(1) -static Client *Clients = NULL; - -static int MonJob = -1; -static int JobId = 0; - -#define min(a, b) (((a) < (b)) ? (a) : (b)) -#define max(a, b) (((a) > (b)) ? (a) : (b)) int is_broken_socket(SOCKET socket); +EXPORT int ServerConnect(char *server); static int start_receiver(uint16_t *port); -int ServerConnect(char *server); -static int RegisterJob(int *msgid, int *retstatus, pthread_rwlock_t *lock, - void (*ast)(), void *astparam, void (*before_ast)(), - int conid); -static void CleanupJob(int status, int jobid); -static void ReceiverThread(void *sockptr); -static void DoMessage(Client *c, fd_set *fdactive); -static void RemoveClient(Client *c, fd_set *fdactive); -static void AddClient(uint32_t addr, uint16_t port, int send_sock); -static void AcceptClient(SOCKET reply_sock, struct sockaddr_in *sin, - fd_set *fdactive); +static void receiver_thread(void *sockptr); +static void accept_client(SOCKET reply_sock, struct sockaddr_in *sin, fd_set *fdactive); extern void *GetConnectionInfo(); -static SOCKET getSocket(int conid) + +static SOCKET get_socket_by_conid(int conid) { size_t len; char *info_name = NULL; @@ -182,16 +101,26 @@ static SOCKET getSocket(int conid) } int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, - pthread_rwlock_t *lock, int *conid_out, void (*ast)(), - void *astparam, void (*before_ast)(), int numargs_in, + pthread_rwlock_t *lock, int *conid_out, void (*callback_done)(), + void *callback_param, void (*callback_before)(), int numargs_in, ...) { uint16_t port = 0; - int conid; - if (start_receiver(&port) || ((conid = ServerConnect(server)) < 0)) + int conid = INVALID_CONNECTION_ID; + MDSDBG("%s", server); + const int receiver_err = start_receiver(&port); + if (receiver_err || ((conid = ServerConnect(server)) == INVALID_CONNECTION_ID)) { - if (ast && astparam) - ast(astparam); + if (receiver_err) + { + MDSWRN("failed to start receiver"); + } + else + { + MDSWRN("failed to connect"); + } + if (callback_done) + callback_done(callback_param); return ServerPATH_DOWN; } INIT_STATUS; @@ -200,7 +129,8 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, int i; uint32_t addr = 0; char cmd[4096]; - unsigned char numargs = max(0, min(numargs_in, 8)); + char *ccmd = cmd; + uint8_t numargs = numargs_in < 0 ? 0 : (numargs_in > 8 ? 8 : numargs_in); // minmax [0, 8] char dtype; char ndims; int dims[8]; @@ -211,27 +141,26 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, struct descrip *arg; if (conid_out) *conid_out = conid; - SOCKET sock = getSocket(conid); + SOCKET sock = get_socket_by_conid(conid); struct sockaddr_in addr_struct = {0}; socklen_t len = sizeof(addr_struct); if (getsockname(sock, (struct sockaddr *)&addr_struct, &len) == 0) addr = *(uint32_t *)&addr_struct.sin_addr; if (!addr) { - perror("Error getting the address the socket is bound to.\n"); - if (ast && astparam) - ast(astparam); + MDSWRN("could not resolve address the socket is bound to"); + if (callback_done) + callback_done(callback_param); return ServerSOCKET_ADDR_ERROR; } - jobid = RegisterJob(msgid, retstatus, lock, ast, astparam, before_ast, conid); - if (before_ast) + jobid = Job_register(msgid, conid, retstatus, lock, callback_done, callback_param, callback_before); + if (callback_before) flags |= SrvJobBEFORE_NOTIFY; - sprintf(cmd, "MdsServerShr->ServerQAction(%ulu,%uwu,%d,%d,%d", addr, port, op, - flags, jobid); + ccmd += sprintf(ccmd, "MdsServerShr->ServerQAction(%ulu,%uwu,%d,%d,%d", addr, port, op, flags, jobid); va_start(vlist, numargs_in); for (i = 0; i < numargs; i++) { - strcat(cmd, ","); + *ccmd++ = ','; arg = va_arg(vlist, struct descrip *); if (op == SrvMonitor && numargs == 8 && i == 5 && arg->dtype == DTYPE_LONG && *(int *)arg->ptr == MonitorCheckin) @@ -240,37 +169,35 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, { case DTYPE_CSTRING: { - int j, k; + int j; char *c = (char *)arg->ptr; int len = strlen(c); - strcat(cmd, "\""); - for (j = 0, k = strlen(cmd); j < len; j++, k++) + ccmd += sprintf(ccmd, "\""); + for (j = 0; j < len; j++) { if (c[j] == '"' || c[j] == '\\') - cmd[k++] = '\\'; - cmd[k] = c[j]; + *ccmd++ = '\\'; + *ccmd++ = c[j]; } - cmd[k] = 0; - strcat(cmd, "\""); + ccmd += sprintf(ccmd, "\""); break; } case DTYPE_LONG: - sprintf(&cmd[strlen(cmd)], "%d", *(int *)arg->ptr); + ccmd += sprintf(ccmd, "%d", *(int *)arg->ptr); break; case DTYPE_CHAR: - sprintf(&cmd[strlen(cmd)], "%d", (int)*(char *)arg->ptr); + ccmd += sprintf(ccmd, "%d", (int)*(char *)arg->ptr); break; default: - fprintf(stderr, "shouldn't get here! ServerSendMessage dtype = %d\n", - arg->dtype); + MDSWRN("unexpected dtype = %d", arg->dtype); } } - strcat(cmd, ")"); - status = SendArg(conid, 0, DTYPE_CSTRING, 1, (short)strlen(cmd), 0, 0, cmd); + *ccmd++ = ')'; + status = SendArg(conid, 0, DTYPE_CSTRING, 1, (short)(ccmd - cmd), 0, 0, cmd); if (STATUS_NOT_OK) { - perror("Error sending message to server"); - CleanupJob(status, jobid); + MDSWRN("could not sending message to server"); + Job_cleanup(status, jobid); return status; } status = GetAnswerInfoTS(conid, &dtype, &len, &ndims, dims, &numbytes, @@ -280,273 +207,36 @@ int ServerSendMessage(int *msgid, char *server, int op, int *retstatus, if (STATUS_NOT_OK) { status = MDSplusSUCCESS; - CleanupJob(status, jobid); + Job_cleanup(status, jobid); } else { status = MDSplusERROR; - CleanupJob(status, jobid); + Job_cleanup(status, jobid); } } else { if (STATUS_NOT_OK) { - perror("Error: no response from server"); - CleanupJob(status, jobid); + MDSWRN("no response from server"); + Job_cleanup(status, jobid); return status; } } free(mem); + MDSDBG("status=%d", status); return status; } -static inline void remove_job(Job *j_i) -{ - // only call this when cond is NULL - LOCK_JOBS; - Job *j, *p; - for (j = Jobs, p = NULL; j && j != j_i; p = j, j = j->next) - ; - if (!j) - return; - if (p) - p->next = j->next; - else - Jobs = j->next; - free(j); - UNLOCK_JOBS; -} - -static pthread_mutex_t job_conds = PTHREAD_MUTEX_INITIALIZER; - -static void doCompletionAst(Job *j, int status, char *msg, int removeJob) -{ - if (j->lock) - pthread_rwlock_wrlock(j->lock); - if (j->retstatus) - *j->retstatus = status; - if (j->lock) - pthread_rwlock_unlock(j->lock); - if (j->ast) - (*j->ast)(j->astparam, msg); - /**** If job has a condition, RemoveJob will not remove it. ***/ - pthread_mutex_lock(&job_conds); - pthread_cleanup_push((void *)pthread_mutex_unlock, &job_conds); - if (j->cond) - { - CONDITION_SET(j->cond); - } - else if (removeJob && j->jobid != MonJob) - { - remove_job(j); - DBG("Job #%d async done.\n", j->jobid); - } - pthread_cleanup_pop(1); -} -static inline Job *get_job_by_jobid(int jobid) -{ - Job *j; - LOCK_JOBS; - for (j = Jobs; j && j->jobid != jobid; j = j->next) - ; - UNLOCK_JOBS; - return j; -} -static Job *pop_job_by_jobid(int jobid) -{ - Job *j, *p; - LOCK_JOBS; - for (j = Jobs, p = NULL; j && j->jobid != jobid; p = j, j = j->next) - ; - if (j) - { - if (p) - p->next = j->next; - else - Jobs = j->next; - } - UNLOCK_JOBS; - return j; -} -static Job *pop_job_by_conid(int conid) -{ - Job *j, *p; - LOCK_JOBS; - for (j = Jobs, p = NULL; j && j->conid != conid; p = j, j = j->next) - ; - if (j) - { - if (p) - p->next = j->next; - else - Jobs = j->next; - } - UNLOCK_JOBS; - return j; -} -static inline int get_client_conid(Client *c, fd_set *fdactive) -{ - int client_found; - LOCK_CLIENTS; - client_found = 0; - if (Clients == c) - { - client_found = 1; - Clients = c->next; - } - else - { - Client *cp; - for (cp = Clients; cp && cp->next != c; cp = cp->next) - ; - if (cp && cp->next == c) - { - client_found = 1; - cp->next = c->next; - } - } - UNLOCK_CLIENTS; - if (client_found) - { - int conid = c->conid; - if (c->reply_sock != INVALID_SOCKET) - { - shutdown(c->reply_sock, 2); - close(c->reply_sock); - if (fdactive) - FD_CLR(c->reply_sock, fdactive); - } - if (c->conid >= 0) - DisconnectFromMds(c->conid); - free(c); - return conid; - } - return -1; -} -static void RemoveClient(Client *c, fd_set *fdactive) -{ - int conid = get_client_conid(c, fdactive); - for (;;) - { - Job *j = pop_job_by_conid(conid); - if (j) - { - doCompletionAst(j, ServerPATH_DOWN, NULL, FALSE); - free(j); - } - else - break; - } -} -static void CleanupJob(int status, int jobid) -{ - Job *j = pop_job_by_jobid(jobid); - if (j) - { - const int conid = j->conid; - DisconnectFromMds(conid); - doCompletionAst(j, status, NULL, FALSE); - free(j); - for (;;) - { - j = pop_job_by_conid(conid); - if (j) - { - doCompletionAst(j, status, NULL, FALSE); - free(j); - } - else - break; - } - } -} -static void abandon(void *in) -{ - Job *j = *(Job **)in; - pthread_mutex_lock(&job_conds); - pthread_cleanup_push((void *)pthread_mutex_unlock, &job_conds); - if (j && j->cond) - { - CONDITION_DESTROY_PTR(j->cond, &job_conds); - DBG("Job #%d sync abandoned!\n", j->jobid); - } - pthread_cleanup_pop(1); -} -static inline void wait_and_remove_job(Job *j) -{ - CONDITION_WAIT_SET(j->cond); - CONDITION_DESTROY_PTR(j->cond, &job_conds); - remove_job(j); -} -void ServerWait(int jobid) -{ - Job *j = get_job_by_jobid(jobid); - if (j && j->cond) - { - DBG("Job #%d sync pending.\n", jobid); - pthread_cleanup_push(abandon, (void *)&j); - wait_and_remove_job(j); - pthread_cleanup_pop(0); - DBG("Job #%d sync done.\n", jobid); - } - else - DBG("Job #%d sync lost!\n", jobid); -} - -static void DoBeforeAst(int jobid) -{ - Job *j; - void *astparam; - void (*before_ast)(); - LOCK_JOBS; - astparam = NULL; - before_ast = NULL; - for (j = Jobs; j && (j->jobid != jobid); j = j->next) - ; - if (j) - { - astparam = j->astparam; - before_ast = j->before_ast; - } - UNLOCK_JOBS; - if (before_ast) - before_ast(astparam); -} - -static int RegisterJob(int *msgid, int *retstatus, pthread_rwlock_t *lock, - void (*ast)(), void *astparam, void (*before_ast)(), - int conid) +EXPORT void ServerWait(int jobid) { - Job *j = (Job *)malloc(sizeof(Job)); - j->retstatus = retstatus; - j->lock = lock; - j->ast = ast; - j->astparam = astparam; - j->before_ast = before_ast; - j->conid = conid; - LOCK_JOBS; - j->jobid = ++JobId; - if (msgid) - { - j->cond = malloc(sizeof(Condition)); - CONDITION_INIT(j->cond); - *msgid = j->jobid; - DBG("Job #%d sync registered.\n", j->jobid); - } - else - { - j->cond = NULL; - DBG("Job #%d async registered.\n", j->jobid); - } - j->next = Jobs; - Jobs = j; - UNLOCK_JOBS; - return j->jobid; + if (Job_wait_and_pop_by_jobid(jobid)) + MDSDBG("Job(%d, ?) sync lost!", jobid); } DEFINE_INITIALIZESOCKETS; -static SOCKET CreatePort(uint16_t *port_out) +static SOCKET new_reply_socket(uint16_t *port_out) { static uint16_t start_port = 0, range_port; if (!start_port) @@ -570,48 +260,43 @@ static SOCKET CreatePort(uint16_t *port_out) if (!start_port) { start_port = 8800; - range_port = 256; + range_port = 200; } - DBG("Receiver will be using 'MDSIP_PORT_RANGE=%u-%u'.\n", start_port, - start_port + range_port - 1); + MDSDBG("Receiver will be using 'MDSIP_PORT_RANGE=%u-%u'.", start_port, + start_port + range_port - 1); } - uint16_t port; - static struct sockaddr_in sin; - long sendbuf = 6000, recvbuf = 6000; - SOCKET s; - int c_status = C_ERROR; - int tries = 0; int one = 1; INITIALIZESOCKETS; - s = socket(AF_INET, SOCK_STREAM, 0); + SOCKET s = socket(AF_INET, SOCK_STREAM, 0); if (s == INVALID_SOCKET) { - perror("Error getting Connection Socket\n"); + print_socket_error("Error getting Connection Socket"); return s; } - setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&recvbuf, sizeof(long)); - setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&sendbuf, sizeof(long)); - setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(int)); + setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)); + int c_status = C_ERROR; + static struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; - for (tries = 0; (c_status < 0) && (tries < 500); tries++) + uint16_t port = start_port; + const uint16_t end_port = start_port + range_port; + do { - port = start_port + (random() % range_port); sin.sin_port = htons(port); c_status = bind(s, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)); - } - if (c_status < 0) + } while (c_status && (++port != end_port)); + if (c_status) { - perror("Error binding to service\n"); + print_socket_error("Error binding to service\n"); return INVALID_SOCKET; } c_status = listen(s, 5); - if (c_status < 0) + if (c_status) { - perror("Error from listen\n"); + print_socket_error("Error from listen\n"); return INVALID_SOCKET; } - DBG("Listener opened on port %u.\n", port); + MDSDBG("Listener opened on port %u.", port); *port_out = port; return s; } @@ -627,16 +312,17 @@ static int start_receiver(uint16_t *port_out) _CONDITION_LOCK(&ReceiverRunning); if (port == 0) { - sock = CreatePort(&port); + sock = new_reply_socket(&port); if (sock == INVALID_SOCKET) { + MDSWRN("INVALID_SOCKET"); _CONDITION_UNLOCK(&ReceiverRunning); return C_ERROR; } } if (!ReceiverRunning.value) { - CREATE_DETACHED_THREAD(thread, *16, ReceiverThread, &sock); + CREATE_DETACHED_THREAD(thread, *16, receiver_thread, &sock); if (c_status) { perror("Error creating pthread"); @@ -653,19 +339,14 @@ static int start_receiver(uint16_t *port_out) return STATUS_NOT_OK; } -static void ReceiverExit(void *arg __attribute__((unused))) +static void receiver_atexit(void *arg) { - DBG("ServerSendMessage thread exitted\n"); + (void)arg; + MDSDBG("ServerSendMessage thread exitted"); CONDITION_RESET(&ReceiverRunning); } -static void _RemoveClient(Client *c) -{ - UNLOCK_CLIENTS_REV; - RemoveClient(c, NULL); - LOCK_CLIENTS_REV; -} -static void ResetFdactive(int rep, SOCKET sock, fd_set *active) +static void reset_fdactive(int rep, SOCKET server, fd_set *fdactive) { LOCK_CLIENTS; Client *c; @@ -675,39 +356,35 @@ static void ResetFdactive(int rep, SOCKET sock, fd_set *active) { if (is_broken_socket(c->reply_sock)) { - DBG("removed client in ResetFdactive\n"); - _RemoveClient(c); - c = Clients; + MDSWRN(CLIENT_PRI " removed", CLIENT_VAR(c)); + Client *o = c; + c = c->next; + Client_cleanup_jobs(o, fdactive); } else c = c->next; } } - FD_ZERO(active); - FD_SET(sock, active); + FD_ZERO(fdactive); + FD_SET(server, fdactive); for (c = Clients; c; c = c->next) { if (c->reply_sock != INVALID_SOCKET) - FD_SET(c->reply_sock, active); + FD_SET(c->reply_sock, fdactive); } UNLOCK_CLIENTS; - DBG("reset fdactive in ResetFdactive\n"); + MDSWRN("reset fdactive in reset_fdactive"); } -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wclobbered" -// fc21 claims 'last_client_port' is clobbered -static void ReceiverThread(void *sockptr) +static void receiver_thread(void *sockptr) { - atexit((void *)ReceiverExit); - CONDITION_SET(&ReceiverRunning); + atexit((void *)receiver_atexit); // CONDITION_SET(&ReceiverRunning); _CONDITION_LOCK(&ReceiverRunning); SOCKET sock = *(SOCKET *)sockptr; ReceiverRunning.value = B_TRUE; _CONDITION_SIGNAL(&ReceiverRunning); _CONDITION_UNLOCK(&ReceiverRunning); - CONDITION_SET(&ReceiverRunning); // \CONDITION_SET(&ReceiverRunning); struct sockaddr_in sin; uint32_t last_client_addr = 0; @@ -716,7 +393,7 @@ static void ReceiverThread(void *sockptr) FD_ZERO(&fdactive); FD_SET(sock, &fdactive); int rep; - struct timeval readto, timeout = {1, 0}; + struct timeval readto, timeout = {10, 0}; for (rep = 0; rep < 10; rep++) { for (readfds = fdactive, readto = timeout;; @@ -730,43 +407,47 @@ static void ReceiverThread(void *sockptr) if (FD_ISSET(sock, &readfds)) { socklen_t len = sizeof(struct sockaddr_in); - AcceptClient(accept(sock, (struct sockaddr *)&sin, &len), &sin, - &fdactive); + accept_client(accept(sock, (struct sockaddr *)&sin, &len), &sin, &fdactive); + num--; } - else { - Client *c, *next; + Client *c; for (;;) { LOCK_CLIENTS; - for (c = Clients, next = c ? c->next : 0; - c && (c->reply_sock == INVALID_SOCKET || - !FD_ISSET(c->reply_sock, &readfds)); - c = next, next = c ? c->next : 0) - ; + for (c = Clients; c; c = c->next) + { + if ((c->reply_sock != INVALID_SOCKET) && FD_ISSET(c->reply_sock, &readfds)) + { + last_client_addr = c->addr; + last_client_port = c->port; + break; + } + } UNLOCK_CLIENTS; if (c) { - SOCKET reply_sock = c->reply_sock; - last_client_addr = c->addr; - last_client_port = c->port; - DoMessage(c, &fdactive); - FD_CLR(reply_sock, &readfds); + FD_CLR(c->reply_sock, &readfds); + Client_do_message(c, &fdactive); + num--; } else + { + if (num) + MDSDBG("num not 0 but %d", num); break; + } } } } - SOCKERROR("Dispatcher select loop failed\nLast client: %u.%u.%u.%u:%u\n", - ADDR2IP(last_client_addr), last_client_port); - ResetFdactive(rep, sock, &fdactive); + print_socket_error("Dispatcher select loop failed\n"); + fprintf(stderr, "Last client: " IPADDRPRI ":%u\n", IPADDRVAR(&last_client_addr), last_client_port); + reset_fdactive(rep, sock, &fdactive); } fprintf(stderr, "Cannot recover from select errors in ServerSendMessage, exitting\n"); pthread_exit(0); } -#pragma GCC diagnostic pop int is_broken_socket(SOCKET socket) { @@ -781,190 +462,129 @@ int is_broken_socket(SOCKET socket) return B_TRUE; } -static Client *get_client(uint32_t addr, uint16_t port) +int get_addr_port(char *hostin, uint32_t *addrp, uint16_t *portp) { - Client *c; - LOCK_CLIENTS; - for (c = Clients; c && (c->addr != addr || c->port != port); c = c->next) - ; - UNLOCK_CLIENTS; - return c; -} - -static Client *get_addr_port(char *server, uint32_t *addrp, uint16_t *portp) -{ - uint32_t addr; - uint16_t port; - char hostpart[256] = {0}; - char portpart[256] = {0}; - int num = sscanf(server, "%[^:]:%s", hostpart, portpart); - if (num != 2) - { - DBG("Server '%s' unknown\n", server); - return NULL; + int err; + char *port = strchr(hostin, ':'); + struct sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_addr.s_addr = INADDR_ANY; + if (port) + { + int hostlen = port - hostin; + char *host = memcpy(malloc(hostlen + 1), hostin, hostlen); + FREE_ON_EXIT(host); + host[hostlen] = 0; + err = _LibGetHostAddr(host, port + 1, (struct sockaddr *)&sin); + FREE_NOW(host); + if (!err) + { + *portp = ntohs(sin.sin_port); + *addrp = sin.sin_addr.s_addr; + } } - addr = LibGetHostAddr(hostpart); - if (!addr) - return NULL; - if (strtol(portpart, NULL, 0) == 0) + else { - struct servent *sp = getservbyname(portpart, "tcp"); - if (sp) - port = sp->s_port; - else + err = _LibGetHostAddr(hostin, NULL, (struct sockaddr *)&sin); + if (!err) { - char *portnam = getenv(portpart); - portnam = (!portnam) ? ((hostpart[0] == '_') ? "8200" : "8000") : portnam; - port = htons((uint16_t)strtol(portnam, NULL, 0)); + *portp = 8000; + *addrp = sin.sin_addr.s_addr; } } - else - port = htons((uint16_t)strtol(portpart, NULL, 0)); - if (addrp) - *addrp = addr; - if (portp) - *portp = port; - return get_client(addr, port); + return err; } EXPORT int ServerDisconnect(char *server_in) { char *srv = TranslateLogical(server_in); char *server = srv ? srv : server_in; - Client *c = get_addr_port(server, NULL, NULL); + uint32_t addr; + uint16_t port; + const int err = get_addr_port(server, &addr, &port); free(srv); + if (err) + return MDSplusERROR; + int status; + LOCK_CLIENTS; + Client *c = Client_get_by_addr_and_port_locked(addr, port); if (c) { - RemoveClient(c, NULL); - return MDSplusSUCCESS; + MDSDBG(CLIENT_PRI, CLIENT_VAR(c)); + Client_remove_locked(c, NULL); + status = MDSplusSUCCESS; } - return MDSplusERROR; + else + { + status = MDSplusERROR; + } + UNLOCK_CLIENTS; + return status; } -EXPORT int ServerConnect(char *server_in) +static inline int server_connect(char *server, uint32_t addr, uint16_t port) { - int conid = -1; - char *srv = TranslateLogical(server_in); - char *server = srv ? srv : server_in; - uint32_t addr; - uint16_t port = 0; - Client *c = get_addr_port(server, &addr, &port); - if (c) + int conid; + LOCK_CLIENTS; + conid = ConnectToMds(server); + if (conid != INVALID_CONNECTION_ID) { - if (is_broken_socket(getSocket(c->conid))) - RemoveClient(c, NULL); - else - conid = c->conid; + Client *c = newClient(addr, port, conid); + MDSDBG(CLIENT_PRI " connected to %s", CLIENT_VAR(c), server); + Client_push_locked(c); } - if (port && conid == -1) + else { - conid = ConnectToMds(server); - if (conid >= 0) - AddClient(addr, port, conid); + MDSWRN("Could not connect to %s (" IPADDRPRI ":%d)", server, IPADDRVAR(&addr), port); } - free(srv); + UNLOCK_CLIENTS; return conid; } -static void DoMessage(Client *c, fd_set *fdactive) +EXPORT int ServerConnect(char *server_in) { - char reply[60]; - char *msg = 0; - int jobid; - int replyType; - int status; - int msglen; - int num; - int nbytes; - nbytes = recv(c->reply_sock, reply, 60, MSG_WAITALL); - if (nbytes != 60) - { - RemoveClient(c, fdactive); - return; - } - num = sscanf(reply, "%d %d %d %d", &jobid, &replyType, &status, &msglen); - if (num != 4) - { - RemoveClient(c, fdactive); - return; - } - FREE_ON_EXIT(msg); - if (msglen != 0) - { - msg = (char *)malloc(msglen + 1); - msg[msglen] = 0; - nbytes = recv(c->reply_sock, msg, msglen, MSG_WAITALL); - if (nbytes != msglen) - { - free(msg); - RemoveClient(c, fdactive); - return; - } - } - switch (replyType) - { - case SrvJobFINISHED: + + char *srv = TranslateLogical(server_in); + char *server = srv ? srv : server_in; + uint32_t addr; + uint16_t port = 0; + if (get_addr_port(server, &addr, &port)) { - Job *j = get_job_by_jobid(jobid); - if (!j) - j = get_job_by_jobid(MonJob); - if (j) - doCompletionAst(j, status, msg, TRUE); - break; + MDSWRN("Could not resolve %s", server); + free(srv); + return INVALID_CONNECTION_ID; } - case SrvJobSTARTING: - DoBeforeAst(jobid); - break; - case SrvJobCHECKEDIN: - break; - default: - RemoveClient(c, fdactive); - } - FREE_NOW(msg); -} - -static void AddClient(unsigned int addr, uint16_t port, int conid) -{ - Client *c; - Client *new = (Client *)malloc(sizeof(Client)); - new->reply_sock = INVALID_SOCKET; - new->conid = conid; - new->addr = addr; - new->port = port; - new->next = 0; - LOCK_CLIENTS; - for (c = Clients; c && c->next != 0; c = c->next) - ; - if (c) - c->next = new; - else - Clients = new; - UNLOCK_CLIENTS; - DBG("added connection from %u.%u.%u.%u\n", ADDR2IP(addr)); + int conid = server_connect(server, addr, port); + free(srv); + return conid; } -static void AcceptClient(SOCKET reply_sock, struct sockaddr_in *sin, - fd_set *fdactive) +static void accept_client(SOCKET reply_sock, struct sockaddr_in *sin, fd_set *fdactive) { if (reply_sock == INVALID_SOCKET) return; uint32_t addr = *(uint32_t *)&sin->sin_addr; + uint16_t port = ntohs(sin->sin_port); Client *c; LOCK_CLIENTS; - for (c = Clients; c && (c->addr != addr || c->reply_sock != INVALID_SOCKET); - c = c->next) - ; + for (c = Clients; c; c = c->next) + { + if (c->addr == addr && c->reply_sock == INVALID_SOCKET) + { + c->reply_sock = reply_sock; + break; + } + } UNLOCK_CLIENTS; if (c) { - c->reply_sock = reply_sock; FD_SET(reply_sock, fdactive); - DBG("accepted connection from %u.%u.%u.%u\n", ADDR2IP(addr)); + MDSDBG(CLIENT_PRI " accepted", CLIENT_VAR(c)); } else { + MDSWRN("Dropped connection from " IPADDRPRI ":%d", IPADDRVAR(&addr), port); shutdown(reply_sock, 2); close(reply_sock); - DBG("dropped connection from %u.%u.%u.%u\n", ADDR2IP(addr)); } } diff --git a/servershr/ServerSetDetailProc.c b/servershr/ServerSetDetailProc.c index b04ec0ed10..077a87c333 100644 --- a/servershr/ServerSetDetailProc.c +++ b/servershr/ServerSetDetailProc.c @@ -52,13 +52,23 @@ void (*)(struct dsc$descriptor *)SERVER$GET_DETAIL_PROC() Description: ------------------------------------------------------------------------------*/ - +#include #include +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static char *(*DetailProc)() = 0; EXPORT void ServerSetDetailProc(char *(*detail_proc)()) { + pthread_mutex_lock(&lock); DetailProc = detail_proc; + pthread_mutex_unlock(&lock); } -EXPORT char *(*ServerGetDetailProc())() { return DetailProc; } +EXPORT char *(*ServerGetDetailProc())() +{ + char *(*detail_proc)(); + pthread_mutex_lock(&lock); + detail_proc = DetailProc; + pthread_mutex_unlock(&lock); + return detail_proc; +} diff --git a/servershr/servershrp.h b/servershr/servershrp.h index 0db2a6a7e0..c1ff748c7b 100644 --- a/servershr/servershrp.h +++ b/servershr/servershrp.h @@ -74,11 +74,15 @@ typedef struct int flags; int jobid; } JHeader; +#define JHEADER_PRI "(op=%d, jobid=%d, addr=" IPADDRPRI ", port=%d)" +#define JHEADER_VAR(h) (h)->op, (h)->jobid, IPADDRVAR(&(h)->addr), (h)->port typedef struct _SrvJob { JHeader h; } SrvJob; +#define SVRJOB_PRI "SvrJob" JHEADER_PRI +#define SVRJOB_VAR(j) JHEADER_VAR(&(j)->h) typedef struct { @@ -87,11 +91,15 @@ typedef struct int shot; int nid; } SrvActionJob; +#define SVRACTIONJOB_PRI "SrvActionJob(" JHEADER_PRI ", tree='%s', shot=%d, nid=%d)" +#define SVRACTIONJOB_VAR(j) JHEADER_VAR(&(j)->h), (j)->tree, (j)->shot, (j)->nid typedef struct { JHeader h; } SrvCloseJob; +#define SVRCLOSEJOB_PRI "SrvCloseJob(" JHEADER_PRI ")" +#define SVRCLOSEJOB_VAR(j) JHEADER_VAR(&(j)->h) typedef struct { @@ -99,6 +107,8 @@ typedef struct char *tree; int shot; } SrvCreatePulseJob; +#define SVRCREATEPULSEJOB_PRI "SrvCreatePulseJob(" JHEADER_PRI ", tree='%s', shot=%d)" +#define SVRCREATEPULSEJOB_VAR(j) JHEADER_VAR(&(j)->h), (j)->tree, (j)->shot typedef struct { @@ -106,6 +116,8 @@ typedef struct char *table; char *command; } SrvCommandJob; +#define SVRCOMMANDJOB_PRI "SrvCommandJob(" JHEADER_PRI ", table='%s', command='%s')" +#define SVRCOMMANDJOB_VAR(j) JHEADER_VAR(&(j)->h), (j)->table, (j)->command typedef struct { @@ -119,6 +131,8 @@ typedef struct char *server; int status; } SrvMonitorJob; +#define SVRMONITORJOB_PRI "SrvMonitorJob(" JHEADER_PRI ", tree='%s', shot=%d, phase=%d, nid=%d, on=%d, mode=%d, server='%s', status=%d)" +#define SVRMONITORJOB_VAR(j) JHEADER_VAR(&(j)->h), (j)->tree, (j)->shot, (j)->phase, (j)->nid, (j)->on, (j)->mode, (j)->server, (j)->status typedef struct { diff --git a/tcl/tcl_delete_node.c b/tcl/tcl_delete_node.c index fd07ae68b0..405deb259a 100644 --- a/tcl/tcl_delete_node.c +++ b/tcl/tcl_delete_node.c @@ -102,7 +102,7 @@ EXPORT int TclDeleteNode(void *ctx, char **error, char **output) { ctx_fn = 0; while (TreeFindNodeWild(nodename, &nid, &ctx_fn, usageMask) & 1 && - (status & 1)) + (STATUS_OK)) { nids++; status = TreeDeleteNodeInitialize(nid, &count, reset); diff --git a/tcl/tcl_directory.c b/tcl/tcl_directory.c index b944d8b8af..deb9e7a0d1 100644 --- a/tcl/tcl_directory.c +++ b/tcl/tcl_directory.c @@ -311,7 +311,7 @@ static int doFull(char **output, int nid, unsigned char nodeUsage, int status; vers = version; status = TreeGetNci(nid, full_list); - if (status & 1) + if (STATUS_OK) { if (version == 0) { diff --git a/tcl/tcl_dispatch.c b/tcl/tcl_dispatch.c index 2ac6256120..1732fd6ac1 100644 --- a/tcl/tcl_dispatch.c +++ b/tcl/tcl_dispatch.c @@ -36,6 +36,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include "tcl_p.h" @@ -509,6 +510,7 @@ EXPORT int TclDispatch_command(void *ctx, char **error, CommandDone, c.cmd, iostatusp, NULL, 0); if (STATUS_NOT_OK) { + MDSMSG("ServerDispatchCommand failed."); char *msg = MdsGetMsg(status); *error = malloc(100 + strlen(msg)); sprintf(*error, diff --git a/tcl/tcl_help_device.c b/tcl/tcl_help_device.c index 32a17380f7..6d08853844 100644 --- a/tcl/tcl_help_device.c +++ b/tcl/tcl_help_device.c @@ -38,7 +38,7 @@ EXPORT int tcl_help_device(void *ctx, char **error __attribute__((unused)), char *ans; int status = TdiExecute(&expr_d, &ans_d MDS_END_ARG); free(expr); - if ((status & 1) && (ans_d.pointer != NULL)) + if ((STATUS_OK) && (ans_d.pointer != NULL)) { if ((ans_d.pointer->dtype == DTYPE_T) && (ans_d.pointer->length > 0)) { diff --git a/tcl/tcl_set_callbacks.c b/tcl/tcl_set_callbacks.c index 167a814c71..a3c044ca23 100644 --- a/tcl/tcl_set_callbacks.c +++ b/tcl/tcl_set_callbacks.c @@ -28,7 +28,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include #include #include "tcl_p.h" @@ -64,10 +63,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static void (*ErrorOut)(); static void (*TextOut)(); -STATIC_ROUTINE void (*NodeTouched)(); -STATIC_THREADSAFE char *saved_output = 0; -STATIC_THREADSAFE pthread_mutex_t saved_output_mutex; -STATIC_THREADSAFE int initialized = 0; +static void (*NodeTouched)(); +static char *saved_output = 0; +static pthread_mutex_t saved_output_mutex; +static int initialized = 0; /*************************************************************** * TclSetCallbacks: @@ -105,7 +104,7 @@ EXPORT void TclNodeTouched( /* Returns: void */ (*NodeTouched)(nid, type); } -STATIC_ROUTINE void AppendOut(char *text) +static void AppendOut(char *text) { char *msg = text ? text : ""; size_t len = strlen(msg); @@ -128,7 +127,7 @@ STATIC_ROUTINE void AppendOut(char *text) pthread_mutex_unlock(&saved_output_mutex); } -STATIC_ROUTINE void StatusOut(int status) { AppendOut(MdsGetMsg(status)); } +static void StatusOut(int status) { AppendOut(MdsGetMsg(status)); } EXPORT void TclSaveOut() { diff --git a/tcl/tcl_set_node.c b/tcl/tcl_set_node.c index 02f3fd00ef..c92de0b28e 100644 --- a/tcl/tcl_set_node.c +++ b/tcl/tcl_set_node.c @@ -82,7 +82,7 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) { case MdsdclPRESENT: status = TreeSetSubtree(nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); @@ -95,7 +95,7 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) break; case MdsdclNEGATED: status = TreeSetNoSubtree(nid); - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(nodename) + strlen(msg) + 100); @@ -107,12 +107,12 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) } break; } - if (!(status & 1)) + if (STATUS_NOT_OK) goto error; if (cli_present(ctx, "ON") & 1) { status = TreeTurnOn(nid); - if (status & 1) + if (STATUS_OK) TclNodeTouched(nid, on_off); else { @@ -128,7 +128,7 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) else if (cli_present(ctx, "OFF") & 1) { status = TreeTurnOff(nid); - if (status & 1) + if (STATUS_OK) TclNodeTouched(nid, on_off); else { @@ -237,7 +237,7 @@ EXPORT int TclSetNode(void *ctx, char **error, char **output) status = TreeSetNci(nid, set_itmlst); if (clear_flags) status = TreeSetNci(nid, clear_itmlst); - if (status & 1) + if (STATUS_OK) { if (log) { diff --git a/tcl/tcl_set_readonly.c b/tcl/tcl_set_readonly.c index 1c39158205..c7ebbd5d39 100644 --- a/tcl/tcl_set_readonly.c +++ b/tcl/tcl_set_readonly.c @@ -45,7 +45,7 @@ EXPORT int TclSetReadonly(void *ctx, char **error, * Executable ... *-------------------------------------------------------*/ status = TreeSetDbiItm(DbiREADONLY, (cli_present(ctx, "OFF") & 1) == 0); - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); diff --git a/tcl/tcl_set_tree.c b/tcl/tcl_set_tree.c index 018c72e655..da54c54ea5 100644 --- a/tcl/tcl_set_tree.c +++ b/tcl/tcl_set_tree.c @@ -59,7 +59,7 @@ int tclStringToShot(char *str, int *shot_out, char **error) DESCRIPTOR_LONG(dsc_shot, &shot); struct descriptor str_d = {strlen(str), DTYPE_T, CLASS_S, str}; status = TdiExecute(&str_d, &dsc_shot MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { *error = malloc(strlen(str) + 100); sprintf(*error, @@ -69,7 +69,7 @@ int tclStringToShot(char *str, int *shot_out, char **error) } } } - if ((status & 1) && (shot < -1)) + if ((STATUS_OK) && (shot < -1)) { *error = malloc(100); sprintf(*error, "Error: Invalid shot number specified - %d\n", shot); @@ -78,7 +78,7 @@ int tclStringToShot(char *str, int *shot_out, char **error) } else *error = strdup("Error: Zero length shot string specified\n"); - if (status & 1) + if (STATUS_OK) *shot_out = shot; return status; } diff --git a/tcl/tcl_set_view.c b/tcl/tcl_set_view.c index 6c3474a140..567e235871 100644 --- a/tcl/tcl_set_view.c +++ b/tcl/tcl_set_view.c @@ -59,7 +59,7 @@ EXPORT int TclSetView(void *ctx, char **error, { status = TreeSetViewDate(&viewDate); } - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 200); diff --git a/tcl/tcl_setshow_attribute.c b/tcl/tcl_setshow_attribute.c index 0e2d3f96a7..3a5b1628a7 100644 --- a/tcl/tcl_setshow_attribute.c +++ b/tcl/tcl_setshow_attribute.c @@ -64,16 +64,16 @@ EXPORT int TclShowAttribute(void *ctx, char **error, char **output) struct descriptor_d dsc_string = {0, DTYPE_T, CLASS_D, 0}; cli_get_value(ctx, "NODE", &node); status = TreeFindNode(node, &nid); - if (status & 1) + if (STATUS_OK) { status = cli_get_value(ctx, "NAME", &attr); - if (status & 1) + if (STATUS_OK) { status = TreeGetXNci(nid, attr, &xd); - if (status & 1) + if (STATUS_OK) { status = TdiDecompile(&xd, &dsc_string MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { *output = strncpy(malloc(dsc_string.length + 100), dsc_string.pointer, dsc_string.length); @@ -116,7 +116,7 @@ EXPORT int TclShowAttribute(void *ctx, char **error, char **output) status = 1; } } - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + strlen(node) + 100); diff --git a/tcl/tcl_setshow_versions.c b/tcl/tcl_setshow_versions.c index d1aaceae38..1bd9aae2ad 100644 --- a/tcl/tcl_setshow_versions.c +++ b/tcl/tcl_setshow_versions.c @@ -53,7 +53,7 @@ EXPORT int TclSetVersions(void *ctx, char **error, status = TreeSetDbiItm(DbiVERSIONS_IN_MODEL, 0); break; } - if (!(status & 1)) + if (STATUS_NOT_OK) goto error; switch (cli_present(ctx, "SHOT")) { @@ -65,7 +65,7 @@ EXPORT int TclSetVersions(void *ctx, char **error, break; } error: - if (!(status & 1)) + if (STATUS_NOT_OK) { char *msg = MdsGetMsg(status); *error = malloc(strlen(msg) + 100); @@ -86,7 +86,7 @@ EXPORT int TclShowVersions(void *ctx __attribute__((unused)), {4, DbiVERSIONS_IN_PULSE, &in_pulse, 0}, {0, 0, 0, 0}}; status = TreeGetDbi(itmlst); - if (status & 1) + if (STATUS_OK) { *output = malloc(500); sprintf(*output, diff --git a/tcl/tcl_wfevent.c b/tcl/tcl_wfevent.c index 0a1cc19c3a..c492fe7f7d 100644 --- a/tcl/tcl_wfevent.c +++ b/tcl/tcl_wfevent.c @@ -60,7 +60,7 @@ EXPORT int TclWfevent(void *ctx, char **error, if (seconds > 0) { status = MDSWfeventTimed(event, 0, 0, 0, seconds); - if (!(status & 1)) + if (STATUS_NOT_OK) *error = strdup("Timeout\n"); } else diff --git a/tdic/TdiShrExt.c b/tdic/TdiShrExt.c index 0173509b3c..331a5954bc 100644 --- a/tdic/TdiShrExt.c +++ b/tdic/TdiShrExt.c @@ -70,10 +70,6 @@ extern int ReuseCheck(char *hostin, char *unique, size_t buflen); #define LOCAL "local" #define STRLEN 4096 #define INVALID_ID -1 -/* Variables that stay set between calls */ -static int id = INVALID_ID; /* Mark the conid as unopen */ -static char serv[STRLEN]; /* Current server */ -static EMPTYXD(ans_xd); /* Connection record */ typedef struct _connection @@ -84,6 +80,11 @@ typedef struct _connection char serv[STRLEN]; /* Current server */ struct _connection *next; } Connection; +/* Variables that stay set between calls */ + +static int id = INVALID_ID; /* Mark the conid as unopen */ +static char serv[STRLEN]; /* Current server */ +static EMPTYXD(ans_xd); static Connection *Connections = NULL; /* Routine definitions */ @@ -250,8 +251,7 @@ EXPORT int rMdsConnect(char *hostin) if (!strcmp(host, LOCAL)) { strcpy(serv, LOCAL); - id = INVALID_ID; - return (id); + return INVALID_ID; } /* If no conid, or server name has changed */ if ((id == INVALID_ID) || strcmp(host, serv)) @@ -259,7 +259,7 @@ EXPORT int rMdsConnect(char *hostin) if ((id = AddConnection(hostin)) == INVALID_ID) { *serv = '\0'; - return (0); /* no connection obtained */ + return id; /* no connection obtained */ } else { @@ -369,7 +369,7 @@ EXPORT struct descriptor_xd *rMdsValue(struct descriptor *expression, ...) #endif tdiarg = expression; /* first in list (corresponding to string) */ /* Cycle through the arguments */ - for (i = 0; (i < nargs) && (status & 1); i++) + for (i = 0; (i < nargs) && (STATUS_OK); i++) { #ifdef DEBUG printf("idx[%d] dtype[%d] nargs[%d]\n", i, tdiarg->dtype, nargs); diff --git a/tdic/tdic.c b/tdic/tdic.c index 98ea56f594..92161e7e54 100644 --- a/tdic/tdic.c +++ b/tdic/tdic.c @@ -379,7 +379,7 @@ int main(int argc, char **argv) expr[expr_dsc.length++] = ')'; */ status = BTdiExecute(&expr_dsc, &ans MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { if (!comment) BTdiExecute(&clear_errors, &output_unit, &ans, &ans MDS_END_ARG); diff --git a/tdishr/CvtConvertFloat.c b/tdishr/CvtConvertFloat.c index df0e13ea4d..ad0771ed05 100644 --- a/tdishr/CvtConvertFloat.c +++ b/tdishr/CvtConvertFloat.c @@ -590,11 +590,11 @@ extern EXPORT CVT_STATUS CvtConvertFloat(void *input_value, uint32_t input_type, ** Cray floating point ** ** The input value pointed to by *input_value will be interpreted as being -** of type input_type (types are defined in CVTDEF.H). CvtConvertFloat +** of type input_type. CvtConvertFloat ** will convert *input_value to output_type and store the result in ** *output_value. The conversion may be influenced by several options. ** The options are specified by setting specific bits in the options -** parameter (these bits are also defined in CVTDEF.H). +** parameter. ** ** INPUT PARAMETERS: ** diff --git a/tdishr/TdiCall.c b/tdishr/TdiCall.c index 0db735847d..397e5b6c38 100644 --- a/tdishr/TdiCall.c +++ b/tdishr/TdiCall.c @@ -112,29 +112,58 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") return 1; } -int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +int get_routine(int narg, mdsdsc_t *list[], int (**proutine)()) { - INIT_STATUS; - mds_function_t *pfun; - mdsdsc_xd_t image = EMPTY_XD, entry = EMPTY_XD, tmp[255]; - int j, max = 0, ntmp = 0, (*routine)(); - char result[8] = {0}; // we need up to 8 bytes - unsigned short code; - mdsdsc_t *newdsc[256] = {0}; - mdsdsc_t dx = {0, rtype == DTYPE_C ? DTYPE_T : rtype, CLASS_S, result}; - unsigned char origin[255]; + mdsdsc_xd_t image = EMPTY_XD, entry = EMPTY_XD; if (narg > 255 + 2) - status = TdiNDIM_OVER; - else - status = TdiData(list[0], &image MDS_END_ARG); + return TdiNDIM_OVER; + int status = TdiData(list[0], &image MDS_END_ARG); if (STATUS_OK) status = TdiData(list[1], &entry MDS_END_ARG); if (STATUS_OK) - status = TdiFindImageSymbol(image.pointer, entry.pointer, &routine); + status = TdiFindImageSymbol(image.pointer, entry.pointer, proutine); if (STATUS_NOT_OK) printf("%s\n", LibFindImageSymbolErrString()); MdsFree1Dx(&entry, NULL); MdsFree1Dx(&image, NULL); + return status; +} + +typedef struct cleanup_tdi_call +{ + int count; + mdsdsc_xd_t xds[255]; +} cleanup_tdi_call_t; + +static void cleanup_tdi_call(void *arg) +{ + cleanup_tdi_call_t *c = (cleanup_tdi_call_t *)arg; + int i; + for (i = 0; i < c->count; ++i) + { + MdsFree1Dx(&c->xds[i], NULL); + } +} +#define CUR_POS (c->count - 1) +#define CUR_XD c->xds[CUR_POS] +#define NEW_XD() \ + do \ + { \ + c->xds[(c->count++)] = EMPTY_XD; \ + } while (0) + +int tdi_call(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr, cleanup_tdi_call_t *c) +{ + int (*routine)(); + int status = get_routine(narg, list, &routine); + RETURN_IF_STATUS_NOT_OK; + mds_function_t *pfun; + int j, max = 0; + char result[8] = {0}; // we need up to 8 bytes + unsigned short code; + mdsdsc_t dx = {0, rtype == DTYPE_C ? DTYPE_T : rtype, CLASS_S, result}; + unsigned char origin[255]; + mdsdsc_t *newdsc[256] = {0}; *(int *)&newdsc[0] = narg - 2; for (j = 2; j < narg && STATUS_OK; ++j) { @@ -146,25 +175,25 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) code = *(unsigned short *)pfun->pointer; if (code == OPC_DESCR) { - tmp[ntmp] = EMPTY_XD; - status = TdiData(pfun->arguments[0], &tmp[ntmp] MDS_END_ARG); - newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer; - origin[ntmp++] = (unsigned char)j; + NEW_XD(); + origin[CUR_POS] = (unsigned char)j; + status = TdiData(pfun->arguments[0], &CUR_XD MDS_END_ARG); + newdsc[j - 1] = (mdsdsc_t *)CUR_XD.pointer; } else if (code == OPC_REF) { - tmp[ntmp] = EMPTY_XD; - status = TdiData(pfun->arguments[0], &tmp[ntmp] MDS_END_ARG); - if (tmp[ntmp].pointer) + NEW_XD(); + origin[CUR_POS] = (unsigned char)j; + status = TdiData(pfun->arguments[0], &CUR_XD MDS_END_ARG); + if (CUR_XD.pointer) { - if (tmp[ntmp].pointer->dtype == DTYPE_T) + if (CUR_XD.pointer->dtype == DTYPE_T) { DESCRIPTOR(zero, "\0"); - TdiConcat(&tmp[ntmp], &zero, &tmp[ntmp] MDS_END_ARG); + TdiConcat(&CUR_XD, &zero, &CUR_XD MDS_END_ARG); } - newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer->pointer; + newdsc[j - 1] = (mdsdsc_t *)CUR_XD.pointer->pointer; } - origin[ntmp++] = (unsigned char)j; } else if (code == OPC_VAL) { @@ -184,11 +213,9 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) } else if (code == OPC_XD) { - tmp[ntmp] = EMPTY_XD; - status = - TdiEvaluate(pfun->arguments[0], - newdsc[j - 1] = (mdsdsc_t *)&tmp[ntmp] MDS_END_ARG); - origin[ntmp++] = (unsigned char)j; + NEW_XD(); + origin[CUR_POS] = (unsigned char)j; + status = TdiEvaluate(pfun->arguments[0], newdsc[j - 1] = (mdsdsc_t *)&CUR_XD MDS_END_ARG); } else goto fort; @@ -199,10 +226,11 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) else { fort: - tmp[ntmp] = EMPTY_XD; + NEW_XD(); + origin[CUR_POS] = (unsigned char)j; if (list[j]) - status = TdiData(list[j], &tmp[ntmp] MDS_END_ARG); - newdsc[j - 1] = tmp[ntmp].pointer; + status = TdiData(list[j], &CUR_XD MDS_END_ARG); + newdsc[j - 1] = CUR_XD.pointer; if (newdsc[j - 1]) { if (newdsc[j - 1]->dtype != DTYPE_T) @@ -210,11 +238,10 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) else { DESCRIPTOR(zero_dsc, "\0"); - TdiConcat(&tmp[ntmp], &zero_dsc, &tmp[ntmp] MDS_END_ARG); - newdsc[j - 1] = (mdsdsc_t *)tmp[ntmp].pointer->pointer; + TdiConcat(&CUR_XD, &zero_dsc, &CUR_XD MDS_END_ARG); + newdsc[j - 1] = (mdsdsc_t *)CUR_XD.pointer->pointer; } } - origin[ntmp++] = (unsigned char)j; } } if (STATUS_OK) @@ -276,7 +303,7 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) if (rtype == DTYPE_C) free(*(char **)result); // free result skip: - for (j = 0; j < ntmp; ++j) + for (j = 0; j <= CUR_POS; ++j) { for (pfun = (mds_function_t *)list[origin[j]]; pfun && pfun->dtype == DTYPE_DSC;) @@ -287,10 +314,19 @@ int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) if (code == OPC_DESCR || code == OPC_REF || code == OPC_XD) pfun = (mds_function_t *)pfun->arguments[0]; if (pfun && pfun->dtype == DTYPE_IDENT) - tdi_put_ident(pfun, &tmp[j]); + tdi_put_ident(pfun, &c->xds[j]); } - if (tmp[j].pointer) - MdsFree1Dx(&tmp[j], NULL); } return status; } + +int TdiCall(dtype_t rtype, int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) +{ + int status; + cleanup_tdi_call_t c; + c.count = 0; + pthread_cleanup_push(cleanup_tdi_call, (void *)&c); + status = tdi_call(rtype, narg, list, out_ptr, &c); + pthread_cleanup_pop(1); + return status; +} \ No newline at end of file diff --git a/tdishr/TdiCompile.c b/tdishr/TdiCompile.c index 1af4d5294b..2781904b3a 100644 --- a/tdishr/TdiCompile.c +++ b/tdishr/TdiCompile.c @@ -48,14 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "tdilex.h" #define YY_END_OF_BUFFER_CHAR '\0' -#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif +// #define DEBUG +#include extern int Tdi1Evaluate(); extern int tdi_yacc(); diff --git a/tdishr/TdiDoTask.c b/tdishr/TdiDoTask.c index 4509d91ede..c4fa1d87f5 100644 --- a/tdishr/TdiDoTask.c +++ b/tdishr/TdiDoTask.c @@ -229,8 +229,11 @@ static int StartWorker(struct descriptor_xd *task_xd, { fflush(stdout); fprintf(stderr, "Timeout, terminating Worker .."); - pthread_cancel(Worker); - _CONDITION_WAIT_1SEC(wa.condition, ); +#ifdef WIN32 + if (pthread_cancel(Worker)) +#endif + pthread_kill(Worker, SIGINT); + _CONDITION_WAIT_1SEC(wa.condition); fflush(stdout); if (WorkerRunning.value) { diff --git a/tdishr/TdiExtPython.c b/tdishr/TdiExtPython.c index e07f27b47c..07b9aa4cd4 100644 --- a/tdishr/TdiExtPython.c +++ b/tdishr/TdiExtPython.c @@ -37,8 +37,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include //#define DEBUG +#include #ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) #define DEBUG_GIL_CHECK \ if (PyGILState_Check) \ fprintf(stderr, \ @@ -46,9 +46,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (uintptr_t)pthread_self(), (uintptr_t)GIL, \ "ny"[PyGILState_Check() != 0]); #else -#define DBG(...) \ - { /**/ \ - } #define DEBUG_GIL_CHECK #endif @@ -185,7 +182,7 @@ inline static void initialize() free(lib); return; } - DBG("TdiExtPython: loaded %s\n", lib); + MDSDBG("TdiExtPython: loaded %s\n", lib); free(lib); loadrtn(Py_InitializeEx, 1); } @@ -247,8 +244,8 @@ inline static void initialize() static void PyGILState_Cleanup(void *GIL) { - DBG("PyGILState_Cleanup(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, - (uintptr_t)pthread_self()); + MDSDBG("PyGILState_Cleanup(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, + (uintptr_t)pthread_self()); if (PyGILState_Check && PyGILState_Check()) { fprintf(stderr, @@ -259,20 +256,20 @@ static void PyGILState_Cleanup(void *GIL) } } -#define PYTHON_OPEN \ - if (PyGILState_Ensure) \ - { \ - PyThreadState *GIL = PyGILState_Ensure(); \ - DBG("PyGILState_Ensured(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ - (uintptr_t)pthread_self()); \ +#define PYTHON_OPEN \ + if (PyGILState_Ensure) \ + { \ + PyThreadState *GIL = PyGILState_Ensure(); \ + MDSDBG("PyGILState_Ensured(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ + (uintptr_t)pthread_self()); \ pthread_cleanup_push(PyGILState_Cleanup, (void *)GIL); //" -#define PYTHON_CLOSE \ - PyGILState_Release(GIL); \ - DBG("PyGILState_Released(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ - (uintptr_t)pthread_self()); \ - pthread_cleanup_pop(0); \ - DEBUG_GIL_CHECK; \ +#define PYTHON_CLOSE \ + PyGILState_Release(GIL); \ + MDSDBG("PyGILState_Released(0x%" PRIxPTR ") 0x%" PRIxPTR "\n", (uintptr_t)GIL, \ + (uintptr_t)pthread_self()); \ + pthread_cleanup_pop(0); \ + DEBUG_GIL_CHECK; \ } //" static void importMDSplus() diff --git a/tdishr/TdiGetData.c b/tdishr/TdiGetData.c index 1d7a63ca01..8b71f3b215 100644 --- a/tdishr/TdiGetData.c +++ b/tdishr/TdiGetData.c @@ -198,20 +198,31 @@ int TdiImpose(mdsdsc_a_t *in_ptr, mdsdsc_xd_t *out_ptr) */ static const mdsdsc_t missing_dsc = {0, DTYPE_MISSING, CLASS_S, 0}; +typedef struct get_data_cleanup +{ + mdsdsc_xd_t *out; + mdsdsc_xd_t hold; +} get_data_cleanup_t; +static void get_data_cleanup(void *arg) +{ + get_data_cleanup_t *c = (get_data_cleanup_t *)arg; + MdsFree1Dx(c->out, NULL); + MdsFree1Dx(&c->hold, NULL); +} static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, - mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) + mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG); +static int _get_data(const dtype_t omits[], mdsdsc_t *their_ptr, + mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) { int nid, *pnid; dtype_t dtype = 0; mds_signal_t *keep; - mdsdsc_xd_t hold = EMPTY_XD; mdsdsc_r_t *pin = (mdsdsc_r_t *)their_ptr; INIT_STATUS; TDI_GETDATA_REC++; if (TDI_GETDATA_REC > 1800) { - status = TdiRECURSIVE; - goto end; + return TdiRECURSIVE; } while (pin && (dtype = pin->dtype) == DTYPE_DSC) { @@ -219,175 +230,175 @@ static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, TDI_GETDATA_REC++; if (TDI_GETDATA_REC > 1800) { - status = TdiRECURSIVE; - goto end; + return TdiRECURSIVE; } } if (!pin) - status = MdsCopyDxXd(&missing_dsc, &hold); - else { - int i; - for (i = 0; omits[i] && omits[i] != dtype; i++) - ; - if (omits[i]) - status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); - else - switch (pin->class) + return MdsCopyDxXd(&missing_dsc, out_ptr); + } + int i; + for (i = 0; omits[i]; i++) + { + if (omits[i] == dtype) + { + return MdsCopyDxXd((mdsdsc_t *)pin, out_ptr); + } + } + switch (pin->class) + { + case CLASS_CA: + if (pin->pointer) + { + status = get_data(omits, (mdsdsc_t *)pin->pointer, out_ptr, TDITHREADSTATIC_VAR); + /* Why is this needed????????????? */ + RETURN_IF_STATUS_NOT_OK; + return TdiImpose((mdsdsc_a_t *)pin, out_ptr); + /***********************************/ + } + return MdsCopyDxXd((mdsdsc_t *)pin, out_ptr); + case CLASS_APD: + return TdiEvaluate(pin, out_ptr MDS_END_ARG); + case CLASS_S: + case CLASS_D: + case CLASS_A: + /*********************** + Evaluate on these types. + ***********************/ + switch (dtype) + { + case DTYPE_IDENT: + status = tdi_get_ident(pin, out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_NID: + pnid = (int *)pin->pointer; + status = TdiGetRecord(*pnid, out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_PATH: + { + char *path = MdsDescrToCstring((mdsdsc_t *)pin); + status = TreeFindNode(path, &nid); + MdsFree(path); + RETURN_IF_STATUS_NOT_OK; + status = TdiGetRecord(nid, out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + } + default: + /************************************** + VMS types come here. Renames their XD. + *************************************/ + if (their_ptr->class == CLASS_XD) { - case CLASS_CA: - if (pin->pointer) - { - status = get_data(omits, (mdsdsc_t *)pin->pointer, &hold, - TDITHREADSTATIC_VAR); - /********************* Why is this needed????????????? - * *************************************/ - if (STATUS_OK) - status = TdiImpose((mdsdsc_a_t *)pin, &hold); - /***************************************************************************************/ - } - else - status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); - break; - case CLASS_APD: - status = TdiEvaluate(pin, &hold MDS_END_ARG); - break; - case CLASS_S: - case CLASS_D: - case CLASS_A: - switch (dtype) - { - /*********************** - Evaluate on these types. - ***********************/ - case DTYPE_IDENT: - status = tdi_get_ident(pin, &hold); - redo: - if (STATUS_OK) - status = - get_data(omits, (mdsdsc_t *)&hold, &hold, TDITHREADSTATIC_VAR); - break; - case DTYPE_NID: - pnid = (int *)pin->pointer; - status = TdiGetRecord(*pnid, &hold); - goto redo; - case DTYPE_PATH: - { - char *path = MdsDescrToCstring((mdsdsc_t *)pin); - status = TreeFindNode(path, &nid); - MdsFree(path); - if (STATUS_OK) - status = TdiGetRecord(nid, &hold); - } - goto redo; - /************************************** - VMS types come here. Renames their XD. - *************************************/ - default: - if (their_ptr->class == CLASS_XD) - { - hold = *(mdsdsc_xd_t *)their_ptr; - *(mdsdsc_xd_t *)their_ptr = EMPTY_XD; - } - else - status = MdsCopyDxXd((mdsdsc_t *)pin, &hold); - break; - } - break; - case CLASS_R: - switch (dtype) - { - case DTYPE_FUNCTION: - status = TdiIntrinsic(*(opcode_t *)pin->pointer, pin->ndesc, - pin->dscptrs, &hold); - goto redo; - case DTYPE_CALL: - status = TdiCall(pin->length ? *(dtype_t *)pin->pointer : DTYPE_L, - pin->ndesc, pin->dscptrs, &hold); - goto redo; - case DTYPE_PARAM: - keep = (mds_signal_t *)TDI_SELF_PTR; - TDI_SELF_PTR = (mdsdsc_xd_t *)pin; - status = get_data(omits, (mdsdsc_t *)((mds_param_t *)pin)->value, - &hold, TDITHREADSTATIC_VAR); - TDI_SELF_PTR = (mdsdsc_xd_t *)keep; - break; - case DTYPE_SIGNAL: - /****************************************** - We must set up for reference to our $VALUE. - ******************************************/ - keep = (mds_signal_t *)TDI_SELF_PTR; - TDI_SELF_PTR = (mdsdsc_xd_t *)pin; - status = get_data(omits, (mdsdsc_t *)((mds_signal_t *)pin)->data, - &hold, TDITHREADSTATIC_VAR); - TDI_SELF_PTR = (mdsdsc_xd_t *)keep; - break; - /*************** - Windowless axis. - ***************/ - case DTYPE_SLOPE: - { - int seg; - EMPTYXD(times); - for (seg = 0; (status & 1) && (seg < pin->ndesc / 3); seg++) - { - mdsdsc_t *args[] = {*(pin->dscptrs + (seg * 3 + 1)), - *(pin->dscptrs + (seg * 3 + 2)), - *(pin->dscptrs + (seg * 3))}; - status = TdiIntrinsic(OPC_DTYPE_RANGE, 3, &args, ×); - if (STATUS_OK) - { - args[0] = (mdsdsc_t *)&hold; - args[1] = (mdsdsc_t *)× - status = TdiIntrinsic(OPC_VECTOR, 2, &args, &hold); - } - } - goto redo; - } - case DTYPE_DIMENSION: - status = TdiItoX(pin, &hold MDS_END_ARG); - goto redo; - /************************** - Range can have 2 or 3 args. - **************************/ - case DTYPE_RANGE: - status = TdiIntrinsic(OPC_DTYPE_RANGE, pin->ndesc, &pin->dscptrs[0], - &hold); - goto redo; - case DTYPE_WITH_UNITS: - status = get_data(omits, (mdsdsc_t *)((mds_with_units_t *)pin)->data, - &hold, TDITHREADSTATIC_VAR); - break; - case DTYPE_WITH_ERROR: - status = get_data(omits, (mdsdsc_t *)((mds_with_error_t *)pin)->data, - &hold, TDITHREADSTATIC_VAR); - break; - case DTYPE_OPAQUE: - status = get_data(omits, (mdsdsc_t *)((mds_opaque_t *)pin)->data, - &hold, TDITHREADSTATIC_VAR); - break; - default: - status = TdiINVCLADTY; - break; - } - break; - default: - status = TdiINVCLADSC; - break; + *out_ptr = *(mdsdsc_xd_t *)their_ptr; + *(mdsdsc_xd_t *)their_ptr = EMPTY_XD; + return status; + } + else + return MdsCopyDxXd((mdsdsc_t *)pin, out_ptr); + } + break; + case CLASS_R: + switch (dtype) + { + case DTYPE_FUNCTION: + status = TdiIntrinsic(*(opcode_t *)pin->pointer, pin->ndesc, + pin->dscptrs, out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_CALL: + status = TdiCall(pin->length ? *(dtype_t *)pin->pointer : DTYPE_L, + pin->ndesc, pin->dscptrs, out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_PARAM: + keep = (mds_signal_t *)TDI_SELF_PTR; + TDI_SELF_PTR = (mdsdsc_xd_t *)pin; + status = get_data(omits, (mdsdsc_t *)((mds_param_t *)pin)->value, + out_ptr, TDITHREADSTATIC_VAR); + TDI_SELF_PTR = (mdsdsc_xd_t *)keep; + return status; + case DTYPE_SIGNAL: + /****************************************** + We must set up for reference to our $VALUE. + ******************************************/ + keep = (mds_signal_t *)TDI_SELF_PTR; + TDI_SELF_PTR = (mdsdsc_xd_t *)pin; + status = get_data(omits, (mdsdsc_t *)((mds_signal_t *)pin)->data, + out_ptr, TDITHREADSTATIC_VAR); + TDI_SELF_PTR = (mdsdsc_xd_t *)keep; + return status; + case DTYPE_SLOPE: + { + /*************** + Windowless axis. + ***************/ + int seg; + EMPTYXD(times); + for (seg = 0; (seg < pin->ndesc / 3); seg++) + { + mdsdsc_t *args[] = {*(pin->dscptrs + (seg * 3 + 1)), + *(pin->dscptrs + (seg * 3 + 2)), + *(pin->dscptrs + (seg * 3))}; + status = TdiIntrinsic(OPC_DTYPE_RANGE, 3, &args, ×); + RETURN_IF_STATUS_NOT_OK; + args[0] = (mdsdsc_t *)out_ptr; + args[1] = (mdsdsc_t *)× + status = TdiIntrinsic(OPC_VECTOR, 2, &args, out_ptr); + RETURN_IF_STATUS_NOT_OK; } + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + } + case DTYPE_DIMENSION: + status = TdiItoX(pin, out_ptr MDS_END_ARG); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_RANGE: + /************************** + Range can have 2 or 3 args. + **************************/ + status = TdiIntrinsic(OPC_DTYPE_RANGE, pin->ndesc, &pin->dscptrs[0], + out_ptr); + RETURN_IF_STATUS_NOT_OK; + return get_data(omits, (mdsdsc_t *)out_ptr, out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_WITH_UNITS: + return get_data(omits, (mdsdsc_t *)((mds_with_units_t *)pin)->data, + out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_WITH_ERROR: + return get_data(omits, (mdsdsc_t *)((mds_with_error_t *)pin)->data, + out_ptr, TDITHREADSTATIC_VAR); + case DTYPE_OPAQUE: + return get_data(omits, (mdsdsc_t *)((mds_opaque_t *)pin)->data, + out_ptr, TDITHREADSTATIC_VAR); + default: + return TdiINVCLADTY; + } + break; + default: + return TdiINVCLADSC; } - /********************************** - Watch out for input same as output. - **********************************/ - MdsFree1Dx(out_ptr, NULL); + return status; +} + +static int get_data(const dtype_t omits[], mdsdsc_t *their_ptr, + mdsdsc_xd_t *out_ptr, TDITHREADSTATIC_ARG) +{ + int status; + get_data_cleanup_t c = {out_ptr, MDSDSC_XD_INITIALIZER}; + pthread_cleanup_push(get_data_cleanup, (void *)&c); + status = _get_data(omits, their_ptr, &c.hold, TDITHREADSTATIC_VAR); + MdsFree1Dx(c.out, NULL); if (STATUS_OK) - *out_ptr = hold; + *out_ptr = c.hold; else - MdsFree1Dx(&hold, NULL); -end:; + MdsFree1Dx(&c.hold, NULL); + pthread_cleanup_pop(0); TDI_GETDATA_REC = 0; return status; } + int tdi_get_data(const dtype_t omits[], mdsdsc_t *their_ptr, mdsdsc_xd_t *out_ptr) { diff --git a/tdishr/TdiSubscript.c b/tdishr/TdiSubscript.c index e1e23ad29d..806449a35b 100644 --- a/tdishr/TdiSubscript.c +++ b/tdishr/TdiSubscript.c @@ -342,7 +342,8 @@ int Tdi1Subscript(opcode_t opcode, int narg, struct descriptor *list[], pin -= len * *px[0]; row = arr.m[0] * sizeof(int); inner: - for (j = 0; j < row; j += sizeof(int)) { + for (j = 0; j < row; j += sizeof(int)) + { memcpy(pout, pin + len * *(int *)((char *)px[0] + j), len); pout += len; } diff --git a/tdishr/TdiVar.c b/tdishr/TdiVar.c index 86ba73c847..3021547494 100644 --- a/tdishr/TdiVar.c +++ b/tdishr/TdiVar.c @@ -73,18 +73,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // #define DEBUG -#ifdef DEBUG -#define DBG(...) \ - do \ - { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stdout, __VA_ARGS__); \ - } while (0) -#else -#define DBG(...) \ - { \ - } -#endif +#include extern int TdiFaultHandler(); extern int TdiData(); @@ -765,7 +754,7 @@ static int compile_fun(const mdsdsc_t *const entry, const char *const file) return TdiUNKNOWN_VAR; int status; INIT_AND_FREEXD_ON_EXIT(tmp); - DBG("compile: %s\n", file); + MDSDBG("compile: %s\n", file); FILE *unit = fopen(file, "rb"); if (unit) { @@ -1338,7 +1327,7 @@ int Tdi1ShowPrivate(opcode_t opcode __attribute__((unused)), int narg, mdsdsc_t *list[], mdsdsc_xd_t *out_ptr) { TDITHREADSTATIC_INIT; - DBG("TdiShowPrivate: %" PRIxPTR "\n", (uintptr_t)(void *)_private.head); + MDSDBG("TdiShowPrivate: %" PRIxPTR "\n", (uintptr_t)(void *)_private.head); return wild((int (*)())show_one, narg, list, &_private, out_ptr, TDITHREADSTATIC_VAR); } @@ -1369,7 +1358,7 @@ extern EXPORT int TdiSaveContext(void *ptr[6]) ptr[4] = _public.head_zone; ptr[5] = _public.data_zone; UNLOCK_PUBLIC; - DBG("TdiSaveContext: %" PRIxPTR "\n", (uintptr_t)ptr[0]); + MDSDBG("TdiSaveContext: %" PRIxPTR "\n", (uintptr_t)ptr[0]); return 1; } @@ -1397,7 +1386,7 @@ extern EXPORT int TdiDeleteContext(void *ptr[6]) extern EXPORT int TdiRestoreContext(void *const ptr[6]) { TDITHREADSTATIC_INIT; - DBG("TdiRestoreContext: %" PRIxPTR "\n", (uintptr_t)ptr[0]); + MDSDBG("TdiRestoreContext: %" PRIxPTR "\n", (uintptr_t)ptr[0]); _private.head = (node_type *)ptr[0]; _private.head_zone = ptr[1]; _private.data_zone = ptr[2]; diff --git a/tdishr/TdiYaccSubs.c b/tdishr/TdiYaccSubs.c index d6048e0a6c..67bb21f1fc 100644 --- a/tdishr/TdiYaccSubs.c +++ b/tdishr/TdiYaccSubs.c @@ -40,13 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include //#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif +#include extern int Tdi1Build(); extern int TdiEvaluate(); @@ -179,10 +173,10 @@ int tdi_yacc_IMMEDIATE(mdsdsc_xd_t **dsc_ptr_ptr, TDITHREADSTATIC_ARG) ptr = (mdsdsc_xd_t *)ptr->pointer; ++TDI_STACK_IDX; - DBG("TDI_STACK_IDX = %d\n", TDI_STACK_IDX); + MDSDBG("TDI_STACK_IDX = %d\n", TDI_STACK_IDX); int status = TdiEvaluate(ptr, &xd MDS_END_ARG); --TDI_STACK_IDX; - DBG("TDI_STACK_IDX = %d\n", TDI_STACK_IDX); + MDSDBG("TDI_STACK_IDX = %d\n", TDI_STACK_IDX); /******************* Copy it to our zone. diff --git a/tdishr/cvtdef.h b/tdishr/cvtdef.h deleted file mode 100644 index 6d5bcee803..0000000000 --- a/tdishr/cvtdef.h +++ /dev/null @@ -1,52 +0,0 @@ -/********************************************************************************************************************************/ -/* Created: 28-DEC-1995 08:04:14 by OpenVMS SDL EV1-33 */ -/* Source: 28-DEC-1995 08:03:53 HARPO$DKA400:[SYS0.SYSUPD.CC052]CVTDEF.SDI;1 */ -/********************************************************************************************************************************/ -/*** MODULE cvtdef ***/ -#ifndef __CVTDEF_LOADED -#define __CVTDEF_LOADED 1 - -#ifndef _MSC_VER -#pragma nostandard -#endif - -#ifdef __cplusplus -extern "C" -{ -#define __unknown_params ... -#else -#define __unknown_params -#endif - -#if !defined(__VAXC) && !defined(VAXC) -#define __struct struct -#define __union union -#else -#define __struct variant_struct -#define __union variant_union -#endif - -#define CvtVAX_F 10 /* VAX F Floating point data */ -#define CvtVAX_D 11 /* VAX D Floating point data */ -#define CvtVAX_G 27 /* VAX G Floating point data */ -#define CvtVAX_H 28 /* VAX H Floating point data */ -#define CvtIEEE_S 52 /* IEEE S Floating point data */ -#define CvtIEEE_T 53 /* IEEE T Floating point data */ -#define CvtIBM_LONG 6 /* IBM Long Floating point data */ -#define CvtIBM_SHORT 7 /* IBM Short Floating point data */ -#define CvtCRAY 8 /* Cray Floating point data */ -#define CvtIEEE_X 9 /* IEEE X Floating point data */ - - extern unsigned long CvtConvertFloat(void *input_v, unsigned long input_t, - void *output_v, unsigned long output_t, - ...); - -#ifdef __cplusplus -} -#endif - -#ifndef _MSC_VER -#pragma standard -#endif - -#endif /* __CVTDEF_LOADED */ diff --git a/tdishr/tdirefstandard.h b/tdishr/tdirefstandard.h index 8f8d5bc858..059348ef98 100644 --- a/tdishr/tdirefstandard.h +++ b/tdishr/tdirefstandard.h @@ -8,7 +8,7 @@ #include #include -static struct descriptor_xd const EMPTY_XD = {0, DTYPE_DSC, CLASS_XD, 0, 0}; +static struct descriptor_xd const EMPTY_XD = MDSDSC_XD_INITIALIZER; #define TdiRefStandard(name) \ int name(int opcode, int narg, struct descriptor *list[], \ diff --git a/tditest/testing/do_tditests.sh b/tditest/testing/do_tditests.sh index 78c71380f4..07a9ae95e4 100755 --- a/tditest/testing/do_tditests.sh +++ b/tditest/testing/do_tditests.sh @@ -3,12 +3,12 @@ TMP_LD_PRELOAD="$LD_PRELOAD" unset LD_PRELOAD test=$(basename "$1") test=${test%.tdi} -if [[ "$TMP_LD_PRELOAD" == *"libtsan.so"* ]] && [[ "$test" == "test-dev-py" ]] -then echo "test-dev-py hangs in Tcl('add node a12/model=a12') @ tsan" ;exit 77 +if [[ "$TMP_LD_PRELOAD" == *"libtsan.so"* ]] && [[ "$test" == "test-dev-py" ]]; then + echo "test-dev-py hangs in Tcl('add node a12/model=a12') @ tsan" + exit 77 fi srcdir=$(readlink -f $(dirname ${0})) -if [ "$OS" == "windows" ] -then +if [ "$OS" == "windows" ]; then zdrv="Z:" PYTHON="wine python" TDITEST="wine tditest" @@ -22,82 +22,76 @@ fi status=0 -if [ ! -z $1 ] -then +run() { + eval $1 2>&1 | tee ${2-/dev/null} | + grep -v -e '^[DIWE],' \ + -e '^\s*Data inserted:' \ + -e 'Length:' +} -if [[ "$test" == *"tab"* ]] -then - cmd="$TDITEST < $srcdir/$test.tdi" - # fixes [?1034h for old readline verisons, rhel5/6/7, fc17/18/20 - export TERM=vt100 -else - cmd="$TDITEST $zdrv$srcdir/$test.tdi 1 2 3" -fi +if [ ! -z $1 ]; then + if [[ "$test" == *"tab"* ]]; then + cmd="$TDITEST < $srcdir/$test.tdi" + # fixes [?1034h for old readline verisons, rhel5/6/7, fc17/18/20 + export TERM=vt100 + else + cmd="$TDITEST $zdrv$srcdir/$test.tdi 1 2 3" + fi -if [ -z ${MDSPLUS_DIR} ] -then MDSPLUS_DIR=$(readlink -f ${srcdir}/../..) -fi -# use tmpdir tobisolate shotdb.sys -tmpdir=$(mktemp -d) -trap 'rm -Rf ${tmpdir}' EXIT -MDS_PATH=".;${MDSPLUS_DIR}/tdi;." -MDS_PYDEVICE_PATH="${MDSPLUS_DIR}/pydevices;${MDSPLUS_DIR}/python/MDSplus/tests/devices" -subtree_path="${tmpdir};${MDSPLUS_DIR}/trees/subtree" -main_path="${tmpdir};${MDSPLUS_DIR}/trees" + if [ -z ${MDSPLUS_DIR} ]; then + MDSPLUS_DIR=$(readlink -f ${srcdir}/../..) + fi + # use tmpdir tobisolate shotdb.sys + tmpdir=$(mktemp -d) + trap 'rm -Rf ${tmpdir}' EXIT + MDS_PATH=".;${MDSPLUS_DIR}/tdi;." + MDS_PYDEVICE_PATH="${MDSPLUS_DIR}/pydevices;${MDSPLUS_DIR}/python/MDSplus/tests/devices" + subtree_path="${tmpdir};${MDSPLUS_DIR}/trees/subtree" + main_path="${tmpdir};${MDSPLUS_DIR}/trees" -if [[ $test == *"py"* ]] -then - LD_PRELOAD="$TMP_LD_PRELOAD" - if [ -z $PyLib ] - then echo no python lib;exit 77 + if [[ $test == *"py"* ]]; then + LD_PRELOAD="$TMP_LD_PRELOAD" + if [ -z $PyLib ]; then + echo no python lib + exit 77 + fi fi -fi -if [[ $test == *"dev"* ]] -then - found=0 - for path in ${LD_LIBRARY_PATH//:/ }; do - if [ -e $path/libMitDevices.so ] - then found=1 + if [[ $test == *"dev"* ]]; then + found=0 + for path in ${LD_LIBRARY_PATH//:/ }; do + if [ -e $path/libMitDevices.so ]; then + found=1 + fi + done + if [ $found == 0 ]; then + echo no libMitDevices.so + exit 77 fi - done - if [ $found == 0 ] - then echo no libMitDevices.so;exit 77 fi -fi -if [ -e ./shotid.sys ];then rm -f ./shotid.sys; fi -if [ -e ./tditst.tmp ];then rm -f ./tditst.tmp; fi -LSAN_OPTIONS="$LSAN_OPTIONS,print_suppressions=0" \ + if [ -e ./shotid.sys ]; then rm -f ./shotid.sys; fi + if [ -e ./tditst.tmp ]; then rm -f ./tditst.tmp; fi + LSAN_OPTIONS="$LSAN_OPTIONS,print_suppressions=0" -if [ "$2" == "update" ] - then - eval $cmd 2>&1 \ - | grep -v 'Data inserted:' \ - | grep -v 'Length:' \ - > ${srcdir}/$test.ans - else - unset ok - if diff --help | grep side-by-side &>/dev/null - then - eval $cmd 2>&1 | tee ${test}-out.log \ - | grep -v 'Data inserted:' \ - | grep -v 'Length:' \ - | diff $DIFF_Z --side-by-side -W128 /dev/stdin $srcdir/$test.ans \ - | expand | grep -E -C3 '^.{61} ([|>]\s|<$)' || ok=1 - else - eval $cmd 2>&1 \ - | grep -v 'Data inserted:' \ - | grep -v 'Length:' \ - | diff $DIFF_Z /dev/stdin $srcdir/$test.ans && ok=1 - fi - echo ok=$ok - if [ -z $ok ] - then - echo "FAIL: $test" - exit 1 + if [ "$2" == "update" ]; then + run "${cmd}" >"${srcdir}/$test.ans" else - echo "PASS: $test" - rm -f $test-diff.log - exit 0 + unset ok + if diff --help | grep side-by-side &>/dev/null; then + run "${cmd}" "${test}-out.log" | + diff $DIFF_Z --side-by-side -W128 /dev/stdin ${srcdir}/$test.ans | + expand | grep -E -C3 '^.{61} ([|>]\s|<$)' || ok=1 + else + run "${cmd}" "${test}-out.log" | + diff $DIFF_Z /dev/stdin ${srcdir}/$test.ans && ok=1 + fi + echo ok=$ok + if [ -z $ok ]; then + echo "FAIL: $test" + exit 1 + else + echo "PASS: $test" + rm -f $test-diff.log + exit 0 + fi fi - fi fi diff --git a/tditest/testing/test-mdsip.ans b/tditest/testing/test-mdsip.ans index 73e354604e..d7288f9014 100644 --- a/tditest/testing/test-mdsip.ans +++ b/tditest/testing/test-mdsip.ans @@ -1,5 +1,5 @@ mdsconnect("local://1") -1 +0 mdsvalue("$",[1,2,3]) [1,2,3] mdsvalue("DECOMPILE($)",[[1,2],[3,4]]) diff --git a/tditest/testing/test-tcl.ans b/tditest/testing/test-tcl.ans index aec2589727..f59b21bf22 100644 --- a/tditest/testing/test-tcl.ans +++ b/tditest/testing/test-tcl.ans @@ -260,7 +260,7 @@ Tcl('show db') 265389633 Tcl('show server gub') Checking server: gub -Error connecting to server +Could not resolve server 2752521 Tcl('verify') Node summary: @@ -283,7 +283,7 @@ Tcl('delete pulse 1') 265389633 _status=Tcl(['set tree main','dir','close'],_out,_err) 265389633 -write(*,"output=",_out,"error=",_err),_status +write(*,"output=",_out,"error=",_err),_status output= diff --git a/tditest/testing/test-tcl.tdi b/tditest/testing/test-tcl.tdi index 2ea4409f7f..9dcb1a65fd 100644 --- a/tditest/testing/test-tcl.tdi +++ b/tditest/testing/test-tcl.tdi @@ -83,7 +83,7 @@ Tcl('close') Tcl('set tree main') Tcl('delete pulse 1') _status=Tcl(['set tree main','dir','close'],_out,_err) -write(*,"output=",_out,"error=",_err),_status +write(*,"output=",_out,"error=",_err),_status tcl('# comment shebang') tcl(' ! comment') tcl('@abc ! file') diff --git a/testing/Makefile.am b/testing/Makefile.am index edd916de87..7ff4500784 100644 --- a/testing/Makefile.am +++ b/testing/Makefile.am @@ -53,17 +53,18 @@ endif PYTHON_TEST_DIRS = \ python/MDSplus/tests -C_TEST_DIRS = \ - mdsshr/testing \ - treeshr/testing \ - mdslib/testing \ - mdsobjects/cpp/testing \ - tditest/testing +C_TEST_DIRS =\ + mdsshr/testing\ + treeshr/testing\ + mdslib/testing\ + mdstcpip/testing\ + tditest/testing\ + mdsobjects/cpp/testing # testing/selftest -TEST_DIRS ?= \ - $(PYTHON_TEST_DIRS) \ - $(C_TEST_DIRS) \ +TEST_DIRS ?=\ + $(C_TEST_DIRS)\ + $(PYTHON_TEST_DIRS)\ $(JAVA_TEST_DIRS) TEST_OUTDIR ?= ${top_builddir}/testing diff --git a/testing/helgrind b/testing/helgrind index 490f5a15f4..3964bd4ded 100755 --- a/testing/helgrind +++ b/testing/helgrind @@ -10,5 +10,6 @@ exec valgrind --tool=helgrind --history-level=full\ --gen-suppressions=all --num-callers=64\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ + --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ $suppressions\ "$@" diff --git a/testing/memcheck b/testing/memcheck index 487ad4f81a..a22c731000 100755 --- a/testing/memcheck +++ b/testing/memcheck @@ -10,5 +10,6 @@ exec valgrind --tool=memcheck --leak-check=full --show-reachable=no\ --gen-suppressions=all --num-callers=64\ --trace-children-skip='*/ld,*/collect2,*/ldconfig,*/sh'\ --trace-children=yes --child-silent-after-fork=yes\ + --trace-children-skip-by-arg='*SetMdsplusFileProtection*'\ $suppressions\ "$@" diff --git a/traverser/CallbacksUil.c b/traverser/CallbacksUil.c index 4f6d6695f9..d5ece22257 100644 --- a/traverser/CallbacksUil.c +++ b/traverser/CallbacksUil.c @@ -415,7 +415,7 @@ static ListTreeItem *insert_item(Widget tree, ListTreeItem *parent, int nid) int parent_nid = get_nid(parent); char *name = get_node_name(parent_nid); status = TreeGetDefaultNid(&def_nid); - if ((status & 1) && (parent_nid == def_nid)) + if ((STATUS_OK) && (parent_nid == def_nid)) { char *tmp = malloc(strlen(name) + 3 + 3 + 1); strcpy(tmp, "<<<"); @@ -531,7 +531,7 @@ static void set_default(Widget w, ListTreeItem *item) ListTreeRenameItem(tree, default_item, name); } status = TreeSetDefaultNid(nid); - if (status & 1) + if (STATUS_OK) { char *name = get_node_name(nid); char *new_name = malloc(strlen(name) + 3 + 3 + 1); @@ -560,7 +560,7 @@ static void Init(Widget tree) item = add_item(tree, NULL, 0); /* add the top with no parent */ default_item = 0; status = TreeGetDefaultNid(&nid); - if (status & 1) + if (STATUS_OK) { item = Open(tree, nid); set_default(tree, item); @@ -621,7 +621,7 @@ static void CommandLineOpen(Display *display __attribute__((unused)), } else status = TreeOpen(options.tree, options.shot, options.read_only); - if (status & 1) + if (STATUS_OK) Init(tree); } } @@ -796,12 +796,12 @@ static void TCLOutput(char *text) static void InitializeCommandInterface(Widget w) { int status = mdsdcl_do_command("set command tcl"); - if (status & 1) + if (STATUS_OK) { int (*set_callbacks)() = NULL; status = LibFindImageSymbol_C("tcl_commands", "TclSetCallbacks", &set_callbacks); - if (status & 1) + if (STATUS_OK) status = set_callbacks(TCLOutput, TCLOutput, NodeTouched); } toplevel = BxFindTopShell(w); @@ -1035,7 +1035,7 @@ void DeleteNodeNow(Widget w, XtPointer client_data __attribute__((unused)), TreeDeleteNodeExecute(); status = TreeGetDefaultNid(&def_nid); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) def_nid = 0; for (i = 0; i < NUM_TO_DELETE; i++) { @@ -1113,7 +1113,7 @@ void DeleteNode(Widget w, XtPointer client_data __attribute__((unused)), void RenameNodeNow(Widget w, XtPointer client_data, XtPointer call_data __attribute__((unused))) { - int nid = (int)((char *)client_data - (char *)0); + int nid = (int)(intptr_t)client_data; Widget tree = XtNameToWidget(BxFindTopShell(toplevel), "*.tree"); Widget tw = XtNameToWidget(w, "*.new_name"); char *new_name = (char *)XmTextFieldGetString(tw); @@ -1121,7 +1121,7 @@ void RenameNodeNow(Widget w, XtPointer client_data, int status; parent = parent_nid(nid); status = TreeRenameNode(nid, new_name); - if (status & 1) + if (STATUS_OK) { int new_parent = parent_nid(nid); if (new_parent != parent) @@ -1166,7 +1166,7 @@ void RenameNode(Widget w, XtPointer client_data __attribute__((unused)), }; Widget qdlog; Widget widg; - ok_callback_list[0].closure = (char *)0 + nid; + ok_callback_list[0].closure = (void *)(intptr_t)nid; qargs[0].value = (long)XmStringCreateLtoR("Rename node", XmSTRING_DEFAULT_CHARSET); qargs[1].value = @@ -1392,7 +1392,7 @@ void CloseTree(Widget w, XtPointer client_data __attribute__((unused)), { int status = TreeClose(NULL, 0); ListTreeRefreshOff(tree); - if ((status & 1) && (top != NULL)) + if ((STATUS_OK) && (top != NULL)) ListTreeDelete(tree, top); Init(tree); ListTreeRefreshOn(tree); @@ -1412,12 +1412,12 @@ void WriteTree(Widget w, XtPointer client_data, } else status = TreeQuitTree(0, 0); - if (status & 1) + if (STATUS_OK) { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *top = ListTreeFirstItem(tree); ListTreeRefreshOff(tree); - if ((status & 1) && (top != NULL)) + if ((STATUS_OK) && (top != NULL)) ListTreeDelete(tree, top); Init(tree); ListTreeRefreshOn(tree); @@ -1452,7 +1452,7 @@ void CreateTree(Widget w, XtPointer client_data __attribute__((unused)), status = TreeOpenNew(treeid->tree, treeid->shot); free(treeid->tree); free(treeid); - if (status & 1) + if (STATUS_OK) { Widget tree = TREE; ListTreeItem *top = ListTreeFirstItem(tree); @@ -1479,7 +1479,7 @@ void open_tree(Widget w, char *tree, int shot) Widget r_o = XtNameToWidget(BxFindTopShell(w), "*.r_o_toggle"); status = TreeOpen(tree, shot, XmToggleButtonGetState(r_o)); } - if (status & 1) + if (STATUS_OK) { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); ListTreeItem *top = ListTreeFirstItem(tree); @@ -1609,7 +1609,7 @@ Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, notify_on = FALSE; status = TreeAddConglom(full_path, device_type, &new_nid); notify_on = TRUE; - if (!(status & 1)) + if (STATUS_NOT_OK) XmdsComplain(BxFindTopShell(w), "Error adding device"); } else @@ -1619,15 +1619,15 @@ Boolean add_node(Widget w, ListTreeItem *parent, char *name, int usage, else { status = TreeAddNode(full_path, &new_nid, usage); - if (!(status & 1)) + if (STATUS_NOT_OK) XmdsComplain(BxFindTopShell(w), "Error adding node"); } - if (status & 1) + if (STATUS_OK) { Widget tree = XtNameToWidget(BxFindTopShell(w), "*.tree"); *itm = insert_item(tree, parent, new_nid); } - return status & 1; + return STATUS_OK; } void add_tags(ListTreeItem *itm __attribute__((unused)), @@ -1802,7 +1802,7 @@ static Boolean TagsApply(Widget w, int nid) if (tag_txt) { status = TreeAddTag(nid, tag_txt); - if (!(status & 1)) + if (STATUS_NOT_OK) { retstatus = status; XmdsComplain(toplevel, "Error Adding tag\n%s", tag_txt); diff --git a/traverser/GetSupportedDevices.c b/traverser/GetSupportedDevices.c index 0b5ea7533a..b22dff500e 100644 --- a/traverser/GetSupportedDevices.c +++ b/traverser/GetSupportedDevices.c @@ -39,7 +39,7 @@ int GetSupportedDevices(char ***devnames, int *number) *number = 0; *devnames = 0; status = TdiExecute((struct descriptor *)&expr, &dev_list MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { int i; struct descriptor_a *a_ptr = (struct descriptor_a *)dev_list.pointer; diff --git a/treeshr/RemoteAccess.c b/treeshr/RemoteAccess.c index 017e4e2060..19ac223359 100644 --- a/treeshr/RemoteAccess.c +++ b/treeshr/RemoteAccess.c @@ -45,11 +45,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define F_OFD_SETLKW 38 #endif #endif -#include #include -#include #include #include +#include +#include +#include +#include +#include + +#include #include #include #include @@ -57,23 +62,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include -#include -#include -#include -#include + #include #include "treeshrp.h" +#include "treethreadstatic.h" -//#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - do \ - { \ - } while (0) -#endif +// #define DEBUG +#include <_mdsshr.h> static inline char *replaceBackslashes(char *filename) { @@ -83,227 +78,95 @@ static inline char *replaceBackslashes(char *filename) return filename; } -typedef struct +static int remote_connect(char *server, int inc_count) { - int conid; - int connections; - char *unique; -#ifdef USE_TIME - time_t time; -#endif -} host_t; - -typedef struct host_list -{ - struct host_list *next; - host_t h; -} host_list_t; - -static host_list_t *host_list = NULL; -static int host_list_armed = FALSE; -static pthread_mutex_t host_list_lock = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t host_list_sig = PTHREAD_COND_INITIALIZER; -#define HOST_LIST_LOCK \ - pthread_mutex_lock(&host_list_lock); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &host_list_lock); -#define HOST_LIST_UNLOCK pthread_cleanup_pop(1); -/** host_list_cleanup - * Can be colled to cleanup unused connections in host_list. - * Meant to be called by host_list_clean_main() with conid = -1 - * Can be called by remote_access_disconnect() with conid>=0, - * in which case it will only disconnect the desired connection. - */ -static void host_list_cleanup(const int conid) -{ - static int (*disconnectFromMds)(int) = NULL; - if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "DisconnectFromMds", - &disconnectFromMds))) - perror("Error loading MdsIpShr->DisconnectFromMds in host_list_cleanup"); - host_list_t *host, *prev = NULL; - for (host = host_list; host;) +#define CONMSG(TYP, PRI, ...) TYP("Host(conid=%d, links=?, unique='%s'), server='%s'" PRI, conid, unique, server, __VA_ARGS__) + int conid = -1; + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, ReuseCheck, return conid, int, (char *, char *, int)); + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, ConnectToMds, return conid, int, (char *)); + char unique[128] = ""; + if (ReuseCheck(server, unique, 128) < 0) { - if (conid >= 0 && host->h.conid != conid) + conid = ConnectToMds(server); + if (conid == -1) { - prev = host; - host = host->next; + CONMSG(MDSWRN, ": %s", "error"); } else { - if (host->h.connections <= 0) - { - DBG("Disconnecting %d: %d\n", host->h.conid, host->h.connections); - if (disconnectFromMds && IS_NOT_OK(disconnectFromMds(host->h.conid))) - fprintf(stderr, "Failed to disconnect Connection %d\n", - host->h.conid); - if (prev) - { - prev->next = host->next; - free(host->h.unique); - free(host); - host = prev->next; - } - else - { - host_list = host->next; - free(host->h.unique); - free(host); - host = host_list; - } - } - else - { - prev = host; - host = host->next; - } + CONMSG(MDSDBG, ": %s", "new"); } } -} -/** host_list_clean_main - * Run method of host_list_cleaner. - * Implements a 10 second timout upon which it will call host_list_cleanup(). - * After the cleanup it will go into idle state. - * Signalling host_cleaner_sig will wake it up or reset the timeout. - */ -static void host_list_clean_main() -{ - HOST_LIST_LOCK; - struct timespec tp; - do - { // entering armed state - host_list_armed = TRUE; - clock_gettime(CLOCK_REALTIME, &tp); - tp.tv_sec += 10; - int err = pthread_cond_timedwait(&host_list_sig, &host_list_lock, &tp); - if (!err) - continue; // reset timeout - if (err == ETIMEDOUT) - { - host_list_cleanup(-1); - } - else - { - perror("PANIC in treeshr/RemoteAccess.c -> host_list_clean_main"); - abort(); - } // entering idle state - host_list_armed = FALSE; - pthread_cond_wait(&host_list_sig, &host_list_lock); - } while (1); - pthread_cleanup_pop(1); -} -/** host_list_init_cleanup - * Creates the cleanup thread and detaches. - * This method is only called once in host_list_schedule_cleanup() - */ -static void host_list_init_cleanup() -{ - static pthread_t thread; - int err = pthread_create(&thread, NULL, (void *)host_list_clean_main, NULL); - if (!err) - pthread_detach(thread); -} -/** remote_access_connect - * Both creates and selects existing connections for reuse. - * This method shall reset the cleanup cycle to ensure full timeout period. - * If the cleanup cycle is not armed, it is not required to arm it. - */ -static int remote_access_connect(char *server, int inc_count, - void *dbid __attribute__((unused))) -{ - static int (*ReuseCheck)(char *, char *, int) = NULL; - char unique[128] = "\0"; - if (IS_OK(LibFindImageSymbol_C("MdsIpShr", "ReuseCheck", &ReuseCheck))) - { - if (ReuseCheck(server, unique, 128) < 0) - return -1; // TODO: check if this is required / desired - } else { - int i; - for (i = 0; server[i] && i < 127; i++) - unique[i] = tolower(server[i]); - unique[127] = '\0'; - } - int conid; - HOST_LIST_LOCK; - host_list_t *host; - for (host = host_list; host; host = host->next) - { - if (!strcmp(host->h.unique, unique)) + Host *host = NULL; + TREETHREADSTATIC_INIT; + for (host = TREE_HOSTLIST; host; host = host->next) { - if (inc_count) + if (!strcmp(host->unique, unique)) { - host->h.connections++; - DBG("Connection %d> %d\n", host->h.conid, host->h.connections); + conid = host->conid; + host->links++; + MDSDBG(HOST_PRI ", server='%s': found", HOST_VAR(host), server); + return conid; } - else - DBG("Connection %d= %d\n", host->h.conid, host->h.connections); - break; } - } - static int (*ConnectToMds)(char *) = NULL; - if (!host) - { - if (IS_OK(LibFindImageSymbol_C("MdsIpShr", "ConnectToMds", &ConnectToMds))) + conid = ConnectToMds(unique); + if (conid == -1) { - conid = ConnectToMds(unique); - if (conid > 0) - { - DBG("New connection %d> %s\n", conid, unique); - host = malloc(sizeof(host_list_t)); - host->h.conid = conid; - host->h.connections = inc_count ? 1 : 0; - host->h.unique = strdup(unique); - host->next = host_list; - host_list = host; - } + CONMSG(MDSWRN, ": %s", "error"); } else - conid = -1; + { + host = malloc(sizeof(Host)); + host->conid = conid; + host->links = !!inc_count; + host->unique = strdup(unique); + host->next = TREE_HOSTLIST; + TREE_HOSTLIST = host; + MDSDBG(HOST_PRI ", server='%s': new", HOST_VAR(host), server); + } } - else - conid = host->h.conid; - if (host_list_armed) - pthread_cond_signal(&host_list_sig); - HOST_LIST_UNLOCK; return conid; +#undef CONMSG } -/** remote_access_disconnect - * Used to close a connection either forcefulle or indirect by reducing the - * connection counter. If the counter drops to 0, this method shall arm the - * cleanup cycle. If the cleanup cycle is already armed, it is not required to - * reset it. - */ -static int remote_access_disconnect(int conid, int force) +/// remote_disconnect +/// Used to close a connection either forcefully or indirect by reducing the +/// connection counter. If the counter drops to 0, this method shall arm the +/// cleanup cycle. If the cleanup cycle is already armed, it is not required to +/// reset it. +static int remote_disconnect(int conid, int force) { - HOST_LIST_LOCK; - host_list_t *host; - for (host = host_list; host && host->h.conid != conid; host = host->next) - ; - if (host) + if (conid == -1) + return TreeSUCCESS; + TREETHREADSTATIC_INIT; + Host **prev = &TREE_HOSTLIST, *host = TREE_HOSTLIST; + for (; host; prev = &host->next, host = host->next) { - if (force) - { - fprintf(stderr, "Connection %d: forcefully disconnecting %d links\n", - conid, host->h.connections); - host->h.connections = 0; - host_list_cleanup(conid); - } - else + if (host->conid == conid) { - host->h.connections--; - DBG("Connection %d< %d\n", conid, host->h.connections); - if (host->h.connections <= 0 && !host_list_armed) + host->links--; + if (host->links > 0 && !force) { - // arm host_list_cleaner - RUN_FUNCTION_ONCE(host_list_init_cleanup); - pthread_cond_signal(&host_list_sig); + MDSDBG(HOST_PRI " kept", HOST_VAR(host)); } + else + { + if (force) + { + MDSWRN(HOST_PRI " disconnected", HOST_VAR(host)); + } + else + { + MDSDBG(HOST_PRI " disconnected", HOST_VAR(host)); + } + *prev = host->next; + destroy_host(host); + } + break; } } - else - DBG("Disconnected %d\n", conid); - HOST_LIST_UNLOCK; return TreeSUCCESS; } @@ -325,45 +188,29 @@ struct descrip (struct descrip) { DTYPE_T, 0, {0}, strlen(str), (char *)str } static int MdsValue(int conid, char *exp, ...) { - static int (*_mds_value)() = NULL; - int status = - LibFindImageSymbol_C("MdsIpShr", "_MdsValue", (void **)&_mds_value); - if (STATUS_NOT_OK) - { - fprintf(stderr, "Error loadig symbol MdsIpShr->_MdsValue: %d\n", status); - return status; - } + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, _MdsValue, return status, int, ()); int nargs; struct descrip *arglist[256]; VA_LIST_NULL(arglist, nargs, 1, -1, exp); struct descrip expd = STR2DESCRIP(exp); arglist[0] = &expd; - return _mds_value(conid, nargs, arglist, arglist[nargs]); + return _MdsValue(conid, nargs, arglist, arglist[nargs]); } static int MdsValueDsc(int conid, char *exp, ...) { - static int (*_mds_value_dsc)() = NULL; - int status = LibFindImageSymbol_C("MdsIpShr", "MdsIpGetDescriptor", - (void **)&_mds_value_dsc); - if (STATUS_NOT_OK) - { - fprintf(stderr, "Error loadig symbol MdsIpShr->MdsIpGetDescriptor: %d\n", - status); - return status; - } + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, MdsIpGetDescriptor, return status, int, ()); int nargs; struct descrip *arglist[256]; VA_LIST_NULL(arglist, nargs, 0, -1, exp); - return _mds_value_dsc(conid, exp, nargs, arglist, arglist[nargs]); + return MdsIpGetDescriptor(conid, exp, nargs, arglist, arglist[nargs]); } inline static void MdsIpFree(void *ptr) { // used to free ans.ptr returned by MdsValue static void (*mdsIpFree)(void *) = NULL; - if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", &mdsIpFree))) - return; + MDSSHR_LOAD_LIBROUTINE(mdsIpFree, MdsIpShr, MdsIpFree, abort()); mdsIpFree(ptr); } @@ -371,8 +218,7 @@ inline static void MdsIpFreeDsc(struct descriptor_xd *xd) { // used to free ans.ptr returned by MdsValueDsc static void (*mdsIpFreeDsc)(struct descriptor_xd *) = NULL; - if (IS_NOT_OK(LibFindImageSymbol_C("MdsIpShr", "MdsIpFree", (void **)&mdsIpFreeDsc))) - return; + MDSSHR_LOAD_LIBROUTINE(mdsIpFreeDsc, MdsIpShr, MdsIpFreeDsc, abort()); mdsIpFreeDsc(xd); } @@ -400,7 +246,7 @@ int ConnectTreeRemote(PINO_DATABASE *dblist, char const *tree, int conid; logname[strlen(logname) - 2] = '\0'; int status = TreeSUCCESS; - conid = remote_access_connect(logname, 1, (void *)dblist); + conid = remote_connect(logname, 1); if (conid != -1) { status = tree_open(dblist, conid, subtree_list ? subtree_list : tree); @@ -423,7 +269,7 @@ int ConnectTreeRemote(PINO_DATABASE *dblist, char const *tree, info->blockid = TreeBLOCKID; info->flush = (dblist->shotid == -1); info->header = (TREE_HEADER *)&info[1]; - info->treenam = strcpy(malloc(strlen(tree) + 1), tree); + info->treenam = strdup(tree); TreeCallHookFun("TreeHook", "OpenTree", tree, dblist->shotid, NULL); TreeCallHook(OpenTree, info, 0); info->channel = conid; @@ -436,7 +282,7 @@ int ConnectTreeRemote(PINO_DATABASE *dblist, char const *tree, } } else - remote_access_disconnect(conid, 0); + remote_disconnect(conid, 0); } else status = TreeCONNECTFAIL; @@ -463,7 +309,7 @@ int CloseTreeRemote(PINO_DATABASE *dblist, status = (ans.dtype == DTYPE_L) ? *(int *)ans.ptr : 0; MdsIpFree(ans.ptr); } - remote_access_disconnect(dblist->tree_info->channel, 0); + remote_disconnect(dblist->tree_info->channel, 0); if (dblist->tree_info) { free(dblist->tree_info->treenam); @@ -646,7 +492,7 @@ char *AbsPathRemote(PINO_DATABASE *dblist, char const *inpatharg) if (ans.ptr) { if (ans.dtype == DTYPE_T && (strlen(ans.ptr) > 0)) - retans = strcpy(malloc(strlen(ans.ptr) + 1), ans.ptr); + retans = strdup(ans.ptr); MdsIpFree(ans.ptr); } return retans; @@ -763,7 +609,7 @@ int GetNciRemote(PINO_DATABASE *dblist, int nid_in, struct nci_itm *nci_itm) int status = TreeSUCCESS; NCI_ITM *itm; struct descrip ans; - for (itm = nci_itm; itm->code != NciEND_OF_LIST && status & 1; itm++) + for (itm = nci_itm; itm->code != NciEND_OF_LIST && STATUS_OK; itm++) { char *getnci_str = NULL; switch (itm->code) @@ -977,7 +823,7 @@ int SetNciRemote(PINO_DATABASE *dblist, int nid, NCI_ITM *nci_itm) { int status = 1; NCI_ITM *itm_ptr; - for (itm_ptr = nci_itm; itm_ptr->code != NciEND_OF_LIST && status & 1; + for (itm_ptr = nci_itm; itm_ptr->code != NciEND_OF_LIST && STATUS_OK; itm_ptr++) { switch (itm_ptr->code) @@ -1000,7 +846,7 @@ int SetDbiRemote(PINO_DATABASE *dblist, DBI_ITM *dbi_itm) { int status = 1; DBI_ITM *itm_ptr; - for (itm_ptr = dbi_itm; itm_ptr->code != DbiEND_OF_LIST && status & 1; + for (itm_ptr = dbi_itm; itm_ptr->code != DbiEND_OF_LIST && STATUS_OK; itm_ptr++) { switch (itm_ptr->code) @@ -1080,7 +926,7 @@ int TreeTurnOffRemote(PINO_DATABASE *dblist, int nid) int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) { int status = TreeFAILURE; - int channel = remote_access_connect(path, 0, 0); + int channel = remote_connect(path, 0); if (channel > 0) { struct descrip ans = {0}; @@ -1092,7 +938,7 @@ int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) if (ans.dtype == DTYPE_L) *shot = *(int *)ans.ptr; else - status = status & 1 ? TreeFAILURE : status; + status = STATUS_OK ? TreeFAILURE : status; MdsIpFree(ans.ptr); } } @@ -1102,7 +948,7 @@ int TreeGetCurrentShotIdRemote(const char *treearg, char *path, int *shot) int TreeSetCurrentShotIdRemote(const char *treearg, char *path, int shot) { int status = 0; - int channel = remote_access_connect(path, 0, 0); + int channel = remote_connect(path, 0); if (channel > 0) { struct descrip ans = {0}; @@ -1155,6 +1001,7 @@ typedef struct iolock_s size_t size; int *deleted; } iolock_t; + static void mds_io_unlock(void *in) { iolock_t *l = (iolock_t *)in; @@ -1186,10 +1033,8 @@ char *ParseFile(char *filename, char **hostpart, char **filepart) } static pthread_mutex_t fds_lock = PTHREAD_MUTEX_INITIALIZER; -#define FDS_LOCK \ - pthread_mutex_lock(&fds_lock); \ - pthread_cleanup_push((void *)pthread_mutex_unlock, &fds_lock); -#define FDS_UNLOCK pthread_cleanup_pop(1); +#define FDS_LOCK MUTEX_LOCK_PUSH(&fds_lock) +#define FDS_UNLOCK MUTEX_LOCK_POP(&fds_lock) int ADD_FD(int fd, int conid, int enhanced) { @@ -1263,9 +1108,6 @@ static inline int mds_io_request(int conid, mds_io_mode idx, size_t size, char **dout, void **m) { int status; - static pthread_mutex_t io_lock = PTHREAD_MUTEX_INITIALIZER; - pthread_mutex_lock(&io_lock); - pthread_cleanup_push((void *)pthread_mutex_unlock, &io_lock); char nargs = size / sizeof(int); status = SendArg(conid, (int)idx, 0, 0, 0, nargs, mdsio->dims, din); if (STATUS_NOT_OK) @@ -1273,7 +1115,7 @@ static inline int mds_io_request(int conid, mds_io_mode idx, size_t size, if (idx != MDS_IO_CLOSE_K) fprintf(stderr, "Error in SendArg: mode = %d, status = %d\n", idx, status); - remote_access_disconnect(conid, 1); + remote_disconnect(conid, 1); } else { @@ -1285,10 +1127,9 @@ static inline int mds_io_request(int conid, mds_io_mode idx, size_t size, if (idx != MDS_IO_CLOSE_K) fprintf(stderr, "Error in GetAnswerInfoTS: mode = %d, status = %d\n", idx, status); - remote_access_disconnect(conid, 0); + remote_disconnect(conid, 0); } } - pthread_cleanup_pop(1); return status; } @@ -1353,13 +1194,13 @@ inline static int io_open_remote(char *host, char *filename, int options, if (options & O_RDWR) mdsio.open.options |= MDS_IO_O_RDWR; if (*conid == -1) - *conid = remote_access_connect(host, 1, 0); + *conid = remote_connect(host, 1); if (*conid != -1) { fd = io_open_request(*conid, enhanced, sizeof(mdsio.open), &mdsio, filename); if (fd < 0) - remote_access_disconnect(*conid, B_FALSE); + remote_disconnect(*conid, B_FALSE); } else { @@ -1396,7 +1237,9 @@ EXPORT int MDS_IO_OPEN(char *filename_in, int options, mode_t mode) fd = io_open_remote(hostpart, filepart, options, mode, &conid, &enhanced); else { + fd = open(filename, options | O_BINARY | O_RANDOM, mode); + MDSDBG("fd=%d, filename='%s'", fd, filename); #ifndef _WIN32 if ((fd >= 0) && ((options & O_CREAT) != 0)) set_mdsplus_file_protection(filename); @@ -1418,7 +1261,7 @@ inline static int io_close_remote(int conid, int fd) int status = MdsIoRequest(conid, MDS_IO_CLOSE_K, sizeof(mdsio.close), &mdsio, NULL, &len, &dout, &msg); if (STATUS_OK) - remote_access_disconnect(conid, 0); + remote_disconnect(conid, 0); if (STATUS_OK && sizeof(int) == len) { ret = *(int *)dout; @@ -1436,6 +1279,7 @@ EXPORT int MDS_IO_CLOSE(int idx) return -1; if (i.conid >= 0) return io_close_remote(i.conid, i.fd); + MDSDBG("I fd=%d", i.fd); return close(i.fd); } @@ -1640,6 +1484,9 @@ inline static int io_lock_remote(fdinfo_t fdinfo, off_t offset, size_t size, static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, int mode_in, int *deleted) { + + MDSDBG("I fd=%d, offset=%" PRIu64 ", size=%" PRIu64 ", mode=%d", + fdinfo.fd, offset, size, mode_in); int fd = fdinfo.fd; int err; int mode = mode_in & MDS_IO_LOCK_MASK; @@ -1667,9 +1514,9 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, err = !UnlockFileEx(h, 0, (DWORD)size, 0, &overlapped); } if (err) - DBG("LOCK_ER %d mode=%d, errorcode=%d\n", fd, mode, (int)GetLastError()); + MDSDBG("LOCK_ER %d mode=%d, errorcode=%d\n", fd, mode, (int)GetLastError()); else - DBG("LOCK_OK %d mode=%d\n", fd, mode); + MDSDBG("LOCK_OK %d mode=%d\n", fd, mode); if (deleted) *deleted = 0; #else @@ -1691,9 +1538,7 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, err = fcntl(fd, nowait ? F_SETLK : F_SETLKW, &flock); if (err == 0) { - fprintf( - stderr, - "OS does not support OFD locks, file access is not threadsafe\n"); + MDSWRN("File system does not support OFD locks, file access is not threadsafe"); use_ofd_locks = 0; } } @@ -1707,6 +1552,8 @@ static int io_lock_local(fdinfo_t fdinfo, off_t offset, size_t size, if (deleted) *deleted = stat.st_nlink <= 0; #endif + MDSDBG("O fd=%d, offset=%" PRIu64 ", size=%" PRIu64 ", mode=%d, err=%d", + fdinfo.fd, (uint64_t)offset, (uint64_t)size, mode_in, err); return err ? TreeLOCK_FAILURE : TreeSUCCESS; } @@ -1727,7 +1574,7 @@ inline static int io_exists_remote(char *host, char *filename) { int ret; INIT_AND_FREE_ON_EXIT(void *, msg); - int conid = remote_access_connect(host, 1, 0); + int conid = remote_connect(host, 1); if (conid != -1) { mdsio_t mdsio = {.exists = {.length = strlen(filename) + 1}}; @@ -1768,7 +1615,7 @@ inline static int io_remove_remote(char *host, char *filename) { int ret; INIT_AND_FREE_ON_EXIT(void *, msg); - int conid = remote_access_connect(host, 1, 0); + int conid = remote_connect(host, 1); if (conid != -1) { mdsio_t mdsio = {.remove = {.length = strlen(filename) + 1}}; @@ -1806,7 +1653,7 @@ inline static int io_rename_remote(char *host, char *filename_old, { int ret; int conid; - conid = remote_access_connect(host, 1, 0); + conid = remote_connect(host, 1); if (conid != -1) { INIT_AND_FREE_ON_EXIT(char *, names); @@ -1959,7 +1806,7 @@ inline static int io_open_one_remote(char *host, char *filepath, &GetConnectionVersion); do { - *conid = remote_access_connect(host, 1, NULL); + *conid = remote_connect(host, 1); if (*conid != -1) { if (GetConnectionVersion(*conid) < MDSIP_VERSION_OPEN_ONE) @@ -1992,7 +1839,7 @@ inline static int io_open_one_remote(char *host, char *filepath, else { status = TreeUNSUPTHICKOP; - remote_access_disconnect(*conid, B_FALSE); + remote_disconnect(*conid, B_FALSE); } break; } @@ -2010,7 +1857,7 @@ inline static int io_open_one_remote(char *host, char *filepath, host, enhanced, fullpath, fd); FREE_NOW(data); if (*fd < 0) - remote_access_disconnect(*conid, B_FALSE); + remote_disconnect(*conid, B_FALSE); } else { diff --git a/treeshr/TreeAddNode.c b/treeshr/TreeAddNode.c index a171d3fc75..edf47046a7 100644 --- a/treeshr/TreeAddNode.c +++ b/treeshr/TreeAddNode.c @@ -25,7 +25,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define EMPTY_NODE #define EMPTY_NCI #include "treeshrp.h" /*must be first or off_t is misdefined */ -#include #include #include @@ -51,9 +50,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define node_to_node_number(node_ptr) node_ptr - dblist->tree_info->node extern void **TreeCtx(); -STATIC_ROUTINE int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, - NODE **trn_node_ptrptr); -STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info); +static int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, + NODE **trn_node_ptrptr); +static int TreeWriteNci(TREE_INFO *info); int TreeAddNode(char const *name, int *nid_out, char usage) { @@ -336,8 +335,8 @@ int TreeInsertMember(NODE *parent_ptr, NODE *member_ptr, int sort) return TreeSUCCESS; /* return the status */ } -STATIC_ROUTINE int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, - NODE **trn_node_ptrptr) +static int TreeNewNode(PINO_DATABASE *db_ptr, NODE **node_ptrptr, + NODE **trn_node_ptrptr) { INIT_STATUS_AS TreeSUCCESS; NODE *node_ptr; @@ -388,8 +387,7 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static NODE *empty_node_array = NULL; static NCI *empty_nci_array = NULL; - pthread_mutex_lock(&lock); - pthread_cleanup_push((void *)pthread_mutex_unlock, &lock); + MUTEX_LOCK_PUSH(&lock); status = TreeSUCCESS; int *saved_node_numbers; NODE *node_ptr; @@ -399,12 +397,12 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) TREE_EDIT *edit_ptr; int i; NCI *nciptr; - STATIC_CONSTANT NCI empty_nci; + static NCI empty_nci; int vm_bytes; // TODO: 2GB limit int nodes; int ncis; - STATIC_CONSTANT size_t empty_node_size = sizeof(NODE) * EXTEND_NODES; - STATIC_CONSTANT size_t empty_nci_size = sizeof(NCI) * EXTEND_NODES; + static size_t empty_node_size = sizeof(NODE) * EXTEND_NODES; + static size_t empty_nci_size = sizeof(NCI) * EXTEND_NODES; if (!empty_node_array) { @@ -541,7 +539,7 @@ int TreeExpandNodes(PINO_DATABASE *db_ptr, int num_fixup, NODE ***fixup_nodes) } header_ptr->nodes += EXTEND_NODES; end:; - pthread_cleanup_pop(1); + MUTEX_LOCK_POP(&lock); return status; } @@ -558,10 +556,7 @@ static void get_add_rtn_c(void *in) free(c->model); free(c->image); } -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wclobbered" -// fc21 claims that '__cancel_routine' is clobbered -// pthread_cleanup_push(get_add_rtn_c,(void*)&c); + static inline int get_add_rtn(char const *congtype, int (**add)()) { static int (*TdiExecute)() = NULL; @@ -611,7 +606,7 @@ static inline int get_add_rtn(char const *congtype, int (**add)()) pthread_cleanup_pop(1); return status; } -#pragma GCC diagnostic pop + int _TreeAddConglom(void *dbid, char const *path, char const *congtype, int *nid) { @@ -790,10 +785,10 @@ int _TreeEndConglomerate(void *dbid) return TreeSUCCESS; } -STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr); +static void trim_excess_nodes(TREE_INFO *info_ptr); #ifdef WORDS_BIGENDIAN -STATIC_ROUTINE TREE_HEADER *HeaderOut(TREE_HEADER *hdr) +static TREE_HEADER *HeaderOut(TREE_HEADER *hdr) { TREE_HEADER *ans = (TREE_HEADER *)malloc(sizeof(TREE_HEADER)); ((char *)ans)[1] = @@ -805,7 +800,7 @@ STATIC_ROUTINE TREE_HEADER *HeaderOut(TREE_HEADER *hdr) return ans; } -STATIC_ROUTINE void FreeHeaderOut(TREE_HEADER *hdr) { free(hdr); } +static void FreeHeaderOut(TREE_HEADER *hdr) { free(hdr); } #else #define HeaderOut(in) in @@ -882,8 +877,7 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) FREE_ON_EXIT(nfilenam); int ntreefd; TREE_INFO *info_ptr = (*dblist)->tree_info; - nfilenam = - strcpy(malloc(strlen(info_ptr->filespec) + 2), info_ptr->filespec); + nfilenam = strcpy(malloc(strlen(info_ptr->filespec) + 2), info_ptr->filespec); _TreeDeleteNodesWrite(*dbid); trim_excess_nodes(info_ptr); header_pages = (sizeof(TREE_HEADER) + 511u) / 512u; @@ -964,7 +958,7 @@ int _TreeWriteTree(void **dbid, char const *exp_ptr, int shotid) return status; } -STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) +static void trim_excess_nodes(TREE_INFO *info_ptr) { int *nodecount_ptr = (int *)&info_ptr->header->nodes; int *free_ptr = (int *)&info_ptr->header->free; @@ -1016,7 +1010,7 @@ STATIC_ROUTINE void trim_excess_nodes(TREE_INFO *info_ptr) } } -STATIC_ROUTINE int TreeWriteNci(TREE_INFO *info) +static int TreeWriteNci(TREE_INFO *info) { INIT_STATUS_AS TreeSUCCESS; if (info->header->nodes > info->edit->first_in_mem) diff --git a/treeshr/TreeAddTag.c b/treeshr/TreeAddTag.c index 04e6660097..895ee4e0e4 100644 --- a/treeshr/TreeAddTag.c +++ b/treeshr/TreeAddTag.c @@ -51,7 +51,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-----------------------------------------------------------------------------*/ #include "treeshrp.h" -#include #include #include #include @@ -100,7 +99,7 @@ int _TreeAddTag(void *dbid, int nid_in, char const *tagnam) ************************************************/ status = IS_OPEN_FOR_EDIT(dblist) ? TreeSUCCESS : TreeNOEDIT; - if (!(status & 1)) + if (STATUS_NOT_OK) return status; len = strlen(tagnam); diff --git a/treeshr/TreeCallHook.c b/treeshr/TreeCallHook.c index 16b1cbc406..173b246b5e 100644 --- a/treeshr/TreeCallHook.c +++ b/treeshr/TreeCallHook.c @@ -23,7 +23,6 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "treeshrp.h" -#include #include #include #include diff --git a/treeshr/TreeCleanDatafile.c b/treeshr/TreeCleanDatafile.c index 29a834bd62..c8ab23c70f 100644 --- a/treeshr/TreeCleanDatafile.c +++ b/treeshr/TreeCleanDatafile.c @@ -23,7 +23,6 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "treeshrp.h" -#include #include #include #include @@ -52,7 +51,7 @@ static void treeclose(void *dbid_p) _TreeClose(dbid_p, 0, 0); free(*(void **)dbid_p); } -STATIC_ROUTINE int RewriteDatafile(char const *tree, int shot, int compress) +static int RewriteDatafile(char const *tree, int shot, int compress) { int status, stat1; void *dbid1 = 0, *dbid2 = 0; diff --git a/treeshr/TreeCreatePulseFile.c b/treeshr/TreeCreatePulseFile.c index 2c54acabd9..9054fc32c2 100644 --- a/treeshr/TreeCreatePulseFile.c +++ b/treeshr/TreeCreatePulseFile.c @@ -52,7 +52,6 @@ int TreeCreatePulseFile(int shotid,int numnids, int *nids) ------------------------------------------------------------------------------*/ #include "treeshrp.h" /* must be first or off_t is defined wrong */ -#include #include #include #include @@ -63,15 +62,9 @@ int TreeCreatePulseFile(int shotid,int numnids, int *nids) #include //#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { \ - } -#endif +#include -STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it); +static int _CopyFile(int src_fd, int dst_fd, int lock_it); extern void **TreeCtx(); @@ -197,7 +190,7 @@ static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, if (tmp) { if (STATUS_OK) - DBG("%s ->\n", tmp); + MDSDBG("%s ->\n", tmp); free(tmp); tmp = NULL; } @@ -214,7 +207,7 @@ static int TreeCreateTreeFilesOne(char const *tree, int shot, int source_shot, if (tmp) { if (STATUS_OK) - DBG("%s <-\n", tmp); + MDSDBG("%s <-\n", tmp); free(tmp); tmp = NULL; } @@ -244,7 +237,7 @@ int TreeCreateTreeFiles(char const *tree, int shot, int source_shot) #define MIN(a, b) ((a) < (b)) ? (a) : (b) #define MAX(a, b) ((a) > (b)) ? (a) : (b) -STATIC_ROUTINE int _CopyFile(int src_fd, int dst_fd, int lock_it) +static int _CopyFile(int src_fd, int dst_fd, int lock_it) { INIT_STATUS_ERROR; if (src_fd != -1) diff --git a/treeshr/TreeDeleteNode.c b/treeshr/TreeDeleteNode.c index 8462b370a4..d3a7b336a1 100644 --- a/treeshr/TreeDeleteNode.c +++ b/treeshr/TreeDeleteNode.c @@ -53,14 +53,13 @@ int TreeDeleteNodeInitialize(NID *nid,int *count,reset) ------------------------------------------------------------------------------*/ #include "treeshrp.h" -#include #include #include #include extern void **TreeCtx(); -STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count); +static void check_nid(PINO_DATABASE *dblist, NID *nid, int *count); int TreeDeleteNodeGetNid(int *nid) { @@ -131,7 +130,7 @@ static inline void setbit(PINO_DATABASE *dblist, int bitnum) (unsigned char)(dblist->delete_list[bitnum / 8] | (1 << bitnum % 8)); } -STATIC_ROUTINE void check_nid(PINO_DATABASE *dblist, NID *nid, int *count) +static void check_nid(PINO_DATABASE *dblist, NID *nid, int *count) { int bitnum = nid->node; if (!getbit(dblist, bitnum)) diff --git a/treeshr/TreeDeletePulseFile.c b/treeshr/TreeDeletePulseFile.c index 25bdd24376..e9b18bc170 100644 --- a/treeshr/TreeDeletePulseFile.c +++ b/treeshr/TreeDeletePulseFile.c @@ -52,7 +52,6 @@ int TreeDeletePulseFile(int shotid,int numnids, int *nids) ------------------------------------------------------------------------------*/ #include "treeshrp.h" /* must be first or off_t wrong */ -#include #include #include #include @@ -65,13 +64,7 @@ int TreeDeletePulseFile(int shotid,int numnids, int *nids) #include //#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { \ - } -#endif +#include extern void **TreeCtx(); @@ -93,7 +86,7 @@ static inline int TreeDeleteTreeFilesOne(char *tree, int shot, char *treepath) status = MDS_IO_OPEN_ONE(treepath, tree, shot, i + TREE_TREEFILE_TYPE, 0, 0, &tmp[i], NULL, &src[i]); if (STATUS_OK && tmp[i]) - DBG("%s -x\n", tmp[i]); + MDSDBG("%s -x\n", tmp[i]); } else src[i] = -1; diff --git a/treeshr/TreeDoMethod.c b/treeshr/TreeDoMethod.c index d1b2b7cd95..dcfbd55add 100644 --- a/treeshr/TreeDoMethod.c +++ b/treeshr/TreeDoMethod.c @@ -52,7 +52,6 @@ int TreeDoMethod( nid_dsc, method_dsc [,args]...) ------------------------------------------------------------------------------*/ #include "treeshrp.h" -#include #include #include #include diff --git a/treeshr/TreeFindNode.c b/treeshr/TreeFindNode.c index 68dea5fe94..4f7fc0422a 100644 --- a/treeshr/TreeFindNode.c +++ b/treeshr/TreeFindNode.c @@ -267,7 +267,7 @@ EXPORT int _TreeFindNodeRelative(void *dbid, char const *path, int startnid, } done: FreeSearchCtx(&ctx); - return (status & 1) ? TreeSUCCESS : status; + return (STATUS_OK) ? TreeSUCCESS : status; } EXPORT int _TreeFindNodeEnd(void *dbid __attribute__((unused)), void **ctx) @@ -807,7 +807,7 @@ extern int TreeFindParent(PINO_DATABASE *dblist, char *name, NODE **node, else { status = _TreeFindNode(dblist, parent_name, (int *)&nid); - if (status & 1) + if (STATUS_OK) { *node = nid_to_node(dblist, &nid); } diff --git a/treeshr/TreeGetDbi.c b/treeshr/TreeGetDbi.c index d8a9d18b26..506ecb509a 100644 --- a/treeshr/TreeGetDbi.c +++ b/treeshr/TreeGetDbi.c @@ -59,7 +59,7 @@ int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst) PINO_DATABASE *db = (PINO_DATABASE *)dbid; struct dbi_itm *lst = itmlst; int status = TreeSUCCESS; - while ((lst->code != 0) && (status & 1)) + while ((lst->code != 0) && (STATUS_OK)) { char *string = NULL; unsigned short retlen = 0; @@ -68,7 +68,7 @@ int _TreeGetDbi(void *dbid, struct dbi_itm *itmlst) case DbiNAME: CheckOpen(db); - string = strcpy(malloc(strlen(db->main_treenam) + 1), db->main_treenam); + string = strdup(db->main_treenam); break; case DbiSHOTID: diff --git a/treeshr/TreeGetNci.c b/treeshr/TreeGetNci.c index b205024d5f..02782e37b8 100644 --- a/treeshr/TreeGetNci.c +++ b/treeshr/TreeGetNci.c @@ -656,7 +656,7 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) break_on_no_node; read_nci; lstr = MdsDtypeString(nci.dtype); - string = strcpy(malloc(strlen(lstr) + 1), lstr); + string = strdup(lstr); break; } @@ -666,7 +666,7 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) break_on_no_node; read_nci; lstr = MdsClassString(nci.class); - string = strcpy(malloc(strlen(lstr) + 1), lstr); + string = strdup(lstr); break; } @@ -675,7 +675,7 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm) char *lstr; break_on_no_node; lstr = MdsUsageString(node->usage); - string = strcpy(malloc(strlen(lstr) + 1), lstr); + string = strdup(lstr); break; } diff --git a/treeshr/TreeGetSetShotId.c b/treeshr/TreeGetSetShotId.c index a0c3c0d6ec..2e45aa4009 100644 --- a/treeshr/TreeGetSetShotId.c +++ b/treeshr/TreeGetSetShotId.c @@ -163,7 +163,7 @@ int TreeGetCurrentShotId(char const *experiment) status = MDS_IO_READ(fd, &shot, sizeof(shot)) == sizeof(shot); MDS_IO_CLOSE(fd); #ifdef WORDS_BIGENDIAN - if (status & 1) + if (STATUS_OK) { int lshot = shot; int i; diff --git a/treeshr/TreeOpen.c b/treeshr/TreeOpen.c index 4c57bcd5f4..b6680c872d 100644 --- a/treeshr/TreeOpen.c +++ b/treeshr/TreeOpen.c @@ -68,13 +68,7 @@ inline static char *strndup(const char *src, size_t n) #endif //#define DEBUG -#ifdef DEBUG -#define DBG(...) fprintf(stderr, __VA_ARGS__) -#else -#define DBG(...) \ - { /**/ \ - } -#endif +#include int treeshr_errno = 0; extern int MDSEventCan(); @@ -650,7 +644,7 @@ EXPORT int _TreeNewDbid(void **dblist) PINO_DATABASE *db = (PINO_DATABASE *)calloc(1, sizeof(PINO_DATABASE)); if (db) { - DBG("Created DB %" PRIxPTR "\n", (uintptr_t)db); + MDSDBG("Created DB %" PRIxPTR "\n", (uintptr_t)db); db->timecontext.start.dtype = DTYPE_DSC; db->timecontext.start.class = CLASS_XD; db->timecontext.end.dtype = DTYPE_DSC; @@ -924,7 +918,7 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) if ((strlen(tilde + 2) > 1) || ((strlen(tilde + 2) == 1) && (tilde[2] != '\\'))) { - tmp = strcpy(malloc(strlen(tilde + 2) + 1), tilde + 2); + tmp = strdup(tilde + 2); tmp2 = strcpy(malloc(strlen(path) + 1 + fname_len), path); strcpy(tmp2 + (tilde - path) + fname_len, tmp); free(tmp); @@ -939,7 +933,7 @@ EXPORT char *MaskReplace(char *path_in, char *tree, int shot) path = tmp2; break; case 't': - tmp = strcpy(malloc(strlen(tilde + 2) + 1), tilde + 2); + tmp = strdup(tilde + 2); const size_t tree_len = strlen(tree); tmp2 = strcpy(malloc(strlen(path) + 1 + tree_len), path); strcpy(tmp2 + (tilde - path) + tree_len, tmp); @@ -1211,7 +1205,7 @@ void *_TreeSaveContext(void *dbid) { ctx = malloc(sizeof(struct context)); ctx->expt = - strcpy(malloc(strlen(dblist->experiment) + 1), dblist->experiment); + strdup(dblist->experiment); ctx->shot = dblist->shotid; ctx->edit = dblist->open_for_edit; ctx->readonly = dblist->open_readonly; @@ -1466,7 +1460,7 @@ void TreeFreeDbid(void *dbid) { if (dbid) { - DBG("Destroyed DB %" PRIxPTR "\n", (uintptr_t)dbid); + MDSDBG("Destroyed DB %" PRIxPTR "\n", (uintptr_t)dbid); PINO_DATABASE *db = (PINO_DATABASE *)dbid; TreeFreeDbid(db->next); CloseTopTree(db, 1); diff --git a/treeshr/TreePutRecord.c b/treeshr/TreePutRecord.c index 6229b597ec..f45c99d46d 100644 --- a/treeshr/TreePutRecord.c +++ b/treeshr/TreePutRecord.c @@ -147,7 +147,7 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, TreeCallHookFun("TreeNidDataHook", "PutDataFull", info_ptr->treenam, info_ptr->shot, nid, descriptor_ptr, NULL); status = TreeCallHook(PutData, info_ptr, nid); - if (status && !(status & 1)) + if (status && STATUS_NOT_OK) return status; TreeGetViewDate(&saved_viewdate); int locked_nci = 0; @@ -218,14 +218,14 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, : nci->DATA_INFO.DATA_LOCATION.record_length; if ((nci->flags & NciM_WRITE_ONCE) && nci->length) status = TreeNOOVERWRITE; - if ((status & 1) && + if ((STATUS_OK) && (shot_open && (nci->flags & NciM_NO_WRITE_SHOT))) status = TreeNOWRITESHOT; - if ((status & 1) && + if ((STATUS_OK) && (!shot_open && (nci->flags & NciM_NO_WRITE_MODEL))) status = TreeNOWRITEMODEL; } - if (status & 1) + if (STATUS_OK) { unsigned char tree = (unsigned char)nid_ptr->tree; int compressible; @@ -250,9 +250,9 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, bitassign(compressible, nci->flags, NciM_COMPRESSIBLE); bitassign_c(data_in_altbuf, nci->flags2, NciM_DATA_IN_ATT_BLOCK); } - if ((status & 1) && nci->length && (!utility_update)) + if ((STATUS_OK) && nci->length && (!utility_update)) status = check_usage(dblist, nid_ptr, nci); - if (status & 1) + if (STATUS_OK) { if (nci->flags2 & NciM_DATA_IN_ATT_BLOCK && !(nci->flags & NciM_VERSIONS) && !extended) @@ -270,14 +270,14 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr, &attributes.facility_length[STANDARD_RECORD_FACILITY], (compress_utility || (nci->flags & NciM_COMPRESS_ON_PUT)) && !(nci->flags & NciM_DO_NOT_COMPRESS)); - if (status & 1) + if (STATUS_OK) { attributes.facility_offset[SEGMENTED_RECORD_FACILITY] = -1; attributes.facility_length[SEGMENTED_RECORD_FACILITY] = 0; status = TreePutExtendedAttributes(info_ptr, &attributes, &extended_offset); } - if (status & 1) + if (STATUS_OK) { bitassign(0, nci->flags, NciM_SEGMENTED); tree_put_nci(info_ptr, nidx, nci, &locked_nci); @@ -674,7 +674,7 @@ int TreeLockDatafile(TREE_INFO *info, int readonly, int64_t offset) int deleted = 1; if (!info->header->readonly) { - while (deleted && status & 1) + while (deleted && STATUS_OK) { status = MDS_IO_LOCK(readonly ? info->data_file->get : info->data_file->put, diff --git a/treeshr/TreeRenameNode.c b/treeshr/TreeRenameNode.c index c929c7bac4..8064cf2094 100644 --- a/treeshr/TreeRenameNode.c +++ b/treeshr/TreeRenameNode.c @@ -105,7 +105,7 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) make sure that the new node is not already there ***************************************************/ status = _TreeFindNode(dbid, upcase_name, &i); - if (status & 1) + if (STATUS_OK) { status = TreeALREADY_THERE; goto cleanup; @@ -115,7 +115,7 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) ******************************************************/ status = TreeFindParent(dblist, upcase_name, &newnode, &newnode_name, &is_child); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; /************************************************ Make sure that the node being renamed is not @@ -221,10 +221,10 @@ int _TreeRenameNode(void *dbid, int nid, char const *newname) status = TreeInsertMember(newnode, oldnode_ptr, dblist->tree_info->header->sort_members); - if (status & 1) + if (STATUS_OK) status = FixParentState(dblist, newnode, oldnode_ptr); - if (status & 1) + if (STATUS_OK) dblist->modified = 1; cleanup: @@ -258,7 +258,7 @@ static int FixParentState(PINO_DATABASE *dblist, NODE *parent_ptr, ****************************************************/ parent_state = _TreeIsOn(dblist, *(int *)&parent_nid) & 1; status = _TreeGetNci(dblist, *(int *)&child_nid, child_itm_list); - if (status & 1) + if (STATUS_OK) { child_parent_state = ((child_flags & NciM_PARENT_STATE) == 0); if (child_parent_state != parent_state) diff --git a/treeshr/TreeSegments.c b/treeshr/TreeSegments.c index e0a51a8dbf..712a704a13 100644 --- a/treeshr/TreeSegments.c +++ b/treeshr/TreeSegments.c @@ -2061,7 +2061,7 @@ fallback:; status = LibFindImageSymbol_C("TdiShr", "_TdiCompile", &_TdiCompile); if (STATUS_OK) { - STATIC_CONSTANT DESCRIPTOR( + static DESCRIPTOR( expression, "execute('$1[$2 : $2+$3-1]',$1,lbound($1,-1),$2)"); DESCRIPTOR_LONG(row_d, &filled_rows); status = _TdiCompile(&dbid, &expression, dim, &row_d, dim MDS_END_ARG); @@ -2792,7 +2792,7 @@ inline static int is_segment_in_range(vars_t *vars, mdsdsc_t *start, { if ((start && start->pointer) && (end && end->pointer)) { - STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $) && ($ >= $)"); + static DESCRIPTOR(expression, "($ <= $) && ($ >= $)"); ans &= IS_OK(_TdiExecute(&vars->dblist, &expression, start, &segend, end, &segstart, &ans_d MDS_END_ARG)); } @@ -2800,13 +2800,13 @@ inline static int is_segment_in_range(vars_t *vars, mdsdsc_t *start, { if (start && start->pointer) { - STATIC_CONSTANT DESCRIPTOR(expression, "($ <= $)"); + static DESCRIPTOR(expression, "($ <= $)"); ans &= IS_OK(_TdiExecute(&vars->dblist, &expression, start, &segend, &ans_d MDS_END_ARG)); } else { - STATIC_CONSTANT DESCRIPTOR(expression, "($ >= $)"); + static DESCRIPTOR(expression, "($ >= $)"); ans &= (_TdiExecute(&vars->dblist, &expression, end, &segstart, &ans_d MDS_END_ARG)); } @@ -3300,7 +3300,7 @@ int _TreeMakeSegmentResampled(void *dbid, int nid, mdsdsc_t *start, DESCRIPTOR_LONG(nRowsD, &nRows); DESCRIPTOR_NID(resNidD, &resampledNid); DESCRIPTOR_A_COEFF(resD, sizeof(float), DTYPE_FS, NULL, 8, 0); - STATIC_CONSTANT DESCRIPTOR( + static DESCRIPTOR( expression, "BUILD_RANGE($1,$2-$3*($4-$5)/$6, $7*($8-$9)/$10)"); EMPTYXD(dimXd); @@ -3439,9 +3439,9 @@ int _TreeMakeSegmentMinMax(void *dbid, int nid, mdsdsc_t *start, mdsdsc_t *end, DESCRIPTOR_LONG(nRowsD, &nRows); DESCRIPTOR_NID(resNidD, &resampledNid); DESCRIPTOR_A_COEFF(resD, sizeof(float), DTYPE_FS, NULL, 8, 0); - STATIC_CONSTANT DESCRIPTOR( + static DESCRIPTOR( expression, "BUILD_RANGE($1,$2-$3/2.*($4-$5)/$6, ($7/2.)*($8-$9)/$10)"); - STATIC_CONSTANT DESCRIPTOR(minMaxD, "MinMax"); + static DESCRIPTOR(minMaxD, "MinMax"); EMPTYXD(dimXd); resampleArrayDsc(initialValue, &resD, resFactor, &rowSize, &nRows, &nResRows, diff --git a/treeshr/TreeSetDbi.c b/treeshr/TreeSetDbi.c index 2f334b9b06..2a3deca3de 100644 --- a/treeshr/TreeSetDbi.c +++ b/treeshr/TreeSetDbi.c @@ -89,7 +89,7 @@ int _TreeSetDbi(void *dbid, DBI_ITM *dbi_itm_ptr) if (dblist->remote) return SetDbiRemote(dbid, dbi_itm_ptr); - for (itm_ptr = dbi_itm_ptr; itm_ptr->code != NciEND_OF_LIST && status & 1; + for (itm_ptr = dbi_itm_ptr; itm_ptr->code != NciEND_OF_LIST && STATUS_OK; itm_ptr++) { switch (itm_ptr->code) diff --git a/treeshr/TreeSetDefault.c b/treeshr/TreeSetDefault.c index 9475f780cb..feea8b82cd 100644 --- a/treeshr/TreeSetDefault.c +++ b/treeshr/TreeSetDefault.c @@ -46,7 +46,7 @@ int _TreeSetDefault(void *dbid, char *path, int *nid) { int status; status = _TreeFindNode(dbid, path, nid); - if (status & 1) + if (STATUS_OK) status = _TreeSetDefaultNid(dbid, *nid); return status; } diff --git a/treeshr/TreeSetNci.c b/treeshr/TreeSetNci.c index 13d49c8fcd..a12217bd10 100644 --- a/treeshr/TreeSetNci.c +++ b/treeshr/TreeSetNci.c @@ -28,8 +28,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define DEBUG - extern void **TreeCtx(); extern int SetNciRemote(); diff --git a/treeshr/TreeThreadStatic.c b/treeshr/TreeThreadStatic.c index 85fd5245a7..6050ebd33d 100644 --- a/treeshr/TreeThreadStatic.c +++ b/treeshr/TreeThreadStatic.c @@ -32,14 +32,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include <_mdsshr.h> #include "../mdsshr/version.h" #include "treethreadstatic.h" +// #define DEBUG +#include + extern int _TreeNewDbid(void **dblist); static pthread_rwlock_t treectx_lock = PTHREAD_RWLOCK_INITIALIZER; static void *DBID = NULL, *G_DBID = NULL; +void destroy_host(Host *host) +{ + MDSSHR_LOAD_LIBROUTINE_LOCAL(MdsIpShr, DisconnectFromMds, abort(), void, (int)); + MDSDBG(HOST_PRI, HOST_VAR(host)); + DisconnectFromMds(host->conid); + free(host->unique); + free(host); +} + static void buffer_free(TREETHREADSTATIC_ARG) { if (TREE_DBID) @@ -68,6 +81,13 @@ static void buffer_free(TREETHREADSTATIC_ARG) TreeFreeDbid(TREE_DBID); } } + Host *host; + while (TREE_HOSTLIST) + { + host = TREE_HOSTLIST; + TREE_HOSTLIST = TREE_HOSTLIST->next; + destroy_host(host); + } free(TREETHREADSTATIC_VAR); } static inline TREETHREADSTATIC_TYPE *buffer_alloc() diff --git a/treeshr/testing/TreeDeleteNodeTest.c b/treeshr/testing/TreeDeleteNodeTest.c index da0febcc22..9eba2726f5 100644 --- a/treeshr/testing/TreeDeleteNodeTest.c +++ b/treeshr/testing/TreeDeleteNodeTest.c @@ -51,7 +51,7 @@ int dbiTest(void *ctx, short int code) {0, DbiEND_OF_LIST, 0, 0}}; int status = _TreeGetDbi(ctx, dbiList); - TEST1(status & 1); + TEST1(STATUS_OK); return supports; } @@ -78,37 +78,37 @@ int main(int argc __attribute__((unused)), // open tree // status = _TreeOpenNew(&ctx, tree_name, shot); - TEST1(status & 1); + TEST1(STATUS_OK); TEST0(ctx == NULL); // add node // int nid; status = _TreeAddNode(ctx, node_name, &nid, TreeUSAGE_ANY); - TEST1(status & 1); + TEST1(STATUS_OK); status = _TreeWriteTree(&ctx, tree_name, shot); - TEST1(status & 1); + TEST1(STATUS_OK); // remove node // int count; status = _TreeDeleteNodeInitialize(ctx, nid, &count, 1); - TEST1(status & 1); + TEST1(STATUS_OK); _TreeDeleteNodeExecute(ctx); status = _TreeWriteTree(&ctx, tree_name, shot); - TEST1(status & 1); + TEST1(STATUS_OK); // close tree // int is_modified = dbiTest(ctx, DbiMODIFIED); if (is_modified) { status = _TreeQuitTree(&ctx, tree_name, shot); - TEST1(status & 1); + TEST1(STATUS_OK); } else { status = _TreeClose(&ctx, tree_name, shot); - TEST1(status & 1); + TEST1(STATUS_OK); } TreeFreeDbid(ctx); diff --git a/treeshr/testing/TreeSegmentTest.c b/treeshr/testing/TreeSegmentTest.c index 111f61b2e7..904d6fe1f5 100644 --- a/treeshr/testing/TreeSegmentTest.c +++ b/treeshr/testing/TreeSegmentTest.c @@ -115,9 +115,13 @@ int main(int const argc, char const *const argv[]) } TEST_STATUS(_TreeWriteTree(&DBID, NULL, 0)); TEST_STATUS(_TreeCleanDatafile(&DBID, tree, shot)); // includes close + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, 0x40000); pthread_t threads[NUM_THREADS]; for (i = 0; i < NUM_THREADS; i++) - pthread_create(&threads[i], NULL, job, (void *)(intptr_t)i); + pthread_create(&threads[i], &attr, job, (void *)(intptr_t)i); + pthread_attr_destroy(&attr); pthread_mutex_lock(&mutex); go = 1; pthread_cond_broadcast(&cond); diff --git a/treeshr/treethreadstatic.h b/treeshr/treethreadstatic.h index 6cb00034f6..a89f0c8c29 100644 --- a/treeshr/treethreadstatic.h +++ b/treeshr/treethreadstatic.h @@ -2,6 +2,18 @@ #include "../mdsshr/mdsthreadstatic.h" #include "treeshrp.h" +typedef struct host +{ + struct host *next; + int conid; + int links; + char *unique; +} Host; +#define HOST_PRI "Host(conid=%d, links=%d, unique='%s')" +#define HOST_VAR(h) (h)->conid, (h)->links, (h)->unique + +void destroy_host(Host *host); + #define TREETHREADSTATIC_VAR TreeThreadStatic_p #define TREETHREADSTATIC_TYPE TreeThreadStatic_t #define TREETHREADSTATIC_ARG TREETHREADSTATIC_TYPE *TREETHREADSTATIC_VAR @@ -10,6 +22,7 @@ typedef struct { void *dbid; + Host *hostlist; int64_t view_date; NCI temp_nci; int private_ctx; @@ -17,6 +30,7 @@ typedef struct int path_ref; } TREETHREADSTATIC_TYPE; #define TREE_DBID TREETHREADSTATIC_VAR->dbid +#define TREE_HOSTLIST TREETHREADSTATIC_VAR->hostlist #define TREE_PRIVATECTX TREETHREADSTATIC_VAR->private_ctx #define TREE_VIEWDATE TREETHREADSTATIC_VAR->view_date #define TREE_NIDREF TREETHREADSTATIC_VAR->nid_ref diff --git a/treeshr/yylex/TreeFindNodeWild.l b/treeshr/yylex/TreeFindNodeWild.l index 24535e627e..6dd6194b70 100644 --- a/treeshr/yylex/TreeFindNodeWild.l +++ b/treeshr/yylex/TreeFindNodeWild.l @@ -3,15 +3,14 @@ %option nounput noinput noyy_push_state noyy_pop_state noyy_top_state %option never-interactive reentrant %{ -#include #include #include #include #include "treeshrp.h" -STATIC_ROUTINE void addSearchTerm(yyscan_t scanner, int type, char *str); +static void addSearchTerm(yyscan_t scanner, int type, char *str); -STATIC_ROUTINE void upcaseAndTrim(char *str) +static void upcaseAndTrim(char *str) { char *p=str; for (p=str; *p; p++) { @@ -19,7 +18,7 @@ STATIC_ROUTINE void upcaseAndTrim(char *str) } } -STATIC_ROUTINE int isPunctuation(char c) +static int isPunctuation(char c) { return ((c == '.') || (c == ':') || (c=='-') || (c=='~') | (c=='^')); } @@ -92,7 +91,7 @@ newline \n } %% /* -STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) +static const char *SearchTypeName(enum yytreepathtokentype typ) { const char * names[] = { "TAG_TREE", @@ -111,7 +110,7 @@ STATIC_ROUTINE const char *SearchTypeName(enum yytreepathtokentype typ) return names[typ-TAG_TREE]; } -STATIC_ROUTINE void PrintCtx(SEARCH_CTX *ctx) +static void PrintCtx(SEARCH_CTX *ctx) { SEARCH_TERM *ptr; printf ("Print Context for %s\n", ctx->wildcard); @@ -123,7 +122,7 @@ STATIC_ROUTINE void PrintCtx(SEARCH_CTX *ctx) } */ -STATIC_ROUTINE SEARCH_TERM *SquishSearches(SEARCH_TERM *terms) { +static SEARCH_TERM *SquishSearches(SEARCH_TERM *terms) { SEARCH_TERM *ptr = terms; SEARCH_TERM *tmp; for (;ptr && ptr->next; ptr = ptr->next) { @@ -203,7 +202,7 @@ EXPORT int WildParse(char const *path, SEARCH_CTX *ctx, int *wild) return(status ==0) ? TreeSUCCESS : TreeINVPATH; } -STATIC_ROUTINE void addSearchTerm(yyscan_t scanner, int type, char *str) +static void addSearchTerm(yyscan_t scanner, int type, char *str) { SEARCH_TERM *ptr, *p; diff --git a/wfevent/wfevent.c b/wfevent/wfevent.c index 9c3e5b673c..f12bf21e8f 100644 --- a/wfevent/wfevent.c +++ b/wfevent/wfevent.c @@ -149,7 +149,7 @@ int main(int argc, char **argv) } event = argv[optind]; status = MDSWfeventTimed(event, MAXDATA, data, &len, timeout); - if (status & 1) + if (STATUS_OK) { if (showdata && len) { @@ -159,7 +159,7 @@ int main(int argc, char **argv) EMPTYXD(xd); struct descriptor ans = {0, DTYPE_T, CLASS_D, 0}; status = MdsSerializeDscIn(data, &xd); - if (status & 1) + if (STATUS_OK) { TdiDecompile(&xd, &ans MDS_END_ARG); if (ans.pointer) diff --git a/xmdsshr/ListTree.c b/xmdsshr/ListTree.c index f6903afe8b..fdb82b468a 100644 --- a/xmdsshr/ListTree.c +++ b/xmdsshr/ListTree.c @@ -63,19 +63,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #endif -#ifdef DEBUG -#define DBG(fmt, ...) \ - do \ - { \ - fprintf(stderr, "%s:%d %s() ", __FILE__, __LINE__, __FUNCTION__); \ - fprintf(stderr, fmt, __VA_ARGS__); \ - } while (0) -#define DBGW(a) \ - fprintf(stderr, "%s:%d %s() %s\n", __FILE__, __LINE__, __FUNCTION__, a) -#else -#define DBG(fmt...) -#define DBGW(a) -#endif +#include #define folder_width 16 #define folder_height 12 @@ -575,8 +563,8 @@ static void InitializeGeometry(ListTreeWidget w) w->list.preferredHeight = XtHeight(w) - 2 * Prim_ShadowThickness(w) - 2 * Prim_HighlightThickness(w); } - DBG("prefWidth=%d prefHeight=%d\n", w->list.preferredWidth, - w->list.preferredHeight); + MDSDBG("prefWidth=%d prefHeight=%d\n", w->list.preferredWidth, + w->list.preferredHeight); } static void Initialize(Widget request, Widget tnew, ArgList args, @@ -722,10 +710,10 @@ static void SetScrollbars(ListTreeWidget w) top = w->list.topItemPos; bot = w->list.itemCount; size = w->list.visibleCount; - DBG("BEFORE: top=%d bot=%d size=%d ", top, bot, size); + MDSDBG("BEFORE: top=%d bot=%d size=%d ", top, bot, size); if (top + size > bot) bot = top + size; - DBG(" AFTER: bot=%d\n", bot); + MDSDBG(" AFTER: bot=%d\n", bot); XtVaSetValues(w->list.vsb, XmNvalue, top, XmNsliderSize, size, XmNpageIncrement, w->list.visibleCount, XmNmaximum, bot, @@ -768,7 +756,7 @@ static void SetScrollbars(ListTreeWidget w) } } - DBG("item=%d visible=%d\n", w->list.itemCount, w->list.visibleCount); + MDSDBG("item=%d visible=%d\n", w->list.itemCount, w->list.visibleCount); } static void VSBCallback(Widget scrollbar, XtPointer client_data, @@ -779,15 +767,15 @@ static void VSBCallback(Widget scrollbar, XtPointer client_data, w->list.topItemPos = cbs->value; - DBG("topItemPos=%d\n", w->list.topItemPos); + MDSDBG("topItemPos=%d\n", w->list.topItemPos); #if 0 - DBG( "VSBCallback: cbs->reason=%d ", cbs->reason); + MDSDBG( "VSBCallback: cbs->reason=%d ", cbs->reason); if (cbs->reason == XmCR_INCREMENT) { - DBG( "increment\n"); + MDSDBG( "increment\n"); } else if (cbs->reason == XmCR_DECREMENT) { - DBG( "decrement\n"); + MDSDBG( "decrement\n"); } else if (cbs->reason == XmCR_VALUE_CHANGED) { - DBG( "value_changed\n"); + MDSDBG( "value_changed\n"); SetScrollbars(w); } #else @@ -809,8 +797,8 @@ static void HSBCallback(Widget scrollbar, XtPointer client_data, w->list.hsbPos = cbs->value; HSB2X(w); - DBG("XOffset=%d prefWidth=%d viewWidth=%d\n", w->list.XOffset, - w->list.preferredWidth, w->list.viewWidth); + MDSDBG("XOffset=%d prefWidth=%d viewWidth=%d\n", w->list.XOffset, + w->list.preferredWidth, w->list.viewWidth); if (w->list.XOffset != w->list.lastXOffset) { DrawAll(w); @@ -836,7 +824,7 @@ static XtGeometryResult QueryGeometry(ListTreeWidget w, answer->height = w->list.preferredHeight + 2 * Prim_ShadowThickness(w) + 2 * Prim_HighlightThickness(w); - DBG("w=%d h=%d\n", answer->width, answer->height); + MDSDBG("w=%d h=%d\n", answer->width, answer->height); if (proposed->width >= answer->width && proposed->height >= answer->height) return XtGeometryYes; @@ -1235,7 +1223,7 @@ static void extend_select(Widget aw, XEvent *event, String *params, { if (item) { - DBG("Highlighting y=%d item=%s\n", y, item->text); + MDSDBG("Highlighting y=%d item=%s\n", y, item->text); HighlightItem(w, item, True, True); y += item->height + w->list.VSpacing; } @@ -1248,7 +1236,7 @@ static void extend_select(Widget aw, XEvent *event, String *params, { if (item) { - DBG("Highlighting y=%d item=%s\n", y, item->text); + MDSDBG("Highlighting y=%d item=%s\n", y, item->text); HighlightItem(w, item, True, True); y -= item->height + w->list.VSpacing; } @@ -1302,7 +1290,7 @@ static void focus_in(Widget aw, XEvent *event, String *params, { ListTreeWidget w = (ListTreeWidget)aw; - DBGW("focus_in"); + MDSDBG("focus_in"); if (!w->list.HasFocus) { @@ -1318,7 +1306,7 @@ static void focus_out(Widget aw, XEvent *event, String *params, { ListTreeWidget w = (ListTreeWidget)aw; - DBGW("focus_out"); + MDSDBG("focus_out"); if (w->list.HasFocus) { @@ -1360,7 +1348,7 @@ XEvent *event; String *params; Cardinal *num_params; { - DBG("keypress\n"); + MDSDBG("keypress\n"); } /* ListTree private drawing functions ------------------------------------- */ @@ -1602,14 +1590,14 @@ static void DrawVertical(ListTreeWidget w, ListTreeItem *item) else yroot = item->parent->y + item->parent->height; - DBG("parent=%s drawing x=%d y=%d\n", item->parent->text, xroot, yroot); + MDSDBG("parent=%s drawing x=%d y=%d\n", item->parent->text, xroot, yroot); XDrawLine(XtDisplay(w), XtWindow(w), w->list.drawGC, xroot + w->list.XOffset, yroot, xroot + w->list.XOffset, w->list.exposeBot); } else { - DBG("parent=%s NOT DRAWING\n", item->parent->text); + MDSDBG("parent=%s NOT DRAWING\n", item->parent->text); } item = item->parent; @@ -1645,7 +1633,7 @@ static void Draw(ListTreeWidget w, int yevent, int hevent) DrawChildren(w, item, &lastdrawn, y, xbranch, ybranch); - DBG("lastdrawn=%s\n", lastdrawn->text); + MDSDBG("lastdrawn=%s\n", lastdrawn->text); w->list.bottomItemPos = lastdrawn->count; DrawVertical(w, lastdrawn); @@ -1915,7 +1903,7 @@ static int SearchChildren(ListTreeWidget w, ListTreeItem *item, { while (item) { - DBG("searching y=%d item=%s\n", y, item->text); + MDSDBG("searching y=%d item=%s\n", y, item->text); if (findy >= y && findy <= y + item->height + w->list.VSpacing) { *finditem = item; @@ -1989,7 +1977,7 @@ Boolean *found; while (item) { - /* DBG("Checking y=%d item=%s\n",y,item->text); */ + /* MDSDBG("Checking y=%d item=%s\n",y,item->text); */ if (item == finditem) { *found = True; diff --git a/xmdsshr/XmdsDigChans.c b/xmdsshr/XmdsDigChans.c index 49dd27775c..781def4694 100644 --- a/xmdsshr/XmdsDigChans.c +++ b/xmdsshr/XmdsDigChans.c @@ -74,6 +74,7 @@ XmdsDigChansApply(Widget w) Boolean XmdsIsDigChans(Widget w) External functions or symbols referenced: */ #include +#include #include #include #include @@ -159,7 +160,7 @@ EXPORT Widget XmdsCreateDigChans(Widget parent, String name, ArgList args, MrmFetchWidgetOverride(drm_hierarchy, "channels_1", parent, name, args, argcount, &channels_w, &class); XtVaSetValues(XtNameToWidget(channels_w, "this_is_a_DigChans_widget"), - XmNuserData, (char *)0 + info.put_on_apply, NULL); + XmNuserData, (void *)(intptr_t)info.put_on_apply, NULL); rowcol_w = XtNameToWidget(channels_w, "*c_rowcol"); for (i = 0; i < info.channels; i++) { @@ -189,10 +190,10 @@ EXPORT Widget XmdsCreateDigChans(Widget parent, String name, ArgList args, {"c_startidx_nid", NULL}, {"c_endidx_nid", NULL}, {"c_path", NULL}}; - uilnames[0].value = data_nid + (char *)0; + uilnames[0].value = (char *)(intptr_t)data_nid; uilnames[1].value = name; - uilnames[2].value = startidx_nid + (char *)0; - uilnames[3].value = endidx_nid + (char *)0; + uilnames[2].value = (char *)(intptr_t)startidx_nid; + uilnames[3].value = (char *)(intptr_t)endidx_nid; uilnames[4].value = path; MrmRegisterNamesInHierarchy(drm_hierarchy, uilnames, XtNumber(uilnames)); if (info.nodes_per_channel > 1) @@ -221,7 +222,7 @@ EXPORT void XmdsDigChansReset(Widget w) XtPointer userdata; int nid; XtVaGetValues(chan_w[i], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; XmToggleButtonGadgetSetState(XtNameToWidget(chan_w[i], "*on_off_button"), XmdsIsOn((int)nid), FALSE); } @@ -246,7 +247,7 @@ EXPORT int XmdsDigChansPut(Widget w) Widget *children; XtVaGetValues(chan_w[i], XmNnumChildren, &num_ctls, XmNchildren, &children, XmNuserData, &user_data, NULL); - nid = (char *)user_data - (char *)0; + nid = (int)(intptr_t)user_data; if (XmToggleButtonGadgetGetState(children[1])) TreeTurnOn(nid); else diff --git a/xmdsshr/XmdsDisplay.c b/xmdsshr/XmdsDisplay.c index bd05874f68..e5ab33da84 100644 --- a/xmdsshr/XmdsDisplay.c +++ b/xmdsshr/XmdsDisplay.c @@ -136,10 +136,10 @@ EXPORT Widget XmdsCreateDisplay(Widget parent, String name, ArgList args, int status; nid_dsc.pointer = (char *)&nid; status = TdiEvaluate(&nid_dsc, &xd MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { status = TdiDecompile(&xd, &display_dsc MDS_END_ARG); - if (status & 1) + if (STATUS_OK) { static DESCRIPTOR(zero_dsc, "\0"); StrConcat((struct descriptor *)&display_dsc, diff --git a/xmdsshr/XmdsExpr.c b/xmdsshr/XmdsExpr.c index 1dd789b189..bdee17094e 100644 --- a/xmdsshr/XmdsExpr.c +++ b/xmdsshr/XmdsExpr.c @@ -373,7 +373,7 @@ EXPORT struct descriptor *XmdsExprGetXd(Widget w) TreeSetDefaultNid(def_nid); } status = (*ew->expr.compile)(&text_dsc, ans MDS_END_ARG); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) { TdiComplain(w); XtFree((char *)ans); @@ -413,7 +413,7 @@ EXPORT Boolean XmdsExprPut(Widget w) XtFree((char *)new_xd); } } - return status & 1; + return STATUS_OK; } EXPORT Boolean XmdsExprFieldApply(Widget w) { return XmdsExprApply(w); } @@ -485,7 +485,7 @@ EXPORT void XmdsExprSetNid(Widget w, int nid, int offset) new_nid = ew->expr.nid + offset; status = TreeGetRecord(new_nid, ew->expr.xd); - if (status & 1) + if (STATUS_OK) LoadExpr(ew, (struct descriptor *)ew->expr.xd); else LoadExpr(ew, 0); @@ -755,7 +755,7 @@ static void LoadExpr(XmdsExprWidget w, struct descriptor *dsc) } status = (*w->expr.decompile)(xd, &text MDS_END_ARG); w->expr.is_text = 0; - if (status & 1) + if (STATUS_OK) { char *c_text = DescToNull((struct descriptor_s *)&text); SetString(w->expr.text_widget, c_text); diff --git a/xmdsshr/XmdsGetPutNid.c b/xmdsshr/XmdsGetPutNid.c index 923d98fb63..6476220122 100644 --- a/xmdsshr/XmdsGetPutNid.c +++ b/xmdsshr/XmdsGetPutNid.c @@ -412,5 +412,5 @@ Boolean XmdsApplyAllXds(Widget w) for (i = 0; i < num && status; i++) status = XmdsApplyAllXds(popups[i]); } - return status & 1; + return STATUS_OK; } diff --git a/xmdsshr/XmdsInput.c b/xmdsshr/XmdsInput.c index 7e3c9d2f78..42ae63b921 100644 --- a/xmdsshr/XmdsInput.c +++ b/xmdsshr/XmdsInput.c @@ -190,15 +190,15 @@ EXPORT void XmdsInputReset(Widget w) XtVaGetValues(w, XtNchildren, &children, NULL); XmdsResetAllXds(w); XtVaGetValues(children[ON_OFF], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; XmToggleButtonSetState(children[ON_OFF], (TreeIsOn((int)nid) & 1), (Boolean)0); XtVaGetValues(children[IDX_TIME], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; XmToggleButtonSetState(children[IDX_TIME], XmdsGetNidBooleanValue(nid, 1) & 1, (Boolean)0); XtVaGetValues(children[PATH], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; label = XmStringCreateSimple(path = TreeGetMinimumPath(0, nid)); TreeFree(path); XtVaSetValues(children[PATH], XmNlabelString, label, NULL); @@ -212,10 +212,10 @@ EXPORT void XmdsInputPut(Widget w) int nid; XtVaGetValues(w, XtNchildren, &children, NULL); XtVaGetValues(children[ON_OFF], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; XmdsSetState(nid, children[ON_OFF]); XtVaGetValues(children[IDX_TIME], XmNuserData, &userdata, NULL); - nid = (char *)userdata - (char *)0; + nid = (int)(intptr_t)userdata; XmdsPutNidToggleButton(children[IDX_TIME], nid, 1 & XmdsGetNidBooleanValue(nid, 1)); XmdsExprPut(children[START_IDX]); diff --git a/xmdsshr/XmdsNidOptionMenu.c b/xmdsshr/XmdsNidOptionMenu.c index 53dd5975e6..01b81ded82 100644 --- a/xmdsshr/XmdsNidOptionMenu.c +++ b/xmdsshr/XmdsNidOptionMenu.c @@ -176,7 +176,7 @@ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") b = XmCreatePushButtonGadget(info->pulldown, "", arglist, XtNumber(arglist)); XtAddCallback(b, XmNactivateCallback, (XtCallbackProc)ButtonPushed, - (XtPointer)(idx + (char *)0)); + (XtPointer)(void *)(intptr_t)(idx)); } } } @@ -413,7 +413,7 @@ static void MenuChanged(Widget w, Resources *info, if (cb->reason == XmCR_ACTIVATE) { int num; - int bnum = (char *)cb->data - (char *)0; + int bnum = (int)(intptr_t)cb->data; Widget *buttons; struct descriptor_xd *xd = 0; XtVaGetValues(info->pulldown, XtNnumChildren, &num, XtNchildren, &buttons, diff --git a/xmdsshr/XmdsPath.c b/xmdsshr/XmdsPath.c index 17cd75f280..8aa3464d27 100644 --- a/xmdsshr/XmdsPath.c +++ b/xmdsshr/XmdsPath.c @@ -140,7 +140,7 @@ EXPORT Widget XmdsCreatePath(Widget parent, String name, ArgList args, nci[0].code = (info.path_type == NciABSOLUTE_PATH) ? NciFULLPATH : NciMINPATH; status = TreeGetNci(nid, nci); - if (status & 1) + if (STATUS_OK) { lab_args[0].value = (long)XmStringCreateSimple(nci[0].pointer); TreeFree(nci[0].pointer); diff --git a/xmdsshr/XmdsSetSubvalues.c b/xmdsshr/XmdsSetSubvalues.c index f732446b5a..d1cb19747b 100644 --- a/xmdsshr/XmdsSetSubvalues.c +++ b/xmdsshr/XmdsSetSubvalues.c @@ -62,6 +62,7 @@ num_resources, Arglist args, Cardinal argcount ) ------------------------------------------------------------------------------*/ #include +#include int XmdsSetSubvalues(XtPointer record, XtResourceList resources, Cardinal num_resources, ArgList args, Cardinal argcount) @@ -71,14 +72,14 @@ int XmdsSetSubvalues(XtPointer record, XtResourceList resources, { if (*((int *)&resources[i].resource_offset) >= 0) { - resources[i].resource_name = - XrmStringToQuark(resources[i].resource_name) + (char *)0; - resources[i].resource_class = - XrmStringToQuark(resources[i].resource_class) + (char *)0; - resources[i].resource_type = - XrmStringToQuark(resources[i].resource_type) + (char *)0; - resources[i].default_type = - XrmStringToQuark(resources[i].default_type) + (char *)0; + resources[i].resource_name = (char *)(intptr_t) + XrmStringToQuark(resources[i].resource_name); + resources[i].resource_class = (char *)(intptr_t) + XrmStringToQuark(resources[i].resource_class); + resources[i].resource_type = (char *)(intptr_t) + XrmStringToQuark(resources[i].resource_type); + resources[i].default_type = (char *)(intptr_t) + XrmStringToQuark(resources[i].default_type); resources[i].resource_offset = -(resources[i].resource_offset + 1); } } diff --git a/xmdsshr/XmdsSupport.c b/xmdsshr/XmdsSupport.c index f0b788c1c8..7003a74f1f 100644 --- a/xmdsshr/XmdsSupport.c +++ b/xmdsshr/XmdsSupport.c @@ -109,7 +109,7 @@ Boolean ConglomerateElt(int nid) {sizeof(cong_elt), NciCONGLOMERATE_ELT, (unsigned char *)&cong_elt, 0}, {0, 0, 0, 0}}; int status = TreeGetNci(nid, lst); - if (status & 1) + if (STATUS_OK) return (cong_elt != 0); else return 0; @@ -122,7 +122,7 @@ int ConglomerateHead(int nid) {sizeof(head_nid), NciCONGLOMERATE_NIDS, (unsigned char *)&head_nid, 0}, {0, 0, 0, 0}}; int status = TreeGetNci(nid, lst); - if (status & 1) + if (STATUS_OK) return head_nid; else return 0; @@ -145,7 +145,7 @@ int NodeParent(int nid) {sizeof(parent_nid), NciPARENT, (unsigned char *)&parent_nid, 0}, {0, 0, 0, 0}}; int status = TreeGetNci(nid, lst); - if (status & 1) + if (STATUS_OK) return parent_nid; else return 0; @@ -183,7 +183,7 @@ struct descriptor *TdiGet(int nid) int status; *answer = empty_xd; status = TreeGetRecord(nid, answer); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) { XtFree((char *)answer); answer = 0; @@ -209,5 +209,5 @@ Boolean PutIfChanged(int nid, struct descriptor_xd *xd) } } } - return status & 1; + return STATUS_OK; } diff --git a/xmdsshr/XmdsWaveform.c b/xmdsshr/XmdsWaveform.c index c23fae3b4e..0556d555b7 100644 --- a/xmdsshr/XmdsWaveform.c +++ b/xmdsshr/XmdsWaveform.c @@ -55,6 +55,7 @@ Widget XmdsCreateWaveform( parent, name, args, argcount ) /*------------------------------------------------------------------------------ Macros: */ +#include #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -3292,7 +3293,7 @@ static Boolean UpdateLimit(float *old, float *req, float **new) { if (old == req) return FALSE; - else if ((((char *)req - (char *)0) & 0xffffffff) == 0xffffffff) + else if ((((intptr_t)req) & 0xffffffff) == 0xffffffff) { *new = old; return FALSE; diff --git a/xmdsshr/XmdsXdBox.c b/xmdsshr/XmdsXdBox.c index 8e3983678d..62eeb579c7 100644 --- a/xmdsshr/XmdsXdBox.c +++ b/xmdsshr/XmdsXdBox.c @@ -626,7 +626,7 @@ static void Initialize(Widget req, Widget new, ArgList args, int status; itms[0].pointer = (unsigned char *)&w->xdbox.usage; status = TreeGetNci(nid, itms); - if ((status & 1) == 0) + if ((STATUS_OK) == 0) w->xdbox.usage = 0; } else @@ -1219,7 +1219,7 @@ static struct descriptor_xd *ExpressionUnload(Widget w) ans = (struct descriptor_xd *)XtMalloc(sizeof(struct descriptor_xd)); *ans = empty_xd; status = TdiCompile(&w_units, data, units, ans MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) { TdiComplain(w); ans = 0; @@ -2223,7 +2223,7 @@ static void UpdateTags(Widget w, int nid, char *tags) while (t_ptr) { status = TreeAddTag(nid, t_ptr); - if (!status & 1) + if (STATUS_NOT_OK) XmdsComplain(w, "Error adding tag %s to node number %d", t_ptr, nid); t_ptr = strtok(NULL, ", "); } diff --git a/xtreeshr/XTreeDefaultResample.c b/xtreeshr/XTreeDefaultResample.c index 1425778ecc..12d1f4979a 100644 --- a/xtreeshr/XTreeDefaultResample.c +++ b/xtreeshr/XTreeDefaultResample.c @@ -241,11 +241,11 @@ static int XTreeDefaultResampleMode(mds_signal_t *inSignalD, mdsdsc_t *startD, MdsCopyDxXd((mdsdsc_t *)inSignalD, outSignalXd); return 3; // Cannot convert timebase to 64 bit int } - if(numData == 0) //If empty segment + if (numData == 0) //If empty segment { - MdsFree1Dx(&dataXd, 0); - MdsCopyDxXd((mdsdsc_t *)inSignalD, outSignalXd); - return 1; + MdsFree1Dx(&dataXd, 0); + MdsCopyDxXd((mdsdsc_t *)inSignalD, outSignalXd); + return 1; } // Check data array too short diff --git a/xtreeshr/XTreeGetSegmentList.c b/xtreeshr/XTreeGetSegmentList.c index b5c5c272ce..a3a5619af1 100644 --- a/xtreeshr/XTreeGetSegmentList.c +++ b/xtreeshr/XTreeGetSegmentList.c @@ -59,7 +59,7 @@ static void printDecompiled(struct descriptor *inD) char *buf; status = TdiDecompile(inD, &out_xd MDS_END_ARG); - if (!(status & 1)) { + if (STATUS_NOT_OK) { printf("%s\n", MdsGetMsg(status)); return; } @@ -81,7 +81,7 @@ static int check(char *compExpr, struct descriptor *time1Dsc, int status; EMPTYXD(ansXd); status = TdiExecute(&compExprDsc, time1Dsc, time2Dsc, &ansXd MDS_END_ARG); - if (!(status & 1)) + if (STATUS_NOT_OK) return status; *answ = *ansXd.pointer->pointer; MdsFree1Dx(&ansXd, 0); From 1403262ebc29fdcd2ec3d0a4f3c119190c37dce0 Mon Sep 17 00:00:00 2001 From: Fernando Santoro <44955673+santorofer@users.noreply.github.com> Date: Mon, 24 May 2021 07:26:19 -0500 Subject: [PATCH 27/27] Fix: Add extra selection for different trigger sources (#2314) * Rework acq423 trigger sources * Fix missing self from min freq variable * Fix calls to HAPI library: for 423 Acq400, for 435 Acq2106 * Revert to calling HAPI Acq400() for 435st, without wrong has_wr parameter in it. --- pydevices/HtsDevices/acq2106_423st.py | 224 ++++++++++++++++++++------ pydevices/HtsDevices/acq2106_435st.py | 4 +- 2 files changed, 173 insertions(+), 55 deletions(-) diff --git a/pydevices/HtsDevices/acq2106_423st.py b/pydevices/HtsDevices/acq2106_423st.py index 2139263504..1359385ddd 100755 --- a/pydevices/HtsDevices/acq2106_423st.py +++ b/pydevices/HtsDevices/acq2106_423st.py @@ -57,39 +57,102 @@ class _ACQ2106_423ST(MDSplus.Device): """ carrier_parts = [ - {'path': ':NODE', 'type': 'text', - 'options': ('no_write_shot',)}, - {'path': ':COMMENT', 'type': 'text', - 'options': ('no_write_shot',)}, - {'path': ':TRIGGER', 'type': 'numeric', - 'value': 0.0, 'options': ('no_write_shot',)}, - {'path': ':TRIG_MODE', 'type': 'text', - 'value': 'master:hard', 'options': ('no_write_shot',)}, - {'path': ':EXT_CLOCK', 'type': 'axis', - 'options': ('no_write_shot',)}, - {'path': ':FREQ', 'type': 'numeric', - 'value': 16000, 'options': ('no_write_shot',)}, - {'path': ':DEF_DECIMATE', 'type': 'numeric', - 'value': 1, 'options': ('no_write_shot',)}, - {'path': ':SEG_LENGTH', 'type': 'numeric', - 'value': 8000, 'options': ('no_write_shot',)}, - {'path': ':MAX_SEGMENTS', 'type': 'numeric', - 'value': 1000, 'options': ('no_write_shot',)}, - {'path': ':SEG_EVENT', 'type': 'text', - 'value': 'STREAM', 'options': ('no_write_shot',)}, - {'path': ':TRIG_TIME', 'type': 'numeric', - 'options': ('write_shot',)}, - {'path': ':TRIG_STR', 'type': 'text', - 'valueExpr': "EXT_FUNCTION(None,'ctime',head.TRIG_TIME)", 'options': ('nowrite_shot',)}, - {'path': ':RUNNING', 'type': 'numeric', - 'options': ('no_write_model',)}, - {'path': ':LOG_FILE', 'type': 'text', 'options': ('write_once',)}, - {'path': ':LOG_OUTPUT', 'type': 'text', 'options': ( - 'no_write_model', 'write_once', 'write_shot',)}, - {'path': ':INIT_ACTION', 'type': 'action', - 'valueExpr': "Action(Dispatch('CAMAC_SERVER','INIT',50,None),Method(None,'INIT',head,'auto'))", 'options': ('no_write_shot',)}, - {'path': ':STOP_ACTION', 'type': 'action', - 'valueExpr': "Action(Dispatch('CAMAC_SERVER','STORE',50,None),Method(None,'STOP',head))", 'options': ('no_write_shot',)}, + { + 'path': ':NODE', + 'type': 'text', + 'value': '192.168.0.254', + 'options': ('no_write_shot',) + }, + { + 'path': ':COMMENT', + 'type': 'text', + 'options': ('no_write_shot',) + }, + { + 'path': ':TRIGGER', + 'type': 'numeric', + 'value': 0.0, + 'options': ('no_write_shot',) + }, + { + 'path': ':TRIG_MODE', + 'type': 'text', + 'value': 'master:hard', + 'options': ('no_write_shot',) + }, + { + 'path': ':EXT_CLOCK', + 'type': 'axis', + 'options': ('no_write_shot',) + }, + { + 'path': ':FREQ', + 'type': 'numeric', + 'value': 16000, + 'options': ('no_write_shot',) + }, + { + 'path': ':DEF_DECIMATE', + 'type': 'numeric', + 'value': 1, + 'options': ('no_write_shot',) + }, + { + 'path': ':SEG_LENGTH', + 'type': 'numeric', + 'value': 8000, + 'options': ('no_write_shot',) + }, + { + 'path': ':MAX_SEGMENTS', + 'type': 'numeric', + 'value': 1000, + 'options': ('no_write_shot',) + }, + { + 'path': ':SEG_EVENT', + 'type': 'text', + 'value': 'STREAM', + 'options': ('no_write_shot',) + }, + { + 'path': ':TRIG_TIME', + 'type': 'numeric', + 'options': ('write_shot',) + }, + { + 'path': ':TRIG_STR', + 'type': 'text', + 'valueExpr': "EXT_FUNCTION(None,'ctime',head.TRIG_TIME)", + 'options': ('no_write_shot',) + }, + { + 'path': ':RUNNING', + 'type': 'numeric', + 'options': ('no_write_model',) + }, + { + 'path': ':LOG_FILE', + 'type': 'text', + 'options': ('write_once',) + }, + { + 'path': ':LOG_OUTPUT', + 'type': 'text', + 'options': ('no_write_model', 'write_once', 'write_shot',) + }, + { + 'path': ':INIT_ACTION', + 'type': 'action', + 'valueExpr': "Action(Dispatch('CAMAC_SERVER','INIT',50,None),Method(None,'INIT',head,'auto'))", + 'options': ('no_write_shot',) + }, + { + 'path': ':STOP_ACTION', + 'type': 'action', + 'valueExpr': "Action(Dispatch('CAMAC_SERVER','STORE',50,None),Method(None,'STOP',head))", + 'options': ('no_write_shot',) + }, ] data_socket = -1 @@ -254,12 +317,31 @@ def run(self): break else: self.full_buffers.put(buf) + # The minimum frequency we can operate at + MIN_FREQUENCY = 10000 + + # These are partial lists of the options we support. + # For a complete list, consult D-Tacq + + # Trigger Source Options for Signal Highway d0 + TRIG_SRC_OPTS_0 = [ + 'ext', # External Trigger + 'hdmi', # HDMI Trigger + 'gpg0', # Gateway Pulse Generator Trigger + 'wrtt0' # White Rabbit Trigger + ] - def init(self): - import acq400_hapi - MIN_FREQUENCY = 10000 + # Trigger Source Options for Signal Highway d1 + TRIG_SRC_OPTS_1 = [ + 'strig', # Software Trigger + 'hdmi_gpio', # HDMI General Purpose I/O Trigger + 'gpg1', # Gateway Pulse Generator Trigger + 'fp_sync', # Front Panel SYNC + 'wrtt1' # White Rabbit Trigger + ] - uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + def init(self): + uut = self.getUUT() uut.s0.set_knob('set_abort', '1') if self.ext_clock.length > 0: @@ -267,11 +349,11 @@ def init(self): freq = int(self.freq.data()) # D-Tacq Recommendation: the minimum sample rate is 10kHz. - if freq < MIN_FREQUENCY: + if freq < self.MIN_FREQUENCY: raise MDSplus.DevBAD_PARAMETER( " Sample rate should be greater or equal than 10kHz") - mode = self.trig_mode.data() + mode = str(self.trig_mode.data()).lower() if mode == 'hard': role = 'master' trg = 'hard' @@ -280,16 +362,28 @@ def init(self): trg = 'soft' else: role = mode.split(":")[0] - trg = mode.split(":")[1] + trg = mode.split(":")[1] - print("Role is {} and {} trigger".format(role, trg)) + if self.debug: + print("Role is %s and %s trigger" % (role, trg)) + + src_trg_0 = None + src_trg_1 = None if trg == 'hard': trg_dx = 'd0' - elif trg == 'automatic': + src_trg_0 = 'EXT' # External Trigger + elif trg == 'soft' or trg == 'automatic': trg_dx = 'd1' - elif trg == 'soft': + src_trg_1 = 'STRIG' # Soft Trigger + elif trg in self.TRIG_SRC_OPTS_0: + trg_dx = 'd0' + src_trg_0 = trg + elif trg in self.TRIG_SRC_OPTS_1: trg_dx = 'd1' + src_trg_1 = trg + elif trg != 'none': + raise MDSplus.DevBAD_PARAMETER("TRIG_MODE does not contain a valid trigger source") # USAGE sync_role {fpmaster|rpmaster|master|slave|solo} [CLKHZ] [FIN] # modifiers [CLK|TRG:SENSE=falling|rising] [CLK|TRG:DX=d0|d1] @@ -297,6 +391,14 @@ def init(self): # modifiers [CLKDIV=div] uut.s0.sync_role = '%s %s TRG:DX=%s' % (role, self.freq.data(), trg_dx) + # snyc_role will set a default trigger source, we need to override it to the selected trigger source + # These must be uppercase + if src_trg_0: + uut.s0.SIG_SRC_TRG_0 = src_trg_0.upper() + + if src_trg_1: + uut.s0.SIG_SRC_TRG_1 = src_trg_1.upper() + # Fetching all calibration information from every channel. uut.fetch_all_calibration() coeffs = uut.cal_eslo[1:] @@ -322,11 +424,15 @@ def stop(self): STOP = stop def trig(self): - import acq400_hapi - uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + uut = self.getUUT() uut.s0.set_knob('soft_trigger', '1') TRIG = trig + def getUUT(self): + import acq400_hapi + uut = acq400_hapi.Acq400(self.node.data(), monitor=False) + return uut + def setChanScale(self, num): chan = self.__getattr__('INPUT_%3.3d' % num) chan.setSegmentScale(MDSplus.ADD(MDSplus.MULTIPLY( @@ -337,14 +443,26 @@ def assemble(cls): cls.parts = list(_ACQ2106_423ST.carrier_parts) for i in range(cls.sites*32): cls.parts += [ - {'path': ':INPUT_%3.3d' % (i+1,), 'type': 'SIGNAL', 'valueExpr': 'head.setChanScale(%d)' % ( - i+1,), 'options': ('no_write_model', 'write_once',)}, - {'path': ':INPUT_%3.3d:DECIMATE' % ( - i+1,), 'type': 'NUMERIC', 'valueExpr': 'head.def_decimate', 'options': ('no_write_shot',)}, - {'path': ':INPUT_%3.3d:COEFFICIENT' % (i+1,), 'type': 'NUMERIC', - 'options': ('no_write_model', 'write_once',)}, - {'path': ':INPUT_%3.3d:OFFSET' % (i+1,), 'type': 'NUMERIC', - 'options': ('no_write_model', 'write_once',)}, + { + 'path': ':INPUT_%3.3d' % (i+1,), + 'type': 'SIGNAL', 'valueExpr': 'head.setChanScale(%d)' % (i+1,), + 'options': ('no_write_model', 'write_once',) + }, + { + 'path': ':INPUT_%3.3d:DECIMATE' % (i+1,), + 'type': 'NUMERIC', 'valueExpr': 'head.def_decimate', + 'options': ('no_write_shot',) + }, + { + 'path': ':INPUT_%3.3d:COEFFICIENT' % (i+1,), + 'type': 'NUMERIC', + 'options': ('no_write_model', 'write_once',) + }, + { + 'path': ':INPUT_%3.3d:OFFSET' % (i+1,), + 'type': 'NUMERIC', + 'options': ('no_write_model', 'write_once',) + }, ] diff --git a/pydevices/HtsDevices/acq2106_435st.py b/pydevices/HtsDevices/acq2106_435st.py index 3ab868bde7..9e089d6d43 100755 --- a/pydevices/HtsDevices/acq2106_435st.py +++ b/pydevices/HtsDevices/acq2106_435st.py @@ -146,7 +146,7 @@ class _ACQ2106_435ST(MDSplus.Device): { 'path': ':TRIG_STR', 'type': 'text', - 'options': ('nowrite_shot',), + 'options': ('no_write_shot',), 'valueExpr': "EXT_FUNCTION(None,'ctime',head.TRIG_TIME)" }, { @@ -536,7 +536,7 @@ def trig(self): def getUUT(self): import acq400_hapi - uut = acq400_hapi.Acq400(self.node.data(), monitor=False, has_wr=True) + uut = acq400_hapi.Acq400(self.node.data(), monitor=False) return uut def setChanScale(self, num):